]> arthur.barton.de Git - netatalk.git/commitdiff
Merge 2-2
authorFrank Lahm <franklahm@googlemail.com>
Sat, 23 Jun 2012 11:57:28 +0000 (13:57 +0200)
committerFrank Lahm <franklahm@googlemail.com>
Sat, 23 Jun 2012 11:57:28 +0000 (13:57 +0200)
762 files changed:
.gitignore
Makefile.am
NEWS
VERSION
abigen.sh [new file with mode: 0755]
bin/Makefile.am
bin/ad/Makefile.am
bin/ad/ad.c
bin/ad/ad.h
bin/ad/ad_cp.c
bin/ad/ad_find.c
bin/ad/ad_ls.c
bin/ad/ad_mv.c
bin/ad/ad_rm.c
bin/ad/ad_set.c [new file with mode: 0644]
bin/ad/ad_util.c
bin/adv1tov2/.gitignore [deleted file]
bin/adv1tov2/Makefile.am [deleted file]
bin/adv1tov2/adv1tov2.c [deleted file]
bin/aecho/.gitignore [deleted file]
bin/aecho/Makefile.am [deleted file]
bin/aecho/aecho.c [deleted file]
bin/afppasswd/afppasswd.c
bin/getzones/.gitignore [deleted file]
bin/getzones/Makefile.am [deleted file]
bin/getzones/getzones.c [deleted file]
bin/megatron/Makefile.am
bin/megatron/asingle.c
bin/megatron/hqx.c
bin/megatron/macbin.c
bin/megatron/megatron.c
bin/megatron/nad.c
bin/misc/Makefile.am
bin/misc/fce.c
bin/misc/logger_test.c
bin/misc/uuidtest.c
bin/nbp/.gitignore [deleted file]
bin/nbp/Makefile.am [deleted file]
bin/nbp/nbplkup.c [deleted file]
bin/nbp/nbprgstr.c [deleted file]
bin/nbp/nbpunrgstr.c [deleted file]
bin/pap/.gitignore [deleted file]
bin/pap/Makefile.am [deleted file]
bin/pap/pap.c [deleted file]
bin/pap/papstatus.c [deleted file]
bin/psorder/.gitignore [deleted file]
bin/psorder/Makefile.am [deleted file]
bin/psorder/pa.c [deleted file]
bin/psorder/pa.h [deleted file]
bin/psorder/psorder.c [deleted file]
bin/psorder/psorder.h [deleted file]
bin/uniconv/iso8859_1_adapted.c
bin/uniconv/uniconv.c
bootstrap
config/.gitignore
config/AppleVolumes.default.tmpl [deleted file]
config/AppleVolumes.system [deleted file]
config/Makefile.am
config/README [new file with mode: 0644]
config/afp.conf.tmpl [new file with mode: 0644]
config/afp_ldap.conf [deleted file]
config/afpd.conf.tmpl [deleted file]
config/atalkd.conf [deleted file]
config/netatalk.conf [deleted file]
config/papd.conf [deleted file]
configure.ac
contrib/Makefile.am
contrib/a2boot/.gitignore [deleted file]
contrib/a2boot/COPYRIGHT [deleted file]
contrib/a2boot/Makefile.am [deleted file]
contrib/a2boot/VERSION [deleted file]
contrib/a2boot/a2boot.c [deleted file]
contrib/misc/libevent.patch [new file with mode: 0644]
contrib/printing/.gitignore [deleted file]
contrib/printing/Makefile.am [deleted file]
contrib/printing/add_netatalk_printer [deleted file]
contrib/printing/netatalk.template [deleted file]
contrib/shell_utils/.gitignore
contrib/shell_utils/Makefile.am
contrib/shell_utils/apple_dump.in
contrib/shell_utils/asip-status.pl.in
contrib/shell_utils/lp2pap.sh.tmpl [deleted file]
contrib/timelord/.gitignore [deleted file]
contrib/timelord/COPYRIGHT [deleted file]
contrib/timelord/Makefile.am [deleted file]
contrib/timelord/README [deleted file]
contrib/timelord/VERSION [deleted file]
contrib/timelord/timelord.c [deleted file]
distrib/Makefile.am
distrib/initscripts/.gitignore
distrib/initscripts/Makefile.am
distrib/initscripts/netatalk.xml.tmpl [new file with mode: 0644]
distrib/initscripts/rc.afpd.netbsd.tmpl [deleted file]
distrib/initscripts/rc.atalk.bsd.tmpl [deleted file]
distrib/initscripts/rc.atalk.debian.tmpl [deleted file]
distrib/initscripts/rc.atalk.gentoo.tmpl [deleted file]
distrib/initscripts/rc.atalk.redhat-sysv.tmpl [deleted file]
distrib/initscripts/rc.atalk.suse-sysv.tmpl [deleted file]
distrib/initscripts/rc.atalk.systemd.tmpl [deleted file]
distrib/initscripts/rc.atalk.sysv.tmpl [deleted file]
distrib/initscripts/rc.atalk.tru64.tmpl [deleted file]
distrib/initscripts/rc.atalkd.netbsd.tmpl [deleted file]
distrib/initscripts/rc.bsd.tmpl [new file with mode: 0644]
distrib/initscripts/rc.cnid_metad.netbsd.tmpl [deleted file]
distrib/initscripts/rc.debian.tmpl [new file with mode: 0644]
distrib/initscripts/rc.gentoo.tmpl [new file with mode: 0644]
distrib/initscripts/rc.netbsd.tmpl [new file with mode: 0644]
distrib/initscripts/rc.papd.netbsd.tmpl [deleted file]
distrib/initscripts/rc.redhat.tmpl [new file with mode: 0644]
distrib/initscripts/rc.solaris.tmpl [new file with mode: 0644]
distrib/initscripts/rc.suse.tmpl [new file with mode: 0644]
distrib/initscripts/rc.timelord.netbsd.tmpl [deleted file]
distrib/initscripts/service.atalk.systemd.tmpl [deleted file]
distrib/initscripts/service.systemd.tmpl [new file with mode: 0644]
distrib/systemd/Makefile.am [deleted file]
distrib/systemd/README [deleted file]
distrib/systemd/netatalk-cnid.service [deleted file]
distrib/systemd/netatalk.service [deleted file]
doc/DEVELOPER
doc/Makefile.am
doc/README.AppleTalk [deleted file]
etc/.gitignore
etc/Makefile.am
etc/afpd/Makefile.am
etc/afpd/acl_mappings.h
etc/afpd/acls.c
etc/afpd/acls.h
etc/afpd/afp_asp.c [deleted file]
etc/afpd/afp_avahi.c
etc/afpd/afp_avahi.h
etc/afpd/afp_config.c
etc/afpd/afp_config.h
etc/afpd/afp_dsi.c
etc/afpd/afp_mdns.c
etc/afpd/afp_mdns.h
etc/afpd/afp_options.c
etc/afpd/afp_zeroconf.c
etc/afpd/afp_zeroconf.h
etc/afpd/afprun.c
etc/afpd/afs.c
etc/afpd/appl.c
etc/afpd/auth.c
etc/afpd/auth.h
etc/afpd/catsearch.c
etc/afpd/desktop.c
etc/afpd/desktop.h
etc/afpd/dircache.c
etc/afpd/dircache.h
etc/afpd/directory.c
etc/afpd/directory.h
etc/afpd/enumerate.c
etc/afpd/extattrs.c
etc/afpd/fce_api.c
etc/afpd/fce_util.c
etc/afpd/file.c
etc/afpd/file.h
etc/afpd/filedir.c
etc/afpd/filedir.h
etc/afpd/fork.c
etc/afpd/fork.h
etc/afpd/gettok.c
etc/afpd/icon.h
etc/afpd/main.c
etc/afpd/mangle.c
etc/afpd/messages.c
etc/afpd/misc.h
etc/afpd/nfsquota.c
etc/afpd/ofork.c
etc/afpd/quota.c
etc/afpd/status.c
etc/afpd/status.h
etc/afpd/uam.c
etc/afpd/uam_auth.h
etc/afpd/uid.c
etc/afpd/uid.h
etc/afpd/unix.c
etc/afpd/unix.h
etc/afpd/volume.c
etc/afpd/volume.h
etc/atalkd/.gitignore [deleted file]
etc/atalkd/Makefile.am [deleted file]
etc/atalkd/aep.c [deleted file]
etc/atalkd/atserv.h [deleted file]
etc/atalkd/config.c [deleted file]
etc/atalkd/gate.h [deleted file]
etc/atalkd/interface.h [deleted file]
etc/atalkd/list.h [deleted file]
etc/atalkd/main.c [deleted file]
etc/atalkd/main.h [deleted file]
etc/atalkd/multicast.c [deleted file]
etc/atalkd/multicast.h [deleted file]
etc/atalkd/nbp.c [deleted file]
etc/atalkd/nbp.h [deleted file]
etc/atalkd/route.c [deleted file]
etc/atalkd/route.h [deleted file]
etc/atalkd/rtmp.c [deleted file]
etc/atalkd/rtmp.h [deleted file]
etc/atalkd/zip.c [deleted file]
etc/atalkd/zip.h [deleted file]
etc/cnid_dbd/Makefile.am
etc/cnid_dbd/README [deleted file]
etc/cnid_dbd/cmd_dbd.c
etc/cnid_dbd/cmd_dbd.h
etc/cnid_dbd/cmd_dbd_scanvol.c
etc/cnid_dbd/cnid_metad.c
etc/cnid_dbd/comm.c
etc/cnid_dbd/db_param.h
etc/cnid_dbd/dbd.h
etc/cnid_dbd/dbd_add.c
etc/cnid_dbd/dbd_dbcheck.c
etc/cnid_dbd/dbd_delete.c
etc/cnid_dbd/dbd_get.c
etc/cnid_dbd/dbd_getstamp.c
etc/cnid_dbd/dbd_lookup.c
etc/cnid_dbd/dbd_rebuild_add.c
etc/cnid_dbd/dbd_resolve.c
etc/cnid_dbd/dbd_search.c
etc/cnid_dbd/dbd_update.c
etc/cnid_dbd/dbif.c
etc/cnid_dbd/dbif.h
etc/cnid_dbd/main.c
etc/cnid_dbd/pack.c
etc/cnid_dbd/pack.h
etc/cnid_dbd/usockfd.c
etc/netatalk/.gitignore [new file with mode: 0644]
etc/netatalk/Makefile.am [new file with mode: 0644]
etc/netatalk/netatalk.c [new file with mode: 0644]
etc/papd/.gitignore [deleted file]
etc/papd/Makefile.am [deleted file]
etc/papd/auth.c [deleted file]
etc/papd/comment.c [deleted file]
etc/papd/comment.h [deleted file]
etc/papd/file.c [deleted file]
etc/papd/file.h [deleted file]
etc/papd/headers.c [deleted file]
etc/papd/lp.c [deleted file]
etc/papd/lp.h [deleted file]
etc/papd/magics.c [deleted file]
etc/papd/main.c [deleted file]
etc/papd/ppd.c [deleted file]
etc/papd/ppd.h [deleted file]
etc/papd/print_cups.c [deleted file]
etc/papd/print_cups.h [deleted file]
etc/papd/printcap.c [deleted file]
etc/papd/printcap.h [deleted file]
etc/papd/printer.h [deleted file]
etc/papd/queries.c [deleted file]
etc/papd/session.c [deleted file]
etc/papd/session.h [deleted file]
etc/papd/showppd.c [deleted file]
etc/papd/uam.c [deleted file]
etc/papd/uam_auth.h [deleted file]
etc/psf/.gitignore [deleted file]
etc/psf/Makefile.am [deleted file]
etc/psf/etc2ps.sh [deleted file]
etc/psf/pagecount.ps [deleted file]
etc/psf/psa.c [deleted file]
etc/psf/psf.c [deleted file]
etc/uams/Makefile.am
etc/uams/uams_dhx2_pam.c
etc/uams/uams_dhx2_passwd.c
etc/uams/uams_dhx_pam.c
etc/uams/uams_dhx_passwd.c
etc/uams/uams_gss.c
etc/uams/uams_guest.c
etc/uams/uams_krb4/.gitignore [deleted file]
etc/uams/uams_krb4/Makefile.am [deleted file]
etc/uams/uams_krb4/kuam.c [deleted file]
etc/uams/uams_krb4/lifetime.c [deleted file]
etc/uams/uams_krb4/send_to_kdc.c [deleted file]
etc/uams/uams_krb4/uams_krb4.c [deleted file]
etc/uams/uams_pam.c
etc/uams/uams_passwd.c
etc/uams/uams_pgp.c
etc/uams/uams_randnum.c
include/atalk/.gitignore
include/atalk/Makefile.am
include/atalk/adouble.h
include/atalk/aep.h [deleted file]
include/atalk/afp.h
include/atalk/asp.h [deleted file]
include/atalk/atp.h [deleted file]
include/atalk/cnid.h
include/atalk/cnid_dbd_private.h
include/atalk/compat.h
include/atalk/ddp.h [deleted file]
include/atalk/dictionary.h [new file with mode: 0644]
include/atalk/directory.h
include/atalk/dsi.h
include/atalk/ea.h
include/atalk/errchk.h
include/atalk/fce_api.h
include/atalk/globals.h
include/atalk/iniparser.h [new file with mode: 0644]
include/atalk/ldapconfig.h
include/atalk/logger.h
include/atalk/nbp.h [deleted file]
include/atalk/netatalk_conf.h [new file with mode: 0644]
include/atalk/netddp.h [deleted file]
include/atalk/pap.h [deleted file]
include/atalk/paths.h
include/atalk/rpc.h [new file with mode: 0644]
include/atalk/rtmp.h [deleted file]
include/atalk/server_child.h
include/atalk/tdb.h
include/atalk/uam.h
include/atalk/unicode.h
include/atalk/unix.h
include/atalk/util.h
include/atalk/uuid.h
include/atalk/volinfo.h [deleted file]
include/atalk/volume.h
include/atalk/zip.h [deleted file]
libatalk/.gitignore
libatalk/Makefile.am
libatalk/acl/Makefile.am
libatalk/acl/cache.c
libatalk/acl/cache.h
libatalk/acl/ldap.c
libatalk/acl/ldap_config.c
libatalk/acl/unix.c
libatalk/acl/uuid.c
libatalk/adouble/Makefile.am
libatalk/adouble/ad_attr.c
libatalk/adouble/ad_conv.c [new file with mode: 0644]
libatalk/adouble/ad_date.c
libatalk/adouble/ad_flush.c
libatalk/adouble/ad_lock.c
libatalk/adouble/ad_lock.h [new file with mode: 0644]
libatalk/adouble/ad_mmap.c
libatalk/adouble/ad_open.c
libatalk/adouble/ad_private.h [deleted file]
libatalk/adouble/ad_read.c
libatalk/adouble/ad_sendfile.c
libatalk/adouble/ad_size.c
libatalk/adouble/ad_write.c
libatalk/asp/.gitignore [deleted file]
libatalk/asp/Makefile.am [deleted file]
libatalk/asp/asp_attn.c [deleted file]
libatalk/asp/asp_child.h [deleted file]
libatalk/asp/asp_close.c [deleted file]
libatalk/asp/asp_cmdreply.c [deleted file]
libatalk/asp/asp_getreq.c [deleted file]
libatalk/asp/asp_getsess.c [deleted file]
libatalk/asp/asp_init.c [deleted file]
libatalk/asp/asp_shutdown.c [deleted file]
libatalk/asp/asp_tickle.c [deleted file]
libatalk/asp/asp_write.c [deleted file]
libatalk/atp/.gitignore [deleted file]
libatalk/atp/Makefile.am [deleted file]
libatalk/atp/atp_bufs.c [deleted file]
libatalk/atp/atp_close.c [deleted file]
libatalk/atp/atp_internals.h [deleted file]
libatalk/atp/atp_open.c [deleted file]
libatalk/atp/atp_packet.c [deleted file]
libatalk/atp/atp_rreq.c [deleted file]
libatalk/atp/atp_rresp.c [deleted file]
libatalk/atp/atp_rsel.c [deleted file]
libatalk/atp/atp_sreq.c [deleted file]
libatalk/atp/atp_sresp.c [deleted file]
libatalk/cnid/cdb/cnid_cdb.h
libatalk/cnid/cdb/cnid_cdb_add.c
libatalk/cnid/cdb/cnid_cdb_delete.c
libatalk/cnid/cdb/cnid_cdb_get.c
libatalk/cnid/cdb/cnid_cdb_lookup.c
libatalk/cnid/cdb/cnid_cdb_open.c
libatalk/cnid/cdb/cnid_cdb_private.h
libatalk/cnid/cdb/cnid_cdb_rebuild_add.c
libatalk/cnid/cdb/cnid_cdb_update.c
libatalk/cnid/cnid.c
libatalk/cnid/dbd/cnid_dbd.c
libatalk/cnid/dbd/cnid_dbd.h
libatalk/cnid/last/cnid_last.c
libatalk/cnid/last/cnid_last.h
libatalk/cnid/tdb/cnid_tdb.h
libatalk/cnid/tdb/cnid_tdb_add.c
libatalk/cnid/tdb/cnid_tdb_get.c
libatalk/cnid/tdb/cnid_tdb_lookup.c
libatalk/cnid/tdb/cnid_tdb_open.c
libatalk/cnid/tdb/cnid_tdb_update.c
libatalk/compat/Makefile.am
libatalk/compat/misc.c
libatalk/compat/rquota_xdr.c
libatalk/compat/snprintf.c [deleted file]
libatalk/compat/strcasecmp.c [deleted file]
libatalk/compat/strdup.c [deleted file]
libatalk/compat/strlcpy.c [new file with mode: 0644]
libatalk/compat/strstr.c [deleted file]
libatalk/dsi/Makefile.am
libatalk/dsi/dsi_attn.c
libatalk/dsi/dsi_close.c
libatalk/dsi/dsi_cmdreply.c
libatalk/dsi/dsi_getsess.c
libatalk/dsi/dsi_getstat.c
libatalk/dsi/dsi_init.c
libatalk/dsi/dsi_opensess.c
libatalk/dsi/dsi_private.h [deleted file]
libatalk/dsi/dsi_read.c
libatalk/dsi/dsi_stream.c
libatalk/dsi/dsi_tcp.c
libatalk/dsi/dsi_tickle.c
libatalk/dsi/dsi_write.c
libatalk/iniparser/Makefile.am [new file with mode: 0644]
libatalk/iniparser/dictionary.c [new file with mode: 0644]
libatalk/iniparser/iniparser.c [new file with mode: 0644]
libatalk/libatalk-3.0beta1.abi [new file with mode: 0644]
libatalk/libatalk-3.0beta2.abi [new file with mode: 0644]
libatalk/libatalk-3.0dev.abi [new file with mode: 0644]
libatalk/locking/.gitignore [new file with mode: 0644]
libatalk/locking/Makefile.am [new file with mode: 0644]
libatalk/locking/locking.c [new file with mode: 0644]
libatalk/nbp/.gitignore [deleted file]
libatalk/nbp/Makefile.am [deleted file]
libatalk/nbp/nbp_conf.h [deleted file]
libatalk/nbp/nbp_lkup.c [deleted file]
libatalk/nbp/nbp_rgstr.c [deleted file]
libatalk/nbp/nbp_unrgstr.c [deleted file]
libatalk/nbp/nbp_util.c [deleted file]
libatalk/netddp/.gitignore [deleted file]
libatalk/netddp/Makefile.am [deleted file]
libatalk/netddp/netddp_open.c [deleted file]
libatalk/netddp/netddp_recvfrom.c [deleted file]
libatalk/netddp/netddp_sendto.c [deleted file]
libatalk/tdb/Makefile.am
libatalk/tdb/check.c [new file with mode: 0644]
libatalk/tdb/dump.c [new file with mode: 0644]
libatalk/tdb/error.c [new file with mode: 0644]
libatalk/tdb/freelist.c [new file with mode: 0644]
libatalk/tdb/freelistcheck.c [new file with mode: 0644]
libatalk/tdb/io.c [new file with mode: 0644]
libatalk/tdb/lock.c [new file with mode: 0644]
libatalk/tdb/open.c [new file with mode: 0644]
libatalk/tdb/spinlock.c [deleted file]
libatalk/tdb/spinlock.h [deleted file]
libatalk/tdb/tdb.c
libatalk/tdb/tdb_private.h [new file with mode: 0644]
libatalk/tdb/transaction.c [new file with mode: 0644]
libatalk/tdb/traverse.c [new file with mode: 0644]
libatalk/unicode/byteorder.h
libatalk/unicode/charcnv.c
libatalk/unicode/charsets/generic_cjk.c
libatalk/unicode/charsets/generic_cjk.h
libatalk/unicode/charsets/generic_mb.c
libatalk/unicode/charsets/mac_centraleurope.c
libatalk/unicode/charsets/mac_chinese_simp.c
libatalk/unicode/charsets/mac_chinese_simp.h
libatalk/unicode/charsets/mac_chinese_trad.c
libatalk/unicode/charsets/mac_chinese_trad.h
libatalk/unicode/charsets/mac_cyrillic.c
libatalk/unicode/charsets/mac_greek.c
libatalk/unicode/charsets/mac_hebrew.c
libatalk/unicode/charsets/mac_japanese.c
libatalk/unicode/charsets/mac_japanese.h
libatalk/unicode/charsets/mac_korean.c
libatalk/unicode/charsets/mac_korean.h
libatalk/unicode/charsets/mac_roman.c
libatalk/unicode/charsets/mac_turkish.c
libatalk/unicode/iconv.c
libatalk/unicode/utf8.c
libatalk/unicode/util_unistr.c
libatalk/util/.gitignore
libatalk/util/Makefile.am
libatalk/util/atalk_addr.c [deleted file]
libatalk/util/bprint.c
libatalk/util/cnid.c
libatalk/util/fault.c
libatalk/util/getiface.c
libatalk/util/logger.c
libatalk/util/netatalk_conf.c [new file with mode: 0644]
libatalk/util/server_child.c
libatalk/util/server_ipc.c
libatalk/util/server_lock.c
libatalk/util/strcasestr.c [deleted file]
libatalk/util/strlcpy.c [deleted file]
libatalk/util/unix.c
libatalk/util/volinfo.c [deleted file]
libatalk/vfs/Makefile.am
libatalk/vfs/ea.c [deleted file]
libatalk/vfs/ea_ad.c [new file with mode: 0644]
libatalk/vfs/ea_sys.c
libatalk/vfs/extattr.c [new file with mode: 0644]
libatalk/vfs/sys_ea.c [deleted file]
libatalk/vfs/unix.c
libatalk/vfs/vfs.c
libevent/.gitignore [new file with mode: 0644]
libevent/ChangeLog [new file with mode: 0644]
libevent/Doxyfile [new file with mode: 0644]
libevent/LICENSE [new file with mode: 0644]
libevent/Makefile.am [new file with mode: 0644]
libevent/Makefile.nmake [new file with mode: 0644]
libevent/README [new file with mode: 0644]
libevent/WIN32-Code/event2/event-config.h [new file with mode: 0644]
libevent/WIN32-Code/tree.h [new file with mode: 0644]
libevent/arc4random.c [new file with mode: 0644]
libevent/autogen.sh [new file with mode: 0755]
libevent/buffer.c [new file with mode: 0644]
libevent/buffer_iocp.c [new file with mode: 0644]
libevent/bufferevent-internal.h [new file with mode: 0644]
libevent/bufferevent.c [new file with mode: 0644]
libevent/bufferevent_async.c [new file with mode: 0644]
libevent/bufferevent_filter.c [new file with mode: 0644]
libevent/bufferevent_openssl.c [new file with mode: 0644]
libevent/bufferevent_pair.c [new file with mode: 0644]
libevent/bufferevent_ratelim.c [new file with mode: 0644]
libevent/bufferevent_sock.c [new file with mode: 0644]
libevent/changelist-internal.h [new file with mode: 0644]
libevent/compat/sys/queue.h [new file with mode: 0644]
libevent/configure.in [new file with mode: 0644]
libevent/defer-internal.h [new file with mode: 0644]
libevent/devpoll.c [new file with mode: 0644]
libevent/epoll.c [new file with mode: 0644]
libevent/epoll_sub.c [new file with mode: 0644]
libevent/evbuffer-internal.h [new file with mode: 0644]
libevent/evdns.3 [new file with mode: 0644]
libevent/evdns.c [new file with mode: 0644]
libevent/evdns.h [new file with mode: 0644]
libevent/event-internal.h [new file with mode: 0644]
libevent/event.3 [new file with mode: 0644]
libevent/event.c [new file with mode: 0644]
libevent/event.h [new file with mode: 0644]
libevent/event_iocp.c [new file with mode: 0644]
libevent/event_rpcgen.py [new file with mode: 0755]
libevent/event_tagging.c [new file with mode: 0644]
libevent/evhttp.h [new file with mode: 0644]
libevent/evmap-internal.h [new file with mode: 0644]
libevent/evmap.c [new file with mode: 0644]
libevent/evport.c [new file with mode: 0644]
libevent/evrpc-internal.h [new file with mode: 0644]
libevent/evrpc.c [new file with mode: 0644]
libevent/evrpc.h [new file with mode: 0644]
libevent/evsignal-internal.h [new file with mode: 0644]
libevent/evthread-internal.h [new file with mode: 0644]
libevent/evthread.c [new file with mode: 0644]
libevent/evthread_pthread.c [new file with mode: 0644]
libevent/evthread_win32.c [new file with mode: 0644]
libevent/evutil.c [new file with mode: 0644]
libevent/evutil.h [new file with mode: 0644]
libevent/evutil_rand.c [new file with mode: 0644]
libevent/ht-internal.h [new file with mode: 0644]
libevent/http-internal.h [new file with mode: 0644]
libevent/http.c [new file with mode: 0644]
libevent/include/Makefile.am [new file with mode: 0644]
libevent/include/event2/buffer.h [new file with mode: 0644]
libevent/include/event2/buffer_compat.h [new file with mode: 0644]
libevent/include/event2/bufferevent.h [new file with mode: 0644]
libevent/include/event2/bufferevent_compat.h [new file with mode: 0644]
libevent/include/event2/bufferevent_ssl.h [new file with mode: 0644]
libevent/include/event2/bufferevent_struct.h [new file with mode: 0644]
libevent/include/event2/dns.h [new file with mode: 0644]
libevent/include/event2/dns_compat.h [new file with mode: 0644]
libevent/include/event2/dns_struct.h [new file with mode: 0644]
libevent/include/event2/event.h [new file with mode: 0644]
libevent/include/event2/event_compat.h [new file with mode: 0644]
libevent/include/event2/event_struct.h [new file with mode: 0644]
libevent/include/event2/http.h [new file with mode: 0644]
libevent/include/event2/http_compat.h [new file with mode: 0644]
libevent/include/event2/http_struct.h [new file with mode: 0644]
libevent/include/event2/keyvalq_struct.h [new file with mode: 0644]
libevent/include/event2/listener.h [new file with mode: 0644]
libevent/include/event2/rpc.h [new file with mode: 0644]
libevent/include/event2/rpc_compat.h [new file with mode: 0644]
libevent/include/event2/rpc_struct.h [new file with mode: 0644]
libevent/include/event2/tag.h [new file with mode: 0644]
libevent/include/event2/tag_compat.h [new file with mode: 0644]
libevent/include/event2/thread.h [new file with mode: 0644]
libevent/include/event2/util.h [new file with mode: 0644]
libevent/iocp-internal.h [new file with mode: 0644]
libevent/ipv6-internal.h [new file with mode: 0644]
libevent/kqueue.c [new file with mode: 0644]
libevent/libevent.pc.in [new file with mode: 0644]
libevent/libevent_openssl.pc.in [new file with mode: 0644]
libevent/libevent_pthreads.pc.in [new file with mode: 0644]
libevent/listener.c [new file with mode: 0644]
libevent/log-internal.h [new file with mode: 0644]
libevent/log.c [new file with mode: 0644]
libevent/m4/acx_pthread.m4 [new file with mode: 0644]
libevent/minheap-internal.h [new file with mode: 0644]
libevent/mm-internal.h [new file with mode: 0644]
libevent/poll.c [new file with mode: 0644]
libevent/ratelim-internal.h [new file with mode: 0644]
libevent/sample/Makefile.am [new file with mode: 0644]
libevent/sample/dns-example.c [new file with mode: 0644]
libevent/sample/event-test.c [new file with mode: 0644]
libevent/sample/hello-world.c [new file with mode: 0644]
libevent/sample/http-server.c [new file with mode: 0644]
libevent/sample/le-proxy.c [new file with mode: 0644]
libevent/sample/signal-test.c [new file with mode: 0644]
libevent/sample/time-test.c [new file with mode: 0644]
libevent/select.c [new file with mode: 0644]
libevent/signal.c [new file with mode: 0644]
libevent/strlcpy-internal.h [new file with mode: 0644]
libevent/strlcpy.c [new file with mode: 0644]
libevent/test/Makefile.am [new file with mode: 0644]
libevent/test/Makefile.nmake [new file with mode: 0644]
libevent/test/bench.c [new file with mode: 0644]
libevent/test/bench_cascade.c [new file with mode: 0644]
libevent/test/bench_http.c [new file with mode: 0644]
libevent/test/bench_httpclient.c [new file with mode: 0644]
libevent/test/regress.c [new file with mode: 0644]
libevent/test/regress.h [new file with mode: 0644]
libevent/test/regress.rpc [new file with mode: 0644]
libevent/test/regress_buffer.c [new file with mode: 0644]
libevent/test/regress_bufferevent.c [new file with mode: 0644]
libevent/test/regress_dns.c [new file with mode: 0644]
libevent/test/regress_et.c [new file with mode: 0644]
libevent/test/regress_http.c [new file with mode: 0644]
libevent/test/regress_iocp.c [new file with mode: 0644]
libevent/test/regress_listener.c [new file with mode: 0644]
libevent/test/regress_main.c [new file with mode: 0644]
libevent/test/regress_minheap.c [new file with mode: 0644]
libevent/test/regress_rpc.c [new file with mode: 0644]
libevent/test/regress_ssl.c [new file with mode: 0644]
libevent/test/regress_testutils.c [new file with mode: 0644]
libevent/test/regress_testutils.h [new file with mode: 0644]
libevent/test/regress_thread.c [new file with mode: 0644]
libevent/test/regress_util.c [new file with mode: 0644]
libevent/test/regress_zlib.c [new file with mode: 0644]
libevent/test/rpcgen_wrapper.sh [new file with mode: 0755]
libevent/test/test-changelist.c [new file with mode: 0644]
libevent/test/test-eof.c [new file with mode: 0644]
libevent/test/test-init.c [new file with mode: 0644]
libevent/test/test-ratelim.c [new file with mode: 0644]
libevent/test/test-ratelim.sh [new file with mode: 0755]
libevent/test/test-time.c [new file with mode: 0644]
libevent/test/test-weof.c [new file with mode: 0644]
libevent/test/test.sh [new file with mode: 0755]
libevent/test/tinytest.c [new file with mode: 0644]
libevent/test/tinytest.h [new file with mode: 0644]
libevent/test/tinytest_demo.c [new file with mode: 0644]
libevent/test/tinytest_local.h [new file with mode: 0644]
libevent/test/tinytest_macros.h [new file with mode: 0644]
libevent/util-internal.h [new file with mode: 0644]
libevent/whatsnew-2.0.txt [new file with mode: 0644]
libevent/win32select.c [new file with mode: 0644]
macros/Makefile.am
macros/afs-check.m4
macros/config-checks.m4
macros/cups.m4 [deleted file]
macros/db3-check.m4
macros/gssapi-check.m4
macros/iconv.m4
macros/libgcrypt.m4
macros/netatalk.m4 [new file with mode: 0644]
macros/pam-check.m4
macros/quota-check.m4
macros/snprintf-check.m4 [deleted file]
macros/srvloc.m4 [deleted file]
macros/ssl-check.m4
macros/summary.m4
macros/tcp-wrappers.m4
macros/webmin.m4 [deleted file]
macros/zeroconf.m4
man/Makefile.am
man/man1/Makefile.am
man/man1/ad.1
man/man1/aecho.1 [deleted file]
man/man1/afpldaptest.1.tmpl
man/man1/afppasswd.1
man/man1/apple_dump.1
man/man1/asip-status.pl.1.tmpl
man/man1/dbd.1
man/man1/getzones.1 [deleted file]
man/man1/macusers.1
man/man1/megatron.1
man/man1/nbp.1 [deleted file]
man/man1/nbplkup.1 [deleted file]
man/man1/nbprgstr.1 [deleted file]
man/man1/nbpunrgstr.1 [deleted file]
man/man1/netatalk-config.1
man/man1/pap.1 [deleted file]
man/man1/papstatus.1 [deleted file]
man/man1/psorder.1 [deleted file]
man/man1/uniconv.1.tmpl
man/man3/.gitignore [deleted file]
man/man3/Makefile.am [deleted file]
man/man3/atalk_aton.3 [deleted file]
man/man3/nbp_name.3 [deleted file]
man/man4/.gitignore [deleted file]
man/man4/Makefile.am [deleted file]
man/man4/atalk.4 [deleted file]
man/man5/.gitignore
man/man5/AppleVolumes.5 [deleted file]
man/man5/AppleVolumes.default.5.tmpl [deleted file]
man/man5/AppleVolumes.system.5 [deleted file]
man/man5/Makefile.am
man/man5/afp.conf.5.tmpl [new file with mode: 0644]
man/man5/afp_ldap.conf.5.tmpl [deleted file]
man/man5/afp_signature.conf.5.tmpl
man/man5/afp_voluuid.conf.5.tmpl
man/man5/afpd.conf.5.tmpl [deleted file]
man/man5/atalkd.conf.5.tmpl [deleted file]
man/man5/netatalk.conf.5.tmpl [deleted file]
man/man5/papd.conf.5.tmpl [deleted file]
man/man8/.gitignore
man/man8/Makefile.am
man/man8/afpd.8.tmpl
man/man8/atalkd.8.tmpl [deleted file]
man/man8/cnid_dbd.8.tmpl
man/man8/cnid_metad.8.tmpl
man/man8/netatalk.8.tmpl [new file with mode: 0644]
man/man8/papd.8.tmpl [deleted file]
man/man8/papstatus.8.tmpl [deleted file]
man/man8/psf.8.tmpl [deleted file]
man/man8/timelord.8 [deleted file]
services.atalk [deleted file]
sys/.gitignore [deleted file]
sys/Makefile.am [deleted file]
sys/generic/.gitignore [deleted file]
sys/generic/Makefile.am [deleted file]
sys/generic/sys/.gitignore [deleted file]
sys/generic/sys/Makefile.am [deleted file]
sys/generic/sys/cdefs.h [deleted file]
sys/netatalk/.gitignore [deleted file]
sys/netatalk/Makefile.am [deleted file]
sys/netatalk/aarp.c [deleted file]
sys/netatalk/aarp.h [deleted file]
sys/netatalk/at.h [deleted file]
sys/netatalk/at_control.c [deleted file]
sys/netatalk/at_proto.c [deleted file]
sys/netatalk/at_var.h [deleted file]
sys/netatalk/ddp.h [deleted file]
sys/netatalk/ddp_input.c [deleted file]
sys/netatalk/ddp_output.c [deleted file]
sys/netatalk/ddp_usrreq.c [deleted file]
sys/netatalk/ddp_var.h [deleted file]
sys/netatalk/endian.h [deleted file]
sys/netatalk/phase2.h [deleted file]
sys/netbsd/.gitignore [deleted file]
sys/netbsd/Makefile.am [deleted file]
sys/netbsd/netatalk/.gitignore [deleted file]
sys/netbsd/netatalk/Makefile.am [deleted file]
sys/netbsd/netatalk/endian.h [deleted file]
sys/solaris/.gitignore [deleted file]
sys/solaris/Makefile.in [deleted file]
sys/solaris/aarp.c [deleted file]
sys/solaris/ddp.c [deleted file]
sys/solaris/ddp.conf [deleted file]
sys/solaris/dlpi.c [deleted file]
sys/solaris/if.c [deleted file]
sys/solaris/if.h [deleted file]
sys/solaris/ioc.c [deleted file]
sys/solaris/ioc.h [deleted file]
sys/solaris/linkage.c [deleted file]
sys/solaris/rt.c [deleted file]
sys/solaris/rt.h [deleted file]
sys/solaris/sock.c [deleted file]
sys/solaris/sock.h [deleted file]
sys/solaris/tpi.c [deleted file]
sys/sunos/.gitignore [deleted file]
sys/sunos/Makefile.am [deleted file]
sys/sunos/Makefile.kernel [deleted file]
sys/sunos/at_sun.c [deleted file]
sys/ultrix/.gitignore [deleted file]
sys/ultrix/Makefile.am [deleted file]
sys/ultrix/Makefile.kernel [deleted file]
sys/ultrix/at_ultrix.c [deleted file]
sys/ultrix/kpatch-4.1 [deleted file]
sys/ultrix/kpatch-4.2 [deleted file]
test/afpd/Makefile.am
test/afpd/afpfunc_helpers.c
test/afpd/test.c
test/afpd/test.sh

index df298a156691d33a5798ab8f181a12130d3ad4b5..f9ba2b20ff909c898baa04bd4f33e589c40fde61 100644 (file)
@@ -26,5 +26,4 @@ autoscan.log
 *.tar.gz
 *.diff.gz
 *~
-.gitignore
 *.o
index 1203023118901ebe8c00249ef3cc2889222fe104..448375a8ca32e6ae1c576ade6563140cb86c1427 100644 (file)
@@ -1,9 +1,19 @@
 # Makefile.am for top level of netatalk package
 
-SUBDIRS = libatalk bin config etc man contrib distrib include sys doc macros test
+SUBDIRS = libatalk libevent bin config etc man contrib distrib include doc macros test
 
-EXTRA_DIST = CONTRIBUTORS COPYRIGHT COPYING NEWS VERSION services.atalk
+EXTRA_DIST = CONTRIBUTORS COPYRIGHT COPYING NEWS VERSION
 
 ACLOCAL_AMFLAGS = -I macros
 AUTOMAKE_OPTIONS = foreign
 
+if USE_BUILTIN_LIBEVENT
+       SUBDIRS += libevent
+endif
+
+if RUN_LDCONFIG
+install-exec-hook:
+       @printf "Running ldconfig to ensure libraries installed in system library directories are added to the dynamic linker cache ... "
+       @-@NETA_LDCONFIG@
+       @printf "done\n"
+endif
diff --git a/NEWS b/NEWS
index 0f88863b1f853ac675babfc5f83e62a7c53d03df..4c6e3dd2cf8aae37f878923a39e6c4e16577866d 100644 (file)
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,85 @@
+Changes in 3.0 beta3
+====================
+* UPD: read only mode if cnid scheme is last
+* REM: global option "icon"
+
+Changes in 3.0 beta2
+====================
+* UPD: Solaris and friends: Replace initscript with SMF manifest
+* FIX: Solaris and friends: resource fork handling
+
+Changes in 3.0 beta1
+====================
+* UPD: afpd: Performance tuning of read/write AFP operations. New option
+       "afp read locks" (default: no) which disables that the server
+       applies UNIX byte range locks to regions of files in AFP read and
+       write calls.
+* UPD: apple_dump: Extended Attributes AppleDouble support.
+       (*BSD is not supported yet)
+
+Changes in 3.0 alpha3
+=====================
+
+* NEW: afpd: Per volume "login message", NetAFP bug ID #18
+* NEW: afpd: Cross-platform locking (share modes) on Solaris and derivates
+       with Solaris CIFS/SMB server. Uses new Solaris fcntl F_SHARE share
+       reservation locking primitives. Enabled by default, set global
+       "solaris share reservations" option to false to disable it.
+* NEW: ad: ad set subcommand for changing Mac metadata on the server
+* UPD: unix charset is UTF8 by default.
+       vol charset is same value as unix charset by default.
+* UPD: .AppleDesktop/ are stored in $localstatedir/netatalk/CNID
+       (default: /var/netatalk/CNID), databases found in AFP volumes are
+       automatically moved
+* FIX: afpd: Server info packet was malformed resulting in broken
+       server names being displayed on clients
+* FIX: afpd: Byte order detection. Fixes an error where Netatalk on
+       OpenIndiana returned wrong volume size information.
+
+Changes in 3.0 alpha2
+=====================
+
+* UPD: afpd: Store '.' as is and '/' as ':' on the server, don't
+       CAP hexencode as "2e" and "2f" respectively
+* UPD: afdp: Automatic name conversion, renaming files and directories
+       containing CAP sequences to their not enscaped forms
+* UPD: afpd: Correct handling of user homes and users without homes
+* UPD: afpd: Perform complete automatic adouble:v2 to adouble:ea conversion
+       as root. Previously only unlinking the adouble:v2 file was done as root
+* UPD: dbd: -C option removes CAP encoding
+* UPD: Add graceful option to RedHat init script
+* UPD: Add --disable-bundled-libevent configure options When set to yes,
+       we rely on a properly installed version on libevent CPPFLAGS and LDFLAGS
+       should be set properly to pick that up
+* UPD: Run ldconfig on Linux at the end of make install
+* FIX: afpd: ad cp on appledouble = ea volumes
+* FIX: dbd: ignore ._ appledouble files
+* REM: Volumes options "use dots" and "hex encoding"
+
+Changes in 3.0 alpha1
+=====================
+
+* NEW: Central configuration file afp.conf which replaces all previous files
+* NEW: netatalk: service controller starting and restarting afpd and cnid_metad
+       as necessary
+* NEW: afpd: Extended Attributes AppleDouble backend (default)
+* UPD: CNID databases are stored in $localstatedir/netatalk/CNID
+       (default: /var/netatalk/CNID), databases found in AFP volumes are
+       automatically moved
+* UPD: Start scripts and service manifests have been changed to only start
+       the new netatalk service controller process
+* UPD: afpd: UNIX privileges and use dots enabled by default
+* UPD: afpd: Support for arbitrary AFP volumes using variable expansion has been
+       removed
+* UPD: afpd: afp_voluuid.conf and afp_signature.conf location has been
+       changed to $localstatedir/netatalk/ (default: /var/netatalk/)
+* UPD: afpd: default server messages dir changed to $localstatedir/netatalk/msg/
+* UPD: dbd: new option -C for conversion from AppleDouble v2 to ea
+* REM: AppleTalk support has been removed
+* REM: afpd: SLP and AFP proxy support have been removed
+* REM: afpd: legacy file extension to type/creator mapping has been removed
+* REM: afpd: AppleDouble backends v1, osx and sfm have been removed
+
 Changes in 2.2.4
 ================
 
diff --git a/VERSION b/VERSION
index c3ff749c71ea9ec9f2e89bca8ecc796a7b96780b..48898d6a616ca58a9e8798ab09639b25511eaf08 100644 (file)
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-2.2.4dev
\ No newline at end of file
+3.0dev
\ No newline at end of file
diff --git a/abigen.sh b/abigen.sh
new file mode 100755 (executable)
index 0000000..3d3c33d
--- /dev/null
+++ b/abigen.sh
@@ -0,0 +1,21 @@
+#!/bin/sh
+# generate a set of ABI signatures from a shared library
+
+SHAREDLIB="$1"
+
+GDBSCRIPT="gdb_syms.$$"
+
+(
+cat <<EOF
+set height 0
+set width 0
+EOF
+nm "$SHAREDLIB" | cut -d' ' -f2- | egrep '^[BDGTRVWS]' | grep -v @ | cut -c3- | sort | while read s; do
+    echo "echo $s: "
+    echo p $s
+done
+) > $GDBSCRIPT
+
+# forcing the terminal avoids a problem on Fedora12
+TERM=none gdb -batch -x $GDBSCRIPT "$SHAREDLIB" < /dev/null | sed -e 's/:\$[0-9]* = /: /g' -e 's/<[0-9a-zA-Z_]*>$//g' -e 's/0x[0-9a-f]* $//g' -e 's/0x[[:xdigit:]]* \("[[:alnum:] _-]*"\)/\1/g' -e 's/0x[[:xdigit:]]* \(<[[:alnum:] _-]*>\)/\1/g' -e 's/{\(.*\)} $/\1/g'
+rm -f $GDBSCRIPT
index 7c633f748f409ed1fecf5ba637ebfa75d7ce572b..f5d1448ae3621d70a8241af4864a925335693e68 100644 (file)
@@ -1,10 +1,6 @@
 # Makefile.am for bin/
 
-SUBDIRS = adv1tov2 afppasswd cnid megatron uniconv misc
-
-if USE_APPLETALK
-SUBDIRS += aecho getzones nbp pap psorder
-endif
+SUBDIRS = afppasswd cnid megatron uniconv misc
 
 if HAVE_ATFUNCS
 SUBDIRS += ad
index 7e6fe922b911db850841a15d3e7e72eb6d3cf491..5c3f47b67f918c634dc9247d97d3c70e42896f5c 100644 (file)
@@ -12,7 +12,8 @@ ad_SOURCES = \
        ad_ls.c \
        ad_cp.c \
        ad_mv.c \
-       ad_rm.c
+       ad_rm.c \
+       ad_set.c
 
 ad_CFLAGS = -D_PATH_AD=\"$(bindir)/ad\"
 
index 38fd62bb3890099335d3780496af36a1eaaf8004..7f5b3da6260e626ae210dfa71c82e13777a55240 100644 (file)
 #include <errno.h>
 
 #include <atalk/cnid.h>
-#include <atalk/volinfo.h>
 #include <atalk/logger.h>
 #include <atalk/util.h>
+#include <atalk/netatalk_conf.h>
 
 #include "ad.h"
 
 static void usage_main(void)
 {
-    printf("Usage: ad ls|cp|rm|mv|find [file|dir, ...]\n");
+    printf("Usage: ad ls|cp|rm|mv|set|find [file|dir, ...]\n");
     printf("       ad -v|--version\n");
 }
 
@@ -46,23 +46,33 @@ static void show_version(void)
 
 int main(int argc, char **argv)
 {
-    setuplog("default log_note /dev/tty");
+    AFPObj obj = { 0 };
 
     if (argc < 2) {
         usage_main();
         return 1;
     }
 
+    if (afp_config_parse(&obj, "ad") != 0)
+        return 1;
+
+    setuplog("default:note", "/dev/tty");
+
+    if (load_volumes(&obj, NULL) != 0)
+        return 1;
+
     if (STRCMP(argv[1], ==, "ls"))
-        return ad_ls(argc - 1, argv + 1);
+        return ad_ls(argc - 1, argv + 1, &obj);
     else if (STRCMP(argv[1], ==, "cp"))
-        return ad_cp(argc - 1, argv + 1);
+        return ad_cp(argc - 1, argv + 1, &obj);
     else if (STRCMP(argv[1], ==, "rm"))
-        return ad_rm(argc - 1, argv + 1);
+        return ad_rm(argc - 1, argv + 1, &obj);
     else if (STRCMP(argv[1], ==, "mv"))
-        return ad_mv(argc, argv);
+        return ad_mv(argc, argv, &obj);
+    else if (STRCMP(argv[1], ==, "set"))
+        return ad_set(argc - 1, argv + 1, &obj);
     else if (STRCMP(argv[1], ==, "find"))
-        return ad_find(argc, argv);
+        return ad_find(argc, argv, &obj);
     else if (STRCMP(argv[1], ==, "-v")) {
         show_version();
         return 1;
index 6e41a9c02ba932cd5e2829b11b5da05f9aacb668..3195641f7cb291c78e66d580a4d3a047f9d53997 100644 (file)
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <signal.h>
+#include <arpa/inet.h>
 
+#include <atalk/globals.h>
 #include <atalk/ftw.h>
-#include <atalk/volinfo.h>
 #include <atalk/cnid.h>
+#include <atalk/compat.h>
+#include <atalk/volume.h>
 
 #define DIR_DOT_OR_DOTDOT(a) \
         ((strcmp(a, ".") == 0) || (strcmp(a, "..") == 0))
@@ -35,6 +38,8 @@
     }
 #endif
 
+#define ADVOL_V2_OR_EA(ad) ((ad) == AD_VERSION2 || (ad) == AD_VERSION_EA)
+
 enum logtype {STD, DBG};
 
 #define SLOG(...)                             \
@@ -47,26 +52,26 @@ enum logtype {STD, DBG};
     } while (0)
 
 typedef struct {
-    struct volinfo volinfo;
-    struct vol     volume;
+    struct vol     *vol;
     char           db_stamp[ADEDLEN_PRIVSYN];
 } afpvol_t;
 
 extern int log_verbose;             /* Logging flag */
 extern void _log(enum logtype lt, char *fmt, ...);
 
-extern int ad_ls(int argc, char **argv);
-extern int ad_cp(int argc, char **argv);
-extern int ad_rm(int argc, char **argv);
-extern int ad_mv(int argc, char **argv);
-extern int ad_find(int argc, char **argv);
+extern int ad_ls(int argc, char **argv, AFPObj *obj);
+extern int ad_cp(int argc, char **argv, AFPObj *obj);
+extern int ad_rm(int argc, char **argv, AFPObj *obj);
+extern int ad_mv(int argc, char **argv, AFPObj *obj);
+extern int ad_set(int argc, char **argv, AFPObj *obj);
+extern int ad_find(int argc, char **argv, AFPObj *obj);
 
 /* ad_util.c */
-extern int openvol(const char *path, afpvol_t *vol);
+extern int openvol(AFPObj *obj, const char *path, afpvol_t *vol);
 extern void closevol(afpvol_t *vol);
 extern cnid_t cnid_for_path(const afpvol_t *vol, const char *path, cnid_t *did);
 extern cnid_t cnid_for_paths_parent(const afpvol_t *vol, const char *path, cnid_t *did);
-extern char *utompath(const struct volinfo *volinfo, const char *upath);
+extern char *utompath(const struct vol *, const char *);
 extern int convert_dots_encoding(const afpvol_t *svol, const afpvol_t *dvol, char *path, size_t buflen);
 
 typedef struct {
index 720ea6d3175027bc5d62480cbd31a58b61f2bcd3..ef995ce8cf3f159c6346a5e32a4858e9cfad8948 100644 (file)
@@ -67,7 +67,6 @@
 #include <atalk/util.h>
 #include <atalk/unix.h>
 #include <atalk/volume.h>
-#include <atalk/volinfo.h>
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
 #include <atalk/queue.h>
@@ -212,7 +211,7 @@ static void usage_cp(void)
     exit(EXIT_FAILURE);
 }
 
-int ad_cp(int argc, char *argv[])
+int ad_cp(int argc, char *argv[], AFPObj *obj)
 {
     struct stat to_stat, tmp_stat;
     int r, ch, have_trailing_slash;
@@ -352,11 +351,11 @@ int ad_cp(int argc, char *argv[])
 #endif
 
     /* Load .volinfo file for destination*/
-    openvol(to.p_path, &dvolume);
+    openvol(obj, to.p_path, &dvolume);
 
     for (int i = 0; argv[i] != NULL; i++) {
         /* Load .volinfo file for source */
-        openvol(argv[i], &svolume);
+        openvol(obj, argv[i], &svolume);
 
         if (nftw(argv[i], copy, upfunc, 20, ftw_options) == -1) {
             if (alarmed) {
@@ -396,7 +395,7 @@ static int copy(const char *path,
         dir = path;
     else
         dir++;
-    if (check_netatalk_dirs(dir) != NULL)
+    if (!dvolume.vol->vfs->vfs_validupath(dvolume.vol, dir))
         return FTW_SKIP_SUBTREE;
 
     /*
@@ -475,7 +474,7 @@ static int copy(const char *path,
     }
 
     /* Convert basename to appropiate volume encoding */
-    if (dvolume.volinfo.v_path) {
+    if (dvolume.vol->v_path) {
         if ((convert_dots_encoding(&svolume, &dvolume, to.p_path, MAXPATHLEN)) == -1) {
             SLOG("Error converting name for %s", to.p_path);
             badcp = rval = 1;
@@ -511,18 +510,19 @@ static int copy(const char *path,
         }
 
         /* Create ad dir and copy ".Parent" */
-        if (dvolume.volinfo.v_path && dvolume.volinfo.v_adouble == AD_VERSION2) {
-
-            /* Create ".AppleDouble" dir */
+        if (dvolume.vol->v_path && ADVOL_V2_OR_EA(dvolume.vol->v_adouble)) {
             mode_t omask = umask(0);
-            bstring addir = bfromcstr(to.p_path);
-            bcatcstr(addir, "/.AppleDouble");
-            mkdir(cfrombstr(addir), 02777);
-            bdestroy(addir);
-
-            if (svolume.volinfo.v_path && svolume.volinfo.v_adouble == AD_VERSION2) {
-                /* copy ".Parent" file */
-                if (dvolume.volume.vfs->vfs_copyfile(&dvolume.volume, -1, path, to.p_path)) {
+            if (dvolume.vol->v_adouble == AD_VERSION2) {
+                /* Create ".AppleDouble" dir */
+                bstring addir = bfromcstr(to.p_path);
+                bcatcstr(addir, "/.AppleDouble");
+                mkdir(cfrombstr(addir), 02777);
+                bdestroy(addir);
+            }
+
+            if (svolume.vol->v_path && ADVOL_V2_OR_EA(svolume.vol->v_adouble)) {
+                /* copy metadata file */
+                if (dvolume.vol->vfs->vfs_copyfile(dvolume.vol, -1, path, to.p_path)) {
                     SLOG("Error copying adouble for %s -> %s", path, to.p_path);
                     badcp = rval = 1;
                     break;
@@ -543,18 +543,19 @@ static int copy(const char *path,
                 badcp = rval = 1;
                 break;
             }
-            ad_init(&ad, dvolume.volinfo.v_adouble, dvolume.volinfo.v_ad_options);
-            if (ad_open_metadata(to.p_path, ADFLAGS_DIR, O_RDWR | O_CREAT, &ad) != 0) {
+            ad_init(&ad, dvolume.vol);
+            if (ad_open(&ad, to.p_path, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) != 0) {
                 ERROR("Error opening adouble for: %s", to.p_path);
             }
             ad_setid( &ad, st.st_dev, st.st_ino, did, pdid, dvolume.db_stamp);
-            ad_setname(&ad, utompath(&dvolume.volinfo, basename(to.p_path)));
+            if (dvolume.vol->v_adouble == AD_VERSION2)
+                ad_setname(&ad, utompath(dvolume.vol, basename(to.p_path)));
             ad_setdate(&ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
             ad_setdate(&ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
             ad_setdate(&ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
             ad_setdate(&ad, AD_DATE_BACKUP, AD_DATE_START);
             ad_flush(&ad);
-            ad_close_metadata(&ad);
+            ad_close(&ad, ADFLAGS_HF);
 
             umask(omask);
         }
@@ -583,12 +584,12 @@ static int copy(const char *path,
         if (ftw_copy_file(ftw, path, statp, dne))
             badcp = rval = 1;
 
-        if (dvolume.volinfo.v_path && dvolume.volinfo.v_adouble == AD_VERSION2) {
+        if (dvolume.vol->v_path && ADVOL_V2_OR_EA(dvolume.vol->v_adouble)) {
 
             mode_t omask = umask(0);
-            if (svolume.volinfo.v_path && svolume.volinfo.v_adouble == AD_VERSION2) {
+            if (svolume.vol->v_path && ADVOL_V2_OR_EA(svolume.vol->v_adouble)) {
                 /* copy ad-file */
-                if (dvolume.volume.vfs->vfs_copyfile(&dvolume.volume, -1, path, to.p_path)) {
+                if (dvolume.vol->vfs->vfs_copyfile(dvolume.vol, -1, path, to.p_path)) {
                     SLOG("Error copying adouble for %s -> %s", path, to.p_path);
                     badcp = rval = 1;
                     break;
@@ -610,18 +611,19 @@ static int copy(const char *path,
                 badcp = rval = 1;
                 break;
             }
-            ad_init(&ad, dvolume.volinfo.v_adouble, dvolume.volinfo.v_ad_options);
-            if (ad_open_metadata(to.p_path, 0, O_RDWR | O_CREAT, &ad) != 0) {
+            ad_init(&ad, dvolume.vol);
+            if (ad_open(&ad, to.p_path, ADFLAGS_HF | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) != 0) {
                 ERROR("Error opening adouble for: %s", to.p_path);
             }
             ad_setid( &ad, st.st_dev, st.st_ino, cnid, did, dvolume.db_stamp);
-            ad_setname(&ad, utompath(&dvolume.volinfo, basename(to.p_path)));
+            if (dvolume.vol->v_adouble == AD_VERSION2)
+                ad_setname(&ad, utompath(dvolume.vol, basename(to.p_path)));
             ad_setdate(&ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
             ad_setdate(&ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
             ad_setdate(&ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
             ad_setdate(&ad, AD_DATE_BACKUP, AD_DATE_START);
             ad_flush(&ad);
-            ad_close_metadata(&ad);
+            ad_close(&ad, ADFLAGS_HF);
             umask(omask);
         }
         break;
@@ -693,7 +695,7 @@ static int ftw_copy_file(const struct FTW *entp,
             /* remove existing destination file name,
              * create a new file  */
             (void)unlink(to.p_path);
-            (void)dvolume.volume.vfs->vfs_deletefile(&dvolume.volume, -1, to.p_path);
+            (void)dvolume.vol->vfs->vfs_deletefile(dvolume.vol, -1, to.p_path);
             to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
                          sp->st_mode & ~(S_ISUID | S_ISGID));
         } else {
index 8501500c7c7ff9acb229a3a005a0279db55442d3..88a46752e2f1199b20f506c3a9d0034c912e645b 100644 (file)
@@ -28,7 +28,6 @@
 #include <atalk/adouble.h>
 #include <atalk/cnid.h>
 #include <atalk/cnid_dbd_private.h>
-#include <atalk/volinfo.h>
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
 #include <atalk/directory.h>
@@ -83,7 +82,7 @@ static void usage_find(void)
         );
 }
 
-int ad_find(int argc, char **argv)
+int ad_find(int argc, char **argv, AFPObj *obj)
 {
     int c, ret;
     afpvol_t vol;
@@ -112,14 +111,14 @@ int ad_find(int argc, char **argv)
     set_signal();
     cnid_init();
 
-    if (openvol(srchvol, &vol) != 0)
+    if (openvol(obj, srchvol, &vol) != 0)
         ERROR("Cant open volume \"%s\"", srchvol);
 
     uint16_t flags = CONV_TOLOWER;
     char namebuf[MAXPATHLEN + 1];
-    if (convert_charset(vol.volinfo.v_volcharset,
-                        vol.volinfo.v_volcharset,
-                        vol.volinfo.v_maccharset,
+    if (convert_charset(vol.vol->v_volcharset,
+                        vol.vol->v_volcharset,
+                        vol.vol->v_maccharset,
                         argv[optind],
                         strlen(argv[optind]),
                         namebuf,
@@ -130,7 +129,7 @@ int ad_find(int argc, char **argv)
 
     int count;
     char resbuf[DBD_MAX_SRCH_RSLTS * sizeof(cnid_t)];
-    if ((count = cnid_find(vol.volume.v_cdb,
+    if ((count = cnid_find(vol.vol->v_cdb,
                            namebuf,
                            strlen(namebuf),
                            resbuf,
@@ -146,7 +145,7 @@ int ad_find(int argc, char **argv)
             bufp += sizeof(cnid_t);
 
             bstring path = NULL;
-            bstring volpath = bfromcstr(vol.volinfo.v_path);
+            bstring volpath = bfromcstr(vol.vol->v_path);
             BSTRING_STRIP_SLASH(volpath);
             char buffer[12 + MAXPATHLEN + 1];
             int buflen = 12 + MAXPATHLEN + 1;
@@ -155,7 +154,7 @@ int ad_find(int argc, char **argv)
             struct bstrList *pathlist = bstrListCreateMin(32);
 
             while (did != DIRDID_ROOT) {
-                if ((name = cnid_resolve(vol.volume.v_cdb, &did, buffer, buflen)) == NULL)
+                if ((name = cnid_resolve(vol.vol->v_cdb, &did, buffer, buflen)) == NULL)
                     goto next;
                 bstrListPush(pathlist, bfromcstr(name));
             }
index 63226a37cd77ccc5a174ad285151546481a88268..d8362595e4647a7ef54098d4f1711b5b45b5b2ce 100644 (file)
@@ -33,7 +33,6 @@
 
 #include <atalk/adouble.h>
 #include <atalk/cnid.h>
-#include <atalk/volinfo.h>
 #include "ad.h"
 
 #define ADv2_DIRNAME ".AppleDouble"
@@ -228,10 +227,10 @@ static void print_flags(char *path, afpvol_t *vol, const struct stat *st)
     if (S_ISDIR(st->st_mode))
         adflags = ADFLAGS_DIR;
 
-    if (vol->volinfo.v_path == NULL)
+    if (vol->vol->v_path == NULL)
         return;
 
-    ad_init(&ad, vol->volinfo.v_adouble, vol->volinfo.v_ad_options);
+    ad_init(&ad, vol->vol);
 
     if ( ad_metadata(path, adflags, &ad) < 0 )
         return;
@@ -381,7 +380,7 @@ static void print_flags(char *path, afpvol_t *vol, const struct stat *st)
     else
         printf(" !ADVOL_CACHE ");
 
-    ad_close_metadata(&ad);
+    ad_close(&ad, ADFLAGS_HF);
 }
 
 #define TYPE(b) ((st->st_mode & (S_IFMT)) == (b))
@@ -595,7 +594,7 @@ exit:
     return ret;
 }
 
-int ad_ls(int argc, char **argv)
+int ad_ls(int argc, char **argv, AFPObj *obj)
 {
     int c, firstarg;
     afpvol_t vol;
@@ -631,7 +630,7 @@ int ad_ls(int argc, char **argv)
     cnid_init();
 
     if ((argc - optind) == 0) {
-        openvol(".", &vol);
+        openvol(obj, ".", &vol);
         ad_ls_r(".", &vol);
         closevol(&vol);
     }
@@ -651,7 +650,7 @@ int ad_ls(int argc, char **argv)
             first = 1;
             recursion = 0;
 
-            openvol(argv[optind], &vol);
+            openvol(obj, argv[optind], &vol);
             ad_ls_r(argv[optind], &vol);
             closevol(&vol);
         next:
@@ -673,7 +672,7 @@ int ad_ls(int argc, char **argv)
             first = 1;
             recursion = 0;
 
-            openvol(argv[optind], &vol);
+            openvol(obj, argv[optind], &vol);
             ad_ls_r(argv[optind], &vol);
             closevol(&vol);
 
index 4d23183ae13865c3c59a8298cde36e5cedbfeb91..7f592dd27e1aaf0623bb2a2e34038e13a6468b33 100644 (file)
@@ -34,7 +34,6 @@
 #include <atalk/util.h>
 #include <atalk/unix.h>
 #include <atalk/volume.h>
-#include <atalk/volinfo.h>
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
 #include <atalk/queue.h>
@@ -140,7 +139,7 @@ static void usage_mv(void)
     exit(EXIT_FAILURE);
 }
 
-int ad_mv(int argc, char *argv[])
+int ad_mv(int argc, char *argv[], AFPObj *obj)
 {
     size_t baselen, len;
     int rval;
@@ -185,7 +184,7 @@ int ad_mv(int argc, char *argv[])
 
     set_signal();
     cnid_init();
-    if (openvol(argv[argc - 1], &dvolume) != 0) {
+    if (openvol(obj, argv[argc - 1], &dvolume) != 0) {
         SLOG("Error opening CNID database for source \"%s\": ", argv[argc - 1]);
         return 1;
     }
@@ -197,7 +196,7 @@ int ad_mv(int argc, char *argv[])
     if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
         if (argc > 2)
             usage_mv();
-        if (openvol(argv[0], &svolume) != 0) {
+        if (openvol(obj, argv[0], &svolume) != 0) {
             SLOG("Error opening CNID database for destination \"%s\": ", argv[0]);
             return 1;
         }
@@ -235,7 +234,7 @@ int ad_mv(int argc, char *argv[])
             rval = 1;
         } else {
             memmove(endp, p, (size_t)len + 1);
-            openvol(*argv, &svolume);
+            openvol(obj, *argv, &svolume);
 
             if (do_move(*argv, path))
                 rval = 1;
@@ -295,9 +294,9 @@ static int do_move(const char *from, const char *to)
      * 1) source AFP volume != dest AFP volume
      * 2) either source or dest isn't even an AFP volume
      */
-    if (!svolume.volinfo.v_path
-        || !dvolume.volinfo.v_path
-        || strcmp(svolume.volinfo.v_path, dvolume.volinfo.v_path) != 0)
+    if (!svolume.vol->v_path
+        || !dvolume.vol->v_path
+        || strcmp(svolume.vol->v_path, dvolume.vol->v_path) != 0)
         mustcopy = 1;
     
     cnid_t cnid = 0;
@@ -340,7 +339,7 @@ static int do_move(const char *from, const char *to)
         
         switch (sb.st_mode & S_IFMT) {
         case S_IFREG:
-            if (dvolume.volume.vfs->vfs_renamefile(&dvolume.volume, -1, from, to) != 0) {
+            if (dvolume.vol->vfs->vfs_renamefile(dvolume.vol, -1, from, to) != 0) {
                 SLOG("Error moving adouble file for %s", from);
                 return -1;
             }
@@ -366,21 +365,21 @@ static int do_move(const char *from, const char *to)
 
         char *p = strdup(to);
         char *name = basename(p);
-        if (cnid_update(dvolume.volume.v_cdb, cnid, &sb, newdid, name, strlen(name)) != 0) {
+        if (cnid_update(dvolume.vol->v_cdb, cnid, &sb, newdid, name, strlen(name)) != 0) {
             SLOG("Cant update CNID for: %s", to);
             return 1;
         }
         free(p);
 
         struct adouble ad;
-        ad_init(&ad, dvolume.volinfo.v_adouble, dvolume.volinfo.v_ad_options);
-        if (ad_open_metadata(to, S_ISDIR(sb.st_mode) ? ADFLAGS_DIR : 0, O_RDWR, &ad) != 0) {
+        ad_init(&ad, dvolume.vol);
+        if (ad_open(&ad, to, S_ISDIR(sb.st_mode) ? (ADFLAGS_DIR | ADFLAGS_HF | ADFLAGS_RDWR) : ADFLAGS_HF | ADFLAGS_RDWR) != 0) {
             SLOG("Error opening adouble for: %s", to);
             return 1;
         }
         ad_setid(&ad, sb.st_dev, sb.st_ino, cnid, newdid, dvolume.db_stamp);
         ad_flush(&ad);
-        ad_close_metadata(&ad);
+        ad_close(&ad, ADFLAGS_HF);
 
         if (vflg)
             printf("%s -> %s\n", from, to);
index b9ef2c3c2d941d11b8a0c7eba4227e0e4011a047..195fee06979301eeef8e9e80d1c66c7d34f00904 100644 (file)
@@ -32,7 +32,6 @@
 #include <atalk/util.h>
 #include <atalk/unix.h>
 #include <atalk/volume.h>
-#include <atalk/volinfo.h>
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
 #include <atalk/queue.h>
@@ -133,7 +132,7 @@ static void usage_rm(void)
     exit(EXIT_FAILURE);
 }
 
-int ad_rm(int argc, char *argv[])
+int ad_rm(int argc, char *argv[], AFPObj *obj)
 {
     int ch;
 
@@ -166,7 +165,7 @@ int ad_rm(int argc, char *argv[])
 
     for (int i = 0; argv[i] != NULL; i++) {
         /* Load .volinfo file for source */
-        openvol(argv[i], &volume);
+        openvol(obj, argv[i], &volume);
 
         if (nftw(argv[i], rm, upfunc, 20, FTW_DEPTH | FTW_PHYS) == -1) {
             if (alarmed) {
@@ -201,8 +200,8 @@ static int rm(const char *path,
     switch (statp->st_mode & S_IFMT) {
 
     case S_IFLNK:
-        if (volume.volinfo.v_path) {
-            if ((volume.volinfo.v_adouble == AD_VERSION2)
+        if (volume.vol->v_path) {
+            if ((volume.vol->v_adouble == AD_VERSION2)
                 && (strstr(path, ".AppleDouble") != NULL)) {
                 /* symlink inside adouble dir */
                 if (unlink(path) != 0)
@@ -216,7 +215,7 @@ static int rm(const char *path,
                 SLOG("Error resolving CNID for %s", path);
                 return -1;
             }
-            if (cnid_delete(volume.volume.v_cdb, cnid) != 0) {
+            if (cnid_delete(volume.vol->v_cdb, cnid) != 0) {
                 SLOG("Error removing CNID %u for %s", ntohl(cnid), path);
                 return -1;
             }
@@ -235,8 +234,8 @@ static int rm(const char *path,
             return FTW_SKIP_SUBTREE;
         }
 
-        if (volume.volinfo.v_path) {
-            if ((volume.volinfo.v_adouble == AD_VERSION2)
+        if (volume.vol->v_path) {
+            if ((volume.vol->v_adouble == AD_VERSION2)
                 && (strstr(path, ".AppleDouble") != NULL)) {
                 /* should be adouble dir itself */
                 if (rmdir(path) != 0) {
@@ -252,7 +251,7 @@ static int rm(const char *path,
                 SLOG("Error resolving CNID for %s", path);
                 return -1;
             }
-            if (cnid_delete(volume.volume.v_cdb, did) != 0) {
+            if (cnid_delete(volume.vol->v_cdb, did) != 0) {
                 SLOG("Error removing CNID %u for %s", ntohl(did), path);
                 return -1;
             }
@@ -283,8 +282,8 @@ static int rm(const char *path,
         break;
 
     default:
-        if (volume.volinfo.v_path) {
-            if ((volume.volinfo.v_adouble == AD_VERSION2)
+        if (volume.vol->v_path) {
+            if ((volume.vol->v_adouble == AD_VERSION2)
                 && (strstr(path, ".AppleDouble") != NULL)) {
                 /* file in adouble dir */
                 if (unlink(path) != 0)
@@ -298,13 +297,13 @@ static int rm(const char *path,
                 SLOG("Error resolving CNID for %s", path);
                 return -1;
             }
-            if (cnid_delete(volume.volume.v_cdb, cnid) != 0) {
+            if (cnid_delete(volume.vol->v_cdb, cnid) != 0) {
                 SLOG("Error removing CNID %u for %s", ntohl(cnid), path);
                 return -1;
             }
 
             /* Ignore errors, because with -R adouble stuff is always alread gone */
-            volume.volume.vfs->vfs_deletefile(&volume.volume, -1, path);
+            volume.vol->vfs->vfs_deletefile(volume.vol, -1, path);
         }
 
         if (unlink(path) != 0) {
diff --git a/bin/ad/ad_set.c b/bin/ad/ad_set.c
new file mode 100644 (file)
index 0000000..d41d522
--- /dev/null
@@ -0,0 +1,331 @@
+/* 
+   Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
+   
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <unistd.h>
+#include <sys/types.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <limits.h>
+#include <string.h>
+#include <errno.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <ctype.h>
+#include <pwd.h>
+#include <grp.h>
+#include <time.h>
+
+#include <atalk/adouble.h>
+#include <atalk/cnid.h>
+#include "ad.h"
+
+#define ADv2_DIRNAME ".AppleDouble"
+
+#define DIR_DOT_OR_DOTDOT(a)                            \
+    ((strcmp(a, ".") == 0) || (strcmp(a, "..") == 0))
+
+static const char *labels[] = {
+    "none",
+    "grey",
+    "green",
+    "violet",
+    "blue",
+    "yellow",
+    "red",
+    "orange",
+    NULL
+};
+
+static char *new_label;
+static char *new_type;
+static char *new_creator;
+static char *new_flags;
+static char *new_attributes;
+
+static void usage_set(void)
+{
+    printf(
+        "Usage: ad set [-t TYPE] [-c CREATOR] [-l label] [-f flags] [-a attributes] file|dir \n\n"
+        "     Color Label:\n"
+        "       none | grey | green | violet | blue | yellow | red | orange\n\n"
+        "     FinderFlags:\n"
+        "       d = On Desktop (f/d)\n"
+        "       e = Hidden extension (f/d)\n"
+        "       m = Shared (can run multiple times) (f)\n"
+        "       n = No INIT resources (f)\n"
+        "       i = Inited (f/d)\n"
+        "       c = Custom icon (f/d)\n"
+        "       t = Stationery (f)\n"
+        "       s = Name locked (f/d)\n"
+        "       b = Bundle (f/d)\n"
+        "       v = Invisible (f/d)\n"
+        "       a = Alias file (f/d)\n\n"
+        "     AFPAttributes:\n"
+        "       y = System (f/d)\n"
+        "       w = No write (f)\n"
+        "       p = Needs backup (f/d)\n"
+        "       r = No rename (f/d)\n"
+        "       l = No delete (f/d)\n"
+        "       o = No copy (f)\n\n"
+        "     Uppercase letter sets the flag, lowercase removes the flag\n"
+        "     f = valid for files\n"
+        "     d = valid for directories\n"
+
+        );
+}
+
+static void change_type(char *path, afpvol_t *vol, const struct stat *st, struct adouble *ad, char *new_type)
+{
+    char *FinderInfo;
+
+    if ((FinderInfo = ad_entry(ad, ADEID_FINDERI)))
+        memcpy(FinderInfo, new_type, 4);
+}
+
+static void change_creator(char *path, afpvol_t *vol, const struct stat *st, struct adouble *ad, char *new_creator)
+{
+    char *FinderInfo;
+
+    if ((FinderInfo = ad_entry(ad, ADEID_FINDERI)))
+        memcpy(FinderInfo + 4, new_creator, 4);
+
+}
+
+static void change_label(char *path, afpvol_t *vol, const struct stat *st, struct adouble *ad, char *new_label)
+{
+    char *FinderInfo;
+    const char **color = &labels[0];
+    uint16_t FinderFlags;
+    unsigned char color_count = 0;
+
+    if ((FinderInfo = ad_entry(ad, ADEID_FINDERI)) == NULL)
+        return;
+
+    while (*color) {
+        if (strcasecmp(*color, new_label) == 0) {
+            /* get flags */
+            memcpy(&FinderFlags, FinderInfo + 8, 2);
+            FinderFlags = ntohs(FinderFlags);
+
+            /* change value */
+            FinderFlags &= ~FINDERINFO_COLOR;
+            FinderFlags |= color_count << 1;
+
+            /* copy it back */
+            FinderFlags = ntohs(FinderFlags);
+            memcpy(FinderInfo + 8, &FinderFlags, 2);
+
+            break;
+        }
+        color++;
+        color_count++;
+    }
+}
+
+static void change_attributes(char *path, afpvol_t *vol, const struct stat *st, struct adouble *ad, char *new_attributes)
+{
+    char *FinderInfo;
+    uint16_t AFPattributes;
+
+    ad_getattr(ad, &AFPattributes);
+    AFPattributes = ntohs(AFPattributes);
+
+    if (S_ISREG(st->st_mode)) {
+        if (strchr(new_attributes, 'W'))
+            AFPattributes |= ATTRBIT_NOWRITE;
+        if (strchr(new_attributes, 'w'))
+            AFPattributes &= ~ATTRBIT_NOWRITE;
+
+        if (strchr(new_attributes, 'O'))
+            AFPattributes |= ATTRBIT_NOCOPY;
+        if (strchr(new_attributes, 'o'))
+            AFPattributes &= ~ATTRBIT_NOCOPY;
+    }
+
+    if (strchr(new_attributes, 'Y'))
+        AFPattributes |= ATTRBIT_SYSTEM;
+    if (strchr(new_attributes, 'y'))
+        AFPattributes &= ~ATTRBIT_SYSTEM;
+
+    if (strchr(new_attributes, 'P'))
+        AFPattributes |= ATTRBIT_BACKUP;
+    if (strchr(new_attributes, 'p'))
+        AFPattributes &= ~ATTRBIT_BACKUP;
+
+    if (strchr(new_attributes, 'R'))
+        AFPattributes |= ATTRBIT_NORENAME;
+    if (strchr(new_attributes, 'r'))
+        AFPattributes &= ~ATTRBIT_NORENAME;
+
+    if (strchr(new_attributes, 'L'))
+        AFPattributes |= ATTRBIT_NODELETE;
+    if (strchr(new_attributes, 'l'))
+        AFPattributes &= ~ATTRBIT_NODELETE;
+
+    AFPattributes = ntohs(AFPattributes);
+    ad_setattr(ad, AFPattributes);
+}
+
+static void change_flags(char *path, afpvol_t *vol, const struct stat *st, struct adouble *ad, char *new_flags)
+{
+    char *FinderInfo;
+    uint16_t FinderFlags;
+
+    if ((FinderInfo = ad_entry(ad, ADEID_FINDERI)) == NULL)
+        return;
+
+    memcpy(&FinderFlags, FinderInfo + 8, 2);
+    FinderFlags = ntohs(FinderFlags);
+
+    if (S_ISREG(st->st_mode)) {
+        if (strchr(new_flags, 'M'))
+            FinderFlags |= FINDERINFO_ISHARED;
+        if (strchr(new_flags, 'm'))
+            FinderFlags &= ~FINDERINFO_ISHARED;
+
+        if (strchr(new_flags, 'N'))
+            FinderFlags |= FINDERINFO_HASNOINITS;
+        if (strchr(new_flags, 'n'))
+            FinderFlags &= ~FINDERINFO_HASNOINITS;
+
+        if (strchr(new_flags, 'T'))
+            FinderFlags |= FINDERINFO_ISSTATIONNERY;
+        if (strchr(new_flags, 't'))
+            FinderFlags &= ~FINDERINFO_ISSTATIONNERY;
+    }
+
+    if (strchr(new_flags, 'D'))
+        FinderFlags |= FINDERINFO_ISONDESK;
+    if (strchr(new_flags, 'd'))
+        FinderFlags &= ~FINDERINFO_ISONDESK;
+
+    if (strchr(new_flags, 'E'))
+        FinderFlags |= FINDERINFO_HIDEEXT;
+    if (strchr(new_flags, 'e'))
+        FinderFlags &= ~FINDERINFO_HIDEEXT;
+
+    if (strchr(new_flags, 'I'))
+        FinderFlags |= FINDERINFO_HASBEENINITED;
+    if (strchr(new_flags, 'i'))
+        FinderFlags &= ~FINDERINFO_HASBEENINITED;
+
+    if (strchr(new_flags, 'C'))
+        FinderFlags |= FINDERINFO_HASCUSTOMICON;
+    if (strchr(new_flags, 'c'))
+        FinderFlags &= ~FINDERINFO_HASCUSTOMICON;
+
+    if (strchr(new_flags, 'S'))
+        FinderFlags |= FINDERINFO_NAMELOCKED;
+    if (strchr(new_flags, 's'))
+        FinderFlags &= ~FINDERINFO_NAMELOCKED;
+
+    if (strchr(new_flags, 'B'))
+        FinderFlags |= FINDERINFO_HASBUNDLE;
+    if (strchr(new_flags, 'b'))
+        FinderFlags &= ~FINDERINFO_HASBUNDLE;
+
+    if (strchr(new_flags, 'V'))
+        FinderFlags |= FINDERINFO_INVISIBLE;
+    if (strchr(new_flags, 'v'))
+        FinderFlags &= ~FINDERINFO_INVISIBLE;
+
+    if (strchr(new_flags, 'A'))
+        FinderFlags |= FINDERINFO_ISALIAS;
+    if (strchr(new_flags, 'a'))
+        FinderFlags &= ~FINDERINFO_ISALIAS;
+
+    FinderFlags = ntohs(FinderFlags);
+    memcpy(FinderInfo + 8, &FinderFlags, 2);
+}
+
+int ad_set(int argc, char **argv, AFPObj *obj)
+{
+    int c, firstarg;
+    afpvol_t vol;
+    struct stat st;
+    int adflags = 0;
+    struct adouble ad;
+
+    while ((c = getopt(argc, argv, ":l:t:c:f:a:")) != -1) {
+        switch(c) {
+        case 'l':
+            new_label = strdup(optarg);
+            break;
+        case 't':
+            new_type = strdup(optarg);
+            break;
+        case 'c':
+            new_creator = strdup(optarg);
+            break;
+        case 'f':
+            new_flags = strdup(optarg);
+            break;
+        case 'a':
+            new_attributes = strdup(optarg);
+            break;
+        case ':':
+        case '?':
+            usage_set();
+            return -1;
+            break;
+        }
+
+    }
+
+    if (argc <= optind)
+        exit(1);
+
+    cnid_init();
+
+    openvol(obj, argv[optind], &vol);
+    if (vol.vol->v_path == NULL)
+        exit(1);
+
+    if (stat(argv[optind], &st) != 0) {
+        perror("stat");
+        exit(1);
+    }
+
+    if (S_ISDIR(st.st_mode))
+        adflags = ADFLAGS_DIR;
+
+    ad_init(&ad, vol.vol);
+
+    if (ad_open(&ad, argv[optind], adflags | ADFLAGS_HF | ADFLAGS_CREATE | ADFLAGS_RDWR, 0666) < 0)
+        goto exit;
+
+    if (new_label)
+        change_label(argv[optind], &vol, &st, &ad, new_label);
+    if (new_type)
+        change_type(argv[optind], &vol, &st, &ad, new_type);
+    if (new_creator)
+        change_creator(argv[optind], &vol, &st, &ad, new_creator);
+    if (new_flags)
+        change_flags(argv[optind], &vol, &st, &ad, new_flags);
+    if (new_attributes)
+        change_attributes(argv[optind], &vol, &st, &ad, new_attributes);
+
+    ad_flush(&ad);
+    ad_close(&ad, ADFLAGS_HF);
+
+exit:
+    closevol(&vol);
+
+    return 0;
+}
index 4a8ff11b62ecee83730290246975aa2ee597fa8c..897bdf3b1415c609efdae24f2104d019ef3464fc 100644 (file)
 
 #include <atalk/util.h>
 #include <atalk/cnid.h>
-#include <atalk/volinfo.h>
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
 #include <atalk/logger.h>
 #include <atalk/errchk.h>
 #include <atalk/unicode.h>
+#include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
+
 
 #include "ad.h"
 
@@ -96,46 +98,38 @@ void _log(enum logtype lt, char *fmt, ...)
  *
  * @returns 0 on success, exits on error
  */
-int openvol(const char *path, afpvol_t *vol)
+int openvol(AFPObj *obj, const char *path, afpvol_t *vol)
 {
     int flags = 0;
 
     memset(vol, 0, sizeof(afpvol_t));
 
-    /* try to find a .AppleDesktop/.volinfo */
-    if (loadvolinfo((char *)path, &vol->volinfo) != 0)
+    if ((vol->vol = getvolbypath(obj, path)) == NULL)
         return -1;
 
-    if (STRCMP(vol->volinfo.v_cnidscheme, != , "dbd"))
-        ERROR("\"%s\" isn't a \"dbd\" CNID volume!", vol->volinfo.v_path);
-
-    if (vol_load_charsets(&vol->volinfo) == -1)
-        ERROR("Error loading charsets!");
+    if (STRCMP(vol->vol->v_cnidscheme, != , "dbd"))
+        ERROR("\"%s\" isn't a \"dbd\" CNID volume!", vol->vol->v_path);
 
     /* Sanity checks to ensure we can touch this volume */
-    if (vol->volinfo.v_adouble != AD_VERSION2)
-        ERROR("Unsupported adouble versions: %u", vol->volinfo.v_adouble);
+    if (vol->vol->v_adouble != AD_VERSION2
+        && vol->vol->v_adouble != AD_VERSION_EA)
+        ERROR("Unsupported adouble versions: %u", vol->vol->v_adouble);
 
-    if (vol->volinfo.v_vfs_ea != AFPVOL_EA_SYS)
-        ERROR("Unsupported Extended Attributes option: %u", vol->volinfo.v_vfs_ea);
+    if (vol->vol->v_vfs_ea != AFPVOL_EA_SYS)
+        ERROR("Unsupported Extended Attributes option: %u", vol->vol->v_vfs_ea);
 
-    /* initialize sufficient struct vol for VFS initialisation */
-    vol->volume.v_adouble = AD_VERSION2;
-    vol->volume.v_vfs_ea = AFPVOL_EA_SYS;
-    initvol_vfs(&vol->volume);
-
-    if ((vol->volinfo.v_flags & AFPVOL_NODEV))
+    if ((vol->vol->v_flags & AFPVOL_NODEV))
         flags |= CNID_FLAG_NODEV;
 
-    if ((vol->volume.v_cdb = cnid_open(vol->volinfo.v_path,
-                                       0000,
-                                       "dbd",
-                                       flags,
-                                       vol->volinfo.v_dbd_host,
-                                       vol->volinfo.v_dbd_port)) == NULL)
-        ERROR("Cant initialize CNID database connection for %s", vol->volinfo.v_path);
+    if ((vol->vol->v_cdb = cnid_open(vol->vol->v_path,
+                                     0000,
+                                     "dbd",
+                                     flags,
+                                     vol->vol->v_cnidserver,
+                                     vol->vol->v_cnidport)) == NULL)
+        ERROR("Cant initialize CNID database connection for %s", vol->vol->v_path);
 
-    cnid_getstamp(vol->volume.v_cdb,
+    cnid_getstamp(vol->vol->v_cdb,
                   vol->db_stamp,
                   sizeof(vol->db_stamp));
     
@@ -144,16 +138,17 @@ int openvol(const char *path, afpvol_t *vol)
 
 void closevol(afpvol_t *vol)
 {
-    if (vol->volume.v_cdb)
-        cnid_close(vol->volume.v_cdb);
-
+    if (vol->vol->v_cdb) {
+        cnid_close(vol->vol->v_cdb);
+        vol->vol->v_cdb = NULL;
+    }
     memset(vol, 0, sizeof(afpvol_t));
 }
 
 /*
   Taken form afpd/desktop.c
 */
-char *utompath(const struct volinfo *volinfo, const char *upath)
+char *utompath(const struct vol *vol, const char *upath)
 {
     static char  mpath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
     char         *m;
@@ -168,22 +163,22 @@ char *utompath(const struct volinfo *volinfo, const char *upath)
     u = upath;
     outlen = strlen(upath);
 
-    if ((volinfo->v_casefold & AFPVOL_UTOMUPPER))
+    if ((vol->v_casefold & AFPVOL_UTOMUPPER))
         flags |= CONV_TOUPPER;
-    else if ((volinfo->v_casefold & AFPVOL_UTOMLOWER))
+    else if ((vol->v_casefold & AFPVOL_UTOMLOWER))
         flags |= CONV_TOLOWER;
 
-    if ((volinfo->v_flags & AFPVOL_EILSEQ)) {
+    if ((vol->v_flags & AFPVOL_EILSEQ)) {
         flags |= CONV__EILSEQ;
     }
 
     /* convert charsets */
-    if ((size_t)-1 == ( outlen = convert_charset(volinfo->v_volcharset,
+    if ((size_t)-1 == ( outlen = convert_charset(vol->v_volcharset,
                                                  CH_UTF8_MAC,
-                                                 volinfo->v_maccharset,
+                                                 vol->v_maccharset,
                                                  u, outlen, mpath, MAXPATHLEN, &flags)) ) {
         SLOG("Conversion from %s to %s for %s failed.",
-             volinfo->v_volcodepage, volinfo->v_maccodepage, u);
+             vol->v_volcodepage, vol->v_maccodepage, u);
         return NULL;
     }
 
@@ -213,26 +208,18 @@ int convert_dots_encoding(const afpvol_t *svol, const afpvol_t *dvol, char *path
     int pos = bname - path;
     uint16_t flags = 0;
 
-    if ( ! svol->volinfo.v_path) {
+    if ( ! svol->vol->v_path) {
         /* no source volume: escape special chars (eg ':') */
-        from = dvol->volinfo.v_volcharset; /* src = dst charset */
-        flags |= CONV_ESCAPEHEX;
+        from = dvol->vol->v_volcharset; /* src = dst charset */
+        if (dvol->vol->v_adouble == AD_VERSION2)
+            flags |= CONV_ESCAPEHEX;
     } else {
-        from = svol->volinfo.v_volcharset;
-    }
-
-    if ( (svol->volinfo.v_path)
-         && ! (svol->volinfo.v_flags & AFPVOL_USEDOTS)
-         && (dvol->volinfo.v_flags & AFPVOL_USEDOTS)) {
-        /* source is without dots, destination is with */
-        flags |= CONV_UNESCAPEHEX;
-    } else if (! (dvol->volinfo.v_flags & AFPVOL_USEDOTS)) {
-        flags |= CONV_ESCAPEDOTS;
+        from = svol->vol->v_volcharset;
     }
 
     int len = convert_charset(from,
-                              dvol->volinfo.v_volcharset,
-                              dvol->volinfo.v_maccharset,
+                              dvol->vol->v_volcharset,
+                              dvol->vol->v_maccharset,
                               bname, strlen(bname),
                               buf, MAXPATHLEN,
                               &flags);
@@ -276,8 +263,8 @@ cnid_t cnid_for_path(const afpvol_t *vol,
 
     cnid = htonl(2);
 
-    EC_NULL(rpath = rel_path_in_vol(path, vol->volinfo.v_path));
-    EC_NULL(statpath = bfromcstr(vol->volinfo.v_path));
+    EC_NULL(rpath = rel_path_in_vol(path, vol->vol->v_path));
+    EC_NULL(statpath = bfromcstr(vol->vol->v_path));
     EC_ZERO(bcatcstr(statpath, "/"));
 
     l = bsplit(rpath, '/');
@@ -290,7 +277,7 @@ cnid_t cnid_for_path(const afpvol_t *vol,
                        cfrombstr(rpath), cfrombstr(l->entry[i]),
                        cfrombstr(statpath), strerror(errno));
 
-        if ((cnid = cnid_add(vol->volume.v_cdb,
+        if ((cnid = cnid_add(vol->vol->v_cdb,
                              &st,
                              *did,
                              cfrombstr(l->entry[i]),
@@ -344,8 +331,8 @@ cnid_t cnid_for_paths_parent(const afpvol_t *vol,
     *did = htonl(1);
     cnid = htonl(2);
 
-    EC_NULL(rpath = rel_path_in_vol(path, vol->volinfo.v_path));
-    EC_NULL(statpath = bfromcstr(vol->volinfo.v_path));
+    EC_NULL(rpath = rel_path_in_vol(path, vol->vol->v_path));
+    EC_NULL(statpath = bfromcstr(vol->vol->v_path));
 
     l = bsplit(rpath, '/');
     if (l->qty == 1)
@@ -359,7 +346,7 @@ cnid_t cnid_for_paths_parent(const afpvol_t *vol,
                        cfrombstr(rpath), cfrombstr(l->entry[i]),
                        cfrombstr(statpath), strerror(errno));
 
-        if ((cnid = cnid_add(vol->volume.v_cdb,
+        if ((cnid = cnid_add(vol->vol->v_cdb,
                              &st,
                              *did,
                              cfrombstr(l->entry[i]),
diff --git a/bin/adv1tov2/.gitignore b/bin/adv1tov2/.gitignore
deleted file mode 100644 (file)
index 4fada59..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Makefile
-Makefile.in
-adv1tov2
-.deps
-.libs
-.gitignore
-adv1tov2.o
diff --git a/bin/adv1tov2/Makefile.am b/bin/adv1tov2/Makefile.am
deleted file mode 100644 (file)
index 1bfc6ca..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-# Makefile.am for bin/adv1tov2/
-
-INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/sys
-
-bin_PROGRAMS = adv1tov2
-
-adv1tov2_SOURCES = adv1tov2.c
-adv1tov2_LDADD = $(top_builddir)/libatalk/libatalk.la
diff --git a/bin/adv1tov2/adv1tov2.c b/bin/adv1tov2/adv1tov2.c
deleted file mode 100644 (file)
index eade898..0000000
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * $Id: adv1tov2.c,v 1.5 2009-10-14 01:38:28 didg Exp $
- * v1tov2: given a root directory, run down and convert all the
- * files/directories into appledouble v2.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <atalk/adouble.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <dirent.h>
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <ctype.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/param.h>
-#include <errno.h>
-#include <string.h>
-
-#include <atalk/util.h>
-
-#if AD_VERSION == AD_VERSION2
-#if 0
-/* translate characters */
-static void xlate(char *name, int flags) {
-  static const char hexdig[] = "0123456789abcdef";
-  char upath[MAXPATHLEN + 1];
-  char *m, *u;
-  int doit = 0;
-
-  m = name;
-  u = upath;
-  while (*m != '\0') {
-    if (isascii(*m) && !isprint(*m)) {
-      doit = 1;
-      *u++ = ':';
-      *u++ = hexdig[(*m & 0xf0) >> 4];
-      *u++ = hexdig[*m & 0x0f];
-    } else
-      *u++ = *m;
-    m++;
-  }
-  
-  if (doit) {
-    *u = '\0';
-    rename(name, upath);
-    if ((flags & ADFLAGS_DIR) == 0)
-      rename(ad_path(name, flags), ad_path(upath, flags)); /* rename rfork */
-  }
-}
-#endif
-
-#define MAXDESCEND 0xFFFF
-/* recursively descend subdirectories. 
- * oh the stack space we use up! */
-static void descend(DIR *dp)
-{
-  DIR *dpnew;
-  struct dirent *de;
-  struct stat st;
-  struct adouble ad;
-  int flags;
-  static int count = 0;
-
-  ad_init(&ad, AD_VERSION2, 0);
-  if (count++ > MAXDESCEND) {
-    fprintf(stderr, "FAILURE: too many subdirectories! possible infinite recursion.");
-    return;
-  }
-    
-  putc('(', stderr);
-  for (de = readdir(dp); de; de = readdir(dp)) {
-    if (de->d_name[0] == '.') 
-      continue;
-
-    if (stat(de->d_name, &st) < 0) {
-      fprintf(stderr, "FAILURE: can't stat %s\n", de->d_name);
-      continue;
-    }
-
-    /* go down subdirectory */
-    flags = ADFLAGS_HF;
-    if (S_ISDIR(st.st_mode) && (dpnew = opendir(de->d_name))) {
-      chdir(de->d_name);
-      descend(dpnew);
-      closedir(dpnew);
-      chdir("..");
-      flags |= ADFLAGS_DIR;
-    }
-
-    if (ad_open(de->d_name, flags, O_RDWR, 0, &ad) < 0) {
-      if (errno != ENOENT)
-          fprintf(stderr, "\nFAILURE: can't convert %s, %s\n", fullpathname(de->d_name), strerror(errno));
-      continue;
-    }
-    ad_close(&ad, ADFLAGS_HF);
-    fputc('.', stderr);
-  }
-  putc(')', stderr);
-}
-
-
-int main(int argc, char **argv)
-{
-  DIR           *dp;
-  struct adouble ad;
-  ad_init(&ad, AD_VERSION2, 0);
-  if (argc != 2) {
-    fprintf(stderr, "%s <directory>\n", *argv);
-    return -1;
-  }
-    
-  /* convert main directory */
-  if (ad_open(argv[1], ADFLAGS_HF | ADFLAGS_DIR, O_RDWR, 0, 
-             &ad) < 0) {
-    fprintf(stderr, "FAILURE: can't convert %s\n", argv[1]);
-    return -1;
-  }
-
-  ad_close(&ad, ADFLAGS_HF);
-  if ((dp = opendir(argv[1])) == NULL) {
-    fprintf(stderr, "%s: unable to open %s\n", *argv, argv[1]);
-    return -1;
-  }
-
-  chdir(argv[1]);
-  descend(dp);
-  closedir(dp);
-  chdir("..");
-
-  putc('\n', stderr);
-  return 0;
-}
-
-#else /* AD_VERSION == AD_VERSION2 */
-int main(int argc, char **argv)
-{
-  fprintf(stderr, "%s not built for v2 AppleDouble files.\n", *argv);
-  return -1;
-}
-#endif /* AD_VERSION == AD_VERSION2 */
diff --git a/bin/aecho/.gitignore b/bin/aecho/.gitignore
deleted file mode 100644 (file)
index 76402fb..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Makefile
-Makefile.in
-aecho
-.deps
-.libs
-.gitignore
-aecho.o
diff --git a/bin/aecho/Makefile.am b/bin/aecho/Makefile.am
deleted file mode 100644 (file)
index d3e487e..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-# Makefile.am for bin/aecho/
-
-INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/sys
-
-bin_PROGRAMS = aecho
-
-aecho_SOURCES = aecho.c
-aecho_LDADD = $(top_builddir)/libatalk/libatalk.la
diff --git a/bin/aecho/aecho.c b/bin/aecho/aecho.c
deleted file mode 100644 (file)
index 274421b..0000000
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * $Id: aecho.c,v 1.9 2009-10-14 01:38:28 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-/*
- * AppleTalk Echo Protocol Client
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <errno.h>
-
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif /* HAVE_NETDB_H */
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/compat.h>
-#include <atalk/aep.h>
-#include <atalk/nbp.h>
-#include <atalk/netddp.h>
-#include <atalk/ddp.h>
-#include <atalk/util.h>
-
-/* FIXME/SOCKLEN_T: socklen_t is a unix98 feature */
-#ifndef SOCKLEN_T
-#define SOCKLEN_T unsigned int
-#endif /* ! SOCKLEN_T */
-
-static struct sockaddr_at      target;
-static int                     sock;
-static unsigned int            nsent = 0, nrecv = 0;
-static time_t                  totalms = 0, minms = -1, maxms = -1;
-static unsigned int            pings = 0;
-
-static void usage(char *);
-
-static void done(int sig _U_)
-{
-    if ( nsent) {
-       printf( "\n----%d.%d AEP Statistics----\n",
-               ntohs( target.sat_addr.s_net ), target.sat_addr.s_node );
-       printf( "%d packets sent, %d packets received, %d%% packet loss\n",
-               nsent, nrecv, (( nsent - nrecv ) * 100 ) / nsent );
-       if ( nrecv ) {
-           printf( "round-trip (ms)  min/avg/max = %ld/%ld/%ld\n",
-                   minms, totalms / nrecv, maxms );
-       }       
-    }
-    exit( 0 );
-}
-  
-static void aep_send(int sig _U_)
-{
-    struct timeval     tv;
-    char               *p, buf[ 1024 ];
-    static unsigned int        seq = 0;
-
-    p = buf;
-    *p++ = DDPTYPE_AEP;
-    *p++ = AEPOP_REQUEST;
-    memcpy( p, &seq, sizeof( unsigned int ));
-    p += sizeof( unsigned int );
-    seq++;
-
-    if ( gettimeofday( &tv, (struct timezone *)0 ) < 0 ) {
-       perror( "gettimeofday" );
-       exit( 1 );
-    }
-    memcpy( p, &tv, sizeof( struct timeval ));
-    p += sizeof( struct timeval );
-
-    if ( netddp_sendto( sock, buf, p - buf, 0, (struct sockaddr *) &target,
-           sizeof( struct sockaddr_at )) < 0 ) {
-       perror( "sendto" );
-       exit( 1 );
-    }
-    nsent++;
-    if (pings && nsent > pings) done(0);
-}
-
-int main(int ac, char **av)
-{
-    struct servent     *se;
-    struct sigaction   sv;
-    struct itimerval   it;
-    struct sockaddr_at sat, saddr;
-    struct timeval     tv, atv;
-    struct nbpnve      nn;
-    char               *obj = NULL, *type = "Workstation", *zone = "*";
-    int                        cc;
-    SOCKLEN_T          satlen;
-    unsigned int       seq;
-    time_t             ms;
-    char               buf[ 1024 ], *p;
-    unsigned char      port;
-
-    extern char                *optarg;
-    extern int         optind;
-  
-    memset(&saddr, 0, sizeof(saddr));
-    while (( cc = getopt( ac, av, "c:A:" )) != EOF ) {
-       switch ( cc ) {
-       case 'A':
-           if (!atalk_aton(optarg, &saddr.sat_addr)) {
-               fprintf(stderr, "Bad address.\n");
-               exit(1);
-           }
-           break;
-
-         case 'c' :
-           pings = atoi( optarg );
-           break;
-
-       default :
-           usage( av[ 0 ] );
-           exit( 1 );
-       }
-    }
-    if ( ac - optind != 1 ) {
-       usage( av[ 0 ] );
-       exit( 1 );
-    }
-    
-    /*
-     * Save the port, since nbp_lookup calls getservbyname() to get the
-     * nbp port.
-     */
-    if (( se = getservbyname( "echo", "ddp" )) == NULL ) 
-       port = 4;
-    else
-       port = ntohs( se->s_port );
-
-    memset( &target, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    target.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    target.sat_family = AF_APPLETALK;
-    if ( !atalk_aton( av[ optind ], &target.sat_addr )) {
-       if ( nbp_name( av[ optind ], &obj, &type, &zone ) || !obj ) {
-           fprintf( stderr, "Bad name: %s\n", av[ optind ] );
-           exit( 1 );
-       }
-       if ( nbp_lookup( obj, type, zone, &nn, 1, &saddr.sat_addr) <= 0 ) {
-           fprintf( stderr, "Can't find: %s\n", av[ optind ] );
-           exit( 1 );
-       }
-       memcpy( &target, &nn.nn_sat, sizeof( struct sockaddr_at ));
-    }
-    target.sat_port = port;
-
-    if ((sock = netddp_open(saddr.sat_addr.s_net || saddr.sat_addr.s_node ? 
-                        &saddr : NULL, NULL)) < 0) {
-       perror("ddp_open");
-       exit(1);
-    }        
-
-    sv.sa_handler = aep_send;
-    sigemptyset( &sv.sa_mask );
-    sigaddset( &sv.sa_mask, SIGINT );
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGALRM, &sv, (struct sigaction *)0 ) < 0 ) {
-       perror( "sigaction" );
-       exit( 1 );
-    }
-
-    sv.sa_handler = done;
-    sigemptyset( &sv.sa_mask );
-    sigaddset( &sv.sa_mask, SIGALRM );
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGINT, &sv, (struct sigaction *)0 ) < 0 ) {
-       perror( "sigaction" );
-       exit( 1 );
-    }
-
-    it.it_interval.tv_sec = 1L;
-    it.it_interval.tv_usec = 0L;
-    it.it_value.tv_sec = 1L;
-    it.it_value.tv_usec = 0L;
-
-    if ( setitimer( ITIMER_REAL, &it, (struct itimerval *)0 ) < 0 ) {
-       perror( "setitimer" );
-       exit( 1 );
-    }
-
-    for (;;) {
-       satlen = sizeof( struct sockaddr_at );
-       if (( cc = netddp_recvfrom( sock, buf, sizeof( buf ), 0, 
-                                   (struct sockaddr *) &sat,
-                                   &satlen )) < 0 ) {
-           if ( errno == EINTR ) {
-               errno = 0;
-               continue;
-           } else {
-               perror( "recvfrom" );
-               exit( 1 );
-           }
-       }
-       p = buf;
-       if ( *p++ != DDPTYPE_AEP || *p++ != AEPOP_REPLY ) {
-           fprintf( stderr, "%s: bad packet!\n", av[ 0 ] );
-           continue;
-       }
-       if ( gettimeofday( &tv, (struct timezone *)0 ) < 0 ) {
-           perror( "gettimeofday" );
-           exit( 1 );
-       }
-       memcpy( &seq, p, sizeof( unsigned int ));
-       p += sizeof( unsigned int );
-       memcpy( &atv, p, sizeof( struct timeval ));
-       nrecv++;
-       ms = ( tv.tv_sec - atv.tv_sec ) * 1000 +
-               ( tv.tv_usec - atv.tv_usec ) / 1000;
-       totalms += ms;
-       if ( ms > maxms ) {
-           maxms = ms;
-       }
-       if ( ms < minms || minms == -1 ) {
-           minms = ms;
-       }
-       printf( "%d bytes from %u.%u: aep_seq=%d. time=%ld. ms\n",
-               cc, ntohs( sat.sat_addr.s_net ), sat.sat_addr.s_node,
-               seq, ms );
-        if (pings && seq + 1 >= pings) done(0);
-    }
-}
-
-static void usage( char * av0 )
-{
-    fprintf( stderr, "usage:\t%s [-A source address ] [-c count] ( addr | nbpname )\n", av0 );
-    exit( 1 );
-}
index 7a003560b2c9a677128a369008a02ef582e8d53d..f5778a53d03ba6b398ece79cb0d163ba44a7eb8e 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <ctype.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <sys/param.h>
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <pwd.h>
-
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 
 #include <des.h>
 
@@ -69,7 +64,7 @@ static char buf[MAXPATHLEN + 1];
 #define unhex(x)  (isdigit(x) ? (x) - '0' : toupper(x) + 10 - 'A')
 static void convert_passwd(char *buf, char *newpwd, const int keyfd)
 {
-  u_int8_t key[HEXPASSWDLEN];
+  uint8_t key[HEXPASSWDLEN];
   Key_schedule schedule;
   unsigned int i, j;
 
diff --git a/bin/getzones/.gitignore b/bin/getzones/.gitignore
deleted file mode 100644 (file)
index 2cbaa2c..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Makefile
-Makefile.in
-getzones
-.deps
-.libs
-.gitignore
-getzones.o
diff --git a/bin/getzones/Makefile.am b/bin/getzones/Makefile.am
deleted file mode 100644 (file)
index e99d41f..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-# Makefile.am for bin/getzones/
-
-INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/sys
-
-bin_PROGRAMS = getzones
-
-getzones_SOURCES = getzones.c
-getzones_LDADD = $(top_builddir)/libatalk/libatalk.la
diff --git a/bin/getzones/getzones.c b/bin/getzones/getzones.c
deleted file mode 100644 (file)
index b175710..0000000
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * $Id: getzones.c,v 1.9 2009-10-14 01:38:28 didg Exp $
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/param.h>
-#include <sys/uio.h>
-#include <sys/time.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif /* HAVE_NETDB_H */
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/util.h>
-#include <atalk/unicode.h>
-#include <atalk/zip.h>
-
-static void print_zones(short n, char *buf);
-
-static void usage( char *s)
-{
-    fprintf( stderr, "usage:\t%s [-m | -l] [address]\n", s );
-    exit( 1 );
-}
-
-int main( int argc, char *argv[])
-{
-    struct atp_handle  *ah;
-    struct atp_block   atpb;
-    struct sockaddr_at saddr;
-    struct servent     *se;
-    char               reqdata[4], buf[ ATP_MAXDATA ];
-    struct iovec       iov;
-    short              temp, index = 0;
-    int                        c, myzoneflg = 0, localzonesflg = 0, errflg = 0;
-    extern int         optind;
-
-    reqdata[ 0 ] = ZIPOP_GETZONELIST;
-
-    while (( c = getopt( argc, argv, "ml" )) != EOF ) {
-       switch (c) {
-       case 'm':
-           if ( localzonesflg ) {
-               ++errflg;
-           }
-           ++myzoneflg;
-           reqdata[ 0 ] = ZIPOP_GETMYZONE;
-           break;
-       case 'l':
-           if ( myzoneflg ) {
-               ++errflg;
-           }
-           ++localzonesflg;
-           reqdata[ 0 ] = ZIPOP_GETLOCALZONES;
-           break;
-       default:
-           ++errflg;
-       }
-    }
-
-    if ( errflg || argc - optind > 1 ) {
-       usage( argv[ 0 ] );
-    }
-
-    memset( &saddr, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    saddr.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    saddr.sat_family = AF_APPLETALK;
-    if (( se = getservbyname( "zip", "ddp" )) == NULL )
-       saddr.sat_port = 6;
-    else 
-        saddr.sat_port = ntohs( se->s_port );
-
-    if ( argc == optind ) {
-       saddr.sat_addr.s_net = ATADDR_ANYNET;
-       saddr.sat_addr.s_node = ATADDR_ANYNODE;
-    } else {
-       if ( !atalk_aton( argv[ optind ], &saddr.sat_addr )) {
-           fprintf( stderr, "Bad address.\n" );
-           exit( 1 );
-       }
-    }
-
-    if (( ah = atp_open( ATADDR_ANYPORT, &saddr.sat_addr )) == NULL ) {
-       perror( "atp_open" );
-       exit( 1 );
-    }
-
-    index = ( myzoneflg ? 0 : 1 );
-    reqdata[1] = 0;
-
-    do {
-       atpb.atp_saddr = &saddr;
-       temp = htons( index );
-       memcpy( reqdata + 2, &temp, 2 );
-       atpb.atp_sreqdata = reqdata;
-       atpb.atp_sreqdlen = 4;
-       atpb.atp_sreqto = 2;
-       atpb.atp_sreqtries = 5;
-
-       /* send getzone request zones (or get my zone)
-       */
-       if ( atp_sreq( ah, &atpb, 1, 0 ) < 0 ) {
-           perror( "atp_sreq" );
-           exit( 1 );
-       }
-
-       iov.iov_base = buf;
-       iov.iov_len = ATP_MAXDATA;
-       atpb.atp_rresiov = &iov;
-       atpb.atp_rresiovcnt = 1;
-
-       if ( atp_rresp( ah, &atpb ) < 0 ) {
-           perror( "atp_rresp" );
-           exit( 1 );
-       }
-
-       memcpy( &temp, (char *) iov.iov_base + 2, 2 );
-       temp = ntohs( temp );
-       print_zones( temp, (char *) iov.iov_base+4 );
-       index += temp;
-    } while ( !myzoneflg && !((char *)iov.iov_base)[ 0 ] );
-
-    if ( atp_close( ah ) != 0 ) {
-       perror( "atp_close" );
-       exit( 1 );
-    }
-
-    exit( 0 );
-}
-
-
-/*
- * n:   number of zones in this packet
- * buf: zone length/name pairs
- */
-static void print_zones( short n, char *buf )
-{
-    size_t zone_len;
-    char *zone;
-
-    for ( ; n--; buf += (*buf) + 1 ) {
-
-        if ((size_t)(-1) == (zone_len = convert_string_allocate( CH_MAC,
-                       CH_UNIX, buf+1, *buf, &zone)) ) {
-            zone_len = *buf;
-            if (( zone = strdup(buf+1)) == NULL ) {
-               perror( "strdup" );
-               exit( 1 );
-            }
-        }
-
-       printf( "%.*s\n", (int)zone_len, zone );
-
-       free(zone);
-    }
-}
index c93e201fd3fe696f371b86e0242ce286823d3f04..3032efa4bc2e09716bc7e8929326d71ca38b377b 100644 (file)
@@ -1,23 +1,4 @@
 # Makefile.am for bin/megatron/
 
-INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/sys
-
-bin_PROGRAMS = megatron
-
-megatron_SOURCES = asingle.c hqx.c macbin.c megatron.c nad.c updcrc.c
-megatron_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-noinst_HEADERS = asingle.h megatron.h hqx.h macbin.h nad.h updcrc.h
-
-LINKS = unbin unhex unsingle hqx2bin single2bin macbinary binheader nadheader
-
-install-exec-hook:
-       @for LINK in $(LINKS); do \
-               rm -f $(DESTDIR)$(bindir)/$$LINK; \
-               $(LN_S) megatron $(DESTDIR)$(bindir)/$$LINK; \
-       done
-
-uninstall-hook:
-       @for LINK in $(LINKS); do \
-               rm -f $(DESTDIR)$(bindir)/$$LINK; \
-       done
+# EXTRADIST = asingle.c hqx.c macbin.c megatron.c nad.c updcrc.c \
+#      asingle.h megatron.h hqx.h macbin.h nad.h updcrc.h
index 467ac5f7eb302ab576a70b8b7dafe5716eeb61f2..73e4ffaaff1022e6bc60a160ae2d550338b56d17 100644 (file)
 #include <sys/uio.h>
 #include <sys/time.h>
 #include <sys/param.h>
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <time.h>
 #include <string.h>
 #include <ctype.h>
 #include <stdio.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
+
 #include <atalk/adouble.h>
 #include <netatalk/endian.h>
 #include "asingle.h"
index 117c9dd65d08b0726ab83168cfb18c83a93aa89f..da2f71cf58f04f7c25d6a0851fd8d8659ff78605 100644 (file)
@@ -18,9 +18,7 @@
 #include <time.h>
 
 #include <unistd.h>
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 
 #include <netinet/in.h>
 
index 73ae629204b4ff0afd55b417a03e72cbe61062ef..51b7ac5f616ede35aeb604892e423e3bbf4a35e6 100644 (file)
 #include <sys/uio.h>
 #include <sys/time.h>
 #include <sys/param.h>
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <string.h>
 #include <strings.h>
 #include <ctype.h>
index c86ba637a8980119600e025e1c46041526c59b73..573a3dc88696c408e92a2173687cec417c978107 100644 (file)
@@ -6,9 +6,7 @@
 #include <sys/param.h>
 #include <sys/stat.h>
 #include <sys/uio.h>
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <time.h>
 #include <ctype.h>
 #include <stdio.h>
index 92be35413fc8ed3c17a91ef2dc120e42ea5e55bc..9d0b64bf5627612a6bfeb1502d0512b6b8d27f1a 100644 (file)
@@ -16,9 +16,7 @@
 #include <stdio.h>
 #include <string.h>
 #include <dirent.h>
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 
 #include <atalk/adouble.h>
 #include <atalk/util.h>
index 426dc3179f25ad99371bdff4e0e341e0a3cc6386..5b2fd4e3ffc3154547b344dfaf152710a76f60e0 100644 (file)
@@ -17,6 +17,7 @@ fce_CFLAGS = -I$(top_srcdir)/include
 
 bin_PROGRAMS += afpldaptest
 afpldaptest_SOURCES = uuidtest.c
-afpldaptest_CFLAGS = -D_PATH_ACL_LDAPCONF=\"$(pkgconfdir)/afp_ldap.conf\"
-afpldaptest_LDADD =  $(top_builddir)/libatalk/libatalk.la
+afpldaptest_CFLAGS = -D_PATH_CONFDIR=\"$(pkgconfdir)/\" @LDAP_CFLAGS@
+afpldaptest_LDFLAGS = @LDAP_LDFLAGS@
+afpldaptest_LDADD  = $(top_builddir)/libatalk/libatalk.la
 
index 76ca0a8e6a63505b41d736245b768ae1682345d3..d69699079ff99c63df589f5450fbddc226f3ee3f 100644 (file)
@@ -14,9 +14,7 @@
 #include <netdb.h>
 #include <inttypes.h>
 #include <sys/types.h>
-
 #include <sys/param.h>
-#include <sys/cdefs.h>
 
 #include <atalk/fce_api.h>
 #include <atalk/util.h>
index b3ab7b53be6f2d70947c57d2691f34852bb6ffdf..585c15839158a61534c96aafb62258908308d4ef 100644 (file)
@@ -25,11 +25,11 @@ int main(int argc, char *argv[])
 #endif
   /* filelog testing */
 
-  setuplog("DSI log_maxdebug test.log");
+  setuplog("DSI:maxdebug", "test.log");
   LOG(log_info, logtype_dsi, "This should log.");
   LOG(log_error, logtype_default, "This should not log.");
 
-  setuplog("Default log_debug test.log");
+  setuplog("Default:debug", "test.log");
   LOG(log_debug, logtype_default, "This should log.");
   LOG(log_maxdebug, logtype_default, "This should not log.");
 
index 0efc3318c6a45d0fe25c85b3cdf5016b9c548789..030a4f522d7d3fabafddbcc601caf130123aff17 100644 (file)
@@ -30,6 +30,7 @@
 #include <atalk/ldapconfig.h>
 #include <atalk/uuid.h>
 #include <atalk/logger.h>
+#include <atalk/iniparser.h>
 
 #define STRNCMP(a, R, b, l) (strncmp(a,b,l) R 0)
 
@@ -41,25 +42,27 @@ static void usage()
 static void parse_ldapconf()
 {
     static int inited = 0;
+    dictionary *iniconfig;
 
     if (! inited) {
 #ifdef HAVE_LDAP
-        /* Parse afp_ldap.conf */
-        printf("Start parsing afp_ldap.conf\n");
-        acl_ldap_readconfig(_PATH_ACL_LDAPCONF);
-        printf("Finished parsing afp_ldap.conf\n");
+        /* Parse afp.conf */
+        printf("Start parsing afp.conf\n");
+        iniconfig = iniparser_load(_PATH_CONFDIR "afp.conf");
+        acl_ldap_readconfig(iniconfig);
+        printf("Finished parsing afp.conf\n");
         if (ldap_config_valid) {
             if (ldap_auth_method == LDAP_AUTH_NONE)
-                printf("afp_ldap.conf is ok. Using anonymous bind.\n");
+                printf("afp.conf is ok. Using anonymous bind.\n");
             else if (ldap_auth_method == LDAP_AUTH_SIMPLE)
-                printf("afp_ldap.conf is ok. Using simple bind.\n");
+                printf("afp.conf is ok. Using simple bind.\n");
             else {
                 ldap_config_valid = 0;
-                printf("afp_ldap.conf wants SASL which is not yet supported.\n");
+                printf("afp.conf wants SASL which is not yet supported.\n");
                 exit(EXIT_FAILURE);
             }
         } else {
-            printf("afp_ldap.conf is not ok, not using LDAP. Only local UUID testing available.\n");
+            printf("afp.conf is not ok, not using LDAP. Only local UUID testing available.\n");
         }
 #else
         printf("Built without LDAP support, only local UUID testing available.\n");
@@ -83,14 +86,14 @@ int main( int argc, char **argv)
         case 'v':
             if (! verbose) {
                 verbose = 1;
-                setuplog("default log_maxdebug /dev/tty");
+                setuplog("default:maxdebug", "/dev/tty");
                 logsetup = 1;
             }
             break;
 
         case 'u':
             if (! logsetup)
-                setuplog("default log_info /dev/tty");
+                setuplog("default:info", "/dev/tty");
             parse_ldapconf();
             printf("Searching user: %s\n", optarg);
             ret = getuuidfromname( optarg, UUID_USER, uuid);
@@ -103,7 +106,7 @@ int main( int argc, char **argv)
 
         case 'g':
             if (! logsetup)
-                setuplog("default log_info /dev/tty");
+                setuplog("default:info", "/dev/tty");
             parse_ldapconf();
             printf("Searching group: %s\n", optarg);
             ret = getuuidfromname( optarg, UUID_GROUP, uuid);
@@ -116,7 +119,7 @@ int main( int argc, char **argv)
 
         case 'i':
             if (! logsetup)
-                setuplog("default log_info /dev/tty");
+                setuplog("default:info", "/dev/tty");
             parse_ldapconf();
             printf("Searching uuid: %s\n", optarg);
             uuid_string2bin(optarg, uuid);
diff --git a/bin/nbp/.gitignore b/bin/nbp/.gitignore
deleted file mode 100644 (file)
index e70b05a..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-Makefile
-Makefile.in
-nbplkup
-nbprgstr
-nbpunrgstr
-.deps
-.libs
-.gitignore
-nbplkup.o nbprgstr.o nbpunrgstr.o
diff --git a/bin/nbp/Makefile.am b/bin/nbp/Makefile.am
deleted file mode 100644 (file)
index c369c1e..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-# Makefile.am for bin/nbp/
-
-INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/sys
-
-bin_PROGRAMS = nbplkup nbprgstr nbpunrgstr
-
-nbplkup_SOURCES = nbplkup.c
-nbplkup_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-nbprgstr_SOURCES = nbprgstr.c
-nbprgstr_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-nbpunrgstr_SOURCES = nbpunrgstr.c
-nbpunrgstr_LDADD = $(top_builddir)/libatalk/libatalk.la
diff --git a/bin/nbp/nbplkup.c b/bin/nbp/nbplkup.c
deleted file mode 100644 (file)
index a43ac41..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * $Id: nbplkup.c,v 1.9 2009-10-29 11:35:57 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/nbp.h>
-#include <atalk/util.h>
-#include <string.h>
-#include <stdio.h>
-#ifdef HAVE_STDLIB_H
-#include <stdlib.h>
-#endif
-
-
-#include <atalk/unicode.h>
-
-static char *Obj = "=";
-static char *Type = "=";
-static char *Zone = "*";
-
-static void Usage(char *av0)
-{
-    char       *p;
-
-    if (( p = strrchr( av0, '/' )) == NULL ) {
-       p = av0;
-    } else {
-       p++;
-    }
-
-    printf( "Usage:\t%s [ -A address ] [ -r responses] [-m Mac charset] [ obj:type@zone ]\n", p );
-    exit( 1 );
-}
-
-int main(int ac, char **av)
-{
-    struct nbpnve      *nn;
-    char               *name;
-    int                        i, c, nresp = 1000;
-    struct at_addr      addr;
-    char               *obj = NULL;
-    size_t             obj_len;
-    charset_t          chMac = CH_MAC;
-    char *             convname;
-
-    extern char                *optarg;
-    extern int         optind;
-
-    memset(&addr, 0, sizeof(addr));
-    while (( c = getopt( ac, av, "r:A:m:" )) != EOF ) {
-       switch ( c ) {
-       case 'A':
-           if (!atalk_aton(optarg, &addr)) {
-               fprintf(stderr, "Bad address.\n");
-               exit(1);
-           }
-           break;
-       case 'r' :
-           nresp = atoi( optarg );
-           break;
-        case 'm':
-            if ((charset_t)-1 == (chMac = add_charset(optarg)) ) {
-               fprintf(stderr, "Invalid Mac charset.\n");
-               exit(1);
-           }
-            break;
-
-       default :
-           Usage( av[ 0 ] );
-           exit( 1 );
-       }
-    }
-
-    if (( nn = (struct nbpnve *)malloc( nresp * sizeof( struct nbpnve )))
-           == NULL ) {
-       perror( "malloc" );
-       exit( 1 );
-    }
-
-    if ( ac - optind > 1 ) {
-       Usage( av[ 0 ] );
-       exit( 1 );
-    }
-
-    /*
-     * Get default values from the environment. We need to copy out
-     * the results, here, since nbp_name returns it's parameters
-     * in static space, and we'll clobber them when we call it again
-     * later.
-     */
-    if (( name = getenv( "NBPLKUP" )) != NULL ) {
-       if ( nbp_name( name, &Obj, &Type, &Zone )) {
-           fprintf( stderr,
-                   "Environment variable syntax error: NBPLKUP = %s\n",
-                   name );
-           exit( 1 );
-       }
-
-       if (( name = (char *)malloc( strlen( Obj ) + 1 )) == NULL ) {
-           perror( "malloc" );
-           exit( 1 );
-       }
-       strcpy( name, Obj );
-       Obj = name;
-
-       if (( name = (char *)malloc( strlen( Type ) + 1 )) == NULL ) {
-           perror( "malloc" );
-           exit( 1 );
-       }
-       strcpy( name, Type );
-       Type = name;
-
-       if (( name = (char *)malloc( strlen( Zone ) + 1 )) == NULL ) {
-           perror( "malloc" );
-           exit( 1 );
-       }
-       strcpy( name, Zone );
-       Zone = name;
-
-    }
-
-    if ( ac - optind == 1 ) {
-       if ((size_t)(-1) == convert_string_allocate( CH_UNIX, chMac,
-                           av[ optind ], -1, &convname))
-            convname = av[ optind ];
-
-       if ( nbp_name( convname, &Obj, &Type, &Zone )) {
-           Usage( av[ 0 ] );
-           exit( 1 );
-       }
-    }
-
-    if (( c = nbp_lookup( Obj, Type, Zone, nn, nresp, &addr)) < 0 ) {
-       perror( "nbp_lookup" );
-       exit( -1 );
-    }
-    for ( i = 0; i < c; i++ ) {
-       
-       if ((size_t)(-1) == (obj_len = convert_string_allocate( chMac, 
-                       CH_UNIX, nn[ i ].nn_obj, nn[ i ].nn_objlen, &obj)) ) {
-            obj_len = nn[ i ].nn_objlen;
-            if (( obj = strdup(nn[ i ].nn_obj)) == NULL ) {
-               perror( "strdup" );
-               exit( 1 );
-           }
-        }
-
-       printf( "%31.*s:%-34.*s %u.%u:%u\n",
-               (int)obj_len, obj,
-               nn[ i ].nn_typelen, nn[ i ].nn_type,
-               ntohs( nn[ i ].nn_sat.sat_addr.s_net ),
-               nn[ i ].nn_sat.sat_addr.s_node,
-               nn[ i ].nn_sat.sat_port );
-
-       free(obj);
-    }
-
-    free(nn);
-    return 0;
-}
diff --git a/bin/nbp/nbprgstr.c b/bin/nbp/nbprgstr.c
deleted file mode 100644 (file)
index bef33a1..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * $Id: nbprgstr.c,v 1.9 2009-10-29 11:35:58 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/param.h>
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/netddp.h>
-#include <atalk/nbp.h>
-#include <atalk/util.h>
-#include <atalk/unicode.h>
-
-static void Usage(char *av0)
-{
-    char       *p;
-
-    if (( p = strrchr( av0, '/' )) == NULL ) {
-       p = av0;
-    } else {
-       p++;
-    }
-
-    fprintf( stderr, "Usage: %s [ -A address ] [-m Mac charset] [ -p port] obj:type@zone\n", p );
-    exit( 1 );
-}
-
-int main(int ac, char **av)
-{
-    struct sockaddr_at addr;
-    struct at_addr      ataddr;
-    char               *Obj = NULL, *Type = NULL, *Zone = NULL;
-    char               *convname = NULL;
-    int                        s, c, port = 0;
-    charset_t          chMac = CH_MAC;
-    
-    extern char                *optarg;
-    extern int         optind;
-
-    memset(&ataddr, 0, sizeof(ataddr));
-    while (( c = getopt( ac, av, "p:A:m:" )) != EOF ) {
-       switch ( c ) {
-       case 'A':
-           if (!atalk_aton(optarg, &ataddr)) {
-               fprintf(stderr, "Bad address.\n");
-               exit(1);
-           }
-           break;
-
-        case 'm':
-            if ((charset_t)-1 == (chMac = add_charset(optarg)) ) {
-                fprintf(stderr, "Invalid Mac charset.\n");
-                exit(1);
-            }
-            break;
-
-       case 'p' :
-           port = atoi( optarg );
-           break;
-
-       default :
-           Usage( av[ 0 ] );
-       }
-    }
-
-    if ( ac - optind != 1 ) {
-       Usage( av[ 0 ] );
-    }
-
-    /* Convert the name */
-    if ((size_t)(-1) == convert_string_allocate(CH_UNIX, chMac,
-                        av[optind], -1, &convname))
-        convname = av[optind];
-
-    /*
-     * Get the name. If Type or Obj aren't specified, error.
-     */
-    if ( nbp_name( convname, &Obj, &Type, &Zone ) || !Obj || !Type ) {
-       Usage( av[ 0 ] );
-    }
-
-    memset(&addr, 0, sizeof(addr));
-    memcpy(&addr.sat_addr, &ataddr, sizeof(addr.sat_addr));
-    if ((s = netddp_open(&addr, NULL)) < 0)
-       return( -1 );
-
-    if ( port ) {
-       addr.sat_port = port;
-    }
-
-    if ( nbp_rgstr( &addr, Obj, Type, Zone ) < 0 ) {
-       perror( "nbp_rgstr" );
-       fprintf( stderr, "Can't register %s:%s@%s\n", Obj, Type,
-               Zone ? Zone : "*" );
-       exit( 1 );
-    }
-    netddp_close(s);
-
-    return 0;
-}
diff --git a/bin/nbp/nbpunrgstr.c b/bin/nbp/nbpunrgstr.c
deleted file mode 100644 (file)
index a4a9465..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * $Id: nbpunrgstr.c,v 1.10 2009-10-29 11:35:58 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/util.h>
-#include <atalk/nbp.h>
-
-#include <atalk/unicode.h>
-
-static void Usage(char *av0)
-{
-    char       *p;
-
-    if (( p = strrchr( av0, '/' )) == NULL ) {
-       p = av0;
-    } else {
-       p++;
-    }
-
-    fprintf( stderr, "Usage: %s [ -A address ] [ -m Mac charset] obj:type@zone\n", p );
-    exit( 1 );
-}
-
-int main(int ac, char **av)
-{
-    char               *Obj = NULL, *Type = NULL, *Zone = NULL;
-    char               *convname = NULL;
-    struct at_addr      addr;
-    int                 c;
-    charset_t          chMac = CH_MAC;
-
-    extern char                *optarg;
-    extern int         optind;
-    
-    memset(&addr, 0, sizeof(addr));
-    while ((c = getopt(ac, av, "A:m:")) != EOF) {
-      switch (c) {
-      case 'A':
-       if (!atalk_aton(optarg, &addr)) {
-         fprintf(stderr, "Bad address.\n");
-         exit(1);
-       }
-       break;
-      case 'm':
-        if ((charset_t)-1 == (chMac = add_charset(optarg)) ) {
-          fprintf(stderr, "Invalid Mac charset.\n");
-          exit(1);
-        }
-        break;
-
-      default:
-       Usage(av[0]);
-       break;
-      }
-    }
-
-    if (ac - optind != 1) {
-       Usage( av[ 0 ] );
-    }
-
-    /* Convert the name */
-    if ((size_t)(-1) == convert_string_allocate(CH_UNIX, chMac, 
-                        av[optind], -1, &convname))
-        convname = av[optind]; 
-
-    /*
-     * Get the name. If Type or Obj aren't specified, error.
-     */
-    if ( nbp_name( convname, &Obj, &Type, &Zone ) || !Obj || !Type ) {
-       Usage( av[ 0 ] );
-    }
-
-    if ( nbp_unrgstr( Obj, Type, Zone, &addr ) < 0 ) {
-       fprintf( stderr, "Can't unregister %s:%s@%s\n", Obj, Type,
-               Zone ? Zone : "*" );
-       exit( 1 );
-    }
-
-    return 0;
-}
diff --git a/bin/pap/.gitignore b/bin/pap/.gitignore
deleted file mode 100644 (file)
index 850951f..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Makefile
-Makefile.in
-pap
-papstatus
-.deps
-.libs
-.gitignore
-pap.o papstatus.o
diff --git a/bin/pap/Makefile.am b/bin/pap/Makefile.am
deleted file mode 100644 (file)
index 344cf72..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-# Makefile.am for bin/pap/
-
-INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/sys
-
-bin_PROGRAMS = pap papstatus
-
-pap_SOURCES = pap.c
-pap_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-papstatus_SOURCES = papstatus.c
-papstatus_LDADD = $(top_builddir)/libatalk/libatalk.la
diff --git a/bin/pap/pap.c b/bin/pap/pap.c
deleted file mode 100644 (file)
index a8c97ad..0000000
+++ /dev/null
@@ -1,870 +0,0 @@
-/*
- * $Id: pap.c,v 1.14 2009-10-16 01:10:59 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <errno.h>
-#include <atalk/atp.h>
-#include <atalk/pap.h>
-#include <atalk/nbp.h>
-#include <atalk/util.h>
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#include <stdio.h>
-#include <string.h>
-#include <string.h>
-#include <stdlib.h>
-
-#define FUCKED
-
-#define _PATH_PAPRC    ".paprc"
-
-/* Forward Declarations */
-static void updatestatus(char *s, int len);
-static int send_file(int fd, ATP atp, int lastfile);
-
-static void usage(char *path)
-{
-    char       *p;
-
-    if (( p = strrchr( path, '/' )) == NULL ) {
-       p = path;
-    } else {
-       p++;
-    }
-    fprintf( stderr,
-       "Usage:\t%s [ -A address ] [ -c ] [ -d ] [ -e ] [ -E ] [ -p printer ]\n"
-       "    [ -s statusfile ] [ -w ] [ -W ] [ FILES ]\n"
-       "  -A address    - printer Appletalk address\n"
-       "  -c            - take cuts (lie about wait time)\n"
-       "  -d            - enable debug\n"
-       "  -e            - send stdout to stderr\n"
-       "  -E            - don't wait for EOF from printer\n"
-       "  -p printer    - printer name\n"
-       "  -s statusfile - put current printer status in statusfile\n"
-       "  -w            - wait for printer status = 'waiting'\n"
-       "  -W            - wait for printer status = 'idle'\n"
-       "  FILES         - send FILES to printer\n"
-       , p );
-    exit( 2 );
-}
-
-static char *
-paprc(void)
-{
-    static char        s[ 32 + 1 + 32 + 1 + 32 ];
-    char       *name = NULL;
-    FILE       *f;
-
-    if (( f = fopen( _PATH_PAPRC, "r" )) == NULL ) {
-       if ( errno == ENOENT ) {
-           return( NULL );
-       } else {
-           perror( _PATH_PAPRC );
-           exit( 2 );
-       }
-    }
-    while ( fgets( s, sizeof( s ), f ) != NULL ) {
-       s[ strlen( s ) - 1 ] = '\0';    /* remove trailing newline */
-       if ( *s == '#' ) {
-           continue;
-       }
-       name = s;
-       break;
-    }
-    fclose( f );
-    return( name );
-}
-
-static char                    *printer = NULL;
-static char                    *status = NULL;
-static int                     noeof = 0;
-static int                     waitforprinter = 0;
-
-static unsigned char           connid, quantum, oquantum = PAP_MAXQUANTUM;
-static struct sockaddr_at      sat;
-
-static char                    cbuf[ 8 ];
-static struct nbpnve           nn;
-static ATP                     satp;
-
-static char            fbuf[ PAP_MAXQUANTUM ][ 4 + PAP_MAXDATA ];
-static struct iovec    rfiov[ PAP_MAXQUANTUM ] = {
-    { fbuf[ 0 ] + 4,   0 },
-    { fbuf[ 1 ] + 4,   0 },
-    { fbuf[ 2 ] + 4,   0 },
-    { fbuf[ 3 ] + 4,   0 },
-    { fbuf[ 4 ] + 4,   0 },
-    { fbuf[ 5 ] + 4,   0 },
-    { fbuf[ 6 ] + 4,   0 },
-    { fbuf[ 7 ] + 4,   0 },
-};
-
-static struct iovec    sniov[ PAP_MAXQUANTUM ] = {
-    { fbuf[ 0 ],       0 },
-    { fbuf[ 1 ],       0 },
-    { fbuf[ 2 ],       0 },
-    { fbuf[ 3 ],       0 },
-    { fbuf[ 4 ],       0 },
-    { fbuf[ 5 ],       0 },
-    { fbuf[ 6 ],       0 },
-    { fbuf[ 7 ],       0 },
-};
-
-static char            nbuf[ PAP_MAXQUANTUM ][ 4 + PAP_MAXDATA ];
-static struct iovec    rniov[ PAP_MAXQUANTUM ] = {
-    { nbuf[ 0 ],       0 },
-    { nbuf[ 1 ],       0 },
-    { nbuf[ 2 ],       0 },
-    { nbuf[ 3 ],       0 },
-    { nbuf[ 4 ],       0 },
-    { nbuf[ 5 ],       0 },
-    { nbuf[ 6 ],       0 },
-    { nbuf[ 7 ],       0 },
-};
-
-static struct iovec    sfiov[ PAP_MAXQUANTUM ] = {
-    { nbuf[ 0 ] + 4,   0 },
-    { nbuf[ 1 ] + 4,   0 },
-    { nbuf[ 2 ] + 4,   0 },
-    { nbuf[ 3 ] + 4,   0 },
-    { nbuf[ 4 ] + 4,   0 },
-    { nbuf[ 5 ] + 4,   0 },
-    { nbuf[ 6 ] + 4,   0 },
-    { nbuf[ 7 ] + 4,   0 },
-};
-
-static int debug;
-
-int main( int ac, char **av)
-{
-    ATP                        atp;
-    struct atp_block   atpb;
-    int                        c, err = 0, fd, cuts = 0;
-    char               *obj = NULL, *type = "LaserWriter", *zone = "*";
-    struct timeval     stv, tv;
-    char               rbuf[ ATP_MAXDATA ];
-    struct iovec       iov;
-    unsigned short     waiting, result;
-    int                        connattempts = 10;
-    int                        waitforidle = 0;
-    struct at_addr      addr;
-
-    extern char                *optarg;
-    extern int         optind;
-
-    memset(&addr, 0, sizeof(addr));
-    while (( c = getopt( ac, av, "dWwcep:s:EA:" )) != EOF ) {
-       switch ( c ) {
-#ifdef FUCKED
-       case 'w' :
-           waitforprinter = 1;
-           break;
-
-       case 'W' :
-           waitforidle = 1;
-           break;
-#endif /* FUCKED */
-
-       /* enable debugging */
-       case 'd' :
-           debug++;
-           break;
-
-       case 'c' :
-           cuts++;
-           break;
-
-       case 'e' :      /* send stdout to stderr */
-           dup2( 2, 1 );
-           break;
-
-       case 'p' :
-           printer = optarg;
-           break;
-
-       case 's' :
-           status = optarg;
-           break;
-
-       case 'E' :
-           noeof = 1;
-           break;
-          
-       case 'A':
-           if (!atalk_aton(optarg, &addr)) {
-             fprintf(stderr, "Bad address.\n");
-             exit(1);
-           }
-           break;
-
-       default :
-           err++;
-       }
-    }
-    if ( err ) {
-       usage( *av );
-    }
-    if ( printer == NULL && (( printer = paprc()) == NULL )) {
-       fprintf( stderr, "No printer specified and ./.paprc not found.\n" );
-       exit( 2 );
-    }
-
-    /*
-     * Open connection.
-     */
-    if ( nbp_name( printer, &obj, &type, &zone ) < 0 ) {
-       fprintf( stderr, "%s: Bad name\n", printer );
-       exit( 2 );
-    }
-    if ( obj == NULL ) {
-       fprintf( stderr, "%s: Bad name\n", printer );
-       exit( 2 );
-    }
-
-    if ( nbp_lookup( obj, type, zone, &nn, 1, &addr ) <= 0 ) {
-       if ( errno != 0 ) {
-           perror( "nbp_lookup" );
-           exit( 2 );
-       }
-       fprintf( stderr, "%s:%s@%s: NBP Lookup failed\n", obj, type, zone );
-       exit( 1 );
-    }
-
-    if ( isatty( 1 )) {
-       printf( "Trying %u.%d:%d ...\n", ntohs( nn.nn_sat.sat_addr.s_net ),
-               nn.nn_sat.sat_addr.s_node, nn.nn_sat.sat_port );
-    }
-
-    if (( atp = atp_open( ATADDR_ANYPORT, &addr )) == NULL ) {
-       perror( "atp_open" );
-       exit( 2 );
-    }
-    if (( satp = atp_open( ATADDR_ANYPORT, &addr )) == NULL ) {
-       perror( "atp_open" );
-       exit( 2 );
-    }
-
-    while ( waitforidle ) {
-       char    st_buf[ 1024 ]; /* XXX too big */
-
-       cbuf[ 0 ] = 0;
-       cbuf[ 1 ] = PAP_SENDSTATUS;
-       cbuf[ 2 ] = cbuf[ 3 ] = 0;
-       atpb.atp_saddr = &nn.nn_sat;
-       atpb.atp_sreqdata = cbuf;
-       atpb.atp_sreqdlen = 4;  /* bytes in SendStatus request */
-       atpb.atp_sreqto = 2;            /* retry timer */
-       atpb.atp_sreqtries = 5;         /* retry count */
-       if ( atp_sreq( satp, &atpb, 1, 0 ) < 0 ) {
-           perror( "atp_sreq" );
-           exit( 1 );
-       }
-
-       if(debug){ printf( "SENDSTATUS >\n" ), fflush( stdout );}
-
-       atpb.atp_saddr = &nn.nn_sat;
-       rniov[ 0 ].iov_len = PAP_MAXDATA + 4;
-       atpb.atp_rresiov = rniov;
-       atpb.atp_rresiovcnt = 1;
-       if ( atp_rresp( satp, &atpb ) < 0 ) {
-           perror( "atp_rresp" );
-           continue;
-       }
-
-#ifndef NONZEROSTATUS
-       /*
-        * The stinking LaserWriter IINTX puts crap in this
-        * field.
-        */
-       if ( ((char *)rniov[ 0 ].iov_base)[ 0 ] != 0 ) {
-           fprintf( stderr, "Bad status response!\n" );
-           exit( 1 );
-       }
-#endif /* NONZEROSTATUS */
-
-       if ( ((char *)rniov[ 0 ].iov_base)[ 1 ] != PAP_STATUS ||
-               atpb.atp_rresiovcnt != 1 ) {
-           fprintf( stderr, "Bad status response!\n" );
-           exit( 1 );
-       }
-
-       if(debug){ printf( "< STATUS\n" ), fflush( stdout );}
-
-       memcpy( st_buf, (char *) rniov[ 0 ].iov_base + 9, 
-               ((char *)rniov[ 0 ].iov_base)[ 8 ] );
-       st_buf[ (int) ((char *)rniov[ 0 ].iov_base)[ 8 ]] = '\0';
-       if ( strstr( st_buf, "idle" ) != NULL ) {
-           waitforidle = 0;
-       } else {
-           updatestatus( (char *) rniov[ 0 ].iov_base + 9,
-                   ((char *)rniov[ 0 ].iov_base)[ 8 ] );
-           sleep( 5 );
-       }
-    }
-
-    cbuf[ 0 ] = connid = getpid() & 0xff;
-    cbuf[ 1 ] = PAP_OPEN;
-    cbuf[ 2 ] = cbuf[ 3 ] = 0;
-    cbuf[ 4 ] = atp_sockaddr( atp )->sat_port;
-    cbuf[ 5 ] = oquantum;      /* flow quantum */
-    if ( gettimeofday( &stv, NULL ) < 0 ) {
-       perror( "gettimeofday" );
-       exit( 2 );
-    }
-    for (;;) {
-       if ( cuts ) {
-           waiting = 0xffff;
-       } else {
-           if ( gettimeofday( &tv, NULL ) < 0 ) {
-               perror( "gettimeofday" );
-               exit( 2 );
-           }
-           waiting = htons( tv.tv_sec - stv.tv_sec );
-       }
-       memcpy(cbuf +  6, &waiting, sizeof( waiting ));
-
-       atpb.atp_saddr = &nn.nn_sat;
-       atpb.atp_sreqdata = cbuf;
-       atpb.atp_sreqdlen = 8;          /* bytes in OpenConn request */
-       atpb.atp_sreqto = 2;            /* retry timer */
-       atpb.atp_sreqtries = 5;         /* retry count */
-       if ( atp_sreq( atp, &atpb, 1, ATP_XO ) < 0 ) {
-           perror( "atp_sreq" );
-           exit( 1 );
-       }
-
-       if(debug){ printf( "OPEN >\n" ), fflush( stdout );}
-
-       iov.iov_base = rbuf;
-       iov.iov_len = sizeof( rbuf );
-       atpb.atp_rresiov = &iov;
-       atpb.atp_rresiovcnt = 1;
-       if ( atp_rresp( atp, &atpb ) < 0 ) {
-           perror( "atp_rresp" );
-           if ( connattempts-- <= 0 ) {
-               fprintf( stderr, "Can't connect!\n" );
-               exit( 1 );
-           }
-           continue;
-       }
-
-       /* sanity */
-       if ( iov.iov_len < 8 || (unsigned char)rbuf[ 0 ] != connid ||
-               rbuf[ 1 ] != PAP_OPENREPLY ) {
-           fprintf( stderr, "Bad response!\n" );
-           continue;   /* This is weird, since TIDs must match... */
-       }
-
-       if(debug){ printf( "< OPENREPLY\n" ), fflush( stdout );}
-
-       if ( isatty( 1 )) {
-           printf( "%.*s\n", (int)iov.iov_len - 9, (char *) iov.iov_base + 9 );
-       }
-       updatestatus( (char *) iov.iov_base + 9, iov.iov_len - 9 );
-
-       memcpy( &result, rbuf +  6,  sizeof( result ));
-       if ( result != 0 ) {
-           sleep( 2 );
-       } else {
-           memcpy( &sat, &nn.nn_sat, sizeof( struct sockaddr_at ));
-           sat.sat_port = rbuf[ 4 ];
-           quantum = rbuf[ 5 ];
-           break;
-       }
-    }
-
-    if ( isatty( 1 )) {
-       printf( "Connected to %.*s:%.*s@%.*s.\n",
-               nn.nn_objlen, nn.nn_obj,
-               nn.nn_typelen, nn.nn_type,
-               nn.nn_zonelen, nn.nn_zone );
-    }
-
-    if ( optind == ac ) {
-       send_file( 0, atp, 1 );
-    } else {
-       for (; optind < ac; optind++ ) {
-           if ( strcmp( av[ optind ], "-" ) == 0 ) {
-               fd = 0;
-           } else if (( fd = open( av[ optind ], O_RDONLY )) < 0 ) {
-               perror( av[ optind ] );
-               continue;
-           }
-           send_file( fd, atp, ( optind == ac - 1 ) ? 1 : 0 );
-           if ( fd != 0 ) {
-               close( fd );
-           }
-       }
-    }
-
-    /*
-     * Close connection.
-     */
-    cbuf[ 0 ] = connid;
-    cbuf[ 1 ] = PAP_CLOSE;
-    cbuf[ 2 ] = cbuf[ 3 ] = 0;
-
-    atpb.atp_saddr = &sat;
-    atpb.atp_sreqdata = cbuf;
-    atpb.atp_sreqdlen = 4;             /* bytes in CloseConn request */
-    atpb.atp_sreqto = 2;               /* retry timer */
-    atpb.atp_sreqtries = 5;            /* retry count */
-    if ( atp_sreq( atp, &atpb, 1, ATP_XO ) < 0 ) {
-       perror( "atp_sreq" );
-       exit( 1 );
-    }
-
-       if(debug){ printf( "CLOSE >\n" ), fflush( stdout );}
-
-    iov.iov_base = rbuf;
-    iov.iov_len = sizeof( rbuf );
-    atpb.atp_rresiov = &iov;
-    atpb.atp_rresiovcnt = 1;
-    if ( atp_rresp( atp, &atpb ) < 0 ) {
-       perror( "atp_rresp" );
-       exit( 1 );
-    }
-
-    /* sanity */
-    if ( iov.iov_len != 4 || rbuf[ 1 ] != PAP_CLOSEREPLY ) {
-       fprintf( stderr, "Bad response!\n" );
-       exit( 1 );
-    }
-
-#ifndef ZEROCONNID
-    /*
-     * The AGFA Viper Rip doesn't have the connection id in the close request.
-     */
-    if ((unsigned char)rbuf[ 0 ] != connid ) {
-       fprintf( stderr, "Bad connid in close!\n" );
-       exit( 1 );
-    }
-#endif /* ZEROCONNID */
-
-       if(debug){ printf( "< CLOSEREPLY\n" ), fflush( stdout );}
-
-    if ( isatty( 1 )) {
-       printf( "Connection closed.\n" );
-    }
-    exit( 0 );
-}
-
-static int             data = 0;
-static unsigned char   port;
-static u_int16_t       seq = 0;
-
-static int send_file( int fd, ATP atp, int lastfile)
-{
-    struct timeval     stv, tv;
-    struct sockaddr_at ssat;
-    struct atp_block   atpb;
-    fd_set             fds;
-    int                        fiovcnt = 0, eof = 0, senteof = 0, to = 0;
-    int                        cc, i;
-    unsigned short     netseq;
-
-    if ( gettimeofday( &stv, NULL ) < 0 ) {
-       perror( "gettimeofday" );
-       exit( 2 );
-    }
-
-    /*
-     * Ask for more data.
-     */
-    cbuf[ 0 ] = connid;
-    cbuf[ 1 ] = PAP_READ;
-    if ( ++seq == 0 ) seq = 1;
-    netseq = htons( seq );
-    memcpy( cbuf +  2, &netseq, sizeof( netseq ));
-    atpb.atp_saddr = &sat;
-    atpb.atp_sreqdata = cbuf;
-    atpb.atp_sreqdlen = 4;             /* bytes in SendData request */
-    atpb.atp_sreqto = 15;              /* retry timer */
-    atpb.atp_sreqtries = -1;           /* retry count */
-    if ( atp_sreq( atp, &atpb, oquantum, ATP_XO ) < 0 ) {
-       perror( "atp_sreq" );
-       exit( 1 );
-    }
-
-       if(debug){ printf( "READ %d >\n", seq ), fflush( stdout );}
-
-    for (;;) {
-       if ( gettimeofday( &tv, NULL ) < 0 ) {
-           perror( "gettimeofday" );
-           exit( 2 );
-       }
-
-       if (( tv.tv_sec - stv.tv_sec ) >= 60 ) {
-           stv = tv;
-
-           /*
-            * Send a tickle.
-            */
-           cbuf[ 0 ] = connid;
-           cbuf[ 1 ] = PAP_TICKLE;
-           cbuf[ 2 ] = cbuf[ 3 ] = 0;
-           atpb.atp_saddr = &sat;
-           atpb.atp_sreqdata = cbuf;
-           atpb.atp_sreqdlen = 4;              /* bytes in Tickle request */
-           atpb.atp_sreqto = 0;                /* retry timer */
-           atpb.atp_sreqtries = 1;             /* retry count */
-           if ( atp_sreq( satp, &atpb, 0, 0 ) < 0 ) {
-               perror( "atp_sreq" );
-               exit( 1 );
-           }
-
-       if(debug){ printf( "TICKLE >\n" ), fflush( stdout );}
-       }
-
-       tv.tv_sec = stv.tv_sec + 60 - tv.tv_sec;
-       tv.tv_usec = 0;
-
-       FD_ZERO( &fds );
-       if ( !waitforprinter && !eof && fiovcnt == 0 ) {
-           FD_SET( fd, &fds );
-       }
-       FD_SET( atp_fileno( atp ), &fds );
-
-       if (( cc = select( FD_SETSIZE, &fds, NULL, NULL, &tv )) < 0 ) {
-           perror( "select" );
-           exit( 2 );
-       }
-
-       /*
-        * A timeout has occured. Keep track of it.
-        */
-       if ( cc == 0 ) {
-           if ( to++ > 2 ) {
-               fprintf( stderr, "Connection timed out.\n" );
-               exit( 1 );
-           }
-           continue;
-       }
-
-       /*
-        * Read data.
-        */
-       if ( !fiovcnt && FD_ISSET( fd, &fds )) {
-           for ( i = 0; i < quantum; i++ ) {
-               rfiov[ i ].iov_len = PAP_MAXDATA;
-           }
-           if (( cc = readv( fd, rfiov, quantum )) < 0 ) {
-               perror( "readv" );
-               exit( 2 );
-           }
-           if ( cc == 0 ) {
-               eof = 1;
-           }
-           fiovcnt = cc / PAP_MAXDATA + ( cc % PAP_MAXDATA > 0 );
-           for ( i = 0; cc > 0; i++ ) {
-               rfiov[ i ].iov_len = ( cc > PAP_MAXDATA ) ? PAP_MAXDATA : cc;
-               cc -= ( cc > PAP_MAXDATA ) ? PAP_MAXDATA : cc;
-           }
-       }
-
-       if ( FD_ISSET( atp_fileno( atp ), &fds )) {
-           ssat = sat;
-           ssat.sat_port = ATADDR_ANYPORT;
-           switch( atp_rsel( atp, &ssat, ATP_TRESP | ATP_TREQ )) {
-           case ATP_TREQ :
-               atpb.atp_saddr = &ssat;
-               atpb.atp_rreqdata = cbuf;
-               atpb.atp_rreqdlen = sizeof( cbuf );
-               if ( atp_rreq( atp, &atpb ) < 0 ) {
-                   perror( "atp_rreq" );
-                   exit( 1 );
-               }
-
-               if ( (unsigned char)cbuf[ 0 ] != connid ) {
-                   break;
-               }
-
-               /* reset timeout counter for all valid requests */
-               to = 0;
-
-               switch ( cbuf[ 1 ] ) {
-               case PAP_READ :
-                   memcpy( cbuf +  2, &netseq, sizeof( netseq ));
-       if(debug){ printf( "< READ %d\n", ntohs( netseq )), fflush( stdout );}
-#ifdef notdef
-                   if ( netseq != 0 ) {
-                       if ( rseq != ntohs( netseq )) {
-       if(debug){ printf( "| DUP %d\n", rseq ), fflush( stdout );}
-                           break;
-                       }
-                       if ( rseq++ == 0xffff ) rseq = 1;
-                   }
-#endif /* notdef */
-
-                   data = 1;
-                   port = ssat.sat_port;
-                   break;
-
-               case PAP_CLOSE :
-
-       if(debug){ printf( "< CLOSE\n" ), fflush( stdout );}
-
-                   /*
-                    * Respond to the close request, and fail.
-                    */
-                   sniov[ 0 ].iov_len = 4;
-                   ((char *)sniov[ 0 ].iov_base)[ 0 ] = connid;
-                   ((char *)sniov[ 0 ].iov_base)[ 1 ] = PAP_CLOSEREPLY;
-                   ((char *)sniov[ 0 ].iov_base)[ 2 ] =
-                           ((char *)sniov[ 0 ].iov_base)[ 3 ] = 0;
-                   atpb.atp_sresiov = sniov;
-                   atpb.atp_sresiovcnt = 1;
-                   if ( atp_sresp( atp, &atpb ) < 0 ) {
-                       perror( "atp_sresp" );
-                       exit( 1 );
-                   }
-
-       if(debug){ printf( "CLOSEREPLY >\n" ), fflush( stdout );}
-
-                   fprintf( stderr, "Connection closed by foreign host.\n" );
-                   exit( 1 );
-
-               case PAP_TICKLE :
-
-       if(debug){ printf( "< TICKLE\n" ), fflush( stdout );}
-
-                   break;
-               default :
-                   fprintf( stderr, "Bad PAP request!\n" );
-                   exit( 1 );
-               }
-               break;
-
-           case ATP_TRESP :
-               /* reset timeout counter for all valid requests */
-               to = 0;
-
-               atpb.atp_saddr = &ssat;
-               for ( i = 0; i < oquantum; i++ ) {
-                   rniov[ i ].iov_len = PAP_MAXDATA + 4;
-               }
-               atpb.atp_rresiov = rniov;
-               atpb.atp_rresiovcnt = oquantum;
-               if ( atp_rresp( atp, &atpb ) < 0 ) {
-                   perror( "atp_rresp" );
-                   exit( 1 );
-               }
-
-#ifndef ZEROCONNID
-               /*
-                * The HP LJIIISI w/ BridgePort LocalTalk card sends
-                * zero instead of the connid.
-                */
-               if ( ((unsigned char *)rniov[ 0 ].iov_base)[ 0 ] != connid ) {
-                   fprintf( stderr, "Bad data response!\n" );
-                   exit( 1 );
-               }
-#endif /* ZEROCONNID */
-               if ( ((char *)rniov[ 0 ].iov_base)[ 1 ] != PAP_DATA ) {
-                   fprintf( stderr, "Bad data response!\n" );
-                   exit( 1 );
-               }
-
-               for ( cc = 0, i = 0; i < atpb.atp_rresiovcnt; i++ ) {
-                   sfiov[ i ].iov_len = rniov[ i ].iov_len - 4;
-                   cc += sfiov[ i ].iov_len;
-               }
-               if ( cc && writev( 1, sfiov, atpb.atp_rresiovcnt ) < cc ) {
-                   perror( "writev" );
-                   exit( 2 );
-               }
-
-               /* eof */
-               if ( ((char *)rniov[ 0 ].iov_base)[ 2 ] ) {
-
-       if(debug){ printf( "< DATA (eof)\n" ), fflush( stdout );}
-
-                   return( 0 );
-               }
-
-       if(debug){ printf( "< DATA\n" ), fflush( stdout );}
-
-
-               /*
-                * Ask for more data.
-                */
-               cbuf[ 0 ] = connid;
-               cbuf[ 1 ] = PAP_READ;
-               if ( ++seq == 0 ) seq = 1;
-               netseq = htons( seq );
-               memcpy( cbuf +  2, &netseq, sizeof( netseq ));
-               atpb.atp_saddr = &sat;
-               atpb.atp_sreqdata = cbuf;
-               atpb.atp_sreqdlen = 4;          /* bytes in SendData request */
-               atpb.atp_sreqto = 15;           /* retry timer */
-               atpb.atp_sreqtries = -1;        /* retry count */
-               if ( atp_sreq( atp, &atpb, oquantum, ATP_XO ) < 0 ) {
-                   perror( "atp_sreq" );
-                   exit( 1 );
-               }
-
-       if(debug){ printf( "READ %d >\n", seq ), fflush( stdout );}
-
-               break;
-
-           case 0:
-
-       if(debug){ printf( "| RETRANS\n" ), fflush( stdout );}
-
-               break;
-
-           default:
-               perror( "atp_rsel" );
-               exit( 1 );
-           }
-       }
-
-       /*
-        * Send whatever is pending.
-        */
-       if ( !waitforprinter && !senteof && data && ( fiovcnt || eof )) {
-           ssat.sat_port = port;
-           atpb.atp_saddr = &ssat;
-           if ( fiovcnt ) {
-               for ( i = 0; i < fiovcnt; i++ ) {
-                   sniov[ i ].iov_len = rfiov[ i ].iov_len + 4;
-                   ((char *)sniov[ i ].iov_base)[ 0 ] = connid;
-                   ((char *)sniov[ i ].iov_base)[ 1 ] = PAP_DATA;
-                   senteof = ((char *)sniov[ i ].iov_base)[ 2 ] = eof;
-                   ((char *)sniov[ i ].iov_base)[ 3 ] = 0;
-               }
-           } else {
-               sniov[ 0 ].iov_len = 4;
-               ((char *)sniov[ 0 ].iov_base)[ 0 ] = connid;
-               ((char *)sniov[ 0 ].iov_base)[ 1 ] = PAP_DATA;
-               senteof = ((char *)sniov[ 0 ].iov_base)[ 2 ] = eof;
-               ((char *)sniov[ 0 ].iov_base)[ 3 ] = 0;
-           }
-           atpb.atp_sresiov = sniov;
-           atpb.atp_sresiovcnt = fiovcnt ? fiovcnt : 1;
-           if ( atp_sresp( atp, &atpb ) < 0 ) {
-               perror( "atp_sresp" );
-               exit( 1 );
-           }
-           data = fiovcnt = 0;
-
-       if(debug){ printf( "DATA %s\n", eof ? "(eof) >" : ">" ), fflush( stdout );}
-
-           /*
-            * The Apple LaserWriter IIf, the HP LWIIISi, and IV, don't
-            * seem to send us an EOF on large jobs.  To work around
-            * this heinous protocol violation, we won't wait for their
-            * EOF before closing.
-            */
-           if ( eof && noeof && lastfile ) {
-               return( 0 );
-           }
-       } else {
-           /*
-            * If we can't send data right now, go ahead and get the
-            * status. This is cool, because we get here reliably
-            * if there is a problem.
-            */
-           cbuf[ 0 ] = 0;
-           cbuf[ 1 ] = PAP_SENDSTATUS;
-           cbuf[ 2 ] = cbuf[ 3 ] = 0;
-           atpb.atp_saddr = &nn.nn_sat;
-           atpb.atp_sreqdata = cbuf;
-           atpb.atp_sreqdlen = 4;      /* bytes in SendStatus request */
-           atpb.atp_sreqto = 2;                /* retry timer */
-           atpb.atp_sreqtries = 5;             /* retry count */
-           if ( atp_sreq( satp, &atpb, 1, 0 ) < 0 ) {
-               perror( "atp_sreq" );
-               exit( 1 );
-           }
-
-       if(debug){ printf( "SENDSTATUS >\n" ), fflush( stdout );}
-
-           atpb.atp_saddr = &nn.nn_sat;
-           rniov[ 0 ].iov_len = PAP_MAXDATA + 4;
-           atpb.atp_rresiov = rniov;
-           atpb.atp_rresiovcnt = 1;
-           if ( atp_rresp( satp, &atpb ) < 0 ) {
-               perror( "atp_rresp" );
-               continue;
-           }
-
-#ifndef NONZEROSTATUS
-           /*
-            * The stinking LaserWriter IINTX puts crap in this
-            * field.
-            */
-           if ( ((char *)rniov[ 0 ].iov_base)[ 0 ] != 0 ) {
-               fprintf( stderr, "Bad status response!\n" );
-               exit( 1 );
-           }
-#endif /* NONZEROSTATUS */
-
-           if ( ((char *)rniov[ 0 ].iov_base)[ 1 ] != PAP_STATUS ||
-                   atpb.atp_rresiovcnt != 1 ) {
-               fprintf( stderr, "Bad status response!\n" );
-               exit( 1 );
-           }
-
-       if(debug){ printf( "< STATUS\n" ), fflush( stdout );}
-
-#ifdef FUCKED
-           if ( waitforprinter ) {
-               char    st_buf[ 1024 ]; /* XXX too big */
-
-               memcpy( st_buf, (char *) rniov[ 0 ].iov_base + 9, 
-                       ((char *)rniov[ 0 ].iov_base)[ 8 ] );
-               st_buf[ (int) ((char *)rniov[ 0 ].iov_base)[ 8 ]] = '\0';
-               if ( strstr( st_buf, "waiting" ) != NULL ) {
-                   waitforprinter = 0;
-               }
-           }
-#endif /* FUCKED */
-
-           updatestatus( (char *) rniov[ 0 ].iov_base + 9,
-                   ((char *)rniov[ 0 ].iov_base)[ 8 ] );
-       }
-    }
-}
-
-static void updatestatus(char *s, int len)
-{
-    int                        fd = -1;
-    struct iovec       iov[ 3 ];
-
-    if ( status ) {
-       if (( fd = open( status, O_WRONLY|O_TRUNC )) < 0 ) {
-           perror( status );
-           status = NULL;
-       }
-    }
-
-    if ( fd < 0 ) {
-       fd = 2;
-    }
-
-    iov[ 0 ].iov_base = "%%[ ";
-    iov[ 0 ].iov_len = 4;
-    iov[ 1 ].iov_base = s;
-    iov[ 1 ].iov_len = len;
-    iov[ 2 ].iov_base = " ]%%\n";
-    iov[ 2 ].iov_len = 5;
-
-    writev( fd, iov, 3 );
-    if ( status ) {
-       close( fd );
-    }
-}
diff --git a/bin/pap/papstatus.c b/bin/pap/papstatus.c
deleted file mode 100644 (file)
index 0ada9c0..0000000
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * $Id: papstatus.c,v 1.7 2009-10-14 01:38:28 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/file.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <errno.h>
-#include <atalk/atp.h>
-#include <atalk/pap.h>
-#include <atalk/nbp.h>
-#include <atalk/util.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define _PATH_PAPRC    ".paprc"
-
-/* Forward Declaration */
-static void getstatus(ATP atp, struct sockaddr_at *sat);
-
-static void usage(char *path)
-{
-    char       *p;
-
-    if (( p = strrchr( path, '/' )) == NULL ) {
-       p = path;
-    } else {
-       p++;
-    }
-    fprintf( stderr,
-       "Usage:\t%s [ -A address ] [ -p printername ]\n", p );
-    exit( 1 );
-}
-
-static char *
-paprc(void)
-{
-    static char        s[ 32 + 1 + 32 + 1 + 32 ];
-    char       *name = NULL;
-    FILE       *f;
-
-    if (( f = fopen( _PATH_PAPRC, "r" )) == NULL ) {
-       return( NULL );
-    }
-    while ( fgets( s, sizeof( s ), f ) != NULL ) {
-       s[ strlen( s ) - 1 ] = '\0';    /* remove trailing newline */
-       if ( *s == '#' ) {
-           continue;
-       }
-       name = s;
-       break;
-    }
-    fclose( f );
-    return( name );
-}
-
-static char                    *printer = NULL;
-
-static char                    cbuf[ 8 ];
-static struct nbpnve           nn;
-
-int main( int ac, char **av)
-{
-    ATP                        atp;
-    int                        wait, c, err = 0;
-    char               *obj = NULL, *type = "LaserWriter", *zone = "*";
-    struct at_addr      addr;
-
-    extern char                *optarg;
-    extern int         optind;
-
-    memset(&addr, 0, sizeof(addr));
-    while (( c = getopt( ac, av, "p:s:A:" )) != EOF ) {
-       switch ( c ) {
-       case 'A':
-           if (!atalk_aton(optarg, &addr)) {
-             fprintf(stderr, "Bad address.\n");
-             exit(1);
-           }
-           break;
-       case 'p' :
-           printer = optarg;
-           break;
-
-       default :
-           fprintf( stderr, "Unknown option: '%c'\n", c );
-           err++;
-       }
-    }
-    if ( err ) {
-       usage( *av );
-    }
-    if ( printer == NULL && (( printer = paprc()) == NULL )) {
-       usage( *av );
-    }
-
-    /*
-     * Open connection.
-     */
-    if ( nbp_name( printer, &obj, &type, &zone ) < 0 ) {
-       fprintf( stderr, "%s: Bad name\n", printer );
-       exit( 1 );
-    }
-    if ( obj == NULL ) {
-       fprintf( stderr, "%s: Bad name\n", printer );
-       exit( 1 );
-    }
-    if ( nbp_lookup( obj, type, zone, &nn, 1, &addr ) <= 0 ) {
-       if ( errno != 0 ) {
-           perror( "nbp_lookup" );
-       } else {
-           fprintf( stderr, "%s:%s@%s: NBP Lookup failed\n", obj, type, zone );
-       }
-       exit( 1 );
-    }
-
-    if (( atp = atp_open( ATADDR_ANYPORT, &addr )) == NULL ) {
-       perror( "atp_open" );
-       exit( 1 );
-    }
-
-    if ( optind == ac ) {
-       getstatus( atp, &nn.nn_sat );
-       exit( 0 );
-    }
-    if ( optind - ac > 1 ) {
-       usage( *av );
-    }
-    wait = atoi( av[ optind ] );
-    for (;;) {
-       getstatus( atp, &nn.nn_sat );
-       sleep( wait );
-    }
-
-    return 0;
-}
-
-static void getstatus(ATP atp, struct sockaddr_at *sat)
-{
-    struct iovec       iov;
-    struct atp_block   atpb;
-    char               rbuf[ ATP_MAXDATA ];
-
-    cbuf[ 0 ] = 0;
-    cbuf[ 1 ] = PAP_SENDSTATUS;
-    cbuf[ 2 ] = cbuf[ 3 ] = 0;
-
-    atpb.atp_saddr = sat;
-    atpb.atp_sreqdata = cbuf;
-    atpb.atp_sreqdlen = 4;             /* bytes in SendStatus request */
-    atpb.atp_sreqto = 2;               /* retry timer */
-    atpb.atp_sreqtries = 5;            /* retry count */
-    if ( atp_sreq( atp, &atpb, 1, ATP_XO ) < 0 ) {
-       perror( "atp_sreq" );
-       exit( 1 );
-    }
-
-    iov.iov_base = rbuf;
-    iov.iov_len = sizeof( rbuf );
-    atpb.atp_rresiov = &iov;
-    atpb.atp_rresiovcnt = 1;
-    if ( atp_rresp( atp, &atpb ) < 0 ) {
-       perror( "atp_rresp" );
-       exit( 1 );
-    }
-
-    /* sanity */
-    if ( iov.iov_len < 8 ||
-           rbuf[ 1 ] != PAP_STATUS ) {
-       fprintf( stderr, "Bad response!\n" );
-       return; /* This is weird, since TIDs must match... */
-    }
-
-    printf( "%.*s\n", (int)iov.iov_len - 9, (char *) iov.iov_base + 9 );
-}
diff --git a/bin/psorder/.gitignore b/bin/psorder/.gitignore
deleted file mode 100644 (file)
index 379b39e..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Makefile
-Makefile.in
-psorder
-.deps
-.libs
-.gitignore
-pa.o psorder.o
diff --git a/bin/psorder/Makefile.am b/bin/psorder/Makefile.am
deleted file mode 100644 (file)
index b54fa36..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-# Makefile.am for bin/psorder
-
-INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/sys
-
-bin_PROGRAMS = psorder
-
-psorder_SOURCES = psorder.c pa.c
-psorder_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-noinst_HEADERS = psorder.h pa.h
diff --git a/bin/psorder/pa.c b/bin/psorder/pa.c
deleted file mode 100644 (file)
index b55b48a..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * $Id: pa.c,v 1.6 2009-10-14 02:24:05 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-/* This is used with pa.h */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-
-#include "pa.h"
-
-pa_buf_t *pa_init(int fd)
-{
-       pa_buf_t *h;
-       int rc;
-
-       h = (pa_buf_t *) malloc( sizeof( pa_buf_t ));
-       h->buf = (char *) malloc( PA_BUFBLK * 2 );
-       h->bufsz = PA_BUFBLK * 2;
-
-       if (( rc = read( fd, h->buf, PA_BUFBLK )) < 0 ) {
-               free(h->buf);
-               free(h);
-               return( NULL );
-       }
-
-       h->cur = h->buf - 1;
-       h->end = h->buf + rc - 1;
-       h->state = PA_NORMAL;
-       h->fd = fd;
-
-       return( h );
-}
-
-char *pa_gettok(pa_buf_t *h)
-{
-       h->state = PA_NORMAL;
-       h->tmp = *(h->cur);
-       *(h->cur) = 0;
-       return( h->mark );
-}
-
-char _pa_fixbuf(pa_buf_t *h)
-{
-       int rc;
-       char *t;
-
-       if ( h->state == PA_NORMAL ) {
-               *(h->buf) = *(h->cur);
-               h->cur = h->buf;
-       } else {
-               bcopy( h->mark, h->buf, h->end - h->mark + 1 );
-               h->cur = h->buf + ( h->cur - h->mark );
-               h->end = h->buf + ( h->end - h->mark );
-               h->mark = h->buf;
-       }
-
-       if ( h->bufsz - (( h->cur - h->buf ) + 1 ) < PA_BUFBLK ) {
-               t = h->buf;
-               h->buf = (char *) realloc( h->buf, h->bufsz + PA_BUFBLK );
-               h->bufsz += PA_BUFBLK;
-               h->mark = h->buf + ( h->mark - t );
-               h->cur = h->buf + ( h->cur - t );
-               h->end = h->buf + ( h->end - t );
-       }
-
-       if (( rc = read( h->fd, h->cur + 1, PA_BUFBLK )) <= 0 ) {
-               return( (char) 0 );
-       }
-
-       h->end = h->cur + rc;
-       return( *(++(h->cur)) );
-}
diff --git a/bin/psorder/pa.h b/bin/psorder/pa.h
deleted file mode 100644 (file)
index 7839970..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * $Id: pa.h,v 1.3 2009-10-13 22:55:36 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-/*
- * Functions to aid in parsing:
- *
- *     pa_init( fd )           Allocate and return a handle. Reads
- *                             from fd. Call this first, always.
- *     pa_getchar( h )         Return a single character or nul, 0,
- *                             to indicate end-of-file.
- *     pa_match( h )           Mark the character last read as the start
- *                             of a match.
- *     pa_gettok( h )          The match up to but excluding the last
- *                             character is returned.
- *     pa_cont( h )            Continue match with previous match. Call
- *                             immediately after pa_gettok() to get
- *                             correct behavior.
- *     pa_cancel( h )          Cancel previous match start.
- */
-
-#ifndef _PA_H
-#define _PA_H 1
-
-#ifndef FILE_H
-#include <stdio.h>
-#endif /* FILE_H */
-
-#define PA_BUFBLK      1024
-
-#define PA_NORMAL      0
-#define PA_MATCHING    1
-
-typedef struct pa_buf_t {
-       char *buf;
-       char *cur;
-       char *mark;
-       char *end;
-       int fd;
-       int state;
-       unsigned bufsz;
-       char tmp;
-} pa_buf_t;
-
-extern pa_buf_t *pa_init(int fd);
-extern char _pa_fixbuf(pa_buf_t *h);
-extern char *pa_gettok(pa_buf_t *h);
-
-#define pa_getchar(h)  (((h)->cur==(h)->end)?(_pa_fixbuf(h)):\
-                       (*(++((h)->cur))))
-#define pa_match(h)    ((h)->state=PA_MATCHING,(h)->mark=(h)->cur)
-#define pa_cont(h)     (*((h)->cur)=(h)->tmp,(h)->state=PA_MATCHING)
-#define pa_cancel(h)   ((h)->state=PA_NORMAL)
-#define pa_back(h)     (--((h)->cur))
-
-#endif /* _PA_H */
diff --git a/bin/psorder/psorder.c b/bin/psorder/psorder.c
deleted file mode 100644 (file)
index 4a37bab..0000000
+++ /dev/null
@@ -1,555 +0,0 @@
-/*
- * $Id: psorder.c,v 1.10 2010-04-12 14:28:47 franklahm Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/time.h>
-#include <sys/stat.h>
-#include <sys/uio.h>
-#include <sys/file.h>
-#include <ctype.h>
-#include <limits.h>
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#include <stdio.h>
-#include <string.h>
-#include <dirent.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include "pa.h"
-#include "psorder.h"
-
-#include <atalk/paths.h>
-
-/*
- *                     Global Variables
- */
-
-static u_char                  psbuf[ 8192 ];
-static struct psinfo_st                psinfo;
-static int                     orderflag, forceflag;
-
-static void
-filecleanup( int errorcode, int tfd, char *tfile)
-{
-
-/*
-       Close and unlink the temporary file.
- */
-
-    if ( tfd != 0 ) {
-       if ( close( tfd ) != 0 ) {
-           perror( tfile );
-           exit( errorcode );
-       }
-       if ( unlink( tfile ) != 0 ) {
-           perror( tfile );
-           exit( errorcode );
-       }
-    }
-
-    exit( errorcode );
-}
-
-static void
-filesetup( char *inputfile, int *infd, char *tfile, int *tfd)
-{
-    struct stat                st;
-    char               *template = _PATH_TMPPAGEORDER;
-
-    if ( strcmp( inputfile, STDIN ) != 0 ) {
-       if ( stat( inputfile, &st ) < 0 ) {
-           perror( inputfile );
-           filecleanup( -1, -1, "" );
-       }
-       if ( st.st_mode & S_IFMT & S_IFDIR ) {
-           fprintf( stderr, "%s is a directory.\n", inputfile );
-           filecleanup( 0, -1, "" );
-       }
-       if (( *infd = open( inputfile, O_RDONLY, 0600 )) < 0 ) {
-           perror( inputfile );
-           filecleanup( -1, -1, "" );
-       }
-    } else {
-       *infd = 0;
-    }
-
-#if DEBUG
-    fprintf( stderr, "Input file or stdin and stdout opened.\n" );
-    fprintf( stderr, "Input file descriptor is %d .\n", *infd );
-#endif /* DEBUG */
-
-/*
-       make temporary file
- */
-
-#if defined(NAME_MAX)
-    (void *)strncpy( tfile, template, NAME_MAX );
-#else
-    (void *)strncpy( tfile, template, MAXNAMLEN );
-#endif
-    if (( *tfd = mkstemp( tfile )) == -1 ) {
-       fprintf( stderr, "can't create temporary file %s\n", tfile );
-       filecleanup( -1, -1, "" );
-    }
-
-#if DEBUG
-    fprintf( stderr, "Temporary file %s created and opened.\n", tfile );
-    fprintf( stderr, "Temporary file descriptor is %d .\n", *tfd );
-#endif /* DEBUG */
-
-    psinfo.firstpage = NULL;
-    psinfo.lastpage = NULL;
-    psinfo.trailer = 0;
-    psinfo.pages.offset = 0;
-    psinfo.pages.end = 0;
-    psinfo.pages.num[0] = '\0';
-    psinfo.pages.order[0] = '\0';
-
-    return;
-}
-
-static struct pspage_st
-*getpspage(off_t off)
-{
-    struct pspage_st   *newpspage;
-
-    newpspage = (struct pspage_st *)malloc( sizeof( struct pspage_st )); 
-    if ( newpspage != NULL ) {
-       newpspage->offset = off;
-       newpspage->nextpage = NULL;
-       *newpspage->lable = '\0';
-       *newpspage->ord = '\0';
-    }
-    return( newpspage );
-}
-
-static int
-handletok(off_t count, char *token)
-{
-    int                        incdoc = 0;
-    struct pspage_st   *newpage;
-    char               *tmp;
-
-    if (( strncmp( PENDDOC, token, strlen( PENDDOC )) == 0 ) && incdoc ) {
-       incdoc--;
-#if DEBUG
-       fprintf( stderr, "found an EndDoc\n" );
-#endif /* DEBUG */
-
-    } else if ( strncmp( PBEGINDOC, token, strlen( PBEGINDOC )) == 0 ) {
-       incdoc++;
-#if DEBUG
-       fprintf( stderr, "found a BeginDoc\n" );
-#endif /* DEBUG */
-
-    } else if ( !incdoc && 
-           ( strncmp( PPAGE, token, strlen( PPAGE )) == 0 )) {
-#if DEBUG
-       fprintf( stderr, "found a Page\n" );
-#endif /* DEBUG */
-       if (( newpage = getpspage( count )) == NULL ) {
-           return( -1 );
-       }
-       if ( psinfo.firstpage == NULL ) {
-           newpage->prevpage = NULL;
-           psinfo.firstpage = newpage;
-       } else {
-           newpage->prevpage = psinfo.lastpage;
-           psinfo.lastpage->nextpage = newpage;
-       }
-       psinfo.lastpage = newpage;
-       while ( *token++ != ':' );
-       if (( tmp = strtok( token, WHITESPACE )) != NULL ) {
-           (void)strncpy( newpage->lable, tmp, NUMLEN );
-           if (( tmp = strtok( NULL, WHITESPACE )) != NULL ) {
-               (void)strncpy( newpage->ord, tmp, ORDLEN );
-           }
-       }
-#if DEBUG
-       fprintf( stderr, "page lable %s, page ord %s\n", newpage->lable,
-               newpage->ord );
-#endif /* DEBUG */
-
-    } else if ( !incdoc && 
-           ( strncmp( PPAGES, token, strlen( PPAGES )) == 0 )) {
-#if DEBUG
-       fprintf( stderr, "found a Pages\n" );
-#endif /* DEBUG */
-       psinfo.pages.offset = count;
-       psinfo.pages.end = strlen( token ) + count;
-       while ( *token++ != ':' );
-       while ( isspace( *token )) token++;
-       if ( strncmp( ATEND, token, strlen( ATEND )) == 0 ) {
-#if DEBUG
-           fprintf( stderr, "it is a Pages: (atend)\n" );
-#endif /* DEBUG */
-           psinfo.pages.offset = 0;
-           psinfo.pages.end = 0;
-       } else {
-           if (( tmp = strtok( token, WHITESPACE )) != NULL ) {
-               (void)strncpy( psinfo.pages.num, tmp, NUMLEN );
-               if (( tmp = strtok( NULL, WHITESPACE )) != NULL ) {
-                   (void)strncpy( psinfo.pages.order, tmp, ORDERLEN );
-               }
-           }
-#if DEBUG
-           fprintf( stderr, "number of pages %s\n", psinfo.pages.num );
-           fprintf( stderr, "order control number %s\n", psinfo.pages.order );
-#endif /* DEBUG */
-       }
-
-    } else if ( !incdoc && 
-           ( strncmp( PTRAILER, token, strlen( PTRAILER )) == 0 )) {
-#if DEBUG
-       fprintf( stderr, "found the Trailer\n" );
-#endif /* DEBUG */
-       if  ( psinfo.trailer == 0 ) {
-           psinfo.trailer = count;
-       }
-    }
-
-    return( 0 );
-}
-
-static void
-readps(int inputfd, int tempfd, char *tempfile)
-{
-    off_t              ccread = 0;
-    off_t              ccmatch;
-    char               *curtok = NULL;
-    FILE               *tempstream;
-    pa_buf_t           *pb;
-    int                        n;
-    char               c = -1;
-    char               pc, cc = 0;
-
-    pb = pa_init( inputfd );
-    if (( tempstream = fdopen( tempfd, "w" )) == NULL ) {
-       perror( "fdopen fails for tempfile" );
-       filecleanup( -1, tempfd, tempfile );
-    }
-
-    if (( c = pa_getchar( pb )) != 0 ) {
-       ccread++;
-       (void)putc( c, tempstream );
-       pc = 0;
-       cc = c;
-       pa_match( pb );
-       n = strlen( PPSADOBE );
-       for ( ; ( n > 0 ) && (( c = pa_getchar( pb )) != 0 ) ; n-- ) {
-           ccread++ ;
-           (void)putc( c, tempstream );
-           pc = cc;
-           cc = c;
-       }
-       curtok = pa_gettok( pb );
-    }
-#if DEBUG
-    fprintf( stderr, "%s\n", curtok );
-#endif /* DEBUG */
-
-/*
- * not postscript
- */
-    if ( strcmp( curtok, PPSADOBE ) != 0 ) {
-#if DEBUG
-    fprintf( stderr, "in the not postscript section of readps\n" );
-#endif /* DEBUG */
-       while (( c = pa_getchar( pb )) != 0 ) {
-           ccread++;
-           (void)putc( c, tempstream );
-           pc = cc;
-           cc = c;
-       }
-
-       (void)fflush( tempstream );
-       return;
-    }
-
-/*
- * postscript
- */
-#if DEBUG
-    fprintf( stderr, "in the postscript section of readps\n" );
-#endif /* DEBUG */
-    while (( c = pa_getchar( pb )) != 0 ) {
-       ccread++;
-       (void)putc( c, tempstream );
-       pc = cc;
-       cc = c;
-       if ((( pc == '\r' ) || ( pc == '\n' )) && ( cc == '%' )) {
-#if DEBUG
-           fprintf( stderr, "supposed start of match, cc = %c\n", cc );
-#endif /* DEBUG */
-           pa_match( pb );
-           ccmatch = ccread - 1;
-           while ( ( c = pa_getchar( pb ) ) ) {
-               if ( c != 0 ) {
-                   ccread++;
-                   (void)putc( c, tempstream );
-                   pc = cc;
-                   cc = c;
-               }
-               if (( c == '\r' ) || ( c == '\n' ) || ( cc == '\0' )) {
-                   curtok = pa_gettok( pb );
-#if DEBUG
-                   fprintf( stderr, "%s\n", curtok );
-#endif /* DEBUG */
-                   if ( handletok( ccmatch, curtok ) < 0 ) {
-                       perror( "malloc died" );
-                       filecleanup( -1, tempfd, tempfile );
-                   }
-                   break;
-               }
-               if ( c == 0 ) break;
-           }
-           if ( c == 0 ) break;
-       }
-    }
-
-    (void)fflush( tempstream );
-    return;
-}
-
-static void
-temp2out(int tempfd, char *tempfile, off_t length)
-{
-    int                        ccread;
-    int                        ccwrite;
-    int                        size;
-
-    while ( length > 0 ) {
-       if ( length > sizeof( psbuf )) {
-           size = sizeof( psbuf );
-       } else size = length;
-       if (( ccread = read( tempfd, psbuf, size )) > 0 ) {
-           size = ccread;
-           while ( ccread > 0 ) {
-               ccwrite = write( 1, psbuf, ccread );
-               if ( ccwrite < 0 ) {
-                   perror( "stdout" );
-                   filecleanup( ccwrite, tempfd, tempfile );
-               } else {
-                   ccread -= ccwrite;
-               }
-           }
-       }
-       if ( ccread < 0 ) {
-           perror( "temporary file" );
-           filecleanup( ccread, tempfd, tempfile );
-       }
-       length -= size;
-    }
-}
-
-static void
-writelable(int tempfd, char *tempfile, char *lable)
-{
-    char               line[256];
-    int                        ccwrite;
-    int                        linelen;
-    char               *argone;
-    char               *argtwo;
-
-    if ( strcmp( lable, PPAGES ) == 0 ) {
-       argone = psinfo.pages.num;
-       argtwo = psinfo.pages.order;
-    } else {
-       argone = argtwo = NULL;
-    }
-    (void)sprintf( line, "%s %s %s", lable, argone, argtwo );
-    linelen = strlen( line );
-
-    ccwrite = write( 1, line, linelen );
-    if ( ccwrite < 0 ) {
-       perror( "stdout" );
-       filecleanup( ccwrite, tempfd, tempfile );
-    } else {
-       linelen -= ccwrite;
-    }
-}
-
-static void
-writeps(int tempfd, char *tempfile)
-{
-    struct stat                st;
-    off_t              endofpage;
-    int                        order;
-
-    if ( stat( tempfile, &st ) < 0 ) {
-       perror( "stat failed" );
-       filecleanup( -1, tempfd, tempfile );
-    }
-    if ( psinfo.trailer == 0 ) {
-       endofpage = st.st_size;
-    } else endofpage = psinfo.trailer;
-
-    if (( psinfo.firstpage == NULL ) || 
-           ( psinfo.firstpage == psinfo.lastpage )) {
-       order = FORWARD;
-    } else if ( psinfo.pages.offset == 0 ) {
-       order = orderflag;
-    } else if (( strncmp( psinfo.pages.order, "", ORDERLEN ) == 0 ) ||
-           ( strncmp( psinfo.pages.order, "1", ORDERLEN ) == 0 )) {
-       order = orderflag;
-       if ( order == REVERSE ) strcpy( psinfo.pages.order, "-1" );
-    } else if ( strncmp( psinfo.pages.order, "-1", ORDERLEN ) == 0 ) {
-       if ( orderflag == FORWARD ) {
-           order = REVERSE;
-           strcpy( psinfo.pages.order, "1" );
-       } else order = FORWARD;
-    } else if (( strncmp( psinfo.pages.order, "0", ORDERLEN ) == 0 ) &&
-           forceflag ) {
-       order = orderflag;
-    } else order = FORWARD;
-
-    if ( order == FORWARD ) {
-       temp2out( tempfd, tempfile, st.st_size );
-    } else {
-/*
- *     output the header stuff and rewrite the $$Pages line
- *     if it is in the header and not %%Pages: (atend)
- */
-       if ( psinfo.firstpage->offset > 0 ) {
-           if (( psinfo.firstpage->offset > psinfo.pages.offset ) &&
-                   ( psinfo.pages.offset != 0 )) {
-               temp2out( tempfd, tempfile, psinfo.pages.offset );
-               writelable( tempfd, tempfile, PPAGES );
-               if ( lseek( tempfd, psinfo.pages.end, SEEK_SET ) < 0 ) {
-                   perror( tempfile );
-                   filecleanup( -1, tempfd, tempfile );
-               }
-               temp2out( tempfd, tempfile, 
-                       psinfo.firstpage->offset - psinfo.pages.end );
-           } else temp2out( tempfd, tempfile, psinfo.firstpage->offset );
-       }
-/*
- *     output the pages, last to first
- */
-       while ( psinfo.lastpage != NULL ) {
-           if ( lseek( tempfd, psinfo.lastpage->offset, SEEK_SET ) < 0 ) {
-               perror( tempfile );
-               filecleanup( -1, tempfd, tempfile );
-           }
-           temp2out( tempfd, tempfile, endofpage - psinfo.lastpage->offset );
-           endofpage = psinfo.lastpage->offset;
-           psinfo.lastpage = psinfo.lastpage->prevpage;
-           if ( psinfo.lastpage != NULL ) {
-               (void)free( psinfo.lastpage->nextpage );
-               psinfo.lastpage->nextpage = NULL;
-           }
-       }
-/*
- *     output the trailer stuff and rewrite the $$Pages line
- *     if it is in the trailer
- */
-       if ( psinfo.trailer != 0 ) {
-           if ( lseek( tempfd, psinfo.trailer, SEEK_SET ) < 0 ) {
-               perror( tempfile );
-               filecleanup( -1, tempfd, tempfile );
-           }
-           if ( psinfo.trailer < psinfo.pages.offset ) {
-               temp2out( tempfd, tempfile,
-                       psinfo.pages.offset - psinfo.trailer );
-               writelable( tempfd, tempfile, PPAGES );
-               if ( lseek( tempfd, psinfo.pages.end, SEEK_SET ) < 0 ) {
-                   perror( tempfile );
-                   filecleanup( -1, tempfd, tempfile );
-               }
-               temp2out( tempfd, tempfile, st.st_size - psinfo.pages.end );
-           } else temp2out( tempfd, tempfile, st.st_size - psinfo.trailer );
-       }
-    }
-
-    return;
-}
-
-static int
-psorder(char *path)
-{
-    int                        tempfd;
-    int                        inputfd;
-#if defined(NAME_MAX)
-    char               tempfile[NAME_MAX];
-#else
-    char               tempfile[MAXNAMLEN];
-#endif
-
-    filesetup( path, &inputfd, tempfile, &tempfd );
-    readps( inputfd, tempfd, tempfile );
-    if ( lseek( tempfd, REWIND, SEEK_SET ) < 0 ) {
-       perror( tempfile );
-       filecleanup( -1, tempfd, tempfile );
-    }
-    writeps( tempfd, tempfile );
-    filecleanup( 0, tempfd, tempfile );
-    return( 0 );
-}
-
-int main(int argc, char **argv)
-{
-    extern int optind;
-    char       *progname;
-    int                errflag = 0;
-    int                c;
-
-    while (( c = getopt( argc, argv, OPTSTR )) != -1 ) {
-       switch ( c ) {
-       case REVCHAR:
-           if ( orderflag ) errflag++;
-           else orderflag = REVERSE;
-           break;
-       case FORWCHAR:
-           if ( orderflag ) errflag++;
-           else orderflag = FORWARD;
-           break;
-       case FORCECHAR:
-           if ( forceflag ) errflag++;
-           else forceflag++;
-           break;
-       }
-    }
-    if ( errflag ) {
-       if (( progname = strrchr( argv[ 0 ], '/' )) == NULL ) {
-           progname = argv[ 0 ];
-       } else progname++;
-       fprintf( stderr, "usage: %s [-duf] [sourcefile]\n", progname );
-       return( -1 );
-    } else if ( !orderflag ) orderflag = FORWARD;
-
-    if ( optind >= argc ) {
-       return( psorder( STDIN ));
-    }
-    return( psorder( argv[ optind ] ));
-}
-
diff --git a/bin/psorder/psorder.h b/bin/psorder/psorder.h
deleted file mode 100644 (file)
index 5d810b4..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * $Id: psorder.h,v 1.3 2009-10-13 22:55:36 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef        STDIN
-#      define  STDIN   "-"
-#endif /* ! STDIN */
-#ifndef FALSE
-#      define  FALSE   0
-#      define  TRUE    1
-#endif /* ! FALSE */
-
-#define REVCHAR                'd'
-#define FORWCHAR       'u'
-#define FORCECHAR      'f'
-#define OPTSTR         "duf"
-
-#define WHITESPACE     " \t"
-#define ATEND          "(atend)"
-#define PPSADOBE       "%!PS-Adobe-"
-#define        PPAGE           "%%Page:"
-#define PPAGES         "%%Pages:"
-#define PTRAILER       "%%Trailer"
-#define PBEGINDOC      "%%BeginDocument:"
-#define PENDDOC                "%%EndDocument"
-#define PBEGINBIN      "%%BeginBinary:"
-#define PENDBIN                "%%EndBinary"
-
-#define REWIND         0L
-#define REVERSE                1
-#define FORWARD                2
-
-#define LABELLEN       32
-#define ORDLEN         4
-struct pspage_st {
-    struct pspage_st   *nextpage;
-    struct pspage_st   *prevpage;
-    off_t              offset;
-    char               lable[ LABELLEN ];
-    char               ord[ ORDLEN ];
-};
-
-#define NUMLEN         10
-#define ORDERLEN       3
-struct pages_st {
-    off_t              offset;
-    off_t              end;
-    char               num[ NUMLEN ];
-    char               order[ ORDERLEN ];
-};
-
-struct psinfo_st {
-    struct pspage_st   *firstpage;
-    struct pspage_st   *lastpage;
-    off_t              trailer;
-    struct pages_st    pages;
-};
-
index 38e7d336dc16ca5da52887e90b1358d5d0bf25c0..7cdd43c3995d31ee455910d872f9071d589085b6 100644 (file)
@@ -23,8 +23,8 @@
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/unicode.h>
 #include <atalk/logger.h>
 
index e6d1daeb4d5fa470bb677687d3fcfc2ec7ad726d..8a786a601dd4c1c641bc8c3d4c2bb8730e67eea6 100644 (file)
 #include <sys/param.h>
 #include <pwd.h>
 #include <dirent.h>
+#include <arpa/inet.h>
+
 #include <atalk/afp.h>
 #include <atalk/unicode.h>
 #include <atalk/util.h>
 #include <atalk/logger.h>
+#include <atalk/compat.h>
 
 #include "atalk/cnid.h"
 #ifndef MAXPATHLEN
@@ -57,7 +60,7 @@ char* to_charset;
 static charset_t ch_mac;
 char* mac_charset;
 static int usedots = 0;
-static u_int16_t conv_flags = 0;
+static uint16_t conv_flags = 0;
 static int dry_run = 0;
 static int verbose=0;
 char *cnid_type;
@@ -146,7 +149,7 @@ static char *convert_name(char *name, struct stat *st, cnid_t cur_did)
        size_t outlen = 0;
        unsigned char *p,*q;
        int require_conversion = 0;
-    u_int16_t    flags = conv_flags;
+    uint16_t    flags = conv_flags;
        cnid_t id;
 
        p = (unsigned char *)name;
index 1cd523f23a9a372920f744dbca39027a4601dd2c..76b98f3b45993438dce5160bcf203d46c4541953 100755 (executable)
--- a/bootstrap
+++ b/bootstrap
@@ -4,22 +4,26 @@ set -x
 
 rm -rf autom4te*.cache
 
+LIBTOOLIZE=libtoolize
+SYSNAME=`uname`
+if [ "x$SYSNAME" = "xDarwin" ] ; then
+  LIBTOOLIZE=glibtoolize
+fi
+
 # build it all.
 aclocal -I macros $ACLOCAL_FLAGS || exit 1
 autoheader || exit 1
-libtoolize --force --copy
+$LIBTOOLIZE --force --copy
 automake --include-deps --add-missing --foreign --copy || exit 1
 autoconf || exit 1
 
-# Original configure call was:
-#./configure --enable-maintainer-mode "$@"
-# However, according to:
-#  http://sources.redhat.com/autobook/autobook/autobook_43.html#SEC43
-# we need to have AM_MAINTAINER_MODE in configure.in in order to use
-# this feature.  It's not there at the moment, so I'm changing the
-# configure call.
-# And sometimes I don't want this to run.
-# [ -z "$NOEXECCONFIGURE" ] && ./configure "$@"
+# libevent
+cd libevent
+aclocal -I m4 && \
+       autoheader && \
+       $LIBTOOLIZE --force --copy && \
+       autoconf && \
+       automake --include-deps --add-missing --force-missing --copy || exit 1
 
 # Let's not fall off the end...
 exit 0
index 76bc5fa4ed85ce6df1c3e6e1e1f2645757c26e86..ec0b4097416de6cd166138540731526921984658 100644 (file)
@@ -1,6 +1,4 @@
-AppleVolumes.default
 Makefile
 Makefile.in
-afpd.conf
-.gitignore
 *.o
+afp.conf
diff --git a/config/AppleVolumes.default.tmpl b/config/AppleVolumes.default.tmpl
deleted file mode 100644 (file)
index d402389..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-# Netatalk 2.x afp volume cofiguration
-# This file looks empty when viewed with "vi".  In fact, there is one
-# '~', so users with no AppleVolumes file in their home directory get
-# their home directory by default.
-
-#
-# volume format:
-# :DEFAULT: [all of the default options except volume name]
-# path [name] [casefold:x] [options:z,l,j] \
-#   [allow:a,@b,c,d] [deny:a,@b,c,d] [dbpath:path] [password:p] \
-#   [rwlist:a,@b,c,d] [rolist:a,@b,c,d] [limitsize:value in bytes] \
-#   [preexec:cmd] [root_preexec:cmd] [postexec:cmd]  [root_postexec:cmd] \
-#   [allowed_hosts:IPv4 address[/IPv4 netmask bits]] \
-#   [denied_hosts:IPv4 address[/IPv4 netmask bits]] \
-#   ... more, see below ...
-#   
-# name:      volume name. it can't include the ':' character
-#
-
-#
-# variable substitutions:
-# you can use variables for both <path> and <name> now. here are the
-# rules:
-#     1) if you specify an unknown variable, it will not get converted. 
-#     2) if you specify a known variable, but that variable doesn't have
-#        a value, it will get ignored.
-#
-# the variables:
-# $b   -> basename of path
-# $c   -> client's ip or appletalk address
-# $d   -> volume pathname on server    
-# $f   -> full name (whatever's in the gecos field)
-# $g   -> group
-# $h   -> hostname 
-# $i   -> client ip without tcp port or appletalk network   
-# $s   -> server name (can be the hostname)
-# $u   -> username (if guest, it's whatever user guest is running as)
-# $v   -> volume name (either ADEID_NAME or basename of path)
-# $z   -> zone (may not exist)
-# $$   -> $
-#
-
-#
-# casefold options [syntax: casefold:option]:
-# tolower    -> lowercases names in both directions
-# toupper    -> uppercases names in both directions
-# xlatelower -> client sees lowercase, server sees uppercase
-# xlateupper -> client sees uppercase, server sees lowercase
-#
-# allow/deny/rwlist/rolist format [syntax: allow:user1,@group]:
-# user1,@group,user2  -> allows/denies access from listed users/groups
-#                        rwlist/rolist control whether or not the
-#                        volume is ro for those users.
-# allowed_hosts       -> Only listed hosts and networks are allowed,
-#                        all others are rejected. Example:
-#                        allowed_hosts:10.1.0.0/16,10.2.1.100
-# denied_hosts        -> Listed hosts and nets are rejected,
-#                        all others are allowed. Example:
-#                        denied_hosts: 192.168.100/24,10.1.1.1
-# preexec             -> command to be run when the volume is mounted,
-#                        ignore for user defined volumes
-# root_preexec        -> command to be run as root when the volume is mounted,
-#                        ignore for user defined volumes
-# postexec            -> command to be run when the volume is closed,
-#                        ignore for user defined volumes
-# root_postexec       -> command to be run as root when the volume is closed,
-#                        ignore for user defined volumes
-# veto                -> hide files and directories,where the path matches
-#                        one of the "/" delimited vetoed names. Matches are
-#                        partial, e.g. path is /abc/def/file and veto:/abc/
-#                        will hide the file.
-# adouble             -> specify the format of the metadata files.
-#                        default is "v2". netatalk 1.x used "v1".
-#                        "osx" cannot be treated normally any longer.
-# volsizelimit        -> size in MiB.  Useful for TimeMachine: limits the
-#                         reported volume size, thus preventing TM from using
-#                         the whole real disk space for backup.
-#                         Example: "volsizelimit:1000" would limit the
-#                         reported disk space to 1 GB.
-
-
-#
-# codepage options [syntax: options:charsetname]
-# volcharset          -> specifies the charset to be used
-#                        as the volume codepage
-#                        e.g. "UTF8", "UTF8-MAC", "ISO-8859-15"
-# maccharset          -> specifies the charset to be used
-#                        as the legacy client (<=Mac OS 9) codepage
-#                        e.g. "MAC_ROMAN", "MAC_CYRILLIC"
-#
-# perm                -> default permission value
-#                        OR with the client requested perm
-#                        Use with options:upriv
-# dperm               -> default permission value for directories
-#                        OR with the client requested perm
-#                        Use with options:upriv
-# fperm               -> default permission value for files
-#                        OR with the client requested perm
-#                        Use with options:upriv
-# umask               -> set perm mask
-#                        Use with options:upriv
-# dbpath:path         -> store the database stuff in the following path.
-# cnidserver:server[:port]
-#                     -> Query this servername or IP address
-#                        (default:localhost) and port (default: 4700)
-#                        for CNIDs. Only used with CNID backend "dbd".
-#                        This option here overrides any setting from
-#                        afpd.conf:cnidserver.
-# password:password   -> set a volume password (8 characters max)
-# cnidscheme:scheme   -> set the cnid scheme for the volume,
-#                        default is [:DEFAULT_CNID_SCHEME:]
-#                        available schemes: [:COMPILED_BACKENDS:]
-# ea                  -> none|auto|sys|ad
-#                        Specify how Extended Attributes are stores. default
-#                        is auto.
-#                        auto: try "sys" (by setting an EA on the shared
-#                              directory itself), fallback to "ad".  Requires
-#                              writable volume for performing the test.
-#                              Note: options:ro overwrites "auto" with "none."
-#                        sys:  Use filesystem EAs
-#                        ad:   Use files in AppleDouble directories
-#                        none: No EA support
-#
-
-#
-# miscellaneous options [syntax: options:option1,option2]:
-# tm                  -> enable TimeMachine support
-# prodos              -> make compatible with appleII clients.
-# crlf                -> enable crlf translation for TEXT files.
-# noadouble           -> don't create .AppleDouble unless a resource
-#                        fork needs to be created.
-# ro                  -> mount the volume as read-only.
-# mswindows           -> enforce filename restrictions imposed by MS
-#                        Windows. this will also invoke a default
-#                        codepage (iso8859-1) if one isn't already 
-#                        specified.
-# nohex               -> don't do :hex translations for anything
-#                        except dot files. specify usedots as well if
-#                        you want that turned off. note: this option
-#                         makes the / character illegal.
-# usedots             -> don't do :hex translation for dot files. note: when 
-#                        this option gets set, certain file names
-#                        become illegal. these are .Parent and
-#                        anything that starts with .Apple.
-# invisibledots       -> don't do :hex translation for dot files. note: when 
-#                        this option gets set, certain file names
-#                        become illegal. these are .Parent and
-#                        anything that starts with .Apple. also, dot
-#                        files created on the unix side are marked invisible. 
-# limitsize           -> limit disk size reporting to 2GB. this is
-#                        here for older macintoshes using newer
-#                        appleshare clients. yucko.
-# nofileid            -> don't advertise createfileid, resolveid, deleteid 
-#                        calls
-# root_preexec_close  -> a non-zero return code from root_preexec close the 
-#                        volume being mounted.
-# preexec_close       -> a non-zero return code from preexec close the 
-#                        volume being mounted.
-# nostat              -> don't stat volume path when enumerating volumes list
-# upriv               -> use unix privilege.  
-# illegalseq          -> encode illegal sequence in filename asis,
-#                        ex "\217-", which is not a valid SHIFT-JIS char,
-#                        is encoded  as U\217 -
-# nocnidcache         -> Don't store and read CNID to/from AppleDouble file.
-#                        This should not be used as it also prevents a CNID
-#                        database rebuild with `dbd`!
-# caseinsensitive     -> The underlying FS is case insensitive (only 
-#                        test with JFS in OS2 mode)
-# dropbox             -> Allows a volume to be declared as being a "dropbox."
-#                        Note that netatalk must be compiled with dropkludge
-#                        support for this to function. Warning: This option
-#                        is deprecated and might not work as expected.
-# dropkludge          -> same as "dropbox"
-# nodev               -> always use 0 for device number, helps when the
-#                        device number is not constant across a reboot,
-#                        cluster, ...
-#
-
-# The line below sets some DEFAULT, starting with Netatalk 2.1.
-:DEFAULT: options:upriv,usedots
-
-# The "~" below indicates that Home directories are visible by default.
-# If you do not wish to have people accessing their Home directories,
-# please put a pound sign in front of the tilde or delete it.
-~
-
-# End of File
diff --git a/config/AppleVolumes.system b/config/AppleVolumes.system
deleted file mode 100644 (file)
index ee79b9c..0000000
+++ /dev/null
@@ -1,326 +0,0 @@
-# Netatalk 2.x afp volume configuration
-###
-### Delete a '#' character at the head of line if you need.
-### If clients are Mac OS X only, it is not especially necessary.
-### However, it might be useful for Mac OS 9 or earlier.
-### 
-### Use at your own risk.  No guarantees express or implied.
-###
-### Try to use MacPerl script 'ICDumpSuffixMap' included in /usr/doc 
-### to download file mapping list from your Internet Config Preference.
-###
-### inoue@ma.ns.musashi-tech.ac.jp.
-###
-
-### default translation -- note that CR <-> LF translation is done on all
-### files of type TEXT (if crlf is set in volume's options).  
-### The first line turns off translation for files of unknown type, 
-### the third turns this translation on.
-###.         "????"  "????"      Unix Binary                    Unix                      application/octet-stream
-###.         "BINA"  "UNIX"      Unix Binary                    Unix                      application/octet-stream
-###.         "TEXT"  "ttxt"      ASCII Text                     SimpleText                text/plain
-
-#.1st      "TEXT"  "ttxt"      Text Readme                    SimpleText                application/text
-#.669      "6669"  "SNPL"      669 MOD Music                  PlayerPro
-#.8med     "STrk"  "SCPL"      Amiga OctaMed music            SoundApp
-#.8svx     "8SVX"  "SCPL"      Amiga 8-bit sound              SoundApp
-#.a        "TEXT"  "ttxt"      Assembly Source                SimpleText
-#.aif      "AIFF"  "SCPL"      AIFF Sound                     SoundApp                  audio/x-aiff
-#.aifc     "AIFC"  "SCPL"      AIFF Sound Compressed          SoundApp                  audio/x-aiff
-#.aiff     "AIFF"  "SCPL"      AIFF Sound                     SoundApp                  audio/x-aiff
-#.al       "ALAW"  "SCPL"      ALAW Sound                     SoundApp
-#.ani      "ANIi"  "GKON"      Animated NeoChrome             GraphicConverter
-#.apd      "TEXT"  "ALD3"      Aldus Printer Description      Aldus PageMaker
-#.arc      "mArc"  "SITx"      PC ARChive                     StuffIt Expander
-#.arj      "BINA"  "DArj"      ARJ Archive                    DeArj
-#.arr      "ARR "  "GKON"      Amber ARR image                GraphicConverter
-#.art      "ART "  "GKON"      First Publisher                GraphicConverter
-#.asc      "TEXT"  "ttxt"      ASCII Text                     SimpleText                text/plain
-#.ascii    "TEXT"  "ttxt"      ASCII Text                     SimpleText                text/plain
-#.asf      "ASF_"  "Ms01"      Netshow Player                 Netshow Server            video/x-ms-asf
-#.asm      "TEXT"  "ttxt"      Assembly Source                SimpleText
-#.asx      "ASX_"  "Ms01"      Netshow Player                 Netshow Server            video/x-ms-asf
-#.au       "ULAW"  "TVOD"      Sun Sound                      QuickTime Player          audio/basic
-#.avi      "VfW "  "TVOD"      AVI Movie                      QuickTime Player          video/avi
-#.bar      "BARF"  "S691"      Unix BAR Archive               SunTar
-#.bas      "TEXT"  "ttxt"      BASIC Source                   SimpleText
-#.bat      "TEXT"  "ttxt"      MS-DOS Batch File              SimpleText
-#.bga      "BMPp"  "ogle"      OS/2 Bitmap                    PictureViewer
-#.bib      "TEXT"  "ttxt"      BibTex Bibliography            SimpleText
-#.bin      "SIT!"  "SITx"      MacBinary                      StuffIt Expander          application/macbinary
-#.binary   "BINA"  "hDmp"      Untyped Binary Data            HexEdit                   application/octet-stream
-#.bmp      "BMPp"  "ogle"      Windows Bitmap                 PictureViewer
-#.boo      "TEXT"  "ttxt"      BOO encoded                    SimpleText
-#.bst      "TEXT"  "ttxt"      BibTex Style                   SimpleText
-#.bw       "SGI "  "GKON"      SGI Image                      GraphicConverter
-#.c        "TEXT"  "CWIE"      C Source                       CodeWarrior
-#.cgm      "CGMm"  "GKON"      Computer Graphics Meta         GraphicConverter
-#.class    "Clss"  "CWIE"      Java Class File                CodeWarrior
-#.clp      "CLPp"  "GKON"      Windows Clipboard              GraphicConverter
-#.cmd      "TEXT"  "ttxt"      OS/2 Batch File                SimpleText
-#.com      "PCFA"  "SWIN"      MS-DOS Executable              SoftWindows
-#.cp       "TEXT"  "CWIE"      C++ Source                     CodeWarrior
-#.cpp      "TEXT"  "CWIE"      C++ Source                     CodeWarrior
-#.cpt      "PACT"  "SITx"      Compact Pro Archive            StuffIt Expander
-#.csv      "TEXT"  "XCEL"      Comma Separated Vars           Excel
-#.ct       "..CT"  "GKON"      Scitex-CT                      GraphicConverter
-#.cut      "Halo"  "GKON"      Dr Halo Image                  GraphicConverter
-#.cvs      "drw2"  "DAD2"      Canvas Drawing                 Canvas
-#.dbf      "COMP"  "FOX+"      DBase Document                 FoxBase+
-#.dcx      "DCXx"  "GKON"      Some PCX Images                GraphicConverter
-#.dif      "TEXT"  "XCEL"      Data Interchange Format        Excel
-#.diz      "TEXT"  "R*Ch"      BBS Descriptive Text           BBEdit
-#.dl       "DL  "  "AnVw"      DL Animation                   MacAnim Viewer
-#.dll      "PCFL"  "SWIN"      Windows DLL                    SoftWindows
-#.doc      "WDBN"  "MSWD"      Word Document                  Microsoft Word            application/msword
-#.dot      "sDBN"  "MSWD"      Word for Windows Template      Microsoft Word
-#.dvi      "ODVI"  "xdvi"      TeX DVI Document               xdvi                      application/x-dvi
-#.dwt      "TEXT"  "DmWr"      Dreamweaver Template           Dreamweaver
-#.dxf      "TEXT"  "SWVL"      AutoCAD 3D Data                Swivel Pro
-#.eps      "EPSF"  "vgrd"      Postscript                     LaserWriter 8             application/postscript
-#.epsf     "EPSF"  "vgrd"      Postscript                     LaserWriter 8             application/postscript
-#.etx      "TEXT"  "ezVu"      SEText                         Easy View                 text/x-setext
-#.evy      "EVYD"  "ENVY"      Envoy Document                 Envoy
-#.exe      "PCFA"  "SWIN"      MS-DOS Executable              SoftWindows
-#.faq      "TEXT"  "ttxt"      ASCII Text                     SimpleText                text/x-usenet-faq
-#.fit      "FITS"  "GKON"      Flexible Image Transport       GraphicConverter          image/x-fits
-#.flc      "FLI "  "TVOD"      FLIC Animation                 QuickTime Player
-#.fli      "FLI "  "TVOD"      FLI Animation                  QuickTime Player
-#.fm       "FMPR"  "FMPR"      FileMaker Pro Database         FileMaker Pro
-#.for      "TEXT"  "MPS "      Fortran Source                 MPW Shell
-#.fts      "FITS"  "GKON"      Flexible Image Transport       GraphicConverter
-#.gem      "GEM-"  "GKON"      GEM Metafile                   GraphicConverter
-#.gif      "GIFf"  "ogle"      GIF Picture                    PictureViewer             image/gif
-#.gl       "GL  "  "AnVw"      GL Animation                   MacAnim Viewer
-#.grp      "GRPp"  "GKON"      GRP Image                      GraphicConverter
-#.gz       "SIT!"  "SITx"      Gnu ZIP Archive                StuffIt Expander          application/x-gzip
-#.h        "TEXT"  "CWIE"      C Include File                 CodeWarrior
-#.hcom     "FSSD"  "SCPL"      SoundEdit Sound ex SOX         SoundApp
-#.hp       "TEXT"  "CWIE"      C Include File                 CodeWarrior
-#.hpgl     "HPGL"  "GKON"      HP GL/2                        GraphicConverter
-#.hpp      "TEXT"  "CWIE"      C Include File                 CodeWarrior
-#.hqx      "TEXT"  "SITx"      BinHex                         StuffIt Expander          application/mac-binhex40
-#.htm      "TEXT"  "MOSS"      HyperText                      Netscape Communicator     text/html
-#.html     "TEXT"  "MOSS"      HyperText                      Netscape Communicator     text/html
-#.i3       "TEXT"  "R*ch"      Modula 3 Interface             BBEdit
-#.ic1      "IMAG"  "GKON"      Atari Image                    GraphicConverter
-#.ic2      "IMAG"  "GKON"      Atari Image                    GraphicConverter
-#.ic3      "IMAG"  "GKON"      Atari Image                    GraphicConverter
-#.icn      "ICO "  "GKON"      Windows Icon                   GraphicConverter
-#.ico      "ICO "  "GKON"      Windows Icon                   GraphicConverter
-#.ief      "IEF "  "GKON"      IEF image                      GraphicConverter          image/ief
-#.iff      "ILBM"  "GKON"      Amiga IFF Image                GraphicConverter
-#.ilbm     "ILBM"  "GKON"      Amiga ILBM Image               GraphicConverter
-#.image    "dImg"  "ddsk"      Apple DiskCopy Image           Disk Copy
-#.img      "IMGg"  "GKON"      GEM bit image/XIMG             GraphicConverter
-#.ini      "TEXT"  "ttxt"      Windows INI File               SimpleText
-#.java     "TEXT"  "CWIE"      Java Source File               CodeWarrior
-#.jfif     "JPEG"  "ogle"      JFIF Image                     PictureViewer
-#.jpe      "JPEG"  "ogle"      JPEG Picture                   PictureViewer             image/jpeg
-#.jpeg     "JPEG"  "ogle"      JPEG Picture                   PictureViewer             image/jpeg
-#.jpg      "JPEG"  "ogle"      JPEG Picture                   PictureViewer             image/jpeg
-#.latex    "TEXT"  "OTEX"      Latex                          OzTex                     application/x-latex
-#.lbm      "ILBM"  "GKON"      Amiga IFF Image                GraphicConverter
-#.lha      "LHA "  "SITx"      LHArc Archive                  StuffIt Expander
-#.lzh      "LHA "  "SITx"      LHArc Archive                  StuffIt Expander
-#.m1a      "MPEG"  "TVOD"      MPEG-1 audiostream             MoviePlayer               audio/x-mpeg
-#.m1s      "MPEG"  "TVOD"      MPEG-1 systemstream            MoviePlayer
-#.m1v      "M1V "  "TVOD"      MPEG-1 IPB videostream         MoviePlayer               video/mpeg
-#.m2       "TEXT"  "R*ch"      Modula 2 Source                BBEdit
-#.m2v      "MPG2"  "MPG2"      MPEG-2 IPB videostream         MPEG2decoder
-#.m3       "TEXT"  "R*ch"      Modula 3 Source                BBEdit
-#.mac      "PICT"  "ogle"      PICT Picture                   PictureViewer             image/x-pict
-#.mak      "TEXT"  "R*ch"      Makefile                       BBEdit
-#.mcw      "WDBN"  "MSWD"      Mac Word Document              Microsoft Word
-#.me       "TEXT"  "ttxt"      Text Readme                    SimpleText
-#.med      "STrk"  "SCPL"      Amiga MED Sound                SoundApp
-#.mf       "TEXT"  "*MF*"      Metafont                       Metafont
-#.mid      "Midi"  "TVOD"      MIDI Music                     MoviePlayer
-#.midi     "Midi"  "TVOD"      MIDI Music                     MoviePlayer
-#.mif      "TEXT"  "Fram"      FrameMaker MIF                 FrameMaker                application/x-framemaker
-#.mime     "TEXT"  "SITx"      MIME Message                   StuffIt Expander          message/rfc822
-#.ml       "TEXT"  "R*ch"      ML Source                      BBEdit
-#.mod      "STrk"  "SCPL"      MOD Music                      SoundApp
-#.mol      "TEXT"  "RSML"      MDL Molfile                    RasMac
-#.moov     "MooV"  "TVOD"      QuickTime Movie                MoviePlayer               video/quicktime
-#.mov      "MooV"  "TVOD"      QuickTime Movie                MoviePlayer               video/quicktime
-#.mp2      "MPEG"  "TVOD"      MPEG-1 audiostream             MoviePlayer               audio/x-mpeg
-#.mp3      "MPG3"  "TVOD"      MPEG-3 audiostream             MoviePlayer               audio/x-mpeg
-#.mpa      "MPEG"  "TVOD"      MPEG-1 audiostream             MoviePlayer               audio/x-mpeg
-#.mpe      "MPEG"  "TVOD"      MPEG Movie of some sort        MoviePlayer               video/mpeg
-#.mpeg     "MPEG"  "TVOD"      MPEG Movie of some sort        MoviePlayer               video/mpeg
-#.mpg      "MPEG"  "TVOD"      MPEG Movie of some sort        MoviePlayer               video/mpeg
-#.msp      "MSPp"  "GKON"      Microsoft Paint                GraphicConverter
-#.mtm      "MTM "  "SNPL"      MultiMOD Music                 PlayerPro
-#.mw       "MW2D"  "MWII"      MacWrite Document              MacWrite II               application/macwriteii
-#.mwii     "MW2D"  "MWII"      MacWrite Document              MacWrite II               application/macwriteii
-#.neo      "NeoC"  "GKON"      Atari NeoChrome                GraphicConverter
-#.nfo      "TEXT"  "ttxt"      Info Text                      SimpleText                application/text
-#.nst      "STrk"  "SCPL"      MOD Music                      SoundApp
-#.obj      "PCFL"  "SWIN"      Object (DOS/Windows)           SoftWindows
-#.oda      "ODIF"  "ODA "      ODA Document                   MacODA XTND Translator    application/oda
-#.okt      "OKTA"  "SCPL"      Oktalyser MOD Music            SoundApp
-#.out      "BINA"  "hDmp"      Output File                    HexEdit
-#.ovl      "PCFL"  "SWIN"      Overlay (DOS/Windows)          SoftWindows
-#.p        "TEXT"  "CWIE"      Pascal Source                  CodeWarrior
-#.pac      "STAD"  "GKON"      Atari STAD Image               GraphicConverter
-#.pas      "TEXT"  "CWIE"      Pascal Source                  CodeWarrior
-#.pbm      "PPGM"  "GKON"      Portable Bitmap                GraphicConverter          image/x-portable-bitmap
-#.pc1      "Dega"  "GKON"      Atari Degas Image              GraphicConverter
-#.pc2      "Dega"  "GKON"      Atari Degas Image              GraphicConverter
-#.pc3      "Dega"  "GKON"      Atari Degas Image              GraphicConverter
-#.pcs      "PICS"  "GKON"      Animated PICTs                 GraphicConverter
-#.pct      "PICT"  "ogle"      PICT Picture                   PictureViewer             image/x-pict
-#.pcx      "PCXx"  "GKON"      PC PaintBrush                  GraphicConverter
-#.pdb      "TEXT"  "RSML"      Brookhaven PDB file            RasMac
-#.pdf      "PDF "  "CARO"      Portable Document Format       Acrobat Reader            application/pdf
-#.pdx      "TEXT"  "ALD5"      Printer Description            PageMaker
-#.pf       "CSIT"  "SITx"      Private File                   StuffIt Expander 
-#.pgm      "PPGM"  "GKON"      Portable Graymap               GraphicConverter          image/x-portable-graymap
-#.pi1      "Dega"  "GKON"      Atari Degas Image              GraphicConverter
-#.pi2      "Dega"  "GKON"      Atari Degas Image              GraphicConverter
-#.pi3      "Dega"  "GKON"      Atari Degas Image              GraphicConverter
-#.pic      "PICT"  "ogle"      PICT Picture                   PictureViewer             image/x-pict
-#.pict     "PICT"  "ogle"      PICT Picture                   PictureViewer             image/x-macpict
-#.pit      "PIT "  "SITx"      PackIt Archive                 StuffIt Expander
-#.pkg      "HBSF"  "SITx"      AppleLink Package              StuffIt Expander
-#.pl       "TEXT"  "McPL"      Perl Source                    MacPerl
-#.plt      "HPGL"  "GKON"      HP GL/2                        GraphicConverter
-#.pm       "PMpm"  "GKON"      Bitmap from xv                 GraphicConverter
-#.pm3      "ALB3"  "ALD3"      PageMaker 3 Document           PageMaker
-#.pm4      "ALB4"  "ALD4"      PageMaker 4 Document           PageMaker
-#.pm5      "ALB5"  "ALD5"      PageMaker 5 Document           PageMaker
-#.png      "PNG "  "ogle"      Portable Network Graphic       PictureViewer
-#.pntg     "PNTG"  "ogle"      Macintosh Painting             PictureViewer
-#.ppd      "TEXT"  "ALD5"      Printer Description            PageMaker
-#.ppm      "PPGM"  "GKON"      Portable Pixmap                GraphicConverter          image/x-portable-pixmap
-#.prn      "TEXT"  "R*ch"      Printer Output File            BBEdit
-#.ps       "TEXT"  "vgrd"      PostScript                     LaserWriter 8             application/postscript
-#.psd      "8BPS"  "8BIM"      PhotoShop Document             Photoshop
-#.pt4      "ALT4"  "ALD4"      PageMaker 4 Template           PageMaker
-#.pt5      "ALT5"  "ALD5"      PageMaker 5 Template           PageMaker
-#.pxr      "PXR "  "8BIM"      Pixar Image                    Photoshop
-#.qdv      "QDVf"  "GKON"      QDV image                      GraphicConverter
-#.qt       "MooV"  "TVOD"      QuickTime Movie                MoviePlayer               video/quicktime
-#.qxd      "XDOC"  "XPR3"      QuarkXpress Document           QuarkXpress
-#.qxt      "XTMP"  "XPR3"      QuarkXpress Template           QuarkXpress
-#.raw      "BINA"  "GKON"      Raw Image                      GraphicConverter
-#.readme   "TEXT"  "ttxt"      Text Readme                    SimpleText                application/text
-#.rgb      "SGI "  "GKON"      SGI Image                      GraphicConverter          image/x-rgb
-#.rgba     "SGI "  "GKON"      SGI Image                      GraphicConverter          image/x-rgb
-#.rib      "TEXT"  "RINI"      Renderman 3D Data              Renderman
-#.rif      "RIFF"  "GKON"      RIFF Graphic                   GraphicConverter
-#.rle      "RLE "  "GKON"      RLE image                      GraphicConverter
-#.rme      "TEXT"  "ttxt"      Text Readme                    SimpleText
-#.rpl      "FRL!"  "REP!"      Replica Document               Replica
-#.rsc      "rsrc"  "RSED"      Resource File                  ResEdit
-#.rsrc     "rsrc"  "RSED"      Resource File                  ResEdit
-#.rtf      "TEXT"  "MSWD"      Rich Text Format               Microsoft Word            application/rtf
-#.rtx      "TEXT"  "R*ch"      Rich Text                      BBEdit                    text/richtext
-#.s3m      "S3M "  "SNPL"      ScreamTracker 3 MOD            PlayerPro
-#.scc      "MSX "  "GKON"      MSX pitcure                    GraphicConverter
-#.scg      "RIX3"  "GKON"      ColoRIX                        GraphicConverter
-#.sci      "RIX3"  "GKON"      ColoRIX                        GraphicConverter
-#.scp      "RIX3"  "GKON"      ColoRIX                        GraphicConverter
-#.scr      "RIX3"  "GKON"      ColoRIX                        GraphicConverter
-#.scu      "RIX3"  "GKON"      ColoRIX                        GraphicConverter
-#.sea      "APPL"  "????"      Self-Extracting Archive        Self Extracting Archive
-#.sf       "IRCM"  "SDHK"      IRCAM Sound                    SoundHack
-#.sgi      ".SGI"  "ogle"      SGI Image                      PictureViewer
-#.sha      "TEXT"  "UnSh"      Unix Shell Archive             UnShar                    application/x-shar
-#.shar     "TEXT"  "UnSh"      Unix Shell Archive             UnShar                    application/x-shar
-#.shp      "SHPp"  "GKON"      Printmaster Icon Library       GraphicConverter
-#.sit      "SIT!"  "SITx"      StuffIt 1.5.1 Archive          StuffIt Expander          application/x-stuffit
-#.sithqx   "TEXT"  "SITx"      BinHexed StuffIt Archive       StuffIt Expander          application/mac-binhex40
-#.six      "SIXE"  "GKON"      SIXEL image                    GraphicConverter
-#.slk      "TEXT"  "XCEL"      SYLK Spreadsheet               Excel
-#.snd      "BINA"  "SCPL"      Sound of various types         SoundApp
-#.spc      "Spec"  "GKON"      Atari Spectrum 512             GraphicConverter
-#.sr       "SUNn"  "GKON"      Sun Raster Image               GraphicConverter
-#.sty      "TEXT"  "*TEX"      TeX Style                      Textures
-#.sun      "SUNn"  "GKON"      Sun Raster Image               GraphicConverter
-#.sup      "SCRN"  "GKON"      StartupScreen                  GraphicConverter
-#.svx      "8SVX"  "SCPL"      Amiga IFF Sound                SoundApp
-#.syk      "TEXT"  "XCEL"      SYLK Spreadsheet               Excel
-#.sylk     "TEXT"  "XCEL"      SYLK Spreadsheet               Excel
-#.tar      "TARF"  "SITx"      Unix Tape ARchive              StuffIt Expander          application/x-tar
-#.targa    "TPIC"  "GKON"      Truevision Image               GraphicConverter
-#.taz      "ZIVU"  "SITx"      Compressed Tape ARchive        StuffIt Expander          application/x-compress
-#.tex      "TEXT"  "OTEX"      TeX Document                   OzTeX                     application/x-tex
-#.texi     "TEXT"  "OTEX"      TeX Document                   OzTeX
-#.texinfo  "TEXT"  "OTEX"      TeX Document                   OzTeX                     application/x-texinfo
-#.text     "TEXT"  "ttxt"      ASCII Text                     SimpleText                text/plain
-#.tga      "TPIC"  "GKON"      Truevision Image               GraphicConverter
-#.tgz      "Gzip"  "SITx"      Gnu ZIPed Tape ARchive         StuffIt Expander          application/x-gzip
-#.tif      "TIFF"  "ogle"      TIFF Picture                   PictureViewer             image/tiff
-#.tiff     "TIFF"  "ogle"      TIFF Picture                   PictureViewer             image/tiff
-#.tny      "TINY"  "GKON"      Atari TINY Bitmap              GraphicConverter
-#.tsv      "TEXT"  "XCEL"      Tab Separated Values           Excel                     text/tab-separated-values
-#.tx8      "TEXT"  "ttxt"      8-bit ASCII Text               SimpleText
-#.txt      "TEXT"  "ttxt"      ASCII Text                     SimpleText                text/plain
-#.ul       "ULAW"  "TVOD"      Mu-Law Sound                   MoviePlayer               audio/basic
-#.url      "AURL"  "Arch"      URL Bookmark                   Anarchie                  message/external-body
-#.uu       "TEXT"  "SITx"      UUEncode                       StuffIt Expander
-#.uue      "TEXT"  "SITx"      UUEncode                       StuffIt Expander
-#.vff      "VFFf"  "GKON"      DESR VFF Greyscale Image       GraphicConverter
-#.vga      "BMPp"  "ogle"      OS/2 Bitmap                    PictureViewer
-#.voc      "VOC "  "SCPL"      VOC Sound                      SoundApp
-#.w51      ".WP5"  "WPC2"      WordPerfect PC 5.1 Doc         WordPerfect               application/wordperfect5.1
-#.wav      "WAVE"  "TVOD"      Windows WAV Sound              MoviePlayer               audio/x-wav
-#.wk1      "XLBN"  "XCEL"      Lotus Spreadsheet r2.1         Excel
-#.wks      "XLBN"  "XCEL"      Lotus Spreadsheet r1.x         Excel
-#.wmf      "WMF "  "GKON"      Windows Metafile               GraphicConverter
-#.wp       ".WP5"  "WPC2"      WordPerfect PC 5.1 Doc         WordPerfect               application/wordperfect5.1
-#.wp4      ".WP4"  "WPC2"      WordPerfect PC 4.2 Doc         WordPerfect
-#.wp5      ".WP5"  "WPC2"      WordPerfect PC 5.x Doc         WordPerfect               application/wordperfect5.1
-#.wp6      ".WP6"  "WPC2"      WordPerfect PC 6.x Doc         WordPerfect
-#.wpg      "WPGf"  "GKON"      WordPerfect Graphic            GraphicConverter
-#.wpm      "WPD1"  "WPC2"      WordPerfect Mac                WordPerfect
-#.wri      "WDBN"  "MSWD"      MS Write/Windows               Microsoft Word
-#.wve      "BINA"  "SCPL"      PSION sound                    SoundApp
-#.x10      "XWDd"  "GKON"      X-Windows Dump                 GraphicConverter          image/x-xwd
-#.x11      "XWDd"  "GKON"      X-Windows Dump                 GraphicConverter          image/x-xwd
-#.xbm      "XBM "  "GKON"      X-Windows Bitmap               GraphicConverter          image/x-xbm
-#.xl       "XLS "  "XCEL"      Excel Spreadsheet              Excel
-#.xlc      "XLC "  "XCEL"      Excel Chart                    Excel
-#.xlm      "XLM "  "XCEL"      Excel Macro                    Excel
-#.xls      "XLS "  "XCEL"      Excel Spreadsheet              Excel
-#.xlw      "XLW "  "XCEL"      Excel Workspace                Excel
-#.xm       "XM  "  "SNPL"      FastTracker MOD Music          PlayerPro
-#.xpm      "XPM "  "GKON"      X-Windows Pixmap               GraphicConverter          image/x-xpm
-#.xwd      "XWDd"  "GKON"      X-Windows Dump                 GraphicConverter          image/x-xwd
-#.Z        "ZIVU"  "SITx"      Unix Compress Archive          StuffIt Expander          application/x-compress
-#.zip      "ZIP "  "SITx"      PC ZIP Archive                 StuffIt Expander          application/zip
-#.zoo      "Zoo "  "Booz"      Zoo Archive                    MacBooz
-
-### Last Updated Jan 2, 2002
-### Use at your own risk.  Take care !
-###
-### I'd like to dedicate this as follows code to Miss.Tamaki Imazu
-###
-### Kazuhiko Okudaira the Nursery Teacher
-### kokudaira@hotmail.com
-
-#.bld  "BLD "  "GKON"  BLD                            GraphicConverter
-#.bum  ".bMp"  "GKON"  QuickTime Importer(QuickDraw)  GraphicConverter
-#.cel  "CEL "  "GKON"  KISS CEL                       GraphicConverter
-#.cur  "CUR "  "GKON"  Windows Cursor                 GraphicConverter
-#.cwj  "CWSS"  "cwkj"  ClarisWorks Document           ClarisWorks 4.0
-#.dat  "TCLl"  "GKON"  TCL image                      GraphicConverter
-#.hr   "TR80"  "GKON"  TSR-80 HR                      GraphicConverter
-#.iss  "ISS "  "GKON"  ISS                            GraphicConverter
-#.jif  "JIFf"  "GKON"  JIF99a                         GraphicConverter
-#.lwf  "lwfF"  "GKON"  LuraWave(LWF)                  GraphicConverter
-#.mbm  "MBM "  "GKON"  PSION 5(MBM)                   GraphicConverter
-#.ngg  "NGGC"  "GKON"  Mobile Phone(Nokia)Format      GraphicConverter
-#.nol  "NOL "  "GKON"  Mobile Phone(Nokia)Format      GraphicConverter
-#.pal  "8BCT"  "8BIM"  Color Table                    GraphicConverter
-#.pgc  "PGCF"  "GKON"  PGC/PGF  Atari Portfolio PCG   GraphicConverter
-#.pics "PICS"  "GKON"  PICS-PICT Sequence             GraphicConverter
-#.swf  "SWFL"  "SWF2"  Flash                          Macromedia Flash
-#.vpb  "VPB "  "GKON"  VPB QUANTEL                    GraphicConverter
-#.wbmp "WBMP"  "GKON"  WBMP                           GraphicConverter
-#.x-face  "TEXT"  "GKON"  X-Face                      GraphicConverter
-
-### Nov 29, 2002
-#.fla  "SPA "  "MFL2"  Flash source                   Macromedia Flash
index ce0fb96e2d3c02f02620a88f843082299a31d6c6..4763046063a2ce5cd491e74dd8f0c46a831fa96c 100644 (file)
@@ -3,41 +3,16 @@
 SUBDIRS = pam
 SUFFIXES = .tmpl .
 
-TMPLFILES = afpd.conf.tmpl AppleVolumes.default.tmpl
-GENFILES = afpd.conf AppleVolumes.default
+TMPLFILES = afp.conf.tmpl
+GENFILES = afp.conf
 CLEANFILES = $(GENFILES)
-EXTRA_DIST = \
-       AppleVolumes.default.tmpl \
-       AppleVolumes.system \
-       afp_ldap.conf \
-       afpd.conf.tmpl \
-       atalkd.conf \
-       netatalk.conf \
-       papd.conf
+EXTRA_DIST = afp.conf.tmpl
 
 OVERWRITE_CONFIG = @OVERWRITE_CONFIG@
 
-if USE_DEBIAN
-CONFFILES = AppleVolumes.system
-else
-CONFFILES = AppleVolumes.system netatalk.conf
-endif
-
-if HAVE_ACLS
-CONFFILES += afp_ldap.conf
-endif
-
-if USE_APPLETALK
-CONFFILES += atalkd.conf papd.conf
-endif
+CONFFILES = 
 
 pkgconfdir = @PKGCONFDIR@
-webminpath = @WEBMIN_PATH@
-webminuser = @WEBMIN_USER@
-webminversion = @WEBMIN_VERSION@
-webminpass = @WEBMIN_PASS@
-webminport = @WEBMIN_PORT@
-
 #
 # rule to parse template files
 #
@@ -53,91 +28,38 @@ webminport = @WEBMIN_PORT@
 # install configuration files
 #
 
-install-data-local: install-config-files install-webmin
+install-data-local: install-config-files
+       mkdir -pm 0755 $(DESTDIR)$(localstatedir)/netatalk/
+       mkdir -pm 0755 $(DESTDIR)$(localstatedir)/netatalk/CNID/
+       $(INSTALL_DATA) $(srcdir)/README $(DESTDIR)$(localstatedir)/netatalk/
+       $(INSTALL_DATA) $(srcdir)/README $(DESTDIR)$(localstatedir)/netatalk/CNID/
 
 uninstall-local:
        for f in $(CONFFILES) $(GENFILES); do \
                echo rm -f $(DESTDIR)$(pkgconfdir)/$$f; \
                rm -f $(DESTDIR)$(pkgconfdir)/$$f; \
        done
+       rm -f $(DESTDIR)$(localstatedir)/netatalk/README
+       rm -f $(DESTDIR)$(localstatedir)/netatalk/CNID/README
 if USE_DEBIAN
        rm -f $(DESTDIR)/etc/default/netatalk
 endif
 
 install-config-files: $(CONFFILES) $(GENFILES)
        $(mkinstalldirs) $(DESTDIR)$(pkgconfdir)
-       for f in $(CONFFILES) $(GENFILES); do \
+       for f in $(CONFFILES) ; do \
                if test "x$(OVERWRITE_CONFIG)" = "xyes" -o ! -f $(DESTDIR)$(pkgconfdir)/$$f; then \
                        echo "$(INSTALL_DATA) $$f $(DESTDIR)$(pkgconfdir)"; \
-                       $(INSTALL_DATA) $$f $(DESTDIR)$(pkgconfdir); \
+                       $(INSTALL_DATA) $(srcdir)/$$f $(DESTDIR)$(pkgconfdir); \
                else \
                        echo "not overwriting $$f"; \
                fi; \
        done
-if USE_DEBIAN
-       $(mkinstalldirs) $(DESTDIR)/etc/default
-       if test "x$(OVERWRITE_CONFIG)" = "xyes" -o ! -f /etc/default/netatalk; then \
-               echo "$(INSTALL_DATA) $(srcdir)/netatalk.conf $(DESTDIR)/etc/default/netatalk"; \
-               $(INSTALL_DATA) $(srcdir)/netatalk.conf $(DESTDIR)/etc/default/netatalk; \
-       else \
-               echo "not overwriting /etc/default/netatalk"; \
-       fi
-endif
-
-install-webmin:
-       if test "x$(webminpath)" != "x"; then \
-               if ! test -d "x$(webminpath)"; then \
-                       mkdir -p "$(webminpath)"; \
+       for f in $(GENFILES); do \
+               if test "x$(OVERWRITE_CONFIG)" = "xyes" -o ! -f $(DESTDIR)$(pkgconfdir)/$$f; then \
+                       echo "$(INSTALL_DATA) $$f $(DESTDIR)$(pkgconfdir)"; \
+                       $(INSTALL_DATA) $$f $(DESTDIR)$(pkgconfdir); \
+               else \
+                       echo "not overwriting $$f"; \
                fi; \
-               cd "$(webminpath)"; \
-               wget http://prdownloads.sourceforge.net/webadmin/webmin-$(webminversion).tar.gz ; \
-               tar xzf webmin-$(webminversion).tar.gz; \
-               rm webmin-$(webminversion).tar.gz; \
-               /etc/init.d/webmin stop; \
-               rm -r webmin; \
-               mv webmin-$(webminversion) webmin; \
-               cd webmin; \
-               rm -r adsl-client apache at backup-config bacula-backup bandwidth bind8 bsdexports burner \
-                       cfengine cluster-copy cluster-cron cluster-passwd cluster-shell cluster-software cluster-useradmin \
-                       cluster-usermin cluster-webmin custom \
-                       cron dfsadmin dhcpd dnsadmin dovecot exim exports \
-                       fdisk fetchmail file filter firewall format frox fsdump grub heartbeat hpuxexports \
-                       htaccess-htpasswd idmapd inetd inittab ipfilter ipfw ipsec jabber \
-                       ldap-server lilo logrotate lpadmin lvm \
-                       mailboxes mailcap majordomo man mon mscstyle3 mysql \
-                       net nis openslp pap phpini postfix postgresql ppp-client pptp-client pptp-server \
-                       procmail proftpd pserver qmailadmin raid rbac \
-                       samba sarg sendmail sentry sgiexports shell \
-                       shorewall smart-status smf software spam squid sshd \
-                       status stunnel tcpwrappers telnet time tunnel \
-                       updown usermin vgetty webalizer wuftpd xinetd zones; \
-               wget https://sourceforge.net/projects/netatalk/files/Netatalk%20Webmin%20Module/0.9-beta2/netatalk.wbm.gz/download ; \
-               tar xzf netatalk.wbm.gz; \
-               rm netatalk.wbm.gz; \
-               cd netatalk; \
-               rm config; \
-               echo "applevolumedefault_c=$(sysconfdir)/netatalk/AppleVolumes.default" >> config; \
-               echo "applevolumesystem_c=$(sysconfdir)/netatalk/AppleVolumes.system" >> config; \
-               echo "afpd_c=$(sysconfdir)/netatalk/afpd.conf" >> config; \
-               echo "atalk_c=$(sysconfdir)/netatalk/atalk.conf" >> config; \
-               echo "papd_c=$(sysconfdir)/netatalk/papd.conf" >> config; \
-               echo "afpd_d=$(sbindir)/afpd" >> config; \
-               echo "atalkd_d=$(sbindir)/atalkd" >> config; \
-               echo "papd_d=$(sbindir)/papd" >> config; \
-               echo "netatalk_c=@PAMDIR@/etc/pam.d" >> config; \
-               echo "atalk_start=$(sysconfdir)/init.d/atalk" >> config; \
-               echo "select_minUsers=" >> config; \
-               echo "select_maxUsers=" >> config; \
-               echo "atalk_nls=" >> config; \
-               cd ..; \
-               config_dir="$(sysconfdir)/netatalk/webmin-config" \
-                       var_dir="$(prefix)/var" \
-                       perl="`which perl`" \
-                       port="$(webminport)" \
-                       login="$(webminuser)" \
-                       password="$(webminpass)" \
-                       ssl=1 \
-                       atboot=1 \
-                       bootscript=netamin \
-                       ./setup.sh > /dev/null; \
-       fi
+       done
diff --git a/config/README b/config/README
new file mode 100644 (file)
index 0000000..f0f9ab7
--- /dev/null
@@ -0,0 +1 @@
+This directory contains modifiable Netatalk configuration files and the CNID databases.
\ No newline at end of file
diff --git a/config/afp.conf.tmpl b/config/afp.conf.tmpl
new file mode 100644 (file)
index 0000000..b2ee186
--- /dev/null
@@ -0,0 +1,12 @@
+;
+; Netatalk 3.x configuration file
+;
+
+[Global]
+; Global server settings
+
+; [Homes]
+; basedir regex = /xxxx
+
+; [My AFP Volume]
+; path = /path/to/volume
diff --git a/config/afp_ldap.conf b/config/afp_ldap.conf
deleted file mode 100644 (file)
index f1700c0..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-# Netatalk 2.x LDAP configuration
-
-# ldap_server      = localhost
-# ldap_auth_method = simple
-# ldap_auth_dn     = cn=admin,dc=domain,dc=org
-# ldap_auth_pw     = notthisone
-# ldap_userbase    = ou=users,dc=domain,dc=org
-# ldap_userscope   = one
-# ldap_groupbase   = ou=groups,dc=domain,dc=org
-# ldap_groupscope  = one
-# ldap_uuid_attr   = apple-generateduid
-# ldap_name_attr   = cn
-# ldap_group_attr  = cn
diff --git a/config/afpd.conf.tmpl b/config/afpd.conf.tmpl
deleted file mode 100644 (file)
index 4e77287..0000000
+++ /dev/null
@@ -1,362 +0,0 @@
-#
-# CONFIGURATION FOR AFPD (Netatalk 2.x)
-#
-# Each single line defines a virtual server that should be available.
-# Though, using "\" character, newline escaping is supported.
-# Empty lines and lines beginning with `#' are ignored.
-# Options in this file will override both compiled-in defaults
-# and command line options.
-#
-
-
-#
-# Format:
-#  - [options]               to specify options for the default server
-#  "Server name" [options]   to specify an additional server
-#
-
-
-#
-# The following options are available:
-#   Transport Protocols:
-#     -[no]tcp       Make "AFP over TCP" [not] available
-#     -[no]ddp       Make "AFP over AppleTalk" [not] available.
-#                    If you have -proxy specified, specify -uamlist "" to 
-#                    prevent ddp connections from working.
-#
-#     -transall      Make both available
-#
-#   Transport Options:
-#     -ipaddr <ipaddress> Specifies the IP address that the server should
-#                         advertise and listens to. The default is advertise
-#                         the first IP address of the system, but to listen
-#                         for any incoming request. The network address may
-#                         be specified either in dotted-decimal format for
-#                         IPv4 or in hexadecimal format for IPv6.
-#                         This option also allows to use one machine to
-#                         advertise the AFP-over-TCP/IP settings of another
-#                         machine via NBP when used together with the -proxy
-#                         option.
-#     -server_quantum <number> 
-#                         Specifies the DSI server quantum. The minimum
-#                         value is 1MB. The max value is 0xFFFFFFFF. If you 
-#                         specify a value that is out of range, you'll get 
-#                         the default value (currently the minimum).
-#     -admingroup <groupname>
-#                         Specifies the group of administrators who should
-#                         all be seen as the superuser when they log in.
-#                         Default is disabled.
-#     -ddpaddr x.y        Specifies the DDP address of the server.
-#                         the  default is to auto-assign an address (0.0).
-#                         this is only useful if you're running on
-#                         a multihomed host.
-#     -port <number>      Specifies the TCP port the server should respond
-#                         to (default is 548)
-#     -fqdn <name:port>   specify a fully-qualified domain name (+optional
-#                         port). this gets discarded if the server can't
-#                         resolve it. this is not honored by appleshare
-#                         clients <= 3.8.3 (default: none)
-#     -hostname <name>    Use this instead of the result from calling
-#                         hostname for dertermening which IP address to
-#                         advertise, therfore the hostname is resolved to
-#                         an IP which is the advertised. This is NOT used for
-#                         listening and it is also overwritten by -ipaddr.
-#     -proxy              Run an AppleTalk proxy server for specified
-#                         AFP/TCP server (if address/port aren't given,
-#                         then first IP address of the system/548 will
-#                         be used).
-#                         if you don't want the proxy server to act as
-#                         a ddp server as well, set -uamlist to an empty
-#                         string.
-#     -dsireadbuf [number]
-#                         Scale factor that determines the size of the
-#                         DSI/TCP readahead buffer, default is 12. This is
-#                         multiplies with the DSI server quantum (default
-#                         ~300k) to give the size of the buffer. Increasing
-#                         this value might increase throughput in fast local
-#                         networks for volume to volume copies.  Note: This
-#                         buffer is allocated per afpd child process, so
-#                         specifying large values will eat up large amount of
-#                         memory (buffer size * number of clients).
-#     -tcprcvbuf [number]
-#                         Try to set TCP receive buffer using setsockpt().
-#                         Often OSes impose restrictions on the applications
-#                         ability to set this value.
-#     -tcpsndbuf [number]
-#                         Try to set TCP send buffer using setsockpt().
-#                         Often OSes impose restrictions on the applications
-#                         ability to set this value.
-#     -slp                Register this server with the Service Location
-#                         Protocol (if SLP support was compiled in).
-#     -nozeroconf         Don't register this server with the Multicats
-#                         DNS Protocol.
-#     -advertise_ssh      Allows Mac OS X clients (10.3.3-10.4) to
-#                         automagically establish a tunneled AFP connection
-#                         through SSH. This option is not so significant
-#                         for the recent Mac OS X. See the Netatalk Manual
-#                         in detail.
-#
-#
-#   Authentication Methods:
-#     -uampath <path>  Use this path to look for User Authentication Modules.
-#                      (default: :UAMS_PATH:)
-#     -uamlist <a,b,c> Comma-separated list of UAMs.
-#                      (default: uams_dhx.so,uams_dhx2.so)
-#
-#                      some commonly available UAMs:
-#                      uams_guest.so: Allow guest logins
-#
-#                      uams_clrtxt.so: (uams_pam.so or uams_passwd.so)
-#                                     Allow logins with passwords
-#                                     transmitted in the clear. 
-#
-#                      uams_randnum.so: Allow Random Number and Two-Way
-#                                      Random Number exchange for
-#                                      authentication.
-#
-#                      uams_dhx.so: (uams_dhx_pam.so or uams_dhx_passwd.so)
-#                                  Allow Diffie-Hellman eXchange
-#                                  (DHX) for authentication.
-#
-#                      uams_dhx2.so: (uams_dhx2_pam.so or uams_dhx2_passwd.so)
-#                                   Allow Diffie-Hellman eXchange 2
-#                                   (DHX2) for authentication.
-#
-#   Password Options:
-#     -[no]savepassword   [Don't] Allow clients to save password locally
-#     -passwdfile <path>  Use this path to store Randnum passwords.
-#                         (Default: :ETCDIR:/afppasswd. The only other
-#                         useful value is ~/.passwd. See 'man afppasswd'
-#                         for details.)
-#     -passwdminlen <#>   minimum password length. may be ignored.
-#     -[no]setpassword    [Don't] Allow clients to change their passwords.
-#     -loginmaxfail <#>   maximum number of failed logins. this may be
-#                         ignored if the uam can't handle it.
-#
-#   AppleVolumes files:
-#     -defaultvol <path>  Specifies path to AppleVolumes.default file
-#                         (default :ETCDIR:/AppleVolumes.default,
-#                         same as -f on command line)
-#     -systemvol <path>   Specifies path to AppleVolumes.system file
-#                         (default :ETCDIR:/AppleVolumes.system,
-#                         same as -s on command line)
-#     -[no]uservolfirst   [Don't] read the user's ~/AppleVolumes or
-#                         ~/.AppleVolumes before reading
-#                         :ETCDIR:/AppleVolumes.default
-#                         (same as -u on command line)
-#     -[no]uservol        [Don't] Read the user's volume file
-#     -closevol           Immediately unmount volumes removed from
-#                         AppleVolumes files on SIGHUP sent to the afp
-#                         master process.
-#
-#   Miscellaneous:
-#     -authprintdir <path> Specifies the path to be used (per server) to 
-#                          store the files required to do CAP-style
-#                          print authentication which papd will examine
-#                          to determine if a print job should be allowed.
-#                          These files are created at login and if they
-#                          are to be properly removed, this directory
-#                          probably needs to be umode 1777
-#     -guestname "user"   Specifies the user name for the guest login
-#                         (default "nobody", same as -g on command line)
-#     -loginmesg "Message"  Client will display "Message" upon logging in
-#                         (no default, same as -l "Message" on commandline)
-#     -nodebug            Switch off debugging
-#     -client_polling     With this switch enabled, afpd won't advertise
-#                         that it is capable of server notifications, so that
-#                         connected clients poll the server every 10 seconds
-#                         to detect changes in opened server windows.
-#                         Note: Depending on the number of simultaneously
-#                         connected clients and the network's speed, this can
-#                         lead to a significant higher load on your network!
-#     -sleep   <number>   AFP 3.x wait number hours before disconnecting
-#                         clients in sleep mode. Default 10 hours
-#     -tickleval <number> Specify the tickle timeout interval (in seconds).
-#                         Note, this defaults to 30 seconds, and really 
-#                         shouldn't be changed.  If you want to control
-#                         the server idle timeout, use the -timeout option.
-#     -timeout <number>   Specify the number of tickles to send before
-#                         timing out a connection.
-#                         The default is 4, therefore a connection will
-#                         timeout in 2 minutes.
-#     -[no]icon           [Don't] Use the platform-specific icon. Recent
-#                         Mac OS don't display it any longer.
-#     -volnamelen <number>
-#                         Max length of UTF8-MAC volume name for Mac OS X.
-#                         Note that Hangul is especially sensitive to this.
-#                           255: limit of spec
-#                           80:  limit of generic Mac OS X (default)
-#                           73:  limit of Mac OS X 10.1, if >= 74
-#                                Finder crashed and restart repeatedly.
-#                         Mac OS 9 and earlier is not influenced by this,
-#                         Maccharset volume names are always limitted to 27.
-#     -[un]setuplog "<logtype> <loglevel> [<filename>]"
-#                         Specify that any message of a loglevel up to the
-#                         given loglevel should be logged to the given file.
-#                         If the filename is ommited the loglevel applies to
-#                         messages passed to syslog.
-#
-#                         By default (no explicit -setuplog and no buildtime
-#                         configure flag --with-logfile) afpd logs to syslog
-#                         with a default logging setup equivalent to
-#                         "-setuplog default log_info".
-#
-#                         If build with --with-logfile[=somefile]
-#                         (default logfile /var/log/netatalk.log) afpd
-#                         defaults to a setup that is equivalent to
-#                         "-setuplog default log_info [netatalk.log|somefile]"
-#
-#                         logtypes:  Default, AFPDaemon, Logger, UAMSDaemon
-#                         loglevels: LOG_SEVERE, LOG_ERROR, LOG_WARN,
-#                                    LOG_NOTE, LOG_INFO, LOG_DEBUG,
-#                                    LOG_DEBUG6, LOG_DEBUG7, LOG_DEBUG8,
-#                                    LOG_DEBUG9, LOG_MAXDEBUG
-#
-#                Example: Useful default config
-#                         -setuplog "default log_info /var/log/afpd.log"
-#
-#                         Debugging config
-#                         -setuplog "default log_maxdebug /var/log/afpd.log"
-#
-#     -signature { user:<text> | auto }
-#                         Specify a server signature. This option is useful
-#                         while running multiple independent instances of
-#                         afpd on one machine (eg. in clustered environments,
-#                         to provide fault isolation etc.).
-#                         Default is "auto".
-#                         "auto" signature type allows afpd generating
-#                         signature and saving it to afp_signature.conf
-#                         automatically (based on random number).
-#                         "host" signature type switches back to "auto"
-#                         because it is obsoleted.
-#                         "user" signature type allows administrator to
-#                         set up a signature string manually.
-#                         Examples: three servers running on one machine:
-#                               first   -signature user:USERS
-#                               second  -signature user:USERS
-#                               third   -signature user:ADMINS
-#                         First two servers will act as one logical AFP
-#                         service. If user logs in to first one and then
-#                         connects to second one, session will be
-#                         automatically redirected to the first one. But if
-#                         client connects to first and then to third, 
-#                         will be asked for password twice and will see
-#                         resources of both servers.
-#                         Traditional method of signature generation causes
-#                         two independent afpd instances to have the same
-#                         signature and thus cause clients to be redirected
-#                         automatically to server (s)he logged in first.
-#     -k5keytab <path>
-#     -k5service <service>
-#     -k5realm <realm>
-#                         These are required if the server supports
-#                         Kerberos 5 authentication
-#     -ntdomain
-#     -ntseparator
-#                         Use for eg. winbind authentication, prepends
-#                         both strings before the username from login and
-#                         then tries to authenticate with the result
-#                         through the availabel and active UAM authentication
-#                         modules.
-#     -dircachesize entries
-#                         Maximum possible entries in the directory cache.
-#                         The cache stores directories and files. It is used
-#                         to cache the full path to directories and CNIDs
-#                         which considerably speeds up directory enumeration.
-#                         Default size is 8192, maximum size is 131072. Given
-#                         value is rounded up to nearest power of 2. Each
-#                         entry takes about 100 bytes, which is not much, but
-#                         remember that every afpd child process for every
-#                         connected user has its cache.
-#     -fcelistener host[:port]
-#                         Enables sending FCE events to the specified host,
-#                         default port is 12250 if not specified. Specifying
-#                         mutliple listeners is done by having this option
-#                         once for each of them.
-#     -fceevents fmod,fdel,ddel,fcre,dcre,tmsz
-#                         Speficies which FCE events are active, default is
-#                         fmod,fdel,ddel,fcre,dcre.
-#     -fcecoalesce all|delete|create
-#                         Coalesce FCE events.
-#     -fceholdfmod seconds
-#                         This determines the time delay in seconds which is
-#                         always waited if another file modification for the
-#                         same file is done by a client before sending an FCE
-#                         file modification event (fmod). For example saving
-#                         a file in Photoshop would generate multiple events
-#                         by itself because the application is opening,
-#                         modifying and closing a file mutliple times for
-#                         every "save". Defautl: 60 seconds.
-#     -keepsessions       Enable "Continuous AFP Service". This means the
-#                         ability to stop the master afpd process with a
-#                         SIGQUIT signal, possibly install an afpd update and
-#                         start the afpd process. Existing AFP sessions afpd
-#                         processes will remain unaffected. Technically they
-#                         will be notified of the master afpd shutdown, sleep
-#                         15-20 seconds and then try to reconnect their IPC
-#                         channel to the master afpd process. If this
-#                         reconnect fails, the sessions are in an undefined
-#                         state. Therefor it's absolutely critical to restart
-#                         the master process in time!
-#     -noacl2maccess      Don't map filesystem ACLs to effective permissions.
-#
-#   Codepage Options:
-#     -unixcodepage <CODEPAGE>  Specifies the servers unix codepage,
-#                               e.g. "ISO-8859-15" or "UTF8".
-#                               This is used to convert strings to/from
-#                               the systems locale, e.g. for authenthication.
-#                               Defaults to LOCALE if your system supports it,
-#                               otherwise ASCII will be used.
-#
-#     -maccodepage <CODEPAGE>   Specifies the legacy clients (<= Mac OS 9)
-#                               codepage, e.g. "MAC_ROMAN".
-#                               This is used to convert strings to the
-#                               systems locale, e.g. for authenthication
-#                               and SIGUSR2 messaging. This will also be
-#                               the default for volumes maccharset.
-#
-#   CNID related options:
-#     -cnidserver <ipaddress:port>
-#                               Specifies the IP address and port of a
-#                               cnid_metad server, required for CNID dbd
-#                               backend. Defaults to localhost:4700.
-#                               The network address may be specified either
-#                               in dotted-decimal format for IPv4 or in
-#                               hexadecimal format for IPv6.
-#
-#   Avahi (Bonjour) related options:
-#     -mimicmodel <model>
-#                               Specifies the icon model that appears on
-#                               clients. Defaults to off. Examples: RackMac
-#                               (same as Xserve), PowerBook, PowerMac, Macmini,
-#                               iMac, MacBook, MacBookPro, MacBookAir, MacPro,
-#                               AppleTV1,1, AirPort
-#
-
-
-#
-# Some examples:
-#
-#       The simplest case is to not have an afpd.conf.
-#
-#       4 servers w/ names server1-3 and one w/ the hostname. servers
-#       1-3 get routed to different ports with server 3 being bound 
-#       specifically to address 192.168.1.3
-#
-#           -
-#           server1 -port 12000
-#           server2 -port 12001
-#           server3 -port 12002 -ipaddr 192.168.1.3
-#
-#       a dedicated guest server, a user server, and a special
-#       AppleTalk-only server:
-#
-#           "Guest Server" -uamlist uams_guest.so \
-#                   -loginmesg "Welcome guest! I'm a public server."
-#           "User Server" -uamlist uams_dhx2.so -port 12000
-#           "special" -ddp -notcp -defaultvol <path> -systemvol <path>
-#
-
-
-# default:
-# - -tcp -noddp -uamlist uams_dhx.so,uams_dhx2.so
diff --git a/config/atalkd.conf b/config/atalkd.conf
deleted file mode 100644 (file)
index 4648e3a..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-#
-# Format of lines in this file:
-#
-#    interface [ -seed ] [ -router | -dontroute ] 
-#       [ -phase { 1 | 2 } ] [ -addr net.node ]
-#      [ -net first[-last] ] [ -zone ZoneName ] ...
-#
-# -seed only works if you have multi-interfaces.  Any missing arguments are
-# automatically configured from the network.  Note: lines can't actually be
-# split, tho it's a good idea.
-#
-# -router is like -seed but it allows single-interface routing. -dontroute 
-# disables routing for the specified interface.
-#
-# Some examples:
-#
-#      The simplest case is no atalkd.conf.  This works on most platforms
-#      (notably not Solaris), since atalkd can discover the local interfaces
-#      on the machine.
-#
-#      Very slightly more complicated:
-#
-#              le0
-#      or
-#              eth0
-#
-#      for Solaris/SunOS or Linux.
-#
-#      A much more complicated example:
-#
-#              le0 -phase 1
-#              le1 -seed -phase 2 -addr 66.6 -net 66-67 -zone "No Parking"
-#
-#      This turns on transition routing between the le0 and le1
-#      interfaces on a Sun.  It also causes atalkd to fail if other
-#      routers disagree about it's configuration of le1.
-#
diff --git a/config/netatalk.conf b/config/netatalk.conf
deleted file mode 100644 (file)
index a050460..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-# Netatalk 2.x configuration
-
-#########################################################################
-# Global configuration
-#########################################################################
-
-#### machine's AFPserver/AppleTalk name.
-#ATALK_NAME=machinename
-
-#### server (unix) and legacy client (<= Mac OS 9) charsets
-ATALK_UNIX_CHARSET='LOCALE'
-ATALK_MAC_CHARSET='MAC_ROMAN'
-
-#### Don't Edit. export the charsets, read form ENV by apps
-export ATALK_UNIX_CHARSET
-export ATALK_MAC_CHARSET
-
-#########################################################################
-# AFP specific configuration
-#########################################################################
-
-#### Set which daemons to run.
-#### If you use AFP file server, run both cnid_metad and afpd.
-CNID_METAD_RUN=yes
-AFPD_RUN=yes
-
-#### maximum number of clients that can connect:
-#AFPD_MAX_CLIENTS=20
-
-#### UAMs (User Authentication Modules)
-#### available options: uams_dhx.so, uams_dhx2.so, uams_guest.so,
-####                    uams_clrtxt.so(legacy), uams_randnum.so(legacy)
-#AFPD_UAMLIST="-U uams_dhx.so,uams_dhx2.so"
-
-#### Set the id of the guest user when using uams_guest.so
-#AFPD_GUEST=nobody
-
-#### config for cnid_metad. Default log config:
-#CNID_CONFIG="-l log_note"
-
-#########################################################################
-# AppleTalk specific configuration (legacy)
-#########################################################################
-
-#### Set which legacy daemons to run.
-#### If you need AppleTalk, run atalkd.
-#### papd, timelord and a2boot are dependent upon atalkd.
-#ATALKD_RUN=no
-#PAPD_RUN=no
-#TIMELORD_RUN=no
-#A2BOOT_RUN=no
-
-#### Control whether the daemons are started in the background.
-#### If it is dissatisfied that legacy atalkd starts slowly, set "yes".
-#### In case using systemd/systemctl, this is not so significant.
-#ATALK_BGROUND=no
-
-#### Set the AppleTalk Zone name.
-#### NOTE: if your zone has spaces in it, you're better off specifying
-####       it in atalkd.conf
-#ATALK_ZONE=@zone
diff --git a/config/papd.conf b/config/papd.conf
deleted file mode 100644 (file)
index ec36a6a..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-# Attributes are:
-#
-#      Name Type Default       Description
-#      pd   str  ".ppd"        Pathname to ppd file.
-#      pr   str  "lp"          LPD printer name.
-#       pa   str  "0.0"         AppleTalk address (not usually needed).
-#      op   str  "operator"    Operator name, for LPD spooling.
-#      au   flag not-present   If present, authentication required
-#                              note that if ca and sp are both set,
-#                              ca will be tried first and then sp
-#      am   str  none          Comma separated list of uams to use
-#                              (for every printer) whenever 
-#                              authentication is on
-#      ca   str  not-present   If present, use cap-style authentication
-#                              directory to place print authentication files 
-#      sp   flag not-present   use PSSP authentication.
-#
-# Some examples:
-#
-#      On many systems (notably not Solaris), no papd.conf is required,
-#      since papd shares the same defaults as lpd.
-#
-#      A simple example:
-#
-#              terminator:\
-#                      :pr=lp:op=wes:\
-#                      :pd=/usr/share/lib/ppd/HPLJ_4M.PPD:
-#
-#      An example with authenticated printing:
-#              authprn:\
-#                      :pr=|/usr/bin/lpr -Plp:\
-#                      :pd=/usr/share/lib/ppd/HPLJ_4M.PPD:\
-#                      :sp:ca=/tmp/print:\
-#                      :am=uams_clrtxt.so:
-#
-#      Note also that papd.conf can list several printers.
-#
-#      The printer name in papd may be a full NBP-name of the form
-#      name:type@zone, for example:
-#              Printer 1:LaserWriter@Printing and Mailing:\
-#                      :pr=|/usr/bin/lpr -Plp1:
-#
-# Warning: If you are using more than 15 printers and you do not
-# specify the zone in the printer name, only some of the printers may
-# appear in the Chooser.
index 176c03b144f3af0aeca66efbbdb94d8c6b5c6e28..fd4dd2732598d84dccf7df96a43db1de1b383eb0 100644 (file)
@@ -1,4 +1,4 @@
-dnl configure.in for netatalk
+dnl configure.ac for netatalk
 
 AC_INIT(etc/afpd/main.c)
 
@@ -22,35 +22,36 @@ AC_PROG_LIBTOOL
 AC_PROG_PERL
 AC_PROG_GREP
 AC_PROG_PS
-
 AM_PROG_CC_C_O
+AC_C_BIGENDIAN
+AC_C_INLINE
 
-dnl Checks for header files.
-AC_HEADER_DIRENT
-AC_HEADER_STDC
-AC_HEADER_SYS_WAIT
-AC_CHECK_HEADERS(fcntl.h limits.h stdint.h strings.h time.h sys/param.h sys/fcntl.h sys/file.h sys/ioctl.h sys/time.h sys/mnttab.h sys/statvfs.h sys/stat.h sys/vfs.h mntent.h syslog.h unistd.h termios.h sys/termios.h netdb.h sgtty.h ufs/quota.h mount.h statfs.h sys/types.h dlfcn.h errno.h sys/errno.h sys/uio.h langinfo.h locale.h sys/filio.h)
-AC_CHECK_HEADER(sys/cdefs.h,,
-       AC_MSG_RESULT([enabling generic cdefs.h from tree])
-       CFLAGS="-I\$(top_srcdir)/sys/generic $CFLAGS"
-)
+dnl Check if we can use attribute unused (gcc only) from ethereal
+AC_MSG_CHECKING(to see if we can add '__attribute__((unused))' to CFLAGS)
+if test x$GCC != x ; then
+  CFLAGS="-D_U_=\"__attribute__((unused))\" $CFLAGS"
+  AC_MSG_RESULT(yes)
+else
+  CFLAGS="-D_U_=\"\" $CFLAGS"
+  AC_MSG_RESULT(no)
+fi
+
+dnl Checks for header files, some checks are obsolete, unfortunately the code
+dnl uses the resulting macros, so the code has to cleaned up too before
+dnl we can remove the checks here.
+AC_CHECK_HEADERS(mntent.h unistd.h termios.h ufs/quota.h)
+AC_CHECK_HEADERS(netdb.h sgtty.h statfs.h dlfcn.h langinfo.h locale.h)
+AC_CHECK_HEADERS(sys/param.h sys/fcntl.h sys/termios.h)
+AC_CHECK_HEADERS(sys/mnttab.h sys/statvfs.h sys/stat.h sys/vfs.h)
+dnl Checks for header files, confirmed to be required as of 2011
 AC_CHECK_HEADERS([sys/mount.h], , , 
 [#ifdef HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
 ])
+AC_CHECK_TYPES([fshare_t], [], [], [[#include <fcntl.h>]])
 
-dnl Checks for typedefs, structures, and compiler characteristics.
-AC_C_CONST
-AC_TYPE_UID_T
-AC_C_INLINE
-AC_TYPE_MODE_T
-AC_TYPE_OFF_T
-AC_TYPE_PID_T
-AC_TYPE_SIZE_T
-AC_STRUCT_ST_RDEV
-AC_HEADER_TIME
-AC_STRUCT_TM
+AC_SYS_LARGEFILE([], AC_MSG_ERROR([AFP 3.x support requires Large File Support.]))
 
 dnl --------------------------------------------------------------------------
 dnl check if dlsym needs to add an underscore, uses libtool macros 
@@ -62,1307 +63,196 @@ if test x"$libltdl_cv_need_uscore" = xyes; then
     AC_DEFINE(DLSYM_PREPEND_UNDERSCORE, 1, [BSD compatibility macro])
 fi
 
-dnl Checks for library functions.
-AC_TYPE_GETGROUPS
-AC_PROG_GCC_TRADITIONAL
-AC_FUNC_MEMCMP
-AC_HEADER_MAJOR
-AC_FUNC_MMAP
-AC_TYPE_SIGNAL
-AC_FUNC_UTIME_NULL
-AC_FUNC_WAIT3
-AC_CHECK_FUNCS(getcwd gethostname gettimeofday getusershell mkdir rmdir select socket strdup strcasestr strstr strtoul strchr memcpy)
-AC_CHECK_FUNCS(backtrace_symbols setlocale nl_langinfo strlcpy strlcat setlinebuf dirfd pselect access pread pwrite)
-AC_CHECK_FUNCS(waitpid getcwd strdup strndup strnlen strtoul strerror chown fchown chmod fchmod chroot link mknod mknod64)
+dnl Special hecks
 ac_neta_haveatfuncs=yes
 AC_CHECK_FUNCS(openat renameat fstatat unlinkat, , ac_neta_haveatfuncs=no)
 if test x"$ac_neta_haveatfuncs" = x"yes" ; then
    AC_DEFINE([_ATFILE_SOURCE], 1, AT file source)
    AC_DEFINE([HAVE_ATFUNCS], 1, whether at funcs are available)
 fi
-
 AC_CHECK_MEMBERS(struct tm.tm_gmtoff,,, [#include <time.h>])
 
-AC_CHECK_FUNC(gethostbyname,,[AC_CHECK_LIB(nsl,gethostbyname)])
-AC_CHECK_FUNC(connect,,[AC_CHECK_LIB(socket,connect)])
-dnl search for necessary libs for libpthread stuff
-AC_SEARCH_LIBS(pthread_sigmask, pthread,, 
-               [AC_MSG_ERROR([cannot find pthread_sigmask in libc or libpthread])])
+dnl these tests have been comfirmed to be needed in 2011
+AC_CHECK_FUNCS(backtrace_symbols dirfd getusershell pread pwrite pselect)
+AC_CHECK_FUNCS(setlinebuf strlcat strlcpy strnlen)
+AC_CHECK_FUNCS(mmap utime getpagesize) dnl needed by tbd
+
+dnl search for necessary libraries
+AC_SEARCH_LIBS(gethostbyname, nsl)
+AC_SEARCH_LIBS(connect, socket)
+AC_SEARCH_LIBS(pthread_sigmask, pthread,,[AC_MSG_ERROR([missing pthread_sigmask])])
 if test x"$ac_cv_search_pthread_sigmask" != x"none required" ; then
    PTHREAD_LIBS=$ac_cv_search_pthread_sigmask
 fi
 AC_SUBST(PTHREAD_LIBS)
-AC_CACHE_SAVE
 
-dnl Checks for (v)snprintf
-NETATALK_SNPRINTF_CHECK
+AC_DEFINE(OPEN_NOFOLLOW_ERRNO, ELOOP, errno returned by open with O_NOFOLLOW)
 
-dnl --------------------------------------------------------------------------
 dnl 64bit platform check
-dnl --------------------------------------------------------------------------
-
-AC_MSG_CHECKING([whether to check for 64bit libraries])
-# Test if the compiler is in 64bit mode
-echo 'int i;' > conftest.$ac_ext
-atalk_cv_cc_64bit_output=no
-if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.$ac_objext` in
-    *"ELF 64"*)
-      atalk_cv_cc_64bit_output=yes
-      ;;
-    esac
-fi
-rm -rf conftest*
-
-case $host_cpu:$atalk_cv_cc_64bit_output in
-powerpc64:yes | s390x:yes | sparc*:yes | x86_64:yes | i386:yes)
-    case $target_os in
-    solaris2*)
-        AC_MSG_RESULT([yes])
-        atalk_libname="lib/64"
-        ;;
-    *bsd* | dragonfly*)
-        AC_MSG_RESULT([no])
-        atalk_libname="lib"
-        ;;
-    *)
-        AC_MSG_RESULT([yes])
-        atalk_libname="lib64"
-        ;;
-    esac
-    ;;
-*:*)
-    AC_MSG_RESULT([no])
-    atalk_libname="lib"
-    ;;
-esac
-
-dnl --------------------------------------------------------------------------
-dnl specific configuration comes in here:
-dnl --------------------------------------------------------------------------
-
-
-netatalk_cv_admin_group=yes
-AC_MSG_CHECKING([for administrative group support])
-AC_ARG_ENABLE(admin-group,
-       [  --disable-admin-group   disable admin group],[
-        if test x"$enableval" = x"no"; then
-               AC_DEFINE(ADMIN_GRP, 0, [Define if the admin group should be enabled])
-               netatalk_cv_admin_group=no
-               AC_MSG_RESULT([no])
-       else
-               AC_DEFINE(ADMIN_GRP, 1, [Define if the admin group should be enabled])
-               AC_MSG_RESULT([yes])
-        fi],[
-               AC_DEFINE(ADMIN_GRP, 1, [Define if the admin group should be enabled])
-               AC_MSG_RESULT([yes])
-       ]
-)
+AC_NETATALK_64BIT_LIBS
 
-NETATALK_AFS_CHECK
+dnl OS specific checks
+AC_NETATALK_OS_SPECIFIC
 
-NETATALK_CONFIG_DIRS
+dnl Check for optional admin group support
+AC_NETATALK_ADMIN_GROUP
 
-netatalk_cv_with_cracklib=no
-AC_ARG_WITH(cracklib,
-       [  --with-cracklib=DICT    enable/set location of cracklib dictionary],[
-       if test "x$withval" != "xno" ; then
-               cracklib="$withval"
-               AC_CHECK_LIB(crack, main, [
-                       AC_DEFINE(USE_CRACKLIB, 1, [Define if cracklib should be used])
-                       LIBS="$LIBS -lcrack"
-                       if test "$cracklib" = "yes"; then
-                               cracklib="/usr/$atalk_libname/cracklib_dict"
-                       fi
-                       AC_DEFINE_UNQUOTED(_PATH_CRACKLIB, "$cracklib",
-                               [path to cracklib dictionary])
-                       AC_MSG_RESULT([setting cracklib dictionary to $cracklib])
-                       netatalk_cv_with_cracklib=yes
-                       ],[
-                       AC_MSG_ERROR([cracklib not found!])
-                       ]
-               )
-       fi
-       ]
-)
-AC_MSG_CHECKING([for cracklib support])
-AC_MSG_RESULT([$netatalk_cv_with_cracklib])
-
-netatalk_cv_ddp_enabled=no
-AC_MSG_CHECKING([whether to enable DDP])
-AC_ARG_ENABLE(ddp,
-       [  --enable-ddp            enable DDP (AppleTalk)],[
-       if test "$enableval" = "yes"; then 
-               AC_MSG_RESULT([yes])
-               netatalk_cv_ddp_enabled=yes
-       else
-               AC_MSG_RESULT([yes])
-               AC_DEFINE(NO_DDP, 1, [Define if DDP should be disabled])
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-               AC_DEFINE(NO_DDP, 1, [Define if DDP should be disabled])
-       ]
-)
-
-AC_MSG_CHECKING([whether to enable debug code])
-AC_ARG_ENABLE(debug1,
-       [  --enable-debug1         enable debug code],[
-       if test "$enableval" != "no"; then
-               if test "$enableval" = "yes"; then
-                       AC_DEFINE(DEBUG1, 1, [Define if debugging information should be included])
-               else
-                       AC_DEFINE_UNQUOTED(DEBUG1, $enableval, [Define if debugging information should be included])
-               fi 
-               AC_MSG_RESULT([yes])
-       else
-               AC_MSG_RESULT([no])
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-       ]
-)
-
-AC_MSG_CHECKING([whether to enable verbose debug code])
-AC_ARG_ENABLE(debug,
-       [  --enable-debug          enable verbose debug code],[
-       if test "$enableval" != "no"; then
-               if test "$enableval" = "yes"; then
-                       AC_DEFINE(DEBUG, 1, [Define if verbose debugging information should be included])
-               else
-                       AC_DEFINE_UNQUOTED(DEBUG, $enableval, [Define if verbose debugging information should be included])
-               fi 
-               AC_MSG_RESULT([yes])
-       else
-               AC_MSG_RESULT([no])
-        AC_DEFINE(NDEBUG, 1, [Disable assertions])
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-        AC_DEFINE(NDEBUG, 1, [Disable assertions])
-       ]
-)
+dnl Check for optional AFS support
+AC_NETATALK_AFS_CHECK
 
-AC_MSG_CHECKING([whether to enable debugging with debuggers])
-AC_ARG_ENABLE(debugging,
-       [  --enable-debugging      disable SIGALRM timers and DSI tickles (eg for debugging with gdb/dbx/...)],[
-       if test "$enableval" != "no"; then
-               if test "$enableval" = "yes"; then
-                       AC_DEFINE(DEBUGGING, 1, [Define if you want to disable SIGALRM timers and DSI tickles])
-               else
-                       AC_DEFINE_UNQUOTED(DEBUGGING, $enableval, [Define if you want to disable SIGALRM timers and DSI tickles])
-               fi 
-               AC_MSG_RESULT([yes])
-       else
-               AC_MSG_RESULT([no])
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-       ]
-)
+dnl --with-pkgconfdir check to change configuration directory location
+AC_NETATALK_CONFIG_DIRS
 
-AC_SYS_LARGEFILE([], AC_MSG_ERROR([AFP 3.x support requires Large File Support.]))
-AC_CHECK_ICONV
+dnl Check for optional cracklib support
+AC_NETATALK_CRACKLIB
 
-dnl ----------- A NOTE ABOUT DROPKLUDGE
-dnl The trouble with this fix is that if you know what the file is called, it
-dnl can be read from the Unix side.  That's okay for most academic institutions
-dnl since the students don't have telnet access to the Mac servers.  There is
-dnl currently no one working on further development/fixes of DROPKLUDGE.
-dnl -----------
+dnl Check whether to enable debug code
+AC_NETATALK_DEBUG
 
-netatalk_cv_dropkludge=no
-AC_MSG_CHECKING([whether to enable experimental dropbox support])
-AC_ARG_ENABLE(dropkludge,
-       [  --enable-dropkludge     enable the experimental dropbox fix (INSECURE!) ],[
-       if test "$enableval" = "yes"; then 
-               AC_DEFINE(DROPKLUDGE, 1, [Define if you want to use the experimental dropkludge support])
-               AC_MSG_RESULT([yes])
-               netatalk_cv_dropkludge=yes
-       else
-               AC_MSG_RESULT([no])
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-       ]
-)
+dnl Check whethe to disable tickle SIGALARM stuff, which eases debugging
+AC_NETATALK_DEBUGGING
 
-netatalk_cv_force_uidgid=no
-AC_MSG_CHECKING([whether to enable forcing of uid/gid per volume])
-AC_ARG_ENABLE(force-uidgid,
-       [  --enable-force-uidgid   allow forcing of uid/gid per volume (BROKEN) ],[
-       if test "$enableval" = "yes"; then
-               AC_DEFINE(FORCE_UIDGID, 1, [Define if you want forcing of uid/gid per volume])
-               AC_MSG_RESULT([enabling forcing of uid/gid per volume])
-               AC_MSG_RESULT([yes])
-               netatalk_cv_force_uidgid=yes
-       else
-               AC_MSG_RESULT([no])
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-       ]
-)
+dnl    Check for libiconv support
+AC_NETATALK_CHECK_ICONV
 
 dnl Check for CNID database backends
-bdb_required=no
 AC_NETATALK_CNID([bdb_required=yes],[bdb_required=no])
 
 dnl Check for quota support
-AC_CHECK_QUOTA
-
-dnl Check for optional server location protocol support (used by MacOS X)
-NETATALK_SRVLOC
+AC_NETATALK_CHECK_QUOTA
 
 dnl Check for optional Zeroconf support
-NETATALK_ZEROCONF
-
-dnl Check for PAM libs
-netatalk_cv_use_pam=no
-AC_PATH_PAM([
-       use_pam_so=yes
-       compile_pam=yes
-       netatalk_cv_use_pam=yes
-       AC_DEFINE(USE_PAM, 1, [Define to enable PAM support])
-])
+AC_NETATALK_ZEROCONF
 
-netatalk_cv_use_shadowpw=no
-AC_ARG_WITH(shadow,
-       [  --with-shadow           enable shadow password support [[auto]]],
-       [netatalk_cv_use_shadowpw="$withval"],
-       [netatalk_cv_use_shadowpw=auto]
-)
+dnl Check for optional TCP-wrappers support
+AC_NETATALK_TCP_WRAPPERS
 
-if test "x$netatalk_cv_use_shadowpw" != "xno"; then
-    AC_CHECK_HEADER([shadow.h])
-    if test x"$ac_cv_header_shadow_h" = x"yes"; then
-       netatalk_cv_use_shadowpw=yes
-       AC_DEFINE(SHADOWPW, 1, [Define if shadow passwords should be used])
-    else 
-      if test "x$shadowpw" = "xyes"; then
-        AC_MSG_ERROR([shadow support not available])
-      else
-               netatalk_cv_use_shadowpw=no
-      fi
-    fi 
-fi
+dnl Check for PAM libs
+AC_NETATALK_PATH_PAM
 
-AC_MSG_CHECKING([whether shadow support should be enabled])
-if test "x$netatalk_cv_use_shadowpw" = "xyes"; then
-       AC_MSG_RESULT([yes])
-else
-       AC_MSG_RESULT([no])
-fi
-       
+dnl Check for optional shadow password support
+AC_NETATALK_SHADOW
        
-       
-netatalk_cv_use_shellcheck=yes
-AC_MSG_CHECKING([whether checking for a valid shell should be enabled])
-AC_ARG_ENABLE(shell-check,
-       [  --disable-shell-check   disable checking for a valid shell],[
-       if test "$enableval" = "no"; then 
-               AC_DEFINE(DISABLE_SHELLCHECK, 1, [Define if shell check should be disabled])
-               AC_MSG_RESULT([no])
-               netatalk_cv_use_shellcheck=no
-       else
-               AC_MSG_RESULT([yes])
-       fi
-       ],[
-               AC_MSG_RESULT([yes])
-       ]
-)
+dnl Check for optional valid-shell-check support
+AC_NETATALK_SHELL_CHECK
 
-NETATALK_TCP_WRAPPERS
+dnl Check for optional sysv initscript install
+AC_NETATALK_INIT_STYLE
 
-AC_MSG_CHECKING([whether system (fcntl) locking should be disabled])
-AC_ARG_ENABLE(locking,
-        [  --disable-locking       disable system locking],[
-               if test "$enableval" = "no"; then
-                       AC_DEFINE(DISABLE_LOCKING, 1, [Define if system (fcntl) locking should be disabled])
-                       AC_MSG_RESULT([yes])
-               else
-                       AC_MSG_RESULT([no])
-               fi
-               
-       ],[
-               AC_MSG_RESULT([no])
-       ]
+dnl Path where UAM modules shall be installed
+AC_ARG_WITH(uams-path, [  --with-uams-path=PATH   path to UAMs [[$libdir/netatalk/]]], [uams_path="$withval/"], [uams_path="$libdir/netatalk/"])
 
-)
+dnl Check for libgcrypt, if found enables DHX2 UAM
+AC_NETATALK_PATH_LIBGCRYPT([1:1.2.3])
 
-AC_ARG_ENABLE(redhat,
-       [  --enable-redhat         obsoleted ],[
-       echo "ERROR: --enable-redhat is obsoleted. Use --enable-redhat-sysv or --enable-redhat-systemd."
-       exit 1
-       ]
-)
+dnl Check for openssl, if found enables DHX UAM and Randnum UAM
+AC_NETATALK_PATH_SSL
 
-AC_ARG_ENABLE(redhat-sysv,
-       [  --enable-redhat-sysv    use redhat-style sysv (upstart) configuration ],[
-       if test "$enableval" = "yes"; then
-               sysv_style=redhat-sysv
-       fi
-       AC_MSG_RESULT([enabling redhat-style sysv support])
-       ]
-)
-
-AC_ARG_ENABLE(redhat-systemd,
-       [  --enable-redhat-systemd use redhat-style systemd (>=Fedora15) configuration ],[
-       if test "$enableval" = "yes"; then
-               sysv_style=redhat-systemd
-       fi
-       AC_MSG_RESULT([enabling redhat-style systemd support])
-       ]
-)
+dnl Check for Berkeley DB library
+AC_NETATALK_PATH_BDB
 
-AC_ARG_ENABLE(suse,
-       [  --enable-suse           obsoleted ],[
-       echo "ERROR: --enable-suse is obsoleted. Use --enable-suse-sysv or --enable-suse-systemd."
-       exit 1
-       ]
-)
+dnl Check for crypt
+AC_NETATALK_CRYPT
 
-AC_ARG_ENABLE(suse-sysv,
-       [  --enable-suse-sysv      use suse-style sysv configuration ],[
-       if test "$enableval" = "yes"; then
-               sysv_style=suse-sysv
-       fi
-       AC_MSG_RESULT([enabling suse-style sysv support])
-       ]
-)
+dnl Check for building PGP UAM module
+AC_NETATALK_PGP_UAM
 
-AC_ARG_ENABLE(suse-systemd,
-       [  --enable-suse-systemd   use suse-style systemd (>=openSUSE12.1) configuration ],[
-       if test "$enableval" = "yes"; then
-               sysv_style=suse-systemd
-       fi
-       AC_MSG_RESULT([enabling suse-style systemd support])
-       ]
-)
+dnl Check for building Kerberos V UAM module
+AC_NETATALK_KRB5_UAM
 
-AC_ARG_ENABLE(gentoo,
-       [  --enable-gentoo         use gentoo-style sysv configuration ],[
-       if test "$enableval" = "yes"; then
-               sysv_style=gentoo
-       fi
-       AC_MSG_RESULT([enabling gentoo-style sysv support])
-       ]
-)
+dnl Check for Kerberos 5 support
+AC_NETATALK_KERBEROS
 
-AC_ARG_ENABLE(netbsd,
-       [  --enable-netbsd         use NetBSD-style rc.d configuration ],
-       if test "x$enableval" = "xyes"; then
-               sysv_style=netbsd
-       fi
-       AC_MSG_RESULT([enabling NetBSD-style rc.d support])
-)
+dnl Check for overwrite the config files or not
+AC_NETATALK_OVERWRITE_CONFIG
 
-AC_ARG_ENABLE(debian,
-       [  --enable-debian         use debian-style sysv configuration ],[
-       if test "$enableval" = "yes"; then
-               sysv_style=debian
-       fi
-       AC_MSG_RESULT([enabling debian-style sysv support])
-       ]
-)
+dnl Check for LDAP support, for client-side ACL visibility
+AC_NETATALK_LDAP
 
-AC_ARG_ENABLE(systemd,
-       [  --enable-systemd        use general systemd configuration],[
-       if test "$enableval" = "yes"; then
-               sysv_style=systemd
-       fi
-       AC_MSG_RESULT([enabling general systemd support])
-       ]
-)
+dnl Check for ACL support
+AC_NETATALK_ACL
 
-dnl ----- timelord compilation (disabled by default)
-AC_MSG_CHECKING([whether timelord should be compiled])
-compile_timelord=no
-AC_ARG_ENABLE(timelord,
-       [  --enable-timelord       enable compilation of timelord server],
-       [compile_timelord="$enableval"],
-       [compile_timelord="no"]
-)
-AC_MSG_RESULT([$compile_timelord])
+dnl Check for Extended Attributes support
+AC_NETATALK_EXTENDED_ATTRIBUTES
 
-dnl ----- a2boot compilation (disabled by default)
-AC_MSG_CHECKING([whether a2boot should be compiled])
-compile_a2boot=no
-AC_ARG_ENABLE(a2boot,
-       [  --enable-a2boot         enable compilation of Apple2 boot server],
-       [compile_a2boot="$enableval"],
-       [compile_a2boot="no"]
-)
-AC_MSG_RESULT([$compile_a2boot])
+dnl Check for libsmbsharemodes from Samba for Samba/Netatalk access/deny/share modes interop
+AC_NETATALK_SMB_SHAREMODES
 
-AC_ARG_WITH(uams-path,
-       [  --with-uams-path=PATH   path to UAMs [[PKGCONF/uams]]],[
-               uams_path="$withval"
-       ],[
-               uams_path="${PKGCONFDIR}/uams"
-       ]
-)
+dnl Check if realpath() takes NULL
+AC_NETATALK_REALPATH
 
-NETATALK_AC_CUPS
+dnl Check for sendfile()
+AC_NETATALK_SENDFILE
 
-dnl check if we can use attribute unused (gcc only) from ethereal
-AC_MSG_CHECKING(to see if we can add '__attribute__((unused))' to CFLAGS)
-if test x$GCC != x ; then
-  CFLAGS="-D_U_=\"__attribute__((unused))\" $CFLAGS"
-  AC_MSG_RESULT(yes)
-else
-  CFLAGS="-D_U_=\"\" $CFLAGS"
-  AC_MSG_RESULT(no)
-fi
+dnl Check whether bundled libevent shall not be used
+AC_NETATALK_LIBEVENT
 
-dnl --------------------------------------------------------------------------
 dnl FHS stuff has to be done last because it overrides other defaults
-dnl --------------------------------------------------------------------------
+AC_NETATALK_FHS
 
-AC_MSG_CHECKING([whether to use Filesystem Hierarchy Standard (FHS) compatibility])
-AC_ARG_ENABLE(fhs,
-       [  --enable-fhs            use Filesystem Hierarchy Standard (FHS) compatibility],[
-       if test "$enableval" = "yes"; then
-               uams_path="${libdir}/netatalk"
-               sysconfdir="/etc"
-               PKGCONFDIR=${sysconfdir}/netatalk
-               SERVERTEXT="${PKGCONFDIR}/msg"
-               use_pam_so=yes
-               mandir="/usr/share/man"
-               AC_DEFINE(FHS_COMPATIBILITY, 1, [Define if you want compatibily with the FHS])
-               AC_MSG_RESULT([yes])
-       else
-               AC_MSG_RESULT([no])
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-       ]
-)
-
-dnl --------------------------------------------------------------------------
-dnl post-FHS substitutions, etc
-dnl --------------------------------------------------------------------------
+AC_DEVELOPER
 
-dnl ***** UAMS_PATH
-dnl AC_DEFINE_UNQUOTED(UAMS_PATH, "${uams_path}",
-dnl    [path to UAMs [default=PKGCONF/uams]])
+CFLAGS="-I\$(top_srcdir)/include -I\$(top_srcdir)/sys $CFLAGS"
 UAMS_PATH="${uams_path}"
-AC_SUBST(UAMS_PATH)
-
-dnl --------------------------------------------------------------------------
-dnl drop in includes for top level directory structures here...
-dnl --------------------------------------------------------------------------
-
-dnl Note: $(top_srcdir)/include should be added before all other includes
-dnl       so that includes from that directory a preferred to includes from
-dnl       /usr/include or similar places.
-LIBS="$LIBS -L\$(top_srcdir)/libatalk"
-CFLAGS="-I\$(top_srcdir)/include $CFLAGS -I\$(top_srcdir)/sys"
-
-AC_DEFINE(OPEN_NOFOLLOW_ERRNO, ELOOP, errno returned by open with O_NOFOLLOW)
-
-dnl --------------------------------------------------------------------------
-dnl specific configuration comes in here:
-dnl --------------------------------------------------------------------------
-
-dnl ac_cv_target_os is now host_os, ac_cv_target_cpu is now host_cpu
-
-dnl --------------------- determine operating system from "target"
-case "$host_os" in
-       *aix*)                          this_os=aix ;;
-       *kfreebsd*-gnu)                 this_os=kfreebsd-gnu ;;
-       *freebsd*)                      this_os=freebsd ;;
-       *hpux11*)                       this_os=hpux11 ;;
-       *irix*)                         this_os=irix ;;
-       *linux*)                        this_os=linux ;;
-       *osx*)                          this_os=macosx ;;
-       *darwin*)                       this_os=macosx ;;
-       *netbsd*)                       this_os=netbsd ;;
-       *openbsd*)                      this_os=openbsd ;;
-       *osf*)                          this_os=tru64 ;;
-       *solaris*)                      this_os=solaris ;;
-esac
-
-case "$host_cpu" in
-       i386|i486|i586|i686|k7)         this_cpu=x86 ;;
-       alpha)                                          this_cpu=alpha ;;
-       mips)                                           this_cpu=mips ;;
-       powerpc|ppc)                            this_cpu=ppc ;;
-esac
-
-dnl --------------------- GNU source
-case "$this_os" in
-       linux)  AC_DEFINE(_GNU_SOURCE, 1, [Whether to use GNU libc extensions])
-        ;;
-     kfreebsd-gnu) AC_DEFINE(_GNU_SOURCE, 1, [Whether to use GNU libc extensions])
-        ;;
-esac
-
-dnl --------------------- operating system specific flags (port from sys/*)
-
-dnl ----- AIX specific -----
-if test x"$this_os" = "xaix"; then
-       AC_MSG_RESULT([ * AIX specific configuration])
-       AC_DEFINE(NO_STRUCT_TM_GMTOFF, 1, [Define if the gmtoff member of struct tm is not available])
-
-       dnl This is probably a lie; AIX 4.3 supports a 64-bit long
-       dnl compilation environment.  It's enough to get things defined
-       dnl right in endian.h provided that long long is supported, though.
-       AC_DEFINE(HAVE_32BIT_LONGS, 1, [Define if the data type long has 32 bit])
-fi
-
-dnl ----- FreeBSD specific -----
-if test x"$this_os" = "xfreebsd"; then 
-       AC_MSG_RESULT([ * FreeBSD specific configuration])
-       AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
-       AC_DEFINE(FREEBSD, 1, [Define if OS is FreeBSD])
-    AC_DEFINE(OPEN_NOFOLLOW_ERRNO, EMLINK, errno returned by open with O_NOFOLLOW)
-fi
-
-dnl ----- GNU/kFreeBSD specific -----
-if test x"$this_os" = "xkfreebsd-gnu"; then 
-       AC_MSG_RESULT([ * GNU/kFreeBSD specific configuration])
-       AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
-       AC_DEFINE(FREEBSD, 1, [Define if OS is FreeBSD])
-    AC_DEFINE(OPEN_NOFOLLOW_ERRNO, EMLINK, errno returned by open with O_NOFOLLOW)
-fi
-
-dnl ----- HP-UX 11 specific -----
-if test x"$this_os" = "xhpux11"; then
-       AC_MSG_RESULT([ * HP-UX 11 specific configuration])
-
-       AC_DEFINE(_ISOC9X_SOURCE, 1, [Compatibility macro])
-       AC_DEFINE(NO_STRUCT_TM_GMTOFF, 1, [Define if the gmtoff member of struct tm is not available])
-fi
-
-dnl ----- IRIX specific -----
-if test x"$this_os" = "xirix"; then
-       AC_MSG_RESULT([ * IRIX specific configuration])
-
-       AC_DEFINE(NO_STRUCT_TM_GMTOFF, 1, [Define if the gmtoff member of struct tm is not available])
-fi
-
-dnl ----- Linux specific -----
-if test x"$this_os" = "xlinux"; then 
-       AC_MSG_RESULT([ * Linux specific configuration])
-       
-       dnl ----- kernel 2.6 changed struct at_addr to atalk_addr
-       AC_MSG_CHECKING([for struct atalk_addr])
-dnl    AC_COMPILE_IFELSE([
-       AC_TRY_COMPILE([
-#include <sys/socket.h>
-#include <asm/types.h>
-#include <linux/atalk.h>
-
-       struct atalk_addr foo;
-],
-[ ], [
-               ac_have_atalk_addr=yes
-               AC_MSG_RESULT([yes])
-       ], [
-               AC_MSG_RESULT([no])
-       ])
-
-if test "x$ac_have_atalk_addr" = "xyes"; then
-       AC_DEFINE(HAVE_ATALK_ADDR, 1, [set if struct at_addr is called atalk_addr])
-fi
-
-       dnl ----- check if we need the quotactl wrapper
-#      AC_CHECK_HEADERS(sys/quota.h linux/quota.h)
-#      AC_CHECK_FUNC(quotactl,,
-#              AC_DEFINE(NEED_QUOTACTL_WRAPPER, 1, [Define if the quotactl wrapper is needed])
-#              AC_MSG_RESULT([enabling quotactl wrapper])
-#      )
-
-        # For quotas on Linux XFS filesystems
-        
-        # For linux > 2.5.56
-        AC_CHECK_HEADERS(linux/dqblk_xfs.h,,
-               [AC_CHECK_HEADERS(linux/xqm.h linux/xfs_fs.h)
-               AC_CHECK_HEADERS(xfs/libxfs.h xfs/xqm.h xfs/xfs_fs.h)]
-       )
-
-
-       dnl ----- as far as I can tell, dbtob always does the wrong thing
-       dnl ----- on every single version of linux I've ever played with.
-       dnl ----- see etc/afpd/quota.c
-       AC_DEFINE(HAVE_BROKEN_DBTOB, 1, [Define if dbtob is broken])
-
-
-       dnl ----- Linux/alpha specific -----
-       if test x"$this_cpu" = "xalpha"; then 
-               AC_MSG_RESULT([enabling gcc memcpy bug workaround])
-               AC_DEFINE(HAVE_GCC_MEMCPY_BUG, 1, [Define if memcpy is buggy])
-       fi
-       need_dash_r=no
-
-
-fi
-
-dnl ----- Mac OSX specific -----
-if test x"$this_os" = "xmacosx"; then 
-       AC_MSG_RESULT([ * Mac OSX specific configuration])
-       AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
-       AC_DEFINE(HAVE_2ARG_DBTOB, 1, [Define if dbtob takes two arguments])
-       dnl AC_DEFINE(NO_DLFCN_H)
-       AC_DEFINE(NO_DDP, 1, [Define if DDP should be disabled])
-       AC_DEFINE(NO_QUOTA_SUPPORT, 1, [Define if Quota support should be disabled])
-       AC_DEFINE(MACOSX_SERVER, 1, [Define if compiling for MacOS X Server])
-fi
-
-dnl ----- NetBSD specific -----
-if test x"$this_os" = "xnetbsd"; then 
-       AC_MSG_RESULT([ * NetBSD specific configuration])
-       AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
-       AC_DEFINE(NETBSD, 1, [Define if OS is NetBSD])
-    AC_DEFINE(OPEN_NOFOLLOW_ERRNO, EFTYPE, errno returned by open with O_NOFOLLOW)
-
-       CFLAGS="-I\$(top_srcdir)/sys/netbsd $CFLAGS"
-       need_dash_r=yes 
-
-       dnl ----- NetBSD does not have crypt.h, uses unistd.h -----
-       AC_DEFINE(UAM_DHX, 1, [Define if the DHX UAM modules should be compiled])
-fi
-
-dnl ----- OpenBSD specific -----
-if test x"$this_os" = "xopenbsd"; then 
-       AC_MSG_RESULT([ * OpenBSD specific configuration])
-    AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
-       dnl ----- OpenBSD does not have crypt.h, uses unistd.h -----
-       AC_DEFINE(UAM_DHX, 1, [Define if the DHX UAM modules should be compiled])
-    AC_DEFINE(NO_DDP, 1, [Define if DDP should be disabled])
-fi
-
-dnl ----- Solaris specific -----
-if test x"$this_os" = "xsolaris"; then 
-       AC_MSG_RESULT([ * Solaris specific configuration])
-       AC_DEFINE(__svr4__, 1, [Solaris compatibility macro])
-       AC_DEFINE(_ISOC9X_SOURCE, 1, [Compatibility macro])
-       AC_DEFINE(NO_STRUCT_TM_GMTOFF, 1, [Define if the gmtoff member of struct tm is not available])
-       AC_DEFINE(SOLARIS, 1, [Solaris compatibility macro])
-    AC_DEFINE(_XOPEN_SOURCE, 600, [Solaris compilation environment])
-    AC_DEFINE(__EXTENSIONS__,  1, [Solaris compilation environment])
-       CFLAGS="-I\$(top_srcdir)/sys/generic $CFLAGS"
-       need_dash_r=yes
-       sysv_style=solaris
-
-       solaris_module=no
-       AC_MSG_CHECKING([if we can build Solaris kernel module])
-       if test -x /usr/ccs/bin/ld && test x"$netatalk_cv_ddp_enabled" = x"yes" ; then
-               solaris_module=yes
-       fi
-       AC_MSG_RESULT([$solaris_module])
-
-       COMPILE_64BIT_KMODULE=no
-       KCFLAGS=""
-       KLDFLAGS=""
-       COMPILE_KERNEL_GCC=no
-
-       if test "$solaris_module" = "yes"; then
-          dnl Solaris kernel module stuff
-           AC_MSG_CHECKING([if we have to build a 64bit kernel module])
-
-          # check for isainfo, if not found it has to be a 32 bit kernel (<=2.6)       
-          if test -x /usr/bin/isainfo; then
-               # check for 64 bit platform
-               if isainfo -kv | grep '^64-bit'; then
-                       COMPILE_64BIT_KMODULE=yes
-               fi
-          fi
-
-          AC_MSG_RESULT([$COMPILE_64BIT_KMODULE])
-
-          if test "${GCC}" = yes; then
-               COMPILE_KERNEL_GCC=yes
-               if test "$COMPILE_64BIT_KMODULE" = yes; then
-               
-                        AC_MSG_CHECKING([if we can build a 64bit kernel module])
-                       
-                        case `$CC --version 2>/dev/null` in
-                       [[12]].* | 3.0.*)
-                               COMPILE_64BIT_KMODULE=no
-                               COMPILE_KERNEL_GCC=no   
-                               solaris_module=no;;
-                       *)
-                               # use for 64 bit
-                               KCFLAGS="-m64"
-                               #KLDFLAGS="-melf64_sparc"
-                               KLDFLAGS="-64";;
-                       esac    
-                       
-                       AC_MSG_RESULT([$COMPILE_64BIT_KMODULE])
-                       
-               else
-                       KCFLAGS=""
-                       KLDFLAGS=""
-               fi
-               KCFLAGS="$KCFLAGS -D_KERNEL -Wall -Wstrict-prototypes"
-           else
-               if test "$COMPILE_64BIT_KMODULE" = yes; then
-                # use Sun CC (for a 64-bit kernel, uncomment " -xarch=v9 -xregs=no%appl ")
-                       KCFLAGS="-xarch=v9 -xregs=no%appl"
-                       KLDFLAGS="-64"
-               else
-                       KCFLAGS=""
-                       KLDFLAGS=""
-               fi
-               KCFLAGS="-D_KERNEL $KCFLAGS -mno-app-regs -munaligned-doubles -fpcc-struct-return"
-          fi
-
-           AC_CACHE_CHECK([for timeout_id_t],netatalk_cv_HAVE_TIMEOUT_ID_T,[
-           AC_TRY_LINK([\
-#include <sys/stream.h>
-#include <sys/ddi.h>],
-[\
-timeout_id_t dummy;
-],
-netatalk_cv_HAVE_TIMEOUT_ID_T=yes,netatalk_cv_HAVE_TIMEOUT_ID_T=no,netatalk_cv_HAVE_TIMEOUT_ID_T=cross)])
-
-          AC_DEFINE(HAVE_TIMEOUT_ID_T, test x"$netatalk_cv_HAVE_TIMEOUT_ID" = x"yes", [define for timeout_id_t])
-       fi
-
-       AC_SUBST(COMPILE_KERNEL_GCC)
-       AC_SUBST(COMPILE_64BIT_KMODULE)
-       AC_SUBST(KCFLAGS)
-       AC_SUBST(KLDFLAGS)
-fi
-
-dnl ----- Tru64 specific -----
-if test x"$this_os" = "xtru64"; then 
-       AC_MSG_RESULT([ * Tru64 specific configuration])
-       AC_DEFINE(NO_DDP, 1, [Define if DDP should be disabled])
-       AC_DEFINE(HAVE_64BIT_LONGS, 1, [Define if the data type long has 64 bit])
-       dnl AC_DEFINE(USE_MOUNT_H)
-       AC_DEFINE(USE_OLD_RQUOTA, 1, [Define to use old rquota])
-       dnl AC_DEFINE(USE_UFS_QUOTA_H)
-       AC_DEFINE(TRU64, 1, [Define on Tru64 platforms])
-       AC_DEFINE(_OSF_SOURCE, 1, [Define if the *passwd UAMs should be used])
-       AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Define for Berkeley DB 4])
-       AC_CHECK_LIB(security,set_auth_parameters)
-       CFLAGS="-I\$(top_srcdir)/sys/tru64 $CFLAGS"
-       need_dash_r=no
-       sysv_style=tru64
-fi
-
-dnl ------ Check for sendfile() --------
-netatalk_cv_search_sendfile=yes
-AC_ARG_ENABLE(sendfile,
-    [  --disable-sendfile       disable sendfile syscall],
-    [if test x"$enableval" = x"no"; then
-            netatalk_cv_search_sendfile=no
-        fi]
-)
-
-if test x"$netatalk_cv_search_sendfile" = x"yes"; then
-   case "$host_os" in
-   *linux*)
-        AC_DEFINE(SENDFILE_FLAVOR_LINUX,1,[Whether linux sendfile() API is available])
-        AC_CHECK_FUNC([sendfile], [netatalk_cv_HAVE_SENDFILE=yes])
-        ;;
-
-    *solaris*)
-        AC_DEFINE(SENDFILE_FLAVOR_SOLARIS, 1, [Solaris sendfile()])
-        AC_SEARCH_LIBS(sendfile, sendfile)
-        AC_CHECK_FUNC([sendfile], [netatalk_cv_HAVE_SENDFILE=yes])
-        ;;
-
-    *freebsd*)
-        AC_DEFINE(SENDFILE_FLAVOR_BSD, 1, [Define if the sendfile() function uses BSD semantics])
-        AC_CHECK_FUNC([sendfile], [netatalk_cv_HAVE_SENDFILE=yes])
-        ;;
-
-    *)
-        ;;
-
-    esac
-
-    if test x"$netatalk_cv_HAVE_SENDFILE" = x"yes"; then
-        AC_DEFINE(WITH_SENDFILE,1,[Whether sendfile() should be used])
-    fi
-fi
-
-dnl -- check for libgcrypt, if found enables DHX UAM
-AM_PATH_LIBGCRYPT([1:1.2.3],[neta_cv_compile_dhx2=yes
-                       neta_cv_have_libgcrypt=yes
-                       AC_MSG_NOTICE([Enabling DHX2 UAM])
-                       AC_DEFINE(HAVE_LIBGCRYPT, 1, [Define if the DHX2 modules should be built with libgcrypt])
-                       AC_DEFINE(UAM_DHX2, 1, [Define if the DHX2 UAM modules should be compiled])
-                       ])
-
-dnl -- look for openssl, if found enables DHX UAM and Randnum UAM
-AC_PATH_SSL
-
-dnl Check for Berkeley DB library
-if test "x$bdb_required" = "xyes"; then
-       AC_PATH_BDB(, [
-               AC_MSG_RESULT([])
-               AC_MSG_RESULT([Make sure you have the required Berkeley DB libraries AND headers installed.])
-               AC_MSG_RESULT([You can download the latest version from http://www.sleepycat.com.])
-               AC_MSG_RESULT([If you have installed BDB in a non standard location use the])
-               AC_MSG_RESULT([--with-bdb=/path/to/bdb configure option and make sure])
-               AC_MSG_RESULT([your linker is configured to check for libraries there.])
-               AC_MSG_ERROR([Berkeley DB library required but not found!])
-       ])
-fi
-
-dnl -- check for crypt
-AC_CRYPT
-
-dnl --------------------- check for building PGP UAM module
-
-AC_MSG_CHECKING([whether the PGP UAM should be build])
-AC_ARG_ENABLE(pgp-uam,
-       [  --enable-pgp-uam        enable build of PGP UAM module],[
-       if test "$enableval" = "yes"; then 
-               if test "x$neta_cv_have_openssl" = "xyes"; then 
-                       AC_DEFINE(UAM_PGP, 1, [Define if the PGP UAM module should be compiled])
-                       compile_pgp=yes
-                       AC_MSG_RESULT([yes])
-               else
-                       AC_MSG_RESULT([no])
-               fi
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-       ]
-)
-
-dnl --------------------- check for building Kerberos v4 UAM module
-
-AC_MSG_CHECKING([whether the Kerberos IV UAM should be build])
-AC_ARG_ENABLE(krb4-uam,
-       [  --enable-krb4-uam       enable build of Kerberos v4 UAM module],[
-       if test "$enableval" = "yes"; then
-               AC_DEFINE(UAM_KRB4, 1, [Define if the Kerberos 4 UAM module should be compiled])
-               compile_kerberos=yes
-               AC_MSG_RESULT([yes])
-       else
-               AC_MSG_RESULT([no])
-       fi
-       ],[
-               AC_MSG_RESULT([no])
-       ]
-)
-
-dnl --------------------- check for building Kerberos V UAM module
-
-netatalk_cv_build_krb5_uam=no
-AC_ARG_ENABLE(krbV-uam,
-       [  --enable-krbV-uam       enable build of Kerberos V UAM module],
-       [
-               if test x"$enableval" = x"yes"; then
-                       NETATALK_GSSAPI_CHECK([
-                               netatalk_cv_build_krb5_uam=yes
-                       ],[
-                               AC_MSG_ERROR([need GSSAPI to build Kerberos V UAM])
-                       ])
-               fi
-       ]
-       
-)
-
-AC_MSG_CHECKING([whether Kerberos V UAM should be build])
-if test x"$netatalk_cv_build_krb5_uam" = x"yes"; then
-       AC_MSG_RESULT([yes])
-else
-       AC_MSG_RESULT([no])
-fi
-AM_CONDITIONAL(USE_GSSAPI, test x"$netatalk_cv_build_krb5_uam" = x"yes")
-
-dnl --------------------- overwrite the config files . . . or not.
-
-AC_MSG_CHECKING([whether configuration files should be overwritten])
-AC_ARG_ENABLE(overwrite,
-       [  --enable-overwrite      overwrite configuration files during installation],
-       [OVERWRITE_CONFIG="${enable_overwrite}"],
-       [OVERWRITE_CONFIG="no"]
-)
-AC_MSG_RESULT([$OVERWRITE_CONFIG])
-
-dnl --------------------- check for LDAP support, for client-side ACL visibility
-AC_MSG_CHECKING(for LDAP (necessary for client-side ACL visibility))
-AC_ARG_WITH(ldap,
-    [AS_HELP_STRING([--with-ldap],
-        [LDAP support (default=auto)])],
-    [ case "$withval" in
-      yes|no)
-          with_ldap="$withval"
-                 ;;
-      *)
-          with_ldap=auto
-          ;;
-      esac ])
-AC_MSG_RESULT($with_ldap)
-
-if test x"$with_ldap" != x"no" ; then
-       AC_CHECK_HEADER([ldap.h], with_ldap=yes,
-        [ if test x"$with_ldap" = x"yes" ; then
-            AC_MSG_ERROR([Missing LDAP headers])
-        fi
-               with_ldap=no
-        ])
-       AC_CHECK_LIB(ldap, ldap_init, with_ldap=yes,
-        [ if test x"$with_ldap" = x"yes" ; then
-            AC_MSG_ERROR([Missing LDAP library])
-        fi
-               with_ldap=no
-        ])
-fi
-
-if test x"$with_ldap" = x"yes"; then
-       AC_DEFINE(HAVE_LDAP,1,[Whether LDAP is available])
-fi
-
-dnl --------------------- check for ACL support
-AC_MSG_CHECKING(whether to support ACLs)
-AC_ARG_WITH(acls,
-    [AS_HELP_STRING([--with-acls],
-        [Include ACL support (default=auto)])],
-    [ case "$withval" in
-      yes|no)
-          with_acl_support="$withval"
-                 ;;
-      *)
-          with_acl_support=auto
-          ;;
-      esac ],
-    [with_acl_support=auto])
-AC_MSG_RESULT($with_acl_support)
-
-if test x"$with_acl_support" = x"no"; then
-       AC_MSG_RESULT(Disabling ACL support)
-       AC_DEFINE(HAVE_NO_ACLS,1,[Whether no ACLs support should be built in])
-else
-    with_acl_support=yes
-fi
-
-if test x"$with_acl_support" = x"yes" ; then
-       AC_MSG_NOTICE(checking whether ACL support is available:)
-       case "$host_os" in
-       *sysv5*)
-               AC_MSG_NOTICE(Using UnixWare ACLs)
-               AC_DEFINE(HAVE_UNIXWARE_ACLS,1,[Whether UnixWare ACLs are available])
-               ;;
-       *solaris*)
-               AC_MSG_NOTICE(Using solaris ACLs)
-               AC_DEFINE(HAVE_SOLARIS_ACLS,1,[Whether solaris ACLs are available])
-               ACL_LIBS="$ACL_LIBS -lsec"
-               ;;
-       *hpux*)
-               AC_MSG_NOTICE(Using HPUX ACLs)
-               AC_DEFINE(HAVE_HPUX_ACLS,1,[Whether HPUX ACLs are available])
-               ;;
-       *irix*)
-               AC_MSG_NOTICE(Using IRIX ACLs)
-               AC_DEFINE(HAVE_IRIX_ACLS,1,[Whether IRIX ACLs are available])
-               ;;
-       *aix*)
-               AC_MSG_NOTICE(Using AIX ACLs)
-               AC_DEFINE(HAVE_AIX_ACLS,1,[Whether AIX ACLs are available])
-               ;;
-       *osf*)
-               AC_MSG_NOTICE(Using Tru64 ACLs)
-               AC_DEFINE(HAVE_TRU64_ACLS,1,[Whether Tru64 ACLs are available])
-               ACL_LIBS="$ACL_LIBS -lpacl"
-               ;;
-       *darwin*)
-               AC_MSG_NOTICE(ACLs on Darwin currently not supported)
-               AC_DEFINE(HAVE_NO_ACLS,1,[Whether no ACLs support is available])
-               ;;
-       *)
-               AC_CHECK_LIB(acl,acl_get_file,[ACL_LIBS="$ACL_LIBS -lacl"])
-               case "$host_os" in
-               *linux*)
-                       AC_CHECK_LIB(attr,getxattr,[ACL_LIBS="$ACL_LIBS -lattr"])
-                       ;;
-               esac
-               AC_CACHE_CHECK([for POSIX ACL support],netatalk_cv_HAVE_POSIX_ACLS,[
-                       acl_LIBS=$LIBS
-                       LIBS="$LIBS $ACL_LIBS"
-                       AC_TRY_LINK([
-                               #include <sys/types.h>
-                               #include <sys/acl.h>
-                       ],[
-                               acl_t acl;
-                               int entry_id;
-                               acl_entry_t *entry_p;
-                               return acl_get_entry(acl, entry_id, entry_p);
-                       ],
-                       [netatalk_cv_HAVE_POSIX_ACLS=yes],
-                       [netatalk_cv_HAVE_POSIX_ACLS=no
-                with_acl_support=no])
-                       LIBS=$acl_LIBS
-               ])
-               if test x"$netatalk_cv_HAVE_POSIX_ACLS" = x"yes"; then
-                       AC_MSG_NOTICE(Using POSIX ACLs)
-                       AC_DEFINE(HAVE_POSIX_ACLS,1,[Whether POSIX ACLs are available])
-                       AC_CACHE_CHECK([for acl_get_perm_np],netatalk_cv_HAVE_ACL_GET_PERM_NP,[
-                               acl_LIBS=$LIBS
-                               LIBS="$LIBS $ACL_LIBS"
-                               AC_TRY_LINK([
-                                       #include <sys/types.h>
-                                       #include <sys/acl.h>
-                               ],[
-                                       acl_permset_t permset_d;
-                                       acl_perm_t perm;
-                                       return acl_get_perm_np(permset_d, perm);
-                               ],
-                               [netatalk_cv_HAVE_ACL_GET_PERM_NP=yes],
-                               [netatalk_cv_HAVE_ACL_GET_PERM_NP=no])
-                               LIBS=$acl_LIBS
-                       ])
-                       if test x"$netatalk_cv_HAVE_ACL_GET_PERM_NP" = x"yes"; then
-                               AC_DEFINE(HAVE_ACL_GET_PERM_NP,1,[Whether acl_get_perm_np() is available])
-                       fi
-
-                       AC_CACHE_CHECK([for acl_from_mode], netatalk_cv_HAVE_ACL_FROM_MODE,[
-                               acl_LIBS=$LIBS
-                               LIBS="$LIBS $ACL_LIBS"
-                AC_CHECK_FUNCS(acl_from_mode,
-                               [netatalk_cv_HAVE_ACL_FROM_MODE=yes],
-                               [netatalk_cv_HAVE_ACL_FROM_MODE=no])
-                               LIBS=$acl_LIBS
-                       ])
-                       if test x"netatalk_cv_HAVE_ACL_FROM_MODE" = x"yes"; then
-                               AC_DEFINE(HAVE_ACL_FROM_MODE,1,[Whether acl_from_mode() is available])
-                       fi
-
-
-               else
-                       AC_MSG_NOTICE(ACL support is not avaliable)
-                       AC_DEFINE(HAVE_NO_ACLS,1,[Whether no ACLs support is available])
-               fi
-               ;;
-    esac
-fi
-
-if test x"$with_acl_support" = x"yes" ; then
-   AC_CHECK_HEADERS([acl/libacl.h])
-    AC_DEFINE(HAVE_ACLS,1,[Whether ACLs support is available])
-    AC_SUBST(ACL_LIBS)
-fi
-
-dnl --------------------- check for Extended Attributes support
-neta_cv_eas="ad"
-neta_cv_eas_sys_found=no
-neta_cv_eas_sys_not_found=no
-
-AC_CHECK_HEADERS(sys/attributes.h attr/xattr.h sys/xattr.h sys/extattr.h sys/uio.h sys/ea.h)
-
-case "$this_os" in
-
-  *osf*)
-       AC_SEARCH_LIBS(getproplist, [proplist])
-       AC_CHECK_FUNCS([getproplist fgetproplist setproplist fsetproplist],
-                   [neta_cv_eas_sys_found=yes],
-                   [neta_cv_eas_sys_not_found=yes])
-       AC_CHECK_FUNCS([delproplist fdelproplist add_proplist_entry get_proplist_entry],,
-                   [neta_cv_eas_sys_not_found=yes])
-       AC_CHECK_FUNCS([sizeof_proplist_entry],,
-                   [neta_cv_eas_sys_not_found=yes])
-  ;;
-
-  *solaris*)
-       AC_CHECK_FUNCS([attropen],
-                   [neta_cv_eas_sys_found=yes],
-                   [neta_cv_eas_sys_not_found=yes])
-  ;;
-
-  'freebsd')
-    AC_CHECK_FUNCS([extattr_delete_fd extattr_delete_file extattr_delete_link],
-                   [neta_cv_eas_sys_found=yes],
-                   [neta_cv_eas_sys_not_found=yes])
-    AC_CHECK_FUNCS([extattr_get_fd extattr_get_file extattr_get_link],,
-                   [neta_cv_eas_sys_not_found=yes])
-    AC_CHECK_FUNCS([extattr_list_fd extattr_list_file extattr_list_link],,
-                   [neta_cv_eas_sys_not_found=yes])
-    AC_CHECK_FUNCS([extattr_set_fd extattr_set_file extattr_set_link],,
-                   [neta_cv_eas_sys_not_found=yes])
-  ;;
-
-  *freebsd4* | *dragonfly* )
-    AC_DEFINE(BROKEN_EXTATTR, 1, [Does extattr API work])
-  ;;
-
-  *)
-       AC_SEARCH_LIBS(getxattr, [attr])
-
-    if test "x$neta_cv_eas_sys_found" != "xyes" ; then
-       AC_CHECK_FUNCS([getxattr lgetxattr fgetxattr listxattr llistxattr],
-                      [neta_cv_eas_sys_found=yes],
-                      [neta_cv_eas_sys_not_found=yes])
-          AC_CHECK_FUNCS([flistxattr removexattr lremovexattr fremovexattr],,
-                      [neta_cv_eas_sys_not_found=yes])
-          AC_CHECK_FUNCS([setxattr lsetxattr fsetxattr],,
-                      [neta_cv_eas_sys_not_found=yes])
-    fi
-
-    if test "x$neta_cv_eas_sys_found" != "xyes" ; then
-          AC_CHECK_FUNCS([getea fgetea lgetea listea flistea llistea],
-                      [neta_cv_eas_sys_found=yes],
-                      [neta_cv_eas_sys_not_found=yes])
-          AC_CHECK_FUNCS([removeea fremoveea lremoveea setea fsetea lsetea],,
-                      [neta_cv_eas_sys_not_found=yes])
-    fi
-
-    if test "x$neta_cv_eas_sys_found" != "xyes" ; then
-          AC_CHECK_FUNCS([attr_get attr_list attr_set attr_remove],,
-                      [neta_cv_eas_sys_not_found=yes])
-       AC_CHECK_FUNCS([attr_getf attr_listf attr_setf attr_removef],,
-                      [neta_cv_eas_sys_not_found=yes])
-    fi
-  ;;
-esac
-
-# Do xattr functions take additional options like on Darwin?
-if test x"$ac_cv_func_getxattr" = x"yes" ; then
-       AC_CACHE_CHECK([whether xattr interface takes additional options], smb_attr_cv_xattr_add_opt, [
-               old_LIBS=$LIBS
-               LIBS="$LIBS $ACL_LIBS"
-               AC_TRY_COMPILE([
-                       #include <sys/types.h>
-                       #if HAVE_ATTR_XATTR_H
-                       #include <attr/xattr.h>
-                       #elif HAVE_SYS_XATTR_H
-                       #include <sys/xattr.h>
-                       #endif
-               ],[
-                       getxattr(0, 0, 0, 0, 0, 0);
-               ],
-               [smb_attr_cv_xattr_add_opt=yes],
-               [smb_attr_cv_xattr_add_opt=no;LIBS=$old_LIBS])
-       ])
-       if test x"$smb_attr_cv_xattr_add_opt" = x"yes"; then
-               AC_DEFINE(XATTR_ADD_OPT, 1, [xattr functions have additional options])
-       fi
-fi
-
-if test "x$neta_cv_eas_sys_found" = "xyes" ; then
-   if test "x$neta_cv_eas_sys_not_found" != "xyes" ; then
-      neta_cv_eas="$neta_cv_eas | sys"
-   fi
-fi
-AC_DEFINE_UNQUOTED(EA_MODULES,["$neta_cv_eas"],[Available Extended Attributes modules])
-
-dnl --------------------- Check if realpath() takes NULL
-AC_CACHE_CHECK([if the realpath function allows a NULL argument],
-    neta_cv_REALPATH_TAKES_NULL, [
-        AC_TRY_RUN([
-            #include <stdio.h>
-            #include <limits.h>
-            #include <signal.h>
-
-            void exit_on_core(int ignored) {
-                 exit(1);
-            }
-
-            main() {
-                char *newpath;
-                signal(SIGSEGV, exit_on_core);
-                newpath = realpath("/tmp", NULL);
-                exit((newpath != NULL) ? 0 : 1);
-            }],
-            neta_cv_REALPATH_TAKES_NULL=yes,
-            neta_cv_REALPATH_TAKES_NULL=no,
-            neta_cv_REALPATH_TAKES_NULL=cross
-        )
-    ]
-)
-
-if test x"$neta_cv_REALPATH_TAKES_NULL" = x"yes"; then
-    AC_DEFINE(REALPATH_TAKES_NULL,1,[Whether the realpath function allows NULL])
-fi
-
-dnl --------------------- Netatalk Webmin
-NETATALK_WEBMIN
-
-dnl --------------------- last minute substitutions
 
 AC_SUBST(LIBS)
 AC_SUBST(CFLAGS)
-AC_SUBST(OVERWRITE_CONFIG)
+AC_SUBST(UAMS_PATH)
 
 AM_CONDITIONAL(SOLARIS_MODULE, test x$solaris_module = xyes)
-AM_CONDITIONAL(COMPILE_TIMELORD, test x$compile_timelord = xyes)
-AM_CONDITIONAL(COMPILE_A2BOOT, test x$compile_a2boot = xyes)
 AM_CONDITIONAL(HAVE_LIBGCRYPT, test x$neta_cv_have_libgcrypt = xyes)
 AM_CONDITIONAL(HAVE_OPENSSL, test x$neta_cv_have_openssl = xyes)
 AM_CONDITIONAL(HAVE_ACLS, test x"$with_acl_support" = x"yes")
-AM_CONDITIONAL(HAVE_LDAP, test x"$with_ldap" = x"yes")
+AM_CONDITIONAL(HAVE_LDAP, test x"$netatalk_cv_ldap" = x"yes")
 AM_CONDITIONAL(USE_DHX, test x$neta_cv_compile_dhx = xyes)
 AM_CONDITIONAL(USE_DHX2, test x$neta_cv_compile_dhx2 = xyes)
 AM_CONDITIONAL(USE_RANDNUM, test x$neta_cv_have_openssl = xyes)
-AM_CONDITIONAL(USE_KERBEROS, test x$compile_kerberos = xyes)
 AM_CONDITIONAL(USE_PAM_SO, test x$use_pam_so = xyes)
 AM_CONDITIONAL(USE_PAM, test x$netatalk_cv_install_pam = xyes)
 AM_CONDITIONAL(BUILD_PAM, test x$compile_pam = xyes)
 AM_CONDITIONAL(USE_PGP, test x$compile_pgp = xyes)
 AM_CONDITIONAL(DEFAULT_HOOK, test x$neta_cv_have_libgcrypt != xyes && test x$neta_cv_have_openssl != xyes)
-AM_CONDITIONAL(USE_NETBSD, test x$sysv_style = xnetbsd)
-AM_CONDITIONAL(USE_REDHAT_SYSV, test x$sysv_style = xredhat-sysv)
-AM_CONDITIONAL(USE_SUSE_SYSV, test x$sysv_style = xsuse-sysv)
-AM_CONDITIONAL(USE_SHADOWPW, test x$shadowpw = xyes)
-AM_CONDITIONAL(USE_TRU64, test x$sysv_style = xtru64)
-AM_CONDITIONAL(USE_SOLARIS, test x$sysv_style = xsolaris)
-AM_CONDITIONAL(USE_GENTOO, test x$sysv_style = xgentoo)
-AM_CONDITIONAL(USE_DEBIAN, test x$sysv_style = xdebian)
-AM_CONDITIONAL(USE_SYSTEMD, test x$sysv_style = xsystemd || test x$sysv_style = xredhat-systemd || test x$sysv_style = xsuse-systemd)
-AM_CONDITIONAL(USE_UNDEF, test x$sysv_style = x)
 AM_CONDITIONAL(USE_BDB, test x$bdb_required = xyes)
-AM_CONDITIONAL(USE_APPLETALK, test x$netatalk_cv_ddp_enabled = xyes)
 AM_CONDITIONAL(HAVE_ATFUNCS, test x"$ac_neta_haveatfuncs" = x"yes")
+AM_CONDITIONAL(USE_SHADOWPW, test x$shadowpw = xyes)
 
-dnl --------------------- generate files
+dnl Enable silent Automake rules if present                                                                           
+m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])])
 
+dnl --------------------- generate files
 AC_OUTPUT([Makefile
        bin/Makefile
        bin/ad/Makefile
-       bin/adv1tov2/Makefile
-       bin/aecho/Makefile
        bin/afppasswd/Makefile
        bin/cnid/Makefile
        bin/cnid/cnid2_create
-       bin/getzones/Makefile
        bin/megatron/Makefile
        bin/misc/Makefile
-       bin/nbp/Makefile
-       bin/pap/Makefile
-       bin/psorder/Makefile
        bin/uniconv/Makefile
        config/Makefile
        config/pam/Makefile
        contrib/Makefile
        contrib/macusers/Makefile
        contrib/macusers/macusers
-       contrib/misc/Makefile
-       contrib/printing/Makefile
        contrib/shell_utils/Makefile
        contrib/shell_utils/apple_dump
        contrib/shell_utils/asip-status.pl
-       contrib/timelord/Makefile
-       contrib/a2boot/Makefile
        distrib/Makefile
        distrib/config/Makefile
        distrib/config/netatalk-config
        distrib/initscripts/Makefile
        distrib/m4/Makefile
-       distrib/systemd/Makefile
        doc/Makefile
        etc/Makefile
        etc/afpd/Makefile
-       etc/atalkd/Makefile
        etc/cnid_dbd/Makefile
+       etc/netatalk/Makefile
        etc/uams/Makefile
-       etc/uams/uams_krb4/Makefile
-       etc/papd/Makefile
-       etc/psf/Makefile
        include/Makefile
        include/atalk/Makefile
        libatalk/Makefile
        libatalk/acl/Makefile
        libatalk/adouble/Makefile
-       libatalk/asp/Makefile
-       libatalk/atp/Makefile
        libatalk/bstring/Makefile
        libatalk/cnid/Makefile
        libatalk/cnid/cdb/Makefile
@@ -1371,29 +261,17 @@ AC_OUTPUT([Makefile
        libatalk/cnid/tdb/Makefile
        libatalk/compat/Makefile
        libatalk/dsi/Makefile
-       libatalk/nbp/Makefile
-       libatalk/netddp/Makefile
-       libatalk/util/Makefile
+       libatalk/iniparser/Makefile
        libatalk/tdb/Makefile
        libatalk/unicode/Makefile
        libatalk/unicode/charsets/Makefile
+       libatalk/util/Makefile
        libatalk/vfs/Makefile
        macros/Makefile
        man/Makefile
        man/man1/Makefile
-       man/man3/Makefile
-       man/man4/Makefile
        man/man5/Makefile
        man/man8/Makefile
-       sys/Makefile
-       sys/generic/Makefile
-       sys/generic/sys/Makefile
-       sys/netatalk/Makefile
-       sys/netbsd/Makefile
-       sys/netbsd/netatalk/Makefile
-       sys/solaris/Makefile
-       sys/sunos/Makefile
-       sys/ultrix/Makefile
        test/Makefile
        test/afpd/Makefile
        ],
index 0d2f10741ae95fa8f208fba46270e6fbe7013fcb..3c076643be908516495c3d69a1988eba0861a5c6 100644 (file)
@@ -1,15 +1,3 @@
 # Makefile.am for contrib/
 
-SUBDIRS = macusers misc shell_utils
-
-if COMPILE_TIMELORD
-SUBDIRS += timelord
-endif
-
-if COMPILE_A2BOOT
-SUBDIRS += a2boot
-endif
-
-if USE_APPLETALK
-SUBDIRS += printing
-endif
+SUBDIRS = macusers shell_utils
diff --git a/contrib/a2boot/.gitignore b/contrib/a2boot/.gitignore
deleted file mode 100644 (file)
index a751359..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Makefile
-Makefile.in
-a2boot
-.deps
-.libs
-.gitignore
-*.o
diff --git a/contrib/a2boot/COPYRIGHT b/contrib/a2boot/COPYRIGHT
deleted file mode 100644 (file)
index c698aba..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
-       Recoding circa Dec 2002-early 2003          by Marsha Jackson
-       support booting of Apple 2 computers,   with aid of Steven N. Hirsch
-       Code is copyrighted as listed below...
-       M. Jackson is establishing no personal copyright
-       or personal restrictions on this software.  Only the below rights exist
-*/
-
-/*
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Wesley Craig
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1 313 764 2278
- *     netatalk@umich.edu
- */
-
-/*
- * The "timelord protocol" was reverse engineered from Timelord,
- * distributed with CAP, Copyright (c) 1990, The University of
- * Melbourne.  The following copyright, supplied by The University
- * of Melbourne, may apply to this code:
- *
- *     This version of timelord.c is based on code distributed
- *     by the University of Melbourne as part of the CAP package.
- *
- *     The tardis/Timelord package for Macintosh/CAP is
- *     Copyright (c) 1990, The University of Melbourne.
- */
diff --git a/contrib/a2boot/Makefile.am b/contrib/a2boot/Makefile.am
deleted file mode 100644 (file)
index 9ab8cba..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-# Makefile.am for contrib/a2boot/
-
-sbin_PROGRAMS = a2boot
-
-a2boot_SOURCES = a2boot.c
-a2boot_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-LIBS = @LIBS@
-
-EXTRA_DIST = COPYRIGHT VERSION
-
-AM_CFLAGS = -I$(top_srcdir)/include -I$(top_srcdir)/sys \
-        @SLP_CFLAGS@ \
-        -D_PATH_A_GS_BLOCKS=\"$(PKGCONFDIR)/a2boot/ProDOS16\ Boot\ Blocks\" \
-        -D_PATH_A_2E_BLOCKS=\"$(PKGCONFDIR)/a2boot/Apple\ :2f:2fe\ Boot\ Blocks\" \
-        -D_PATH_P16_IMAGE=\"$(PKGCONFDIR)/a2boot/ProDOS16\ Image\"
diff --git a/contrib/a2boot/VERSION b/contrib/a2boot/VERSION
deleted file mode 100644 (file)
index 8e8299d..0000000
+++ /dev/null
@@ -1 +0,0 @@
-2.4.2
diff --git a/contrib/a2boot/a2boot.c b/contrib/a2boot/a2boot.c
deleted file mode 100644 (file)
index 77fc641..0000000
+++ /dev/null
@@ -1,317 +0,0 @@
-/*
- * $Id: a2boot.c,v 1.2 2003-01-15 06:24:28 jmarcus Exp $
- *   Apple II boot support code.       with aid of Steven N. Hirsch
- *
- * based on timelord 1.6 so below copyrights still apply
- *
- * Copyright (c) 1990,1992 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * The "timelord protocol" was reverse engineered from Timelord,
- * distributed with CAP, Copyright (c) 1990, The University of
- * Melbourne.  The following copyright, supplied by The University
- * of Melbourne, may apply to this code:
- *
- *     This version of timelord.c is based on code distributed
- *     by the University of Melbourne as part of the CAP package.
- *
- *     The tardis/Timelord package for Macintosh/CAP is
- *     Copyright (c) 1990, The University of Melbourne.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/file.h>
-#include <sys/uio.h>
-
-#include <unistd.h>
-
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <atalk/atp.h>
-#include <atalk/nbp.h>
-
-#ifdef HAVE_SGTTY_H
-#include <sgtty.h>
-#endif /* HAVE_SGTTY_H */
-
-#include <errno.h>
-#include <signal.h>
-#include <atalk/logger.h>
-#include <stdio.h>
-#include <string.h>
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif /* HAVE_NETDB_H */
-
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#ifdef HAVE_SYS_FCNTL_H
-#include <sys/fcntl.h>
-#endif /* HAVE_SYS_FCNTL_H */
-
-#ifdef HAVE_TERMIOS_H
-#include <termios.h>
-#endif /* HAVE_TERMIOS_H */
-#ifdef HAVE_SYS_TERMIOS_H
-#include <sys/termios.h>
-#endif /* HAVE_SYS_TERMIOS_H */
-
-#define        TL_OK           '\0'
-#define TL_EOF         '\1'
-
-int    debug = 0;
-char   *bad = "Bad request!";
-char   buf[ 4624 ];
-char   *server;
-int32_t fileoff;
-
-long a2bootreq(char *fname);
-
-void usage( char *p )
-{
-    char       *s;
-
-    if (( s = rindex( p, '/' )) == NULL ) {
-       s = p;
-    } else {
-       s++;
-    }
-    fprintf( stderr, "Usage:\t%s -d -n nbpname\n", s );
-    exit( 1 );
-}
-
-/*
- * Unregister ourself on signal.
- */
-void
-goaway(int signal)
-{
-    int regerr;
-    regerr = nbp_unrgstr( server, "Apple //gs", "*", NULL );
-    regerr += nbp_unrgstr( server, "Apple //e Boot", "*", NULL );
-    regerr += nbp_unrgstr( server, "ProDOS16 Image", "*", NULL );
-    if ( regerr < 0 ) {
-       LOG(log_error, logtype_default, "Can't unregister Apple II boot files %s", server );
-       exit( 1 );
-    }
-    LOG(log_info, logtype_default, "going down" );
-    exit( 0 );
-}
-
-int main( int ac, char **av )
-{
-    ATP                atp;
-    struct sockaddr_at sat;
-    struct atp_block   atpb;
-    struct iovec       iov;
-    char       hostname[ MAXHOSTNAMELEN ];
-    char       *p;
-    int                c;
-    int32_t    req, resp;
-    int        regerr;
-    extern char        *optarg;
-    extern int         optind;
-
-
-    if ( gethostname( hostname, sizeof( hostname )) < 0 ) {
-       perror( "gethostname" );
-       exit( 1 );
-    }
-    if (( server = index( hostname, '.' )) != 0 ) {
-       *server = '\0';
-    }
-    server = hostname;
-
-    while (( c = getopt( ac, av, "dn:" )) != EOF ) {
-       switch ( c ) {
-       case 'd' :
-           debug++;
-           break;
-       case 'n' :
-           server = optarg;
-           break;
-       default :
-           fprintf( stderr, "Unknown option -- '%c'\n", c );
-           usage( *av );
-       }
-    }
-
-    /*
-     * Disassociate from controlling tty.
-     */
-    if ( !debug ) {
-       int             i, dt;
-
-       switch ( fork()) {
-       case 0 :
-           dt = getdtablesize();
-           for ( i = 0; i < dt; i++ ) {
-               (void)close( i );
-           }
-           if (( i = open( "/dev/tty", O_RDWR )) >= 0 ) {
-               (void)ioctl( i, TIOCNOTTY, 0 );
-               setpgid( 0, getpid());
-               (void)close( i );
-           }
-           break;
-       case -1 :
-           perror( "fork" );
-           exit( 1 );
-       default :
-           exit( 0 );
-       }
-    }
-
-    if (( p = rindex( *av, '/' )) == NULL ) {
-       p = *av;
-    } else {
-       p++;
-    }
-
-#ifdef ultrix
-    openlog( p, LOG_PID );
-#else /* ultrix */
-    set_processname(p);
-    syslog_setup(log_debug, logtype_default, logoption_ndelay|logoption_pid, logfacility_daemon );
-#endif /* ultrix */
-
-    /* allocate memory */
-    memset (&sat.sat_addr, 0, sizeof (sat.sat_addr));
-
-/*
-       force port 3 as the semi-official ATP access port        MJ 2002
-*/
-    if (( atp = atp_open( (u_int8_t)3, &sat.sat_addr )) == NULL ) {
-       LOG(log_error, logtype_default, "main: atp_open: %s", strerror( errno ) );
-       exit( 1 );
-    }
-
-    regerr = nbp_rgstr( atp_sockaddr( atp ), server, "Apple //gs", "*" );
-    regerr += nbp_rgstr( atp_sockaddr( atp ), server, "Apple //e Boot", "*" );
-    regerr += nbp_rgstr( atp_sockaddr( atp ), server, "ProDOS16 Image", "*" );
-    if ( regerr < 0 ) {
-       LOG(log_error, logtype_default, "Can't register Apple II boot files %s", server );
-       exit( 1 );
-    }
-
-    LOG(log_info, logtype_default, "%s:Apple 2 Boot started", server );
-
-       signal(SIGHUP, goaway);
-       signal(SIGTERM, goaway);
-
-    for (;;) {
-       /*
-        * Something seriously wrong with atp, since these assigns must
-        * be in the loop...
-        */
-       atpb.atp_saddr = &sat;
-       atpb.atp_rreqdata = buf;
-       bzero( &sat, sizeof( struct sockaddr_at ));
-       atpb.atp_rreqdlen = sizeof( buf );
-
-       if ( atp_rreq( atp, &atpb ) < 0 ) {
-       LOG(log_error, logtype_default, "main: atp_rreq: %s", strerror( errno ) );
-           exit( 1 );
-       }
-
-       p = buf;
-       bcopy( p, &req, sizeof( int32_t ));
-       req = ntohl( req );
-       p += sizeof( int32_t );
-
-/*
-    LOG(log_info, logtype_default, "req = %08lx",(long)req );
-*/
-       /* Byte-swap and multiply by 0x200. Converts block number to
-          file offset. */
-       fileoff = (( req & 0x00ff0000 ) >> 7 ) | (( req & 0x0000ff00 ) << 9 );
-       req &= 0xff000000;
-
-/*
-    LOG(log_info, logtype_default, "       reqblklo = %02x",(int)reqblklo );
-    LOG(log_info, logtype_default, "       reqblkhi = %02x",(int)reqblkhi );
-    LOG(log_info, logtype_default, "       req now = %08lx",(long)req );
-*/
-
-       switch( req ) {
-       case 0x01000000 :       /* Apple IIgs both ROM 1 and ROM 3 */
-/*    LOG(log_info, logtype_default, "          Req ProDOS16 Boot Blocks" ); */
-               resp = a2bootreq(_PATH_A_GS_BLOCKS);
-           break;
-
-       case 0x02000000 :       /* Apple 2 Workstation card  */
-/*    LOG(log_info, logtype_default, "          Req Apple //e Boot" );  */
-               resp = a2bootreq(_PATH_A_2E_BLOCKS);
-           break;
-
-       case 0x03000000 :       /* Apple IIgs both ROM 1 and ROM 3 */
-/*    LOG(log_info, logtype_default, "          Req ProDOS16 Image" );    */
-               resp = a2bootreq(_PATH_P16_IMAGE);
-           break;
-
-       default :
-           LOG(log_error, logtype_default, bad );
-
-           resp = TL_EOF;
-           *( buf + sizeof( int32_t ) ) = (unsigned char)strlen( bad );
-           strcpy( buf + 1 + sizeof( int32_t ), bad );
-
-           break;
-       }
-
-       bcopy( &resp, buf, sizeof( int32_t ));
-
-       iov.iov_len = sizeof( int32_t ) + 512;
-       iov.iov_base = buf;
-       atpb.atp_sresiov = &iov;
-       atpb.atp_sresiovcnt = 1;
-
-       if ( atp_sresp( atp, &atpb ) < 0 ) {
-           LOG(log_error, logtype_default, "main: atp_sresp: %s", strerror( errno ) );
-           exit( 1 );
-       }
-    }
-}
-
-
-/* below MJ 2002 (initially borrowed from aep_packet */
-long a2bootreq(fname)
-       char    *fname;
-{
-       int f,m;
-       int32_t readlen;
-/*
-    LOG(log_info, logtype_default, "          a2bootreq( %s )",fname );
-*/
-       f=open(fname,O_RDONLY );
-       if(f==EOF) {
-       LOG(log_error, logtype_default, "a2boot open error on %s",fname);
-               return close(f);
-       }
-
-/*
-    LOG(log_info, logtype_default, "would lseek to %08lx",fileoff);
-*/
-       lseek(f,fileoff,0);
-       readlen=read(f, buf + sizeof( int32_t ), 512 );
-
-/*
-    LOG(log_info, logtype_default, "length is %08lx", readlen);
-*/
-
-       if(readlen < 0x200) {
-/*    LOG(log_info, logtype_default, "Read to EOF");  */
-               close(f);
-               return TL_EOF;
-       }
-       close(f);
-       return  TL_OK;
-}
-
diff --git a/contrib/misc/libevent.patch b/contrib/misc/libevent.patch
new file mode 100644 (file)
index 0000000..7d69713
--- /dev/null
@@ -0,0 +1,19 @@
+diff --git a/libevent/Makefile.am b/libevent/Makefile.am
+index 46f6d34..dda19b2 100644
+--- a/libevent/Makefile.am
++++ b/libevent/Makefile.am
+@@ -173,7 +173,7 @@ NO_UNDEFINED =
+ MAYBE_CORE =
+ endif
+-GENERIC_LDFLAGS = -version-info $(VERSION_INFO) $(RELEASE) $(NO_UNDEFINED)
++GENERIC_LDFLAGS = -static
+ libevent_la_SOURCES = $(CORE_SRC) $(EXTRA_SRC)
+ libevent_la_LIBADD = @LTLIBOBJS@ $(SYS_LIBS)
+@@ -221,3 +221,5 @@ FORCE:
+ DISTCLEANFILES = *~ libevent.pc ./include/event2/event-config.h
++install:
++
diff --git a/contrib/printing/.gitignore b/contrib/printing/.gitignore
deleted file mode 100644 (file)
index f2f0549..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Makefile
-Makefile.in
-timeout
-.deps
-.libs
-.gitignore
-*.o
diff --git a/contrib/printing/Makefile.am b/contrib/printing/Makefile.am
deleted file mode 100644 (file)
index 649c5fb..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# Makefile.am for contrib/printing/
-
-bin_SCRIPTS = add_netatalk_printer
-
-EXTRA_DIST = netatalk.template add_netatalk_printer
diff --git a/contrib/printing/add_netatalk_printer b/contrib/printing/add_netatalk_printer
deleted file mode 100644 (file)
index 40de174..0000000
+++ /dev/null
@@ -1,366 +0,0 @@
-#! /bin/sh
-#
-# $Id: add_netatalk_printer,v 1.7 2003-02-23 03:16:34 srittau Exp $
-#
-# A lovely script to add netatalk printers 
-#
-#ident  "@(#)netatalk   0.5     99/06/22 job@uchicago.edu"  /* Netatalk 1.4*/
-#
-# This File is released under the Perl Artistic Licence.
-# See http://www.perl.org for details
-#
-# Or you can use it under the licence that accompanies Netatalk 1.3 =)
-#
-# This file is maintained by Job Bogan <job@uchicago.edu>
-# Please contact me at this address for bug reports, problems, etc.
-# Please do not bother the netatalk  maintainers with problems from
-# this program.
-#
-#
-#
-# Exit Codes ...  1 for missed path or user input
-# 2 for an aborted run (by not saying yes to a 'are you sure?'
-# 3 for failed lpadmin commands
-# 4 for possible security problem
-
-# make base name for temp files.
-
-TMP_STUFF="/tmp/`basename $0`.$$"
-export TMP_STUFF
-rm -rf ${TMP_STUFF}
-mkdir -m 700 ${TMP_STUFF} || exit 4
-trap 'rm -f $TMP_STUFF > /dev/null 2>&1' 0
-trap 'exit' 1 2 3
-
-# grab the pathname the script was called w/
-# if it was run by ./add...  then make the path == `pwd`
-
-RUNHOME=`dirname $0`
-
-if [ "$RUNHOME" = "." ]; then
-       RUNHOME=`pwd`
-fi
-
-# allow for the env NETATALKHOME to override the guessed one from above
-
-NETATALKHOME=${NETATALKHOME:-$RUNHOME}
-export NETATALKHOME
-
-PATH=/bin:${PATH}:${NETATALKHOME}/bin:${NETATALKHOME}/etc:${NETATALKHOME}/libexec:/usr/lib:/usr/sbin
-
-if [ ! -x ${NETATALKHOME}/bin/pap ]; then
-       echo "OOPS:     I don't see ${NETATALKHOME}/bin/pap ,"
-       echo '  Check that it is executable or set ${NETATALKHOME}'
-       echo '  so i can find pap at ${NETATALKHOME}/bin/pap'
-       echo '[We are guessing the location of the binary from the'
-       echo 'path that was used to run this script or $NETATALKHOME]'
-       exit 1
-fi
-
-# get the user to tell us where to look for things, and list things there.
-
-echo ''
-echo "Enter Appletalk zone [default: local]: \c"
-
-read ZONE
-
-echo ""
-echo "Looking for LaserWriters in Zone ${ZONE} ..."
-${NETATALKHOME}/bin/nbplkup ":LaserWriter@${ZONE}"
-
-echo ""
-echo "Enter AppleTalk printer name: \c"
-
-read DEST
-
-if [ "$DEST" = "" ]; then
-       echo "OOPS: you need to tell me a printer name"
-       exit 1
-fi
-
-echo "checking nbplkup ${DEST}:LaserWriter@${ZONE}"
-echo ""
-TestDEST=`${NETATALKHOME}/bin/nbplkup "${DEST}:LaserWriter@${ZONE}"`
-echo "${TestDEST}"
-echo ""
-
-if [ "${TestDEST}" = "" ]; then
-    echo "I don't see that printer on the network.  You may have entered an incorrect"
-    echo "printer name - if so, exit and restart."
-    echo "[You should only enter the printer name, not the :LaserWriter portion]"
-    sleep 3
-fi
-
-unset TestDEST
-
-NBPNAME="${DEST}@${ZONE}"
-
-echo ""
-echo ""
-
-# scrunch all of the whitespace and / out of the appletalk name and suggest
-# that as the unix name
-
-SUGGEST=`echo "$DEST" | cut -d: -f1 | sed 's/ //g' | sed 's#/##g` ; export SUGGEST
-
-# truncate the suggested name to 14 chars to conform to lp specs.
-
-SUGGEST1=`expr ${SUGGEST} : '\(..............\)'`
-SUGGEST=${SUGGEST1:-$SUGGEST}
-
-echo "Enter Unix printer name - [default: ${SUGGEST}] : \c"
-read UNIXPRINT
-echo ''
-if [ "${UNIXPRINT}" = "" ]; then
-       UNIXPRINT="${SUGGEST}"
-fi
-export UNIXPRINT
-
-#####
-# Here we check for legal names again. >14 chars
-#####
-
-UNIXPRINT1=`expr "${UNIXPRINT}" : '\(..............\)'`
-
-# if UNIXPRINT is shorter than 14chars, UNIXPRINT1 ends up null ("")
-# if UNIXPRINT was longer, then we get a 14char version of it.  bleah.
-
-if [ "${UNIXPRINT1}" = "" ]; then
-       UNIXPRINT1="${UNIXPRINT}"
-else
-#if [ "${UNIXPRINT1}" != "${UNIXPRINT}" ]; then
-    echo "Oops, that name was too long...  Truncating to 14 chars."
-    echo "setting printer name to '${UNIXPRINT}'"
-    UNIXPRINT="${UNIXPRINT1}"
-fi
-
-echo "Enter a description for this printer.  [The Appletalk name will"
-echo "be included by default, and must be included for the printing"
-echo "filters to work.] : \c"
-read DESC
-
-DESC="${DESC} [${NBPNAME}]"
-
-echo ""
-echo "Do you want all print jobs to print out in reversed page order?"
-echo "This is usually only desired if this printer stacks jobs"
-echo "face up in the output bin. [N/y] \c"
-read REV
-case ${REV} in         [Yy]*)  REV="Netatalk-R" ;;
-                       *)      REV="Netatalk"   ;;
-esac
-export REV
-
-if lpstat -p ${UNIXPRINT} >/dev/null 2>&1 ; then
-       echo '\a'
-       echo "OOPS:     There already exists a printer named '${UNIXPRINT}'"
-       echo "          here are the comments from /etc/lp/printers/${UNIXPRINT}/comment"
-       cat /etc/lp/printers/${UNIXPRINT}/comment
-       echo ""
-       echo "Do you still want to do this? This will flush "
-       echo "all pending jobs!  [Y/n]? \c"
-       read DOTHIS
-       case ${DOTHIS} in       [Yy]*)         ;;
-                               *)      exit 2 ;;
-       esac
-
-       echo "Rejecting all new jobs for ${UNIXPRINT}"
-       reject -r "Making ${UNIXPRINT} a netatalk printer" ${UNIXPRINT}
-       echo "Disabling and Flushing the ${UNIXPRINT} queue"
-       disable -c -r "Making ${UNIXPRINT} a netatalk printer" ${UNIXPRINT}
-fi
-
-#####
-# Check if we need to do silly tricks to share the printer... only on 5.5.1 or older
-#####
-
-if [ "`uname -r`" -lt "5.6" ]; then
-    echo ""
-    echo "Do you want to share this printer with other machines [Y/n]?\c"
-    read SHARE
-else
-    echo "You're running SunOS 5.6 or higher... skipping 'sacadm' and 'pmadm'"
-fi
-
-if nistest printers.org_dir; then
-    echo "Do you want to add this printer to your NIS printer map? [y/N]"
-    echo "(You will need to share this printer with other machines)"
-    read NIS
-    case ${NIS} in     [Yy]*)    ADD_NIS=1 ;;
-                           *)              ;;
-    esac
-fi
-
-echo "Do you want to save the error messages from pap in"
-echo "'/var/spool/lp/tmp/Netatalk/${UNIXPRINT}' [y/N]"
-echo "(If you answer N, error messages will go to /dev/null.)"
-read SAVEerr
-case ${SAVEerr} in      [Yy]*)     SAVEerr=1 ;;
-                           *)     unset SAVEerr ;;
-esac
-
-echo "Making ${UNIXPRINT} print to ${DEST} via netatalk"
-
-if [ "${SAVEerr}" = "" ]; then
-    LOCKDEV=/dev/null
-else
-    LOCKS=/var/spool/lp/tmp/Netatalk
-    if [ ! -d ${LOCKS} ]; then
-           mkdir -m 0771       ${LOCKS}
-           chown lp    ${LOCKS}
-           chgrp lp    ${LOCKS}
-    fi
-    LOCKDEV=${LOCKS}/${UNIXPRINT}
-    touch              ${LOCKDEV}
-    chown lp:lp        ${LOCKDEV}
-    chmod 600  ${LOCKDEV}
-fi
-
-echo ""
-
-if [ ! -r /etc/lp/filter.table ]; then
-        echo "Setting up the existing print filters..."
-        for i in `ls /etc/lp/fd | sed 's/.fd$//'`; do
-                lpfilter -f ${i} -F/etc/lp/fd/${i}.fd
-        done
-fi
-if lpfilter -f netatalk -l > /dev/null 2>&1 ; then
-       echo 'Looks like you have a Netatalk printer filter defined. Good!'
-else
-       echo "Humm... You need a Netatalk printer filter..."
-       echo "... making you one ..."
-       cat > /etc/lp/fd/netatalk.fd << EOF
-#ident  "@(#)netatalk.fd 0.2 97/09/04 job@uchicago.edu"      /* Netatalk 1.4 */
-
-Input types: postscript
-Output types: PS
-Printer types: Netatalk
-Printers: any
-Filter type: fast
-Command: ${NETATALKHOME}/libexec/ifpap 2>&1 > /dev/null
-EOF
-       chown lp:lp /etc/lp/fd/netatalk.fd
-       chmod 664   /etc/lp/fd/netatalk.fd
-       lpfilter -f netatalk -F /etc/lp/fd/netatalk.fd
-fi
-
-if lpfilter -f netatalk-r -l 2>&1 > /dev/null ; then
-       echo 'Looks like you have a Reverse Netatalk printer filter defined. Good!'
-else
-       echo "Humm... You need a Reverse Netatalk printer filter..."
-       echo "... making you one ..."
-       cat > /etc/lp/fd/netatalk-r.fd << EOF
-#ident  "@(#)netatalk-r.fd 0.2 97/09/04 job@uchicago.edu"      /* Netatalk 1.4 */
-
-Input types: postscript
-Output types: PS
-Printer types: Netatalk-R
-Printers: any
-Filter type: fast
-Command: "/usr/lib/lp/postscript/postreverse | ${NETATALKHOME}/libexec/ifpap 2>&1 >/dev/null"
-EOF
-       chown lp:lp /etc/lp/fd/netatalk-r.fd
-       chmod 664   /etc/lp/fd/netatalk-r.fd
-       lpfilter -f netatalk-r -F /etc/lp/fd/netatalk-r.fd
-fi
-
-if [ ! -r /usr/share/lib/terminfo/N/Netatalk ]; then
-       echo "Making a Terminfo entry for Netatalk printers"
-       cat > ${TMP_STUFF}/terminfo << EOF
-Netatalk,
-       cols#80, lines#66,
-       cpi=null, csnm=^D, lpi=null, scs=^D, slines=^D, u9=^D,
-EOF
-       tic ${TMP_STUFF}/terminfo
-       chown bin:bin /usr/share/lib/terminfo/N/Netatalk
-       chmod 644     /usr/share/lib/terminfo/N/Netatalk
-fi
-
-if [ ! -r /usr/share/lib/terminfo/N/Netatalk-R ]; then
-       echo "Making a Terminfo entry for Reversed Netatalk printers"
-       cat > ${TMP_STUFF}/terminfoR << EOF
-Netatalk-R,
-       cols#80, lines#66,
-       cpi=null, csnm=^D, lpi=null, scs=^D, slines=^D, u9=^D,
-EOF
-       tic "${TMP_STUFF}/terminfoR"
-       chown bin:bin /usr/share/lib/terminfo/N/Netatalk-R
-       chmod 644     /usr/share/lib/terminfo/N/Netatalk-R
-fi
-
-###
-# this is old cruft...  we should not have done this in the 1st place.
-# we need to edit the template interface file to point to the local netatalk bins
-#cat ${RUNHOME}/etc/netatalk.template | sed "s#DEFAULT_NETATALK_HOME#${RUNHOME}#g" \
-#      > "/etc/lp/interfaces/${UNIXPRINT}"
-#chown lp:lp   /etc/lp/interfaces/${UNIXPRINT}
-#chmod 0775    /etc/lp/interfaces/${UNIXPRINT}
-# below is the correct way.
-###
-
-echo "Setting up ${UNIXPRINT} ...  Edit options later as you see fit."
-lpadmin -p ${UNIXPRINT} -D "${DESC}" -T ${REV} \
-    -i ${RUNHOME}/netatalk.template -I PS -v ${LOCKDEV} -A none || exit 3
-accept ${UNIXPRINT} || exit 3
-enable ${UNIXPRINT} || exit 3
-
-case ${SHARE} in       [Nn]*)  exit; ;;
-                       *)            ;;
-esac
-
-echo "Setting up network sharing for ${UNIXPRINT}"
-
-# from p925 in the Solaris Administration Guide, Vol. II (2.5)
-
-echo ""
-if sacadm -l -p tcp > /dev/null; then
-   echo "already running a tcp listener"
-else
-   echo "Defining tcp listener ..."
-   sacadm -a -p tcp -t listen -c "/usr/lib/saf/listen tcp" \
-          -v `nlsadmin -V` -n 999
-fi
-
-# this is extra, but a good idea...
-
-LPD_ADDR="\\x`lpsystem -A`" ; export LPD_ADDR
-ADDR_0=`echo $LPD_ADDR | sed -e 's/\\x00020203/\\x00020ACE/g'`; export ADDR_0
-
-if pmadm -l -p tcp -s 0 > /dev/null; then
-   echo "<0> service is already defined."
-else
-   echo "Defining <0>/tcp service ..."
-   pmadm -a -p tcp -s 0 -i root \
-         -m `nlsadmin -c /usr/lib/saf/nlps_server -A ${ADDR_0}` \
-         -v `nlsadmin -V`
-fi
-
-# again from the solaris book noted above.
-
-if pmadm -l -p tcp -s lp > /dev/null; then
-   echo "<lp> service is already defined."
-else
-   echo "Defining <lp>/tcp service ..."
-   pmadm -a -p tcp -s lp -i root \
-         -m `nlsadmin -o /var/spool/lp/fifos/listenS5` \
-         -v `nlsadmin -V`
-fi
-
-if pmadm -l -p tcp -s lpd > /dev/null; then
-   echo "<lpd> service is already defined."
-else
-   echo "Defining <lpd>/tcp service ..."
-   pmadm -a -p tcp -s lpd -i root \
-         -m `nlsadmin -o /var/spool/lp/fifos/listenBSD -A ${LPD_ADDR}` \
-         -v `nlsadmin -V`
-fi
-
-if [ "${ADD_NIS}" = 1 ] ; then
-    if nistest "[printer_name=${UNIXPRINT}]printers.org_dir"; then
-       nistbladm -m    printer_host=`uname -n` \
-       "[printer_name=${UNIXPRINT}]printers.org_dir"  description="$DESC"
-    else
-       nistbladm -a    printer_name=${UNIXPRINT} \
-       description="$DESC" printer_host=`uname -n` printers.org_dir
-    fi
-fi
diff --git a/contrib/printing/netatalk.template b/contrib/printing/netatalk.template
deleted file mode 100644 (file)
index f639914..0000000
+++ /dev/null
@@ -1,610 +0,0 @@
-#ident "@(#)netatalk   0.7     99/06/22 job@uchicago.edu"  /* Netatalk 1.4*/
-
-#####
-# User configuration:
-#
-# Set timeout for pap($time) and papstatus($time2).  both are in seconds.
-# extraneous if you do not have NETATALKHOME/bin/timeout
-# set how many times to loop before we just abort entirely ($attempts)
-# what flags pap is run w/. -c makes pap claim to have been waiting forever
-#####
-
-time=1800
-time2=60
-attempts=3
-pap_flags="-c"
-
-#####
-# this should get "fixed" to something like
-# NETATALKHOME=/opt ; export NETATALKHOME
-# by the add_netatalk_printer script
-#
-# DO NOT use the user's env for this or the PATH above.
-#####
-
-NETATALKHOME=DEFAULT_NETATALK_HOME ; export NETATALKHOME
-#NETATALKHOME=/opt ; export NETATALKHOME
-
-if [ "${NETATALKHOME}" = "DEFAULT_NETATALK_HOME" ]; then
-   echo "bleah, NETATALKHOME not set, exiting..." ; exit 5
-fi
-
-#####
-# BUGS/TODO:
-# move all TMP stuff to use a directory for security reasons
-# run nbplkup to check if the reason we cannot print, is that it's not on 
-#      the net
-# move to "${foo}" from $foo and ${foo}
-# add debuging info that gets sent to "logger lpd.debug"
-# if we timeout while printing the banner page, we do not keep trying to print.
-# perhaps filter_timeout should only complain once per job; like badfile.
-# check if the timeout messages are duplicated by the lp system
-# psa will not drop in for pap to use accting.  perhaps lp does not need it?
-# make pap print all the files at once; kill for file in ($files)
-# move badfile error to printfile function
-#####
-
-# This File is released under the Perl Artistic Licence.  
-# See http://www.perl.org for details
-#
-# Or you can use it under the licence that accompanies Netatalk 1.3 =)
-
-###########
-## Netatalk printer interface.  Heavily modified from 
-## /usr/lib/lp/model/standard on Sparc Solaris 2.5.1 (May 97)
-##
-## Meant to be used w/ add_netatalk_printer
-###########
-
-#####
-# This program is invoked as
-#
-# ${SPOOLDIR}/.../printer request-id user title copies options files...
-#
-# The first three arguments are simply reprinted on the banner page,
-# the fourth (copies) is used to control the number of copies to print,
-# the fifth (options) is a blank separated list (in a single argument)
-# of user or Spooler supplied options (without the -o prefix),
-# and the last argument(s) is/are the file(s) to print.
-#####
-
-#####
-#
-# The protocol between the interface program and the Spooler
-# is fairly simple:
-#
-#      All standard error output is assumed to indicate a
-#      fault WITH THE REQUEST. The output is mailed to the
-#      user who submitted the print request and the print
-#      request is finished.
-#
-#      If the interface program sets a zero exit code,
-#      it is assumed that the file printed correctly.
-#      If the interface program sets a non-zero exit code
-#      less than 128, it is assumed that the file did not
-#      print correctly, and the user will be notified.
-#      In either case the print request is finished.
-#
-#      If the interface program sets an exit code greater
-#      than 128, it is assumed that the file did not print
-#      because of a printer fault. If an alert isn't already
-#      active (see below) one will be activated. (Exit code
-#      128 should not be used at all. The shell, which executes
-#      this program, turns SIGTERM, used to kill this program
-#      for a cancellation or disabling, into exit 128. The
-#      Spooler thus interpretes 128 as SIGTERM.)
-#
-#      A message sent to the standard input of the ${LPTELL}
-#      program is assumed to describe a fault WITH THE PRINTER.
-#      The output is used in an alert (if alerts are defined).
-#      If the fault recovery is "wait" or "begin", the printer
-#      is disabled (killing the interface program if need be),
-#      and the print request is left on the queue.
-#      If the fault recovery is "continue", the interface program
-#      is allowed to wait for the printer fault to be cleared so
-#      it can resume printing.
-#
-#####
-
-###########################################################################
-#
-# Set up the basic traps. and other important things
-#
-###########################################################################
-
-#####
-# For the time being, just exit if we are poked.
-#####
-
-# SIGTERM handler
-
-trap 'exit' 15
-
-#####
-# We can be clever about getting a hangup or interrupt, though, at least
-# until the filter runs. Do this early, even though $LPTELL
-# isn't defined, so that we're covered.
-#####
-
-trap 'catch_hangup; exit_code=129 exit 129' 1
-trap 'catch_interrupt; exit_code=129 exit 129' 2 3
-
-#####
-# VARIBLE DECLARED - put here so we don't ever run the trap below w/o
-# TMPPREFIX defined.  We hard code /tmp for the moment, but fix that later
-#
-# Use ${TMPPREFIX} as the prefix for all temporary files, so
-# that cleanup is easy. The prefix may be up to 13 characters
-# long, so you only have space for one more character to make
-# a file name. If necessary, make a directory using this prefix
-# for better management of unique temporary file names.
-#####
-
-TMPPREFIX=/tmp/`uname -n`$$
-
-#####
-# Before exiting, set ${exit_code} to the value with which to exit.
-# Otherwise, the exit from this script will be 0.
-#####
-
-trap 'rm -fr ${TMPPREFIX}*; exit ${exit_code}' 0
-
-catch_hangup () {
-       if [ -n "${LPTELL}" ]
-       then
-               echo \
-    "Humm, we got a SIGHUP.  Not sure what it means, but... we'll keep going anyway" \
-          | ${LPTELL} "${printer}"
-       fi
-       return 0
-}
-
-catch_interrupt () {
-       if [ -n "${LPTELL}" ]
-       then
-           echo \
-       "Received an interrupt from the printer.  The reason is unknown." \
-           | ${LPTELL} "${printer}"
-       fi
-       return 0
-}
-
-#####
-# Most of the time we don't want the standard error to be captured
-# by the Spooler, mainly to avoid "Terminated" messages that the
-# shell puts out when we get a SIGTERM. We'll save the standard
-# error channel under another number, so we can use it when it
-# should be captured.
-#
-# Open another channel to the printer port, for use when the
-# regular standard output won't be directed there, such as in
-# command substitution (`cmd`).
-#####
-
-exec 5>&2 2>/dev/null 3>&1
-
-###########################################################################
-#
-# Define local varibles and such
-#
-###########################################################################
-
-#####
-# There is one more varible set by the shell that execs us.
-# FILTER       The filter to run ; we ignore this directive
-#####
-
-#####
-# Use the user set env, or else default to standard values.
-#####
-
-: ${SPOOLDIR:=/usr/spool/lp}
-: ${TMPDIR:=/tmp} ; export TMPDIR
-: ${LOCALPATH:=${SPOOLDIR}/bin} ; export LOCALPATH
-
-PATH="/bin:/usr/bin:${LOCALPATH}:${NETATALKHOME}/bin:${NETATALKHOME}/etc"
-export PATH
-
-TMPPREFIX=${TMPDIR}/`uname -n`$$
-
-#####
-# Error levels for the errmsg() func.
-#####
-
-LP_ERR_LABEL="UX:lp" ; export LP_ERR_LABEL
-
-E_IP_ARGS=1
-E_IP_OPTS=2
-E_IP_UNKNOWN=5
-E_IP_BADFILE=6
-
-#####
-# Error message formatter:
-#
-# Invoke as
-#
-#      errmsg severity message-number problem help
-#
-# where severity is "ERROR" or "WARNING", message-number is
-# a unique identifier, problem is a short description of the
-# problem, and help is a short suggestion for fixing the problem.
-#####
-
-errmsg () {
-        case $1 in
-        ERROR )
-                sev="  ERROR";
-                ;;
-        WARNING )
-                sev="WARNING";
-                ;;
-        esac
-        echo "${LP_ERR_LABEL}: ${sev}: $3
-        TO FIX: $4" >&5
-}
-
-parse () {
-        echo "`expr \"$1\" : \"^[^=]*=\(.*\)\"`"
-}
-
-#####
-# die quickly if we do not have the right number of arguments.
-#####
-
-if [ $# -lt 5 ]
-then
-       errmsg ERROR ${E_IP_ARGS} \
-               "wrong number of arguments to interface program" \
-               "consult your system administrator"
-       exit 1
-fi
-
-printer=`basename $0`
-request_id=$1
-
-# this will formated be machine!username, so we want to split that up...
-
-user_name=$2
-machine=`echo $user_name | cut -d! -f1`
-user_name=`echo $user_name | cut -d! -f2`
-
-title=$3
-copies=$4
-option_list=$5
-
-shift 5
-files="$*"
-
-nobanner="yes"
-
-inlist=
-
-for i in ${option_list}
-do
-case "${inlist}${i}" in
-    nobanner )
-       nobanner="yes" ;;
-    banner )
-       nobanner="no" ;;
-#####
-#
-# If you want to add simple options (e.g. -o simple)
-# identify them here.
-#####
-#    simple )
-#      simple="yes" ;;
-
-#####
-# These get ignored, but would matter little anyway since all we see 
-# here is PS anyway.
-#####
-       cpi=* )
-#          cpi=`parse ${i}` ;;
-           true ;;
-       lpi=* )
-#          lpi=`parse ${i}` ;;
-           true ;;
-       length=* )
-#          length=`parse ${i}` ;;
-           true ;;
-       width=* )
-#          width=`parse ${i}` ;;
-           true ;;
-
-       #####
-       # If you want to add simple-value options (e.g. -o value=a)
-       # identify them here.
-       #####
-       #value=* )
-       #    value=`parse ${i}` ;;
-
-       flist=* )
-           flist=`parse ${i}` ;;
-       input* )
-           true ;;
-       * )
-           errmsg WARNING ${E_IP_OPTS} \
-           "unrecognized \"-o ${i}\" option" \
-           "check the option, resubmit if necessary
-           printing continues" ;;
-
-       esac
-done
-
-#####
-# A bit ugly, but grabs the appletalk printer name from the lp system printer
-# description, so it's right up there in admintool.  the appletalk name must 
-# be delimited by [ and ].
-#
-# eg - 'this is the printer [hp-mrsec-l114:lasershared@Research Insitutes] that i use.'
-#####
-
-PAPDEST="`lpstat -D -p "${printer}" | grep -i descrip | sed 's/.*Description:.*\[//g' | sed 's/\].*//g'`"
-
-export PAPDEST
-
-###########################################################################
-#
-# Define our local functions  (parse is declared above option parsing)
-#
-###########################################################################
-
-banner () {
-    echo "#####    User: ${user_name}"
-    echo ""
-    echo "##### Machine: ${user_name}"
-    echo ""
-
-   if [ -n "${title}" ]
-   then
-    echo "#####   Title: ${title}"
-    echo ""
-   fi
-
-    echo "#####   Files: ${flist}"
-    echo ""
-
-#####
-# this should deal w/ the year 2000 ok.  But will die in 2038. =)
-#####
-
-    YEAR=`date '+%y'`
-    YEAR=`expr 1900 + ${YEAR}`
-
-    echo "#####    Date: `date '+%a %H:%M %h %d,'` ${YEAR}"
-    echo ""
-    echo "#####     Job: ${request_id}"
-    echo ""
-
-}
-
-print_banner() {
-    if [ -x ${NETATALKHOME}/bin/timeout ]
-    then
-       banner | ${NETATALKHOME}/etc/psf \
-           | ${NETATALKHOME}/bin/timeout "${time}" ${NETATALKHOME}/bin/pap -c -p "${PAPDEST}"
-    else
-       banner | ${NETATALKHOME}/etc/psf \
-           | ${NETATALKHOME}/bin/pap -c -p "{PAPDEST}"
-    fi
-
-    if [ ${?} -ne 0 ]
-    then
-       filter_timeout
-    fi 
-}
-
-#####
-# ${LPTELL} is the name of a program that will send its
-# standard input to the Spooler. It is used to forward
-# the description of a printer fault to the Spooler,
-# which uses it in an alert to the administrator.
-#####
-if [ ! -x "${LPTELL:=${LOCALPATH}/lp.tell}" ]
-then
-    fake_lptell(){
-       header="no"
-       while read line
-       do
-           if [ "no" = "${header}" ]
-           then
-               errmsg ERROR ${E_IP_UNKNOWN} \
-               "unknown printer/interface failure" \
-               "consult your system administrator; \
-               reasons for failure (if any) follow:"
-               header=yes
-           fi
-           echo "${line}" >&2
-       done
-    return 1
-    }
-    LPTELL=fake_lptell
-fi
-
-
-#####
-# timeout catcher for the printing filter
-#####
-
-filter_timeout() {
-
-       cat > ${TMPPREFIX}D <<EOF
-
-The printer ${printer} either timed out at ${time} seconds or pap exited
-abnormally.  As well, we may have exceeded ${print_tries} print attempts.
-The job ${request_id} from ${user_name} on ${machine} was
-printing when this happened.
-
-It may be that the only problem is the size of the job and the speed
-of the printer.
-
-Here is what $NETATALKHOME/bin/papstatus reports as the current 
-state of the printer:
-
-EOF
-#####
-# We don't need to test for timeout, since we cannot get here w/o it.
-#####
-
-    ${NETATALKHOME}/bin/timeout ${time2} ${NETATALKHOME}/bin/papstatus -p "${PAPDEST}" 2>&1 >> ${TMPPREFIX}D 
-    paperr=${?}
-
-    errmsg WARNING ${E_IP_UNKNOWN} "`cat ${TMPPREFIX}D`" "printing continues"
-#####
-# This ought to deal w/ the problem of nonexistent appletalk names, but...
-# for the moment, it calls filter_death.  But it sends the  papstatus 
-# info to LPTELL anyhow, so you should be able to see the error.
-#####
-
-    if [ ${paperr} -ne 0 -o ${too_many} = "1" ]; then
-       paperr=
-       filter_death
-    fi
-    paperr=
-    echo "serverdict begin 0 exitserver systemdict /quit get exec" | \
-                ${NETATALKHOME}/bin/pap -c -p "${PAPDEST}"
-    return 0
-}
-
-#####
-# Death catcher for filter_timeout
-#####
-
-filter_death() {
-
-    cat > ${TMPPREFIX}Z <<EOF
-Excessive delays w/ the printer ${printer}!
-
-While processing on printer ${printer} the job ${request_id} 
-from ${user_name} on ${machine} timed out at ${time} seconds.  
-
-Then while cleaning that timeout, the cleanup operation failed as
-well.
-
-EOF
-    errmsg ERROR ${E_IP_UNKNOWN} "`cat ${TMPPREFIX}Z`"
-    exit 129
-#####
-# Exit and fault the printer.
-#####
-}
-
-#####
-# Print the job
-#####
-printfile() {
-    trap '' 1  # Let the filter handle a hangup
-    trap '' 2 3        # and interrupts
-#####
-# We use timeout so as to not hang the print queue indefinately.  (pap does not
-# timeout on it's own.)
-#
-# Put the 0<${files} before the "eval" to keep clever users from giving 
-# a file name that evaluates as something to execute.
-#####
-    if [ "${TERM}" == "Netatalk-R" ]; then
-       if [ -x ${NETATALKHOME}/bin/timeout ]; then
-           0<${file} /usr/lib/lp/postscript/postreverse | ${NETATALKHOME}/bin/timeout ${time} ${NETATALKHOME}/bin/pap -c -p "${PAPDEST}"
-       else
-           0<${file} /usr/lib/lp/postscript/postreverse | ${NETATALKHOME}/bin/pap -c -p "${PAPDEST}"
-       fi
-    else
-       if [ -x ${NETATALKHOME}/bin/timeout ]; then
-           0<${file} ${NETATALKHOME}/bin/timeout ${time} ${NETATALKHOME}/bin/pap -c -p "${PAPDEST}"
-       else
-           0<${file} ${NETATALKHOME}/bin/pap -c -p "${PAPDEST}"
-       fi
-    fi
-    paperr=${?}
-    print_tries=`expr "${print_tries}" + 1`
-    if [ "${paperr}" != "0" -a "${print_tries}" -gt "${attempts}" ]; then
-       too_many=1
-    fi
-    trap 'catch_hangup; exit_code=129 exit 129' 1
-    trap 'catch_interrupt; exit_code=129 exit 129' 2 3
-    return ${paperr}
-}
-
-#####
-# Some basic sanity checking:
-#####
-
-if [ ! -x $NETATALKHOME/bin/pap ]
-then
-    echo "Opps, cannot find $NETATALKHOME/bin/pap, so I don't know how to"
-    echo "print things"
-    # exit w/ less than 128 to mark an error w/ the job, and call it done
-    exit 1 
-fi
-
-###########################################################################
-#
-# Start the main section of the program.
-#
-###########################################################################
-
-#####
-# Here i should have a "job canceled" page ready in a trap in case of getting killed
-# but, alas, that would most likely muck up the PS.  So we just drop the job on the 
-# floor.
-#####
-
-#####
-# If you want a custom banner, change the code up in the functions section.
-#####
-
-if [ "no" = "${nobanner}" -a "${TERM}" != "Netatalk-R" ]
-then
-    print_banner
-fi
-
-#####
-# Print some copies of the file(s)
-#####
-
-badfileyet=
-i=1
-while [ $i -le $copies ]
-do
-    for file in ${files}
-    do
-       if [ -r "${file}" ]
-        then
-            print_tries=0
-           until printfile
-           do
-               filter_timeout;
-           done
-       else
-#####
-# Don't complain about not being able to read a file on second and
-# subsequent copies, unless we've not complained yet. This removes
-# repeated messages about the same file yet reduces the chance that the
-# user can remove a file and not know that we had trouble finding it.
-#####
-           if [ "${i}" -le 1 -o -z "${badfileyet}" ]
-           then
-               errmsg WARNING ${E_IP_BADFILE} \
-                   "cannot read file \"${file}\" " \
-                   "see if the file still exists and is readable by the user\
-                   lp (or world), or consult your system administrator; \
-                   We will keep trying to print the other files or copies"
-               badfileyet=yes
-           fi
-       fi
-    done
-    i=`expr $i + 1`
-done
-
-#####
-# print the banner page if we are a reversed queue
-#####
-if [ "no" = "${nobanner}" -a "${TERM}" == "Netatalk-R" ]
-then
-    print_banner
-fi
-
-echo "serverdict begin 0 exitserver systemdict /quit get exec" | \
-                ${NETATALKHOME}/bin/pap -c -p "${PAPDEST}"
-
-Exit_code=0 exit 0
index c2af4d0e544e6c525088624bf689a6e12519089c..608cd04c73c5a4dac0ea80acc3c606d647595501 100644 (file)
@@ -1,12 +1,5 @@
 Makefile
 Makefile.in
-apple_cleanup
-apple_cp
-apple_mv
-apple_rm
-cleanappledouble.pl
-netatalkshorternamelinks.pl
-lp2pap.sh
 asip-status.pl
 apple_dump
 .gitignore
index 5e4aaa91abe17fedd8f559c67f94567a379e51de..bb4d9cbf0637381a924e0a0d2f41b8364381ce72 100644 (file)
@@ -2,8 +2,8 @@
 
 pkgconfdir = @PKGCONFDIR@
 
-GENERATED_FILES = lp2pap.sh
-TEMPLATE_FILES = lp2pap.sh.tmpl
+GENERATED_FILES = 
+TEMPLATE_FILES = 
 PERLSCRIPTS = \
        asip-status.pl \
        apple_dump
index 65eec7908e0b4ea2c61e5f52308a1c2b5f537a13..e98ad357e31a7dcc70ab30706023ffb55618d30f 100755 (executable)
@@ -2,7 +2,7 @@
 #
 # AppleSingle/AppleDouble dump
 #
-# (c) 2009-2010 by HAT <hat@fa2.so-net.ne.jp>
+# (c) 2009-2012 by HAT <hat@fa2.so-net.ne.jp>
 #
 #  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
 #  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.
-# 
+#
 
-# 
+#
 # References:
-# 
+#
 # Applesingle and AppleDouble format internals (version 1)
 # http://users.phg-online.de/tk/netatalk/doc/Apple/v1/
-# 
+#
 # AppleSingle/AppleDouble Formats for Foreign Files Developer's Note (version2)
 # http://users.phg-online.de/tk/netatalk/doc/Apple/v2/AppleSingle_AppleDouble.pdf
-# 
+#
 # Inside Macintosh: Macintosh Toolbox Essentials /
 # Chapter 7 - Finder Interface / Finder Interface Reference
 # http://developer.apple.com/legacy/mac/library/documentation/mac/toolbox/Toolbox-463.html
-# 
+#
 # Finder Interface Reference
 # http://developer.apple.com/legacy/mac/library/documentation/Carbon/Reference/Finder_Interface/Reference/reference.html
-# 
+#
 # Technical Note TN1150  HFS Plus Volume Format
 # http://developer.apple.com/mac/library/technotes/tn/tn1150.html#FinderInfo
-# 
+#
 # CarbonHeaders source
 # http://www.opensource.apple.com/source/CarbonHeaders/CarbonHeaders-8A428/Finder.h
 # http://www.opensource.apple.com/source/CarbonHeaders/CarbonHeaders-9A581/Finder.h
-# 
+#
 # Xcode 3.2.1
 # /usr/bin/SetFile
 # /usr/bin/GetFileInfo
-# 
+#
 # Mac OS X 10.6.2 kernel source
 # http://www.opensource.apple.com/source/xnu/xnu-1486.2.11/bsd/vfs/vfs_xattr.c
-# 
+#
 
 use File::Basename;
 use File::Spec;
+use File::Temp qw /tempfile/;
 use bigint; # require perl >= 5.8
 
+# check command for extended attributes -----------------------------------
+
+if (     0 == system("which getfattr > /dev/null 2>&1")) {
+    $eacommand = 1;
+} elsif (0 == system("which xattr > /dev/null 2>&1")) {
+    $eacommand = 2;
+} elsif (0 == system("which runat > /dev/null 2>&1")) {
+    $eacommand = 3;
+} else {
+    $eacommand = 0;
+}
+
+#printf ( "eacommand = %d\n", $eacommand );   # debug
+
 # parse command line -----------------------------------------------
 
+$eaoption = 0;
 $finderinfo = 0;              #  0: unknown   1: file   2: directory
 while ($arg = shift @ARGV)
 {
     if  ($arg =~ /^(-h|-help|--help)$/ ) {
         printf ("usage: %s [-a] FILE|DIR\n"           ,basename($0));
+        printf (" or:   %s -e FILE|DIR\n"             ,basename($0));
         printf (" or:   %s -f FILE\n"                 ,basename($0));
         printf (" or:   %s -d FILE\n"                 ,basename($0));
         printf (" or:   %s -h|-help|--help\n"         ,basename($0));
         printf (" or:   %s -v|-version|--version\n"   ,basename($0));
-        printf ("Dump AppleSingle/AppleDouble format file.\n");
+        printf ("Dump AppleSingle/AppleDouble format data.\n");
         printf ("\n");
-        printf ("  -a (default)     Dump a AppleSingle/AppleDouble file for FILE or DIR\n");
+        printf ("  -a (default)     Dump a AppleSingle/AppleDouble data for FILE or DIR\n");
         printf ("                   automatically.\n");
-        printf ("                   Extrapolate FinderInfo type from absolute path.\n");
         printf ("                   If FILE is not AppleSingle/AppleDouble format,\n");
-        printf ("                   look for '.AppleDouble/FILE' and '._FILE'.\n");
-        printf ("                   If DIR, look for 'DIR/.AppleDouble/.Parent' and '._DIR'.\n");
+        printf ("                   look for extended attribute, .AppleDouble/FILE and ._FILE.\n");
+        printf ("                   If DIR, look for extended attribute,\n");
+        printf ("                   DIR/.AppleDouble/.Parent and ._DIR.\n");
+        printf ("  -e               Dump extended attribute of FILE or DIR\n");
         printf ("  -f               Dump FILE. Assume FinderInfo to be FileInfo.\n");
         printf ("  -d               Dump FILE. Assume FinderInfo to be DirInfo.\n");
         printf ("  -h,-help,--help  Display this help and exit\n");
@@ -78,7 +96,7 @@ while ($arg = shift @ARGV)
         printf ("By default, %s examins whether file or directory,\n"   ,basename($0));
         printf ("a parent directory is .AppleDouble, filename is ._*, filename is .Parent,\n");
         printf ("and so on.\n");
-        printf ("If setting option -f or -d, %s assume FinderInfo and doesn't look for\n");
+        printf ("If setting option -e, -f or -d, %s assume FinderInfo and doesn't look for\n");
         printf ("another file.\n");
         exit 1;
     } elsif ($arg =~ /^(-v|-version|--version)$/ ) {
@@ -86,14 +104,21 @@ while ($arg = shift @ARGV)
         exit 1;
     } elsif ($arg eq "-a") {
         $finderinfo = 0;
+    } elsif ($arg eq "-e") {
+        if ($eacommand == 0) {
+            printf (STDERR "%s: unsupported option -e\n", basename($0));
+            printf (STDERR "because neither getfattr, xattr nor runat is found.\n");
+            exit 1;
+        }
+        $eaoption = 1;
     } elsif ($arg eq "-f") {
         $finderinfo = 1;
     } elsif ($arg eq "-d") {
         $finderinfo = 2;
     } elsif ($arg =~ /^-/) {
-       printf (STDERR "%s: invalid option %s\n", basename($0), $arg);
-       printf (STDERR "Try \`%s\ -h' for more information.\n", basename($0));
-       exit 1;
+        printf (STDERR "%s: invalid option %s\n", basename($0), $arg);
+        printf (STDERR "Try \`%s\ -h' for more information.\n", basename($0));
+        exit 1;
     } else {
         $afile = $arg;
     }
@@ -104,7 +129,7 @@ if (!($afile)) {
     exit 1;
 }
 if (!( -e $afile)) {
-    printf (STDERR "\"%s\" not found.\n", $afile);
+    printf (STDERR "\"%s\" is not found.\n", $afile);
     exit 1;
 }
 
@@ -113,80 +138,124 @@ if (!( -e $afile)) {
 $abspath = File::Spec->rel2abs($afile);
 ($basename, $path, $ext) = fileparse($abspath);
 
-if ( $finderinfo != 0 ) {
-    ;
+if ( $eaoption == 1 ) {
+    if ( -f $afile ) {
+        $finderinfo = 1;
+    } elsif ( -d $afile ) {
+        $finderinfo = 2;
+    } else {
+        printf (STDERR "unknown error: %s\n", $afile);
+        exit 1;
+    }
+    if ( 0 == checkea($afile) ) {
+        printf (STDERR "\"%s\"'s extended attribute is not found\n",  $afile);
+        exit 1;
+    }
+    $openfile = eaopenfile($afile);
+    $openmessage = "Dumping \"$afile\"'s extended attribute...\n";
+} elsif ( $finderinfo != 0 ) {
+    $openfile = $afile;
 } elsif ( -f $afile ) {
     if ( $basename eq ".Parent") {
-       $finderinfo = 2;
+        $finderinfo = 2;
     } elsif ( $path =~ /\/.AppleDouble\/$/ ) {
-       $finderinfo =1;
+        $finderinfo = 1;
     } elsif ( $basename =~ /^._/ ) {
-       if ( -f $path.substr($basename, 2) ) {
-           $finderinfo =1;
-       } elsif ( -d $path.substr($basename, 2) ) {
-           $finderinfo =2;
-       }
+        if ( -f $path.substr($basename, 2) ) {
+            $finderinfo = 1;
+        } elsif ( -d $path.substr($basename, 2) ) {
+            $finderinfo = 2;
+        }
     }
     if (!open(INFILE, "<$afile")) {
-       printf (STDERR "cannot open %s\n",  $afile);
-       exit 1;
+        printf (STDERR "cannot open %s\n",  $afile);
+        exit 1;
     }
     read(INFILE,$buf,4);
     $val = unpack("N", $buf );
     close(INFILE);
     if ($val == 0x00051600 || $val == 0x00051607) {
-       ;
+        $openfile = $afile;
+        $openmessage = "Dumping \"$openfile\"...\n";
     } else {
-       printf ("\"%s\" is not AppleSingle/AppleDouble format.\n", $afile);
-       $finderinfo = 1;
-       $netatalkfile = $path.".AppleDouble/".$basename;
-       $osxfile = $path."._".$basename;
-
-       if (( -e $netatalkfile ) && !( -e $osxfile )) {
-           $afile = $netatalkfile;
-       } elsif (!( -e $netatalkfile ) && ( -e $osxfile )) {
-           $afile = $osxfile;
-       } elsif (( -e $netatalkfile ) && ( -e $osxfile )) {
-           printf ("\"%s\" found.\n", $netatalkfile);
-           printf ("\"%s\" found.\n", $osxfile);
-           printf ("Specify which of file.\n");
-           exit 1;
-       } else {
-           printf ("\"%s\" not found.\n", $netatalkfile);
-           printf ("\"%s\" not found.\n", $osxfile);
-           exit 1;
-       }
+        printf ("\"%s\" is not AppleSingle/AppleDouble format.\n", $afile);
+        $finderinfo = 1;
+        $adcount = 0;
+        $netatalkfile = $path.".AppleDouble/".$basename;
+        $osxfile = $path."._".$basename;
+
+        if ( 1 == checkea($afile) ) {
+            printf ("\"%s\"\'s extended attribute is found.\n", $afile);
+            $adcount++;
+            $openfile = eaopenfile($afile);
+            $openmessage = "Dumping \"$afile\"'s extended attribute...\n";
+        }
+        if ( -e $netatalkfile ) {
+            printf ("\"%s\" is found.\n", $netatalkfile);
+            $openfile = $netatalkfile;
+            $openmessage = "Dumping \"$openfile\"...\n";
+        }
+        if ( -e $osxfile ) {
+            printf ("\"%s\" is found.\n", $osxfile);
+            $adcount++;
+            $openfile = $osxfile;
+            $openmessage = "Dumping \"$openfile\"...\n";
+        }
+        if ( $adcount == 0 ) {
+            printf ("AppleSingle/AppleDouble data is not found.\n");
+            exit 1;
+        }
+        if ( $adcount != 1 ) {
+            printf ("Specify any one.\n");
+            exit 1;
+        }
     }
 } elsif ( -d $afile) {
     printf ("\"%s\" is a directory.\n", $afile);
-    $finderinfo =2;
+    $finderinfo = 2;
+    $adcount = 0;
     $netatalkfile = $path.$basename."/.AppleDouble/.Parent";
     $osxfile = $path."._".$basename;
 
-    if (( -e $netatalkfile ) && !( -e $osxfile )) {
-       $afile = $netatalkfile;
-    } elsif (!( -e $netatalkfile ) && ( -e $osxfile )) {
-       $afile = $osxfile;
-    } elsif (( -e $netatalkfile ) && ( -e $osxfile )) {
-       printf ("\"%s\" found.\n", $netatalkfile);
-       printf ("\"%s\" found.\n", $osxfile);
-       printf ("Specify which of file.\n");
-       exit 1;
-    } else {
-       printf ("\"%s\" not found.\n", $netatalkfile);
-       printf ("\"%s\" not found.\n", $osxfile);
-       exit 1;
+    if ( 1 == checkea($afile) ) {
+        printf ("\"%s\"\'s extended attribute is found.\n", $afile);
+        $adcount++;
+        $openfile = eaopenfile($afile);
+        $openmessage = "Dumping \"$afile\"'s extended attribute...\n";
+    }
+    if ( -e $netatalkfile ) {
+        printf ("\"%s\" is found.\n", $netatalkfile);
+        $adcount++;
+        $openfile= $netatalkfile;
+        $openmessage = "Dumping \"$openfile\"...\n";
+    }
+    if ( -e $osxfile ) {
+        printf ("\"%s\" is found.\n", $osxfile);
+        $adcount++;
+        $openfile = $osxfile;
+        $openmessage = "Dumping \"$openfile\"...\n";
+    }
+    if ( $adcount == 0 ) {
+        printf ("AppleSingle/AppleDouble data is not found.\n");
+        exit 1;
+    }
+    if ( $adcount != 1 ) {
+        printf ("Specify any one.\n");
+        exit 1;
     }
 } else {
     printf (STDERR "unknown error: %s\n", $afile);
     exit 1;
 }
 
-if (!open(INFILE, "<$afile")) {
-    printf (STDERR "cannot open %s\n",  $afile);
+if (!open(INFILE, "<$openfile")) {
+    printf (STDERR "cannot open %s\n",  $openfile);
     exit 1;
 }
-printf ("%s:\n\n", $afile);
+
+printf ($openmessage);
+
+#Dump --------------------------------------------------------
 
 # Magic Number -----------------------------------------------
 
@@ -306,7 +375,7 @@ for ( $num = 0 ; $num < $entnum ; $num++) {
 #    if ( $entid == 13 ) { ; } # Short Name
 #    if ( $entid == 14 ) { ; } # AFP File Info 
     elsif ( $entid == 15 ) { print "\n"; bedump($ofst,$len); } # Directory ID
-    elsif ( $entid == 0x8053567E  ) { print "\n"; bedump($ofst,$len); } # CNID (Netatalk Extended)
+    elsif ( $entid == 0x8053567E  ) { print "\n"; bedump($ofst,$len); ledump($ofst,$len); } # CNID (Netatalk Extended)
     elsif ( $entid == 0x8053594E  ) { print "\n"; bedump($ofst,$len); ledump($ofst,$len); } # DB stamp (Netatalk Extended)
     elsif ( $entid == 0x80444556  ) { print "\n"; bedump($ofst,$len); ledump($ofst,$len); } # dev (Netatalk Extended)
     elsif ( $entid == 0x80494E4F  ) { print "\n"; bedump($ofst,$len); ledump($ofst,$len); } # inode (Netatalk Extended)
@@ -314,8 +383,8 @@ for ( $num = 0 ; $num < $entnum ; $num++) {
 #    RAW Dump ---------------------------------------------------
 
     if ( ($quo > 0) || ($rem > 0)) {
-       print "\n";
-       print "-RAW DUMP--:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F : (ASCII)\n";
+        print "\n";
+        print "-RAW DUMP--:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F : (ASCII)\n";
     }
 
     seek(INFILE, $ofst, 0);
@@ -365,16 +434,16 @@ sub finderinfodump {
     seek(INFILE, $ofst, 0);
 
     if ($finderinfo == 0) {
-       print "\n";
-       print "-NOTE------: cannot detect whether FInfo or DInfo. assume FInfo.\n";
+        print "\n";
+        print "-NOTE------: cannot detect whether FInfo or DInfo. assume FInfo.\n";
     }
 
     if ($finderinfo == 0 || $finderinfo == 1) {
-       filefinderinfodump();
+        filefinderinfodump();
     } elsif ($finderinfo == 2) {
-       dirfinderinfodump();
+        dirfinderinfodump();
     } else {
-       print STDERR "unknown FinderInfo type\n"
+        print STDERR "unknown FinderInfo type\n"
     }
 
     if ($len > 32) { eadump(); }
@@ -533,27 +602,27 @@ sub flagsdump {
     printf ("color      : %d%d%d      : %s\n", ($flags >>  3) & 1,
             ($flags >>  2) & 1,
             ($flags >>  1) & 1,
-           @colortype[($flags & 0xE)>>1]);
+            @colortype[($flags & 0xE)>>1]);
     printf ("isOnDesk   : %d\n", ($flags >>  0) & 1);
 
 }
 
 sub xflagsdump {
-    
+
     read(INFILE,$buf,2);
     $flags = unpack("n", $buf );
-    
+
     if (($flags >> 15) == 1) {
-       print "Script     : ";
-       hexdump($buf, 1, 4, "");
+        print "Script     : ";
+        hexdump($buf, 1, 4, "");
     } else {
-       printf ("AreInvalid : %d\n", ($flags >> 15) & 1);
-       printf ("unknown bit: %d\n", ($flags >> 14) & 1);
-       printf ("unknown bit: %d\n", ($flags >> 13) & 1);
-       printf ("unknown bit: %d\n", ($flags >> 12) & 1);
-       printf ("unknown bit: %d\n", ($flags >> 11) & 1);
-       printf ("unknown bit: %d\n", ($flags >> 10) & 1);
-       printf ("unknown bit: %d\n", ($flags >>  9) & 1);
+        printf ("AreInvalid : %d\n", ($flags >> 15) & 1);
+        printf ("unknown bit: %d\n", ($flags >> 14) & 1);
+        printf ("unknown bit: %d\n", ($flags >> 13) & 1);
+        printf ("unknown bit: %d\n", ($flags >> 12) & 1);
+        printf ("unknown bit: %d\n", ($flags >> 11) & 1);
+        printf ("unknown bit: %d\n", ($flags >> 10) & 1);
+        printf ("unknown bit: %d\n", ($flags >>  9) & 1);
     }
 
     printf ("CustomBadge: %d\n", ($flags >>  8) & 1);
@@ -569,7 +638,7 @@ sub xflagsdump {
 }
 
 sub eadump {
-    
+
     print "\n";
     print "-EA--------:\n";
 
@@ -623,45 +692,45 @@ sub eadump {
     printf("     : %d\n", $ea_num_attrs);
 
     $pos = tell(INFILE);
-    
+
     for ($i = 0 ; $i < $ea_num_attrs ; $i++) {
-       
-       $pos = (($pos & 0x3) == 0) ? ($pos) : ((($pos >> 2) + 1) << 2);
-       seek(INFILE, $pos, 0);
-
-       print "-EA ENTRY--:\n";
-       
-       read(INFILE,$buf,4);
-       $ea_offset = unpack("N", $buf );
-       printf("offset     : %08X", $ea_offset);
-       printf(" : %d\n", $ea_offset);
-       
-       read(INFILE,$buf,4);
-       $ea_length = unpack("N", $buf );
-       printf("length     : %08X", $ea_length);
-       printf(" : %d\n", $ea_length);
-       
-       read(INFILE,$buf,2);
-       print "flags      : ";
-       hexdump($buf, 2, 4, "");
-       
-       read(INFILE,$buf,1);
-       $ea_namelen = unpack("C", $buf );
-       printf("namelen    : %02X", $ea_namelen);
-       printf("       : %d\n", $ea_namelen);
-
-       $ea_namequo = $ea_namelen >> 4;
-       $ea_namerem = $ea_namelen & 0xF;
-       print "-EA NAME---:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F : (ASCII)\n";
-       rawdump($ea_namequo, $ea_namerem);
-
-       $pos = tell(INFILE);
-
-       seek(INFILE, $ea_offset, 0);
-       $ea_quo = $ea_length >> 4;
-       $ea_rem = $ea_length & 0xF;
-       print "-EA VALUE--:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F : (ASCII)\n";
-       rawdump($ea_quo, $ea_rem);
+
+        $pos = (($pos & 0x3) == 0) ? ($pos) : ((($pos >> 2) + 1) << 2);
+        seek(INFILE, $pos, 0);
+
+        print "-EA ENTRY--:\n";
+
+        read(INFILE,$buf,4);
+        $ea_offset = unpack("N", $buf );
+        printf("offset     : %08X", $ea_offset);
+        printf(" : %d\n", $ea_offset);
+
+        read(INFILE,$buf,4);
+        $ea_length = unpack("N", $buf );
+        printf("length     : %08X", $ea_length);
+        printf(" : %d\n", $ea_length);
+
+        read(INFILE,$buf,2);
+        print "flags      : ";
+        hexdump($buf, 2, 4, "");
+
+        read(INFILE,$buf,1);
+        $ea_namelen = unpack("C", $buf );
+        printf("namelen    : %02X", $ea_namelen);
+        printf("       : %d\n", $ea_namelen);
+
+        $ea_namequo = $ea_namelen >> 4;
+        $ea_namerem = $ea_namelen & 0xF;
+        print "-EA NAME---:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F : (ASCII)\n";
+        rawdump($ea_namequo, $ea_namerem);
+
+        $pos = tell(INFILE);
+
+        seek(INFILE, $ea_offset, 0);
+        $ea_quo = $ea_length >> 4;
+        $ea_rem = $ea_length & 0xF;
+        print "-EA VALUE--:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F : (ASCII)\n";
+        rawdump($ea_quo, $ea_rem);
     }
 }
 
@@ -669,56 +738,54 @@ sub bedump  {
     my ($ofst, $len) = @_;
     my ($i);
     my ($value);
-    
+
     seek(INFILE, $ofst, 0);
-    
+
     printf("%2dbit-BE   : ", $len * 8 );
-    
+
     $value = 0;
     for ( $i=0 ; $i < $len ; $i++ ) {
-       read(INFILE,$buf,1);
-       $bytedata[$i] = unpack("C", $buf );
-       $value += $bytedata[$i] << (($len - $i -1) * 8) ;
+        read(INFILE,$buf,1);
+        $bytedata[$i] = unpack("C", $buf );
+          $value += $bytedata[$i] << (($len - $i -1) * 8) ;
     }
 
     for ( $i=0 ; $i < $len ; $i++ ) {
-       printf("%02X", $bytedata[$i]);
+        printf("%02X", $bytedata[$i]);
     }
 
     printf(" : %s", $value);
     print "\n";
-    
 }
 
 sub ledump  {
     my ($ofst, $len) = @_;
     my ($i);
     my ($value);
-    
+
     seek(INFILE, $ofst, 0);
-    
+
     printf("%2dbit-LE   : ", $len * 8 );
-    
+
     $value = 0;
     for ( $i=0 ; $i < $len ; $i++ ) {
-       read(INFILE,$buf,1);
-       $bytedata[$len - $i - 1] = unpack("C", $buf );
-       $value += $bytedata[$len - $i -1] << ($i * 8) ;
+        read(INFILE,$buf,1);
+        $bytedata[$len - $i - 1] = unpack("C", $buf );
+          $value += $bytedata[$len - $i -1] << ($i * 8) ;
     }
 
     for ( $i=0 ; $i < $len ; $i++ ) {
-       printf("%02X", $bytedata[$i]);
+        printf("%02X", $bytedata[$i]);
     }
 
     printf(" : %s", $value);
     print "\n";
-    
 }
 
 sub rawdump {
     my ($quo, $rem) = @_;
     my ($addrs, $line, $buf);
-    
+
     $addrs = 0;
     for ( $line = 0 ; $line < $quo ; $line++) {
         read(INFILE, $buf, 16);
@@ -731,7 +798,6 @@ sub rawdump {
         printf ( "%08X   :", $addrs);
         hexdump($buf, $rem, 16, " ");
     }
-    
 }
 
 sub hexdump {
@@ -761,4 +827,69 @@ sub hexdump {
     print "\n";
 }
 
+sub checkea {
+    my ($file) = @_;
+
+    $file =~ s/\\/\\\\/g;
+    $file =~ s/\"/\\\"/g;
+    $file =~ s/\$/\\\$/g;
+    $file =~ s/\`/\\\`/g;
+    if ( $eacommand == 1 ) {
+        open(EALIST, "getfattr \"$file\" |");
+        while(<EALIST>) {
+            if ( $_ eq "user.org.netatalk.Metadata\n" ) {
+                close (EALIST);
+                return 1;
+            }
+        }
+        close (EALIST);
+        return 0;
+    } elsif ( $eacommand == 2 ) {
+        open(EALIST, "attr -q -l \"$file\" |");
+        while(<EALIST>) {
+            if ( $_ eq "org.netatalk.Metadata\n" ) {
+                close (EALIST);
+                return 1;
+            }
+        }
+        close (EALIST);
+        return 0;
+    } elsif ( $eacommand == 3 ) {
+        open(EALIST, "runat \"$file\" ls -1 |");
+        while(<EALIST>) {
+            if ( $_ eq "org.netatalk.Metadata\n" ) {
+                close (EALIST);
+                return 1;
+            }
+        }
+        close (EALIST);
+        return 0;
+    } else {
+        return 0;
+    }
+}
+
+sub eaopenfile {
+    my ($file) = @_;
+
+    $file =~ s/\\/\\\\/g;
+    $file =~ s/\"/\\\"/g;
+    $file =~ s/\$/\\\$/g;
+    $file =~ s/\`/\\\`/g;
+    ($eatempfh, $eatempfile) = tempfile(UNLINK => 1);
+
+    if ( $eacommand == 1 ) {
+        system("getfattr --only-values -n user.org.netatalk.Metadata \"$file\" > $eatempfile");
+    } elsif ( $eacommand == 2 ) {
+        system("attr -q -g org.netatalk.Metadata \"$file\" > $eatempfile");
+    } elsif ( $eacommand == 3 ) {
+        system("runat \"$file\" cat org.netatalk.Metadata > $eatempfile");
+    } else {
+        return "";
+    }
+
+    close($eatempfh);
+    return $eatempfile;
+}
+
 #EOF
index 4fa260947ca9c059fb354350d8cd22c2b71a5c8c..8814b8ecb0c9ec9c3c39841207bb741439f41b72 100755 (executable)
@@ -229,7 +229,12 @@ sub parse_FPGetSrvrInfo()
 
        my ($icon_offset) = unpack("n", @packet[6] . @packet[7]);
        print "Volume Icon & Mask offset: $icon_offset\n" if ($main::debug);
-       print "Volume Icon & Mask: exist\n" if ($icon_offset);
+       print "Volume Icon & Mask: ";
+       if ($icon_offset) {
+           print "Yes\n";
+       } else {
+           print "No\n";
+       }
 
        my ($flags) = unpack("n", @packet[8] . @packet[9]);
        my (@flags) = parse_afp_flags($flags);
diff --git a/contrib/shell_utils/lp2pap.sh.tmpl b/contrib/shell_utils/lp2pap.sh.tmpl
deleted file mode 100755 (executable)
index fea0cf4..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/bin/sh
-# pap script for lp systems
-
-chdir "/etc/lp/printers/`basename $0`"
-
-if [ -r "$6" ]; then
-    :BINDIR:/pap -E "$6"
-    exit $?
-fi
-
-exit 2
diff --git a/contrib/timelord/.gitignore b/contrib/timelord/.gitignore
deleted file mode 100644 (file)
index 47b8196..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Makefile
-Makefile.in
-timelord
-.deps
-.libs
-.gitignore
-*.o
diff --git a/contrib/timelord/COPYRIGHT b/contrib/timelord/COPYRIGHT
deleted file mode 100644 (file)
index f6141ea..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Wesley Craig
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1 313 764 2278
- *     netatalk@umich.edu
- */
-
-/*
- * The "timelord protocol" was reverse engineered from Timelord,
- * distributed with CAP, Copyright (c) 1990, The University of
- * Melbourne.  The following copyright, supplied by The University
- * of Melbourne, may apply to this code:
- *
- *     This version of timelord.c is based on code distributed
- *     by the University of Melbourne as part of the CAP package.
- *
- *     The tardis/Timelord package for Macintosh/CAP is
- *     Copyright (c) 1990, The University of Melbourne.
- */
diff --git a/contrib/timelord/Makefile.am b/contrib/timelord/Makefile.am
deleted file mode 100644 (file)
index b592695..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-# Makefile.am for contrib/timelord/
-
-sbin_PROGRAMS = timelord
-
-timelord_SOURCES = timelord.c
-timelord_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-LIBS = @LIBS@
-
-EXTRA_DIST = COPYRIGHT README VERSION
diff --git a/contrib/timelord/README b/contrib/timelord/README
deleted file mode 100644 (file)
index 37446f1..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-$Id: README,v 1.3 2002-02-21 09:59:24 srittau Exp $
-
-This is the README file for timelord 1.0 (previously known as
-ntimelord), for use with netatalk 1.5. Previous versions of this
-software were designed to work with netatalk 1.3, but this has
-been patched to work with netatalk 1.5.  Please see the COPYRIGHT
-file.  This package's COPYRIGHT is *not* the same as netatalk's.
-
-Building timelord:
-
-1.  Run ./configure from the base directory of your netatalk
-    distribution, and add --enable-timelord to your command line
-    options.
-
-2.  Run "make all" for netatalk, and timelord will be built along
-    with the rest of netatalk.
-
-Installing timelord:
-
-1.  To install the binaries, type "make install" from either the base
-    directory of your netatalk distribution or from this directory. 
-    This will install all of the binaries in the directory specified
-    by ./configure.
-
-2.  The file rc.atalk as distributed with netatalk 1.5 includes lines to
-    start timelord.
diff --git a/contrib/timelord/VERSION b/contrib/timelord/VERSION
deleted file mode 100644 (file)
index d3827e7..0000000
+++ /dev/null
@@ -1 +0,0 @@
-1.0
diff --git a/contrib/timelord/timelord.c b/contrib/timelord/timelord.c
deleted file mode 100644 (file)
index 60fdb8e..0000000
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * $Id: timelord.c,v 1.8 2005-04-28 20:49:36 bfernhomberg Exp $
- *
- * Copyright (c) 1990,1992 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * The "timelord protocol" was reverse engineered from Timelord,
- * distributed with CAP, Copyright (c) 1990, The University of
- * Melbourne.  The following copyright, supplied by The University
- * of Melbourne, may apply to this code:
- *
- *     This version of timelord.c is based on code distributed
- *     by the University of Melbourne as part of the CAP package.
- *
- *     The tardis/Timelord package for Macintosh/CAP is
- *     Copyright (c) 1990, The University of Melbourne.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/file.h>
-#include <sys/uio.h>
-#include <stdlib.h>
-
-#include <unistd.h>
-
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <atalk/atp.h>
-#include <atalk/nbp.h>
-
-#include <time.h>
-#ifdef HAVE_SGTTY_H
-#include <sgtty.h>
-#endif /* HAVE_SGTTY_H */
-#include <errno.h>
-#include <signal.h>
-#pragma warn "testing 123"
-#include <atalk/logger.h>
-#include <stdio.h>
-#include <string.h>
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif /* HAVE_NETDB_H */
-
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#ifdef HAVE_SYS_FCNTL_H
-#include <sys/fcntl.h>
-#endif /* HAVE_SYS_FCNTL_H */
-
-#ifdef HAVE_TERMIOS_H
-#include <termios.h>
-#endif /* HAVE_TERMIOS_H */
-#ifdef HAVE_SYS_TERMIOS_H
-#include <sys/termios.h>
-#endif /* HAVE_SYS_TERMIOS_H */
-
-#define        TL_GETTIME      0
-#define        TL_OK           12
-#define TL_BAD         10
-#define EPOCH          0x7C25B080      /* 00:00:00 GMT Jan 1, 1970 for Mac */
-
-int    debug = 0;
-char   *bad = "Bad request!";
-char   buf[ 4624 ];
-char   *server;
-
-void usage( char *p )
-{
-    char       *s;
-
-    if (( s = rindex( p, '/' )) == NULL ) {
-       s = p;
-    } else {
-       s++;
-    }
-    fprintf( stderr, "Usage:\t%s -d -n nbpname\n", s );
-    exit( 1 );
-}
-
-/*
- * Unregister ourself on signal.
- */
-void
-goaway(int signal)
-{
-    if ( nbp_unrgstr( server, "TimeLord", "*", NULL ) < 0 ) {
-       LOG(log_error, logtype_default, "Can't unregister %s", server );
-       exit( 1 );
-    }
-    LOG(log_info, logtype_default, "going down" );
-    exit( 0 );
-}
-
-int main( int ac, char **av )
-{
-    ATP                        atp;
-    struct sockaddr_at sat;
-    struct atp_block   atpb;
-    struct timeval     tv;
-    struct timezone    tz;
-    struct iovec       iov;
-    struct tm          *tm;
-    char               hostname[ MAXHOSTNAMELEN ];
-    char               *p;
-    int                        c;
-    long               req, mtime, resp;
-    extern char                *optarg;
-    extern int         optind;
-
-    if ( gethostname( hostname, sizeof( hostname )) < 0 ) {
-       perror( "gethostname" );
-       exit( 1 );
-    }
-    if (( server = index( hostname, '.' )) != 0 ) {
-       *server = '\0';
-    }
-    server = hostname;
-
-    while (( c = getopt( ac, av, "dn:" )) != EOF ) {
-       switch ( c ) {
-       case 'd' :
-           debug++;
-           break;
-       case 'n' :
-           server = optarg;
-           break;
-       default :
-           fprintf( stderr, "Unknown option -- '%c'\n", c );
-           usage( *av );
-       }
-    }
-
-    /*
-     * Disassociate from controlling tty.
-     */
-    if ( !debug ) {
-       int             i, dt;
-
-       switch ( fork()) {
-       case 0 :
-           dt = getdtablesize();
-           for ( i = 0; i < dt; i++ ) {
-               (void)close( i );
-           }
-           if (( i = open( "/dev/tty", O_RDWR )) >= 0 ) {
-               (void)ioctl( i, TIOCNOTTY, 0 );
-               setpgid( 0, getpid());
-               (void)close( i );
-           }
-           break;
-       case -1 :
-           perror( "fork" );
-           exit( 1 );
-       default :
-           exit( 0 );
-       }
-    }
-
-    if (( p = rindex( *av, '/' )) == NULL ) {
-       p = *av;
-    } else {
-       p++;
-    }
-
-#ifdef ultrix
-    openlog( p, LOG_PID );
-#else /* ultrix */
-    set_processname(p);
-    syslog_setup(log_debug, logtype_default, logoption_ndelay|logoption_pid, logfacility_daemon );
-#endif /* ultrix */
-
-    /* allocate memory */
-    memset (&sat.sat_addr, 0, sizeof (sat.sat_addr));
-
-    if (( atp = atp_open( ATADDR_ANYPORT, &sat.sat_addr )) == NULL ) {
-       LOG(log_error, logtype_default, "main: atp_open: %s", strerror( errno ) );
-       exit( 1 );
-    }
-
-    if ( nbp_rgstr( atp_sockaddr( atp ), server, "TimeLord", "*" ) < 0 ) {
-       LOG(log_error, logtype_default, "Can't register %s", server );
-       exit( 1 );
-    }
-    LOG(log_info, logtype_default, "%s:TimeLord started", server );
-
-       signal(SIGHUP, goaway);
-       signal(SIGTERM, goaway);
-
-    for (;;) {
-       /*
-        * Something seriously wrong with atp, since these assigns must
-        * be in the loop...
-        */
-       atpb.atp_saddr = &sat;
-       atpb.atp_rreqdata = buf;
-       bzero( &sat, sizeof( struct sockaddr_at ));
-       atpb.atp_rreqdlen = sizeof( buf );
-       if ( atp_rreq( atp, &atpb ) < 0 ) {
-           LOG(log_error, logtype_default, "main: atp_rreq: %s", strerror( errno ) );
-           exit( 1 );
-       }
-
-       p = buf;
-       bcopy( p, &req, sizeof( long ));
-       req = ntohl( req );
-       p += sizeof( long );
-
-       switch( req ) {
-       case TL_GETTIME :
-           if ( atpb.atp_rreqdlen > 5 ) {
-                   bcopy( p + 1, &mtime, sizeof( long ));
-                   mtime = ntohl( mtime );
-                   LOG(log_info, logtype_default, "gettime from %s %s was %lu",
-                           (*( p + 5 ) == '\0' ) ? "<unknown>" : p + 5,
-                           ( *p == 0 ) ? "at boot" : "in chooser",
-                           mtime );
-           } else {
-                   LOG(log_info, logtype_default, "gettime" );
-           }
-
-           if ( gettimeofday( &tv, &tz ) < 0 ) {
-               LOG(log_error, logtype_default, "main: gettimeofday: %s", strerror( errno ) );
-               exit( 1 );
-           }
-           if (( tm = gmtime( &tv.tv_sec )) == 0 ) {
-               perror( "localtime" );
-               exit( 1 );
-           }
-
-           mtime = tv.tv_sec + EPOCH;
-           mtime = htonl( mtime );
-
-           resp = TL_OK;
-           bcopy( &resp, buf, sizeof( long ));
-           bcopy( &mtime, buf + sizeof( long ), sizeof( long ));
-           iov.iov_len = sizeof( long ) + sizeof( long );
-           break;
-
-       default :
-           LOG(log_error, logtype_default, bad );
-
-           resp = TL_BAD;
-           bcopy( &resp, buf, sizeof( long ));
-           *( buf + 4 ) = (unsigned char)strlen( bad );
-           strcpy( buf + 5, bad );
-           iov.iov_len = sizeof( long ) + 2 + strlen( bad );
-           break;
-       }
-
-       iov.iov_base = buf;
-       atpb.atp_sresiov = &iov;
-       atpb.atp_sresiovcnt = 1;
-       if ( atp_sresp( atp, &atpb ) < 0 ) {
-           LOG(log_error, logtype_default, "main: atp_sresp: %s", strerror( errno ) );
-           exit( 1 );
-       }
-    }
-}
index 5d9bda826dc9e0427fa7fdf3efe9178d42ab885e..765af279125f6f94cce45f0276e614a7be1bbfe3 100644 (file)
@@ -1,3 +1,3 @@
 # Makefile.am for distrib/
 
-SUBDIRS = config initscripts m4 systemd
+SUBDIRS = config initscripts m4
index 8600d948d60807980141689b845e0d14e5f2fafb..125825eb761984ba0e04cc68ba5af8a529a7a658 100644 (file)
@@ -1,15 +1,14 @@
 Makefile
 Makefile.in
-rc.atalk.bsd
-rc.atalk.redhat-sysv
-rc.atalk.systemd
-rc.atalk.suse-sysv
-rc.atalk.tru64
-rc.atalk.sysv
-service.atalk.systemd
+rc.bsd
+rc.debian
+rc.gentoo
+rc.netbsd
+rc.redhat
+rc.solaris
+rc.suse
+service.systemd
 netatalk
-atalk
 netatalk.service
-netatalk.sh
-.gitignore
+netatalk.xml
 *.o
index 360dfccd478762cdfe8c61b06589394ac5fcc9ce..4b88ba9d39f6ac37bc4195ff89f0b9459fcb951a 100644 (file)
@@ -12,43 +12,32 @@ pkgconfdir = @PKGCONFDIR@
        sed -e s@:BINDIR:@${bindir}@ \
            -e s@:SBINDIR:@${sbindir}@ \
            -e s@:ETCDIR:@${pkgconfdir}@ \
-           -e s@:PKGLIBEXECDIR:@${pkglibexecdir}@ \
            -e s@:NETATALK_VERSION:@${NETATALK_VERSION}@ \
            <$< >$@
 
 GENERATED_FILES = \
-       rc.afpd.netbsd          \
-       rc.atalk.redhat-sysv    \
-       rc.atalk.systemd        \
-       rc.atalk.tru64          \
-       rc.atalk.bsd            \
-       rc.atalkd.netbsd        \
-       rc.atalk.suse-sysv      \
-       rc.cnid_metad.netbsd    \
-       rc.papd.netbsd          \
-       rc.timelord.netbsd      \
-       rc.atalk.sysv           \
-       rc.atalk.gentoo         \
-       rc.atalk.debian         \
-       service.atalk.systemd
+       rc.bsd \
+       rc.debian \
+       rc.gentoo \
+       rc.netbsd \
+       rc.redhat \
+       rc.solaris \
+       rc.suse \
+       service.systemd \
+       netatalk.xml
 
 TEMPLATES = \
-       rc.afpd.netbsd.tmpl             \
-       rc.atalk.redhat-sysv.tmpl       \
-       rc.atalk.systemd.tmpl           \
-       rc.atalk.tru64.tmpl             \
-       rc.atalk.bsd.tmpl               \
-       rc.atalkd.netbsd.tmpl           \
-       rc.atalk.suse-sysv.tmpl         \
-       rc.cnid_metad.netbsd.tmpl       \
-       rc.papd.netbsd.tmpl             \
-       rc.timelord.netbsd.tmpl         \
-       rc.atalk.sysv.tmpl              \
-       rc.atalk.gentoo.tmpl            \
-       rc.atalk.debian.tmpl            \
-       service.atalk.systemd.tmpl
-
-CLEANFILES = $(GENERATED_FILES) $(sysv_SCRIPTS) $(service_DATA) afpd atalkd cnid_metad papd timelord
+       rc.bsd.tmpl \
+       rc.debian.tmpl \
+       rc.gentoo.tmpl \
+       rc.netbsd.tmpl \
+       rc.redhat.tmpl \
+       rc.solaris.tmpl \
+       rc.suse.tmpl \
+       service.systemd.tmpl \
+       netatalk.xml.tmpl
+
+CLEANFILES = $(GENERATED_FILES) $(sysv_SCRIPTS) $(service_DATA) afpd cnid_metad
 EXTRA_DIST = $(TEMPLATES)
 
 # overwrite automake uninstall
@@ -66,8 +55,8 @@ if USE_REDHAT_SYSV
 sysvdir        = /etc/rc.d/init.d
 sysv_SCRIPTS = netatalk
 
-$(sysv_SCRIPTS): rc.atalk.redhat-sysv
-       cp -f rc.atalk.redhat-sysv $(sysv_SCRIPTS)
+$(sysv_SCRIPTS): rc.redhat
+       cp -f rc.redhat $(sysv_SCRIPTS)
        chmod a+x $(sysv_SCRIPTS)
 
 install-data-hook:
@@ -85,26 +74,18 @@ endif
 
 if USE_SYSTEMD
 
-sysvdir        = $(pkglibexecdir)
-sysv_SCRIPTS = netatalk.sh
-
 servicedir     = /lib/systemd/system
 service_DATA   = netatalk.service
 
-$(sysv_SCRIPTS): rc.atalk.systemd
-       cp -f rc.atalk.systemd $(sysv_SCRIPTS)
-       chmod a+x $(sysv_SCRIPTS)
-
-$(service_DATA): service.atalk.systemd
-       cp -f service.atalk.systemd $(service_DATA)
+netatalk.service: service.systemd
+       cp -f service.systemd netatalk.service
 
 install-data-hook:
        -systemctl daemon-reload
 
 uninstall-startup:
        -systemctl disable $(service_DATA)
-       rm -f $(DESTDIR)$(sysvdir)/$(sysv_SCRIPTS)      \
-               $(DESTDIR)$(servicedir)/$(service_DATA)
+       rm -f $(DESTDIR)$(servicedir)/netatalk.service
        -systemctl daemon-reload
 
 endif
@@ -118,8 +99,8 @@ if USE_SUSE_SYSV
 sysvdir        = /etc/init.d
 sysv_SCRIPTS = netatalk
 
-$(sysv_SCRIPTS): rc.atalk.suse-sysv
-       cp -f rc.atalk.suse-sysv $(sysv_SCRIPTS)
+$(sysv_SCRIPTS): rc.suse
+       cp -f rc.suse $(sysv_SCRIPTS)
        chmod a+x $(sysv_SCRIPTS)
 
 install-data-hook:
@@ -131,27 +112,6 @@ uninstall-startup:
 
 endif
 
-#
-# checking for "tru64" style sysv scripts:
-#
-
-if USE_TRU64
-
-sysvdir        = /etc/init.d
-sysv_SCRIPTS = netatalk
-
-$(sysv_SCRIPTS): rc.atalk.tru64
-       cp -f rc.atalk.tru64 $(sysv_SCRIPTS)
-       chmod a+x $(sysv_SCRIPTS)
-
-install-data-hook:
-
-uninstall-hook:
-
-uninstall-startup: uninstall-am
-
-endif
-
 #
 # checking for NetBSD init scripts
 #
@@ -159,25 +119,9 @@ endif
 if USE_NETBSD
 
 sysvdir = /etc/rc.d
-sysv_SCRIPTS = afpd atalkd cnid_metad papd timelord
-
-afpd: rc.afpd.netbsd
-       cp -f $< $@
-       chmod a+x $@
-
-atalkd: rc.atalkd.netbsd
-       cp -f $< $@
-       chmod a+x $@
-
-cnid_metad: rc.cnid_metad.netbsd
-       cp -f $< $@
-       chmod a+x $@
-
-papd: rc.papd.netbsd
-       cp -f $< $@
-       chmod a+x $@
+sysv_SCRIPTS = netatalk
 
-timelord: rc.timelord.netbsd
+netatalk: rc.netbsd
        cp -f $< $@
        chmod a+x $@
 
@@ -195,23 +139,14 @@ endif
 
 if USE_SOLARIS
 
-sysvdir = /etc/init.d
-sysv_SCRIPTS = netatalk
-
-$(sysv_SCRIPTS): rc.atalk.sysv
-       cp -f rc.atalk.sysv $@
-       chmod a+x $@
+servicedir = /lib/svc/manifest/network/
+service_DATA = netatalk.xml
 
 install-data-hook:
-       rm -f $(DESTDIR)/etc/rc2.d/S90$(sysv_SCRIPTS)
-       -ln -s ../init.d/$(sysv_SCRIPTS) $(DESTDIR)/etc/rc2.d/S90$(sysv_SCRIPTS)
-       rm -f $(DESTDIR)/etc/rc0.d/K04$(sysv_SCRIPTS)
-       -ln -s ../init.d/$(sysv_SCRIPTS) $(DESTDIR)/etc/rc0.d/K04$(sysv_SCRIPTS)
+       svccfg import netatalk.xml
 
 uninstall-startup:
-       rm -f $(DESTDIR)$(sysvdir)/$(sysv_SCRIPTS) \
-               $(DESTDIR)/etc/rc2.d/S90$(sysv_SCRIPTS) \
-               $(DESTDIR)/etc/rc0.d/K04$(sysv_SCRIPTS)
+       svccfg delete network/netatalk
 
 endif
 
@@ -224,8 +159,8 @@ if USE_GENTOO
 sysvdir = /etc/init.d
 sysv_SCRIPTS = netatalk
 
-$(sysv_SCRIPTS): rc.atalk.gentoo
-       cp -f rc.atalk.gentoo $(sysv_SCRIPTS)
+$(sysv_SCRIPTS): rc.gentoo
+       cp -f rc.gentoo $(sysv_SCRIPTS)
        chmod a+x $(sysv_SCRIPTS)
 
 install-data-hook:
@@ -246,8 +181,8 @@ if USE_DEBIAN
 sysvdir = /etc/init.d
 sysv_SCRIPTS = netatalk
 
-$(sysv_SCRIPTS): rc.atalk.debian
-       cp -f rc.atalk.debian $(sysv_SCRIPTS)
+$(sysv_SCRIPTS): rc.debian
+       cp -f rc.debian $(sysv_SCRIPTS)
        chmod a+x $(sysv_SCRIPTS)
 
 install-data-hook:
diff --git a/distrib/initscripts/netatalk.xml.tmpl b/distrib/initscripts/netatalk.xml.tmpl
new file mode 100644 (file)
index 0000000..6349e0c
--- /dev/null
@@ -0,0 +1,51 @@
+<?xml version="1.0"?>
+<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
+<service_bundle type="manifest" name="netatalk">
+
+    <service name="network/netatalk" type="service" version="1">
+
+        <create_default_instance enabled="false"/>
+        
+        <single_instance/>
+
+        <dependency name="network" grouping="require_all" restart_on="error" type="service">
+            <service_fmri value="svc:/milestone/network:default"/>
+        </dependency>
+
+        <dependency name="filesystem" grouping="require_all" restart_on="error" type="service">
+            <service_fmri value="svc:/system/filesystem/local"/>
+        </dependency>
+
+        <dependency name="mdns" grouping="optional_all" restart_on="error" type="service">
+            <service_fmri value="svc:/network/dns/multicast"/>
+        </dependency>
+
+        <method_context>
+        </method_context>
+
+        <exec_method type="method" name="start" exec=":SBINDIR:/netatalk" timeout_seconds="60"/>
+
+        <exec_method type="method" name="stop" exec=":kill" timeout_seconds="60"/>
+
+        <property_group name="startd" type="framework">
+            <propval name="duration" type="astring" value="contract"/>
+            <propval name="ignore_error" type="astring" value="core,signal"/>
+        </property_group>
+
+        <property_group name="application" type="application">
+            <propval name="config_file" type="astring" value=":ETCDIR:/afp.conf"/>
+        </property_group>
+        
+        <stability value="Evolving"/>
+
+        <template>
+            <common_name>
+                <loctext xml:lang="C">
+                    Netatalk AFP Server
+                </loctext>
+            </common_name>
+        </template>
+
+    </service>
+
+</service_bundle>
diff --git a/distrib/initscripts/rc.afpd.netbsd.tmpl b/distrib/initscripts/rc.afpd.netbsd.tmpl
deleted file mode 100644 (file)
index 672c2ed..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/sh
-#
-# PROVIDE: afpd
-# REQUIRE: cnid_metad
-# KEYWORD: shutdown
-#
-# Apple Filing Protocol daemon. (netatalk :NETATALK_VERSION:)
-# If you use AppleTalk, Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-#
-
-. /etc/rc.subr
-
-name="afpd"
-rcvar=$name
-command=":SBINDIR:/afpd"
-etcdir=":ETCDIR:"
-pidfile="/var/run/${name}.pid"
-command_args="-P ${pidfile}"
-required_files="$etcdir/afpd.conf $etcdir/AppleVolumes.default $etcdir/AppleVolumes.system"
-
-load_rc_config $name
-run_rc_command "$1"
-
diff --git a/distrib/initscripts/rc.atalk.bsd.tmpl b/distrib/initscripts/rc.atalk.bsd.tmpl
deleted file mode 100755 (executable)
index b3249cc..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/bin/sh
-#
-# Netatalk :NETATALK_VERSION: daemons.
-# If you use AppleTalk, Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-#
-
-#
-# SUNOS: UNCOMMENT THESE LINES TO LOAD THE KERNEL MODULE.  Note that
-# modunload-ing netatalk may cause your machine to panic or hang.
-#
-##echo -n 'loading netatalk: '
-##if [ -f :ETCDIR:/netatalk.o ]; then
-##     /usr/etc/modload -sym :ETCDIR:/netatalk.o;
-##fi
-
-ATALK_NAME=`hostname|sed 's/\..*$//'`
-ATALK_UNIX_CHARSET='LOCALE'
-ATALK_MAC_CHARSET='MAC_ROMAN'
-
-CNID_METAD_RUN=yes
-AFPD_RUN=yes
-AFPD_MAX_CLIENTS=20
-AFPD_UAMLIST="-U uams_dhx.so,uams_dhx2.so"
-AFPD_GUEST=nobody
-CNID_CONFIG="-l log_note"
-
-ATALKD_RUN=no
-PAPD_RUN=no
-TIMELORD_RUN=no
-#A2BOOT_RUN=no
-ATALK_ZONE=
-#ATALK_BGROUND=no
-
-netatalk_conf=":ETCDIR:/netatalk.conf"
-
-[ -f ${netatalk_conf} ] && . ${netatalk_conf}
-
-echo -n 'starting netatalk daemons:'
-if [ X"${ATALKD_RUN}" != X"no" ]; then
-if [ -x :SBINDIR:/atalkd ]; then
-       :SBINDIR:/atalkd;               echo -n ' atalkd'
-fi
-
-if [ -x :BINDIR:/nbprgstr ]; then
-       :BINDIR:/nbprgstr -p 4 ${ATALK_NAME}:Workstation
-       :BINDIR:/nbprgstr -p 4 ${ATALK_NAME}:netatalk
-       echo -n ' nbprgstr'
-fi
-fi
-
-if [ -x :SBINDIR:/papd -a X"${PAPD_RUN}" != X"no" ]; then
-       :SBINDIR:/papd;         echo -n ' papd'
-fi
-
-if [ -x :SBINDIR:/cnid_metad -a X"${CNID_METAD_RUN}" != X"no" ]; then
-       :SBINDIR:/cnid_metad $CNID_CONFIG
-       echo -n ' cnid_metad'
-fi
-
-if [ -x :SBINDIR:/afpd -a X"${AFPD_RUN}" != X"no" ]; then
-       :SBINDIR:/afpd ${AFPD_UAMLIST} -g ${AFPD_GUEST} \
-           -c ${AFPD_MAX_CLIENTS} -n ${ATALK_NAME}${ATALK_ZONE}
-       echo -n ' afpd'
-fi
-
-if [ -x :SBINDIR:/timelord -a X"${TIMELORD_RUN}" != X"no" ]; then
-       :SBINDIR:/timelord;             echo -n ' timelord'
-fi
-
-                                       echo '.'
diff --git a/distrib/initscripts/rc.atalk.debian.tmpl b/distrib/initscripts/rc.atalk.debian.tmpl
deleted file mode 100644 (file)
index f6d1e40..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          netatalk
-# Required-Start:    $remote_fs $syslog
-# Should-Start:      avahi-daemon
-# Required-Stop:     $remote_fs $syslog
-# Default-Start:     2 3 4 5
-# Default-Stop:      1
-### END INIT INFO
-#
-# netatalk      Netatalk :NETATALK_VERSION: initscript
-# Author:       Thomas Kaiser <Thomas.Kaiser@phg-online.de>
-
-set -e
-
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-DESC="Netatalk"
-NAME=netatalk
-SCRIPTNAME=/etc/init.d/$NAME
-
-# Guard to prevent execution if netatalk was removed.
-test -x :SBINDIR:/afpd || exit 0
-
-# Set defaults. Please change these options in /etc/default/netatalk
-ATALK_NAME=`/bin/hostname --short`
-ATALK_UNIX_CHARSET='LOCALE'
-ATALK_MAC_CHARSET='MAC_ROMAN'
-
-CNID_METAD_RUN=yes
-AFPD_RUN=yes
-AFPD_MAX_CLIENTS=50
-AFPD_UAMLIST="-U uams_dhx2.so"
-AFPD_GUEST=nobody
-CNID_CONFIG="-l log_note"
-
-ATALKD_RUN=no
-PAPD_RUN=no
-TIMELORD_RUN=no
-#A2BOOT_RUN=no
-ATALK_ZONE=
-ATALK_BGROUND=no
-
-# old /etc/default/netatalk expected hostname in $HOSTNAME by default
-HOSTNAME=`/bin/hostname`
-
-# Read in netatalk configuration.
-if [ -f /etc/default/netatalk ]; then
-    . /etc/default/netatalk
-fi
-
-# Start Netatalk servers.
-atalk_startup() {
-       if [ x"$ATALKD_RUN" = x"yes" ]; then
-
-       # Try to load the AppleTalk kernel module if it was intended.
-    if grep -q '^appletalk$' /etc/modules; then
-               /sbin/modprobe appletalk || echo "[could not load appletalk module]"
-    fi
-
-       # Start atalkd server.
-       :SBINDIR:/atalkd
-
-       # register workstation
-       :BINDIR:/nbprgstr -p 4 "$ATALK_NAME:Workstation$ATALK_ZONE"
-       :BINDIR:/nbprgstr -p 4 "$ATALK_NAME:netatalk$ATALK_ZONE"
-
-       echo -n " atalkd"
-       fi
-       
-       # prepare startup of file services
-       if [ "x$CNID_METAD_RUN" = "xyes" -a -x :SBINDIR:/cnid_metad ] ; then
-               echo -n " cnid_metad"
-        :SBINDIR:/cnid_metad $CNID_CONFIG
-    fi
-       
-       if [ x"$AFPD_RUN" = x"yes" ]; then
-       :SBINDIR:/afpd $AFPD_UAMLIST -g $AFPD_GUEST -c $AFPD_MAX_CLIENTS \
-               -n "$ATALK_NAME$ATALK_ZONE"
-       echo -n " afpd"
-       fi
-
-    if [ "x$ATALKD_RUN" = "xyes" ]; then
-        if [ "x$PAPD_RUN" = "xyes" ]; then
-            :SBINDIR:/papd
-            echo -n " papd"
-        fi
-
-        if [ x"$TIMELORD_RUN" = x"yes" ]; then
-            :SBINDIR:/timelord
-            echo -n " timelord"
-        fi
-    fi
-}
-
-case "$1" in
-       start)
-               if [ "x$ATALK_BGROUND" = "xyes" -a "x$ATALKD_RUN" = "xyes" ]; then
-                       echo "Starting Netatalk services in the background."
-                       atalk_startup >/dev/null &
-               else
-                       echo -n "Starting Netatalk services (this will take a while): "
-                       atalk_startup
-                       echo "."
-               fi
-       ;;
-
-       stop)
-               echo -n "Stopping Netatalk Daemons:"
-               echo -n " afpd"
-               start-stop-daemon --stop --quiet --oknodo --exec :SBINDIR:/afpd
-
-               echo -n " cnid_metad"
-               start-stop-daemon --stop --quiet --oknodo --exec :SBINDIR:/cnid_metad
-       
-               if test -x :SBINDIR:/papd; then
-                    echo -n " papd"
-                   start-stop-daemon --stop --quiet --oknodo --exec :SBINDIR:/papd
-               fi
-       
-               if test -x :SBINDIR:/timelord; then
-                    echo -n " timelord"
-                   start-stop-daemon --stop --quiet --oknodo --exec :SBINDIR:/timelord
-               fi
-
-               if test -x :SBINDIR:/atalkd; then
-                    echo -n " atalkd"
-                   start-stop-daemon --stop --quiet --oknodo --exec :SBINDIR:/atalkd
-               fi
-       
-               echo "."
-       ;;
-       
-       restart)
-               $0 force-reload
-       ;;
-
-       force-reload)
-               echo -n "Restarting Netatalk Daemons (this will take a while)"
-               $0 stop
-               echo -n "."
-               sleep 2
-               echo -n "."
-               if $0 start; then
-                       echo "done."
-               fi
-       ;;
-  
-       *)
-               echo "Usage: $0 {start|stop|restart|force-reload}" >&2
-               exit 1
-       ;;
-esac
diff --git a/distrib/initscripts/rc.atalk.gentoo.tmpl b/distrib/initscripts/rc.atalk.gentoo.tmpl
deleted file mode 100644 (file)
index 5f0c65f..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/sbin/runscript
-
-# Netatalk :NETATALK_VERSION: daemons.
-# If you use AppleTalk, Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-
-ATALK_NAME=`echo ${HOSTNAME}|cut -d. -f1`
-ATALK_UNIX_CHARSET='LOCALE'
-ATALK_MAC_CHARSET='MAC_ROMAN'
-
-CNID_METAD_RUN=yes
-AFPD_RUN=yes
-AFPD_MAX_CLIENTS=20
-AFPD_UAMLIST="-U uams_dhx.so,uams_dhx2.so"
-AFPD_GUEST=nobody
-CNID_CONFIG="-l log_note"
-
-ATALKD_RUN=no
-PAPD_RUN=no
-TIMELORD_RUN=no
-#A2BOOT_RUN=no
-ATALK_ZONE=
-ATALK_BGROUND=no
-
-depend() {
-       need net
-       use logger dns
-}
-
-atalk_startup () {
-#      . :ETCDIR:/netatalk.conf
-
-       if [ "${ATALKD_RUN}" != "no" ]; then
-               ebegin "Starting atalkd"
-               start-stop-daemon --start --quiet --exec :SBINDIR:/atalkd
-               eend $?
-
-               for reg in \
-                       "${ATALK_NAME}:Workstation${ATALK_ZONE}" \
-                       "${ATALK_NAME}:netatalk${ATALK_ZONE}"
-               do
-                       ebegin "  Registering $reg"
-                       :BINDIR:/nbprgstr "$reg"
-                       eend $?
-               done
-
-               if [ "${PAPD_RUN}" = "yes" ]; then
-                       ebegin "  Starting papd"
-                       start-stop-daemon --start --quiet --exec :SBINDIR:/papd
-                       eend $?
-               fi
-
-       fi
-
-       if [ "${CNID_METAD_RUN}" = "yes" ] ; then
-        ebegin "Starting cnid_metad"
-               start-stop-daemon --start --quiet --exec :SBINDIR:/cnid_metad -- \
-                       ${CNID_CONFIG}
-               eend $?
-       fi
-
-
-       if [ "${AFPD_RUN}" = "yes" ]; then
-               ebegin "Starting afpd"
-               start-stop-daemon --start --quiet --exec :SBINDIR:/afpd -- \
-                       ${AFPD_UAMLIST} -g ${AFPD_GUEST} -c ${AFPD_MAX_CLIENTS} \
-                       -n "${ATALK_NAME}${ATALK_ZONE}"
-               eend $?
-       fi
-
-       if [ "${TIMELORD_RUN}" = "yes" ]; then
-               ebegin "Starting timelord"
-               start-stop-daemon --start --quiet --exec :SBINDIR:/timelord
-               eend $?
-       fi
-}
-
-start () {
-       . :ETCDIR:/netatalk.conf
-
-        if [ x"${ATALK_BGROUND}" = x"yes" -a "${ATALKD_RUN}" != "no" ]; then
-            echo "Starting netatalk in the background ... "
-            atalk_startup >& /dev/null &
-        else
-            atalk_startup
-        fi
-}
-
-stop () {
-       . :ETCDIR:/netatalk.conf
-
-       if [ "${AFPD_RUN}" = "yes" ]; then
-               ebegin "Stopping afpd"
-               start-stop-daemon --stop --quiet --exec :SBINDIR:/afpd
-               eend $?
-       fi
-
-       if [ "${TIMELORD_RUN}" = "yes" ]; then
-               ebegin "Stopping timelord"
-               start-stop-daemon --stop --quiet --exec :SBINDIR:/timelord
-               eend $?
-       fi
-
-       if [ "${ATALKD_RUN}" != "no" ]; then
-               if [ "${PAPD_RUN}" = "yes" ]; then
-                       ebegin "Stopping papd"
-                       start-stop-daemon --stop --quiet --exec :SBINDIR:/papd
-                       eend $?
-               fi
-
-               for reg in \
-                       "${ATALK_NAME}:Workstation${ATALK_ZONE}" \
-                       "${ATALK_NAME}:netatalk${ATALK_ZONE}"
-               do
-                       ebegin "Unregistering $reg"
-                       :BINDIR:/nbpunrgstr "$reg"
-                       eend $?
-               done
-
-               ebegin "Stopping atalkd"
-               start-stop-daemon --stop --quiet --exec :SBINDIR:/atalkd
-               eend $?
-       fi
-
-       if [ "${CNID_METAD_RUN}" = "yes" ] ; then
-               ebegin "Stopping cnid_metad"
-               start-stop-daemon --stop --quiet --exec :SBINDIR:/cnid_metad
-               eend $?
-       fi
-}
diff --git a/distrib/initscripts/rc.atalk.redhat-sysv.tmpl b/distrib/initscripts/rc.atalk.redhat-sysv.tmpl
deleted file mode 100644 (file)
index f066232..0000000
+++ /dev/null
@@ -1,241 +0,0 @@
-#! /bin/sh
-# chkconfig: - 91 35
-# description: This package is an implementation of "AFP over TCP"
-#              and provides printer, file sharing, and routing 
-#              services via legacy AppleTalk networking protocol.
-#
-# Netatalk :NETATALK_VERSION: daemons.
-# If you use AppleTalk, Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-
-ATALK_BIN=:BINDIR:
-ATALK_CONF_DIR=:ETCDIR:
-ATALK_SBIN=:SBINDIR:
-
-# Source function library.
-. /etc/rc.d/init.d/functions
-
-# Source networking configuration.
-. /etc/sysconfig/network
-
-# default
-ATALK_NAME=`echo ${HOSTNAME}|cut -d. -f1`
-ATALK_UNIX_CHARSET='LOCALE'
-ATALK_MAC_CHARSET='MAC_ROMAN'
-
-CNID_METAD_RUN=yes
-AFPD_RUN=yes
-AFPD_MAX_CLIENTS=20
-AFPD_UAMLIST="-U uams_dhx.so,uams_dhx2.so"
-AFPD_GUEST=nobody
-CNID_CONFIG="-l log_note"
-
-ATALKD_RUN=no
-PAPD_RUN=no
-TIMELORD_RUN=no
-A2BOOT_RUN=no
-ATALK_ZONE=
-ATALK_BGROUND=no
-
-# read in netatalk configuration
-if [ -f ${ATALK_CONF_DIR}/netatalk.conf ]; then
-    . ${ATALK_CONF_DIR}/netatalk.conf
-fi
-
-# initialize return values
-RETVAL=1
-RETVAL_ATALKD=0
-RETVAL_PAPD=0
-RETVAL_CNID_METAD=0
-RETVAL_AFPD=0
-
-# startup code for everything
-atalk_startup() {
-    # Check that networking is up.
-    if [ ${NETWORKING} = "no" ]; then
-         echo "[Network isn't started]"; 
-         exit 1;
-    fi
-
-    if [ ! -f ${ATALK_CONF_DIR}/netatalk.conf ]; then
-         echo "[${ATALK_CONF_DIR}/netatalk.conf not found]";
-         exit 6;
-    fi
-
-    if [ x"${ATALKD_RUN}" != x"no" -a -x ${ATALK_SBIN}/atalkd ]; then 
-         # Quickly probe for appletalk and warn if we can't find it
-         #/sbin/modprobe appletalk || echo "[could not load appletalk module]"
-         # Check for IP Encapsulation support
-         #/sbin/modprobe ipddp || echo "[could not load IP encapsulation]"
-       echo -n "  Starting atalkd:"
-       daemon ${ATALK_SBIN}/atalkd
-       RETVAL_ATALKD=$?
-       echo
-
-       if [ -x ${ATALK_BIN}/nbprgstr ]; then   
-           action "  Registering ${ATALK_NAME}:Workstation${ATALK_ZONE}:" ${ATALK_BIN}/nbprgstr -p 4 \"${ATALK_NAME}:Workstation${ATALK_ZONE}\"
-           action "  Registering ${ATALK_NAME}:netatalk${ATALK_ZONE}:" ${ATALK_BIN}/nbprgstr -p 4 \"${ATALK_NAME}:netatalk${ATALK_ZONE}\"
-       fi      
-
-       if [ x"${PAPD_RUN}" = x"yes"  -a -x ${ATALK_SBIN}/papd ]; then
-           echo -n "  Starting papd:"
-           daemon ${ATALK_SBIN}/papd
-           RETVAL_PAPD=$?
-           echo
-       fi
-
-       # check for timelord in bin directory
-       if [ x"${TIMELORD_RUN}" = x"yes"  -a -x ${ATALK_BIN}/timelord ]; then
-           echo -n "  Starting timelord"
-           daemon ${ATALK_BIN}/timelord
-           echo
-       fi
-
-       # check for timelord in sbin directory
-       if [ x"${TIMELORD_RUN}" = x"yes"  -a -x ${ATALK_SBIN}/timelord ]; then
-           echo -n "  Starting timelord"
-           daemon ${ATALK_SBIN}/timelord
-           echo
-       fi
-
-       # check for a2boot in bin directory
-       if [ x"${A2BOOT_RUN}" = x"yes"  -a -x ${ATALK_BIN}/a2boot ]; then
-           echo -n "  Starting a2boot"
-           daemon ${ATALK_BIN}/a2boot
-           echo
-       fi
-
-       # check for a2boot in sbin directory
-       if [ x"${A2BOOT_RUN}" = x"yes"  -a -x ${ATALK_SBIN}/a2boot ]; then
-           echo -n "  Starting a2boot"
-           daemon ${ATALK_SBIN}/a2boot
-           echo
-       fi
-
-    fi
-
-    if [ x"${CNID_METAD_RUN}" = x"yes" -a -x ${ATALK_SBIN}/cnid_metad ] ; then
-           echo -n "  Starting cnid_metad:"
-        daemon ${ATALK_SBIN}/cnid_metad $CNID_CONFIG
-           RETVAL_CNID_METAD=$?
-           echo
-    fi
-
-    if [ x"${AFPD_RUN}" = x"yes" -a -x ${ATALK_SBIN}/afpd ] ; then
-           echo -n "  Starting afpd:"
-           daemon ${ATALK_SBIN}/afpd ${AFPD_UAMLIST} -g ${AFPD_GUEST} \
-               -c ${AFPD_MAX_CLIENTS} -n \"${ATALK_NAME}${ATALK_ZONE}\"
-           RETVAL_AFPD=$?
-           echo
-    fi
-
-    if [ $RETVAL_ATALKD -eq 0 -a $RETVAL_PAPD -eq 0 -a $RETVAL_CNID_METAD -eq 0 -a $RETVAL_AFPD -eq 0 ]; then
-        RETVAL=0
-       touch /var/lock/subsys/atalk || RETVAL=1
-    fi
-}
-
-case "$1" in
-'start')
-       echo -n 'Starting Netatalk services: '
-       if [ x"${ATALK_BGROUND}" = x"yes" -a x"${ATALKD_RUN}" != x"no" ]; then 
-           echo -n "(backgrounded)"
-           atalk_startup >& /dev/null &
-       else
-           echo
-           atalk_startup
-       fi
-       echo 
-       ;;
-'stop')
-       echo 'Shutting down Netatalk services: '
-       if [ x"${ATALKD_RUN}" != x"no" ]; then
-           if [ x"${PAPD_RUN}" = x"yes" -a -x ${ATALK_SBIN}/papd ]; then
-               echo -n "  Stopping papd:"
-               killproc papd
-               RETVAL_PAPD=$?
-               echo
-           fi
-
-            # checking for timelord in bin directory
-           if [ x"${TIMELORD_RUN}" = x"yes" -a -x ${ATALK_BIN}/timelord ]; then
-               echo -n "  Stopping timelord:"
-               killproc timelord
-               echo
-           fi
-
-            # checking for timelord in sbin directory
-           if [ x"${TIMELORD_RUN}" = x"yes" -a -x ${ATALK_SBIN}/timelord ]; then
-               echo -n "  Stopping timelord:"
-               killproc timelord
-               echo
-           fi
-
-            # checking for a2boot in bin directory
-           if [ x"${A2BOOT_RUN}" = x"yes" -a -x ${ATALK_BIN}/a2boot ]; then
-               echo -n "  Stopping a2boot:"
-               killproc a2boot
-               echo
-           fi
-
-            # checking for a2boot in sbin directory
-           if [ x"${A2BOOT_RUN}" = x"yes" -a -x ${ATALK_SBIN}/a2boot ]; then
-               echo -n "  Stopping a2boot:"
-               killproc a2boot
-               echo
-           fi
-
-           action "  Unregistering ${ATALK_NAME}:Workstation${ATALK_ZONE}:" ${ATALK_BIN}/nbpunrgstr \"${ATALK_NAME}:Workstation${ATALK_ZONE}\"
-           action "  Unregistering ${ATALK_NAME}:netatalk${ATALK_ZONE}:" ${ATALK_BIN}/nbpunrgstr \"${ATALK_NAME}:netatalk${ATALK_ZONE}\"
-
-           # kill atalkd last, since without it the plumbing goes away.
-           if [ -x ${ATALK_SBIN}/atalkd ]; then
-               echo -n "  Stopping atalk:"
-               killproc atalkd
-               RETVAL_ATALKD=$?
-               echo
-           fi
-       fi
-
-       # kill this separately as we also do AFP/tcp
-       if [ x"${AFPD_RUN}" = x"yes" -a -x ${ATALK_SBIN}/afpd ]; then
-           echo -n "  Stopping afpd:"
-           killproc afpd
-           RETVAL_AFPD=$?
-           echo
-       fi
-
-       if [ x"${CNID_METAD_RUN}" = x"yes" -a -x ${ATALK_SBIN}/cnid_metad ]; then
-           echo -n "  Stopping cnid_metad:"
-           killproc cnid_metad
-           RETVAL_CNID_METAD=$?
-           echo
-       fi
-
-       if [ $RETVAL_ATALKD -eq 0 -a $RETVAL_PAPD -eq 0 -a $RETVAL_AFPD -eq 0 ] ; then
-           RETVAL=0
-           rm -f /var/lock/subsys/atalk || RETVAL=1
-       fi
-       echo ""
-       ;;
-  'restart'|'reload')
-       $0 stop
-       $0 start
-       RETVAL=$?
-       ;;
-  'status')
-       status atalkd
-       status papd
-       status timelord
-       status a2boot
-       status cnid_metad
-       status afpd
-       RETVAL=$?
-       ;;
-  *)
-       echo "Usage: $0 {start|stop|restart|reload|status}"
-       exit 2
-esac
-
-exit $RETVAL
diff --git a/distrib/initscripts/rc.atalk.suse-sysv.tmpl b/distrib/initscripts/rc.atalk.suse-sysv.tmpl
deleted file mode 100755 (executable)
index e06d0a0..0000000
+++ /dev/null
@@ -1,159 +0,0 @@
-#! /bin/sh
-# Copyright (c) 1996-2001 SuSE GmbH Nuernberg, Germany.  All rights reserved.
-#
-# Author: 
-#      Reinhold Sojer, <reinhold@suse.de>
-#      Olaf Hering, <olh@suse.de>
-# 
-### BEGIN INIT INFO
-# Provides:       netatalk
-# Required-Start: $local_fs
-# Required-Stop: $local_fs
-# Should-Start:  $network $named $remote_fs $syslog slpd avahi-daemon
-# Should-Stop:   $remote_fs $network $syslog
-# Default-Start:  3 5
-# Default-Stop:
-# Description:    AFP over TCP and legacy AppleTalk daemons
-### END INIT INFO
-
-# Netatalk :NETATALK_VERSION:
-
-ATALK_NAME=`hostname|sed 's/\..*$//'`
-ATALK_UNIX_CHARSET='LOCALE'
-ATALK_MAC_CHARSET='MAC_ROMAN'
-
-CNID_METAD_RUN=yes
-AFPD_RUN=yes
-AFPD_MAX_CLIENTS=20
-AFPD_UAMLIST="-U uams_dhx.so,uams_dhx2.so"
-AFPD_GUEST=nobody
-CNID_CONFIG="-l log_note"
-
-ATALKD_RUN=no
-PAPD_RUN=no
-TIMELORD_RUN=no
-#A2BOOT_RUN=no
-ATALK_ZONE=
-ATALK_BGROUND=no
-
-. /etc/rc.status
-. :ETCDIR:/netatalk.conf
-
-# startup code for everything
-atalk_startup() {
-    if [ x"${ATALKD_RUN}" != x"no" ]; then 
-       echo -n "  Starting atalkd ... "
-       :SBINDIR:/atalkd ; my_ec=$?
-
-       if [ -x :BINDIR:/nbprgstr -a "$my_ec" = "0" ]; then     
-           echo -n ".. "
-           :BINDIR:/nbprgstr -p 4 ${ATALK_NAME}:Workstation
-           echo -n ". "
-           :BINDIR:/nbprgstr -p 4 ${ATALK_NAME}:netatalk
-       fi      
-       if [ "$my_ec" != "0" ] ; then false ; fi
-       rc_status -v
-       
-       rc_reset
-
-       if [ x"${PAPD_RUN}" = x"yes"  -a -x :SBINDIR:/papd ]; then
-           echo -n "  Starting papd"
-           :SBINDIR:/papd
-           rc_status -v
-       fi
-
-       rc_reset
-
-       if [ x"${TIMELORD_RUN}" = x"yes"  -a -x :SBINDIR:/timelord ]; then
-           echo -n "  Starting timelord"
-           :SBINDIR:/timelord
-           rc_status -v
-       fi
-
-       rc_reset
-
-    fi
-
-    if [ x"${CNID_METAD_RUN}" = x"yes" -a -x :SBINDIR:/cnid_metad ] ; then
-           echo -n "  Starting cnid_metad "
-           startproc :SBINDIR:/cnid_metad ${CNID_CONFIG}
-           rc_status -v
-    fi
-
-    if [ x"${AFPD_RUN}" = x"yes" -a -x :SBINDIR:/afpd ] ; then
-           echo -n "  Starting afpd ("
-           echo -n ${AFPD_UAMLIST} -g ${AFPD_GUEST} \
-               -c ${AFPD_MAX_CLIENTS} -n ${ATALK_NAME}${ATALK_ZONE}
-           echo -n ")"
-           startproc :SBINDIR:/afpd ${AFPD_UAMLIST} -g ${AFPD_GUEST} \
-               ${AFPD_OPTIONS} \
-               -c ${AFPD_MAX_CLIENTS} -n "${ATALK_NAME}${ATALK_ZONE}"
-           rc_status -v
-    fi
-
-       touch /var/lock/subsys/atalk 
-}
-
-case "$1" in
-    start)
-       if test ! -z "$UID" -a "$UID" != 0 ; then
-               echo "you have to be root to start netatalk daemons"
-               rc_failed
-       else
-       if [ x"${ATALK_BGROUND}" = x"yes" -a x"${ATALKD_RUN}" != x"no" ]; then 
-           echo -n "Starting netatalk in the background ..."
-           atalk_startup >& /dev/null &
-           rc_status -v
-       else
-           echo "Starting netatalk (this may take a while) ..."
-           atalk_startup
-       fi
-       fi
-       ;;
-    stop)
-       echo -n "Shutting down netatalk"
-       if test -x :SBINDIR:/papd ; then
-           killproc -TERM :SBINDIR:/papd
-       fi
-       if test -x :SBINDIR:/timelord ; then
-           killproc -TERM :SBINDIR:/timelord
-       fi
-       if test -x :SBINDIR:/atalkd ; then
-           killproc -TERM :SBINDIR:/atalkd
-       fi
-       killproc -TERM :SBINDIR:/cnid_metad
-       killproc -TERM :SBINDIR:/afpd
-
-       rc_status -v
-       ;;
-    restart|reload|force-reload)
-       $0 stop
-       $0 start
-       rc_status
-       ;;
-    status)
-       echo "Checking for netatalk services"
-       if [ x"${ATALKD_RUN}" = x"yes" -a -x :SBINDIR:/atalkd ] ; then
-           checkproc :SBINDIR:/atalkd && echo -n "atalkd: OK   " || echo -n "atalkd: No process        "
-       fi
-       if [ x"${PAPD_RUN}" = x"yes" -a -x :SBINDIR:/papd ] ; then
-           checkproc :SBINDIR:/papd && echo -n "papd: OK       " || echo -n "papd: No process  "
-       fi
-       if [ x"${TIMELORD_RUN}" = x"yes" -a -x :SBINDIR:/timelord ] ; then
-           checkproc :SBINDIR:/timelord && echo -n   " timelord: OK    " || echo -n " timelord: No process     "
-       fi
-       if [ x"${CNID_METAD_RUN}" = x"yes" ] ; then
-           checkproc :SBINDIR:/cnid_metad && echo -n " cnid_metad: OK  " || echo -n " cnid_metad: No process   "
-       fi
-       checkproc :SBINDIR:/afpd && echo "afpd: OK" || echo "afpd: No process"
-       # assume that afpd is the "main" process ...
-       checkproc :SBINDIR:/afpd
-       rc_status -v
-       ;;
-    *)
-       echo "Usage: $0 {start|stop|restart|status}"
-       exit 1
-       ;;
-esac
-
-rc_exit
diff --git a/distrib/initscripts/rc.atalk.systemd.tmpl b/distrib/initscripts/rc.atalk.systemd.tmpl
deleted file mode 100644 (file)
index e0bd7fb..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/bin/sh
-
-# Netatalk :NETATALK_VERSION: startup script for systemd.
-
-# The method of using this script is not suitable.
-# This script will be deleted in the future.
-
-ATALK_BIN=:BINDIR:
-ATALK_CONF_DIR=:ETCDIR:
-ATALK_SBIN=:SBINDIR:
-
-# default
-ATALK_NAME=`echo ${HOSTNAME}|cut -d. -f1`
-ATALK_UNIX_CHARSET='LOCALE'
-ATALK_MAC_CHARSET='MAC_ROMAN'
-
-CNID_METAD_RUN=yes
-AFPD_RUN=yes
-AFPD_MAX_CLIENTS=20
-AFPD_UAMLIST="-U uams_dhx.so,uams_dhx2.so"
-AFPD_GUEST=nobody
-CNID_CONFIG="-l log_note"
-
-ATALKD_RUN=no
-PAPD_RUN=no
-TIMELORD_RUN=no
-A2BOOT_RUN=no
-ATALK_ZONE=
-ATALK_BGROUND=no
-
-# read in netatalk configuration
-if [ -f ${ATALK_CONF_DIR}/netatalk.conf ]; then
-    . ${ATALK_CONF_DIR}/netatalk.conf
-fi
-
-netatalk_startup() {
-    if [ x"${ATALKD_RUN}" != x"no" -a -x ${ATALK_SBIN}/atalkd ]; then
-       ${ATALK_SBIN}/atalkd
-       
-       if [ -x ${ATALK_BIN}/nbprgstr ]; then
-           ${ATALK_BIN}/nbprgstr -p 4 ${ATALK_NAME}:Workstation${ATALK_ZONE}
-           ${ATALK_BIN}/nbprgstr -p 4 ${ATALK_NAME}:netatalk${ATALK_ZONE}
-       fi      
-       
-       if [ x"${PAPD_RUN}" = x"yes"  -a -x ${ATALK_SBIN}/papd ]; then
-           ${ATALK_SBIN}/papd
-       fi
-       
-       # check for timelord in bin directory
-       if [ x"${TIMELORD_RUN}" = x"yes"  -a -x ${ATALK_BIN}/timelord ]; then
-           ${ATALK_BIN}/timelord
-       fi
-       
-       # check for timelord in sbin directory
-       if [ x"${TIMELORD_RUN}" = x"yes"  -a -x ${ATALK_SBIN}/timelord ]; then
-           ${ATALK_SBIN}/timelord
-       fi
-       
-       # check for a2boot in bin directory
-       if [ x"${A2BOOT_RUN}" = x"yes"  -a -x ${ATALK_BIN}/a2boot ]; then
-           ${ATALK_BIN}/a2boot
-       fi
-       
-       # check for a2boot in sbin directory
-       if [ x"${A2BOOT_RUN}" = x"yes"  -a -x ${ATALK_SBIN}/a2boot ]; then
-           ${ATALK_SBIN}/a2boot
-       fi
-    fi
-    
-    if [ x"${CNID_METAD_RUN}" = x"yes" -a -x ${ATALK_SBIN}/cnid_metad ]; then
-       ${ATALK_SBIN}/cnid_metad $CNID_CONFIG
-    fi
-    
-    if [ x"${AFPD_RUN}" = x"yes" -a -x ${ATALK_SBIN}/afpd ]; then
-       ${ATALK_SBIN}/afpd ${AFPD_UAMLIST} -g ${AFPD_GUEST} \
-            -c ${AFPD_MAX_CLIENTS} -n ${ATALK_NAME}${ATALK_ZONE}
-    fi
-}
-
-if [ x"${ATALK_BGROUND}" = x"yes" -a x"${ATALKD_RUN}" != x"no" ]; then 
-    netatalk_startup >& /dev/null &
-else
-    netatalk_startup
-fi
diff --git a/distrib/initscripts/rc.atalk.sysv.tmpl b/distrib/initscripts/rc.atalk.sysv.tmpl
deleted file mode 100755 (executable)
index ddad742..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-#! /bin/sh
-#
-# Start/stop the Netatalk :NETATALK_VERSION: daemons.
-#
-# If you use AppleTalk, Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-#
-
-#
-# kill the named process(es)
-#
-killproc() {
-       pid=`/usr/bin/ps -e |
-            /usr/bin/grep $1 |
-            /usr/bin/sed -e 's/^  *//' -e 's/ .*//'`
-       [ "$pid" != "" ] && kill $pid
-}
-
-# default
-ATALK_NAME=`hostname|cut -d. -f1`
-ATALK_UNIX_CHARSET='LOCALE'
-ATALK_MAC_CHARSET='MAC_ROMAN'
-
-CNID_METAD_RUN=yes
-AFPD_RUN=yes
-AFPD_MAX_CLIENTS=20
-AFPD_UAMLIST="-U uams_dhx.so,uams_dhx2.so"
-AFPD_GUEST=nobody
-CNID_CONFIG="-l log_note"
-
-ATALKD_RUN=no
-PAPD_RUN=no
-TIMELORD_RUN=no
-#A2BOOT_RUN=no
-ATALK_ZONE=
-ATALK_BGROUND=no
-
-# old netatalk.conf expected hostname in $HOSTNAME by default
-HOSTNAME=`hostname`
-
-. :ETCDIR:/netatalk.conf
-
-
-#
-# Start the netatalk server processes.
-#
-
-atalk_startup() {
-       echo 'starting netatalk daemons: \c'
-       if [ x"${ATALKD_RUN}" != x"no" ]; then
-               if [ -x :SBINDIR:/atalkd ]; then
-                       :SBINDIR:/atalkd;               echo ' atalkd\c'
-               fi
-
-               if [ -x :BINDIR:/nbprgstr ]; then
-                       :BINDIR:/nbprgstr -p 4 "${ATALK_NAME}:Workstation${ATALK_ZONE}";
-                       :BINDIR:/nbprgstr -p 4 "${ATALK_NAME}:netatalk${ATALK_ZONE}";
-                                                       echo ' nbprgstr\c'
-               fi
-
-               if [ x"${PAPD_RUN}" = x"yes"  -a -x :SBINDIR:/papd ]; then
-                       :SBINDIR:/papd;                 echo ' papd\c'
-               fi
-
-               if [ x"${TIMELORD_RUN}" = x"yes"  -a -x :SBINDIR:/timelord ]; then
-                       :SBINDIR:/timelord;             echo ' timelord\c'
-               fi
-       fi
-
-       if [ x"${CNID_METAD_RUN}" = x"yes" -a -x :SBINDIR:/cnid_metad ]; then
-        :SBINDIR:/cnid_metad $CNID_CONFIG
-        echo ' cnid_metad\c'
-       fi
-
-       if [  x"${AFPD_RUN}" = x"yes" -a -x :SBINDIR:/afpd ]; then
-               :SBINDIR:/afpd  ${AFPD_UAMLIST} -g ${AFPD_GUEST} \
-               -c ${AFPD_MAX_CLIENTS} -n "${ATALK_NAME}${ATALK_ZONE}"; echo ' afpd\c'
-       fi
-
-       echo '.'
-}
-
-
-case "$1" in
-
-'start')
-        if [ x"${ATALK_BGROUND}" = x"yes" -a x"${ATALKD_RUN}" != x"no" ]; then
-            echo "Starting netatalk in the background ... "
-            atalk_startup > /dev/null &
-        else
-            atalk_startup
-        fi
-        ;;
-
-#
-# Stop the netatalk server processes.
-#
-'stop')
-
-       echo 'stopping netatalk daemons:\c'
-
-       if [ -x :SBINDIR:/papd ]; then
-               killproc papd;                  echo ' papd\c'
-       fi
-
-       if [ -x :SBINDIR:/afpd ]; then
-               killproc afpd;                  echo ' afpd\c'
-       fi
-
-       if [ -x :SBINDIR:/cnid_metad ]; then
-               killproc cnid_met;              echo ' cnid_metad\c'
-       fi
-
-       if [ -x :SBINDIR:/timelord ]; then
-               killproc timelord;              echo ' timelord\c'
-       fi
-
-       # kill atalkd last, since without it the plumbing goes away.
-       if [ -x :SBINDIR:/atalkd ]; then
-               killproc atalkd;                echo ' atalkd\c'
-       fi
-
-       echo '.'
-       ;;
-
-#
-# Usage statement.
-#
-
-*)
-       echo "usage: $0 {start|stop}"
-       exit 1
-       ;;
-esac
diff --git a/distrib/initscripts/rc.atalk.tru64.tmpl b/distrib/initscripts/rc.atalk.tru64.tmpl
deleted file mode 100755 (executable)
index 0c350af..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-#! /bin/sh
-#
-# Start/stop the Netatalk :NETATALK_VERSION: daemons.
-#
-# If you use AppleTalk, Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-#
-
-ATALK_BIN=:BINDIR:
-ATALK_CONF_DIR=:ETCDIR:
-ATALK_SBIN=:SBINDIR:
-
-ATALK_START_ATALKD=0
-ATALK_START_NBPRGSTR=0
-ATALK_START_PAPD=0
-ATALK_START_CNID_METAD=1
-ATALK_START_AFPD=1
-ATALK_START_TIMELORD=0
-
-#
-# kill the named process(es)
-#
-killproc() {
-       pid=`/usr/bin/ps -e |
-            /usr/bin/grep $1 |
-            /usr/bin/grep -v grep |
-            /usr/bin/sed -e 's/^  *//' -e 's/ .*//'`
-       [ "$pid" != "" ] && kill $pid
-}
-
-case "$1" in
-
-#
-# Start the netatalk server processes.
-#
-
-'start')
-
-       echo 'starting netatalk daemons: \c'
-       if [ ${ATALK_START_ATALKD} -eq 1 -a -x ${ATALK_SBIN}/atalkd ]; then
-               ${ATALK_SBIN}/atalkd;           echo ' atalkd\c'
-       fi
-
-       if [ ${ATALK_START_NBPRGSTR} -eq 1 -a -x ${ATALK_BIN}/nbprgstr ]; then
-               ${ATALK_BIN}/nbprgstr -p 4 `hostname|sed 's/\..*$//'`:Workstation
-               ${ATALK_BIN}/nbprgstr -p 4 `hostname|sed 's/\..*$//'`:netatalk
-                                               echo ' nbprgstr\c'
-       fi
-
-       if [ ${ATALK_START_PAPD} -eq 1 -a -x ${ATALK_SBIN}/papd ]; then
-               ${ATALK_SBIN}/papd;                     echo ' papd\c'
-       fi
-
-       if [ ${ATALK_START_CNID_METAD} -eq 1 -a -x ${ATALK_SBIN}/cnid_metad ]; then
-               ${ATALK_SBIN}/cnid_metad;                       echo ' cnid_metad\c'
-       fi
-
-       if [ ${ATALK_START_AFPD} -eq 1 -a -x ${ATALK_SBIN}/afpd ]; then
-               ${ATALK_SBIN}/afpd;                     echo ' afpd\c'
-       fi
-
-       if [ ${ATALK_START_TIMELORD} -eq 1 -a -x ${ATALK_SBIN}/timelord ]; then
-               ${ATALK_SBIN}/timelord;         echo ' timelord\c'
-       fi
-
-       echo '.'
-
-       ;;
-
-#
-# Stop the netatalk server processes.
-#
-
-'stop')
-
-       echo 'stopping netatalk daemons:\c'
-
-       if [ -x ${ATALK_SBIN}/papd ]; then
-               killproc papd;                  echo ' papd\c'
-       fi
-
-       if [ -x ${ATALK_SBIN}/afpd ]; then
-               killproc afpd;                  echo ' afpd\c'
-       fi
-
-       if [ -x ${ATALK_SBIN}/cnid_metad ]; then
-               killproc cnid_metad;                    echo ' cnid_metad\c'
-       fi
-
-       if [ -x ${ATALK_SBIN}/timelord ]; then
-               killproc timelord;              echo ' timelord\c'
-       fi
-
-       # kill atalkd last, since without it the plumbing goes away.
-       if [ -x ${ATALK_SBIN}/atalkd ]; then
-               killproc atalkd;                echo ' atalkd\c'
-       fi
-
-       echo '.'
-       ;;
-
-#
-# Usage statement.
-#
-
-*)
-       echo "usage: $0 {start|stop}"
-       exit 1
-       ;;
-esac
diff --git a/distrib/initscripts/rc.atalkd.netbsd.tmpl b/distrib/initscripts/rc.atalkd.netbsd.tmpl
deleted file mode 100644 (file)
index d531204..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/bin/sh
-#
-# PROVIDE: atalkd
-# REQUIRE: DAEMON
-#
-# AppleTalk daemon. (netatalk :NETATALK_VERSION:)
-# If you use AppleTalk, Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-#
-
-. /etc/rc.subr
-
-name="atalkd"
-rcvar=$name
-command=":SBINDIR:/atalkd"
-pidfile="/var/run/${name}.pid"
-register=":BINDIR:/nbprgstr"
-myhostname=`hostname|sed 's/\..*$//'`
-required_files=":ETCDIR:/atalkd.conf $register"
-
-start_cmd="atalkd_start"
-
-atalkd_start()
-{
-       if [ -x $command ]; then
-               echo 'Starting atalkd.'
-               $command $command_args
-       fi
-
-       if [ -x $register ]; then
-               echo 'Setting AppleTalk info with nbprgstr.'
-               $register -p 4 $myhostname:Workstation
-               $register -p 4 $myhostname:netatalk
-       fi
-}
-
-load_rc_config $name
-run_rc_command "$1"
-
diff --git a/distrib/initscripts/rc.bsd.tmpl b/distrib/initscripts/rc.bsd.tmpl
new file mode 100644 (file)
index 0000000..fd00a7b
--- /dev/null
@@ -0,0 +1,13 @@
+#!/bin/sh
+#
+# Netatalk :NETATALK_VERSION: daemons.
+#
+
+echo -n 'starting netatalk daemons:'
+
+if [ -x :SBINDIR:/netatalk ]; then
+    :SBINDIR:/netatalk
+    echo -n ' netatalk'
+fi
+
+echo '.'
diff --git a/distrib/initscripts/rc.cnid_metad.netbsd.tmpl b/distrib/initscripts/rc.cnid_metad.netbsd.tmpl
deleted file mode 100644 (file)
index caeba08..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/bin/sh
-#
-# PROVIDE: cnid_metad
-#
-# Start cnid_dbd daemons on request.  (netatalk :NETATALK_VERSION:)
-# The cnid_dbd is an implementation for accessing to CNID databases
-# through a dedicated daemon process.
-#
-
-. /etc/rc.subr
-
-name="cnid_metad"
-rcvar=$name
-command=":SBINDIR:/cnid_metad"
-etcdir=":ETCDIR:"
-
-load_rc_config $name
-run_rc_command "$1"
-
diff --git a/distrib/initscripts/rc.debian.tmpl b/distrib/initscripts/rc.debian.tmpl
new file mode 100644 (file)
index 0000000..a0eb758
--- /dev/null
@@ -0,0 +1,67 @@
+#!/bin/sh
+### BEGIN INIT INFO
+# Provides:          netatalk
+# Required-Start:    $remote_fs $syslog
+# Should-Start:      avahi-daemon
+# Required-Stop:     $remote_fs $syslog
+# Default-Start:     2 3 4 5
+# Default-Stop:      1
+### END INIT INFO
+#
+# netatalk      Netatalk :NETATALK_VERSION: initscript
+#
+
+set -e
+
+PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
+DESC="Netatalk"
+NAME=netatalk
+SCRIPTNAME=/etc/init.d/$NAME
+
+# Guard to prevent execution if netatalk was removed.
+test -x :SBINDIR:/netatalk || exit 0
+
+# Start Netatalk servers.
+netatalk_startup() {
+    if [ -x :SBINDIR:/netatalk ] ; then
+        :SBINDIR:/netatalk
+        echo -n " netatalk"
+    fi
+    
+}
+
+case "$1" in
+    start)
+        echo -n "Starting Netatalk services: "
+        netatalk_startup
+        echo "."
+        ;;
+    
+    stop)
+        echo -n "Stopping Netatalk Daemons:"
+        echo -n " netatalk"
+        start-stop-daemon --stop --quiet --oknodo --exec :SBINDIR:/netatalk
+        
+        echo "."
+        ;;
+    
+    restart)
+        $0 force-reload
+        ;;
+    
+    force-reload)
+        echo -n "Restarting Netatalk Daemons"
+        $0 stop
+        echo -n "."
+        sleep 2
+        echo -n "."
+        if $0 start; then
+            echo "done."
+        fi
+        ;;
+    
+    *)
+        echo "Usage: $0 {start|stop|restart|force-reload}" >&2
+        exit 1
+        ;;
+esac
diff --git a/distrib/initscripts/rc.gentoo.tmpl b/distrib/initscripts/rc.gentoo.tmpl
new file mode 100644 (file)
index 0000000..c66e1e9
--- /dev/null
@@ -0,0 +1,24 @@
+#!/sbin/runscript
+
+# Netatalk :NETATALK_VERSION: daemons.
+
+depend() {
+    need net
+    use logger dns
+}
+
+netatalk_startup () {
+    ebegin "Starting netatalk"
+    start-stop-daemon --start --quiet --exec :SBINDIR:/netatalk
+    eend $?
+}
+
+start () {
+    netatalk_startup
+}
+
+stop () {
+    ebegin "Stopping netatalk"
+    start-stop-daemon --stop --quiet --exec :SBINDIR:/netatalk
+    eend $?
+}
diff --git a/distrib/initscripts/rc.netbsd.tmpl b/distrib/initscripts/rc.netbsd.tmpl
new file mode 100644 (file)
index 0000000..1f84c43
--- /dev/null
@@ -0,0 +1,19 @@
+#!/bin/sh
+#
+# PROVIDE: netatalk
+# KEYWORD: shutdown
+#
+# AFP fileserver for Macintosh clients (netatalk :NETATALK_VERSION:)
+#
+
+. /etc/rc.subr
+
+name="netatalk"
+rcvar=$name
+command=":SBINDIR:/netatalk"
+etcdir=":ETCDIR:"
+pidfile="/var/run/${name}.pid"
+required_files="$etcdir/afp.conf
+
+load_rc_config $name
+run_rc_command "$1"
diff --git a/distrib/initscripts/rc.papd.netbsd.tmpl b/distrib/initscripts/rc.papd.netbsd.tmpl
deleted file mode 100644 (file)
index f32cb7c..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/bin/sh
-#
-# PROVIDE: papd
-# REQUIRE: atalkd
-#
-# AppleTalk print server daemon.  (netatalk :NETATALK_VERSION:)
-# Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-#
-
-. /etc/rc.subr
-
-name="papd"
-rcvar=$name
-command=":SBINDIR:/papd"
-pidfile="/var/run/${name}.pid"
-required_files=":ETCDIR:/papd.conf"
-
-load_rc_config $name
-run_rc_command "$1"
-
diff --git a/distrib/initscripts/rc.redhat.tmpl b/distrib/initscripts/rc.redhat.tmpl
new file mode 100644 (file)
index 0000000..643448a
--- /dev/null
@@ -0,0 +1,88 @@
+#! /bin/sh
+# chkconfig: - 91 35
+# description: Netatalk AFP fileserver for Macintosh clients
+#
+# Netatalk :NETATALK_VERSION:
+
+NETATALK_CONF_DIR=:ETCDIR:
+NETATALK_SBIN=:SBINDIR:
+prog=netatalk
+
+# Source function library.
+. /etc/rc.d/init.d/functions
+
+# Source networking configuration.
+. /etc/sysconfig/network
+
+# initialize return values
+RETVAL=1
+
+# startup code for everything
+netatalk_startup() {
+    # Check that networking is up.
+    if [ ${NETWORKING} = "no" ]; then
+        echo "[Network isn't started]"; 
+        exit 1;
+    fi
+
+    if [ -x ${NETATALK_SBIN}/netatalk ] ; then
+        echo -n $"Starting $prog: "
+        daemon ${NETATALK_SBIN}/netatalk
+        RETVAL=$?
+        echo
+    fi
+
+    if [ $RETVAL -eq 0 ]; then
+        touch /var/lock/subsys/netatalk || RETVAL=1
+    fi
+}
+
+# stop code for everything
+netatalk_stop() {
+    if [ -x ${NETATALK_SBIN}/netatalk ]; then
+        echo -n $"Stopping $prog: "
+        killproc netatalk
+        RETVAL=$?
+        echo
+    fi
+
+    if [ $RETVAL -eq 0 ] ; then
+        rm -f /var/lock/subsys/netatalk || RETVAL=1
+    fi
+}
+
+# code to cause apfd and cnid_metad to restart
+netatalk_graceful() {
+    if [ -x ${NETATALK_SBIN}/netatalk ]; then
+        echo -n $"Restarting cnid_metad and afpd: "
+        killproc  netatalk -QUIT
+        RETVAL=$?
+        echo
+    fi
+}
+
+case "$1" in
+    'start')
+        netatalk_startup
+        ;;
+    'stop')
+        netatalk_stop
+        ;;
+    'restart'|'reload')
+        $0 stop
+        $0 start
+        RETVAL=$?
+        ;;
+    'status')
+        status netatalk
+        RETVAL=$?
+        ;;
+    'graceful')
+        netatalk_graceful
+        ;;
+    *)
+        echo "Usage: $0 {start|stop|restart|reload|status|graceful}"
+        exit 2
+esac
+
+exit $RETVAL
diff --git a/distrib/initscripts/rc.solaris.tmpl b/distrib/initscripts/rc.solaris.tmpl
new file mode 100644 (file)
index 0000000..5b244da
--- /dev/null
@@ -0,0 +1,60 @@
+#! /bin/sh
+#
+# Start/stop the Netatalk :NETATALK_VERSION: daemons.
+#
+
+#
+# kill the named process(es)
+#
+killproc() {
+    pid=`/usr/bin/ps -e |
+    /usr/bin/grep $1 |
+    /usr/bin/sed -e 's/^  *//' -e 's/ .*//'`
+    [ "$pid" != "" ] && kill $pid
+}
+
+#
+# Start the netatalk server processes.
+#
+
+netatalk_startup() {
+    echo 'starting netatalk daemons: \c'
+
+    if [ -x :SBINDIR:/netatalk ]; then
+        :SBINDIR:/netatalk 
+        echo ' netatalk\c'
+    fi
+
+    echo '.'
+}
+
+
+case "$1" in
+
+    'start')
+            netatalk_startup
+        ;;
+
+#
+# Stop the netatalk server processes.
+#
+    'stop')
+
+        echo 'stopping netatalk daemons:\c'
+
+        if [ -x :SBINDIR:/netatalk ]; then
+            killproc netatalk;                      echo ' netatalk\c'
+        fi
+
+        echo '.'
+        ;;
+
+#
+# Usage statement.
+#
+
+    *)
+        echo "usage: $0 {start|stop}"
+        exit 1
+        ;;
+esac
diff --git a/distrib/initscripts/rc.suse.tmpl b/distrib/initscripts/rc.suse.tmpl
new file mode 100644 (file)
index 0000000..26e019e
--- /dev/null
@@ -0,0 +1,60 @@
+#! /bin/sh
+### BEGIN INIT INFO
+# Provides:       netatalk
+# Required-Start: $local_fs
+# Required-Stop: $local_fs
+# Should-Start:  $network $named $remote_fs $syslog avahi-daemon
+# Should-Stop:   $remote_fs $network $syslog
+# Default-Start:  3 5
+# Default-Stop:
+# Description:    Netatalk AFP fileserver for Macintosh clients
+### END INIT INFO
+
+# Netatalk :NETATALK_VERSION:
+
+. /etc/rc.status
+
+# startup code for everything
+netatalk_startup() {
+    if [ -x :SBINDIR:/netatalk ] ; then
+        echo -n "  Starting netatalk "
+        startproc :SBINDIR:/netatalk
+        rc_status -v
+    fi
+
+    touch /var/lock/subsys/netatalk 
+}
+
+case "$1" in
+    start)
+        if test ! -z "$UID" -a "$UID" != 0 ; then
+            echo "you have to be root to start netatalk daemons"
+            rc_failed
+        else
+            echo "Starting netatalk..."
+            netatalk_startup
+        fi
+        ;;
+    stop)
+        echo -n "Shutting down netatalk"
+        killproc -TERM :SBINDIR:/netatalk
+        rc_status -v
+        ;;
+    restart|reload|force-reload)
+        $0 stop
+        $0 start
+        rc_status
+        ;;
+    status)
+        echo "Checking for netatalk services"
+        checkproc :SBINDIR:/netatalk && echo "netatalk: OK" || echo "netatalk: No process"
+        checkproc :SBINDIR:/netatalk
+        rc_status -v
+        ;;
+    *)
+        echo "Usage: $0 {start|stop|restart|status}"
+        exit 1
+        ;;
+esac
+
+rc_exit
diff --git a/distrib/initscripts/rc.timelord.netbsd.tmpl b/distrib/initscripts/rc.timelord.netbsd.tmpl
deleted file mode 100644 (file)
index aae4b7a..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/bin/sh
-#
-# PROVIDE: timelord
-# REQUIRE: atalkd
-#
-# AppleTalk time server daemon. (netatalk :NETATALK_VERSION:)
-# Make sure not to start atalkd in the background:
-# its data structures must have time to stablize before running the
-# other processes.
-#
-
-. /etc/rc.subr
-
-name="timelord"
-rcvar=$name
-command=":SBINDIR:/timelord"
-pidfile="/var/run/${name}.pid"
-
-load_rc_config $name
-run_rc_command "$1"
-
diff --git a/distrib/initscripts/service.atalk.systemd.tmpl b/distrib/initscripts/service.atalk.systemd.tmpl
deleted file mode 100644 (file)
index 794baa5..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-# This file is part of netatalk :NETATALK_VERSION:.
-
-# The method of using shell-script "netatalk.sh" is not suitable.
-# The future service files are due to start daemons directly.
-# See netatalk-xxx/distrib/systemd/ directory in tarball.
-
-[Unit]
-Description=File and Printer sharing for Macintosh clients
-After=syslog.target network.target slpd.service avahi-daemon.service
-
-[Service]
-Type=oneshot
-ExecStart=/bin/sh -c "exec :PKGLIBEXECDIR:/netatalk.sh"
-RemainAfterExit=yes
-
-[Install]
-WantedBy=multi-user.target
diff --git a/distrib/initscripts/service.systemd.tmpl b/distrib/initscripts/service.systemd.tmpl
new file mode 100644 (file)
index 0000000..2183f30
--- /dev/null
@@ -0,0 +1,15 @@
+# This file is part of netatalk :NETATALK_VERSION:.
+
+[Unit]
+Description=Netatalk AFP fileserver for Macintosh clients
+After=syslog.target network.target avahi-daemon.service
+
+[Service]
+Type=forking
+GuessMainPID=no
+ExecStart=:SBINDIR:/netatalk
+Restart=always
+RestartSec=1
+
+[Install]
+WantedBy=multi-user.target
diff --git a/distrib/systemd/Makefile.am b/distrib/systemd/Makefile.am
deleted file mode 100644 (file)
index 2fad3e5..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-# Makefile for distrib/systemd/
-
-EXTRA_DIST = README netatalk.service netatalk-cnid.service
diff --git a/distrib/systemd/README b/distrib/systemd/README
deleted file mode 100644 (file)
index 1356e82..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-The service file of the current Netatalk is not appropriate because it use
-a shell-script "netatalk.sh".
-
-Two experimental files are here.
-
-    netatalk.service
-    netatalk-cnid.service
-
-You can control starting/stopping by netatalk.service only
-because netatalk-cnid.service is controlled automatically.
-
-    # systemctl enable|disable netatalk.service
-    # systemctl start|stop|restart netatalk.service
-
-These files start daemons directly and do not read "netatalk.conf".
-Therefore, you need to edit files for setting options.
-
-    ATALK_NAME:       set in afpd.conf instead
-    AFPD_MAX_CLIENTS: set in netatalk.service by using -c
-    AFPD_UAMLIST:     set in afpd.conf instead
-    AFPD_GUEST:       set in afpd.conf instead
-    CNID_CONFIG:      set in netatalk-cnid.service by using -l and -f options
-
-There are no service files for atalkd, papd, timelord and a2boot
-because AppleTalk feature is due to be abolished in netatalk 3.0.
diff --git a/distrib/systemd/netatalk-cnid.service b/distrib/systemd/netatalk-cnid.service
deleted file mode 100644 (file)
index 8edfcba..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-# This is experimental service file.
-# See distrib/systemd/README
-
-[Unit]
-Description=Netatalk CNID database daemon for AFP fileserver
-After=syslog.target network.target
-Before=netatalk.service
-Requires=netatalk.service
-
-[Service]
-Type=forking
-GuessMainPID=no
-ExecStart=/usr/sbin/cnid_metad -l log_note
-Restart=always
-RestartSec=1
-
-[Install]
-WantedBy=multi-user.target
-Also=netatalk.service
diff --git a/distrib/systemd/netatalk.service b/distrib/systemd/netatalk.service
deleted file mode 100644 (file)
index 7c6857c..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-# This is experimental service file.
-# See distrib/systemd/README
-
-[Unit]
-Description=Netatalk AFP fileserver for Macintosh clients
-After=syslog.target network.target slpd.service avahi-daemon.service netatalk-cnid.service
-Requires=netatalk-cnid.service
-
-[Service]
-Type=forking
-GuessMainPID=no
-ExecStart=/usr/sbin/afpd -c 20
-Restart=always
-RestartSec=1
-
-[Install]
-WantedBy=multi-user.target
-Also=netatalk-cnid.service
index 9ba1765bcf4fa9364f8be79be7f9349beb84a89b..81ae30d66da95b69e959ac9b734a5ff96c13e8a6 100644 (file)
@@ -1,42 +1,27 @@
 Information for Netatalk Developers
 ===================================
 
-For basic installation instructions, see the INSTALL file.
+For basic installation instructions, see http://netatalk.sourceforge.net .
 
 Netatalk is an implementation of "AFP over TCP".
-Netatalk also support the AppleTalk Protocol Suite for legacy Macs.
-The current release contains support for EtherTalk Phase I and II, 
-DDP, RTMP, NBP, ZIP, AEP, ATP, PAP, ASP, AFP and DSI.
-The complete stack looks like this on a BSD-derived system:
-
-    AFP                          AFP
-     |                            |
-    ASP    PAP                   DSI
-      \   /                       |
-       ATP RTMP NBP ZIP AEP       |
-        |    |   |   |   |        |
-   -+---------------------------------------------------+- (kernel boundary)
-    |                    Socket                         |
-    +-----------------------+------------+--------------+
-    |                       |     TCP    |    UDP       |
-    |          DDP          +------------+--------------+
-    |                       |           IP              |
-    +-----------------------+---------------------------+
-    |                Network-Interface                  |
-    +---------------------------------------------------+
-
 DSI is a session layer used to carry AFP over TCP.
-DDP is in the kernel.  "atalkd" implements RTMP, NBP, ZIP, and AEP.  It
-is the AppleTalk equivalent of Unix "routed".  There is also a
-client-stub library for NBP.  ATP and ASP are implemented as
-libraries.  "papd" allows Macs to spool to "lpd", and "pap" allows Unix
-machines to print to AppleTalk connected printers.  "psf" is a
-PostScript printer filter for "lpd", designed to use "pap".  "psorder"
-is a PostScript reverser, called by "psf" to reverse pages printed to
-face-up stacking printers.  "afpd" provides Macs with an interface to
-the Unix file system.  Refer to the appropriate man pages for
-operational information.
-
+The complete stack looks like this:
+
+          AFP
+           |
+          DSI
+           |
+           | (port:548)
+           |
+   -+---------------------------+- (kernel boundary)
+    |         Socket            |
+    +------------+--------------+
+    |     TCP    |    UDP       |
+    +------------+--------------+
+    |       IP v4 or v6         |
+    +---------------------------+
+    |     Network-Interface     |
+    +---------------------------+
 
 Compilation
 ===========
@@ -68,23 +53,7 @@ Libtool encapsulates the platform specific dependencies for the
 creation of libraries. It determines if the local platform can support
 shared libraries or if it only supports static libraries.
 
-Netatalk currently requires libtool 1.4 or higher (1.4b for OpenBSD).
-If you are using Tru64 you must apply the following patch to the file
-acinclude.m4 (normally found in /usr/share/libtool/libltdl).
-
---- acinclude.m4.old   Tue Nov 20 15:30:23 2001
-+++ acinclude.m4       Tue Nov 20 15:31:54 2001
-@@ -2226,6 +2226,7 @@
- osf3* | osf4* | osf5*)
-   version_type=osf
-+  need_lib_prefix=no
-   need_version=no
-   soname_spec='${libname}${release}.so'
-   library_names_spec='${libname}${release}.so$versuffix ${libname}${release}.so $libname.so'
-
 Documentation: http://www.gnu.org/software/libtool/
-Program: (see the GNU mirrors) /gnu/libtool/libtool-1.4.tar.gz
 
 2. GNU m4
 GNU m4 is an implementation of the Unix macro processor. It reads
@@ -92,20 +61,17 @@ stdin and copies to stdout expanding defined macros as it processes
 the text.
 
 Documentation: http://www.gnu.org/software/m4/
-Program: (see the GNU mirrors) /gnu/m4/m4-1.4.tar.gz
 
 3. Autoconf
 Autoconf is a package of m4 macros that produce shell scripts to
 configure source code packages.
 
 Documentation: http://www.gnu.org/software/autoconf/
-Program: (see the GNU mirrors) /gnu/autoconf/autoconf-2.52.tar.gz
 
 4. Automake
 Automake is a tool that generates  'Makefile.in' files.
 
 Documentation: http://www.gnu.org/software/automake/
-Program: (see the GNU mirrors) /gnu/automake/automake-1.5.tar.gz
 
 Optional
 ========
@@ -223,3 +189,99 @@ int func(void)
 EC_CLEANUP:
     EC_EXIT;
 }
+
+Ini Parser
+==========
+
+The ini parser is taken from <http://ndevilla.free.fr/iniparser/>.
+It has been slightly modified:
+- case-sensitive
+- "include" directive added
+- iniparser_getstrdup() to complemnt iniparser_getstring(), it return allocated strings
+  which the caller must free as necessary
+- the API has been modifed such that all iniparser_get* funcs take a section and a parameter
+  as sepereta args instead of one string of the form "section:parameter" in the original
+  library
+
+CNID Database Daemons
+=====================
+
+The CNID database daemons cnid_metad and cnid_dbd are a implementation of
+the netatalk CNID database support that attempts to put all functionality
+into separate daemons.
+There is one cnid_dbd daemon per netatalk volume. The underlying database
+structure is based on Berkeley DB and the database format is the same
+as in the cdb CNID backend, so this can be used as a drop-in replacement.
+
+Advantages: 
+
+- No locking issues or leftover locks due to crashed afpd daemons any
+  more. Since there is only one thread of control accessing the
+  database, no locking is needed and changes appear atomic.
+
+- Berkeley DB transactions are difficult to get right with several
+  processes attempting to access the CNID database simultanously. This 
+  is much easier with a single process and the database can be made nearly 
+  crashproof this way (at a performance cost).
+
+- No problems with user permissions and access to underlying database
+  files, the cnid_dbd process runs under a configurable user
+  ID that normally also owns the underlying database
+  and can be contacted by whatever afpd daemon accesses a volume.
+
+- If an afpd process crashes, the CNID database is unaffected. If the
+  process was making changes to the database at the time of the crash,
+  those changes will be rolled back entirely (transactions).
+  If the process was not using the database at the time of the crash,
+  no corrective action is necessary. In any case, database consistency
+  is assured.
+
+Disadvantages:
+
+- Performance in an environment of processes sharing the database
+  (files) is potentially better for two reasons:
+
+  i)  IPC overhead.
+  ii) r/o access to database pages is possible by more than one
+      process at once, r/w access is possible for nonoverlapping regions.
+
+  The current implementation of cnid_dbd uses unix domain sockets as
+  the IPC mechanism. While this is not the fastest possible method, it
+  is very portable and the cnid_dbd IPC mechanisms can be extended to
+  use faster IPC (like mmap) on architectures where it is
+  supported. As a ballpark figure, 20000 requests/replies to the cnid_dbd
+  daemon take about 0.6 seconds on a Pentium III 733 Mhz running Linux
+  Kernel 2.4.18 using unix domain sockets. The requests are "empty"
+  (no database lookups/changes), so this is just the IPC
+  overhead.
+  
+  I have not measured the effects of the advantages of simultanous
+  database access.
+
+
+Installation and configuration
+
+There are two executeables that will be built in etc/cnid_dbd and
+installed into the systems binaries directories of netatalk
+cnid_metad and cnid_dbd. cnid_metad should run all the
+time with root permissions. It will be notified when an instance of
+afpd starts up and will in turn make sure that a cnid_dbd daemon is
+started for the volume that afpd wishes to access. The cnid_dbd daemon runs as
+long as necessary and services any
+other instances of afpd that access the volume. You can safely kill it
+with SIGTERM, it will be restarted automatically by cnid_metad as soon
+as the volume is accessed again.
+
+cnid_dbd changes to the Berkeley DB directory on startup and sets
+effective UID and GID to owner and group of that directory. Database and
+supporting files should therefore be writeable by that user/group.
+
+Current shortcomings:
+
+- The parameter file parsing of db_param is very simpleminded. It is
+easy to cause buffer overruns and the like.
+Also, there is no support for blanks (or weird characters) in
+filenames for the usock_file parameter.
+
+- There is no protection against a malicious user connecting to the
+cnid_dbd socket and changing the database.
index 05eaf8415abe36d5a1e997727004daf6c1d15da7..a6fcda87c26eefbfa516d8a595f87943f11a3cb7 100644 (file)
@@ -1,3 +1,3 @@
 # Makefile.am for INSTALL/
 
-EXTRA_DIST = DEVELOPER README.AppleTalk
+EXTRA_DIST = DEVELOPER
diff --git a/doc/README.AppleTalk b/doc/README.AppleTalk
deleted file mode 100644 (file)
index 10e823b..0000000
+++ /dev/null
@@ -1,324 +0,0 @@
-This is a README for the major platforms where Netatalk is in use. 
-
-Platforms Covered:
-A.   Linux
-B.   Tru64
-C.   Solaris
-D.I  OpenBSD
-D.II Other BSDs
-E.   SunOS
-F.   Generic
-
-----------------------------------------------------------------
-
-A. Linux
-
-We no longer include linux kernel code with netatalk, since Linux now
-includes AppleTalk support.
-
-1.  MAKE CONFIG.  Configure your kernel with "make config".  Answer yes
-    to "AppleTalk DDP" support.
-
-2.  INSTALL KERNEL.  Make and install your kernel.  Be sure to update
-    your boot blocks!
-
-3.  Linux 2.2.x provides the sendfile() call. This reduces overhead
-    when sending/copying files. This option will be autoconfigured on
-    compile. NOTE: you might run into problems if you have this option
-    compiled in and you switch to a machine running an os < 2.2.x.
-
-
-Netatalk supplies two different types of Appletalk servers and both
-can run at the same time. Classic Appletalk requires afpd and
-atalkd. Appletalk over IP only requires afpd.
-
-Classic Appletalk on GNU/Linux requires that CONFIG_ATALK is compiled
-into the kernel or as a kernel module. To check to see if the kernel
-has Appletalk installed:
-
-$> dmesg | grep Apple
-This just parses the boot messages for any line containing
-'Apple'.
-
-To see all the  loaded modules (as root):
-$> lsmod
-
-If you don't find it, you may have to compile a kernel and turn on
-Appletalk in Networking options -> Appletalk DDP. You have an option
-to install as a module or directly into the kernel.
-
-Some default distribution kernels have already compiled Appletalk DDP
-as a module, you may have to edit your /etc/modules.conf to include:
-"alias net-pf-5 appletalk ".
-
-Note: check your distribution documentation about editing
-/etc/modules.conf.
-
-For more complete information about the Linux kernel see the
-Kernel-HOWTO:
-http://www.linuxdoc.org/HOWTO/Kernel-HOWTO.html
-
-A note for RedHat users: You may need to install the glibc-devel
-package to be able to compile Netatalk correctly.
-
-----------------------------------------------------------------
-
-B. TRU64
-
-This is the Tru64 README file for netatalk.
-
-1.  Unfortunately, AppleTalk is not available for Digital Unix or Tru64.
-    The reason for this is the kernel patches which Netatalk requires
-    cannot be ported to Tru64. If anyone has the kernel source of Tru64
-    they are welcomed to port the AppleTalk modules themselves.
-
-    As a result, only AppleShare over IP (ASIP) works with Tru64. That
-    is, the program afpd. papd and atalkd compile, but doesn't really
-    work. Anything that requires AppleTalk doesn't work.
-
-2.  Netatalk compiles on Tru64 V4.0D or higher using either the built-in
-    DEC C compiler or GCC V2.95.3. Also, either the Tru64 make command or
-    GNU make can be used. Netatalk supports Tru64's Security Integration
-    Architecture (SIA) and runs on machines configured for Base (BSD) or
-    Enhanced (OSFC2) Security without recompilation.
-
-3.  A peculiar bug in Netatalk has been noticed on a single Tru64
-    machine. However, because other Tru64 machines have not affected, a
-    patch will not be forthcoming until the circumstances where the bug
-    hits is isolated and a more elegant and appropriate patch can be
-    found. In the meantime, there is a description of the bug below. Any
-    users affected can attempt the workarounds provided. The user is
-    urged to report this to the mailing list so that this bug can be
-    isolated and removed.
-
-    HAVE_GCC_MEMCPY_BUG
-    Description -
-       It appears that memcpy() under Tru64 can fail under some
-    circumstances. This maybe due to the fact that Netatalk is compiled
-    with gcc, but since only gcc can compile Netatalk, this is a mute
-    point.
-
-    Symptoms -
-       The symptoms of this bug is that a 18432 byte file uploaded to
-    the server would upload correctly, but a 18433 byte file would
-    result in a sparse file many megabytes big (16MB+). However, due to
-    the low-level nature of memcpy(), there is no reason why other
-    symptoms could not occur.
-
-    Workarounds -
-       There are two known workarounds at this stage.
-    - The first is to #define the macro HAVE_GCC_MEMCPY_BUG. This forces
-    netatalk to use bcopy() in a few (but not all) cases within the code
-    and is enough to stop the bug from occurring. This is the easiest
-    workaround and would merely alter the standard compilation steps to
-
-    CFLAGS="-DHAVE_GCC_MEMCPY_BUG" ./configure [...]
-    make
-    make install
-
-    - The second workaround is to manually remove the optimisation flag
-    "-O2" from within configure and/or configure.in. Although, this
-    isn't the preferred workaround, it shows that the compiler is
-    (at least) partially at fault.
-
-----------------------------------------------------------------
-
-C. SOLARIS
-
-1.  SELECT COMPILER.  This distribution is configured to build with
-    gcc.  It should also work with cc. At the present time only cc
-    v5.0 and gcc 3.1 and above can build the 64-bit kernel module.
-
-1a. SELECT KERNEL TYPE.  Edit sys/solaris/Makefile.kernel and set KCFLAGS
-     to include sparcv9 support if you run a 64-bit kernel, or leave it
-     commented out for a 32-bit kernel. Only UltraSPARC systems
-     running Solaris 7 and above support a 64-bit kernel. If you're
-     not sure what kernel you use, run "isainfo -v". You're running a
-     64-bit kernel if the result includes 64-bit (sparcv9), otherwize
-     it's 32-bit.
-
-     NOTE: If you want both the 32-bit and 64-bit kernel modules to be
-     installed, first compile and install the version appropriate to
-     the kernel that you're currently running, then make clean,
-     compile and install the other version.
-
-2.  EDIT NETCONFIG.  Add the following line to /etc/netconfig:
-
-       ddp tpi_clts - appletalk ddp /dev/ddp -
-
-    This makes the socket library aware of the AppleTalk protocol
-    family.
-
-3.  INSTALL DRIVER.  Since the STREAMS ddp driver must be installed as
-    root, we've separated that portion of the build.  Type
-
-       make -f Makefile.kernel kinstall
-
-    to install the driver.  This copies the driver and its config file
-    into /usr/kernel/drv and /usr/kernel/strmod, runs "add_drv ddp" to
-    make the kernel aware of the new driver, and adds an rc file to
-    /etc/rc?.d. Watch out for error messages after it runs  add_drv.
-    If you see something like
-      devfsadm: driver failed to attach: ddp
-      Warning: Driver (ddp) successfully added to system but failed to attach
-    then recheck sys/solaris/Makefile.kernel and/or try a different
-    compiler.
-
-4.  ATALKD.CONF.  Under Solaris, you must create atalkd.conf, since
-    Solaris provides no method for determining the names of the
-    available interfaces.  It is sufficent to name the available
-    interfaces in atalkd.conf, one per line.  E.g.
-
-       le0
-
-    on a line by itself on many Suns. hme0 on Ultras.  See atalkd(8).
-
-5.  PRINTING.  Netatalk can use any postscript printer that has been set
-    up for use by Solaris. If you haven't already set up a printer,
-    type admintool then select Browse --> Printers, and then Edit --> Add
-    and fill in the form for either a local or remote printer. If adding
-    a local printer, set the Printer Type to PostScript. Then find a
-    postscript file and test your printer from the command line. For
-    example if you created a printer called "fred" your print command
-    would be something like:  lp -d fred some_file.ps
-
-    Once you have a printer that works under Solaris, you need to create
-    a papd.conf file. For example
-
-      MacLaserjet:\
-          :pr=|/usr/bin/lp -d fred:\
-          :op=nobody:\
-          :pd=/usr/local/etc/HPLJ_4M.PPD:
-
-    See doc/CONFIGURE for more information on papd.conf.
-    Once you have this set up, and assuming netatalk starts up after
-      /etc/rc2.d/S79atalk start
-    you should be able to see the printer from the Macintosh Chooser.
-
-----------------------------------------------------------------
-
-D.I OpenBSD
-
-1.  KERNEL SUPPORT. Note that kernel support for netatalk appears in
-    OpenBSD 2.2,  or openbsd-current dated after Aug 1, 1997. But the
-    'comment out' character must be removed and the kernel must be
-    recompiled.
-
-    The kernel file that needs to be edited is usually located in:
-    /usr/src/sys/conf
-
-    Remove the first comment (#) from this line:
-    # option          NETATALK        # AppleTalk
-
-    Generally this is the GENERIC kernal. If you decide to rename 
-    the kernel, don't forget to go to 
-    /usr/src/sys/arch/<your arch>/conf/NEWNAME, and change the 
-    ../../../conf/GENERIC line to your NEWNAME. See 
-    http://www.openbsd.org/faq/faq5.html for more information on 
-    compiling a new kernel.
-
-2.  STARTING NETATALK. The rc scripts that come with openbsd to
-    start netatalk are specific to an older version of netatalk.
-    So, if you use the initscript provided in a current netatalk's
-    distrib/initscripts directory, you must either add the lines
-    from rc.atalk.bsd by hand into /etc/rc.local (or wherever you
-    want to launch the daemons from) or modify your /etc/rc.local
-    file to read: 
-
-    (currently says)
-
-    # Netatalk stuff
-    if [ -f /etc/netatalk/rc.atalk ]; then
-            . /etc/netatlk/rc.atalk
-    fi
-
-    (change to) 
-
-    # Netatalk stuff
-    if [ -f /etc/rc.atalk ]; then
-            . /etc/rc.atalk
-    fi
-
-    and copy netatalk/distrib/initscripts/rc.atalk.bsd to /etc/rc.atalk.
-
-D.II Other BSDs
-
-1.  KERNEL SUPPORT. Note that kernel support for netatalk appears in
-    FreeBSD 2.2-current dated after 12 September 1996.
-
-    Add the line
-
-        options NETATALK
-
-    to the config file for your kernel.  Rebuild and install your
-    kernel.  Reboot.
-
-----------------------------------------------------------------
-
-E. SunOS
-
-1.  KERNEL MODULE. This version of netatalk requires that your kernel
-    be configured with
-
-        options VDDRV
-
-    The loadable kernel module is made and installed during the normal
-    make and make install.  NOTE:  Unloading the kernel module may not
-    work correctly and may cause your kernel to panic, hang, or do
-    other nasty things.
-
-----------------------------------------------------------------
-
-F. Generic
-
-(It's unknown how applicable this is compared to the current codebase)
-
-    The generic system profile is for use on systems that don't have native
-    appletalk support. For those systems, it should still be possible to get
-    the AFP/tcp portion of netatalk to still work.
-    
-    To do that, you will need the following information:
-
-        1) Endian order: If your machine does not specify the
-          byte-order in netinet/in.h, you may need to modify
-          netatalk/endian.h.
-
-        2) Integer sizes: If your machine does not define intX_t and
-          u_intX_t, you will need to define them in
-          netatalk/endian.h. To ease matters, you can specify
-          _ISOC9X_SOURCE if you have inttypes.h, HAVE_64BIT_LONGS for
-          64 bit machines, or HAVE_32BIT_LONGS for 32 bit
-          machines. NOTE: you should only use HAVE_32/64BIT_LONGS on
-          machines that don't have a header file somewhere with the
-          integer sizes. If you have a file with all the relevant
-          bits, modify netatalk/endian.h to include it.
-
-       3) Quota/statfs information: You may be able to get away with
-          either BSD4_4 or __svr4__, but that's unlikely if your os
-          is some bizarre hybrid. If you don't have quota support,
-          just specify NO_QUOTA_SUPPORT. In addition, if you'll need
-          to specify the include file that gets statfs() (usually
-          either USE_VFS_H or USE_STATFS_H although BSD4_4 and
-          __svr4__ bring in a set of include files for that). Look at
-          etc/afpd/quota.c, unix.c, and unix.h for more information.
-          Finally, if you have a really old version of rquota, you
-                  can define USE_OLD_RQUOTA as well.
-
-       4) path information for lock/spool/printer files. you'll need
-           to specify -D_PATH_LOCKDIR if include/atalk/paths.h doesn't
-           have the correct paths specified for printer info and lock
-           files. 
-
-    Beyond that, you should make sure that your operating system looks and
-    smells like a Un*x POSIXy operating system. The only operating systems
-    that netatalk supports that don't quite fit that description are
-    sunos 4 and ultrix. If your operating system is peculiar, you may need
-    to add in compatibility routines (libatalk/compat,
-    include/atalk/compat.h) to make it look more like the others. 
-    
-    If you would like native AppleTalk support, you will need kernel support 
-    for your operating system. Look at the Solaris STREAMS module if your
-    operating system supports that framework. Otherwise, look at the ddp
-    code in FreeBSD, NetBSD, or OpenBSD if your operating system is BSDish
-    in nature. If your operating system looks different than these two
-    cases, you'll have to roll your own implementation.
index 895a5e778b39b68094b7bf7771c67cf63c08dec9..8f1b0d992ec94e80ad60fd4ba1688d5d9900b917 100644 (file)
@@ -1,4 +1,3 @@
 Makefile
 Makefile.in
-.gitignore
 *.o
index 6ad182a5693bd5b7278f9804bf0c0708e52282ca..e5367734d3bc584baa574f0eaceb1897dd66f81e 100644 (file)
@@ -1,7 +1,3 @@
 # Makefile.am for etc/
 
-SUBDIRS = afpd cnid_dbd uams
-
-if USE_APPLETALK
-SUBDIRS += atalkd papd psf
-endif
+SUBDIRS = afpd cnid_dbd netatalk uams
index 7a6ed52d56140fd06e29c8a06aff4ccf1543768a..85b51dc86bdca8971ecb85ce94c66c1273c28e21 100644 (file)
@@ -6,7 +6,6 @@ sbin_PROGRAMS = afpd
 noinst_PROGRAMS = hash fce
 
 afpd_SOURCES = \
-       afp_asp.c \
        afp_avahi.c \
        afp_config.c \
        afp_dsi.c \
@@ -45,26 +44,19 @@ afpd_SOURCES = \
        volume.c
 
 afpd_LDADD =  \
-       $(top_builddir)/libatalk/cnid/libcnid.la \
        $(top_builddir)/libatalk/libatalk.la \
-       @LIBGCRYPT_LIBS@ @ZEROCONF_LIBS@ @QUOTA_LIBS@ @SLP_LIBS@ @WRAP_LIBS@ @LIBADD_DL@ @ACL_LIBS@ @PTHREAD_LIBS@
+       @LIBGCRYPT_LIBS@ @QUOTA_LIBS@ @WRAP_LIBS@ @LIBADD_DL@ @ACL_LIBS@ @ZEROCONF_LIBS@ @PTHREAD_LIBS@ @GSSAPI_LIBS@ @KRB5_LIBS@
 
-afpd_LDFLAGS = -export-dynamic 
+afpd_LDFLAGS = -export-dynamic
 
 afpd_CFLAGS = \
-       -I$(top_srcdir)/include \
-       -I$(top_srcdir)/sys \
-       @SLP_CFLAGS@ @ZEROCONF_CFLAGS@ \
+       @ZEROCONF_CFLAGS@ @GSSAPI_CFLAGS@ @KRB5_CFLAGS@\
        -DAPPLCNAME \
        -DSERVERTEXT=\"$(SERVERTEXT)/\" \
-       -D_PATH_AFPDDEFVOL=\"$(pkgconfdir)/AppleVolumes.default\" \
-       -D_PATH_AFPDSYSVOL=\"$(pkgconfdir)/AppleVolumes.system\" \
        -D_PATH_AFPDPWFILE=\"$(pkgconfdir)/afppasswd\" \
-       -D_PATH_AFPDCONF=\"$(pkgconfdir)/afpd.conf\" \
-       -D_PATH_AFPDSIGCONF=\"$(pkgconfdir)/afp_signature.conf\" \
        -D_PATH_AFPDUAMPATH=\"$(UAMS_PATH)/\" \
-       -D_PATH_ACL_LDAPCONF=\"$(pkgconfdir)/afp_ldap.conf\" \
-       -D_PATH_AFPDUUIDCONF=\"$(pkgconfdir)/afp_voluuid.conf\"
+       -D_PATH_CONFDIR=\"$(pkgconfdir)/\" \
+       -D_PATH_STATEDIR='"$(localstatedir)/netatalk/"'
 
 if HAVE_ACLS
 afpd_SOURCES += acls.c
index b7c4b6d266fdb9863005c61dc889cd66785453e7..87ff5decefdc75d9c09feab9af8c8d971fa54b14 100644 (file)
@@ -31,8 +31,8 @@
 #endif
 
 struct ace_rights_map {
-    u_int32_t from;
-    u_int32_t to;
+    uint32_t from;
+    uint32_t to;
 };
 
 #ifdef HAVE_SOLARIS_ACLS
@@ -71,8 +71,8 @@ struct ace_rights_map darwin_to_nfsv4_rights[] = {
 };
 
 struct nfsv4_to_darwin_flags_map {
-    u_int16_t from;
-    u_int32_t to;
+    uint16_t from;
+    uint32_t to;
 };
 
 struct nfsv4_to_darwin_flags_map nfsv4_to_darwin_flags[] = {
@@ -85,8 +85,8 @@ struct nfsv4_to_darwin_flags_map nfsv4_to_darwin_flags[] = {
 };
 
 struct darwin_to_nfsv4_flags_map {
-    u_int32_t from;
-    u_int16_t to;
+    uint32_t from;
+    uint16_t to;
 };
 
 struct darwin_to_nfsv4_flags_map darwin_to_nfsv4_flags[] = {
index 82d61eb5444d88512ae58aa9ef6ed9c6496f4247..e37c6262bf4264e9766eaa1550efa2073f67f805 100644 (file)
@@ -45,6 +45,8 @@
 #include <atalk/acl.h>
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
+#include <atalk/unix.h>
+#include <atalk/netatalk_conf.h>
 
 #include "directory.h"
 #include "desktop.h"
  * returns the result as a Darwin allowed rights ACE.
  * This must honor trivial ACEs which are a mode_t mapping.
  *
+ * @param obj            (r) handle
  * @param path           (r) path to filesystem object
  * @param sb             (r) struct stat of path
  * @param result         (w) resulting Darwin allow ACE
  *
  * @returns                  0 or -1 on error
  */
-static int solaris_acl_rights(const char *path,
+static int solaris_acl_rights(const AFPObj *obj,
+                              const char *path,
                               const struct stat *sb,
                               uint32_t *result)
 {
@@ -129,15 +133,15 @@ static int solaris_acl_rights(const char *path,
            if its a trivial ACE_EVERYONE ACE
            THEN
            process ACE */
-        if (((who == uuid) && !(flags & (ACE_TRIVIAL|ACE_IDENTIFIER_GROUP)))
+        if (((who == obj->uid) && !(flags & (ACE_TRIVIAL|ACE_IDENTIFIER_GROUP)))
             ||
-            ((flags & ACE_IDENTIFIER_GROUP) && !(flags & ACE_GROUP) && gmem(who))
+            ((flags & ACE_IDENTIFIER_GROUP) && !(flags & ACE_GROUP) && gmem(who, obj->ngroups, obj->groups))
             ||
-            ((flags & ACE_OWNER) && (uuid == sb->st_uid))
+            ((flags & ACE_OWNER) && (obj->uid == sb->st_uid))
             ||
-            ((flags & ACE_GROUP) && !(uuid == sb->st_uid) && gmem(sb->st_gid))
+            ((flags & ACE_GROUP) && !(obj->uid == sb->st_uid) && gmem(sb->st_gid, obj->ngroups, obj->groups))
             ||
-            (flags & ACE_EVERYONE && !(uuid == sb->st_uid) && !gmem(sb->st_gid))
+            (flags & ACE_EVERYONE && !(obj->uid == sb->st_uid) && !gmem(sb->st_gid, obj->ngroups, obj->groups))
             ) {
             /* Found an applicable ACE */
             if (type == ACE_ACCESS_ALLOWED_ACE_TYPE)
@@ -397,7 +401,9 @@ EC_CLEANUP:
  *
  * @returns                  0 or -1 on error
  */
-static int posix_acl_rights(const char *path,
+
+static int posix_acl_rights(const AFPObj *obj,
+                            const char *path,
                             const struct stat *sb,
                             uint32_t *result)
 {
@@ -422,7 +428,7 @@ static int posix_acl_rights(const char *path,
 
         switch (tag) {
             case ACL_USER_OBJ:
-                if (sb->st_uid == uuid) {
+                if (sb->st_uid == obj->uid) {
                     LOG(log_maxdebug, logtype_afpd, "ACL_USER_OBJ: %u", sb->st_uid);
                     rights |= posix_permset_to_darwin_rights(e, S_ISDIR(sb->st_mode));
                 }
@@ -431,7 +437,7 @@ static int posix_acl_rights(const char *path,
             case ACL_USER:
                 EC_NULL_LOG(uid = (uid_t *)acl_get_qualifier(e));
 
-                if (*uid == uuid) {
+                if (*uid == obj->uid) {
                     LOG(log_maxdebug, logtype_afpd, "ACL_USER: %u", *uid);
                     acl_rights |= posix_permset_to_darwin_rights(e, S_ISDIR(sb->st_mode));
                 }
@@ -440,7 +446,7 @@ static int posix_acl_rights(const char *path,
                 break;
 
             case ACL_GROUP_OBJ:
-                if (!(sb->st_uid == uuid) && gmem(sb->st_gid)) {
+                if (!(sb->st_uid == obj->uid) && gmem(sb->st_gid, obj->ngroups, obj->groups)) {
                     LOG(log_maxdebug, logtype_afpd, "ACL_GROUP_OBJ: %u", sb->st_gid);
                     acl_rights |= posix_permset_to_darwin_rights(e, S_ISDIR(sb->st_mode));
                 }
@@ -449,7 +455,7 @@ static int posix_acl_rights(const char *path,
             case ACL_GROUP:
                 EC_NULL_LOG(gid = (gid_t *)acl_get_qualifier(e));
 
-                if (gmem(*gid)) {
+                if (gmem(*gid, obj->ngroups, obj->groups)) {
                     LOG(log_maxdebug, logtype_afpd, "ACL_GROUP: %u", *gid);
                     acl_rights |= posix_permset_to_darwin_rights(e, S_ISDIR(sb->st_mode));
                 }
@@ -463,7 +469,7 @@ static int posix_acl_rights(const char *path,
                 break;
 
             case ACL_OTHER:
-                if (!(sb->st_uid == uuid) && !gmem(sb->st_gid)) {
+                if (!(sb->st_uid == obj->uid) && !gmem(sb->st_gid, obj->ngroups, obj->groups)) {
                     LOG(log_maxdebug, logtype_afpd, "ACL_OTHER");
                     rights |= posix_permset_to_darwin_rights(e, S_ISDIR(sb->st_mode));
                 }
@@ -541,7 +547,7 @@ static u_char acl_permset_to_uarights(acl_entry_t entry) {
  *
  * @returns                  0 or -1 on error
  */
-static int posix_acls_to_uaperms(const char *path, struct stat *sb, struct maccess *ma) {
+static int posix_acls_to_uaperms(const AFPObj *obj, const char *path, struct stat *sb, struct maccess *ma) {
     EC_INIT;
 
     int entry_id = ACL_FIRST_ENTRY;
@@ -567,7 +573,7 @@ static int posix_acls_to_uaperms(const char *path, struct stat *sb, struct macce
             case ACL_USER:
                 EC_NULL_LOG(uid = (uid_t *)acl_get_qualifier(entry));
 
-                if (*uid == uuid && !(whoami == sb->st_uid)) {
+                if (*uid == obj->uid && !(whoami == sb->st_uid)) {
                     LOG(log_maxdebug, logtype_afpd, "ACL_USER: %u", *uid);
                     acl_rights |= acl_permset_to_uarights(entry);
                 }
@@ -578,14 +584,14 @@ static int posix_acls_to_uaperms(const char *path, struct stat *sb, struct macce
                 group_rights = acl_permset_to_uarights(entry);
                 LOG(log_maxdebug, logtype_afpd, "ACL_GROUP_OBJ: %u", sb->st_gid);
 
-                if (gmem(sb->st_gid) && !(whoami == sb->st_uid))
+                if (gmem(sb->st_gid, obj->ngroups, obj->groups) && !(whoami == sb->st_uid))
                     acl_rights |= group_rights;
                 break;
 
             case ACL_GROUP:
                 EC_NULL_LOG(gid = (gid_t *)acl_get_qualifier(entry));
 
-                if (gmem(*gid) && !(whoami == sb->st_uid)) {
+                if (gmem(*gid, obj->ngroups, obj->groups) && !(whoami == sb->st_uid)) {
                     LOG(log_maxdebug, logtype_afpd, "ACL_GROUP: %u", *gid);
                     acl_rights |= acl_permset_to_uarights(entry);
                 }
@@ -985,7 +991,7 @@ static int get_and_map_acl(char *name, char *rbuf, size_t *rbuflen)
     EC_INIT;
     int mapped_aces = 0;
     int dirflag;
-    uint32_t *darwin_ace_count = (u_int32_t *)rbuf;
+    uint32_t *darwin_ace_count = (uint32_t *)rbuf;
 #ifdef HAVE_SOLARIS_ACLS
     int ace_count = 0;
     ace_t *aces = NULL;
@@ -1338,7 +1344,8 @@ EC_CLEANUP:
  *
  * @returns                    AFP result code
 */
-static int check_acl_access(const struct vol *vol,
+static int check_acl_access(const AFPObj *obj,
+                            const struct vol *vol,
                             struct dir *dir,
                             const char *path,
                             const uuidp_t uuid,
@@ -1382,10 +1389,10 @@ static int check_acl_access(const struct vol *vol,
         LOG(log_debug, logtype_afpd, "check_access: allowed rights from dircache: 0x%08x", allowed_rights);
     } else {
 #ifdef HAVE_SOLARIS_ACLS
-        EC_ZERO_LOG(solaris_acl_rights(path, &st, &allowed_rights));
+        EC_ZERO_LOG(solaris_acl_rights(obj, path, &st, &allowed_rights));
 #endif
 #ifdef HAVE_POSIX_ACLS
-        EC_ZERO_LOG(posix_acl_rights(path, &st, &allowed_rights));
+        EC_ZERO_LOG(posix_acl_rights(obj, path, &st, &allowed_rights));
 #endif
         /*
          * The DARWIN_ACE_DELETE right might implicitly result from write acces to the parent
@@ -1415,10 +1422,10 @@ static int check_acl_access(const struct vol *vol,
             EC_ZERO_LOG_ERR(lstat(cfrombstr(parent), &st), AFPERR_MISC);
 
 #ifdef HAVE_SOLARIS_ACLS
-            EC_ZERO_LOG(solaris_acl_rights(cfrombstr(parent), &st, &parent_rights));
+            EC_ZERO_LOG(solaris_acl_rights(obj, cfrombstr(parent), &st, &parent_rights));
 #endif
 #ifdef HAVE_POSIX_ACLS
-            EC_ZERO_LOG(posix_acl_rights(path, &st, &parent_rights));
+            EC_ZERO_LOG(posix_acl_rights(obj, path, &st, &parent_rights));
 #endif
             if (parent_rights & (DARWIN_ACE_WRITE_DATA | DARWIN_ACE_DELETE_CHILD))
                 allowed_rights |= DARWIN_ACE_DELETE; /* man, that was a lot of work! */
@@ -1508,7 +1515,7 @@ int afp_access(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size
         return AFPERR_NOOBJ;
     }
 
-    ret = check_acl_access(vol, dir, s_path->u_name, uuid, darwin_ace_rights);
+    ret = check_acl_access(obj, vol, dir, s_path->u_name, uuid, darwin_ace_rights);
 
     return ret;
 }
@@ -1716,12 +1723,12 @@ int afp_setacl(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size
  * This is the magic function that makes ACLs usable by calculating
  * the access granted by ACEs to the logged in user.
  */
-int acltoownermode(const struct vol *vol, char *path, struct stat *st, struct maccess *ma)
+int acltoownermode(const AFPObj *obj, const struct vol *vol, char *path, struct stat *st, struct maccess *ma)
 {
     EC_INIT;
     uint32_t rights = 0;
 
-    if ( ! (AFPobj->options.flags & OPTION_ACL2MACCESS)
+    if ( ! (obj->options.flags & OPTION_ACL2MACCESS)
          || ! (vol->v_flags & AFPVOL_ACLS))
          return 0;
 
@@ -1729,7 +1736,7 @@ int acltoownermode(const struct vol *vol, char *path, struct stat *st, struct ma
         getcwdpath(), path, ma->ma_user);
 
 #ifdef HAVE_SOLARIS_ACLS
-    EC_ZERO_LOG(solaris_acl_rights(path, st, &rights));
+    EC_ZERO_LOG(solaris_acl_rights(obj, path, st, &rights));
 
     LOG(log_maxdebug, logtype_afpd, "rights: 0x%08x", rights);
 
@@ -1742,7 +1749,7 @@ int acltoownermode(const struct vol *vol, char *path, struct stat *st, struct ma
 #endif
 
 #ifdef HAVE_POSIX_ACLS
-    EC_ZERO_LOG(posix_acls_to_uaperms(path, st, ma));
+    EC_ZERO_LOG(posix_acls_to_uaperms(obj, path, st, ma));
 #endif
 
     LOG(log_maxdebug, logtype_afpd, "resulting user maccess: 0x%02x group maccess: 0x%02x", ma->ma_user, ma->ma_group);
@@ -1750,39 +1757,3 @@ int acltoownermode(const struct vol *vol, char *path, struct stat *st, struct ma
 EC_CLEANUP:
     EC_EXIT;
 }
-
-/*!
- * Check whether a volume supports ACLs
- *
- * @param vol  (r) volume
- *
- * @returns        0 if not, 1 if yes
- */
-int check_vol_acl_support(const struct vol *vol)
-{
-    int ret = 0;
-
-#ifdef HAVE_SOLARIS_ACLS
-    ace_t *aces = NULL;
-    ret = 1;
-    if (get_nfsv4_acl(vol->v_path, &aces) == -1)
-        ret = 0;
-#endif
-#ifdef HAVE_POSIX_ACLS
-    acl_t acl = NULL;
-    ret = 1;
-    if ((acl = acl_get_file(vol->v_path, ACL_TYPE_ACCESS)) == NULL)
-        ret = 0;
-#endif
-
-#ifdef HAVE_SOLARIS_ACLS
-    if (aces) free(aces);
-#endif
-#ifdef HAVE_POSIX_ACLS
-    if (acl) acl_free(acl);
-#endif /* HAVE_POSIX_ACLS */
-
-    LOG(log_debug, logtype_afpd, "Volume \"%s\" ACL support: %s",
-        vol->v_path, ret ? "yes" : "no");
-    return ret;
-}
index 273a9f13e1cca3cdd31cfc659e1c4cafba6454ed..c48f03a9b4ab6da3b3e7e4c4950f8c7868617ac9 100644 (file)
@@ -109,10 +109,9 @@ int afp_access (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf,  size_t *rb
 int afp_getacl (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf,  size_t *rbuflen);
 int afp_setacl (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf,  size_t *rbuflen);
 
-/* Parse afp_ldap.conf */
+/* Parse afp.conf */
 extern int acl_ldap_readconfig(char *name);
 
 /* Misc funcs */
-extern int acltoownermode(const struct vol *vol, char *path, struct stat *st, struct maccess *ma);
-extern int check_vol_acl_support(const struct vol *vol);
+extern int acltoownermode(const AFPObj *obj, const struct vol *vol, char *path, struct stat *st, struct maccess *ma);
 #endif
diff --git a/etc/afpd/afp_asp.c b/etc/afpd/afp_asp.c
deleted file mode 100644 (file)
index 3e208f7..0000000
+++ /dev/null
@@ -1,421 +0,0 @@
-/*
- * $Id: afp_asp.c,v 1.29 2010-03-09 06:55:12 franklahm Exp $
- *
- * Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu)
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- *
- * modified from main.c. this handles afp over asp. 
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifndef NO_DDP
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <atalk/logger.h>
-#include <errno.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif /* HAVE_SYS_TIME_H */
-#ifdef HAVE_SYS_STAT_H
-#include <sys/stat.h>
-#endif /* HAVE_SYS_STAT_H */
-
-#include <netatalk/endian.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-#include <atalk/compat.h>
-#include <atalk/util.h>
-#include <atalk/globals.h>
-
-#include "switch.h"
-#include "auth.h"
-#include "fork.h"
-
-#ifdef FORCE_UIDGID
-#warning UIDGID
-#include "uid.h"
-#endif /* FORCE_UIDGID */
-
-static AFPObj *child;
-
-static void afp_authprint_remove(AFPObj *);
-
-static void afp_asp_close(AFPObj *obj)
-{
-    ASP asp = obj->handle;
-
-    if (seteuid( obj->uid ) < 0) {
-        LOG(log_error, logtype_afpd, "can't seteuid back %s", strerror(errno));
-        exit(EXITERR_SYS);
-    }
-    close_all_vol();
-    if (obj->options.authprintdir) afp_authprint_remove(obj);
-
-    if (obj->logout)
-        (*obj->logout)();
-
-    LOG(log_info, logtype_afpd, "%.2fKB read, %.2fKB written",
-        asp->read_count / 1024.0, asp->write_count / 1024.0);
-    asp_close( asp );
-}
-
-/* removes the authprint trailing when appropriate */
-static void afp_authprint_remove(AFPObj *obj)
-{
-    ASP asp = obj->handle;
-    char addr_filename[256];
-    char addr_filename_buff[256];
-    struct stat cap_st;
-
-    sprintf(addr_filename, "%s/net%d.%dnode%d", obj->options.authprintdir,
-                ntohs( asp->asp_sat.sat_addr.s_net )/256,
-                ntohs( asp->asp_sat.sat_addr.s_net )%256,
-                asp->asp_sat.sat_addr.s_node );
-
-    memset( addr_filename_buff, 0, 256 );
-
-    if(lstat(addr_filename, &cap_st) == 0) {
-       if( S_ISREG(cap_st.st_mode) ) {
-           int len;
-           int capfd = open( addr_filename, O_RDONLY );
-           if ((len = read( capfd, addr_filename_buff, 256 )) > 0) {
-               int file_pid;
-               char *p_filepid;
-               addr_filename_buff[len] = 0;
-               if ( (p_filepid = strrchr(addr_filename_buff, ':')) != NULL) {
-                   *p_filepid = '\0';
-                   p_filepid++;
-                   file_pid = atoi(p_filepid);
-                   if (file_pid == (int)getpid()) {
-                       if(unlink(addr_filename) == 0) {
-                           LOG(log_info, logtype_afpd, "removed %s", addr_filename);
-                       } else {
-                           LOG(log_info, logtype_afpd, "error removing %s: %s",
-                                   addr_filename, strerror(errno));
-                       }
-                   } else {
-                       LOG(log_info, logtype_afpd, "%s belongs to another pid %d",
-                            addr_filename, file_pid );
-                   }
-               } else { /* no pid info */
-                   if (unlink(addr_filename) == 0) {
-                       LOG(log_info, logtype_afpd, "removed %s", addr_filename );
-                   } else {
-                       LOG(log_info, logtype_afpd, "error removing %s: %s",
-                               addr_filename, strerror(errno));
-                   }
-               }
-           } else {
-               LOG(log_info, logtype_afpd, "couldn't read data from %s", addr_filename );
-           }
-        if (capfd != -1)
-            close(capfd);
-       } else {
-           LOG(log_info, logtype_afpd, "%s is not a regular file", addr_filename );
-       }
-    } else {
-        LOG(log_info, logtype_afpd, "error stat'ing %s: %s",
-                   addr_filename, strerror(errno));
-    }
-}
-
-/* ------------------------
- * SIGTERM
-*/
-static void afp_asp_die(const int sig)
-{
-    ASP asp = child->handle;
-
-    asp_attention(asp, AFPATTN_SHUTDOWN);
-    if ( asp_shutdown( asp ) < 0 ) {
-        LOG(log_error, logtype_afpd, "afp_die: asp_shutdown: %s", strerror(errno) );
-    }
-
-    afp_asp_close(child);
-    if (sig == SIGTERM || sig == SIGALRM)
-        exit( 0 );
-    else
-        exit(sig);
-}
-
-/* -----------------------------
- * SIGUSR1
- */
-static void afp_asp_timedown(int sig _U_)
-{
-    struct sigaction   sv;
-    struct itimerval   it;
-
-    /* shutdown and don't reconnect. server going down in 5 minutes. */
-    asp_attention(child->handle, AFPATTN_SHUTDOWN | AFPATTN_NORECONNECT |
-                  AFPATTN_TIME(5));
-
-    it.it_interval.tv_sec = 0;
-    it.it_interval.tv_usec = 0;
-    it.it_value.tv_sec = 300;
-    it.it_value.tv_usec = 0;
-    if ( setitimer( ITIMER_REAL, &it, NULL ) < 0 ) {
-        LOG(log_error, logtype_afpd, "afp_timedown: setitimer: %s", strerror(errno) );
-        afp_asp_die(EXITERR_SYS);
-    }
-
-    memset(&sv, 0, sizeof(sv));
-    sv.sa_handler = afp_asp_die;
-    sigemptyset( &sv.sa_mask );
-    sigaddset(&sv.sa_mask, SIGHUP);
-    sigaddset(&sv.sa_mask, SIGTERM);
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGALRM, &sv, NULL ) < 0 ) {
-        LOG(log_error, logtype_afpd, "afp_timedown: sigaction: %s", strerror(errno) );
-        afp_asp_die(EXITERR_SYS);
-    }
-
-    /* ignore myself */
-    sv.sa_handler = SIG_IGN;
-    sigemptyset( &sv.sa_mask );
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGUSR1, &sv, NULL ) < 0 ) {
-        LOG(log_error, logtype_afpd, "afp_timedown: sigaction SIGUSR1: %s", strerror(errno) );
-        afp_asp_die(EXITERR_SYS);
-    }
-}
-
-/* ---------------------------------
- * SIGHUP reload configuration file
-*/
-extern volatile int reload_request;
-
-static void afp_asp_reload(int sig _U_)
-{
-    reload_request = 1;
-}
-
-/* ---------------------- */
-#ifdef SERVERTEXT
-static void afp_asp_getmesg (int sig _U_)
-{
-    readmessage(child);
-    asp_attention(child->handle, AFPATTN_MESG | AFPATTN_TIME(5));
-}
-#endif /* SERVERTEXT */
-
-/* ---------------------- */
-void afp_over_asp(AFPObj *obj)
-{
-    ASP asp;
-    struct sigaction  action;
-    int                func,  reply = 0;
-#ifdef DEBUG1
-    int ccnt = 0;
-#endif    
-
-    AFPobj = obj;
-    obj->exit = afp_asp_die;
-    obj->reply = (int (*)()) asp_cmdreply;
-    obj->attention = (int (*)(void *, AFPUserBytes)) asp_attention;
-    child = obj;
-    asp = (ASP) obj->handle;
-
-    /* install signal handlers 
-     * With ASP tickle handler is done in the parent process
-    */
-    memset(&action, 0, sizeof(action));
-
-    /* install SIGHUP */
-    action.sa_handler = afp_asp_reload; 
-    sigemptyset( &action.sa_mask );
-    sigaddset(&action.sa_mask, SIGTERM);
-    sigaddset(&action.sa_mask, SIGUSR1);
-#ifdef SERVERTEXT
-    sigaddset(&action.sa_mask, SIGUSR2);
-#endif    
-    action.sa_flags = SA_RESTART;
-    if ( sigaction( SIGHUP, &action, NULL ) < 0 ) {
-        LOG(log_error, logtype_afpd, "afp_over_asp: sigaction: %s", strerror(errno) );
-        afp_asp_die(EXITERR_SYS);
-    }
-
-    /*  install SIGTERM */
-    action.sa_handler = afp_asp_die;
-    sigemptyset( &action.sa_mask );
-    sigaddset(&action.sa_mask, SIGHUP);
-    sigaddset(&action.sa_mask, SIGUSR1);
-#ifdef SERVERTEXT
-    sigaddset(&action.sa_mask, SIGUSR2);
-#endif    
-    action.sa_flags = SA_RESTART;
-    if ( sigaction( SIGTERM, &action, NULL ) < 0 ) {
-        LOG(log_error, logtype_afpd, "afp_over_asp: sigaction: %s", strerror(errno) );
-        afp_asp_die(EXITERR_SYS);
-    }
-
-#ifdef SERVERTEXT
-    /* Added for server message support */
-    action.sa_handler = afp_asp_getmesg;
-    sigemptyset( &action.sa_mask );
-    sigaddset(&action.sa_mask, SIGTERM);
-    sigaddset(&action.sa_mask, SIGUSR1);
-    sigaddset(&action.sa_mask, SIGHUP);
-    action.sa_flags = SA_RESTART;
-    if ( sigaction( SIGUSR2, &action, NULL) < 0 ) {
-        LOG(log_error, logtype_afpd, "afp_over_asp: sigaction: %s", strerror(errno) );
-        afp_asp_die(EXITERR_SYS);
-    }
-#endif /* SERVERTEXT */
-
-    /*  SIGUSR1 - set down in 5 minutes  */
-    action.sa_handler = afp_asp_timedown; 
-    sigemptyset( &action.sa_mask );
-    sigaddset(&action.sa_mask, SIGHUP);
-    sigaddset(&action.sa_mask, SIGTERM);
-#ifdef SERVERTEXT
-    sigaddset(&action.sa_mask, SIGUSR2);
-#endif    
-    action.sa_flags = SA_RESTART;
-    if ( sigaction( SIGUSR1, &action, NULL ) < 0 ) {
-        LOG(log_error, logtype_afpd, "afp_over_asp: sigaction: %s", strerror(errno) );
-        afp_asp_die(EXITERR_SYS);
-    }
-
-    if (dircache_init(obj->options.dircachesize) != 0) {
-        LOG(log_error, logtype_afpd, "afp_over_asp: dircache_init error");
-        afp_asp_die(EXITERR_SYS);
-    }
-
-    LOG(log_info, logtype_afpd, "session from %u.%u:%u on %u.%u:%u",
-        ntohs( asp->asp_sat.sat_addr.s_net ),
-        asp->asp_sat.sat_addr.s_node, asp->asp_sat.sat_port,
-        ntohs( atp_sockaddr( asp->asp_atp )->sat_addr.s_net ),
-        atp_sockaddr( asp->asp_atp )->sat_addr.s_node,
-        atp_sockaddr( asp->asp_atp )->sat_port );
-
-    while ((reply = asp_getrequest(asp))) {
-        if (reload_request) {
-            reload_request = 0;
-            load_volumes(child);
-        }
-        switch (reply) {
-        case ASPFUNC_CLOSE :
-            afp_asp_close(obj);
-            LOG(log_info, logtype_afpd, "done" );
-
-#ifdef DEBUG1
-            if ( obj->options.flags & OPTION_DEBUG ) {
-                printf( "done\n" );
-            }
-#endif
-            return;
-            break;
-
-        case ASPFUNC_CMD :
-#ifdef AFS
-            if ( writtenfork ) {
-                if ( flushfork( writtenfork ) < 0 ) {
-                    LOG(log_error, logtype_afpd, "main flushfork: %s",
-                                               strerror(errno));
-                }
-                writtenfork = NULL;
-            }
-#endif /* AFS */
-            func = (u_char) asp->commands[0];
-#ifdef DEBUG1
-            if ( obj->options.flags & OPTION_DEBUG ) {
-                printf("command: %d (%s)\n", func, AfpNum2name(func));
-                bprint( asp->commands, asp->cmdlen );
-            }
-#endif            
-            if ( afp_switch[ func ] != NULL ) {
-                /*
-                 * The function called from afp_switch is expected to
-                 * read its parameters out of buf, put its
-                 * results in replybuf (updating rbuflen), and
-                 * return an error code.
-                */
-                asp->datalen = ASP_DATASIZ;
-                reply = (*afp_switch[ func ])(obj,
-                                              asp->commands, asp->cmdlen,
-                                              asp->data, &asp->datalen);
-#ifdef FORCE_UIDGID
-               /* bring everything back to old euid, egid */
-               if (obj->force_uid)
-                   restore_uidgid ( &obj->uidgid );
-#endif /* FORCE_UIDGID */
-            } else {
-                LOG(log_error, logtype_afpd, "bad function %X", func );
-                asp->datalen = 0;
-                reply = AFPERR_NOOP;
-            }
-#ifdef DEBUG1
-            if ( obj->options.flags & OPTION_DEBUG ) {
-                printf( "reply: %d, %d\n", reply, ccnt++ );
-                bprint( asp->data, asp->datalen );
-            }
-#endif
-            if ( asp_cmdreply( asp, reply ) < 0 ) {
-                LOG(log_error, logtype_afpd, "asp_cmdreply: %s", strerror(errno) );
-                afp_asp_die(EXITERR_CLNT);
-            }
-            break;
-
-        case ASPFUNC_WRITE :
-            func = (u_char) asp->commands[0];
-#ifdef DEBUG1
-            if ( obj->options.flags & OPTION_DEBUG ) {
-                printf( "(write) command: %d\n", func );
-                bprint( asp->commands, asp->cmdlen );
-            }
-#endif
-            if ( afp_switch[ func ] != NULL ) {
-                asp->datalen = ASP_DATASIZ;
-                reply = (*afp_switch[ func ])(obj,
-                                              asp->commands, asp->cmdlen,
-                                              asp->data, &asp->datalen);
-#ifdef FORCE_UIDGID
-               /* bring everything back to old euid, egid */
-               if (obj->force_uid)
-                   restore_uidgid ( &obj->uidgid );
-#endif /* FORCE_UIDGID */
-            } else {
-                LOG(log_error, logtype_afpd, "(write) bad function %X", func );
-                asp->datalen = 0;
-                reply = AFPERR_NOOP;
-            }
-#ifdef DEBUG1
-            if ( obj->options.flags & OPTION_DEBUG ) {
-                printf( "(write) reply code: %d, %d\n", reply, ccnt++ );
-                bprint( asp->data, asp->datalen );
-            }
-#endif
-            if ( asp_wrtreply( asp, reply ) < 0 ) {
-                LOG(log_error, logtype_afpd, "asp_wrtreply: %s", strerror(errno) );
-                afp_asp_die(EXITERR_CLNT);
-            }
-            break;
-        default:
-            /*
-               * Bad asp packet.  Probably should have asp filter them,
-               * since they are typically things like out-of-order packet.
-               */
-            LOG(log_info, logtype_afpd, "main: asp_getrequest: %d", reply );
-            break;
-        }
-#ifdef DEBUG1
-        if ( obj->options.flags & OPTION_DEBUG ) {
-#ifdef notdef
-            pdesc( stdout );
-#endif /* notdef */
-            of_pforkdesc( stdout );
-            fflush( stdout );
-        }
-#endif
-    }
-}
-
-#endif
index 83f73ff717195c8475c135181896964719334953..5218d51758aebb0554298465c34c63436c67d541 100644 (file)
 #include <atalk/util.h>
 #include <atalk/dsi.h>
 #include <atalk/unicode.h>
+#include <atalk/netatalk_conf.h>
 
 #include "afp_zeroconf.h"
 #include "afp_avahi.h"
-#include "afp_config.h"
-#include "volume.h"
 
 /*****************************************************************
  * Global variables
@@ -45,7 +44,6 @@ static void publish_reply(AvahiEntryGroup *g,
  */
 static void register_stuff(void) {
     uint port;
-    const AFPConfig *config;
     const struct vol *volume;
     DSI *dsi;
     char name[MAXINSTANCENAMELEN+1];
@@ -93,20 +91,18 @@ static void register_stuff(void) {
         }
 
         /* AFP server */
-        for (config = ctx->configs; config; config = config->next) {
-
-            dsi = (DSI *)config->obj.handle;
+        for (dsi = ctx->obj->dsi; dsi; dsi = dsi->next) {
             port = getip_port((struct sockaddr *)&dsi->server);
 
-            if (convert_string(config->obj.options.unixcharset,
+            LOG(log_info, logtype_afpd, "hostname: %s", ctx->obj->options.hostname);
+
+            if (convert_string(ctx->obj->options.unixcharset,
                                CH_UTF8,
-                               config->obj.options.server ?
-                               config->obj.options.server :
-                               config->obj.options.hostname,
+                               ctx->obj->options.hostname,
                                -1,
                                name,
                                MAXINSTANCENAMELEN) <= 0) {
-                LOG(log_error, logtype_afpd, "Could not set Zeroconf instance name");
+                LOG(log_error, logtype_afpd, "Could not set Zeroconf instance name: %s", ctx->obj->options.hostname);
                 goto fail;
             }
             if ((dsi->bonjourname = strdup(name)) == NULL) {
@@ -147,8 +143,8 @@ static void register_stuff(void) {
                 goto fail;
             }  /* if */
 
-            if (config->obj.options.mimicmodel) {
-                strlist2 = avahi_string_list_add_printf(strlist2, "model=%s", config->obj.options.mimicmodel);
+            if (ctx->obj->options.mimicmodel) {
+                strlist2 = avahi_string_list_add_printf(strlist2, "model=%s", ctx->obj->options.mimicmodel);
                 if (avahi_entry_group_add_service_strlst(ctx->group,
                                                          AVAHI_IF_UNSPEC,
                                                          AVAHI_PROTO_UNSPEC,
@@ -279,7 +275,7 @@ static void client_callback(AvahiClient *client,
  * Tries to setup the Zeroconf thread and any
  * neccessary config setting.
  */
-void av_zeroconf_register(const AFPConfig *configs) {
+void av_zeroconf_register(const AFPObj *obj) {
     int error;
 
     /* initialize the struct that holds our config settings. */
@@ -288,7 +284,7 @@ void av_zeroconf_register(const AFPConfig *configs) {
         avahi_entry_group_reset(ctx->group);
     } else {
         ctx = calloc(1, sizeof(struct context));
-        ctx->configs = configs;
+        ctx->obj = obj;
         assert(ctx);
     }
 
index 9a6563ba8f75d89782fe6d2ab589f8b5dc468f89..ae3366db506c59680a73b39a848e67a15c1a2ade 100644 (file)
@@ -31,11 +31,11 @@ struct context {
   AvahiClient       *client;
   AvahiEntryGroup   *group;
        /* Netatalk stuff */
-       const AFPConfig   *configs;
+       const AFPObj      *obj;
 };
 
 /* prototype definitions */
-void av_zeroconf_register(const AFPConfig *configs);
+void av_zeroconf_register(const AFPObj *obj);
 int av_zeroconf_unregister(void);
 
 #endif   /* AFPD_AVAHI_H */
index 29b552d38b641fb77e5ddc131d5138dadd3998c3..a61fe1022f551ccc84b9fef03c860cfe16c51a30 100644 (file)
 #include <netinet/in.h>
 #include <arpa/inet.h>
 
-#ifdef USE_SRVLOC
-#include <slp.h>
-#endif /* USE_SRVLOC */
-
 #include <atalk/logger.h>
 #include <atalk/util.h>
 #include <atalk/dsi.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-#include <atalk/nbp.h>
 #include <atalk/afp.h>
 #include <atalk/compat.h>
 #include <atalk/server_child.h>
+#include <atalk/globals.h>
+#include <atalk/errchk.h>
+#include <atalk/netatalk_conf.h>
+#include <atalk/fce_api.h>
 
 #ifdef HAVE_LDAP
 #include <atalk/ldapconfig.h>
 #endif
 
-#include <atalk/globals.h>
 #include "afp_config.h"
 #include "uam_auth.h"
 #include "status.h"
 #include "volume.h"
 #include "afp_zeroconf.h"
 
-#define LINESIZE 1024  
 
-/* get rid of unneeded configurations. i use reference counts to deal
- * w/ multiple configs sharing the same afp_options. oh, to dream of
- * garbage collection ... */
-void configfree(AFPConfig *configs, const AFPConfig *config)
+/*!
+ * Free and cleanup all linked DSI objects from config
+ *
+ * Preserve object pointed to by "dsi".
+ * "dsi" can be NULL in which case all DSI objects _and_ the options object are freed 
+ */
+void configfree(AFPObj *obj, DSI *dsi)
 {
-    AFPConfig *p, *q;
+    DSI *p, *q;
 
-    for (p = configs; p; p = q) {
+    /* the master loaded the volumes for zeroconf, get rid of that */
+    unload_volumes(obj);
+
+    for (p = obj->dsi; p; p = q) {
         q = p->next;
-        if (p == config)
+        if (p == dsi)
             continue;
-
-        /* do a little reference counting */
-        if (--(*p->optcount) < 1) {
-            afp_options_free(&p->obj.options, p->defoptions);
-            free(p->optcount);
-        }
-
-        switch (p->obj.proto) {
-#ifndef NO_DDP
-        case AFPPROTO_ASP:
-            free(p->obj.Obj);
-            free(p->obj.Type);
-            free(p->obj.Zone);
-            atp_close(((ASP) p->obj.handle)->asp_atp);
-            free(p->obj.handle);
-            break;
-#endif /* no afp/asp */
-        case AFPPROTO_DSI:
-            close(p->fd);
-            free(p->obj.handle);
-            break;
-        }
+        close(p->socket);
         free(p);
     }
 
-    /* the master loaded the volumes for zeroconf, get rid of that */
-    unload_volumes_and_extmap();
-}
-
-#ifdef USE_SRVLOC
-static void SRVLOC_callback(SLPHandle hslp _U_, SLPError errcode, void *cookie) {
-    *(SLPError*)cookie = errcode;
-}
-
-static char hex[17] = "0123456789abcdef";
-
-static char * srvloc_encode(const struct afp_options *options, const char *name)
-{
-       static char buf[512];
-       char *conv_name;
-       unsigned char *p;
-       unsigned int i = 0;
-#ifndef NO_DDP
-       char *Obj, *Type = "", *Zone = "";
-#endif
-
-       /* Convert name to maccharset */
-        if ((size_t)-1 ==(convert_string_allocate( options->unixcharset, options->maccharset,
-                        name, -1, &conv_name)) )
-               return (char*)name;
-
-       /* Escape characters */
-       p = conv_name;
-       while (*p && i<(sizeof(buf)-4)) {
-           if (*p == '@')
-               break;
-           else if (isspace(*p)) {
-               buf[i++] = '%';
-               buf[i++] = '2';
-               buf[i++] = '0';
-               p++;
-           }   
-           else if ((!isascii(*p)) || *p <= 0x2f || *p == 0x3f ) {
-               buf[i++] = '%';
-               buf[i++] = hex[*p >> 4];
-               buf[i++] = hex[*p++ & 15];
-           }
-           else {
-               buf[i++] = *p++;
-           }
-       }
-       buf[i] = '\0';
-
-#ifndef NO_DDP
-       /* Add ZONE,  */
-        if (nbp_name(options->server, &Obj, &Type, &Zone )) {
-               LOG(log_error, logtype_afpd, "srvloc_encode: can't parse %s", options->server );
-       }
-       else {
-               snprintf( buf+i, sizeof(buf)-i-1 ,"&ZONE=%s", Zone);
-       }
-#endif
-       free (conv_name);
-
-       return buf;
-}
-#endif /* USE_SRVLOC */
-
-static void dsi_cleanup(const AFPConfig *config)
-{
-#ifdef USE_SRVLOC
-    SLPError err;
-    SLPError callbackerr;
-    SLPHandle hslp;
-    DSI *dsi = (DSI *)config->obj.handle;
-
-    /*  Do nothing if we didn't register.  */
-    if (!dsi || dsi->srvloc_url[0] == '\0')
-        return;
-
-    err = SLPOpen("en", SLP_FALSE, &hslp);
-    if (err != SLP_OK) {
-        LOG(log_error, logtype_afpd, "dsi_cleanup: Error opening SRVLOC handle");
-        goto srvloc_dereg_err;
-    }
-
-    err = SLPDereg(hslp,
-                   dsi->srvloc_url,
-                   SRVLOC_callback,
-                   &callbackerr);
-    if (err != SLP_OK) {
-        LOG(log_error, logtype_afpd, "dsi_cleanup: Error unregistering %s from SRVLOC", dsi->srvloc_url);
-        goto srvloc_dereg_err;
-    }
-
-    if (callbackerr != SLP_OK) {
-        LOG(log_error, logtype_afpd, "dsi_cleanup: Error in callback while trying to unregister %s from SRVLOC (%d)", dsi->srvloc_url, callbackerr);
-        goto srvloc_dereg_err;
-    }
-
-srvloc_dereg_err:
-    dsi->srvloc_url[0] = '\0';
-    SLPClose(hslp);
-#endif /* USE_SRVLOC */
-}
-
-#ifndef NO_DDP
-static void asp_cleanup(const AFPConfig *config)
-{
-    /* we need to stop tickle handler */
-    asp_stop_tickle();
-    nbp_unrgstr(config->obj.Obj, config->obj.Type, config->obj.Zone,
-                &config->obj.options.ddpaddr);
-}
-
-/* these two are almost identical. it should be possible to collapse them
- * into one with minimal junk. */
-static int asp_start(AFPConfig *config, AFPConfig *configs,
-                     server_child *server_children)
-{
-    ASP asp;
-
-    if (!(asp = asp_getsession(config->obj.handle, server_children,
-                               config->obj.options.tickleval))) {
-        LOG(log_error, logtype_afpd, "main: asp_getsession: %s", strerror(errno) );
-        exit( EXITERR_CLNT );
-    }
-
-    if (asp->child) {
-        configfree(configs, config); /* free a bunch of stuff */
-        afp_over_asp(&config->obj);
-        exit (0);
-    }
-
-    return 0;
-}
-#endif /* no afp/asp */
-
-static afp_child_t *dsi_start(AFPConfig *config, AFPConfig *configs,
-                              server_child *server_children)
-{
-    DSI *dsi = config->obj.handle;
-    afp_child_t *child = NULL;
-
-    if (!(child = dsi_getsession(dsi,
-                                 server_children,
-                                 config->obj.options.tickleval))) {
-        /* we've forked. */
-        configfree(configs, config);
-        afp_over_dsi(&config->obj); /* start a session */
-        exit (0);
-    }
-
-    return child;
-}
-
-#ifndef NO_DDP
-static AFPConfig *ASPConfigInit(const struct afp_options *options,
-                                unsigned char *refcount)
-{
-    AFPConfig *config;
-    ATP atp;
-    ASP asp;
-    char *Obj, *Type = "AFPServer", *Zone = "*";
-    char *convname = NULL;
-
-    if ((config = (AFPConfig *) calloc(1, sizeof(AFPConfig))) == NULL)
-        return NULL;
-
-    if ((atp = atp_open(ATADDR_ANYPORT, &options->ddpaddr)) == NULL)  {
-        LOG(log_error, logtype_afpd, "main: atp_open: %s", strerror(errno) );
-        free(config);
-        return NULL;
-    }
-
-    if ((asp = asp_init( atp )) == NULL) {
-        LOG(log_error, logtype_afpd, "main: asp_init: %s", strerror(errno) );
-        atp_close(atp);
-        free(config);
-        return NULL;
-    }
-
-    /* register asp server */
-    Obj = (char *) options->hostname;
-    if (options->server && (size_t)-1 ==(convert_string_allocate( options->unixcharset, options->maccharset,
-                         options->server, strlen(options->server), &convname)) ) {
-        if ((convname = strdup(options->server)) == NULL ) {
-            LOG(log_error, logtype_afpd, "malloc: %s", strerror(errno) );
-            goto serv_free_return;
-        }
-    }
-
-    if (nbp_name(convname, &Obj, &Type, &Zone )) {
-        LOG(log_error, logtype_afpd, "main: can't parse %s", options->server );
-        goto serv_free_return;
-    }
-    if (convname)
-        free (convname);
-
-    /* dup Obj, Type and Zone as they get assigned to a single internal
-     * buffer by nbp_name */
-    if ((config->obj.Obj  = strdup(Obj)) == NULL)
-        goto serv_free_return;
-
-    if ((config->obj.Type = strdup(Type)) == NULL) {
-        free(config->obj.Obj);
-        goto serv_free_return;
-    }
-
-    if ((config->obj.Zone = strdup(Zone)) == NULL) {
-        free(config->obj.Obj);
-        free(config->obj.Type);
-        goto serv_free_return;
-    }
-
-    /* make sure we're not registered */
-    nbp_unrgstr(Obj, Type, Zone, &options->ddpaddr);
-    if (nbp_rgstr( atp_sockaddr( atp ), Obj, Type, Zone ) < 0 ) {
-        LOG(log_error, logtype_afpd, "Can't register %s:%s@%s", Obj, Type, Zone );
-        free(config->obj.Obj);
-        free(config->obj.Type);
-        free(config->obj.Zone);
-        goto serv_free_return;
-    }
-
-    LOG(log_info, logtype_afpd, "%s:%s@%s started on %u.%u:%u (%s)", Obj, Type, Zone,
-        ntohs( atp_sockaddr( atp )->sat_addr.s_net ),
-        atp_sockaddr( atp )->sat_addr.s_node,
-        atp_sockaddr( atp )->sat_port, VERSION );
-
-    config->fd = atp_fileno(atp);
-    config->obj.handle = asp;
-    config->obj.config = config;
-    config->obj.proto = AFPPROTO_ASP;
-
-    memcpy(&config->obj.options, options, sizeof(struct afp_options));
-    config->optcount = refcount;
-    (*refcount)++;
-
-    config->server_start = asp_start;
-    config->server_cleanup = asp_cleanup;
-
-    return config;
-
-serv_free_return:
-                    asp_close(asp);
-    free(config);
-    return NULL;
-}
-#endif /* no afp/asp */
-
-
-static AFPConfig *DSIConfigInit(const struct afp_options *options,
-                                unsigned char *refcount,
-                                const dsi_proto protocol)
-{
-    AFPConfig *config;
-    DSI *dsi;
-    char *p, *q;
-
-    if ((config = (AFPConfig *) calloc(1, sizeof(AFPConfig))) == NULL) {
-        LOG(log_error, logtype_afpd, "DSIConfigInit: malloc(config): %s", strerror(errno) );
-        return NULL;
-    }
-
-    LOG(log_debug, logtype_afpd, "DSIConfigInit: hostname: %s, ip/port: %s/%s, ",
-        options->hostname,
-        options->ipaddr ? options->ipaddr : "default",
-        options->port ? options->port : "548");
-
-    if ((dsi = dsi_init(protocol, "afpd", options->hostname,
-                        options->ipaddr, options->port,
-                        options->flags & OPTION_PROXY,
-                        options->server_quantum)) == NULL) {
-        LOG(log_error, logtype_afpd, "main: dsi_init: %s", strerror(errno) );
-        free(config);
-        return NULL;
-    }
-    dsi->dsireadbuf = options->dsireadbuf;
-
-    if (options->flags & OPTION_PROXY) {
-        LOG(log_note, logtype_afpd, "AFP/TCP proxy initialized for %s:%d (%s)",
-            getip_string((struct sockaddr *)&dsi->server), getip_port((struct sockaddr *)&dsi->server), VERSION);
+    if (dsi) {
+        dsi->next = NULL;
+        obj->dsi = dsi;
     } else {
-        LOG(log_note, logtype_afpd, "AFP/TCP started, advertising %s:%d (%s)",
-            getip_string((struct sockaddr *)&dsi->server), getip_port((struct sockaddr *)&dsi->server), VERSION);
+        afp_options_free(&obj->options);
     }
-
-#ifdef USE_SRVLOC
-    dsi->srvloc_url[0] = '\0'; /*  Mark that we haven't registered.  */
-    if (!(options->flags & OPTION_NOSLP)) {
-        SLPError err;
-        SLPError callbackerr;
-        SLPHandle hslp;
-        unsigned int afp_port;
-        int   l;
-        char *srvloc_hostname;
-        const char *hostname;
-
-       err = SLPOpen("en", SLP_FALSE, &hslp);
-       if (err != SLP_OK) {
-           LOG(log_error, logtype_afpd, "DSIConfigInit: Error opening SRVLOC handle");
-           goto srvloc_reg_err;
-       }
-
-       /* XXX We don't want to tack on the port number if we don't have to.
-        * Why?
-        * Well, this seems to break MacOS < 10.  If the user _really_ wants to
-        * use a non-default port, they can, but be aware, this server might
-        * not show up int the Network Browser.
-        */
-       afp_port = getip_port((struct sockaddr *)&dsi->server);
-       /* If specified use the FQDN to register with srvloc, otherwise use IP. */
-       p = NULL;
-       if (options->fqdn) {
-           hostname = options->fqdn;
-           p = strchr(hostname, ':');
-       }       
-       else 
-           hostname = getip_string((struct sockaddr *)&dsi->server);
-
-       srvloc_hostname = srvloc_encode(options, (options->server ? options->server : options->hostname));
-
-       if ((p) || afp_port == 548) {
-           l = snprintf(dsi->srvloc_url, sizeof(dsi->srvloc_url), "afp://%s/?NAME=%s", hostname, srvloc_hostname);
-       }
-       else {
-           l = snprintf(dsi->srvloc_url, sizeof(dsi->srvloc_url), "afp://%s:%d/?NAME=%s", hostname, afp_port, srvloc_hostname);
-       }
-
-       if (l == -1 || l >= (int)sizeof(dsi->srvloc_url)) {
-           LOG(log_error, logtype_afpd, "DSIConfigInit: Hostname is too long for SRVLOC");
-           dsi->srvloc_url[0] = '\0';
-           goto srvloc_reg_err;
-       }
-
-       err = SLPReg(hslp,
-                    dsi->srvloc_url,
-                    SLP_LIFETIME_MAXIMUM,
-                    "afp",
-                    "",
-                    SLP_TRUE,
-                    SRVLOC_callback,
-                    &callbackerr);
-       if (err != SLP_OK) {
-           LOG(log_error, logtype_afpd, "DSIConfigInit: Error registering %s with SRVLOC", dsi->srvloc_url);
-           dsi->srvloc_url[0] = '\0';
-           goto srvloc_reg_err;
-       }
-
-       if (callbackerr != SLP_OK) {
-           LOG(log_error, logtype_afpd, "DSIConfigInit: Error in callback trying to register %s with SRVLOC", dsi->srvloc_url);
-           dsi->srvloc_url[0] = '\0';
-           goto srvloc_reg_err;
-       }
-
-       LOG(log_info, logtype_afpd, "Sucessfully registered %s with SRVLOC", dsi->srvloc_url);
-       config->server_cleanup = dsi_cleanup;
-
-srvloc_reg_err:
-       SLPClose(hslp);
-    }
-#endif /* USE_SRVLOC */
-
-    config->fd = dsi->serversock;
-    config->obj.handle = dsi;
-    dsi->AFPobj = &config->obj;
-    config->obj.config = config;
-    config->obj.proto = AFPPROTO_DSI;
-
-    memcpy(&config->obj.options, options, sizeof(struct afp_options));
-    /* get rid of any appletalk info. we use the fact that the DSI
-     * stuff is done after the ASP stuff. */
-    p = config->obj.options.server;
-    if (p && (q = strchr(p, ':')))
-        *q = '\0';
-
-    config->optcount = refcount;
-    (*refcount)++;
-
-    config->server_start = dsi_start;
-    return config;
 }
 
-/* allocate server configurations. this should really store the last
- * entry in config->last or something like that. that would make
- * supporting multiple dsi transports easier. */
-static AFPConfig *AFPConfigInit(struct afp_options *options,
-                                const struct afp_options *defoptions)
+/*!
+ * Get everything running
+ */
+int configinit(AFPObj *obj)
 {
-    AFPConfig *config = NULL, *next = NULL;
-    unsigned char *refcount;
-
-    if ((refcount = (unsigned char *)
-                    calloc(1, sizeof(unsigned char))) == NULL) {
-        LOG(log_error, logtype_afpd, "AFPConfigInit: calloc(refcount): %s", strerror(errno) );
-        return NULL;
-    }
-
-#ifndef NO_DDP
-    /* handle asp transports */
-    if ((options->transports & AFPTRANS_DDP) &&
-            (config = ASPConfigInit(options, refcount)))
-        config->defoptions = defoptions;
-#endif /* NO_DDP */
-
-
-    /* set signature */
-    set_signature(options);
+    EC_INIT;
+    DSI *dsi, **next = &obj->dsi;
+    char *p = NULL, *q = NULL, *savep;
+    const char *r;
 
-    /* handle dsi transports and dsi proxies. we only proxy
-     * for DSI connections. */
+    auth_load(obj->options.uampath, obj->options.uamlist);
+    set_signature(&obj->options);
 
-    /* this should have something like the following:
-     * for (i=mindsi; i < maxdsi; i++)
-     *   if (options->transports & (1 << i) && 
-     *     (next = DSIConfigInit(options, refcount, i)))
-     *     next->defoptions = defoptions;
-     */
-    if ((options->transports & AFPTRANS_TCP) &&
-            (((options->flags & OPTION_PROXY) == 0) ||
-             ((options->flags & OPTION_PROXY) && config))
-            && (next = DSIConfigInit(options, refcount, DSI_TCPIP)))
-        next->defoptions = defoptions;
+    LOG(log_debug, logtype_afpd, "DSIConfigInit: hostname: %s, listen: %s, port: %s",
+        obj->options.hostname,
+        obj->options.listen ? obj->options.listen : "(default: hostname)",
+        obj->options.port);
 
-    /* load in all the authentication modules. we can load the same
-       things multiple times if necessary. however, loading different
-       things with the same names will cause complaints. by not loading
-       in any uams with proxies, we prevent ddp connections from succeeding.
-    */
-    auth_load(options->uampath, options->uamlist);
+    /* obj->options->listen is of the from "IP[:port][,IP:[PORT], ...]" */
+    /* obj->options->port is the default port to listen (548) */
 
-    /* this should be able to accept multiple dsi transports. i think
-     * the only thing that gets affected is the net addresses. */
-    status_init(config, next, options);
-
-    /* attach dsi config to tail of asp config */
-    if (config) {
-        config->next = next;
-        return config;
+    if (obj->options.listen) {
+        EC_NULL( q = p = strdup(obj->options.listen) );
+        EC_NULL( p = strtok_r(p, ", ", &savep) );
     }
 
-    return next;
-}
-
-/* fill in the appropriate bits for each interface */
-AFPConfig *configinit(struct afp_options *cmdline)
-{
-    FILE *fp;
-    char buf[LINESIZE + 1], *p, have_option = 0;
-    size_t len;
-    struct afp_options options;
-    AFPConfig *config=NULL, *first = NULL; 
-
-    /* if config file doesn't exist, load defaults */
-    if ((fp = fopen(cmdline->configfile, "r")) == NULL)
-    {
-        LOG(log_debug, logtype_afpd, "ConfigFile %s not found, assuming defaults",
-            cmdline->configfile);
-        return AFPConfigInit(cmdline, cmdline);
-    }
-
-    /* scan in the configuration file */
-    len = 0;
-    while (!feof(fp)) {
-       if (!fgets(&buf[len], LINESIZE - len, fp) || buf[len] == '#')
-            continue;
-       len = strlen(buf);
-       if ( len >= 2 && buf[len-2] == '\\' ) {
-           len -= 2;
-           continue;
-       } else
-           len = 0;
-
-        /* a little pre-processing to get rid of spaces and end-of-lines */
-        p = buf;
-        while (p && isspace(*p))
-            p++;
-        if (!p || (*p == '\0'))
-            continue;
+    while (1) {
+        if ((dsi = dsi_init(obj, obj->options.hostname, p, obj->options.port)) == NULL)
+            break;
 
-        have_option = 1;
+        status_init(obj, dsi);
+        *next = dsi;
+        next = &dsi->next;
+        dsi->AFPobj = obj;
 
-        memcpy(&options, cmdline, sizeof(options));
-        if (!afp_options_parseline(p, &options))
-            continue;
+        LOG(log_note, logtype_afpd, "Netatalk AFP/TCP listening on %s:%d",
+            getip_string((struct sockaddr *)&dsi->server),
+            getip_port((struct sockaddr *)&dsi->server));
 
-        /* AFPConfigInit can return two linked configs due to DSI and ASP */
-        if (!first) {
-            if ((first = AFPConfigInit(&options, cmdline)))
-                config = first->next ? first->next : first;
-        } else if ((config->next = AFPConfigInit(&options, cmdline))) {
-            config = config->next->next ? config->next->next : config->next;
-        }
+        if (p)
+            /* p is NULL if ! obj->options.listen */
+            p = strtok_r(NULL, ", ", &savep);
+        if (!p)
+            break;
     }
 
 #ifdef HAVE_LDAP
-    /* Parse afp_ldap.conf */
-    acl_ldap_readconfig(_PATH_ACL_LDAPCONF);
+    /* Parse afp.conf */
+    acl_ldap_readconfig(obj->iniconfig);
 #endif /* HAVE_LDAP */
 
-    LOG(log_debug, logtype_afpd, "Finished parsing Config File");
-    fclose(fp);
-
-    if (!have_option)
-        first = AFPConfigInit(cmdline, cmdline);
-
     /* Now register with zeroconf, we also need the volumes for that */
-    if (first && !(first->obj.options.flags & OPTION_NOZEROCONF)) {
-        load_volumes(&first->obj);
-        zeroconf_register(first);
+    if (! (obj->options.flags & OPTION_NOZEROCONF)) {
+        load_volumes(obj, NULL);
+        zeroconf_register(obj);
+    }
+
+    if ((r = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "fce listener", NULL))) {
+               LOG(log_note, logtype_afpd, "Adding FCE listener: %s", r);
+               fce_add_udp_socket(r);
+    }
+    if ((r = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "fce coalesce", NULL))) {
+               LOG(log_note, logtype_afpd, "Fce coalesce: %s", r);
+               fce_set_coalesce(r);
+    }
+    if ((r = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "fce events", NULL))) {
+               LOG(log_note, logtype_afpd, "Fce events: %s", r);
+               fce_set_events(r);
     }
 
-    return first;
+EC_CLEANUP:
+    if (q)
+        free(q);
+    EC_EXIT;
 }
index 7d5c482a16951a17c4e87923a099b8d5069b0c14..bfa93c73d4a6dba22c23a3e95efb21597231daf8 100644 (file)
@@ -1,31 +1,11 @@
-/*
- * $Id: afp_config.h,v 1.5 2009-10-13 22:55:36 didg Exp $
- */
-
 #ifndef AFPD_CONFIG_H
 #define AFPD_CONFIG_H 1
 
-#ifdef HAVE_SYS_CDEFS_H
-#include <sys/cdefs.h>
-#endif /* HAVE_SYS_CDEFS_H */
-
 #include <atalk/server_child.h>
-#include <atalk/atp.h>
 #include <atalk/globals.h>
+#include <atalk/dsi.h>
 
-typedef struct AFPConfig {
-    AFPObj obj;
-    int fd, statuslen;
-    unsigned char *optcount;
-    char status[1400];
-    const void *defoptions, *signature;
-    afp_child_t *(*server_start) (struct AFPConfig *, struct AFPConfig *,
-                             server_child *);
-    void (*server_cleanup) (const struct AFPConfig *);
-    struct AFPConfig *next;
-} AFPConfig;
-
-extern AFPConfig *configinit (struct afp_options *);
-extern void configfree (AFPConfig *, const AFPConfig *);
+extern int configinit (AFPObj *);
+extern void configfree (AFPObj *, DSI *);
 
 #endif
index 7779b2307f9ca16f8dbda74b8587e8391d5950ad..8b1b1a8d7ce98624b41b0e0ae8edf22eaa195a06 100644 (file)
 #include <atalk/paths.h>
 #include <atalk/server_ipc.h>
 #include <atalk/fce_api.h>
-
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
+
 #include "switch.h"
 #include "auth.h"
 #include "fork.h"
 #include "dircache.h"
 
-#ifdef FORCE_UIDGID
-#warning UIDGID
-#include "uid.h"
-#endif /* FORCE_UIDGID */
-
 #ifndef SOL_TCP
 #define SOL_TCP IPPROTO_TCP
 #endif
@@ -79,7 +75,7 @@ static rc_elem_t replaycache[REPLAYCACHE_SIZE];
 static sigjmp_buf recon_jmp;
 static void afp_dsi_close(AFPObj *obj)
 {
-    DSI *dsi = obj->handle;
+    DSI *dsi = obj->dsi;
     sigset_t sigs;
     
     close(obj->ipc_fd);
@@ -97,8 +93,7 @@ static void afp_dsi_close(AFPObj *obj)
         }
     }
 
-    close_all_vol();
-
+    close_all_vol(obj);
     if (obj->logout) {
         /* Block sigs, PAM/systemd/whoever might send us a SIG??? in (*obj->logout)() -> pam_close_session() */
         sigfillset(&sigs);
@@ -119,7 +114,7 @@ static void afp_dsi_close(AFPObj *obj)
  */
 static void afp_dsi_die(int sig)
 {
-    DSI *dsi = (DSI *)AFPobj->handle;
+    DSI *dsi = (DSI *)AFPobj->dsi;
 
     if (dsi->flags & DSI_RECONINPROG) {
         /* Primary reconnect succeeded, got SIGTERM from afpd parent */
@@ -132,7 +127,7 @@ static void afp_dsi_die(int sig)
         exit(0);
     }
 
-    dsi_attention(AFPobj->handle, AFPATTN_SHUTDOWN);
+    dsi_attention(AFPobj->dsi, AFPATTN_SHUTDOWN);
     afp_dsi_close(AFPobj);
    if (sig) /* if no signal, assume dieing because logins are disabled &
                 don't log it (maintenance mode)*/
@@ -148,7 +143,7 @@ static void afp_dsi_die(int sig)
 /* SIGQUIT handler */
 static void ipc_reconnect_handler(int sig _U_)
 {
-    DSI *dsi = (DSI *)AFPobj->handle;
+    DSI *dsi = (DSI *)AFPobj->dsi;
 
     if (reconnect_ipc(AFPobj) != 0) {
         LOG(log_error, logtype_afpd, "ipc_reconnect_handler: failed IPC reconnect");
@@ -169,7 +164,7 @@ static void afp_dsi_transfer_session(int sig _U_)
 {
     uint16_t dsiID;
     int socket;
-    DSI *dsi = (DSI *)AFPobj->handle;
+    DSI *dsi = (DSI *)AFPobj->dsi;
 
     LOG(log_debug, logtype_afpd, "afp_dsi_transfer_session: got SIGURG, trying to receive session");
 
@@ -220,13 +215,13 @@ static void afp_dsi_timedown(int sig _U_)
 {
     struct sigaction   sv;
     struct itimerval   it;
-    DSI                 *dsi = (DSI *)AFPobj->handle;
+    DSI                 *dsi = (DSI *)AFPobj->dsi;
     dsi->flags |= DSI_DIE;
     /* shutdown and don't reconnect. server going down in 5 minutes. */
     setmessage("The server is going down for maintenance.");
-    if (dsi_attention(AFPobj->handle, AFPATTN_SHUTDOWN | AFPATTN_NORECONNECT |
+    if (dsi_attention(AFPobj->dsi, AFPATTN_SHUTDOWN | AFPATTN_NORECONNECT |
                   AFPATTN_MESG | AFPATTN_TIME(5)) < 0) {
-        DSI *dsi = (DSI *)AFPobj->handle;
+        DSI *dsi = (DSI *)AFPobj->dsi;
         dsi->down_request = 1;
     }                  
 
@@ -283,17 +278,17 @@ static void afp_dsi_debug(int sig _U_)
 /* ---------------------- */
 static void afp_dsi_getmesg (int sig _U_)
 {
-    DSI *dsi = (DSI *)AFPobj->handle;
+    DSI *dsi = (DSI *)AFPobj->dsi;
 
     dsi->msg_request = 1;
-    if (dsi_attention(AFPobj->handle, AFPATTN_MESG | AFPATTN_TIME(5)) < 0)
+    if (dsi_attention(AFPobj->dsi, AFPATTN_MESG | AFPATTN_TIME(5)) < 0)
         dsi->msg_request = 2;
 }
 
 static void alarm_handler(int sig _U_)
 {
     int err;
-    DSI *dsi = (DSI *)AFPobj->handle;
+    DSI *dsi = (DSI *)AFPobj->dsi;
 
     /* we have to restart the timer because some libraries may use alarm() */
     setitimer(ITIMER_REAL, &dsi->timer, NULL);
@@ -347,7 +342,7 @@ static void alarm_handler(int sig _U_)
 
     if ((err = pollvoltime(AFPobj)) == 0)
         LOG(log_debug, logtype_afpd, "afp_alarm: sending DSI tickle");
-        err = dsi_tickle(AFPobj->handle);
+        err = dsi_tickle(AFPobj->dsi);
     if (err <= 0) {
         if (geteuid() == 0) {
             LOG(log_note, logtype_afpd, "afp_alarm: unauthenticated user, connection problem");
@@ -371,14 +366,14 @@ static void pending_request(DSI *dsi)
     if (dsi->msg_request) {
         if (dsi->msg_request == 2) {
             /* didn't send it in signal handler */
-            dsi_attention(AFPobj->handle, AFPATTN_MESG | AFPATTN_TIME(5));
+            dsi_attention(AFPobj->dsi, AFPATTN_MESG | AFPATTN_TIME(5));
         }
         dsi->msg_request = 0;
         readmessage(AFPobj);
     }
     if (dsi->down_request) {
         dsi->down_request = 0;
-        dsi_attention(AFPobj->handle, AFPATTN_SHUTDOWN | AFPATTN_NORECONNECT |
+        dsi_attention(AFPobj->dsi, AFPATTN_SHUTDOWN | AFPATTN_NORECONNECT |
                   AFPATTN_MESG | AFPATTN_TIME(5));
     }
 }
@@ -388,10 +383,10 @@ static void pending_request(DSI *dsi)
 */
 void afp_over_dsi(AFPObj *obj)
 {
-    DSI *dsi = (DSI *) obj->handle;
+    DSI *dsi = (DSI *) obj->dsi;
     int rc_idx;
-    u_int32_t err, cmd;
-    u_int8_t function;
+    uint32_t err, cmd;
+    uint8_t function;
     struct sigaction action;
 
     AFPobj = obj;
@@ -547,7 +542,7 @@ void afp_over_dsi(AFPObj *obj)
 
         if (reload_request) {
             reload_request = 0;
-            load_volumes(AFPobj);
+            load_volumes(AFPobj, closevol);
         }
 
         /* The first SIGINT enables debugging, the next restores the config */
@@ -560,15 +555,15 @@ void afp_over_dsi(AFPObj *obj)
 
             if (debugging) {
                 if (obj->options.logconfig)
-                    setuplog(obj->options.logconfig);
+                    setuplog(obj->options.logconfig, obj->options.logfile);
                 else
-                    setuplog("default log_note");
+                    setuplog("default:note", NULL);
                 debugging = 0;
             } else {
                 char logstr[50];
                 debugging = 1;
-                sprintf(logstr, "default log_maxdebug /tmp/afpd.%u.XXXXXX", getpid());
-                setuplog(logstr);
+                sprintf(logstr, "/tmp/afpd.%u.XXXXXX", getpid());
+                setuplog("default:maxdebug", logstr);
             }
         }
 
@@ -632,11 +627,6 @@ void afp_over_dsi(AFPObj *obj)
 
                     dir_free_invalid_q();
 
-#ifdef FORCE_UIDGID
-                    /* bring everything back to old euid, egid */
-                    if (obj->force_uid)
-                        restore_uidgid ( &obj->uidgid );
-#endif /* FORCE_UIDGID */
                     dsi->flags &= ~DSI_RUNNING;
 
                     /* Add result to the AFP replay cache */
@@ -677,11 +667,6 @@ void afp_over_dsi(AFPObj *obj)
                     AfpNum2name(function), AfpErr2name(err));
 
                 dsi->flags &= ~DSI_RUNNING;
-#ifdef FORCE_UIDGID
-               /* bring everything back to old euid, egid */
-               if (obj->force_uid)
-                   restore_uidgid ( &obj->uidgid );
-#endif /* FORCE_UIDGID */
             } else {
                 LOG(log_error, logtype_afpd, "(write) bad function %x", function);
                 dsi->datalen = 0;
index 6b2ba5bacbe5574ab42c605c447a8499258c65dc..e14791fee2dd93c4db6b8deef1c65f92ba168b77 100644 (file)
 #include <atalk/util.h>
 #include <atalk/dsi.h>
 #include <atalk/unicode.h>
+#include <atalk/netatalk_conf.h>
 
 #include "afp_zeroconf.h"
 #include "afp_mdns.h"
-#include "afp_config.h"
-#include "volume.h"
 
 /*
  * We'll store all the DNSServiceRef's here so that we can
@@ -115,9 +114,8 @@ static void unregister_stuff() {
  * This function tries to register the AFP DNS
  * SRV service type.
  */
-static void register_stuff(const AFPConfig *configs) {
+static void register_stuff(const AFPObj *obj) {
     uint                                        port;
-    const AFPConfig                 *config;
     const struct vol                *volume;
     DSI                                         *dsi;
     char                                        name[MAXINSTANCENAMELEN+1];
@@ -159,10 +157,10 @@ static void register_stuff(const AFPConfig *configs) {
 
     // Now we can count the configs so we know how many service
     // records to allocate
-    for (config = configs; config; config = config->next) {
+    for (dsi = obj->dsi; dsi; dsi = dsi->next) {
         svc_ref_count++;                    // AFP_DNS_SERVICE_TYPE
-        if(i) svc_ref_count++;      // ADISK_SERVICE_TYPE
-        if (config->obj.options.mimicmodel) svc_ref_count++;        // DEV_INFO_SERVICE_TYPE
+        if (i) svc_ref_count++;      // ADISK_SERVICE_TYPE
+        if (obj->options.mimicmodel) svc_ref_count++;        // DEV_INFO_SERVICE_TYPE
     }
 
     // Allocate the memory to store our service refs
@@ -171,16 +169,13 @@ static void register_stuff(const AFPConfig *configs) {
     svc_ref_count = 0;
 
     /* AFP server */
-    for (config = configs; config; config = config->next) {
+    for (dsi = obj->dsi; dsi; dsi = dsi->next) {
 
-        dsi = (DSI *)config->obj.handle;
         port = getip_port((struct sockaddr *)&dsi->server);
 
-        if (convert_string(config->obj.options.unixcharset,
+        if (convert_string(obj->options.unixcharset,
                            CH_UTF8,
-                           config->obj.options.server ?
-                           config->obj.options.server :
-                           config->obj.options.hostname,
+                           obj->options.hostname,
                            -1,
                            name,
                            MAXINSTANCENAMELEN) <= 0) {
@@ -233,9 +228,11 @@ static void register_stuff(const AFPConfig *configs) {
             }
         }
 
-        if (config->obj.options.mimicmodel) {
+        if (obj->options.mimicmodel) {
+            LOG(log_info, logtype_afpd, "Registering server '%s' with model '%s'",
+                dsi->bonjourname, obj->options.mimicmodel);
             TXTRecordCreate(&txt_devinfo, 0, NULL);
-            TXTRecordPrintf(&txt_devinfo, "model", config->obj.options.mimicmodel);
+            TXTRecordPrintf(&txt_devinfo, "model=%s", obj->options.mimicmodel);
             error = DNSServiceRegister(&svc_refs[svc_ref_count++],
                                        0,               // no flags
                                        0,               // all network interfaces
@@ -243,7 +240,7 @@ static void register_stuff(const AFPConfig *configs) {
                                        DEV_INFO_SERVICE_TYPE,
                                        "",            // default domains
                                        NULL,            // default host name
-                                       htons(port),
+                                       0,
                                        TXTRecordGetLength(&txt_devinfo),
                                        TXTRecordGetBytesPtr(&txt_devinfo),
                                        RegisterReply,           // callback
@@ -279,10 +276,10 @@ fail:
  * Tries to setup the Zeroconf thread and any
  * neccessary config setting.
  */
-void md_zeroconf_register(const AFPConfig *configs) {
+void md_zeroconf_register(const AFPObj *obj) {
     int error;
 
-    register_stuff(configs);
+    register_stuff(obj);
     return;
 }
 
index fee1b58680f301ea74a575c9bd5cd80075be15a0..5008ae4faca831c4ef6d52d156fa64cc8d2e37c2 100644 (file)
@@ -18,7 +18,7 @@
 #include "afp_config.h"
 
 /* prototype definitions */
-void md_zeroconf_register(const AFPConfig *configs);
+void md_zeroconf_register(const AFPObj *obj);
 int md_zeroconf_unregister(void);
 
 #endif   /* AFPD_MDNS_H */
index d314a037461178e774e0df532ccdb4f3412d1f4d..223f117881e20ca8b485290b4577ec6a999708d3 100644 (file)
 #include <atalk/compat.h>
 #include <atalk/globals.h>
 #include <atalk/fce_api.h>
+#include <atalk/errchk.h>
 
 #include "status.h"
 #include "auth.h"
 #include "dircache.h"
 
-#ifndef MIN
-#define MIN(a, b)  ((a) < (b) ? (a) : (b))
-#endif /* MIN */
-
-/* FIXME CNID */
-const char *Cnid_srv = "localhost";
-const char *Cnid_port = "4700";
-
-#define OPTIONS "dn:f:s:uc:g:P:ptDS:TL:F:U:hIvVm:"
 #define LENGTH 512
 
-/* return an option. this uses an internal array, so it's necessary
- * to duplicate it if you want to hold it for long. this is probably
- * non-optimal. */
-static char *getoption(char *buf, const char *option)
-{
-    static char string[LENGTH + 1];
-    char *end;
-    int len;
-
-    if (option && (buf = strstr(buf, option)))
-        buf = strpbrk(buf, " \t");
-
-    while (buf && isspace(*buf))
-        buf++;
-
-    if (!buf)
-        return NULL;
-
-    /* search for any quoted stuff */
-    if (*buf == '"' && (end = strchr(buf + 1, '"'))) {
-        buf++;
-        len = MIN(end - buf, LENGTH);
-    } else if ((end = strpbrk(buf, " \t\n"))) /* option or eoln */
-        len = MIN(end - buf, LENGTH);
-    else
-        len = MIN(strlen(buf), LENGTH);
-
-    strncpy(string, buf, len);
-    string[len] = '\0';
-    return string;
-}
-
 /* get rid of any allocated afp_option buffers. */
-void afp_options_free(struct afp_options *opt,
-                      const struct afp_options *save)
+void afp_options_free(struct afp_options *opt)
 {
-    if (opt->defaultvol.name && (opt->defaultvol.name != save->defaultvol.name))
-        free(opt->defaultvol.name);
-    if (opt->defaultvol.full_name && (opt->defaultvol.full_name != save->defaultvol.full_name))
-        free(opt->defaultvol.full_name);
-
-    if (opt->systemvol.name && (opt->systemvol.name != save->systemvol.name))
-        free(opt->systemvol.name);
-    if (opt->systemvol.full_name && (opt->systemvol.full_name != save->systemvol.full_name))
-        free(opt->systemvol.full_name);
-
-    if (opt->uservol.name && (opt->uservol.name != save->uservol.name))
-        free(opt->uservol.name);
-    if (opt->uservol.full_name && (opt->uservol.full_name != save->uservol.full_name))
-        free(opt->uservol.full_name);
-
-    if (opt->loginmesg && (opt->loginmesg != save->loginmesg))
-        free(opt->loginmesg);
-    if (opt->guest && (opt->guest != save->guest))
+       if (opt->hostname)
+        free(opt->hostname);
+       if (opt->adminauthuser)
+        free(opt->adminauthuser);
+       if (opt->configfile)
+        free(opt->configfile);
+    if (opt->fqdn)
+        free(opt->fqdn);
+    if (opt->guest)
         free(opt->guest);
-    if (opt->server && (opt->server != save->server))
-        free(opt->server);
-    if (opt->ipaddr && (opt->ipaddr != save->ipaddr))
-        free(opt->ipaddr);
-    if (opt->port && (opt->port != save->port))
+    if (opt->listen)
+        free(opt->listen);
+    if (opt->k5realm)
+        free(opt->k5realm);
+    if (opt->k5keytab)
+        free(opt->k5keytab);
+    if (opt->k5service)
+        free(opt->k5service);
+    if (opt->logconfig)
+        free(opt->logconfig);
+    if (opt->logfile)
+        free(opt->logfile);
+    if (opt->loginmesg)
+        free(opt->loginmesg);
+    if (opt->maccodepage)
+        free(opt->maccodepage);
+       if (opt->mimicmodel)
+        free(opt->mimicmodel);
+    if (opt->ntdomain)
+        free(opt->ntdomain);
+    if (opt->ntseparator)
+        free(opt->ntseparator);
+    if (opt->passwdfile)
+        free(opt->passwdfile);
+    if (opt->port)
         free(opt->port);
-    if (opt->fqdn && (opt->fqdn != save->fqdn))
-        free(opt->fqdn);
-    if (opt->uampath && (opt->uampath != save->uampath))
-        free(opt->uampath);
-    if (opt->uamlist && (opt->uamlist != save->uamlist))
+    if (opt->signatureopt)
+        free(opt->signatureopt);
+    if (opt->uamlist)
         free(opt->uamlist);
-    if (opt->passwdfile && (opt->passwdfile != save->passwdfile))
-        free(opt->passwdfile);
-    if (opt->signatureopt && (opt->signatureopt != save->signatureopt))
-       free(opt->signatureopt);
-    if (opt->k5service && (opt->k5service != save->k5service))
-       free(opt->k5service);
-    if (opt->k5realm && (opt->k5realm != save->k5realm))
-       free(opt->k5realm);
-    if (opt->k5keytab && (opt->k5keytab != save->k5keytab))
-       free(opt->k5keytab);
-    if (opt->unixcodepage && (opt->unixcodepage != save->unixcodepage))
-       free(opt->unixcodepage);
-    if (opt->maccodepage && (opt->maccodepage != save->maccodepage))
-       free(opt->maccodepage);
-
-    if (opt->ntdomain && (opt->ntdomain != save->ntdomain))
-       free(opt->ntdomain);
-    if (opt->ntseparator && (opt->ntseparator != save->ntseparator))
-       free(opt->ntseparator);
-    if (opt->logconfig && (opt->logconfig != save->logconfig))
-       free(opt->logconfig);
-       if (opt->mimicmodel && (opt->mimicmodel != save->mimicmodel))
-       free(opt->mimicmodel);
-       if (opt->adminauthuser && (opt->adminauthuser != save->adminauthuser))
-       free(opt->adminauthuser);
-}
-
-/* initialize options */
-void afp_options_init(struct afp_options *options)
-{
-    memset(options, 0, sizeof(struct afp_options));
-    options->connections = 20;
-    options->pidfile = _PATH_AFPDLOCK;
-    options->defaultvol.name = _PATH_AFPDDEFVOL;
-    options->systemvol.name = _PATH_AFPDSYSVOL;
-    options->configfile = _PATH_AFPDCONF;
-    options->sigconffile = _PATH_AFPDSIGCONF;
-    options->uuidconf = _PATH_AFPDUUIDCONF;
-    options->uampath = _PATH_AFPDUAMPATH;
-    options->uamlist = "uams_dhx.so,uams_dhx2.so";
-    options->guest = "nobody";
-    options->loginmesg = "";
-    options->transports = AFPTRANS_TCP; /*  TCP only */
-    options->passwdfile = _PATH_AFPDPWFILE;
-    options->tickleval = 30;
-    options->timeout = 4;       /* 4 tickles = 2 minutes */
-    options->sleep = 10 * 60 * 2; /* 10 h in 30 seconds tick */
-    options->disconnected = 10 * 60 * 2; /* 10 h in 30 seconds tick */
-    options->server_notif = 1;
-    options->authprintdir = NULL;
-    options->signatureopt = "auto";
-    options->umask = 0;
-#ifdef ADMIN_GRP
-    options->admingid = 0;
-#endif /* ADMIN_GRP */
-    options->k5service = NULL;
-    options->k5realm = NULL;
-    options->k5keytab = NULL;
-    options->unixcharset = CH_UNIX;
-    options->unixcodepage = "LOCALE";
-    options->maccharset = CH_MAC;
-    options->maccodepage = "MAC_ROMAN";
-    options->volnamelen = 80; /* spec: 255, 10.1: 73, 10.4/10.5: 80 */
-    options->ntdomain = NULL;
-    options->ntseparator = NULL;
-#ifdef USE_SRVLOC
-    /* don't advertize slp by default */
-    options->flags |= OPTION_NOSLP;
-#endif
-    options->dircachesize = DEFAULT_MAX_DIRCACHE_SIZE;
-    options->flags |= OPTION_ACL2MACCESS;
-    options->flags |= OPTION_UUID;
-    options->tcp_sndbuf = 0;    /* 0 means don't change OS default */
-    options->tcp_rcvbuf = 0;    /* 0 means don't change OS default */
-    options->dsireadbuf = 12;
-       options->mimicmodel = NULL;
-    options->fce_fmodwait = 60; /* put fmod events 60 seconds on hold */
-    options->adminauthuser = NULL;
-}
-
-/* parse an afpd.conf line. i'm doing it this way because it's
- * easy. it is, however, massively hokey. sample afpd.conf:
- * server:AFPServer@zone -loginmesg "blah blah blah" -nodsi 
- * "private machine"@zone2 -noguest -port 11012
- * server2 -nocleartxt -nodsi
- *
- * NOTE: this ignores unknown options 
- */
-int afp_options_parseline(char *buf, struct afp_options *options)
-{
-    char *c, *opt;
-
-    /* handle server */
-    if (*buf != '-' && (c = getoption(buf, NULL)) && (opt = strdup(c)))
-        options->server = opt;
-
-    /* parse toggles */
-    if (strstr(buf, " -nodebug"))
-        options->flags &= ~OPTION_DEBUG;
-#ifdef USE_SRVLOC
-    if (strstr(buf, " -slp"))
-        options->flags &= ~OPTION_NOSLP;
-#endif
-#ifdef USE_ZEROCONF
-    if (strstr(buf, " -nozeroconf"))
-        options->flags |= OPTION_NOZEROCONF;
-#endif
-    if (strstr(buf, " -nouservolfirst"))
-        options->flags &= ~OPTION_USERVOLFIRST;
-    if (strstr(buf, " -uservolfirst"))
-        options->flags |= OPTION_USERVOLFIRST;
-    if (strstr(buf, " -nouservol"))
-        options->flags |= OPTION_NOUSERVOL;
-    if (strstr(buf, " -uservol"))
-        options->flags &= ~OPTION_NOUSERVOL;
-    if (strstr(buf, " -proxy"))
-        options->flags |= OPTION_PROXY;
-    if (strstr(buf, " -noicon"))
-        options->flags &= ~OPTION_CUSTOMICON;
-    if (strstr(buf, " -icon"))
-        options->flags |= OPTION_CUSTOMICON;
-    if (strstr(buf, " -advertise_ssh"))
-        options->flags |= OPTION_ANNOUNCESSH;
-    if (strstr(buf, " -noacl2maccess"))
-        options->flags &= ~OPTION_ACL2MACCESS;
-    if (strstr(buf, " -keepsessions")) {
-        default_options.flags |= OPTION_KEEPSESSIONS;
-        options->flags |= OPTION_KEEPSESSIONS;
-    }
-
-    /* passwd bits */
-    if (strstr(buf, " -nosavepassword"))
-        options->passwdbits |= PASSWD_NOSAVE;
-    if (strstr(buf, " -savepassword"))
-        options->passwdbits &= ~PASSWD_NOSAVE;
-    if (strstr(buf, " -nosetpassword"))
-        options->passwdbits &= ~PASSWD_SET;
-    if (strstr(buf, " -setpassword"))
-        options->passwdbits |= PASSWD_SET;
-
-    /* transports */
-    if (strstr(buf, " -transall"))
-        options->transports = AFPTRANS_ALL;
-    if (strstr(buf, " -notransall"))
-        options->transports = AFPTRANS_NONE;
-    if (strstr(buf, " -tcp"))
-        options->transports |= AFPTRANS_TCP;
-    if (strstr(buf, " -notcp"))
-        options->transports &= ~AFPTRANS_TCP;
-    if (strstr(buf, " -ddp"))
-        options->transports |= AFPTRANS_DDP;
-    if (strstr(buf, " -noddp"))
-        options->transports &= ~AFPTRANS_DDP;
-    if (strstr(buf, "-client_polling"))
-        options->server_notif = 0;
-
-    /* figure out options w/ values. currently, this will ignore the setting
-     * if memory is lacking. */
-
-    if ((c = getoption(buf, "-hostname"))) {
-        int len = strlen (c);
-        if (len <= MAXHOSTNAMELEN) {
-            memcpy(options->hostname, c, len);
-            options->hostname[len] = 0;
-        }
-        else
-            LOG(log_info, logtype_afpd, "WARNING: hostname %s is too long (%d)",c,len);
-    }
-
-    if ((c = getoption(buf, "-defaultvol")) && (opt = strdup(c)))
-        options->defaultvol.name = opt;
-    if ((c = getoption(buf, "-systemvol")) && (opt = strdup(c)))
-        options->systemvol.name = opt;
-    if ((c = getoption(buf, "-loginmesg")) && (opt = strdup(c))) {
-        int i = 0, j = 0;
-        while (c[i]) {
-            if (c[i] != '\\') {
-                opt[j++] = c[i];
-            } else {
-                i++;
-                if (c[i] == 'n')
-                    opt[j++] = '\n';
-            }
-            i++;
-        }
-        opt[j] = 0;
-        options->loginmesg = opt;
-        
-    }
-    if ((c = getoption(buf, "-guestname")) && (opt = strdup(c)))
-        options->guest = opt;
-    if ((c = getoption(buf, "-passwdfile")) && (opt = strdup(c)))
-        options->passwdfile = opt;
-    if ((c = getoption(buf, "-passwdminlen")))
-        options->passwdminlen = MIN(1, atoi(c));
-    if ((c = getoption(buf, "-loginmaxfail")))
-        options->loginmaxfail = atoi(c);
-    if ((c = getoption(buf, "-tickleval"))) {
-        options->tickleval = atoi(c);
-        if (options->tickleval <= 0) {
-            options->tickleval = 30;
-        }
-    }
-    if ((c = getoption(buf, "-timeout"))) {
-        options->timeout = atoi(c);
-        if (options->timeout <= 0) {
-            options->timeout = 4;
-        }
-    }
-
-    if ((c = getoption(buf, "-sleep"))) {
-        options->disconnected = options->sleep = atoi(c) * 120;
-        if (options->sleep <= 4) {
-            options->disconnected = options->sleep = 4;
-        }
-    }
-
-    if ((c = getoption(buf, "-dsireadbuf"))) {
-        options->dsireadbuf = atoi(c);
-        if (options->dsireadbuf < 6)
-            options->dsireadbuf = 6;
-    }
-
-    if ((c = getoption(buf, "-server_quantum")))
-        options->server_quantum = strtoul(c, NULL, 0);
-
-    if ((c = getoption(buf, "-volnamelen"))) {
-        options->volnamelen = atoi(c);
-        if (options->volnamelen < 8) {
-            options->volnamelen = 8; /* max mangled volname "???#FFFF" */
-        }
-        if (options->volnamelen > 255) {
-           options->volnamelen = 255; /* AFP3 spec */
-        }
-    }
-
-    /* -[no]setuplog <logtype> <loglevel> [<filename>]*/
-    c = buf;
-    /* Now THIS is hokey! Multiple occurrences are not supported by our current code, */
-    /* so I have to loop myself. */
-    while (NULL != (c = strstr(c, "-setuplog"))) {
-        char *optstr;
-        if ((optstr = getoption(c, "-setuplog"))) {
-            /* hokey2: options->logconfig must be converted to store an array of logstrings */
-            if (options->logconfig)
-                free(options->logconfig);
-            options->logconfig = strdup(optstr);
-            setuplog(optstr);
-            c += sizeof("-setuplog");
-        }
-    }
-
-    if ((c = getoption(buf, "-unsetuplog")))
-      unsetuplog(c);
-
-#ifdef ADMIN_GRP
-    if ((c = getoption(buf, "-admingroup"))) {
-        struct group *gr = getgrnam(c);
-        if (gr != NULL) {
-            options->admingid = gr->gr_gid;
-        }
-    }
-#endif /* ADMIN_GRP */
-
-    if ((c = getoption(buf, "-k5service")) && (opt = strdup(c)))
-       options->k5service = opt;
-    if ((c = getoption(buf, "-k5realm")) && (opt = strdup(c)))
-       options->k5realm = opt;
-    if ((c = getoption(buf, "-k5keytab"))) {
-       if ( NULL == (options->k5keytab = (char *) malloc(sizeof(char)*(strlen(c)+14)) )) {
-               LOG(log_error, logtype_afpd, "malloc failed");
-               exit(-1);
-       }
-       snprintf(options->k5keytab, strlen(c)+14, "KRB5_KTNAME=%s", c);
-       putenv(options->k5keytab);
-       /* setenv( "KRB5_KTNAME", c, 1 ); */
-    }
-    if ((c = getoption(buf, "-authprintdir")) && (opt = strdup(c)))
-        options->authprintdir = opt;
-    if ((c = getoption(buf, "-uampath")) && (opt = strdup(c)))
-        options->uampath = opt;
-    if ((c = getoption(buf, "-uamlist")) && (opt = strdup(c)))
-        options->uamlist = opt;
-
-    if ((c = getoption(buf, "-ipaddr"))) {
-#if 0
-        struct in_addr inaddr;
-        if (inet_aton(c, &inaddr) && (opt = strdup(c))) {
-            if (!gethostbyaddr((const char *) &inaddr, sizeof(inaddr), AF_INET))
-                LOG(log_info, logtype_afpd, "WARNING: can't find %s", opt);
-            options->ipaddr = opt;
-        }
-        else {
-            LOG(log_error, logtype_afpd, "Error parsing -ipaddr, is %s in numbers-and-dots notation?", c);
-        }
-#endif
-        options->ipaddr = strdup(c);
-    }
-
-    /* FIXME CNID Cnid_srv is a server attribute */
-    if ((c = getoption(buf, "-cnidserver"))) {
-        char *p = strrchr(c, ':');
-        if (p)
-            *p = 0;
-        Cnid_srv = strdup(c);
-        if (p)
-            Cnid_port = strdup(p + 1);
-        LOG(log_debug, logtype_afpd, "CNID Server: %s:%s", Cnid_srv, Cnid_port);
-    }
-
-    if ((c = getoption(buf, "-port")))
-        options->port = strdup(c);
-#ifndef NO_DDP
-    if ((c = getoption(buf, "-ddpaddr")))
-        atalk_aton(c, &options->ddpaddr);
-#endif
-    if ((c = getoption(buf, "-signature")) && (opt = strdup(c)))
-        options->signatureopt = opt;
-
-    /* do a little checking for the domain name. */
-    if ((c = getoption(buf, "-fqdn"))) {
-        char *p = strchr(c, ':');
-        if (p)
-            *p = '\0';
-        if (gethostbyname(c)) {
-            if (p)
-                *p = ':';
-            if ((opt = strdup(c)))
-                options->fqdn = opt;
-        }
-       else {
-            LOG(log_error, logtype_afpd, "error parsing -fqdn, gethostbyname failed for: %s", c);
-       }
-    }
-
-    if ((c = getoption(buf, "-unixcodepage"))) {
-       if ((charset_t)-1  == ( options->unixcharset = add_charset(c)) ) {
-            options->unixcharset = CH_UNIX;
-            LOG(log_warning, logtype_afpd, "setting Unix codepage to '%s' failed", c);
-       }
-       else {
-            if ((opt = strdup(c)))
-                options->unixcodepage = opt;
-       }
-    }
-       
-    if ((c = getoption(buf, "-maccodepage"))) {
-       if ((charset_t)-1 == ( options->maccharset = add_charset(c)) ) {
-            options->maccharset = CH_MAC;
-            LOG(log_warning, logtype_afpd, "setting Mac codepage to '%s' failed", c);
-       }
-       else {
-            if ((opt = strdup(c)))
-                options->maccodepage = opt;
-       }
-    }
-    
-    if ((c = strstr(buf, "-closevol"))) {
-        options->closevol= 1;
-    }
-
-    if ((c = getoption(buf, "-ntdomain")) && (opt = strdup(c)))
-       options->ntdomain = opt;
-
-    if ((c = getoption(buf, "-ntseparator")) && (opt = strdup(c)))
-       options->ntseparator = opt;
-
-    if ((c = getoption(buf, "-dircachesize")))
-        options->dircachesize = atoi(c);
-     
-    if ((c = getoption(buf, "-tcpsndbuf")))
-        options->tcp_sndbuf = atoi(c);
-
-    if ((c = getoption(buf, "-tcprcvbuf")))
-        options->tcp_rcvbuf = atoi(c);
-
-       if ((c = getoption(buf, "-fcelistener"))) {
-               LOG(log_note, logtype_afpd, "Adding fce listener \"%s\"", c);
-               fce_add_udp_socket(c);
-       }
-       if ((c = getoption(buf, "-fcecoalesce"))) {
-               LOG(log_note, logtype_afpd, "Fce coalesce: %s", c);
-               fce_set_coalesce(c);
-       }
-       if ((c = getoption(buf, "-fceevents"))) {
-               LOG(log_note, logtype_afpd, "Fce events: %s", c);
-               fce_set_events(c);
-       }
-
-    if ((c = getoption(buf, "-fceholdfmod")))
-        options->fce_fmodwait = atoi(c);
-
-    if ((c = getoption(buf, "-mimicmodel")) && (opt = strdup(c)))
-       options->mimicmodel = opt;
-
-    if ((c = getoption(buf, "-adminauthuser")) && (opt = strdup(c)))
-       options->adminauthuser = opt;
-
-    return 1;
+    if (opt->uampath)
+        free(opt->uampath);
+    if (opt->unixcodepage)
+        free(opt->unixcodepage);
 }
 
 /*
@@ -544,13 +117,6 @@ static void show_version( void )
        }
        puts( "" );
 
-       printf( "DDP(AppleTalk) Support:\t" );
-#ifdef NO_DDP
-       puts( "No" );
-#else
-       puts( "Yes" );
-#endif
-
        printf( "         CNID backends:\t" );
 #ifdef CNID_BACKEND_CDB
        printf( "cdb ");
@@ -588,13 +154,6 @@ static void show_version_extended(void )
 {
        show_version( );
 
-       printf( "           SLP support:\t" );
-#ifdef USE_SRVLOC
-       puts( "Yes" );
-#else
-       puts( "No" );
-#endif
-
        printf( "      Zeroconf support:\t" );
 #if defined (HAVE_MDNS)
        puts( "mDNSResponder" );
@@ -639,20 +198,6 @@ static void show_version_extended(void )
        puts( "No" );
 #endif
 
-       printf( "        Dropbox kludge:\t" );
-#ifdef DROPKLUDGE
-       puts( "Yes" );
-#else
-       puts( "No" );
-#endif
-
-       printf( "  Force volume uid/gid:\t" );
-#ifdef FORCE_UIDGID
-       puts( "Yes" );
-#else
-       puts( "No" );
-#endif
-
        printf( "            EA support:\t" );
        puts( EA_MODULES );
 
@@ -676,147 +221,57 @@ static void show_version_extended(void )
  */
 static void show_paths( void )
 {
-       printf( "             afpd.conf:\t%s\n", _PATH_AFPDCONF );
-       printf( "   AppleVolumes.system:\t%s\n", _PATH_AFPDSYSVOL );
-       printf( "  AppleVolumes.default:\t%s\n", _PATH_AFPDDEFVOL );
-       printf( "    afp_signature.conf:\t%s\n", _PATH_AFPDSIGCONF );
-       printf( "      afp_voluuid.conf:\t%s\n", _PATH_AFPDUUIDCONF );
-#ifdef HAVE_LDAP
-       printf( "         afp_ldap.conf:\t%s\n", _PATH_ACL_LDAPCONF );
-#else
-       printf( "         afp_ldap.conf:\tnot supported\n");
-#endif
+       printf( "              afp.conf:\t%s\n", _PATH_CONFDIR "afp.conf");
+       printf( "       state directory:\t%s\n", _PATH_STATEDIR);
+       printf( "    afp_signature.conf:\t%s\n", _PATH_STATEDIR "afp_signature.conf");
+       printf( "      afp_voluuid.conf:\t%s\n", _PATH_STATEDIR "afp_voluuid.conf");
        printf( "       UAM search path:\t%s\n", _PATH_AFPDUAMPATH );
        printf( "  Server messages path:\t%s\n", SERVERTEXT);
-       printf( "              lockfile:\t%s\n", _PATH_AFPDLOCK);
 }
 
 /*
  * Display usage information about afpd.
  */
-static void show_usage( char *name )
+static void show_usage(void)
 {
-       fprintf( stderr, "Usage:\t%s [-duptDTI] [-f defaultvolumes] [-s systemvolumes] [-n nbpname]\n", name );
-       fprintf( stderr, "\t     [-c maxconnections] [-g guest] [-P pidfile] [-S port] [-L message]\n" );
-       fprintf( stderr, "\t     [-F configfile] [-U uams] [-m umask]\n" );
-       fprintf( stderr, "\t%s -h|-v|-V\n", name );
+       fprintf( stderr, "Usage:\tafpd [-d] [-F configfile]\n");
+       fprintf( stderr, "\tafpd -h|-v|-V\n");
 }
 
-int afp_options_parse(int ac, char **av, struct afp_options *options)
+void afp_options_parse_cmdline(AFPObj *obj, int ac, char **av)
 {
-    extern char *optarg;
-    extern int optind;
-
-    char *p;
-    char *tmp; /* Used for error checking the result of strtol */
     int c, err = 0;
 
-    if (gethostname(options->hostname, sizeof(options->hostname )) < 0 ) {
-        perror( "gethostname" );
-        return 0;
-    }
-    if (NULL != ( p = strchr(options->hostname, '.' )) ) {
-        *p = '\0';
-    }
-
-#ifdef ultrix
-    if (NULL == ( p = strrchr( av[ 0 ], '/' )) ) {
-        p = av[ 0 ];
-    } else {
-        p++;
-    }
-    openlog( p, LOG_PID ); /* ultrix only */
-#endif /* ultrix */
-
-    while (EOF != ( c = getopt( ac, av, OPTIONS )) ) {
+    while (EOF != ( c = getopt( ac, av, "dF:vVh" )) ) {
         switch ( c ) {
-        case 'd' :
-            options->flags |= OPTION_DEBUG;
-            break;
-        case 'n' :
-            options->server = optarg;
-            break;
-        case 'f' :
-            options->defaultvol.name = optarg;
-            break;
-        case 's' :
-            options->systemvol.name = optarg;
-            break;
-        case 'u' :
-            options->flags |= OPTION_USERVOLFIRST;
-            break;
-        case 'c' :
-            options->connections = atoi( optarg );
-            break;
-        case 'g' :
-            options->guest = optarg;
-            break;
-
-        case 'P' :
-            options->pidfile = optarg;
-            break;
-
-        case 'p':
-            options->passwdbits |= PASSWD_NOSAVE;
-            break;
-        case 't':
-            options->passwdbits |= PASSWD_SET;
-            break;
-
-        case 'D':
-            options->transports &= ~AFPTRANS_DDP;
-            break;
-        case 'S':
-            options->port = optarg;
-            break;
-        case 'T':
-            options->transports &= ~AFPTRANS_TCP;
-            break;
-        case 'L':
-            options->loginmesg = optarg;
+        case 'd':
+            obj->cmdlineflags |= OPTION_DEBUG;
             break;
         case 'F':
-            options->configfile = optarg;
-            break;
-        case 'U':
-            options->uamlist = optarg;
+            obj->cmdlineconfigfile = strdup(optarg);
             break;
         case 'v':      /* version */
             show_version( ); puts( "" );
-           show_paths( ); puts( "" );
+            show_paths( ); puts( "" );
             exit( 0 );
             break;
         case 'V':      /* extended version */
             show_version_extended( ); puts( "" );
-           show_paths( ); puts( "" );
+            show_paths( ); puts( "" );
             exit( 0 );
             break;
         case 'h':      /* usage */
-            show_usage("afpd");
+            show_usage();
             exit( 0 );
             break;
-        case 'I':
-            options->flags |= OPTION_CUSTOMICON;
-            break;
-        case 'm':
-            options->umask = strtoul(optarg, &tmp, 8);
-            if ((options->umask > 0777)) {
-                fprintf(stderr, "%s: out of range umask setting provided\n", p);
-                err++;
-            }
-            if (tmp[0] != '\0') {
-                fprintf(stderr, "%s: invalid characters in umask setting provided\n", p);
-                err++;
-            }
-            break;
         default :
             err++;
         }
     }
     if ( err || optind != ac ) {
-        show_usage( p );
+        show_usage();
         exit( 2 );
     }
 
-    return 1;
+    return;
 }
index f8bbcf6fb4ed19297f954a4591c6f6141f157537..cf370fc3bf4b052a5defd159dcc40749fcc2bb2b 100644 (file)
@@ -24,7 +24,7 @@
 /*
  * Functions (actually they are just facades)
  */
-void zeroconf_register(const AFPConfig *configs)
+void zeroconf_register(const AFPObj *configs)
 {
 #if defined (HAVE_MDNS)
   LOG(log_debug, logtype_afpd, "Attempting to register with mDNS using mDNSResponder");
index 8c370fd226d3515096309d538d69ffaf762b5888..89fc3ca9916ed4e7e48a7078be0216f156068528 100644 (file)
@@ -25,7 +25,7 @@
 /*
  * registers service with a particular Zerconf implemenation.
  */
-void zeroconf_register(const AFPConfig *configs);
+void zeroconf_register(const AFPObj *obj);
 
 /*
  * de-registers the ntpd service with a particular Zerconf implemenation.
index cd506a58ca2aadce8f13238aa4eb451f496b97ee..74a732e60bdd3a2359754aceb162d1bc58606342 100644 (file)
 
 #include <stdio.h>
 #include <stdlib.h>
-
 #include <sys/types.h>
-#define __USE_GNU 1
+/* #define __USE_GNU 1 */
 #include <unistd.h>
 
 #include <errno.h>
-
-#ifdef HAVE_SYS_WAIT_H 
 #include <sys/wait.h>
-#endif
-
 #include <sys/param.h>  
 #include <string.h>
 
index 9d6835f4d79592f5dc5e774b31df38580437a0a4..f11d77eb22995a400ff43247cf7ddd4441babdbb 100644 (file)
@@ -29,7 +29,7 @@
 #include "misc.h"
 #include "unix.h"
 
-int afs_getvolspace(struct vol *vol, VolSpace *bfree, VolSpace *btotal, u_int32_t *bsize)
+int afs_getvolspace(struct vol *vol, VolSpace *bfree, VolSpace *btotal, uint32_t *bsize)
 {
     struct ViceIoctl   vi;
     struct VolumeStatus        *vs;
@@ -78,8 +78,8 @@ int afp_getdiracl(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *r
     struct vol         *vol;
     struct dir         *dir;
     struct path                *path;
-    u_int32_t          did;
-    u_int16_t          vid;
+    uint32_t           did;
+    uint16_t           vid;
 
     ibuf += 2;
     memcpy( &vid, ibuf, sizeof( vid ));
@@ -162,8 +162,8 @@ int afp_setdiracl(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *r
     struct dir         *dir;
     char               *iend;
     struct path                *path;
-    u_int32_t          did;
-    u_int16_t          vid;
+    uint32_t           did;
+    uint16_t           vid;
 
     *rbuflen = 0;
     iend = ibuf + ibuflen;
@@ -228,7 +228,7 @@ int afp_afschangepw(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t
     char       realm[ MAXKTCREALMLEN ];
     char       oldpw[ 9 ], newpw[ 9 ];
     int                len, rc;
-    u_int16_t  clen;
+    uint16_t   clen;
     struct ktc_encryptionKey   oldkey, newkey;
     struct ktc_token           adtok;
     struct ubik_client         *conn;
index 78b7587d8b829c7c89b4fb6fd828b10aea07a323..3cba16e0c2ae7eab2fe07c28a4cbc6b11498ad85 100644 (file)
@@ -23,6 +23,7 @@
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
 
 #include "volume.h"
 #include "directory.h"
@@ -87,8 +88,8 @@ static int copyapplfile(int sfd, int dfd, char *mpath, u_short mplen)
 {
     int                cc;
     char       *p;
-    u_int16_t  len;
-    u_char     appltag[ 4 ];
+    uint16_t   len;
+    unsigned char      appltag[ 4 ];
     char       buf[ MAXPATHLEN ];
 
     while (( cc = read( sfd, buf, sizeof(appltag) + sizeof( u_short ))) > 0 ) {
@@ -199,12 +200,12 @@ int afp_addappl(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, siz
     struct vol         *vol;
     struct dir         *dir;
     int                        tfd, cc;
-    u_int32_t           did;
-    u_int16_t          vid, mplen;
+    uint32_t           did;
+    uint16_t           vid, mplen;
     struct path         *path;
     char                *dtf, *p, *mp;
-    u_char             creator[ 4 ];
-    u_char             appltag[ 4 ];
+    unsigned char              creator[ 4 ];
+    unsigned char              appltag[ 4 ];
     char               *mpath, *tempfile;
 
     *rbuflen = 0;
@@ -288,11 +289,11 @@ int afp_rmvappl(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, siz
     struct vol         *vol;
     struct dir         *dir;
     int                        tfd, cc;
-    u_int32_t           did;
-    u_int16_t          vid, mplen;
+    uint32_t           did;
+    uint16_t           vid, mplen;
     struct path        *path;
     char                *dtf, *mp;
-    u_char             creator[ 4 ];
+    unsigned char              creator[ 4 ];
     char                *tempfile, *mpath;
 
     *rbuflen = 0;
@@ -361,9 +362,9 @@ int afp_getappl(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
     char               *p, *q;
     int                        cc; 
     size_t             buflen;
-    u_int16_t          vid, aindex, bitmap, len;
-    u_char             creator[ 4 ];
-    u_char             appltag[ 4 ];
+    uint16_t           vid, aindex, bitmap, len;
+    unsigned char              creator[ 4 ];
+    unsigned char              appltag[ 4 ];
     char                *buf, *cbuf;
     struct path         *path;
     
@@ -482,8 +483,8 @@ int afp_getappl(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
         return( AFPERR_NOITEM );
     }
     buflen = *rbuflen - sizeof( bitmap ) - sizeof( appltag );
-    if ( getfilparams(vol, bitmap, path, curdir, rbuf + sizeof( bitmap ) +
-                      sizeof( appltag ), &buflen ) != AFP_OK ) {
+    if ( getfilparams(obj, vol, bitmap, path, curdir, rbuf + sizeof( bitmap ) +
+                      sizeof( appltag ), &buflen, 0) != AFP_OK ) {
         *rbuflen = 0;
         return( AFPERR_BITMAP );
     }
index 40d3a5ac906b7e56a1de886dedd3f52a70f68546..6c81b5e482301c9e4197642e6aec179bbde3e443 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <errno.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <sys/types.h>
 #include <sys/param.h>
 #include <sys/stat.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/afp.h>
 #include <atalk/compat.h>
 #include <atalk/util.h>
@@ -51,24 +50,7 @@ extern void afp_get_cmdline( int *ac, char ***av );
 #include "acls.h"
 #endif
 
-int afp_version = 11;
 static int afp_version_index;
-
-uid_t   uuid;
-
-#if defined( sun ) && !defined( __svr4__ ) || defined( ultrix )
-
-int *groups;
-#define GROUPS_SIZE sizeof(int)
-
-#else /* sun __svr4__ ultrix */
-
-gid_t   *groups;
-#define GROUPS_SIZE sizeof(gid_t)
-#endif /* sun ultrix */
-
-int ngroups;
-
 static struct uam_mod uam_modules = {NULL, NULL, &uam_modules, &uam_modules};
 static struct uam_obj uam_login = {"", "", 0, {{NULL, NULL, NULL, NULL }}, &uam_login,
                                    &uam_login};
@@ -78,23 +60,16 @@ static struct uam_obj uam_changepw = {"", "", 0, {{NULL, NULL, NULL, NULL}}, &ua
 static struct uam_obj *afp_uam = NULL;
 
 
-void status_versions(char *data,
-#ifndef NO_DDP
-                     const ASP asp,
-#endif
-                     const DSI *dsi)
+void status_versions( char *data, const DSI *dsi)
 {
     char                *start = data;
-    u_int16_t           status;
+    uint16_t           status;
     int         len, num, i, count = 0;
 
     memcpy(&status, start + AFPSTATUS_VERSOFF, sizeof(status));
     num = sizeof( afp_versions ) / sizeof( afp_versions[ 0 ] );
 
     for ( i = 0; i < num; i++ ) {
-#ifndef NO_DDP
-        if ( !asp && (afp_versions[ i ].av_number <= 21)) continue;
-#endif /* ! NO_DDP */
         if ( !dsi && (afp_versions[ i ].av_number >= 22)) continue;
         count++;
     }
@@ -102,9 +77,6 @@ void status_versions(char *data,
     *data++ = count;
 
     for ( i = 0; i < num; i++ ) {
-#ifndef NO_DDP
-        if ( !asp && (afp_versions[ i ].av_number <= 21)) continue;
-#endif /* ! NO_DDP */
         if ( !dsi && (afp_versions[ i ].av_number >= 22)) continue;
         len = strlen( afp_versions[ i ].av_name );
         *data++ = len;
@@ -118,7 +90,7 @@ void status_versions(char *data,
 void status_uams(char *data, const char *authlist)
 {
     char                *start = data;
-    u_int16_t           status;
+    uint16_t           status;
     struct uam_obj      *uams;
     int         len, num = 0;
 
@@ -153,7 +125,7 @@ static int send_reply(const AFPObj *obj, const int err)
     if ((err == AFP_OK) || (err == AFPERR_AUTHCONT))
         return err;
 
-    obj->reply(obj->handle, err);
+    obj->reply(obj->dsi, err);
     obj->exit(0);
 
     return AFP_OK;
@@ -173,7 +145,7 @@ static int afp_null_nolog(AFPObj *obj _U_, char *ibuf _U_, size_t ibuflen _U_,
     return( AFPERR_NOOP );
 }
 
-static int set_auth_switch(int expired)
+static int set_auth_switch(const AFPObj *obj, int expired)
 {
     int i;
 
@@ -194,7 +166,7 @@ static int set_auth_switch(int expired)
     }
     else {
         afp_switch = postauth_switch;
-        switch (afp_version) {
+        switch (obj->afp_version) {
 
         case 33:
         case 32:
@@ -269,45 +241,6 @@ static int login(AFPObj *obj, struct passwd *pwd, void (*logout)(void), int expi
     LOG(log_note, logtype_afpd, "%s Login by %s",
         afp_versions[afp_version_index].av_name, pwd->pw_name);
 
-#ifndef NO_DDP
-    if (obj->proto == AFPPROTO_ASP) {
-        ASP asp = obj->handle;
-        int addr_net = ntohs( asp->asp_sat.sat_addr.s_net );
-        int addr_node  = asp->asp_sat.sat_addr.s_node;
-
-        if (obj->options.authprintdir) {
-            if(addr_net && addr_node) { /* Do we have a valid Appletalk address? */
-                char nodename[256];
-                FILE *fp;
-                int mypid = getpid();
-                struct stat stat_buf;
-
-                sprintf(nodename, "%s/net%d.%dnode%d", obj->options.authprintdir,
-                        addr_net / 256, addr_net % 256, addr_node);
-                LOG(log_info, logtype_afpd, "registering %s (uid %d) on %u.%u as %s",
-                    pwd->pw_name, pwd->pw_uid, addr_net, addr_node, nodename);
-
-                if (stat(nodename, &stat_buf) == 0) { /* file exists */
-                    if (S_ISREG(stat_buf.st_mode)) { /* normal file */
-                        unlink(nodename);
-                        fp = fopen(nodename, "w");
-                        fprintf(fp, "%s:%d\n", pwd->pw_name, mypid);
-                        fclose(fp);
-                        chown( nodename, pwd->pw_uid, -1 );
-                    } else { /* somebody is messing with us */
-                        LOG(log_error, logtype_afpd, "print authfile %s is not a normal file, it will not be modified", nodename );
-                    }
-                } else { /* file 'nodename' does not exist */
-                    fp = fopen(nodename, "w");
-                    fprintf(fp, "%s:%d\n", pwd->pw_name, mypid);
-                    fclose(fp);
-                    chown( nodename, pwd->pw_uid, -1 );
-                }
-            } /* if (addr_net && addr_node ) */
-        } /* if (options->authprintdir) */
-    } /* if (obj->proto == AFPPROTO_ASP) */
-#endif
-
     if (initgroups( pwd->pw_name, pwd->pw_gid ) < 0) {
 #ifdef RUN_AS_USER
         LOG(log_info, logtype_afpd, "running with uid %d", geteuid());
@@ -320,17 +253,17 @@ static int login(AFPObj *obj, struct passwd *pwd, void (*logout)(void), int expi
 
     /* Basically if the user is in the admin group, we stay root */
 
-    if (( ngroups = getgroups( 0, NULL )) < 0 ) {
+    if ((obj->ngroups = getgroups( 0, NULL )) < 0 ) {
         LOG(log_error, logtype_afpd, "login: %s getgroups: %s", pwd->pw_name, strerror(errno) );
         return AFPERR_BADUAM;
     }
 
-    if ( NULL == (groups = calloc(ngroups, GROUPS_SIZE)) ) {
-        LOG(log_error, logtype_afpd, "login: %s calloc: %d", ngroups);
+    if ( NULL == (obj->groups = calloc(obj->ngroups, sizeof(gid_t))) ) {
+        LOG(log_error, logtype_afpd, "login: %s calloc: %d", obj->ngroups);
         return AFPERR_BADUAM;
     }
 
-    if (( ngroups = getgroups( ngroups, groups )) < 0 ) {
+    if (( obj->ngroups = getgroups(obj->ngroups, obj->groups )) < 0 ) {
         LOG(log_error, logtype_afpd, "login: %s getgroups: %s", pwd->pw_name, strerror(errno) );
         return AFPERR_BADUAM;
     }
@@ -340,8 +273,8 @@ static int login(AFPObj *obj, struct passwd *pwd, void (*logout)(void), int expi
 
     if (obj->options.admingid != 0) {
         int i;
-        for (i = 0; i < ngroups; i++) {
-            if (groups[i] == obj->options.admingid) admin = 1;
+        for (i = 0; i < obj->ngroups; i++) {
+            if (obj->groups[i] == obj->options.admingid) admin = 1;
         }
     }
     if (admin) {
@@ -392,26 +325,21 @@ static int login(AFPObj *obj, struct passwd *pwd, void (*logout)(void), int expi
     }
 #endif /* TRU64 */
 
-    LOG(log_debug, logtype_afpd, "login: supplementary groups: %s", print_groups(ngroups, groups));
+    LOG(log_debug, logtype_afpd, "login: supplementary groups: %s", print_groups(obj->ngroups, obj->groups));
 
     /* There's probably a better way to do this, but for now, we just play root */
 #ifdef ADMIN_GRP
     if (admin)
-        uuid = 0;
+        obj->uid = 0;
     else
 #endif /* ADMIN_GRP */
-        uuid = pwd->pw_uid;
+        obj->uid = geteuid();
 
-    set_auth_switch(expired);
+    set_auth_switch(obj, expired);
     /* save our euid, we need it for preexec_close */
     obj->uid = geteuid();
     obj->logout = logout;
 
-#ifdef FORCE_UIDGID
-    obj->force_uid = 1;
-    save_uidgid ( &obj->uidgid );
-#endif
-
     /* pam_umask or similar might have changed our umask */
     (void)umask(obj->options.umask);
 
@@ -422,7 +350,7 @@ static int login(AFPObj *obj, struct passwd *pwd, void (*logout)(void), int expi
 int afp_zzz(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
 {
     uint32_t data;
-    DSI *dsi = (DSI *)AFPobj->handle;
+    DSI *dsi = (DSI *)AFPobj->dsi;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -514,10 +442,10 @@ int afp_getsession(
     char   *ibuf, size_t ibuflen, 
     char   *rbuf, size_t *rbuflen)
 {
-    u_int16_t           type;
-    u_int32_t           idlen = 0;
-    u_int32_t       boottime;
-    u_int32_t           tklen, tp;
+    uint16_t           type;
+    uint32_t           idlen = 0;
+    uint32_t       boottime;
+    uint32_t           tklen, tp;
     char                *token;
     char                *p;
 
@@ -615,9 +543,9 @@ int afp_getsession(
 /* ---------------------- */
 int afp_disconnect(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
-    DSI                 *dsi = (DSI *)obj->handle;
-    u_int16_t           type;
-    u_int32_t           tklen;
+    DSI                 *dsi = (DSI *)obj->dsi;
+    uint16_t           type;
+    uint32_t           tklen;
     pid_t               token;
     int                 i;
 
@@ -705,7 +633,7 @@ static int get_version(AFPObj *obj, char *ibuf, size_t ibuflen, size_t len)
     num = sizeof( afp_versions ) / sizeof( afp_versions[ 0 ]);
     for ( i = 0; i < num; i++ ) {
         if ( strncmp( ibuf, afp_versions[ i ].av_name , len ) == 0 ) {
-            afp_version = afp_versions[ i ].av_number;
+            obj->afp_version = afp_versions[ i ].av_number;
             afp_version_index = i;
             break;
         }
@@ -713,11 +641,8 @@ static int get_version(AFPObj *obj, char *ibuf, size_t ibuflen, size_t len)
     if ( i == num )                 /* An inappropo version */
         return AFPERR_BADVERS ;
 
-    if (afp_version >= 30 && obj->proto != AFPPROTO_DSI)
-        return AFPERR_BADVERS ;
-
     /* FIXME Hack */
-    if (afp_version >= 30 && sizeof(off_t) != 8) {
+    if (obj->afp_version >= 30 && sizeof(off_t) != 8) {
         LOG(log_error, logtype_afpd, "get_version: no LARGE_FILE support recompile!" );
         return AFPERR_BADVERS ;
     }
@@ -783,7 +708,7 @@ int afp_login_ext(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *r
     size_t  len;
     int     i;
     char        type;
-    u_int16_t   len16;
+    uint16_t   len16;
     char        *username;
 
     *rbuflen = 0;
@@ -926,11 +851,11 @@ int afp_logincont(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *r
 
 int afp_logout(AFPObj *obj, char *ibuf _U_, size_t ibuflen  _U_, char *rbuf  _U_, size_t *rbuflen)
 {
-    DSI *dsi = (DSI *)(obj->handle);
+    DSI *dsi = (DSI *)(obj->dsi);
 
     LOG(log_note, logtype_afpd, "AFP logout by %s", obj->username);
-    of_close_all_forks();
-    close_all_vol();
+    of_close_all_forks(obj);
+    close_all_vol(obj);
     dsi->flags = DSI_AFP_LOGGED_OUT;
     *rbuflen = 0;
     return AFP_OK;
@@ -969,7 +894,7 @@ int afp_changepw(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rb
     if ((len + 1) & 1) /* pad byte */
         ibuf++;
 
-    if ( afp_version < 30) {
+    if (obj->afp_version < 30) {
         len = (unsigned char) *ibuf++;
         if ( len > sizeof(username) - 1) {
             return AFPERR_PARAM;
@@ -1006,7 +931,7 @@ int afp_changepw(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rb
         (ret == AFPERR_AUTHCONT) ? "continued" :
         (ret ? "failed" : "succeeded"));
     if ( ret == AFP_OK )
-        set_auth_switch(0);
+        set_auth_switch(obj, 0);
 
     return ret;
 }
@@ -1015,9 +940,9 @@ int afp_changepw(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rb
 /* FPGetUserInfo */
 int afp_getuserinfo(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
-    u_int8_t  thisuser;
-    u_int32_t id;
-    u_int16_t bitmap;
+    uint8_t  thisuser;
+    uint32_t id;
+    uint16_t bitmap;
     char *bitmapp;
 
     LOG(log_debug, logtype_afpd, "begin afp_getuserinfo:");
@@ -1132,7 +1057,7 @@ int auth_load(const char *path, const char *list)
         return -1;
 
     strlcpy(buf, list, sizeof(buf));
-    if ((p = strtok(buf, ",")) == NULL)
+    if ((p = strtok(buf, ", ")) == NULL)
         return -1;
 
     strcpy(name, path);
@@ -1157,7 +1082,7 @@ int auth_load(const char *path, const char *list)
         } else {
             LOG(log_info, logtype_afpd, "uam: uam not found (status=%d)", stat(name, &st));
         }
-        p = strtok(NULL, ",");
+        p = strtok(NULL, ", ");
     }
 
     return 0;
index beda0d02ffdcb9d2c92d818560e84423017c93ae..2e9d6a584e3f66a94166f9337f49e296d8ac61b0 100644 (file)
@@ -6,13 +6,7 @@
 #ifndef AFPD_AUTH_H
 #define AFPD_AUTH_H 1
 
-#ifdef HAVE_LIMITS_H
 #include <limits.h>
-#endif /* HAVE_LIMITS_H */
-
-#ifdef HAVE_SYS_CDEFS_H
-#include <sys/cdefs.h>
-#endif /* HAVE_SYS_CDEFS_H */
 
 #include <atalk/globals.h>
 
@@ -22,11 +16,6 @@ struct afp_versions {
 };
 
 static const struct afp_versions  afp_versions[] = {
-#ifndef NO_DDP
-    { "AFPVersion 1.1", 11 },
-    { "AFPVersion 2.0", 20 },
-    { "AFPVersion 2.1", 21 },
-#endif /* ! NO_DDP */
     { "AFP2.2", 22 },
     { "AFPX03", 30 },
     { "AFP3.1", 31 },
index 89a6d5733aed67b6c13de4d41f8b3f357928d0c2..71843e2cd13237863791a396e9e389a8156dcf46 100644 (file)
@@ -48,6 +48,7 @@
 #include <atalk/bstradd.h>
 #include <atalk/unicode.h>
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
 
 #include "desktop.h"
 #include "directory.h"
 
 
 struct finderinfo {
-       u_int32_t f_type;
-       u_int32_t creator;
-       u_int16_t attrs;    /* File attributes (high 8 bits)*/
-       u_int16_t label;    /* Label (low 8 bits )*/
+       uint32_t f_type;
+       uint32_t creator;
+       uint16_t attrs;    /* File attributes (high 8 bits)*/
+       uint16_t label;    /* Label (low 8 bits )*/
        char reserved[22]; /* Unknown (at least for now...) */
 };
 
@@ -86,14 +87,14 @@ typedef char packed_finder[ADEDLEN_FINDERI];
 
 /* This is our search-criteria structure. */
 struct scrit {
-       u_int32_t rbitmap;          /* Request bitmap - which values should we check ? */
-       u_int16_t fbitmap, dbitmap; /* file & directory bitmap - which values should we return ? */
-       u_int16_t attr;             /* File attributes */
+       uint32_t rbitmap;          /* Request bitmap - which values should we check ? */
+       uint16_t fbitmap, dbitmap; /* file & directory bitmap - which values should we return ? */
+       uint16_t attr;             /* File attributes */
        time_t cdate;               /* Creation date */
        time_t mdate;               /* Last modification date */
        time_t bdate;               /* Last backup date */
-       u_int32_t pdid;             /* Parent DID */
-    u_int16_t offcnt;           /* Offspring count */
+       uint32_t pdid;             /* Parent DID */
+    uint16_t offcnt;           /* Offspring count */
        struct finderinfo finfo;    /* Finder info */
        char lname[64];             /* Long name */ 
        char utf8name[514];         /* UTF8 or UCS2 name */ /* for convert_charset dest_len parameter +2 */
@@ -213,7 +214,7 @@ static struct adouble *adl_lkup(struct vol *vol, struct path *path, struct adoub
        if (!isdir && (of = of_findname(path))) {
                adp = of->of_ad;
        } else {
-               ad_init(&ad, vol->v_adouble, vol->v_ad_options);
+               ad_init(&ad, vol);
                adp = &ad;
        } 
 
@@ -260,11 +261,11 @@ unpack_finderinfo(struct vol *vol, struct path *path, struct adouble **adp, stru
  */
 static int crit_check(struct vol *vol, struct path *path) {
        int result = 0;
-       u_int16_t attr, flags = CONV_PRECOMPOSE;
+       uint16_t attr, flags = CONV_PRECOMPOSE;
        struct finderinfo *finfo = NULL, finderinfo;
        struct adouble *adp = NULL;
        time_t c_date, b_date;
-       u_int32_t ac_date, ab_date;
+       uint32_t ac_date, ab_date;
        static char convbuf[514]; /* for convert_charset dest_len parameter +2 */
        size_t len;
     int islnk;
@@ -283,7 +284,7 @@ static int crit_check(struct vol *vol, struct path *path) {
                 * An other option would be to call get_id in utompath but 
                 * we need to pass parent dir
                */
-        if (!(path->m_name = utompath(vol, path->u_name, 0 , utf8_encoding()) )) {
+        if (!(path->m_name = utompath(vol, path->u_name, 0 , utf8_encoding(vol->v_obj)) )) {
                /*retry with the right id */
        
                cnid_t id;
@@ -296,7 +297,7 @@ static int crit_check(struct vol *vol, struct path *path) {
                }
                /* save the id for getfilparm */
                path->id = id;
-               if (!(path->m_name = utompath(vol, path->u_name, id , utf8_encoding()))) {
+               if (!(path->m_name = utompath(vol, path->u_name, id , utf8_encoding(vol->v_obj)))) {
                        return 0;
                }
         }
@@ -421,18 +422,18 @@ static int crit_check(struct vol *vol, struct path *path) {
        result |= 1;
 crit_check_ret:
        if (adp != NULL)
-               ad_close_metadata(adp);
+               ad_close(adp, ADFLAGS_HF);
        return result;
 }  
 
 /* ------------------------------ */
-static int rslt_add ( struct vol *vol, struct path *path, char **buf, int ext)
+static int rslt_add (const AFPObj *obj, struct vol *vol, struct path *path, char **buf, int ext)
 {
 
        char            *p = *buf;
        int             ret;
        size_t          tbuf =0;
-       u_int16_t       resultsize;
+       uint16_t        resultsize;
        int             isdir = S_ISDIR(path->st.st_mode); 
 
        /* Skip resultsize */
@@ -449,11 +450,11 @@ static int rslt_add ( struct vol *vol, struct path *path, char **buf, int ext)
        }
        
        if ( isdir ) {
-        ret = getdirparams(vol, c1.dbitmap, path, path->d_dir, p , &tbuf ); 
+        ret = getdirparams(obj, vol, c1.dbitmap, path, path->d_dir, p , &tbuf ); 
        }
        else {
            /* FIXME slow if we need the file ID, we already know it, done ? */
-               ret = getfilparams ( vol, c1.fbitmap, path, path->d_dir, p, &tbuf);
+               ret = getfilparams (obj, vol, c1.fbitmap, path, path->d_dir, p, &tbuf, 0);
        }
 
        if ( ret != AFP_OK )
@@ -496,7 +497,8 @@ static int rslt_add ( struct vol *vol, struct path *path, char **buf, int ext)
  * @param ext       (r)  extended search flag
  */
 #define NUM_ROUNDS 200
-static int catsearch(struct vol *vol,
+static int catsearch(const AFPObj *obj,
+                     struct vol *vol,
                      struct dir *dir,  
                      int rmatches,
                      uint32_t *pos,
@@ -505,7 +507,7 @@ static int catsearch(struct vol *vol,
                      int *rsize,
                      int ext)
 {
-    static u_int32_t cur_pos;    /* Saved position index (ID) - used to remember "position" across FPCatSearch calls */
+    static uint32_t cur_pos;    /* Saved position index (ID) - used to remember "position" across FPCatSearch calls */
     static DIR *dirpos;                 /* UNIX structure describing currently opened directory. */
     struct dir *currentdir;      /* struct dir of current directory */
        int cidx, r;
@@ -647,7 +649,7 @@ static int catsearch(struct vol *vol,
 
                        /* bit 0 means that criteria has been met */
                        if ((ccr & 1)) {
-                               r = rslt_add ( vol, &path, &rrbuf, ext);
+                               r = rslt_add (obj, vol, &path, &rrbuf, ext);
                                
                                if (r == 0) {
                                        result = AFPERR_MISC;
@@ -709,7 +711,8 @@ catsearch_end: /* Exiting catsearch: error condition */
  * @param rsize     (w)  length of data written to output buffer
  * @param ext       (r)  extended search flag
  */
-static int catsearch_db(struct vol *vol,
+static int catsearch_db(const AFPObj *obj,
+                        struct vol *vol,
                         struct dir *dir,  
                         const char *uname,
                         int rmatches,
@@ -784,7 +787,7 @@ static int catsearch_db(struct vol *vol,
 
         memset(&path, 0, sizeof(path));
         path.u_name = name;
-        path.m_name = utompath(vol, name, cnid, utf8_encoding());
+        path.m_name = utompath(vol, name, cnid, utf8_encoding(vol->v_obj));
 
         if (of_stat(&path) != 0) {
             switch (errno) {
@@ -813,7 +816,7 @@ static int catsearch_db(struct vol *vol,
             LOG(log_debug, logtype_afpd,"catsearch_db: match: %s/%s",
                 getcwdpath(), path.u_name);
             /* bit 1 means that criteria has been met */
-            r = rslt_add(vol, &path, &rrbuf, ext);
+            r = rslt_add(obj, vol, &path, &rrbuf, ext);
             if (r == 0) {
                 result = AFPERR_MISC;
                 goto catsearch_end;
@@ -849,17 +852,17 @@ static int catsearch_afp(AFPObj *obj _U_, char *ibuf, size_t ibuflen,
                   char *rbuf, size_t *rbuflen, int ext)
 {
     struct vol *vol;
-    u_int16_t   vid;
-    u_int16_t   spec_len;
-    u_int32_t   rmatches, reserved;
-    u_int32_t  catpos[4];
-    u_int32_t   pdid = 0;
+    uint16_t   vid;
+    uint16_t   spec_len;
+    uint32_t   rmatches, reserved;
+    uint32_t   catpos[4];
+    uint32_t   pdid = 0;
     int ret, rsize;
-    u_int32_t nrecs = 0;
+    uint32_t nrecs = 0;
     unsigned char *spec1, *spec2, *bspec1, *bspec2;
     size_t     len;
-    u_int16_t  namelen;
-    u_int16_t  flags;
+    uint16_t   namelen;
+    uint16_t   flags;
     char           tmppath[256];
     char        *uname;
 
@@ -1037,7 +1040,7 @@ static int catsearch_afp(AFPObj *obj _U_, char *ibuf, size_t ibuflen,
 
                memcpy (c1.utf8name, spec1+2, namelen);
                c1.utf8name[namelen] = 0;
-        if ((uname = mtoupath(vol, c1.utf8name, 0, utf8_encoding())) == NULL)
+        if ((uname = mtoupath(vol, c1.utf8name, 0, utf8_encoding(obj))) == NULL)
             return AFPERR_PARAM;
 
                /* convert charset */
@@ -1054,10 +1057,10 @@ static int catsearch_afp(AFPObj *obj _U_, char *ibuf, size_t ibuflen,
         && (strcmp(vol->v_cnidscheme, "dbd") == 0)
         && (vol->v_flags & AFPVOL_SEARCHDB))
         /* we've got a name and it's a dbd volume, so search CNID database */
-        ret = catsearch_db(vol, vol->v_root, uname, rmatches, &catpos[0], rbuf+24, &nrecs, &rsize, ext);
+        ret = catsearch_db(obj, vol, vol->v_root, uname, rmatches, &catpos[0], rbuf+24, &nrecs, &rsize, ext);
     else
         /* perform a slow filesystem tree search */
-        ret = catsearch(vol, vol->v_root, rmatches, &catpos[0], rbuf+24, &nrecs, &rsize, ext);
+        ret = catsearch(obj, vol, vol->v_root, rmatches, &catpos[0], rbuf+24, &nrecs, &rsize, ext);
 
     memcpy(rbuf, catpos, sizeof(catpos));
     rbuf += sizeof(catpos);
index 8b6efd7e1bdac95dc73170d0ab6c0bdc4940b42c..c437b7e6b4adb92f2a2c03388b401b3ad2eb8082 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: desktop.c,v 1.50.2.1 2010-02-01 10:56:08 franklahm Exp $
- *
  * See COPYRIGHT.
  *
  * bug:
 #include <sys/uio.h>
 #include <sys/param.h>
 #include <sys/socket.h>
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/dsi.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
 #include <atalk/afp.h>
 #include <atalk/util.h>
 #include <atalk/logger.h>
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
+#include <atalk/unix.h>
+#include <atalk/bstrlib.h>
+#include <atalk/errchk.h>
+
 #include "volume.h"
 #include "directory.h"
 #include "fork.h"
 #include "desktop.h"
 #include "mangle.h"
 
+#define EXEC_MODE (S_IXGRP | S_IXUSR | S_IXOTH)
+
+int setdeskmode(const struct vol *vol, const mode_t mode)
+{
+    EC_INIT;
+    char               wd[ MAXPATHLEN + 1];
+    struct stat         st;
+    char               modbuf[ 12 + 1], *m;
+    struct dirent      *deskp, *subp;
+    DIR                        *desk, *sub;
+
+    if (!dir_rx_set(mode)) {
+        /* want to remove read and search access to owner it will screw the volume */
+        return -1 ;
+    }
+    if ( getcwd( wd , MAXPATHLEN) == NULL ) {
+        return( -1 );
+    }
+
+    bstring dtpath = bfromcstr(vol->v_dbpath);
+    bcatcstr(dtpath, "/" APPLEDESKTOP);
+
+    EC_NEG1( chdir(bdata(dtpath)) );
+
+    if (( desk = opendir( "." )) == NULL ) {
+        if ( chdir( wd ) < 0 ) {
+            LOG(log_error, logtype_afpd, "setdeskmode: chdir %s: %s", wd, strerror(errno) );
+        }
+        EC_FAIL;
+    }
+    for ( deskp = readdir( desk ); deskp != NULL; deskp = readdir( desk )) {
+        if ( strcmp( deskp->d_name, "." ) == 0 ||
+                strcmp( deskp->d_name, ".." ) == 0 || strlen( deskp->d_name ) > 2 ) {
+            continue;
+        }
+        strcpy( modbuf, deskp->d_name );
+        strcat( modbuf, "/" );
+        m = strchr( modbuf, '\0' );
+        if (( sub = opendir( deskp->d_name )) == NULL ) {
+            continue;
+        }
+        for ( subp = readdir( sub ); subp != NULL; subp = readdir( sub )) {
+            if ( strcmp( subp->d_name, "." ) == 0 ||
+                    strcmp( subp->d_name, ".." ) == 0 ) {
+                continue;
+            }
+            *m = '\0';
+            strcat( modbuf, subp->d_name );
+            /* XXX: need to preserve special modes */
+            if (lstat(modbuf, &st) < 0) {
+                LOG(log_error, logtype_afpd, "setdeskmode: stat %s: %s",fullpathname(modbuf), strerror(errno) );
+                continue;
+            }
+
+            if (S_ISDIR(st.st_mode)) {
+                if ( chmod_acl( modbuf,  (DIRBITS | mode)) < 0 && errno != EPERM ) {
+                     LOG(log_error, logtype_afpd, "setdeskmode: chmod %s: %s",fullpathname(modbuf), strerror(errno) );
+                }
+            } else if ( chmod_acl( modbuf,  mode & ~EXEC_MODE ) < 0 && errno != EPERM ) {
+                LOG(log_error, logtype_afpd, "setdeskmode: chmod %s: %s",fullpathname(modbuf), strerror(errno) );
+            }
+
+        }
+        closedir( sub );
+        /* XXX: need to preserve special modes */
+        if ( chmod_acl( deskp->d_name,  (DIRBITS | mode)) < 0 && errno != EPERM ) {
+            LOG(log_error, logtype_afpd, "setdeskmode: chmod %s: %s",fullpathname(deskp->d_name), strerror(errno) );
+        }
+    }
+    closedir( desk );
+    if ( chdir( wd ) < 0 ) {
+        LOG(log_error, logtype_afpd, "setdeskmode: chdir %s: %s", wd, strerror(errno) );
+        EC_FAIL;
+    }
+    /* XXX: need to preserve special modes */
+    if ( chmod_acl(bdata(dtpath),  (DIRBITS | mode)) < 0 && errno != EPERM ) {
+        LOG(log_error, logtype_afpd, "setdeskmode: chmod %s: %s", bdata(dtpath), strerror(errno));
+    }
+
+EC_CLEANUP:
+    bdestroy(dtpath);
+    EC_EXIT;
+}
+
+int setdeskowner(const struct vol *vol, uid_t uid, gid_t gid)
+{
+    EC_INIT;
+    char               wd[ MAXPATHLEN + 1];
+    char               modbuf[12 + 1], *m;
+    struct dirent      *deskp, *subp;
+    DIR                        *desk, *sub;
+
+    if ( getcwd( wd, MAXPATHLEN ) == NULL ) {
+        return( -1 );
+    }
+
+    bstring dtpath = bfromcstr(vol->v_dbpath);
+    bcatcstr(dtpath, "/" APPLEDESKTOP);
+
+    EC_NEG1( chdir(bdata(dtpath)) );
+    
+    if (( desk = opendir( "." )) == NULL ) {
+        if ( chdir( wd ) < 0 ) {
+            LOG(log_error, logtype_afpd, "setdeskowner: chdir %s: %s", wd, strerror(errno) );
+        }
+        EC_FAIL;
+    }
+    for ( deskp = readdir( desk ); deskp != NULL; deskp = readdir( desk )) {
+        if ( strcmp( deskp->d_name, "." ) == 0 ||
+                strcmp( deskp->d_name, ".." ) == 0 ||
+                strlen( deskp->d_name ) > 2 ) {
+            continue;
+        }
+        strcpy( modbuf, deskp->d_name );
+        strcat( modbuf, "/" );
+        m = strchr( modbuf, '\0' );
+        if (( sub = opendir( deskp->d_name )) == NULL ) {
+            continue;
+        }
+        for ( subp = readdir( sub ); subp != NULL; subp = readdir( sub )) {
+            if ( strcmp( subp->d_name, "." ) == 0 ||
+                    strcmp( subp->d_name, ".." ) == 0 ) {
+                continue;
+            }
+            *m = '\0';
+            strcat( modbuf, subp->d_name );
+            /* XXX: add special any uid, ignore group bits */
+            if ( chown( modbuf, uid, gid ) < 0 && errno != EPERM ) {
+                LOG(log_error, logtype_afpd, "setdeskown: chown %s: %s", fullpathname(modbuf), strerror(errno) );
+            }
+        }
+        closedir( sub );
+        /* XXX: add special any uid, ignore group bits */
+        if ( chown( deskp->d_name, uid, gid ) < 0 && errno != EPERM ) {
+            LOG(log_error, logtype_afpd, "setdeskowner: chown %s: %s",
+                deskp->d_name, strerror(errno) );
+        }
+    }
+    closedir( desk );
+    if ( chdir( wd ) < 0 ) {
+        LOG(log_error, logtype_afpd, "setdeskowner: chdir %s: %s", wd, strerror(errno) );
+        EC_FAIL;
+    }
+    if (chown(bdata(dtpath), uid, gid ) < 0 && errno != EPERM ) {
+        LOG(log_error, logtype_afpd, "setdeskowner: chown %s: %s", fullpathname(".AppleDouble"), strerror(errno) );
+    }
+
+EC_CLEANUP:
+    bdestroy(dtpath);
+    EC_EXIT;
+}
+
+static void create_appledesktop_folder(const struct vol * vol)
+{
+    bstring olddtpath = NULL, dtpath = NULL;
+    struct stat st;
+    char *cmd_argv[4];
+
+    olddtpath = bfromcstr(vol->v_path);
+    bcatcstr(olddtpath, "/" APPLEDESKTOP);
+
+    dtpath = bfromcstr(vol->v_dbpath);
+    bcatcstr(dtpath, "/" APPLEDESKTOP);
+
+    if (lstat(bdata(dtpath), &st) != 0) {
+
+        become_root();
+
+        if (lstat(bdata(olddtpath), &st) == 0) {
+            cmd_argv[0] = "mv";
+            cmd_argv[1] = bdata(olddtpath);
+            cmd_argv[2] = bdata(dtpath);
+            cmd_argv[3] = NULL;
+            if (run_cmd("mv", cmd_argv) != 0) {
+                LOG(log_error, logtype_afpd, "moving .AppleDesktop from \"%s\" to \"%s\" failed",
+                    bdata(olddtpath), bdata(dtpath));
+                mkdir(bdata(dtpath), 0777);
+            }
+        } else {
+            mkdir(bdata(dtpath), 0777);
+        }
+
+        unbecome_root();
+    }
+
+    bdestroy(dtpath);
+    bdestroy(olddtpath);
+}
 
 int afp_opendt(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
     struct vol *vol;
-    u_int16_t  vid;
+    uint16_t   vid;
 
     ibuf += 2;
 
@@ -52,6 +241,8 @@ int afp_opendt(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size
         return( AFPERR_PARAM );
     }
 
+    create_appledesktop_folder(vol);
+
     memcpy( rbuf, &vid, sizeof(vid));
     *rbuflen = sizeof(vid);
     return( AFP_OK );
@@ -118,14 +309,11 @@ static int iconopen(struct vol *vol, u_char creator[ 4 ], int flags, int mode)
 int afp_addicon(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
     struct vol         *vol;
-#ifndef NO_DDP
-    struct iovec       iov[ 2 ];
-#endif
     u_char             fcreator[ 4 ], imh[ 12 ], irh[ 12 ], *p;
     int                        itype, cc = AFP_OK, iovcnt = 0;
     size_t             buflen;
-    u_int32_t           ftype, itag;
-    u_int16_t          bsize, rsize, vid;
+    uint32_t           ftype, itag;
+    uint16_t           bsize, rsize, vid;
 
     buflen = *rbuflen;
     *rbuflen = 0;
@@ -211,80 +399,34 @@ int afp_addicon(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
      */
 addicon_err:
     if ( cc < 0 ) {
-        if (obj->proto == AFPPROTO_DSI) {
-            dsi_writeinit(obj->handle, rbuf, buflen);
-            dsi_writeflush(obj->handle);
-        }
+        dsi_writeinit(obj->dsi, rbuf, buflen);
+        dsi_writeflush(obj->dsi);
         return cc;
     }
 
-    switch (obj->proto) {
-#ifndef NO_DDP
-    case AFPPROTO_ASP:
-        buflen = bsize;
-        if ((asp_wrtcont(obj->handle, rbuf, &buflen) < 0) || buflen != bsize)
-            return( AFPERR_PARAM );
-
-#ifdef DEBUG1
-        if (obj->options.flags & OPTION_DEBUG) {
-            printf("(write) len: %d\n", buflen);
-            bprint(rbuf, buflen);
-        }
-#endif
+    DSI *dsi = obj->dsi;
 
-        /*
-         * We're at the end of the file, add the headers, etc.  */
-        if ( cc == 0 ) {
-            iov[ 0 ].iov_base = (caddr_t)imh;
-            iov[ 0 ].iov_len = sizeof( imh );
-            iov[ 1 ].iov_base = rbuf;
-            iov[ 1 ].iov_len = bsize;
-            iovcnt = 2;
-        }
+    iovcnt = dsi_writeinit(dsi, rbuf, buflen);
 
-        /*
-         * We found an icon to replace.
-         */
-        if ( cc > 0 ) {
-            iov[ 0 ].iov_base = rbuf;
-            iov[ 0 ].iov_len = bsize;
-            iovcnt = 1;
-        }
-
-        if ( writev( si.sdt_fd, iov, iovcnt ) < 0 ) {
-            LOG(log_error, logtype_afpd, "afp_addicon(%s): writev: %s", icon_dtfile(vol, fcreator), strerror(errno) );
-            return( AFPERR_PARAM );
-        }
-        break;
-#endif /* no afp/asp */      
-    case AFPPROTO_DSI:
-        {
-            DSI *dsi = obj->handle;
-
-            iovcnt = dsi_writeinit(dsi, rbuf, buflen);
-
-            /* add headers at end of file */
-            if ((cc == 0) && (write(si.sdt_fd, imh, sizeof(imh)) < 0)) {
-                LOG(log_error, logtype_afpd, "afp_addicon(%s): write: %s", icon_dtfile(vol, fcreator), strerror(errno));
-                dsi_writeflush(dsi);
-                return AFPERR_PARAM;
-            }
+    /* add headers at end of file */
+    if ((cc == 0) && (write(si.sdt_fd, imh, sizeof(imh)) < 0)) {
+        LOG(log_error, logtype_afpd, "afp_addicon(%s): write: %s", icon_dtfile(vol, fcreator), strerror(errno));
+        dsi_writeflush(dsi);
+        return AFPERR_PARAM;
+    }
 
-            if ((cc = write(si.sdt_fd, rbuf, iovcnt)) < 0) {
-                LOG(log_error, logtype_afpd, "afp_addicon(%s): write: %s", icon_dtfile(vol, fcreator), strerror(errno));
-                dsi_writeflush(dsi);
-                return AFPERR_PARAM;
-            }
+    if ((cc = write(si.sdt_fd, rbuf, iovcnt)) < 0) {
+        LOG(log_error, logtype_afpd, "afp_addicon(%s): write: %s", icon_dtfile(vol, fcreator), strerror(errno));
+        dsi_writeflush(dsi);
+        return AFPERR_PARAM;
+    }
 
-            while ((iovcnt = dsi_write(dsi, rbuf, buflen))) {
-                if ((cc = write(si.sdt_fd, rbuf, iovcnt)) < 0) {
-                    LOG(log_error, logtype_afpd, "afp_addicon(%s): write: %s", icon_dtfile(vol, fcreator), strerror(errno));
-                    dsi_writeflush(dsi);
-                    return AFPERR_PARAM;
-                }
-            }
+    while ((iovcnt = dsi_write(dsi, rbuf, buflen))) {
+        if ((cc = write(si.sdt_fd, rbuf, iovcnt)) < 0) {
+            LOG(log_error, logtype_afpd, "afp_addicon(%s): write: %s", icon_dtfile(vol, fcreator), strerror(errno));
+            dsi_writeflush(dsi);
+            return AFPERR_PARAM;
         }
-        break;
     }
 
     close( si.sdt_fd );
@@ -337,8 +479,8 @@ static const u_char uicon[] = {
 int afp_geticoninfo(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
     struct vol *vol;
-    u_char     fcreator[ 4 ], ih[ 12 ];
-    u_int16_t  vid, iindex, bsize;
+    unsigned char      fcreator[ 4 ], ih[ 12 ];
+    uint16_t   vid, iindex, bsize;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -411,7 +553,7 @@ int afp_geticon(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
     off_t       offset;
     ssize_t    rc, buflen;
     u_char     fcreator[ 4 ], ftype[ 4 ], itype, ih[ 12 ];
-    u_int16_t  vid, bsize, rsize;
+    uint16_t   vid, bsize, rsize;
 
     buflen = *rbuflen;
     *rbuflen = 0;
@@ -486,8 +628,8 @@ int afp_geticon(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
 #define min(a,b)       ((a)<(b)?(a):(b))
     rc = min( bsize, rsize );
 
-    if ((obj->proto == AFPPROTO_DSI) && (buflen < rc)) {
-        DSI *dsi = obj->handle;
+    if (buflen < rc) {
+        DSI *dsi = obj->dsi;
         struct stat st;
         off_t size;
 
@@ -496,29 +638,29 @@ int afp_geticon(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
             return AFPERR_PARAM;
         }
 
+#ifndef WITH_SENDFILE
         if ((buflen = dsi_readinit(dsi, rbuf, buflen, rc, AFP_OK)) < 0)
             goto geticon_exit;
+#endif
 
         *rbuflen = buflen;
         /* do to the streaming nature, we have to exit if we encounter
          * a problem. much confusion results otherwise. */
         while (*rbuflen > 0) {
 #ifdef WITH_SENDFILE
-            if (!obj->options.flags & OPTION_DEBUG) {
-                if (dsi_stream_read_file(dsi, si.sdt_fd, offset, dsi->datasize) < 0) {
-                    switch (errno) {
-                    case ENOSYS:
-                    case EINVAL:  /* there's no guarantee that all fs support sendfile */
-                        break;
-                    default:
-                        goto geticon_exit;
-                    }
-                }
-                else {
-                    dsi_readdone(dsi);
-                    return AFP_OK;
+            if (dsi_stream_read_file(dsi, si.sdt_fd, offset, dsi->datasize, AFP_OK) < 0) {
+                switch (errno) {
+                case ENOSYS:
+                case EINVAL:  /* there's no guarantee that all fs support sendfile */
+                    break;
+                default:
+                    goto geticon_exit;
                 }
             }
+            else {
+                dsi_readdone(dsi);
+                return AFP_OK;
+            }
 #endif
             buflen = read(si.sdt_fd, rbuf, *rbuflen);
             if (buflen < 0)
@@ -558,8 +700,8 @@ char *dtfile(const struct vol *vol, u_char creator[], char *ext )
     char       *p;
     unsigned int i;
 
-    strcpy( path, vol->v_path );
-    strcat( path, "/.AppleDesktop/" );
+    strcpy( path, vol->v_dbpath );
+    strcat( path, "/" APPLEDESKTOP "/" );
     for ( p = path; *p != '\0'; p++ )
         ;
 
@@ -597,7 +739,7 @@ char *mtoupath(const struct vol *vol, char *mpath, cnid_t did, int utf8)
     char       *m, *u;
     size_t       inplen;
     size_t       outlen;
-    u_int16_t   flags;
+    uint16_t    flags;
         
     if ( *mpath == '\0' ) {
         strcpy(upath, ".");
@@ -636,7 +778,7 @@ char *utompath(const struct vol *vol, char *upath, cnid_t id, int utf8)
 {
     static char  mpath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
     char        *m, *u;
-    u_int16_t    flags;
+    uint16_t    flags;
     size_t       outlen;
 
     m = mpath;
@@ -671,7 +813,7 @@ utompath_error:
 }
 
 /* ------------------------- */
-static int ad_addcomment(struct vol *vol, struct path *path, char *ibuf)
+static int ad_addcomment(const AFPObj *obj, struct vol *vol, struct path *path, char *ibuf)
 {
     struct ofork        *of;
     char                *name, *upath;
@@ -683,18 +825,20 @@ static int ad_addcomment(struct vol *vol, struct path *path, char *ibuf)
     clen = min( clen, 199 );
 
     upath = path->u_name;
-    if (check_access(upath, OPENACC_WR ) < 0) {
+    if (check_access(obj, vol, upath, OPENACC_WR ) < 0) {
         return AFPERR_ACCESS;
     }
     
     isadir = path_isadir(path);
     if (isadir || !(of = of_findname(path))) {
-        ad_init(&ad, vol->v_adouble, vol->v_ad_options);
+        ad_init(&ad, vol);
         adp = &ad;
     } else
         adp = of->of_ad;
 
-    if (ad_open_metadata( upath , ( (isadir) ? ADFLAGS_DIR : 0), O_CREAT, adp) < 0 ) {
+    if (ad_open(adp, upath,
+                ADFLAGS_HF | ( (isadir) ? ADFLAGS_DIR : 0) | ADFLAGS_CREATE | ADFLAGS_RDWR,
+                0666) < 0 ) {
         return( AFPERR_ACCESS );
     }
 
@@ -711,18 +855,18 @@ static int ad_addcomment(struct vol *vol, struct path *path, char *ibuf)
         memcpy( ad_entry( adp, ADEID_COMMENT ), ibuf, clen );
         ad_flush( adp );
     }
-    ad_close_metadata( adp);
+    ad_close(adp, ADFLAGS_HF);
     return( AFP_OK );
 }
 
 /* ----------------------------- */
-int afp_addcomment(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
+int afp_addcomment(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
     struct vol         *vol;
     struct dir         *dir;
     struct path         *path;
-    u_int32_t           did;
-    u_int16_t          vid;
+    uint32_t           did;
+    uint16_t           vid;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -747,7 +891,7 @@ int afp_addcomment(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _
         ibuf++;
     }
 
-    return ad_addcomment(vol, path, ibuf);
+    return ad_addcomment(obj, vol, path, ibuf);
 }
 
 /* -------------------- */
@@ -762,7 +906,7 @@ static int ad_getcomment(struct vol *vol, struct path *path, char *rbuf, size_t
     upath = path->u_name;
     isadir = path_isadir(path);
     if (isadir || !(of = of_findname(path))) {
-        ad_init(&ad, vol->v_adouble, vol->v_ad_options);
+        ad_init(&ad, vol);
         adp = &ad;
     } else
         adp = of->of_ad;
@@ -772,7 +916,7 @@ static int ad_getcomment(struct vol *vol, struct path *path, char *rbuf, size_t
     }
 
     if (!ad_getentryoff(adp, ADEID_COMMENT)) {
-        ad_close_metadata( adp );
+        ad_close(adp, ADFLAGS_HF);
         return AFPERR_NOITEM;
     }
     /*
@@ -780,7 +924,7 @@ static int ad_getcomment(struct vol *vol, struct path *path, char *rbuf, size_t
      */
     if ( ad_getentrylen( adp, ADEID_COMMENT ) <= 0 ||
             ad_getentrylen( adp, ADEID_COMMENT ) > 199 ) {
-        ad_close_metadata( adp );
+        ad_close(adp, ADFLAGS_HF);
         return( AFPERR_NOITEM );
     }
 
@@ -788,7 +932,7 @@ static int ad_getcomment(struct vol *vol, struct path *path, char *rbuf, size_t
     *rbuf++ = clen;
     memcpy( rbuf, ad_entry( adp, ADEID_COMMENT ), clen);
     *rbuflen = clen + 1;
-    ad_close_metadata( adp);
+    ad_close(adp, ADFLAGS_HF);
 
     return( AFP_OK );
 }
@@ -799,8 +943,8 @@ int afp_getcomment(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf,
     struct vol         *vol;
     struct dir         *dir;
     struct path         *s_path;
-    u_int32_t          did;
-    u_int16_t          vid;
+    uint32_t           did;
+    uint16_t           vid;
     
     *rbuflen = 0;
     ibuf += 2;
@@ -825,7 +969,7 @@ int afp_getcomment(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf,
 }
 
 /* ----------------------- */
-static int ad_rmvcomment(struct vol *vol, struct path *path)
+static int ad_rmvcomment(const AFPObj *obj, struct vol *vol, struct path *path)
 {
     struct adouble     ad, *adp;
     struct ofork        *of;
@@ -833,18 +977,18 @@ static int ad_rmvcomment(struct vol *vol, struct path *path)
     char               *upath;
 
     upath = path->u_name;
-    if (check_access(upath, OPENACC_WR ) < 0) {
+    if (check_access(obj, vol, upath, OPENACC_WR ) < 0) {
         return AFPERR_ACCESS;
     }
 
     isadir = path_isadir(path);
     if (isadir || !(of = of_findname(path))) {
-        ad_init(&ad, vol->v_adouble, vol->v_ad_options);
+        ad_init(&ad, vol);
         adp = &ad;
     } else
         adp = of->of_ad;
 
-    if ( ad_open_metadata( upath, (isadir) ? ADFLAGS_DIR : 0, 0, adp) < 0 ) {
+    if ( ad_open(adp, upath, ADFLAGS_HF | ADFLAGS_RDWR | ((isadir) ? ADFLAGS_DIR : 0)) < 0 ) {
         switch ( errno ) {
         case ENOENT :
             return( AFPERR_NOITEM );
@@ -859,7 +1003,7 @@ static int ad_rmvcomment(struct vol *vol, struct path *path)
         ad_setentrylen( adp, ADEID_COMMENT, 0 );
         ad_flush( adp );
     }
-    ad_close_metadata( adp);
+    ad_close(adp, ADFLAGS_HF);
     return( AFP_OK );
 }
 
@@ -869,8 +1013,8 @@ int afp_rmvcomment(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _
     struct vol         *vol;
     struct dir         *dir;
     struct path         *s_path;
-    u_int32_t          did;
-    u_int16_t          vid;
+    uint32_t           did;
+    uint16_t           vid;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -891,5 +1035,5 @@ int afp_rmvcomment(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _
        return get_afp_errno(AFPERR_NOOBJ);
     }
     
-    return ad_rmvcomment(vol, s_path);
+    return ad_rmvcomment(obj, vol, s_path);
 }
index a220a478ee7eebf19841f3c69fcb2f43217ab32f..5f8242439e98fad5534637e6cdf6b4b9b9eb1e9e 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: desktop.h,v 1.6 2009-10-15 10:43:13 didg Exp $
- *
  * Copyright (c) 1990,1991 Regents of The University of Michigan.
  * All Rights Reserved.
  *
 #ifndef AFPD_DESKTOP_H
 #define AFPD_DESKTOP_H 1
 
-#include <sys/cdefs.h>
 #include <atalk/globals.h>
+
 #include "volume.h"
 
+#define APPLEDESKTOP ".AppleDesktop"
+
 struct savedt {
     u_char     sdt_creator[ 4 ];
     int                sdt_fd;
@@ -43,6 +43,9 @@ extern char   *dtfile (const struct vol *, u_char [], char *);
 extern char    *mtoupath (const struct vol *, char *, cnid_t, int utf8);
 extern char    *utompath (const struct vol *, char *, cnid_t, int utf8);
 
+extern int setdeskmode(const struct vol *vol, const mode_t mode);
+extern int setdeskowner(const struct vol *vol, uid_t uid, gid_t gid);
+
 /* FP functions */
 int afp_opendt (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf,  size_t *rbuflen);
 int afp_addcomment (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf,  size_t *rbuflen);
index 05eaff01561a60d992dc98784ee545962f00e4d8..7cd08f6f4ec5182a356447306d5ddfa8baa4f173 100644 (file)
@@ -557,7 +557,7 @@ void dircache_remove(const struct vol *vol _U_, struct dir *dir, int flags)
  * - a DID/name index on the main dircache
  * - a queue index on the dircache
  *
- * @param size   (r) requested maximum size from afpd.conf
+ * @param size   (r) requested maximum size from afp.conf
  *
  * @return 0 on success, -1 on error
  */
index 42466d2dc67f004ba10c6b35779a6170f28699c2..0b79da01e182f3ad11f2e984c903a28dca0f6c16 100644 (file)
@@ -21,7 +21,6 @@
 #include <atalk/directory.h>
 
 /* Maximum size of the dircache hashtable */
-#define DEFAULT_MAX_DIRCACHE_SIZE 8192
 #define MAX_POSSIBLE_DIRCACHE_SIZE 131072
 #define DIRCACHE_FREE_QUANTUM 256
 
index a6b194b176626222cd925cdbcc376dc884cc8b86..7539d3ba8dbd1f28154053450d92b4d9a3d70ad7 100644 (file)
@@ -10,6 +10,7 @@
 #include <string.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <stdbool.h>
 #include <grp.h>
 #include <pwd.h>
 #include <sys/param.h>
@@ -31,6 +32,7 @@
 #include <atalk/errchk.h>
 #include <atalk/globals.h>
 #include <atalk/fce_api.h>
+#include <atalk/netatalk_conf.h>
 
 #include "directory.h"
 #include "dircache.h"
@@ -305,7 +307,7 @@ static int cname_mtouname(const struct vol *vol, const struct dir *dir, struct p
     char *t;
     cnid_t fileid = 0;
 
-    if (afp_version >= 30) {
+    if (vol->v_obj->afp_version >= 30) {
         if (toUTF8) {
             if (dir->d_did == DIRDID_ROOT_PARENT) {
                 /*
@@ -337,7 +339,7 @@ static int cname_mtouname(const struct vol *vol, const struct dir *dir, struct p
             /* duplicate work but we can't reuse all convert_char we did in demangle_osx
              * flags weren't the same
              */
-            if ( (t = utompath(vol, ret->u_name, fileid, utf8_encoding())) ) {
+            if ( (t = utompath(vol, ret->u_name, fileid, utf8_encoding(vol->v_obj))) ) {
                 /* at last got our view of mac name */
                 strcpy(ret->m_name, t);
             }
@@ -346,7 +348,7 @@ static int cname_mtouname(const struct vol *vol, const struct dir *dir, struct p
 
     /* If we haven't got it by now, get it */
     if (ret->u_name == NULL) {
-        if ((ret->u_name = mtoupath(vol, ret->m_name, dir->d_did, utf8_encoding())) == NULL) {
+        if ((ret->u_name = mtoupath(vol, ret->m_name, dir->d_did, utf8_encoding(vol->v_obj))) == NULL) {
             afp_errno = AFPERR_PARAM;
             return -1;
         }
@@ -599,7 +601,7 @@ struct dir *dirlookup(const struct vol *vol, cnid_t did)
         goto exit;
     }
 
-    utf8 = utf8_encoding();
+    utf8 = utf8_encoding(vol->v_obj);
     maxpath = (utf8) ? MAXPATHLEN - 7 : 255;
 
     /* Get it from the database */
@@ -705,86 +707,6 @@ exit:
 
 #define ENUMVETO "./../Network Trash Folder/TheVolumeSettingsFolder/TheFindByContentFolder/:2eDS_Store/Contents/Desktop Folder/Trash/Benutzer/"
 
-int caseenumerate(const struct vol *vol, struct path *path, struct dir *dir)
-{
-    DIR               *dp;
-    struct dirent     *de;
-    int               ret;
-    static u_int32_t  did = 0;
-    static char       cname[MAXPATHLEN];
-    static char       lname[MAXPATHLEN];
-    ucs2_t        u2_path[MAXPATHLEN];
-    ucs2_t        u2_dename[MAXPATHLEN];
-    char          *tmp, *savepath;
-
-    if (!(vol->v_flags & AFPVOL_CASEINSEN))
-        return -1;
-
-    if (veto_file(ENUMVETO, path->u_name))
-        return -1;
-
-    savepath = path->u_name;
-
-    /* very simple cache */
-    if ( dir->d_did == did && strcmp(lname, path->u_name) == 0) {
-        path->u_name = cname;
-        path->d_dir = NULL;
-        if (of_stat( path ) == 0 ) {
-            return 0;
-        }
-        /* something changed, we cannot stat ... */
-        did = 0;
-    }
-
-    if (NULL == ( dp = opendir( "." )) ) {
-        LOG(log_debug, logtype_afpd, "caseenumerate: opendir failed: %s", dir->d_u_name);
-        return -1;
-    }
-
-
-    /* LOG(log_debug, logtype_afpd, "caseenumerate: for %s", path->u_name); */
-    if ((size_t) -1 == convert_string(vol->v_volcharset, CH_UCS2, path->u_name, -1, u2_path, sizeof(u2_path)) )
-        LOG(log_debug, logtype_afpd, "caseenumerate: conversion failed for %s", path->u_name);
-
-    /*LOG(log_debug, logtype_afpd, "caseenumerate: dir: %s, path: %s", dir->d_u_name, path->u_name); */
-    ret = -1;
-    for ( de = readdir( dp ); de != NULL; de = readdir( dp )) {
-        if (NULL == check_dirent(vol, de->d_name))
-            continue;
-
-        if ((size_t) -1 == convert_string(vol->v_volcharset, CH_UCS2, de->d_name, -1, u2_dename, sizeof(u2_dename)) )
-            continue;
-
-        if (strcasecmp_w( u2_path, u2_dename) == 0) {
-            tmp = path->u_name;
-            strlcpy(cname, de->d_name, sizeof(cname));
-            path->u_name = cname;
-            path->d_dir = NULL;
-            if (of_stat( path ) == 0 ) {
-                LOG(log_debug, logtype_afpd, "caseenumerate: using dir: %s, path: %s", de->d_name, path->u_name);
-                strlcpy(lname, tmp, sizeof(lname));
-                did = dir->d_did;
-                ret = 0;
-                break;
-            }
-            else
-                path->u_name = tmp;
-        }
-
-    }
-    closedir(dp);
-
-    if (ret) {
-        /* invalidate cache */
-        cname[0] = 0;
-        did = 0;
-        path->u_name = savepath;
-    }
-    /* LOG(log_debug, logtype_afpd, "caseenumerate: path on ret: %s", path->u_name); */
-    return ret;
-}
-
-
 /*!
  * @brief Construct struct dir
  *
@@ -821,7 +743,7 @@ struct dir *dir_new(const char *m_name,
         return NULL;
     }
 
-    if (convert_string_allocate( (utf8_encoding()) ? CH_UTF8_MAC : vol->v_maccharset,
+    if (convert_string_allocate( (utf8_encoding(vol->v_obj)) ? CH_UTF8_MAC : vol->v_maccharset,
                                  CH_UCS2,
                                  m_name,
                                  -1, (char **)&dir->d_m_name_ucs2) == (size_t)-1 ) {
@@ -912,8 +834,8 @@ struct dir *dir_add(struct vol *vol, const struct dir *dir, struct path *path, i
     }
 
     /* get_id needs adp for reading CNID from adouble file */
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
-    if ((ad_open_metadata(path->u_name, ADFLAGS_DIR, 0, &ad)) == 0) /* 1 */
+    ad_init(&ad, vol);
+    if ((ad_open(&ad, path->u_name, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_RDONLY)) == 0) /* 1 */
         adp = &ad;
 
     /* Get CNID */
@@ -923,11 +845,11 @@ struct dir *dir_add(struct vol *vol, const struct dir *dir, struct path *path, i
     }
 
     if (adp)
-        ad_close_metadata(adp);
+        ad_close(adp, ADFLAGS_HF);
 
     /* Get macname from unixname */
     if (path->m_name == NULL) {
-        if ((path->m_name = utompath(vol, path->u_name, id, utf8_encoding())) == NULL) {
+        if ((path->m_name = utompath(vol, path->u_name, id, utf8_encoding(vol->v_obj))) == NULL) {
             LOG(log_error, logtype_afpd, "dir_add(\"%s\"): can't assign macname", path->u_name);
             err = 2;
             goto exit;
@@ -966,7 +888,7 @@ exit:
             cfrombstr(dir->d_u_name), path->u_name, err);
 
         if (adp)
-            ad_close_metadata(adp);
+            ad_close(adp, ADFLAGS_HF);
         if (!cdir && fullpath)
             bdestroy(fullpath);
         if (cdir)
@@ -1143,8 +1065,8 @@ struct path *cname(struct vol *vol, struct dir *dir, char **cpath)
     struct dir  *cdir;
     char        *data, *p;
     int         len;
-    u_int32_t   hint;
-    u_int16_t   len16;
+    uint32_t   hint;
+    uint16_t   len16;
     int         size = 0;
     int         toUTF8 = 0;
 
@@ -1159,13 +1081,13 @@ struct path *cname(struct vol *vol, struct dir *dir, char **cpath)
         data++;
         len = (unsigned char) *data++;
         size = 2;
-        if (afp_version >= 30) {
+        if (vol->v_obj->afp_version >= 30) {
             ret.m_type = 3;
             toUTF8 = 1;
         }
         break;
     case 3:
-        if (afp_version >= 30) {
+        if (vol->v_obj->afp_version >= 30) {
             data++;
             memcpy(&hint, data, sizeof(hint));
             hint = ntohl(hint);
@@ -1412,11 +1334,8 @@ int movecwd(const struct vol *vol, struct dir *dir)
  * If we aren't the file's owner we can't change its perms when moving it and smb
  * nfs,... don't even try.
  */
-#define AFP_CHECK_ACCESS
-
-int check_access(char *path, int mode)
+int check_access(const AFPObj *obj, struct vol *vol, char *path, int mode)
 {
-#ifdef AFP_CHECK_ACCESS
     struct maccess ma;
     char *p;
 
@@ -1424,21 +1343,21 @@ int check_access(char *path, int mode)
     if (!p)
         return -1;
 
-    accessmode(current_vol, p, &ma, curdir, NULL);
+    accessmode(obj, vol, p, &ma, curdir, NULL);
     if ((mode & OPENACC_WR) && !(ma.ma_user & AR_UWRITE))
         return -1;
     if ((mode & OPENACC_RD) && !(ma.ma_user & AR_UREAD))
         return -1;
-#endif
+
     return 0;
 }
 
 /* --------------------- */
-int file_access(struct path *path, int mode)
+int file_access(const AFPObj *obj, struct vol *vol, struct path *path, int mode)
 {
     struct maccess ma;
 
-    accessmode(current_vol, path->u_name, &ma, curdir, &path->st);
+    accessmode(obj, vol, path->u_name, &ma, curdir, &path->st);
 
     LOG(log_debug, logtype_afpd, "file_access(\"%s\"): mapped user mode: 0x%02x",
         path->u_name, ma.ma_user);
@@ -1456,7 +1375,7 @@ int file_access(struct path *path, int mode)
 }
 
 /* --------------------- */
-void setdiroffcnt(struct dir *dir, struct stat *st,  u_int32_t count)
+void setdiroffcnt(struct dir *dir, struct stat *st,  uint32_t count)
 {
     dir->d_offcnt = count;
     dir->d_ctime = st->st_ctime;
@@ -1477,8 +1396,9 @@ int dirreenumerate(struct dir *dir, struct stat *st)
    (name, dir) with curdir:name == dir, from afp_enumerate
 */
 
-int getdirparams(const struct vol *vol,
-                 u_int16_t bitmap, struct path *s_path,
+int getdirparams(const AFPObj *obj,
+                 const struct vol *vol,
+                 uint16_t bitmap, struct path *s_path,
                  struct dir *dir,
                  char *buf, size_t *buflen )
 {
@@ -1486,10 +1406,10 @@ int getdirparams(const struct vol *vol,
     struct adouble  ad;
     char        *data, *l_nameoff = NULL, *utf_nameoff = NULL;
     int         bit = 0, isad = 0;
-    u_int32_t           aint;
-    u_int16_t       ashort;
+    uint32_t           aint;
+    uint16_t       ashort;
     int                 ret;
-    u_int32_t           utf8 = 0;
+    uint32_t           utf8 = 0;
     cnid_t              pdid;
     struct stat *st = &s_path->st;
     char *upath = s_path->u_name;
@@ -1500,16 +1420,16 @@ int getdirparams(const struct vol *vol,
                    (1 << DIRPBIT_BDATE) |
                    (1 << DIRPBIT_FINFO)))) {
 
-        ad_init(&ad, vol->v_adouble, vol->v_ad_options);
-        if ( !ad_metadata( upath, ADFLAGS_CREATE|ADFLAGS_DIR, &ad) ) {
+        ad_init(&ad, vol);
+        if ( !ad_metadata( upath, ADFLAGS_DIR, &ad) ) {
             isad = 1;
-            if (ad.ad_md->adf_flags & O_CREAT) {
+            if (ad.ad_mdp->adf_flags & O_CREAT) {
                 /* We just created it */
                 if (s_path->m_name == NULL) {
                     if ((s_path->m_name = utompath(vol,
                                                    upath,
                                                    dir->d_did,
-                                                   utf8_encoding())) == NULL) {
+                                                   utf8_encoding(obj))) == NULL) {
                         LOG(log_error, logtype_afpd,
                             "getdirparams(\"%s\"): can't assign macname",
                             cfrombstr(dir->d_fullpath));
@@ -1598,13 +1518,13 @@ int getdirparams(const struct vol *vol,
             if (dir->d_m_name) /* root of parent can have a null name */
                 l_nameoff = data;
             else
-                memset(data, 0, sizeof(u_int16_t));
-            data += sizeof( u_int16_t );
+                memset(data, 0, sizeof(uint16_t));
+            data += sizeof( uint16_t );
             break;
 
         case DIRPBIT_SNAME :
-            memset(data, 0, sizeof(u_int16_t));
-            data += sizeof( u_int16_t );
+            memset(data, 0, sizeof(uint16_t));
+            data += sizeof( uint16_t );
             break;
 
         case DIRPBIT_DID :
@@ -1642,7 +1562,7 @@ int getdirparams(const struct vol *vol,
             break;
 
         case DIRPBIT_ACCESS :
-            accessmode(vol, upath, &ma, dir , st);
+            accessmode(obj, vol, upath, &ma, dir , st);
 
             *data++ = ma.ma_user;
             *data++ = ma.ma_world;
@@ -1654,13 +1574,13 @@ int getdirparams(const struct vol *vol,
                Just pass back the same basic block for all
                directories. <shirsch@ibm.net> */
         case DIRPBIT_PDINFO :
-            if (afp_version >= 30) { /* UTF8 name */
+            if (obj->afp_version >= 30) { /* UTF8 name */
                 utf8 = kTextEncodingUTF8;
                 if (dir->d_m_name) /* root of parent can have a null name */
                     utf_nameoff = data;
                 else
-                    memset(data, 0, sizeof(u_int16_t));
-                data += sizeof( u_int16_t );
+                    memset(data, 0, sizeof(uint16_t));
+                data += sizeof( uint16_t );
                 aint = 0;
                 memcpy(data, &aint, sizeof( aint ));
                 data += sizeof( aint );
@@ -1678,7 +1598,7 @@ int getdirparams(const struct vol *vol,
 
         case DIRPBIT_UNIXPR :
             /* accessmode may change st_mode with ACLs */
-            accessmode(vol, upath, &ma, dir, st);
+            accessmode(obj, vol, upath, &ma, dir, st);
 
             aint = htonl(st->st_uid);
             memcpy( data, &aint, sizeof( aint ));
@@ -1700,7 +1620,7 @@ int getdirparams(const struct vol *vol,
 
         default :
             if ( isad ) {
-                ad_close_metadata( &ad );
+                ad_close(&ad, ADFLAGS_HF);
             }
             return( AFPERR_BITMAP );
         }
@@ -1718,7 +1638,7 @@ int getdirparams(const struct vol *vol,
         data = set_name(vol, data, pdid, cfrombstr(dir->d_m_name), dir->d_did, utf8);
     }
     if ( isad ) {
-        ad_close_metadata( &ad );
+        ad_close(&ad, ADFLAGS_HF);
     }
     *buflen = data - buf;
     return( AFP_OK );
@@ -1744,8 +1664,8 @@ int afp_setdirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_
     struct vol  *vol;
     struct dir  *dir;
     struct path *path;
-    u_int16_t   vid, bitmap;
-    u_int32_t   did;
+    uint16_t   vid, bitmap;
+    uint32_t   did;
     int     rc;
 
     *rbuflen = 0;
@@ -1796,11 +1716,9 @@ int afp_setdirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_
 }
 
 /*
- * cf AFP3.0.pdf page 244 for change_mdate and change_parent_mdate logic
- *
  * assume path == '\0' eg. it's a directory in canonical form
  */
-int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *buf )
+int setdirparams(struct vol *vol, struct path *path, uint16_t d_bitmap, char *buf )
 {
     struct maccess  ma;
     struct adouble  ad;
@@ -1809,19 +1727,21 @@ int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *b
 
     char                *upath;
     struct dir          *dir;
-    int         bit, isad = 1;
+    int         bit, isad = 0;
     int                 cdate, bdate;
     int                 owner, group;
-    u_int16_t       ashort, bshort, oshort;
+    uint16_t       ashort, bshort, oshort;
     int                 err = AFP_OK;
     int                 change_mdate = 0;
     int                 change_parent_mdate = 0;
     int                 newdate = 0;
-    u_int16_t           bitmap = d_bitmap;
+    uint16_t           bitmap = d_bitmap;
     u_char              finder_buf[32];
-    u_int32_t       upriv;
+    uint32_t       upriv;
     mode_t              mpriv = 0;
-    u_int16_t           upriv_bit = 0;
+    bool                set_upriv = false, set_maccess = false;
+
+    LOG(log_debug, logtype_afpd, "setdirparams(\"%s\", bitmap: %02x)", path->u_name, bitmap);
 
     bit = 0;
     upath = path->u_name;
@@ -1858,33 +1778,27 @@ int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *b
             buf += 32;
             break;
         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
-            change_parent_mdate = 1;
             memcpy( &owner, buf, sizeof(owner));
             buf += sizeof( owner );
             break;
         case DIRPBIT_GID :
-            change_parent_mdate = 1;
             memcpy( &group, buf, sizeof( group ));
             buf += sizeof( group );
             break;
         case DIRPBIT_ACCESS :
+            set_maccess = true;
             change_mdate = 1;
-            change_parent_mdate = 1;
             ma.ma_user = *buf++;
             ma.ma_world = *buf++;
             ma.ma_group = *buf++;
             ma.ma_owner = *buf++;
             mpriv = mtoumode( &ma ) | vol->v_dperm;
-            if (dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
-                err = set_dir_errors(path, "setdirmode", errno);
-                bitmap = 0;
-            }
             break;
             /* Ignore what the client thinks we should do to the
                ProDOS information block.  Skip over the data and
                report nothing amiss. <shirsch@ibm.net> */
         case DIRPBIT_PDINFO :
-            if (afp_version < 30) {
+            if (vol->v_obj->afp_version < 30) {
                 buf += 6;
             }
             else {
@@ -1894,27 +1808,16 @@ int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *b
             break;
         case DIRPBIT_UNIXPR :
             if (vol_unix_priv(vol)) {
+                set_upriv = true;
                 memcpy( &owner, buf, sizeof(owner)); /* FIXME need to change owner too? */
                 buf += sizeof( owner );
                 memcpy( &group, buf, sizeof( group ));
                 buf += sizeof( group );
 
                 change_mdate = 1;
-                change_parent_mdate = 1;
                 memcpy( &upriv, buf, sizeof( upriv ));
                 buf += sizeof( upriv );
                 upriv = ntohl (upriv) | vol->v_dperm;
-                if (dir_rx_set(upriv)) {
-                    /* maybe we are trying to set perms back */
-                    if ( setdirunixmode(vol, upath, upriv) < 0 ) {
-                        bitmap = 0;
-                        err = set_dir_errors(path, "setdirunixmode", errno);
-                    }
-                }
-                else {
-                    /* do it later */
-                    upriv_bit = 1;
-                }
                 break;
             }
             /* fall through */
@@ -1927,33 +1830,17 @@ int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *b
         bitmap = bitmap>>1;
         bit++;
     }
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
 
-    if (ad_open_metadata( upath, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
-        /*
-         * Check to see what we're trying to set.  If it's anything
-         * but ACCESS, UID, or GID, give an error.  If it's any of those
-         * three, we don't need the ad to be open, so just continue.
-         *
-         * note: we also don't need to worry about mdate. also, be quiet
-         *       if we're using the noadouble option.
-         */
-        if (!vol_noadouble(vol) && (d_bitmap &
-                                    ~((1<<DIRPBIT_ACCESS)|(1<<DIRPBIT_UNIXPR)|
-                                      (1<<DIRPBIT_UID)|(1<<DIRPBIT_GID)|
-                                      (1<<DIRPBIT_MDATE)|(1<<DIRPBIT_PDINFO)))) {
+    if (d_bitmap & ((1<<DIRPBIT_ATTR) | (1<<DIRPBIT_CDATE) | (1<<DIRPBIT_BDATE) | (1<<DIRPBIT_FINFO))) {
+        ad_init(&ad, vol);
+        if (ad_open(&ad, upath, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_CREATE | ADFLAGS_RDWR, 0777) != 0) {
+            LOG(log_debug, logtype_afpd, "setdirparams(\"%s\", bitmap: %02x): need adouble", path->u_name, d_bitmap);
             return AFPERR_ACCESS;
         }
-
-        isad = 0;
-    } else {
-        /*
-         * Check to see if a create was necessary. If it was, we'll want
-         * to set our name, etc.
-         */
-        if ( (ad_get_HF_flags( &ad ) & O_CREAT)) {
+        if ((ad_get_MD_flags(&ad) & O_CREAT)) {
             ad_setname(&ad, cfrombstr(curdir->d_m_name));
         }
+        isad = 1;
     }
 
     bit = 0;
@@ -1994,7 +1881,7 @@ int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *b
         case DIRPBIT_FINFO :
             if (isad) {
                 /* Fixes #2802236 */
-                u_int16_t *fflags = (u_int16_t *)(finder_buf + FINDERINFO_FRFLAGOFF);
+                uint16_t *fflags = (uint16_t *)(finder_buf + FINDERINFO_FRFLAGOFF);
                 *fflags &= htons(~FINDERINFO_ISHARED);
                 /* #2802236 end */
                 if (  dir->d_did == DIRDID_ROOT ) {
@@ -2015,7 +1902,7 @@ int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *b
             break;
         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
             if ( (dir->d_did == DIRDID_ROOT) &&
-                 (setdeskowner( ntohl(owner), -1 ) < 0)) {
+                 (setdeskowner(vol, ntohl(owner), -1 ) < 0)) {
                 err = set_dir_errors(path, "setdeskowner", errno);
                 if (isad && err == AFPERR_PARAM) {
                     err = AFP_OK; /* ???*/
@@ -2031,55 +1918,22 @@ int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *b
             break;
         case DIRPBIT_GID :
             if (dir->d_did == DIRDID_ROOT)
-                setdeskowner( -1, ntohl(group) );
+                setdeskowner(vol, -1, ntohl(group) );
             if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
                 err = set_dir_errors(path, "setdirowner", errno);
                 goto setdirparam_done;
             }
             break;
         case DIRPBIT_ACCESS :
-            if (dir->d_did == DIRDID_ROOT) {
-                setdeskmode(mpriv);
-                if (!dir_rx_set(mpriv)) {
-                    /* we can't remove read and search for owner on volume root */
-                    err = AFPERR_ACCESS;
-                    goto setdirparam_done;
-                }
-            }
-
-            if (!dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
-                err = set_dir_errors(path, "setdirmode", errno);
-                goto setdirparam_done;
-            }
             break;
         case DIRPBIT_PDINFO :
-            if (afp_version >= 30) {
+            if (vol->v_obj->afp_version >= 30) {
                 err = AFPERR_BITMAP;
                 goto setdirparam_done;
             }
             break;
         case DIRPBIT_UNIXPR :
-            if (vol_unix_priv(vol)) {
-                if (dir->d_did == DIRDID_ROOT) {
-                    if (!dir_rx_set(upriv)) {
-                        /* we can't remove read and search for owner on volume root */
-                        err = AFPERR_ACCESS;
-                        goto setdirparam_done;
-                    }
-                    setdeskowner( -1, ntohl(group) );
-                    setdeskmode( upriv );
-                }
-                if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
-                    err = set_dir_errors(path, "setdirowner", errno);
-                    goto setdirparam_done;
-                }
-
-                if ( upriv_bit && setdirunixmode(vol, upath, upriv) < 0 ) {
-                    err = set_dir_errors(path, "setdirunixmode", errno);
-                    goto setdirparam_done;
-                }
-            }
-            else {
+            if (!vol_unix_priv(vol)) {
                 err = AFPERR_BITMAP;
                 goto setdirparam_done;
             }
@@ -2105,18 +1959,69 @@ setdirparam_done:
         utime(upath, &ut);
     }
 
-    if ( isad ) {
+    if (isad) {
         if (path->st_valid && !path->st_errno) {
             struct stat *st = &path->st;
-
             if (dir && dir->d_pdid) {
                 ad_setid(&ad, st->st_dev, st->st_ino,  dir->d_did, dir->d_pdid, vol->v_stamp);
             }
         }
-        ad_flush( &ad);
-        ad_close_metadata( &ad);
+        if (ad_flush(&ad) != 0) {
+            switch (errno) {
+            case EACCES:
+                err = AFPERR_ACCESS;
+                break;
+            default:
+                err = AFPERR_MISC;
+                break;
+           }
+        }
+        ad_close(&ad, ADFLAGS_HF);
     }
 
+    if (err == AFP_OK) {
+        if (set_maccess == true) {
+            if (dir->d_did == DIRDID_ROOT) {
+                setdeskmode(vol, mpriv);
+                if (!dir_rx_set(mpriv)) {
+                    /* we can't remove read and search for owner on volume root */
+                    err = AFPERR_ACCESS;
+                    goto setprivdone;
+                }
+            }
+            if (setdirunixmode(vol, upath, mpriv) < 0) {
+                LOG(log_info, logtype_afpd, "setdirparams(\"%s\"): setdirunixmode: %s",
+                    fullpathname(upath), strerror(errno));
+                err = set_dir_errors(path, "setdirmode", errno);
+            }
+        }
+        if ((set_upriv == true) && vol_unix_priv(vol)) {
+            if (dir->d_did == DIRDID_ROOT) {
+                if (!dir_rx_set(upriv)) {
+                    /* we can't remove read and search for owner on volume root */
+                    err = AFPERR_ACCESS;
+                    goto setprivdone;
+                }
+                setdeskowner(vol, -1, ntohl(group));
+                setdeskmode(vol, upriv);
+            }
+
+            if (setdirowner(vol, upath, -1, ntohl(group)) < 0) {
+                LOG(log_info, logtype_afpd, "setdirparams(\"%s\"): setdirowner: %s",
+                    fullpathname(upath), strerror(errno));
+                err = set_dir_errors(path, "setdirowner", errno);
+                goto setprivdone;
+            }
+
+            if (setdirunixmode(vol, upath, upriv) < 0) {
+                LOG(log_info, logtype_afpd, "setdirparams(\"%s\"): setdirunixmode: %s",
+                    fullpathname(upath), strerror(errno));
+                err = set_dir_errors(path, "setdirunixmode", errno);
+            }
+        }
+    }
+
+setprivdone:
     if (change_parent_mdate && dir->d_did != DIRDID_ROOT
         && gettimeofday(&tv, NULL) == 0) {
         if (movecwd(vol, dirlookup(vol, dir->d_pdid)) == 0) {
@@ -2127,7 +2032,6 @@ setdirparam_done:
             /* should we reset curdir ?*/
         }
     }
-
     return err;
 }
 
@@ -2139,8 +2043,8 @@ int afp_syncdir(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_,
     int                  dfd;
     struct vol           *vol;
     struct dir           *dir;
-    u_int32_t            did;
-    u_int16_t            vid;
+    uint32_t            did;
+    uint16_t            vid;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -2228,8 +2132,8 @@ int afp_createdir(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_
     struct dir      *dir;
     char        *upath;
     struct path         *s_path;
-    u_int32_t       did;
-    u_int16_t       vid;
+    uint32_t       did;
+    uint16_t       vid;
     int                 err;
 
     *rbuflen = 0;
@@ -2281,10 +2185,8 @@ int afp_createdir(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_
         return( AFPERR_PARAM );
     }
 
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
-    if (ad_open_metadata( ".", ADFLAGS_DIR, O_CREAT, &ad ) < 0)  {
-        if (vol_noadouble(vol))
-            goto createdir_done;
+    ad_init(&ad, vol);
+    if (ad_open(&ad, ".", ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_CREATE | ADFLAGS_RDWR, 0777) < 0)  {
         return( AFPERR_ACCESS );
     }
     ad_setname(&ad, s_path->m_name);
@@ -2292,12 +2194,12 @@ int afp_createdir(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_
 
     fce_register_new_dir(s_path);
 
-    ad_flush( &ad);
-    ad_close_metadata( &ad);
+    ad_flush(&ad);
+    ad_close(&ad, ADFLAGS_HF);
 
 createdir_done:
-    memcpy( rbuf, &dir->d_did, sizeof( u_int32_t ));
-    *rbuflen = sizeof( u_int32_t );
+    memcpy( rbuf, &dir->d_did, sizeof( uint32_t ));
+    *rbuflen = sizeof( uint32_t );
     setvoltime(obj, vol );
     return( AFP_OK );
 }
@@ -2348,12 +2250,12 @@ int renamedir(const struct vol *vol,
 
     vol->vfs->vfs_renamedir(vol, dirfd, src, dst);
 
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
+    ad_init(&ad, vol);
 
-    if (!ad_open_metadata( dst, ADFLAGS_DIR, 0, &ad)) {
+    if (ad_open(&ad, dst, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_RDWR) == 0) {
         ad_setname(&ad, newname);
-        ad_flush( &ad);
-        ad_close_metadata( &ad);
+        ad_flush(&ad);
+        ad_close(&ad, ADFLAGS_HF);
     }
 
     return( AFP_OK );
@@ -2367,7 +2269,7 @@ int deletecurdir(struct vol *vol)
     struct dir  *fdir, *pdir;
     DIR *dp;
     struct adouble  ad;
-    u_int16_t       ashort;
+    uint16_t       ashort;
     int err;
 
     if ((pdir = dirlookup(vol, curdir->d_pdid)) == NULL) {
@@ -2376,12 +2278,12 @@ int deletecurdir(struct vol *vol)
 
     fdir = curdir;
 
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
+    ad_init(&ad, vol);
     /* we never want to create a resource fork here, we are going to delete it */
     if ( ad_metadata( ".", ADFLAGS_DIR, &ad) == 0 ) {
 
         ad_getattr(&ad, &ashort);
-        ad_close_metadata(&ad);
+        ad_close(&ad, ADFLAGS_HF);
         if ((ashort & htons(ATTRBIT_NODELETE))) {
             return  AFPERR_OLOCK;
         }
@@ -2448,7 +2350,7 @@ int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *r
     struct passwd   *pw;
     struct group    *gr;
     char        *name;
-    u_int32_t           id;
+    uint32_t           id;
     int         len, sfunc;
     int         utf8 = 0;
 
@@ -2457,7 +2359,7 @@ int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *r
     *rbuflen = 0;
 
     if (sfunc >= 3 && sfunc <= 6) {
-        if (afp_version < 30) {
+        if (obj->afp_version < 30) {
             return( AFPERR_PARAM );
         }
         utf8 = 1;
@@ -2497,7 +2399,7 @@ int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *r
 
     case 5 : /* UUID -> username */
     case 6 : /* UUID -> groupname */
-        if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
+        if ((obj->afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
             return AFPERR_PARAM;
         LOG(log_debug, logtype_afpd, "afp_mapid: valid UUID request");
         uuidtype_t type;
@@ -2542,7 +2444,7 @@ int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *r
         len = strlen( name );
 
     if (utf8) {
-        u_int16_t tp = htons(len);
+        uint16_t tp = htons(len);
         memcpy(rbuf, &tp, sizeof(tp));
         rbuf += sizeof(tp);
         *rbuflen += 2;
@@ -2560,22 +2462,22 @@ int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *r
     return( AFP_OK );
 }
 
-int afp_mapname(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
+int afp_mapname(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
     struct passwd   *pw;
     struct group    *gr;
     int             len, sfunc;
-    u_int32_t       id;
-    u_int16_t       ulen;
+    uint32_t       id;
+    uint16_t       ulen;
 
     ibuf++;
     sfunc = (unsigned char) *ibuf++;
     *rbuflen = 0;
-    LOG(log_debug, logtype_afpd, "afp_mapname: sfunc: %d, afp_version: %d", sfunc, afp_version);
+    LOG(log_debug, logtype_afpd, "afp_mapname: sfunc: %d", sfunc);
     switch ( sfunc ) {
     case 1 :
     case 2 : /* unicode */
-        if (afp_version < 30) {
+        if (obj->afp_version < 30) {
             return( AFPERR_PARAM );
         }
         memcpy(&ulen, ibuf, sizeof(ulen));
@@ -2589,7 +2491,7 @@ int afp_mapname(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, siz
         break;
     case 5 : /* username -> UUID  */
     case 6 : /* groupname -> UUID */
-        if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
+        if ((obj->afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
             return AFPERR_PARAM;
         memcpy(&ulen, ibuf, sizeof(ulen));
         len = ntohs(ulen);
@@ -2653,8 +2555,8 @@ int afp_closedir(AFPObj *obj _U_, char *ibuf _U_, size_t ibuflen _U_, char *rbuf
 #if 0
     struct vol   *vol;
     struct dir   *dir;
-    u_int16_t    vid;
-    u_int32_t    did;
+    uint16_t    vid;
+    uint32_t    did;
 #endif /* 0 */
 
     *rbuflen = 0;
@@ -2689,8 +2591,8 @@ int afp_opendir(AFPObj *obj _U_, char *ibuf, size_t ibuflen  _U_, char *rbuf, si
     struct vol      *vol;
     struct dir      *parentdir;
     struct path     *path;
-    u_int32_t       did;
-    u_int16_t       vid;
+    uint32_t       did;
+    uint16_t       vid;
 
     *rbuflen = 0;
     ibuf += 2;
index e9c6a457f4344cb2865f0295d0d78885c4f096c7..7f3e8c56a1cd135c2405abb5fb3af61a700222dd 100644 (file)
 #ifndef AFPD_DIRECTORY_H
 #define AFPD_DIRECTORY_H 1
 
-#include <sys/cdefs.h>
 #include <sys/types.h>
-/*#include <sys/stat.h>*/ /* including it here causes some confusion */
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 #include <dirent.h>
 
 /* sys/types.h usually snarfs in major/minor macros. if they don't
@@ -113,21 +111,19 @@ extern struct path *cname (struct vol *, struct dir *, char **);
 
 extern int         deletecurdir (struct vol *);
 extern mode_t      mtoumode (struct maccess *);
-extern void        utommode (struct stat *, struct maccess *);
-extern int         getdirparams (const struct vol *, u_int16_t, struct path *,
+extern int         getdirparams (const AFPObj *obj, const struct vol *, uint16_t, struct path *,
                                  struct dir *, char *, size_t *);
 
-extern int         setdirparams(struct vol *, struct path *, u_int16_t, char *);
+extern int         setdirparams(struct vol *, struct path *, uint16_t, char *);
 extern int         renamedir(const struct vol *, int, char *, char *, struct dir *,
                              struct dir *, char *);
 extern int         path_error(struct path *, int error);
-extern void        setdiroffcnt(struct dir *dir, struct stat *st,  u_int32_t count);
+extern void        setdiroffcnt(struct dir *dir, struct stat *st,  uint32_t count);
 extern int         dirreenumerate(struct dir *dir, struct stat *st);
 extern int         for_each_dirent(const struct vol *, char *, dir_loop , void *);
-extern int         check_access(char *name , int mode);
-extern int         file_access(struct path *path, int mode);
+extern int         check_access(const AFPObj *obj, struct vol *, char *name , int mode);
+extern int         file_access(const AFPObj *obj, struct vol *vol, struct path *path, int mode);
 extern int         netatalk_unlink (const char *name);
-extern int         caseenumerate (const struct vol *, struct path *, struct dir *);
 
 /* from enumerate.c */
 extern char        *check_dirent (const struct vol *, char *);
index fe5a66d993746610ce45747d347abc1e409036e4..d469928c357b465a5781d2f5f51c9aad51fb8a2e 100644 (file)
@@ -23,6 +23,7 @@
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
 
 #include "desktop.h"
 #include "directory.h"
@@ -40,7 +41,7 @@
  */
 struct savedir {
     u_short     sd_vid;
-    u_int32_t   sd_did;
+    uint32_t    sd_did;
     int                 sd_buflen;
     char        *sd_buf;
     char        *sd_last;
@@ -169,9 +170,9 @@ static int enumerate(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,
     int                                did, ret, len, first = 1;
     size_t                     esz;
     char                        *data, *start;
-    u_int16_t                  vid, fbitmap, dbitmap, reqcnt, actcnt = 0;
-    u_int16_t                  temp16;
-    u_int32_t                  sindex, maxsz, sz = 0;
+    uint16_t                   vid, fbitmap, dbitmap, reqcnt, actcnt = 0;
+    uint16_t                   temp16;
+    uint32_t                   sindex, maxsz, sz = 0;
     struct path                 *o_path;
     struct path                 s_path;
     int                         header;
@@ -272,8 +273,8 @@ static int enumerate(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,
     LOG(log_debug, logtype_afpd, "enumerate(\"%s/%s\", f/d:%04x/%04x, rc:%u, i:%u, max:%u)",
         getcwdpath(), o_path->u_name, fbitmap, dbitmap, reqcnt, sindex, maxsz);
 
-    data = rbuf + 3 * sizeof( u_int16_t );
-    sz = 3 * sizeof( u_int16_t );      /* fbitmap, dbitmap, reqcount */
+    data = rbuf + 3 * sizeof( uint16_t );
+    sz = 3 * sizeof( uint16_t );       /* fbitmap, dbitmap, reqcount */
 
     /*
      * Read the directory into a pre-malloced buffer, stored
@@ -346,13 +347,15 @@ static int enumerate(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,
             continue;
         }
         memset(&s_path, 0, sizeof(s_path));
+
+        /* conversions on the fly */
+        const char *convname;
         s_path.u_name = sd.sd_last;
-        if (of_stat( &s_path) < 0 ) {
-            /*
-             * Somebody else plays with the dir, well it can be us with 
-            * "Empty Trash..."
-            */
+        if (ad_convert(sd.sd_last, &s_path.st, vol, &convname) == 0 && convname) {
+            s_path.u_name = (char *)convname;
+        }
 
+        if (of_stat( &s_path) < 0 ) {
             /* so the next time it won't try to stat it again
              * another solution would be to invalidate the cache with 
              * sd.sd_did = 0 but if it's not ENOENT error it will start again
@@ -363,8 +366,18 @@ static int enumerate(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,
             continue;
         }
 
+        /* Fixup CNID db if ad_convert resulted in a rename (then convname != NULL) */
+        if (convname) {
+            s_path.id = cnid_lookup(vol->v_cdb, &s_path.st, curdir->d_did, sd.sd_last, strlen(sd.sd_last));
+            if (s_path.id != CNID_INVALID) {
+                if (cnid_update(vol->v_cdb, s_path.id, &s_path.st, curdir->d_did, convname, strlen(convname)) != 0)
+                    LOG(log_error, logtype_afpd, "enumerate: error updating CNID of \"%s\"", fullpathname(convname));
+            }
+        }
+
         sd.sd_last += len + 1;
         s_path.m_name = NULL;
+
         /*
          * If a fil/dir is not a dir, it's a file. This is slightly
          * inaccurate, since that means /dev/null is a file, /dev/printer
@@ -382,7 +395,7 @@ static int enumerate(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,
                     return AFPERR_MISC;
                 }
             }
-            if ((ret = getdirparams(vol, dbitmap, &s_path, dir, data + header , &esz)) != AFP_OK)
+            if ((ret = getdirparams(obj, vol, dbitmap, &s_path, dir, data + header , &esz)) != AFP_OK)
                 return( ret );
 
         } else {
@@ -390,8 +403,8 @@ static int enumerate(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,
                 continue;
             }
             /* files are added to the dircache in getfilparams() -> getmetadata() */
-            if (AFP_OK != ( ret = getfilparams(vol, fbitmap, &s_path, curdir, 
-                                     data + header , &esz )) ) {
+            if (AFP_OK != ( ret = getfilparams(obj, vol, fbitmap, &s_path, curdir, 
+                                               data + header, &esz, 1)) ) {
                 return( ret );
             }
         }
@@ -440,6 +453,15 @@ static int enumerate(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,
 
     if ( actcnt == 0 ) {
         sd.sd_did = 0;         /* invalidate sd struct to force re-read */
+        /*
+         * in case were converting adouble stuff:
+         * after enumerating the whole dir we should have converted everything
+         * thus the .AppleDouble dir shouls be empty thus we can no try to
+         * delete it
+         */
+        if (vol->v_adouble == AD_VERSION_EA && ! (vol->v_flags & AFPVOL_NOV2TOEACONV))
+            (void)rmdir(".AppleDouble");
+
         return( AFPERR_NOOBJ );
     }
     sd.sd_sindex = sindex + actcnt;
index 40298b50737ccfa62000ac1469c2e4749a4ef511..4cbeb6423ddd316cb28dc32cec5488ce98ed0f81 100644 (file)
@@ -1,5 +1,4 @@
 /*
-  $Id: extattrs.c,v 1.29 2010-01-05 12:06:33 franklahm Exp $
   Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
 
   This program is free software; you can redistribute it and/or modify
@@ -29,6 +28,7 @@
 #include <atalk/logger.h>
 #include <atalk/ea.h>
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
 
 #include "volume.h"
 #include "desktop.h"
@@ -139,7 +139,6 @@ int afp_listextattr(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf,
             return( AFPERR_NOOBJ );
         }
 
-        adp = of_ad(vol, s_path, &ad);
         uname = s_path->u_name;
         /*
           We have to check the FinderInfo for the file, because if they aren't all 0
@@ -151,10 +150,11 @@ int afp_listextattr(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf,
         if (S_ISDIR(st->st_mode))
             adflags = ADFLAGS_DIR;
 
-        if ( ad_metadata( uname, adflags, adp) < 0 ) {
+        adp = &ad;
+        ad_init(adp, vol);
+        if (ad_metadata(uname, adflags, adp) != 0 ) {
             switch (errno) {
             case ENOENT:
-                adp = NULL;
                 break;
             case EACCES:
                 LOG(log_error, logtype_afpd, "afp_listextattr(%s): %s: check resource fork permission?",
@@ -164,16 +164,9 @@ int afp_listextattr(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf,
                 LOG(log_error, logtype_afpd, "afp_listextattr(%s): error getting metadata: %s", uname, strerror(errno));
                 return AFPERR_MISC;
             }
-        }
-
-        if (adp) {
+        } else {
             FinderInfo = ad_entry(adp, ADEID_FINDERI);
 
-#ifdef DEBUG
-            LOG(log_maxdebug, logtype_afpd, "afp_listextattr(%s): FinderInfo:", uname);
-            hexdump( FinderInfo, 32);
-#endif
-
             if ((adflags & ADFLAGS_DIR)) {
                 /* set default view */
                 uint16 = htons(FINDERINFO_CLOSEDVIEW);
@@ -214,7 +207,7 @@ int afp_listextattr(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf,
         default:
             buf_valid = 1;
         }
-    }
+    } /* if ((maxreply == 0) || (buf_valid == 0)) */
 
     /* Start building reply packet */
     bitmap = htons(bitmap);
@@ -240,8 +233,9 @@ int afp_listextattr(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf,
 exit:
     if (ret != AFP_OK)
         buf_valid = 0;
+
     if (adp)
-        ad_close_metadata( adp);
+        ad_close(adp, ADFLAGS_HF);
 
     return ret;
 }
index 87d2503544dc81e76660b6398fbf764e6aaafcc9..b40eafb988a7bf6681faf8fc8a60a2ebcafc40a3 100644 (file)
@@ -37,8 +37,6 @@
 #include <arpa/inet.h>
 #include <netdb.h>
 
-#include <netatalk/at.h>
-
 #include <atalk/adouble.h>
 #include <atalk/vfs.h>
 #include <atalk/logger.h>
@@ -515,24 +513,15 @@ int fce_register_new_file( struct path *path )
 
 int fce_register_file_modification( struct ofork *ofork )
 {
-    char *u_name = NULL;
-    struct vol *vol;
     int ret = AFP_OK;
 
-    if (ofork == NULL || ofork->of_vol == NULL)
+    if (ofork == NULL)
         return AFPERR_PARAM;
 
     if (!(fce_ev_enabled & (1 << FCE_FILE_MODIFY)))
         return ret;
 
-    vol = ofork->of_vol;
-
-    if (NULL == (u_name = mtoupath(vol, of_name(ofork), ofork->of_did, utf8_encoding()))) 
-    {
-        return AFPERR_MISC;
-    }
-    
-    ret = register_fce( u_name, false, FCE_FILE_MODIFY );
+    ret = register_fce(of_name(ofork), false, FCE_FILE_MODIFY );
     
     return ret;    
 }
@@ -586,7 +575,7 @@ int fce_set_events(const char *events)
 
     fce_ev_enabled = 0;
 
-    for (p = strtok(e, ","); p; p = strtok(NULL, ",")) {
+    for (p = strtok(e, ", "); p; p = strtok(NULL, ", ")) {
         if (strcmp(p, "fmod") == 0) {
             fce_ev_enabled |= (1 << FCE_FILE_MODIFY);
         } else if (strcmp(p, "fdel") == 0) {
index 672adac82d9be151e8ba5d552ad2877cb7fd338a..07b59d73621555cf917eebbc4028ac347860cc37 100644 (file)
@@ -35,8 +35,6 @@
 #include <arpa/inet.h>
 #include <netdb.h>
 
-#include <netatalk/at.h>
-
 #include <atalk/adouble.h>
 #include <atalk/vfs.h>
 #include <atalk/logger.h>
@@ -172,7 +170,7 @@ bool fce_handle_coalescation( char *path, int is_dir, int mode )
  * all|delete|create
  */
 
-int fce_set_coalesce(char *opt)
+int fce_set_coalesce(const char *opt)
 {
     char *e;
     char *p;
index 93c91c049634d8ef786afdfecd8e99880a255185..407dc6f9d9e5855e1bdde254ae888acf19e9956b 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
 #include <utime.h>
 #include <errno.h>
 #include <sys/param.h>
@@ -39,6 +24,7 @@ char *strchr (), *strrchr ();
 #include <atalk/unix.h>
 #include <atalk/globals.h>
 #include <atalk/fce_api.h>
+#include <atalk/netatalk_conf.h>
 
 #include "directory.h"
 #include "dircache.h"
@@ -91,24 +77,19 @@ static int default_type(void *finder)
 /* FIXME path : unix or mac name ? (for now it's unix name ) */
 void *get_finderinfo(const struct vol *vol, const char *upath, struct adouble *adp, void *data, int islink)
 {
-    struct extmap      *em;
     void                *ad_finder = NULL;
     int                 chk_ext = 0;
-    
+
     if (adp)
         ad_finder = ad_entry(adp, ADEID_FINDERI);
 
     if (ad_finder) {
         memcpy(data, ad_finder, ADEDLEN_FINDERI);
-        /* default type ? */
-        if (default_type(ad_finder)) 
-            chk_ext = 1;
     }
     else {
         memcpy(data, ufinderi, ADEDLEN_FINDERI);
-        chk_ext = 1;
         if (vol_inv_dots(vol) && *upath == '.') { /* make it invisible */
-            u_int16_t ashort;
+            uint16_t ashort;
             
             ashort = htons(FINDERINFO_INVISIBLE);
             memcpy((char *)data + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
@@ -116,35 +97,29 @@ void *get_finderinfo(const struct vol *vol, const char *upath, struct adouble *a
     }
 
     if (islink){
-        u_int16_t linkflag;
+        uint16_t linkflag;
         memcpy(&linkflag, (char *)data + FINDERINFO_FRFLAGOFF, 2);
         linkflag |= htons(FINDERINFO_ISALIAS);
         memcpy((char *)data + FINDERINFO_FRFLAGOFF, &linkflag, 2);
         memcpy((char *)data + FINDERINFO_FRTYPEOFF,"slnk",4); 
         memcpy((char *)data + FINDERINFO_FRCREATOFF,"rhap",4); 
-        chk_ext = 0;
     }
 
-    /** Only enter if no appledouble information and no finder information found. */
-    if (chk_ext && (em = getextmap( upath ))) {
-        memcpy(data, em->em_type, sizeof( em->em_type ));
-        memcpy((char *)data + 4, em->em_creator, sizeof(em->em_creator));
-    }
     return data;
 }
 
 /* ---------------------
 */
-char *set_name(const struct vol *vol, char *data, cnid_t pid, char *name, cnid_t id, u_int32_t utf8) 
+char *set_name(const struct vol *vol, char *data, cnid_t pid, char *name, cnid_t id, uint32_t utf8) 
 {
-    u_int32_t   aint;
+    uint32_t   aint;
     char        *tp = NULL;
     char        *src = name;
     aint = strlen( name );
 
     if (!utf8) {
         /* want mac name */
-        if (utf8_encoding()) {
+        if (utf8_encoding(vol->v_obj)) {
             /* but name is an utf8 mac name */
             char *u, *m;
            
@@ -164,7 +139,7 @@ char *set_name(const struct vol *vol, char *data, cnid_t pid, char *name, cnid_t
         *data++ = aint;
     }
     else {
-        u_int16_t temp;
+        uint16_t temp;
 
         if (aint > UTF8FILELEN_EARLY)  /* FIXME safeguard, anyway if no ascii char it's game over*/
            aint = UTF8FILELEN_EARLY;
@@ -224,8 +199,8 @@ uint32_t get_id(struct vol *vol,
                 const int len) 
 {
     static int first = 1;       /* mark if this func is called the first time */
-    u_int32_t adcnid;
-    u_int32_t dbcnid = CNID_INVALID;
+    uint32_t adcnid;
+    uint32_t dbcnid = CNID_INVALID;
 
 restart:
     if (vol->v_cdb != NULL) {
@@ -264,7 +239,6 @@ restart:
                         vol->v_path);
                     vol->v_cdb = cnid_open(vol->v_path, vol->v_umask, "tdb", flags, NULL, NULL);
                     if (vol->v_cdb) {
-                        vol->v_flags &= ~AFPVOL_CACHE;
                         if (!(vol->v_flags & AFPVOL_TM)) {
                             vol->v_flags |= AFPVOL_RO;
                             setmessage("Something wrong with the volume's CNID DB, using temporary CNID DB instead."
@@ -281,12 +255,13 @@ restart:
                 goto exit;
             }
         }
-        else if (adp && (adcnid != dbcnid)) { /* 4 */
+        else if (adp && adcnid && (adcnid != dbcnid)) { /* 4 */
             /* Update the ressource fork. For a folder adp is always null */
             LOG(log_debug, logtype_afpd, "get_id(%s/%s): calling ad_setid(old: %u, new: %u)",
                 getcwdpath(), upath, htonl(adcnid), htonl(dbcnid));
             if (ad_setid(adp, st->st_dev, st->st_ino, dbcnid, did, vol->v_stamp)) {
-                ad_flush(adp);
+                if (ad_flush(adp) != 0)
+                    LOG(log_error, logtype_afpd, "get_id(\"%s\"): can't flush", fullpathname(upath));
             }
         }
     }
@@ -297,19 +272,20 @@ exit:
 }
              
 /* -------------------------- */
-int getmetadata(struct vol *vol,
-                 u_int16_t bitmap,
-                 struct path *path, struct dir *dir, 
-                 char *buf, size_t *buflen, struct adouble *adp)
+int getmetadata(const AFPObj *obj,
+                struct vol *vol,
+                uint16_t bitmap,
+                struct path *path, struct dir *dir, 
+                char *buf, size_t *buflen, struct adouble *adp)
 {
     char               *data, *l_nameoff = NULL, *upath;
     char                *utf_nameoff = NULL;
     int                        bit = 0;
-    u_int32_t          aint;
+    uint32_t           aint;
     cnid_t              id = 0;
-    u_int16_t          ashort;
+    uint16_t           ashort;
     u_char              achar, fdType[4];
-    u_int32_t           utf8 = 0;
+    uint32_t           utf8 = 0;
     struct stat         *st;
     struct maccess     ma;
 
@@ -320,7 +296,7 @@ int getmetadata(struct vol *vol,
     data = buf;
 
     if ( ((bitmap & ( (1 << FILPBIT_FINFO)|(1 << FILPBIT_LNAME)|(1 <<FILPBIT_PDINFO) ) ) && !path->m_name)
-         || (bitmap & ( (1 << FILPBIT_LNAME) ) && utf8_encoding()) /* FIXME should be m_name utf8 filename */
+         || (bitmap & ( (1 << FILPBIT_LNAME) ) && utf8_encoding(obj)) /* FIXME should be m_name utf8 filename */
          || (bitmap & (1 << FILPBIT_FNUM))) {
         if (!path->id) {
             bstring fullpath;
@@ -337,7 +313,7 @@ int getmetadata(struct vol *vol,
 
                 /* Get macname from unixname first */
                 if (path->m_name == NULL) {
-                    if ((path->m_name = utompath(vol, upath, id, utf8_encoding())) == NULL) {
+                    if ((path->m_name = utompath(vol, upath, id, utf8_encoding(obj))) == NULL) {
                         LOG(log_error, logtype_afpd, "getmetadata: utompath error");
                         return AFPERR_MISC;
                     }
@@ -369,7 +345,7 @@ int getmetadata(struct vol *vol,
             return afp_errno;
 
         if (!path->m_name) {
-            path->m_name = utompath(vol, upath, id, utf8_encoding());
+            path->m_name = utompath(vol, upath, id, utf8_encoding(vol->v_obj));
         }
     }
     while ( bitmap != 0 ) {
@@ -405,8 +381,8 @@ int getmetadata(struct vol *vol,
             break;
 
         case FILPBIT_PDID :
-            memcpy(data, &dir->d_did, sizeof( u_int32_t ));
-            data += sizeof( u_int32_t );
+            memcpy(data, &dir->d_did, sizeof( uint32_t ));
+            data += sizeof( uint32_t );
             LOG(log_debug, logtype_afpd, "metadata('%s'):     Parent DID: %u",
                 path->u_name, ntohl(dir->d_did));
             break;
@@ -444,12 +420,12 @@ int getmetadata(struct vol *vol,
 
         case FILPBIT_LNAME :
             l_nameoff = data;
-            data += sizeof( u_int16_t );
+            data += sizeof( uint16_t );
             break;
 
         case FILPBIT_SNAME :
-            memset(data, 0, sizeof(u_int16_t));
-            data += sizeof( u_int16_t );
+            memset(data, 0, sizeof(uint16_t));
+            data += sizeof( uint16_t );
             break;
 
         case FILPBIT_FNUM :
@@ -488,10 +464,10 @@ int getmetadata(struct vol *vol,
                to "pXYZ" when we created it.  See IA, Ver 2.
                <shirsch@adelphia.net> */
         case FILPBIT_PDINFO :
-            if (afp_version >= 30) { /* UTF8 name */
+            if (obj->afp_version >= 30) { /* UTF8 name */
                 utf8 = kTextEncodingUTF8;
                 utf_nameoff = data;
-                data += sizeof( u_int16_t );
+                data += sizeof( uint16_t );
                 aint = 0;
                 memcpy(data, &aint, sizeof( aint ));
                 data += sizeof( aint );
@@ -559,7 +535,7 @@ int getmetadata(struct vol *vol,
             break;
         case FILPBIT_UNIXPR :
             /* accessmode may change st_mode with ACLs */
-            accessmode(vol, upath, &ma, dir , st);
+            accessmode(obj, vol, upath, &ma, dir , st);
 
             aint = htonl(st->st_uid);
             memcpy( data, &aint, sizeof( aint ));
@@ -612,14 +588,13 @@ int getmetadata(struct vol *vol,
 }
                 
 /* ----------------------- */
-int getfilparams(struct vol *vol,
-                 u_int16_t bitmap,
-                 struct path *path, struct dir *dir, 
-                 char *buf, size_t *buflen )
+int getfilparams(const AFPObj *obj, struct vol *vol, uint16_t bitmap, struct path *path,
+                 struct dir *dir, char *buf, size_t *buflen, int in_enumerate)
 {
     struct adouble     ad, *adp;
     int                 opened = 0;
     int rc;    
+    int flags;
 
     LOG(log_debug, logtype_afpd, "getfilparams(\"%s\")", path->u_name);
 
@@ -628,12 +603,17 @@ int getfilparams(struct vol *vol,
 
     if (opened) {
         char *upath;
-        int  flags = (bitmap & (1 << FILPBIT_ATTR))?ADFLAGS_OPENFORKS:0;
+        /*
+         * Dont check for and resturn open fork attributes when enumerating
+         * This saves a lot of syscalls, the client will hopefully only use the result
+         * in FPGetFileParms where we return the correct value
+         */
+        flags = (!in_enumerate &&(bitmap & (1 << FILPBIT_ATTR))) ? ADFLAGS_CHECK_OF : 0;
 
         adp = of_ad(vol, path, &ad);
         upath = path->u_name;
 
-        if ( ad_metadata( upath, flags|ADFLAGS_CREATE, adp) < 0 ) {
+        if ( ad_metadata( upath, flags, adp) < 0 ) {
             switch (errno) {
             case EACCES:
                 LOG(log_error, logtype_afpd, "getfilparams(%s): %s: check resource fork permission?",
@@ -649,10 +629,8 @@ int getfilparams(struct vol *vol,
             }
         }
     }
-    rc = getmetadata(vol, bitmap, path, dir, buf, buflen, adp);
-    if ( adp ) {
-        ad_close_metadata( adp);
-    }
+    rc = getmetadata(obj, vol, bitmap, path, dir, buf, buflen, adp);
+    ad_close(adp, ADFLAGS_HF | flags);
 
     return( rc );
 }
@@ -660,13 +638,13 @@ int getfilparams(struct vol *vol,
 /* ----------------------------- */
 int afp_createfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
-    struct adouble     ad, *adp;
+    struct adouble     ad;
     struct vol         *vol;
     struct dir         *dir;
     struct ofork        *of = NULL;
     char               *path, *upath;
     int                        creatf, did, openf, retvalue = AFP_OK;
-    u_int16_t          vid;
+    uint16_t           vid;
     struct path                *s_path;
     
     *rbuflen = 0;
@@ -676,9 +654,8 @@ int afp_createfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_,
     memcpy(&vid, ibuf, sizeof( vid ));
     ibuf += sizeof( vid );
 
-    if (NULL == ( vol = getvolbyvid( vid )) ) {
+    if (NULL == ( vol = getvolbyvid( vid )) )
         return( AFPERR_PARAM );
-    }
 
     if (vol->v_flags & AFPVOL_RO)
         return AFPERR_VLOCK;
@@ -686,44 +663,33 @@ int afp_createfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_,
     memcpy(&did, ibuf, sizeof( did));
     ibuf += sizeof( did );
 
-    if (NULL == ( dir = dirlookup( vol, did )) ) {
+    if (NULL == ( dir = dirlookup( vol, did )) )
         return afp_errno;
-    }
 
-    if (NULL == ( s_path = cname( vol, dir, &ibuf )) ) {
+    if (NULL == ( s_path = cname( vol, dir, &ibuf )) )
         return get_afp_errno(AFPERR_PARAM);
-    }
-
-    if ( *s_path->m_name == '\0' ) {
+    if ( *s_path->m_name == '\0' )
         return( AFPERR_BADTYPE );
-    }
 
     upath = s_path->u_name;
+    ad_init(&ad, vol);
     
     /* if upath is deleted we already in trouble anyway */
     if ((of = of_findname(s_path))) {
-        adp = of->of_ad;
-    } else {
-        ad_init(&ad, vol->v_adouble, vol->v_ad_options);
-        adp = &ad;
-    }
-    if ( creatf) {
-        /* on a hard create, fail if file exists and is open */
-        if (of)
+        if (creatf)
             return AFPERR_BUSY;
-        openf = O_RDWR|O_CREAT|O_TRUNC;
-    } else {
-       /* on a soft create, if the file is open then ad_open won't fail
-          because open syscall is not called
-       */
-       if (of) {
-               return AFPERR_EXIST;
-       }
-        openf = O_RDWR|O_CREAT|O_EXCL;
+        else
+            return AFPERR_EXIST;
     }
 
-    if ( ad_open( upath, ADFLAGS_DF|ADFLAGS_HF|ADFLAGS_NOHF|ADFLAGS_CREATE,
-                  openf, 0666, adp) < 0 ) {
+    if (creatf)
+        openf = ADFLAGS_RDWR | ADFLAGS_CREATE | ADFLAGS_TRUNC;
+    else
+       /* on a soft create, if the file is open then ad_open won't fail
+          because open syscall is not called */
+        openf = ADFLAGS_RDWR | ADFLAGS_CREATE | ADFLAGS_EXCL;
+
+    if (ad_open(&ad, upath, ADFLAGS_DF | ADFLAGS_HF | ADFLAGS_NOHF | openf, 0666) < 0) {
         switch ( errno ) {
         case EROFS:
             return AFPERR_VLOCK;
@@ -741,48 +707,41 @@ int afp_createfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_,
             return( AFPERR_PARAM );
         }
     }
-    if ( ad_reso_fileno( adp ) == -1 ) { /* Hard META / HF */
-         /* on noadouble volumes, just creating the data fork is ok */
-         if (vol_noadouble(vol)) {
-             ad_close( adp, ADFLAGS_DF );
-             goto createfile_done;
-         }
+    if ( ad_meta_fileno( &ad ) == -1 ) { /* Hard META / HF */
          /* FIXME with hard create on an existing file, we already
           * corrupted the data file.
           */
          netatalk_unlink( upath );
-         ad_close( adp, ADFLAGS_DF );
+         ad_close( &ad, ADFLAGS_DF );
          return AFPERR_ACCESS;
     }
 
     path = s_path->m_name;
-    ad_setname(adp, path);
+    ad_setname(&ad, path);
 
     struct stat st;
     if (lstat(upath, &st) != 0) {
         LOG(log_error, logtype_afpd, "afp_createfile(\"%s\"): stat: %s",
             upath, strerror(errno));
-        ad_close( adp, ADFLAGS_DF|ADFLAGS_HF);
+        ad_close(&ad, ADFLAGS_DF|ADFLAGS_HF);
         return AFPERR_MISC;
     }
 
-    (void)get_id(vol, adp, &st, dir->d_did, upath, strlen(upath));
-
-    ad_flush( adp);
+    cnid_t id;
+    if ((id = get_id(vol, &ad, &st, dir->d_did, upath, strlen(upath))) == CNID_INVALID) {
+        LOG(log_error, logtype_afpd, "afp_createfile(\"%s\"): CNID error", upath);
+        goto createfile_iderr;
+    }
+    (void)ad_setid(&ad, st.st_dev, st.st_ino, id, dir->d_did, vol->v_stamp);
 
+createfile_iderr:
+    ad_flush(&ad);
+    ad_close(&ad, ADFLAGS_DF|ADFLAGS_HF );
     fce_register_new_file(s_path);
 
-    ad_close( adp, ADFLAGS_DF|ADFLAGS_HF );
-
 createfile_done:
     curdir->d_offcnt++;
 
-#ifdef DROPKLUDGE
-    if (vol->v_flags & AFPVOL_DROPBOX) {
-        retvalue = matchfile2dirperms(upath, vol, did);
-    }
-#endif /* DROPKLUDGE */
-
     setvoltime(obj, vol );
 
     return (retvalue);
@@ -794,7 +753,7 @@ int afp_setfilparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_
     struct dir *dir;
     struct path *s_path;
     int                did, rc;
-    u_int16_t  vid, bitmap;
+    uint16_t   vid, bitmap;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -834,7 +793,7 @@ int afp_setfilparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_
         ibuf++;
     }
 
-    if (AFP_OK == ( rc = setfilparams(vol, s_path, bitmap, ibuf )) ) {
+    if (AFP_OK == ( rc = setfilparams(obj, vol, s_path, bitmap, ibuf )) ) {
         setvoltime(obj, vol );
     }
 
@@ -847,30 +806,29 @@ int afp_setfilparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_
 */
 extern struct path Cur_Path;
 
-int setfilparams(struct vol *vol,
-                 struct path *path, u_int16_t f_bitmap, char *buf )
+int setfilparams(const AFPObj *obj, struct vol *vol,
+                 struct path *path, uint16_t f_bitmap, char *buf )
 {
     struct adouble     ad, *adp;
     struct extmap      *em;
     int                        bit, isad = 1, err = AFP_OK;
     char                *upath;
     u_char              achar, *fdType, xyy[4]; /* uninitialized, OK 310105 */
-    u_int16_t          ashort, bshort, oshort;
-    u_int32_t          aint;
-    u_int32_t          upriv;
-    u_int16_t           upriv_bit = 0;
-    
-    struct utimbuf     ut;
-
+    uint16_t           ashort, bshort, oshort;
+    uint32_t           aint;
+    uint32_t           upriv;
+    uint16_t           upriv_bit = 0;
+        struct utimbuf ut;
     int                 change_mdate = 0;
     int                 change_parent_mdate = 0;
     int                 newdate = 0;
     struct timeval      tv;
     uid_t              f_uid;
     gid_t              f_gid;
-    u_int16_t           bitmap = f_bitmap;
-    u_int32_t           cdate,bdate;
+    uint16_t           bitmap = f_bitmap;
+    uint32_t           cdate,bdate;
     u_char              finder_buf[32];
+    int symlinked = 0;
 
 #ifdef DEBUG
     LOG(log_debug9, logtype_afpd, "begin setfilparams:");
@@ -879,7 +837,7 @@ int setfilparams(struct vol *vol,
     adp = of_ad(vol, path, &ad);
     upath = path->u_name;
 
-    if (!vol_unix_priv(vol) && check_access(upath, OPENACC_WR ) < 0) {
+    if (!vol_unix_priv(vol) && check_access(obj, vol, upath, OPENACC_WR ) < 0) {
         return AFPERR_ACCESS;
     }
 
@@ -913,16 +871,15 @@ int setfilparams(struct vol *vol,
         case FILPBIT_FINFO :
             change_mdate = 1;
             memcpy(finder_buf, buf, 32 );
-            if (memcmp(buf,"slnkrhap",8)==0 && !S_ISLNK(path->st.st_mode)){
-            // SLFINFO
+            if (memcmp(buf, "slnkrhap", 8) == 0 && !S_ISLNK(path->st.st_mode)) {
                 int fp;
                 ssize_t len;
                 int erc=1;
                 char buf[PATH_MAX+1];
-                if ((fp=open(path->u_name,O_RDONLY))>=0){
-                    if ((len=read(fp,buf,PATH_MAX+1))){
-                        if (unlink(path->u_name)==0){
-                            buf[len]=0;
+                if ((fp = open(path->u_name, O_RDONLY)) >= 0) {
+                    if ((len = read(fp, buf, PATH_MAX+1))) {
+                        if (unlink(path->u_name) == 0) {
+                            buf[len] = 0;
                             erc = symlink(buf, path->u_name);
                             if (!erc)
                                 of_stat(path);
@@ -930,10 +887,11 @@ int setfilparams(struct vol *vol,
                     }
                     close(fp);
                 }
-                if (erc!=0){
+                if (erc != 0) {
                     err=AFPERR_BITMAP;
                     goto setfilparam_done;
                 }
+                symlinked = 1;
             }
             buf += 32;
             break;
@@ -967,7 +925,7 @@ int setfilparams(struct vol *vol,
             }
             break;
         case FILPBIT_PDINFO :
-            if (afp_version < 30) { /* else it's UTF8 name */
+            if (obj->afp_version < 30) { /* else it's UTF8 name */
                 achar = *buf;
                 buf += 2;
                 /* Keep special case to support crlf translations */
@@ -997,20 +955,20 @@ int setfilparams(struct vol *vol,
 
     /* second try with adouble open 
     */
-    if ( ad_open_metadata( upath, 0, O_CREAT, adp) < 0) {
+    if (ad_open(adp, upath, ADFLAGS_HF | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) < 0) {
         LOG(log_debug, logtype_afpd, "setfilparams: ad_open_metadata error");
         /*
          * For some things, we don't need an adouble header:
          * - change of modification date
          * - UNIX privs (Bug-ID #2863424)
          */
-        if (!vol_noadouble(vol) && (f_bitmap & ~(1<<FILPBIT_MDATE | 1<<FILPBIT_UNIXPR))) {
+        if (!symlinked && f_bitmap & ~(1<<FILPBIT_MDATE | 1<<FILPBIT_UNIXPR)) {
             LOG(log_debug, logtype_afpd, "setfilparams: need adouble access");
             return AFPERR_ACCESS;
         }
         LOG(log_debug, logtype_afpd, "setfilparams: no adouble perms, but only FILPBIT_MDATE and/or FILPBIT_UNIXPR");
         isad = 0;
-    } else if ((ad_get_HF_flags( adp ) & O_CREAT) ) {
+    } else if ((ad_get_MD_flags( adp ) & O_CREAT) ) {
         ad_setname(adp, path->m_name);
     }
     
@@ -1044,17 +1002,6 @@ int setfilparams(struct vol *vol,
             ad_setdate(adp, AD_DATE_BACKUP, bdate);
             break;
         case FILPBIT_FINFO :
-            if (default_type( ad_entry( adp, ADEID_FINDERI ))
-                    && ( 
-                     ((em = getextmap( path->m_name )) &&
-                      !memcmp(finder_buf, em->em_type, sizeof( em->em_type )) &&
-                      !memcmp(finder_buf + 4, em->em_creator,sizeof( em->em_creator)))
-                     || ((em = getdefextmap()) &&
-                      !memcmp(finder_buf, em->em_type, sizeof( em->em_type )) &&
-                      !memcmp(finder_buf + 4, em->em_creator,sizeof( em->em_creator)))
-            )) {
-                memcpy(finder_buf, ufinderi, 8 );
-            }
             memcpy(ad_entry( adp, ADEID_FINDERI ), finder_buf, 32 );
             break;
         case FILPBIT_UNIXPR :
@@ -1063,7 +1010,7 @@ int setfilparams(struct vol *vol,
             }
             break;
         case FILPBIT_PDINFO :
-            if (afp_version < 30) { /* else it's UTF8 name */
+            if (obj->afp_version < 30) { /* else it's UTF8 name */
                 memcpy(ad_entry( adp, ADEID_FINDERI ), fdType, 4 );
                 memcpy(ad_entry( adp, ADEID_FINDERI ) + 4, "pdos", 4 );
                 break;
@@ -1089,9 +1036,8 @@ setfilparam_done:
     }
 
     if (isad) {
-        ad_flush( adp);
-        ad_close_metadata( adp);
-
+        ad_flush(adp);
+        ad_close(adp, ADFLAGS_HF);
     }
 
     if (change_parent_mdate && gettimeofday(&tv, NULL) == 0) {
@@ -1177,9 +1123,8 @@ int renamefile(const struct vol *vol, int sdir_fd, char *src, char *dst, char *n
         }
     }
 
-    /* don't care if we can't open the newly renamed ressource fork
-     */
-    if (!ad_open( dst, ADFLAGS_HF, O_RDWR, 0666, adp)) {
+    /* don't care if we can't open the newly renamed ressource fork */
+    if (ad_open(adp, dst, ADFLAGS_HF | ADFLAGS_RDWR) == 0) {
         ad_setname(adp, newname);
         ad_flush( adp );
         ad_close( adp, ADFLAGS_HF );
@@ -1206,17 +1151,17 @@ int copy_path_name(const struct vol *vol, char *newname, char *ibuf)
 {
 char        type = *ibuf;
 size_t      plen = 0;
-u_int16_t   len16;
-u_int32_t   hint;
+uint16_t   len16;
+uint32_t   hint;
 
-    if ( type != 2 && !(afp_version >= 30 && type == 3) ) {
+    if ( type != 2 && !(vol->v_obj->afp_version >= 30 && type == 3) ) {
         return -1;
     }
     ibuf++;
     switch (type) {
     case 2:
         if (( plen = (unsigned char)*ibuf++ ) != 0 ) {
-            if (afp_version >= 30) {
+            if (vol->v_obj->afp_version >= 30) {
                 /* convert it to UTF8 
                 */
                 if ((plen = mtoUTF8(vol, ibuf, plen, newname, AFPOBJ_TMPSIZ)) == (size_t)-1)
@@ -1265,9 +1210,9 @@ int afp_copyfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, si
     struct dir *dir;
     char       *newname, *p, *upath;
     struct path *s_path;
-    u_int32_t  sdid, ddid;
+    uint32_t   sdid, ddid;
     int         err, retvalue = AFP_OK;
-    u_int16_t  svid, dvid;
+    uint16_t   svid, dvid;
 
     struct adouble ad, *adp;
     int denyreadset;
@@ -1307,11 +1252,24 @@ int afp_copyfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, si
 
     adp = of_ad(s_vol, s_path, &ad);
 
-    if (ad_open(s_path->u_name , ADFLAGS_DF |ADFLAGS_HF | ADFLAGS_NOHF, O_RDONLY, 0, adp) < 0) {
+    if (ad_open(adp, s_path->u_name, ADFLAGS_DF | ADFLAGS_HF | ADFLAGS_NOHF | ADFLAGS_RDONLY | ADFLAGS_SETSHRMD) < 0) {
         return AFPERR_DENYCONF;
     }
-    denyreadset = (getforkmode(adp, ADEID_DFORK, AD_FILELOCK_DENY_RD) != 0 || 
-                  getforkmode(adp, ADEID_RFORK, AD_FILELOCK_DENY_RD) != 0 );
+#ifdef HAVE_FSHARE_T
+    fshare_t shmd;
+    shmd.f_access = F_RDACC;
+    shmd.f_deny = F_NODNY;
+    if (fcntl(ad_data_fileno(adp), F_SHARE, &shmd) != 0) {
+        retvalue = AFPERR_DENYCONF;
+        goto copy_exit;
+    }
+    if (AD_RSRC_OPEN(adp) && fcntl(ad_reso_fileno(adp), F_SHARE, &shmd) != 0) {
+        retvalue = AFPERR_DENYCONF;
+        goto copy_exit;
+    }
+#endif
+    denyreadset = (ad_testlock(adp, ADEID_DFORK, AD_FILELOCK_DENY_RD) != 0 || 
+                  ad_testlock(adp, ADEID_RFORK, AD_FILELOCK_DENY_RD) != 0 );
 
     if (denyreadset) {
         retvalue = AFPERR_DENYCONF;
@@ -1327,9 +1285,6 @@ int afp_copyfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, si
         goto copy_exit;
     }
 
-#ifdef FORCE_UIDGID
-    /* FIXME svid != dvid && dvid's user can't read svid */
-#endif
     if (NULL == ( d_vol = getvolbyvid( dvid )) ) {
         retvalue = AFPERR_PARAM;
         goto copy_exit;
@@ -1363,7 +1318,7 @@ int afp_copyfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, si
     /* newname is always only a filename so curdir *is* its
      * parent folder
     */
-    if (NULL == (upath = mtoupath(d_vol, newname, curdir->d_did, utf8_encoding()))) {
+    if (NULL == (upath = mtoupath(d_vol, newname, curdir->d_did, utf8_encoding(d_vol->v_obj)))) {
         retvalue =AFPERR_PARAM;
         goto copy_exit;
     }
@@ -1374,117 +1329,13 @@ int afp_copyfile(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, si
     }
     curdir->d_offcnt++;
 
-#ifdef DROPKLUDGE
-    if (vol->v_flags & AFPVOL_DROPBOX) {
-        retvalue=matchfile2dirperms(upath, vol, ddid); /* FIXME sdir or ddid */
-    }
-#endif /* DROPKLUDGE */
-
     setvoltime(obj, d_vol );
 
 copy_exit:
-    ad_close( adp, ADFLAGS_DF |ADFLAGS_HF );
+    ad_close( adp, ADFLAGS_DF |ADFLAGS_HF | ADFLAGS_SETSHRMD);
     return( retvalue );
 }
 
-/* ----------------------- */
-static int copy_all(const int dfd, const void *buf,
-                               size_t buflen)
-{
-    ssize_t cc;
-
-#ifdef DEBUG
-    LOG(log_debug9, logtype_afpd, "begin copy_all:");
-#endif /* DEBUG */
-
-    while (buflen > 0) {
-        if ((cc = write(dfd, buf, buflen)) < 0) {
-            switch (errno) {
-            case EINTR:
-                continue;
-            default:
-                return -1;
-            }
-        }
-        buflen -= cc;
-    }
-
-#ifdef DEBUG
-    LOG(log_debug9, logtype_afpd, "end copy_all:");
-#endif /* DEBUG */
-
-    return 0;
-}
-
-/* -------------------------- 
- * copy only the fork data stream
-*/
-static int copy_fork(int eid, struct adouble *add, struct adouble *ads)
-{
-    ssize_t cc;
-    int     err = 0;
-    char    filebuf[8192];
-    int     sfd, dfd;
-    
-    if (eid == ADEID_DFORK) {
-        sfd = ad_data_fileno(ads);
-        dfd = ad_data_fileno(add);
-    }
-    else {
-        sfd = ad_reso_fileno(ads);
-        dfd = ad_reso_fileno(add);
-    }        
-
-    if ((off_t)-1 == lseek(sfd, ad_getentryoff(ads, eid), SEEK_SET))
-       return -1;
-
-    if ((off_t)-1 == lseek(dfd, ad_getentryoff(add, eid), SEEK_SET))
-       return -1;
-       
-#if 0 /* ifdef SENDFILE_FLAVOR_LINUX */
-    /* doesn't work With 2.6 FIXME, only check for EBADFD ? */
-    off_t   offset = 0;
-    size_t  size;
-    struct stat         st;
-    #define BUF 128*1024*1024
-
-    if (fstat(sfd, &st) == 0) {
-        
-        while (1) {
-            if ( offset >= st.st_size) {
-               return 0;
-            }
-            size = (st.st_size -offset > BUF)?BUF:st.st_size -offset;
-            if ((cc = sys_sendfile(dfd, sfd, &offset, size)) < 0) {
-                switch (errno) {
-                case ENOSYS:
-                case EINVAL:  /* there's no guarantee that all fs support sendfile */
-                    goto no_sendfile;
-                default:
-                    return -1;
-                }
-            }
-        }
-    }
-    no_sendfile:
-    lseek(sfd, offset, SEEK_SET);
-#endif 
-
-    while (1) {
-        if ((cc = read(sfd, filebuf, sizeof(filebuf))) < 0) {
-            if (errno == EINTR)
-                continue;
-            err = -1;
-            break;
-        }
-
-        if (!cc || ((err = copy_all(dfd, filebuf, cc)) < 0)) {
-            break;
-        }
-    }
-    return err;
-}
-
 /* ----------------------------------
  * if newname is NULL (from directory.c) we don't want to copy the resource fork.
  * because we are doing it elsewhere.
@@ -1509,24 +1360,20 @@ int copyfile(const struct vol *s_vol,
         sfd, src, dst, newname);
 
     if (adp == NULL) {
-        ad_init(&ads, s_vol->v_adouble, s_vol->v_ad_options); 
+        ad_init(&ads, s_vol);
         adp = &ads;
     }
 
-    adflags = ADFLAGS_DF;
-    if (newname) {
-        adflags |= ADFLAGS_HF;
-    }
+    adflags = ADFLAGS_DF | ADFLAGS_RF | ADFLAGS_NORF;
 
-    if (ad_openat(sfd, src, adflags | ADFLAGS_NOHF, O_RDONLY, 0, adp) < 0) {
+    if (ad_openat(adp, sfd, src, adflags | ADFLAGS_RDONLY) < 0) {
         ret_err = errno;
         goto done;
     }
 
-    if (ad_meta_fileno(adp) == -1 && ad_reso_fileno(adp) == -1) { /* META / HF */
+    if (!AD_RSRC_OPEN(adp))
         /* no resource fork, don't create one for dst file */
-        adflags &= ~ADFLAGS_HF;
-    }
+        adflags &= ~ADFLAGS_RF;
 
     stat_result = fstat(ad_data_fileno(adp), &st); /* saving stat exit code, thus saving us on one more stat later on */
 
@@ -1535,8 +1382,8 @@ int copyfile(const struct vol *s_vol,
       st.st_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
     }
 
-    ad_init(&add, d_vol->v_adouble, d_vol->v_ad_options);
-    if (ad_open(dst , adflags, O_RDWR|O_CREAT|O_EXCL, st.st_mode, &add) < 0) {
+    ad_init(&add, d_vol);
+    if (ad_open(&add, dst, adflags | ADFLAGS_RDWR | ADFLAGS_CREATE | ADFLAGS_EXCL, st.st_mode | S_IRUSR | S_IWUSR) < 0) {
         ret_err = errno;
         ad_close( adp, adflags );
         if (EEXIST != ret_err) {
@@ -1545,21 +1392,16 @@ int copyfile(const struct vol *s_vol,
         }
         return AFPERR_EXIST;
     }
-    
-    /*
-     * XXX if the source and the dest don't use the same resource type it's broken
-     */
-    if (ad_reso_fileno(adp) == -1 || 0 == (err = copy_fork(ADEID_RFORK, &add, adp))){
-        /* copy the data fork */
-        if ((err = copy_fork(ADEID_DFORK, &add, adp)) == 0) {
-            if (ad_meta_fileno(adp) != -1)
-                err = d_vol->vfs->vfs_copyfile(d_vol, sfd, src, dst);
-        }
-    }
 
-    if (err < 0) {
+    if ((err = copy_fork(ADEID_DFORK, &add, adp)) != 0)
+        LOG(log_error, logtype_afpd, "copyfile('%s'): %s", src, strerror(errno));
+
+    if (err == 0)
+        if ((err = d_vol->vfs->vfs_copyfile(d_vol, sfd, src, dst)) != 0)
+            LOG(log_error, logtype_afpd, "copyfile('%s'): %s", src, strerror(errno));
+
+    if (err < 0)
        ret_err = errno;
-    }
 
     if (!ret_err && newname && (adflags & ADFLAGS_HF)) {
         /* set the new name in the resource fork */
@@ -1620,7 +1462,7 @@ done:
 
 static int check_attrib(struct adouble *adp)
 {
-u_int16_t   bshort = 0;
+uint16_t   bshort = 0;
 
        ad_getattr(adp, &bshort);
     /*
@@ -1646,16 +1488,16 @@ int deletefile(const struct vol *vol, int dirfd, char *file, int checkAttrib)
 
     LOG(log_debug, logtype_afpd, "deletefile('%s')", file);
 
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
+    ad_init(&ad, vol);
     if (checkAttrib) {
         /* was EACCESS error try to get only metadata */
         /* we never want to create a resource fork here, we are going to delete it 
          * moreover sometimes deletefile is called with a no existent file and 
          * ad_open would create a 0 byte resource fork
         */
-        if ( ad_metadataat(dirfd, file, ADFLAGS_OPENFORKS, &ad) == 0 ) {
+        if ( ad_metadataat(dirfd, file, ADFLAGS_CHECK_OF, &ad) == 0 ) {
             if ((err = check_attrib(&ad))) {
-               ad_close_metadata(&ad);
+                ad_close(&ad, ADFLAGS_HF | ADFLAGS_CHECK_OF);
                return err;
             }
             meta = 1;
@@ -1664,7 +1506,7 @@ int deletefile(const struct vol *vol, int dirfd, char *file, int checkAttrib)
  
     /* try to open both forks at once */
     adflags = ADFLAGS_DF;
-    if ( ad_openat(dirfd, file, adflags |ADFLAGS_HF|ADFLAGS_NOHF, O_RDONLY, 0, &ad ) < 0 ) {
+    if (ad_openat(&ad, dirfd, file, adflags | ADFLAGS_RF | ADFLAGS_NORF | ADFLAGS_RDONLY) < 0 ) {
         switch (errno) {
         case ENOENT:
             err = AFPERR_NOOBJ;
@@ -1683,8 +1525,8 @@ int deletefile(const struct vol *vol, int dirfd, char *file, int checkAttrib)
         adp = &ad;
     }
 
-    if ( adp && ad_reso_fileno( adp ) != -1 ) { /* there's a resource fork */
-        adflags |= ADFLAGS_HF;
+    if ( adp && AD_RSRC_OPEN(adp) != -1 ) { /* there's a resource fork */
+        adflags |= ADFLAGS_RF;
         /* FIXME we have a pb here because we want to know if a file is open 
          * there's a 'priority inversion' if you can't open the ressource fork RW
          * you can delete it if it's open because you can't get a write lock.
@@ -1701,6 +1543,7 @@ int deletefile(const struct vol *vol, int dirfd, char *file, int checkAttrib)
     }
 
     if (adp && ad_tmplock( &ad, ADEID_DFORK, ADLOCK_WR, 0, 0, 0 ) < 0) {
+        LOG(log_error, logtype_afpd, "deletefile('%s'): ad_tmplock error: %s", file, strerror(errno));
         err = AFPERR_BUSY;
     } else if (!(err = vol->vfs->vfs_deletefile(vol, dirfd, file)) && !(err = netatalk_unlinkat(dirfd, file )) ) {
         cnid_t id;
@@ -1711,7 +1554,7 @@ int deletefile(const struct vol *vol, int dirfd, char *file, int checkAttrib)
 
 end:
     if (meta)
-        ad_close_metadata(&ad);
+        ad_close(&ad, ADFLAGS_HF | ADFLAGS_CHECK_OF);
 
     if (adp)
         ad_close( &ad, adflags );  /* ad_close removes locks if any */
@@ -1807,32 +1650,12 @@ static int reenumerate_loop(struct dirent *de, char *mname _U_, void *data)
     cnid_t        did  = param->did;
     cnid_t       aint;
     
-    if ( lstat(de->d_name, &path.st)<0 )
+    if ( lstat(de->d_name, &path.st) < 0 )
         return 0;
     
     /* update or add to cnid */
     aint = cnid_add(vol->v_cdb, &path.st, did, de->d_name, strlen(de->d_name), 0); /* ignore errors */
 
-#if AD_VERSION > AD_VERSION1
-    if (aint != CNID_INVALID && !S_ISDIR(path.st.st_mode)) {
-        struct adouble  ad, *adp;
-
-        path.st_errno = 0;
-        path.st_valid = 1;
-        path.u_name = de->d_name;
-            
-        adp = of_ad(vol, &path, &ad);
-            
-        if ( ad_open_metadata( de->d_name, 0, 0, adp ) < 0 ) {
-            return 0;
-        }
-        if (ad_setid(adp, path.st.st_dev, path.st.st_ino, aint, did, vol->v_stamp)) {
-            ad_flush(adp);
-        }
-        ad_close_metadata(adp);
-    }
-#endif /* AD_VERSION > AD_VERSION1 */
-
     return 0;
 }
 
@@ -1873,7 +1696,7 @@ reenumerate_id(struct vol *vol, char *name, struct dir *dir)
 
 /* ------------------------------
    resolve a file id */
-int afp_resolveid(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
+int afp_resolveid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
     struct vol         *vol;
     struct dir         *dir;
@@ -1882,7 +1705,7 @@ int afp_resolveid(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, s
     int                 err, retry=0;
     size_t             buflen;
     cnid_t             id, cnid;
-    u_int16_t          vid, bitmap;
+    uint16_t           vid, bitmap;
 
     static char buffer[12 + MAXPATHLEN + 1];
     int len = 12 + MAXPATHLEN + 1;
@@ -1959,17 +1782,17 @@ retry:
     /* directories are bad */
     if (S_ISDIR(path.st.st_mode)) {
         /* OS9 and OSX don't return the same error code  */
-        return (afp_version >=30)?AFPERR_NOID:AFPERR_BADTYPE;
+        return (obj->afp_version >=30)?AFPERR_NOID:AFPERR_BADTYPE;
     }
 
     memcpy(&bitmap, ibuf, sizeof(bitmap));
     bitmap = ntohs( bitmap );
-    if (NULL == (path.m_name = utompath(vol, upath, cnid, utf8_encoding()))) {
+    if (NULL == (path.m_name = utompath(vol, upath, cnid, utf8_encoding(obj)))) {
         return AFPERR_NOID;
     }
     path.id = cnid;
-    if (AFP_OK != (err = getfilparams(vol, bitmap, &path , curdir, 
-                            rbuf + sizeof(bitmap), &buflen))) {
+    if (AFP_OK != (err = getfilparams(obj, vol, bitmap, &path , curdir, 
+                                      rbuf + sizeof(bitmap), &buflen, 0))) {
         return err;
     }
     *rbuflen = buflen + sizeof(bitmap);
@@ -2062,7 +1885,7 @@ delete:
 }
 
 /* ------------------------------ */
-static struct adouble *find_adouble(struct path *path, struct ofork **of, struct adouble *adp)
+static struct adouble *find_adouble(const AFPObj *obj, struct vol *vol, struct path *path, struct ofork **of, struct adouble *adp)
 {
     int             ret;
 
@@ -2084,7 +1907,7 @@ static struct adouble *find_adouble(struct path *path, struct ofork **of, struct
     /* we use file_access both for legacy Mac perm and
      * for unix privilege, rename will take care of folder perms
     */
-    if (file_access(path, OPENACC_WR ) < 0) {
+    if (file_access(obj, vol, path, OPENACC_WR ) < 0) {
         afp_errno = AFPERR_ACCESS;
         return NULL;
     }
@@ -2094,7 +1917,7 @@ static struct adouble *find_adouble(struct path *path, struct ofork **of, struct
         adp = (*of)->of_ad;
     }
     else {
-        ret = ad_open( path->u_name, ADFLAGS_HF, O_RDONLY, 0, adp);
+        ret = ad_open(adp, path->u_name, ADFLAGS_HF | ADFLAGS_RDWR);
         /* META and HF */
         if ( !ret && ad_reso_fileno(adp) != -1 && !(adp->ad_resource_fork.adf_flags & ( O_RDWR | O_WRONLY))) {
             /* from AFP spec.
@@ -2128,8 +1951,8 @@ int afp_exchangefiles(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U
     int                 crossdev;
     
     int                 slen, dlen;
-    u_int32_t          sid, did;
-    u_int16_t          vid;
+    uint32_t           sid, did;
+    uint16_t           vid;
 
     uid_t              uid;
     gid_t              gid;
@@ -2179,8 +2002,8 @@ int afp_exchangefiles(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U
         return AFPERR_PARAM ;
     }
     
-    ad_init(&ads, vol->v_adouble, vol->v_ad_options);
-    if (!(adsp = find_adouble( path, &s_of, &ads))) {
+    ad_init(&ads, vol);
+    if (!(adsp = find_adouble(obj, vol, path, &s_of, &ads))) {
         return afp_errno;
     }
 
@@ -2212,8 +2035,8 @@ int afp_exchangefiles(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U
         goto err_exchangefile;
     }
 
-    ad_init(&add, vol->v_adouble, vol->v_ad_options);
-    if (!(addp = find_adouble( path, &d_of, &add))) {
+    ad_init(&add, vol);
+    if (!(addp = find_adouble(obj, vol, path, &d_of, &add))) {
         err = afp_errno;
         goto err_exchangefile;
     }
index 077cd1203b214f98eebccb634fc8b83c82593dcc..aa9f3b4449a8ea386adf328e8b3f97d39cf759b6 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: file.h,v 1.26 2010/03/12 15:16:49 franklahm Exp $
- *
  * Copyright (c) 1990,1991 Regents of The University of Michigan.
  * All Rights Reserved.
  *
@@ -28,8 +26,7 @@
 
 /*#include <sys/stat.h>*/ /* including it here causes some confusion */
 #include <sys/param.h>
-#include <sys/cdefs.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 #include <atalk/adouble.h>
 #include <atalk/globals.h>
 
@@ -106,20 +103,19 @@ typedef enum {
   kTextEncodingMacKeyboardGlyphs = 41,
 } kTextEncoding_t;
 
-extern char *set_name   (const struct vol *, char *, cnid_t, char *, cnid_t, u_int32_t );
+extern char *set_name   (const struct vol *, char *, cnid_t, char *, cnid_t, uint32_t );
 
 extern struct extmap   *getextmap (const char *);
 extern struct extmap   *getdefextmap (void);
 
-extern int getfilparams (struct vol *, u_int16_t, struct path *,
-                                 struct dir *, char *buf, size_t *);
-
-extern int setfilparams (struct vol *, struct path *, u_int16_t, char *);
+extern int getfilparams (const AFPObj *obj, struct vol *, uint16_t, struct path *,
+                         struct dir *, char *buf, size_t *, int);
+extern int setfilparams (const AFPObj *obj, struct vol *, struct path *, uint16_t, char *);
 extern int renamefile   (const struct vol *, int, char *, char *, char *, struct adouble *);
 extern int copyfile     (const struct vol *, const struct vol *, int, char *, char *, char *, struct adouble *);
 extern int deletefile   (const struct vol *, int, char *, int);
 
-extern int getmetadata  (struct vol *vol, u_int16_t bitmap, struct path *path, 
+extern int getmetadata  (const AFPObj *obj, struct vol *vol, uint16_t bitmap, struct path *path, 
                          struct dir *dir, char *buf, size_t *buflen, struct adouble *adp);
 
 extern void *get_finderinfo (const struct vol *, const char *, struct adouble *, void *, int);
index 6fe3c855b2d32d007432a9623ffa2cb2f0b6f8f8..56cbaccffff2d32d59697fb6acad396589284bca 100644 (file)
@@ -9,24 +9,7 @@
 
 #include <stdio.h>
 #include <stdlib.h>
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#ifdef HAVE_STRINGS_H
-#include <strings.h>
-#endif
 #include <errno.h>
 #include <sys/param.h>
 
@@ -42,6 +25,7 @@ char *strchr (), *strrchr ();
 #include <atalk/acl.h>
 #include <atalk/globals.h>
 #include <atalk/fce_api.h>
+#include <atalk/netatalk_conf.h>
 
 #include "directory.h"
 #include "dircache.h"
@@ -52,96 +36,15 @@ char *strchr (), *strrchr ();
 #include "filedir.h"
 #include "unix.h"
 
-#ifdef DROPKLUDGE
-int matchfile2dirperms(
-/* Since it's kinda' big; I decided against an
-   inline function */
-    char    *upath,
-    struct vol  *vol,
-    int     did)
-/* The below code changes the way file ownership is determined in the name of
-   fixing dropboxes.  It has known security problem.  See the netatalk FAQ for
-   more information */
-{
-    struct stat st, sb;
-    struct dir  *dir;
-    char    *adpath;
-    uid_t       uid;
-    int         ret = AFP_OK;
-#ifdef DEBUG
-    LOG(log_debug9, logtype_afpd, "begin matchfile2dirperms:");
-#endif
-
-    if (stat(upath, &st ) < 0) {
-        LOG(log_error, logtype_afpd, "Could not stat %s: %s", upath, strerror(errno));
-        return AFPERR_NOOBJ ;
-    }
-
-    adpath = vol->vfs->ad_path( upath, ADFLAGS_HF );
-    /* FIXME dirsearch doesn't move cwd to did ! */
-    if (( dir = dirlookup( vol, did )) == NULL ) {
-        LOG(log_error, logtype_afpd, "matchfile2dirperms: Unable to get directory info.");
-        ret = AFPERR_NOOBJ;
-    }
-    else if (stat(".", &sb) < 0) {
-        LOG(log_error, logtype_afpd,
-            "matchfile2dirperms: Error checking directory \"%s\": %s",
-            dir->d_m_name, strerror(errno));
-        ret = AFPERR_NOOBJ;
-    }
-    else {
-        uid=geteuid();
-        if ( uid != sb.st_uid )
-        {
-            seteuid(0);
-            if (lchown(upath, sb.st_uid, sb.st_gid) < 0)
-            {
-                LOG(log_error, logtype_afpd,
-                    "matchfile2dirperms(%s): Error changing owner/gid: %s",
-                    upath, strerror(errno));
-                ret = AFPERR_ACCESS;
-            }
-            else if ((!S_ISLNK(st->st_mode)) && (chmod_acl(upath,(st.st_mode&~default_options.umask)| S_IRGRP| S_IROTH) < 0))
-            {
-                LOG(log_error, logtype_afpd,
-                    "matchfile2dirperms(%s): Error adding file read permissions: %s",
-                    upath, strerror(errno));
-                ret = AFPERR_ACCESS;
-            }
-            else if (lchown(adpath, sb.st_uid, sb.st_gid) < 0)
-            {
-                LOG(log_error, logtype_afpd,
-                    "matchfile2dirperms(%s): Error changing AppleDouble owner/gid: %s",
-                    adpath, strerror(errno));
-                ret = AFPERR_ACCESS;
-            }
-            else if (chmod_acl(adpath, (st.st_mode&~default_options.umask)| S_IRGRP| S_IROTH) < 0)
-            {
-                LOG(log_error, logtype_afpd,
-                    "matchfile2dirperms(%s):  Error adding AD file read permissions: %s",
-                    adpath, strerror(errno));
-                ret = AFPERR_ACCESS;
-            }
-            seteuid(uid);
-        }
-    } /* end else if stat success */
-
-#ifdef DEBUG
-    LOG(log_debug9, logtype_afpd, "end matchfile2dirperms:");
-#endif
-    return ret;
-}
-#endif
-
 int afp_getfildirparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
     struct stat     *st;
     struct vol      *vol;
     struct dir      *dir;
-    u_int32_t           did;
+    uint32_t           did;
     int         ret;
     size_t      buflen;
-    u_int16_t       fbitmap, dbitmap, vid;
+    uint16_t       fbitmap, dbitmap, vid;
     struct path         *s_path;
 
     *rbuflen = 0;
@@ -201,22 +104,22 @@ int afp_getfildirparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *r
             if (!dir)
                 return AFPERR_NOOBJ;
 
-            ret = getdirparams(vol, dbitmap, s_path, dir,
-                               rbuf + 3 * sizeof( u_int16_t ), &buflen );
+            ret = getdirparams(obj, vol, dbitmap, s_path, dir,
+                               rbuf + 3 * sizeof( uint16_t ), &buflen );
             if (ret != AFP_OK )
                 return( ret );
         }
         /* this is a directory */
-        *(rbuf + 2 * sizeof( u_int16_t )) = (char) FILDIRBIT_ISDIR;
+        *(rbuf + 2 * sizeof( uint16_t )) = (char) FILDIRBIT_ISDIR;
     } else {
-        if (fbitmap && AFP_OK != (ret = getfilparams(vol, fbitmap, s_path, curdir,
-                                                     rbuf + 3 * sizeof( u_int16_t ), &buflen )) ) {
+        if (fbitmap && AFP_OK != (ret = getfilparams(obj, vol, fbitmap, s_path, curdir,
+                                                     rbuf + 3 * sizeof( uint16_t ), &buflen, 0)) ) {
             return( ret );
         }
         /* this is a file */
-        *(rbuf + 2 * sizeof( u_int16_t )) = FILDIRBIT_ISFILE;
+        *(rbuf + 2 * sizeof( uint16_t )) = FILDIRBIT_ISFILE;
     }
-    *rbuflen = buflen + 3 * sizeof( u_int16_t );
+    *rbuflen = buflen + 3 * sizeof( uint16_t );
     fbitmap = htons( fbitmap );
     memcpy( rbuf, &fbitmap, sizeof( fbitmap ));
     rbuf += sizeof( fbitmap );
@@ -234,7 +137,7 @@ int afp_setfildirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf
     struct vol  *vol;
     struct dir  *dir;
     struct path *path;
-    u_int16_t   vid, bitmap;
+    uint16_t   vid, bitmap;
     int     did, rc;
 
     *rbuflen = 0;
@@ -286,7 +189,7 @@ int afp_setfildirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf
     if (S_ISDIR(st->st_mode)) {
         rc = setdirparams(vol, path, bitmap, ibuf );
     } else {
-        rc = setfilparams(vol, path, bitmap, ibuf );
+        rc = setfilparams(obj, vol, path, bitmap, ibuf );
     }
     if ( rc == AFP_OK ) {
         setvoltime(obj, vol );
@@ -300,13 +203,6 @@ int afp_setfildirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf
 */
 int check_name(const struct vol *vol, char *name)
 {
-    /* check for illegal characters in the unix filename */
-    if (!wincheck(vol, name))
-        return AFPERR_PARAM;
-
-    if ((vol->v_flags & AFPVOL_NOHEX) && strchr(name, '/'))
-        return AFPERR_PARAM;
-
     if (!vol->vfs->vfs_validupath(vol, name)) {
         LOG(log_error, logtype_afpd, "check_name: illegal name: '%s'", name);
         return AFPERR_EXIST;
@@ -345,12 +241,12 @@ static int moveandrename(const struct vol *vol,
         "moveandrename: [\"%s\"/\"%s\"] -> \"%s\"",
         cfrombstr(sdir->d_u_name), oldname, newname);
 
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
+    ad_init(&ad, vol);
     adp = &ad;
     adflags = 0;
 
     if (!isdir) {
-        if ((oldunixname = strdup(mtoupath(vol, oldname, sdir->d_did, utf8_encoding()))) == NULL)
+        if ((oldunixname = strdup(mtoupath(vol, oldname, sdir->d_did, utf8_encoding(vol->v_obj)))) == NULL)
             return AFPERR_PARAM; /* can't convert */
         id = cnid_get(vol->v_cdb, sdir->d_did, oldunixname, strlen(oldunixname));
 
@@ -399,10 +295,11 @@ static int moveandrename(const struct vol *vol,
         }
     }
     if (!ad_metadata(oldunixname, adflags, adp)) {
-        u_int16_t bshort;
+        uint16_t bshort;
 
         ad_getattr(adp, &bshort);
-        ad_close_metadata( adp);
+        
+        ad_close(adp, ADFLAGS_HF);
         if ((bshort & htons(ATTRBIT_NORENAME))) {
             rc = AFPERR_OLOCK;
             goto exit;
@@ -416,7 +313,7 @@ static int moveandrename(const struct vol *vol,
         }
     }
 
-    if (NULL == (upath = mtoupath(vol, newname, curdir->d_did, utf8_encoding()))){ 
+    if (NULL == (upath = mtoupath(vol, newname, curdir->d_did, utf8_encoding(vol->v_obj)))){ 
         rc = AFPERR_PARAM;
         goto exit;
     }
@@ -433,7 +330,7 @@ static int moveandrename(const struct vol *vol,
             goto exit;
         }
 
-        if (stat(upath, st) == 0 || caseenumerate(vol, &path, curdir) == 0) {
+        if (stat(upath, st) == 0) {
             if (!stat(oldunixname, &nst) && !(nst.st_dev == st->st_dev && nst.st_ino == st->st_ino) ) {
                 /* not the same file */
                 rc = AFPERR_EXIST;
@@ -441,7 +338,7 @@ static int moveandrename(const struct vol *vol,
             }
             errno = 0;
         }
-    } else if (stat(upath, st ) == 0 || caseenumerate(vol, &path, curdir) == 0) {
+    } else if (stat(upath, st ) == 0) {
         rc = AFPERR_EXIST;
         goto exit;
     }
@@ -477,7 +374,7 @@ static int moveandrename(const struct vol *vol,
         if (!ad_metadata(upath, adflags, adp)) {
             ad_setid(adp, st->st_dev, st->st_ino, id, curdir->d_did, vol->v_stamp);
             ad_flush(adp);
-            ad_close_metadata(adp);
+            ad_close(adp, ADFLAGS_HF);
         }
 
         /* fix up the catalog entry */
@@ -499,9 +396,9 @@ int afp_rename(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size
     struct dir  *sdir;
     char        *oldname, *newname;
     struct path *path;
-    u_int32_t   did;
+    uint32_t   did;
     int         plen;
-    u_int16_t   vid;
+    uint16_t   vid;
     int         isdir = 0;
     int         rc;
 
@@ -570,12 +467,13 @@ int afp_rename(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size
 /* ------------------------------- */
 int afp_delete(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
-    struct vol      *vol;
-    struct dir      *dir;
-    struct path         *s_path;
+    struct vol  *vol;
+    struct dir  *dir;
+    struct path *s_path;
     char        *upath;
-    int         did, rc;
-    u_int16_t       vid;
+    int         did;
+    int         rc = AFP_OK;
+    uint16_t    vid;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -601,9 +499,33 @@ int afp_delete(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size
     }
 
     upath = s_path->u_name;
-    if ( path_isadir( s_path) ) {
+    if (path_isadir(s_path)) {
         if (*s_path->m_name != '\0' || curdir->d_did == DIRDID_ROOT) {
-            rc = AFPERR_ACCESS;
+            if (vol->v_adouble == AD_VERSION2)
+                return AFPERR_ACCESS;
+            if (*s_path->m_name == '\0' && curdir->d_did == DIRDID_ROOT)
+                return AFPERR_ACCESS;
+            if (rmdir(upath) != 0) {
+                switch (errno) {
+                case ENOTEMPTY:
+                    return AFPERR_DIRNEMPT;
+                case EACCES:
+                    return AFPERR_ACCESS;
+                default:
+                    return AFPERR_MISC;
+                }
+            }
+            struct dir *deldir;
+            cnid_t delcnid = CNID_INVALID;
+            if ((deldir = dircache_search_by_name(vol, curdir, upath, strlen(upath)))) {
+                delcnid = deldir->d_did;
+                dir_remove(vol, deldir);
+            }
+            if (delcnid == CNID_INVALID)
+                delcnid = cnid_get(vol->v_cdb, curdir->d_did, upath, strlen(upath));
+            if (delcnid != CNID_INVALID)
+                cnid_delete(vol->v_cdb, delcnid);
+            fce_register_delete_dir(upath);
         } else {
             /* we have to cache this, the structs are lost in deletcurdir*/
             /* but we need the positive returncode to send our event */
@@ -675,7 +597,7 @@ char *ctoupath(const struct vol *vol, struct dir *dir, char *name)
 {
     if (vol == NULL || dir == NULL || name == NULL)
         return NULL;
-    return absupath(vol, dir, mtoupath(vol, name, dir->d_did, utf8_encoding()));
+    return absupath(vol, dir, mtoupath(vol, name, dir->d_did, utf8_encoding(vol->v_obj)));
 }
 
 /* ------------------------- */
@@ -689,11 +611,8 @@ int afp_moveandrename(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U
     int     did;
     int     pdid;
     int         plen;
-    u_int16_t   vid;
+    uint16_t   vid;
     int         rc;
-#ifdef DROPKLUDGE
-    int     retvalue;
-#endif /* DROPKLUDGE */
     int     sdir_fd = -1;
 
 
@@ -774,31 +693,19 @@ int afp_moveandrename(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U
     rc = moveandrename(vol, sdir, sdir_fd, oldname, newname, isdir);
 
     if ( rc == AFP_OK ) {
-        char *upath = mtoupath(vol, newname, pdid, utf8_encoding());
+        char *upath = mtoupath(vol, newname, pdid, utf8_encoding(obj));
 
         if (NULL == upath) {
             rc = AFPERR_PARAM;
             goto exit;
         }
-        curdir->d_offcnt++;
-        sdir->d_offcnt--;
-#ifdef DROPKLUDGE
-        if (vol->v_flags & AFPVOL_DROPBOX) {
-            /* FIXME did is not always the source id */
-            if ((retvalue=matchfile2dirperms (upath, vol, did)) != AFP_OK) {
-                rc = retvalue;
-                goto exit;
-            }
+        /* if unix priv don't try to match perm with dest folder */
+        if (!isdir && !vol_unix_priv(vol)) {
+            int  admode = ad_mode("", 0777) | vol->v_fperm;
+
+            setfilmode(upath, admode, NULL, vol->v_umask);
+            vol->vfs->vfs_setfilmode(vol, upath, admode, NULL);
         }
-        else
-#endif /* DROPKLUDGE */
-            /* if unix priv don't try to match perm with dest folder */
-            if (!isdir && !vol_unix_priv(vol)) {
-                int  admode = ad_mode("", 0777) | vol->v_fperm;
-
-                setfilmode(upath, admode, NULL, vol->v_umask);
-                vol->vfs->vfs_setfilmode(vol, upath, admode, NULL);
-            }
         setvoltime(obj, vol );
     }
 
index 5daf73f3c975bf0fb000f00a56d77c621b1a62a2..02c9ac15b5382ed99c5ee4cf7a84166d4e85cfda 100644 (file)
@@ -1,11 +1,6 @@
-/*
- * $Id: filedir.h,v 1.11 2009-10-15 10:43:13 didg Exp $
- */
-
 #ifndef AFPD_FILEDIR_H
 #define AFPD_FILEDIR_H 1
 
-#include <sys/cdefs.h>
 #include <sys/stat.h>
 #include <atalk/globals.h>
 #include "volume.h"
index 33aaf66d1c025b1be90da8170b05376a2f988d81..8f5a2e671740c36029424008ecda65b1c67d6e2b 100644 (file)
@@ -1,7 +1,7 @@
 /*
- * $Id: fork.c,v 1.73 2010-03-30 12:55:26 franklahm Exp $
- *
  * Copyright (c) 1990,1993 Regents of The University of Michigan.
+ * Copyright (c) 2010      Frank Lahm
+ *
  * All Rights Reserved.  See COPYRIGHT.
  */
 
 #endif /* HAVE_CONFIG_H */
 
 #include <stdio.h>
-
 #include <string.h>
 #include <errno.h>
-
-#include <atalk/adouble.h>
-#include <atalk/logger.h>
-
 #include <sys/param.h>
 #include <sys/socket.h>
-
-#include <netatalk/at.h>
+#include <inttypes.h>
 
 #include <atalk/dsi.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
 #include <atalk/afp.h>
+#include <atalk/adouble.h>
+#include <atalk/logger.h>
 #include <atalk/util.h>
 #include <atalk/cnid.h>
+#include <atalk/bstradd.h>
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
+#include <atalk/ea.h>
 
 #include "fork.h"
 #include "file.h"
 #include "desktop.h"
 #include "volume.h"
 
-#ifdef DEBUG1
-#define Debug(a) ((a)->options.flags & OPTION_DEBUG)
-#else
-#define Debug(a) (0)
-#endif
-
 #ifdef AFS
 struct ofork *writtenfork;
 #endif
 
-static int getforkparams(struct ofork *ofork, u_int16_t bitmap, char *buf, size_t *buflen)
+static int getforkparams(const AFPObj *obj, struct ofork *ofork, uint16_t bitmap, char *buf, size_t *buflen)
 {
     struct path         path;
-    struct stat                *st;
+    struct stat     *st;
+
+    struct adouble  *adp;
+    struct dir      *dir;
+    struct vol      *vol;
 
-    struct adouble     *adp;
-    struct dir         *dir;
-    struct vol         *vol;
-    
 
     /* can only get the length of the opened fork */
-    if ( ( (bitmap & ((1<<FILPBIT_DFLEN) | (1<<FILPBIT_EXTDFLEN))) 
-                  && (ofork->of_flags & AFPFORK_RSRC)) 
-        ||
-          ( (bitmap & ((1<<FILPBIT_RFLEN) | (1<<FILPBIT_EXTRFLEN))) 
-                  && (ofork->of_flags & AFPFORK_DATA))) {
+    if ( ( (bitmap & ((1<<FILPBIT_DFLEN) | (1<<FILPBIT_EXTDFLEN)))
+           && (ofork->of_flags & AFPFORK_RSRC))
+         ||
+         ( (bitmap & ((1<<FILPBIT_RFLEN) | (1<<FILPBIT_EXTRFLEN)))
+           && (ofork->of_flags & AFPFORK_DATA))) {
         return( AFPERR_BITMAP );
     }
 
-    if ( ad_reso_fileno( ofork->of_ad ) == -1 ) { /* META ? */
+    if (! AD_META_OPEN(ofork->of_ad)) {
         adp = NULL;
     } else {
         adp = ofork->of_ad;
@@ -74,14 +65,14 @@ static int getforkparams(struct ofork *ofork, u_int16_t bitmap, char *buf, size_
     vol = ofork->of_vol;
     dir = dirlookup(vol, ofork->of_did);
 
-    if (NULL == (path.u_name = mtoupath(vol, of_name(ofork), dir->d_did, utf8_encoding()))) {
+    if (NULL == (path.m_name = utompath(vol, of_name(ofork), dir->d_did, utf8_encoding(obj)))) {
         return( AFPERR_MISC );
     }
-    path.m_name = of_name(ofork);
+    path.u_name = of_name(ofork);
     path.id = 0;
     st = &path.st;
-    if ( bitmap & ( (1<<FILPBIT_DFLEN) | (1<<FILPBIT_EXTDFLEN) | 
-                    (1<<FILPBIT_FNUM) | (1 << FILPBIT_CDATE) | 
+    if ( bitmap & ( (1<<FILPBIT_DFLEN) | (1<<FILPBIT_EXTDFLEN) |
+                    (1<<FILPBIT_FNUM) | (1 << FILPBIT_CDATE) |
                     (1 << FILPBIT_MDATE) | (1 << FILPBIT_BDATE))) {
         if ( ad_data_fileno( ofork->of_ad ) <= 0 ) {
             /* 0 is for symlink */
@@ -95,13 +86,12 @@ static int getforkparams(struct ofork *ofork, u_int16_t bitmap, char *buf, size_
             }
         }
     }
-    return getmetadata(vol, bitmap, &path, dir, buf, buflen, adp );
+    return getmetadata(obj, vol, bitmap, &path, dir, buf, buflen, adp );
 }
 
-/* ---------------------------- */
 static off_t get_off_t(char **ibuf, int is64)
 {
-    u_int32_t             temp;
+    uint32_t             temp;
     off_t                 ret;
 
     ret = 0;
@@ -115,15 +105,14 @@ static off_t get_off_t(char **ibuf, int is64)
         ret = ntohl(temp)| (ret << 32);
     }
     else {
-       ret = (int)ret; /* sign extend */
+        ret = (int)ret; /* sign extend */
     }
     return ret;
 }
 
-/* ---------------------- */
 static int set_off_t(off_t offset, char *rbuf, int is64)
 {
-    u_int32_t  temp;
+    uint32_t  temp;
     int        ret;
 
     ret = 0;
@@ -141,39 +130,21 @@ static int set_off_t(off_t offset, char *rbuf, int is64)
     return ret;
 }
 
-/* ------------------------ 
-*/
 static int is_neg(int is64, off_t val)
 {
     if (val < 0 || (sizeof(off_t) == 8 && !is64 && (val & 0x80000000U)))
-       return 1;
+        return 1;
     return 0;
 }
 
-static int sum_neg(int is64, off_t offset, off_t reqcount) 
+static int sum_neg(int is64, off_t offset, off_t reqcount)
 {
-    if (is_neg(is64, offset +reqcount) ) 
-       return 1;
+    if (is_neg(is64, offset +reqcount) )
+        return 1;
     return 0;
 }
 
-/* -------------------------
-*/
-static int setforkmode(struct adouble *adp, int eid, int ofrefnum, off_t what)
-{
-    return ad_lock(adp, eid, ADLOCK_RD | ADLOCK_FILELOCK, what, 1, ofrefnum);
-}
-
-/* -------------------------
-*/
-int getforkmode(struct adouble *adp, int eid, off_t what)
-{
-    return ad_testlock(adp, eid,  what);
-}
-
-/* -------------------------
-*/
-static int fork_setmode(struct adouble *adp, int eid, int access, int ofrefnum)
+static int fork_setmode(const AFPObj *obj, struct adouble *adp, int eid, int access, int ofrefnum)
 {
     int ret;
     int readset;
@@ -181,14 +152,35 @@ static int fork_setmode(struct adouble *adp, int eid, int access, int ofrefnum)
     int denyreadset;
     int denywriteset;
 
+#ifdef HAVE_FSHARE_T
+    fshare_t shmd;
+
+    if (obj->options.flags & OPTION_SHARE_RESERV) {
+        shmd.f_access = (access & OPENACC_RD ? F_RDACC : 0) | (access & OPENACC_WR ? F_WRACC : 0);
+        if (shmd.f_access == 0)
+            /* we must give an access mode, otherwise fcntl will complain */
+            shmd.f_access = F_RDACC;
+        shmd.f_deny = (access & OPENACC_DRD ? F_RDDNY : F_NODNY) | (access & OPENACC_DWR) ? F_WRDNY : 0;
+        shmd.f_id = ofrefnum;
+
+        int fd = (eid == ADEID_DFORK) ? ad_data_fileno(adp) : ad_reso_fileno(adp);
+
+        if (fd != -1 && fd != AD_SYMLINK && fcntl(fd, F_SHARE, &shmd) != 0) {
+            LOG(log_debug, logtype_afpd, "fork_setmode: fcntl: %s", strerror(errno));
+            errno = EACCES;
+            return -1;
+        }
+    }
+#endif
+
     if (! (access & (OPENACC_WR | OPENACC_RD | OPENACC_DWR | OPENACC_DRD))) {
-        return setforkmode(adp, eid, ofrefnum, AD_FILELOCK_OPEN_NONE);
+        return ad_lock(adp, eid, ADLOCK_RD | ADLOCK_FILELOCK, AD_FILELOCK_OPEN_NONE, 1, ofrefnum);
     }
 
     if ((access & (OPENACC_RD | OPENACC_DRD))) {
-        if ((readset = getforkmode(adp, eid, AD_FILELOCK_OPEN_RD)) <0)
+        if ((readset = ad_testlock(adp, eid, AD_FILELOCK_OPEN_RD)) <0)
             return readset;
-        if ((denyreadset = getforkmode(adp, eid, AD_FILELOCK_DENY_RD)) <0)
+        if ((denyreadset = ad_testlock(adp, eid, AD_FILELOCK_DENY_RD)) <0)
             return denyreadset;
 
         if ((access & OPENACC_RD) && denyreadset) {
@@ -198,26 +190,26 @@ static int fork_setmode(struct adouble *adp, int eid, int access, int ofrefnum)
         if ((access & OPENACC_DRD) && readset) {
             errno = EACCES;
             return -1;
-        }   
+        }
         /* boolean logic is not enough, because getforkmode is not always telling the
-         * true 
+         * true
          */
         if ((access & OPENACC_RD)) {
-            ret = setforkmode(adp, eid, ofrefnum, AD_FILELOCK_OPEN_RD);
+            ret = ad_lock(adp, eid, ADLOCK_RD | ADLOCK_FILELOCK, AD_FILELOCK_OPEN_RD, 1, ofrefnum);
             if (ret)
                 return ret;
         }
         if ((access & OPENACC_DRD)) {
-            ret = setforkmode(adp, eid, ofrefnum, AD_FILELOCK_DENY_RD);
+            ret = ad_lock(adp, eid, ADLOCK_RD | ADLOCK_FILELOCK, AD_FILELOCK_DENY_RD, 1, ofrefnum);
             if (ret)
                 return ret;
         }
     }
     /* ------------same for writing -------------- */
     if ((access & (OPENACC_WR | OPENACC_DWR))) {
-        if ((writeset = getforkmode(adp, eid, AD_FILELOCK_OPEN_WR)) <0)
+        if ((writeset = ad_testlock(adp, eid, AD_FILELOCK_OPEN_WR)) <0)
             return writeset;
-        if ((denywriteset = getforkmode(adp, eid, AD_FILELOCK_DENY_WR)) <0)
+        if ((denywriteset = ad_testlock(adp, eid, AD_FILELOCK_DENY_WR)) <0)
             return denywriteset;
 
         if ((access & OPENACC_WR) && denywriteset) {
@@ -227,40 +219,39 @@ static int fork_setmode(struct adouble *adp, int eid, int access, int ofrefnum)
         if ((access & OPENACC_DWR) && writeset) {
             errno = EACCES;
             return -1;
-        }   
+        }
         if ((access & OPENACC_WR)) {
-            ret = setforkmode(adp, eid, ofrefnum, AD_FILELOCK_OPEN_WR);
+            ret = ad_lock(adp, eid, ADLOCK_RD | ADLOCK_FILELOCK, AD_FILELOCK_OPEN_WR, 1, ofrefnum);
             if (ret)
                 return ret;
         }
         if ((access & OPENACC_DWR)) {
-            ret = setforkmode(adp, eid, ofrefnum, AD_FILELOCK_DENY_WR);
+            ret = ad_lock(adp, eid, ADLOCK_RD | ADLOCK_FILELOCK, AD_FILELOCK_DENY_WR, 1, ofrefnum);
             if (ret)
                 return ret;
         }
     }
-    if ( access == (OPENACC_WR | OPENACC_RD | OPENACC_DWR | OPENACC_DRD)) {
-        return ad_excl_lock(adp, eid);
-    }
+
     return 0;
 }
 
 /* ----------------------- */
 int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
-    struct vol         *vol;
-    struct dir         *dir;
-    struct ofork       *ofork, *opened;
-    struct adouble      *adsame = NULL;
-    size_t             buflen;
-    int                        ret, adflags, eid;
-    u_int32_t           did;
-    u_int16_t          vid, bitmap, access, ofrefnum;
-    char               fork, *path, *upath;
-    struct stat         *st;
-    u_int16_t           bshort;
-    struct path         *s_path;
-    
+    struct vol      *vol;
+    struct dir      *dir;
+    struct ofork    *ofork, *opened;
+    struct adouble  *adsame = NULL;
+    size_t          buflen;
+    int             ret, adflags, eid;
+    uint32_t        did;
+    uint16_t        vid, bitmap, access, ofrefnum;
+    char            fork, *path, *upath;
+    struct stat     *st;
+    uint16_t        bshort;
+    struct path     *s_path;
+    struct stat xxx;
+
     ibuf++;
     fork = *ibuf++;
     memcpy(&vid, ibuf, sizeof( vid ));
@@ -275,7 +266,7 @@ int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, si
     ibuf += sizeof( int );
 
     if (NULL == ( dir = dirlookup( vol, did ))) {
-       return afp_errno;    
+        return afp_errno;
     }
 
     memcpy(&bitmap, ibuf, sizeof( bitmap ));
@@ -290,12 +281,12 @@ int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, si
     }
 
     if (NULL == ( s_path = cname( vol, dir, &ibuf ))) {
-       return get_afp_errno(AFPERR_PARAM);    
+        return get_afp_errno(AFPERR_PARAM);
     }
 
     if (*s_path->m_name == '\0') {
-       /* it's a dir ! */
-       return  AFPERR_BADTYPE;
+        /* it's a dir ! */
+        return  AFPERR_BADTYPE;
     }
 
     /* stat() data fork st is set because it's not a dir */
@@ -307,18 +298,17 @@ int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, si
     case EACCES:
         return (access & OPENACC_WR) ? AFPERR_LOCK : AFPERR_ACCESS;
     default:
-        LOG(log_error, logtype_afpd, "afp_openfork(%s): ad_open: %s", s_path->m_name, strerror(errno) );
+        LOG(log_error, logtype_afpd, "afp_openfork(%s): %s", s_path->m_name, strerror(errno));
         return AFPERR_PARAM;
     }
     /* FIXME should we check it first ? */
     upath = s_path->u_name;
     if (!vol_unix_priv(vol)) {
-        if (check_access(upath, access ) < 0) {
+        if (check_access(obj, vol, upath, access ) < 0) {
             return AFPERR_ACCESS;
         }
-    }
-    else {
-        if (file_access(s_path, access ) < 0) {
+    } else {
+        if (file_access(obj, vol, s_path, access ) < 0) {
             return AFPERR_ACCESS;
         }
     }
@@ -327,9 +317,9 @@ int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, si
     /* XXX: this probably isn't the best way to do this. the already
        open bits should really be set if the fork is opened by any
        program, not just this one. however, that's problematic to do
-       if we can't write lock files somewhere. opened is also passed to 
+       if we can't write lock files somewhere. opened is also passed to
        ad_open so that we can keep file locks together.
-       FIXME: add the fork we are opening? 
+       FIXME: add the fork we are opening?
     */
     if ((opened = of_findname(s_path))) {
         adsame = opened->of_ad;
@@ -337,10 +327,12 @@ int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, si
 
     if ( fork == OPENFORK_DATA ) {
         eid = ADEID_DFORK;
-        adflags = ADFLAGS_DF|ADFLAGS_HF;
+        adflags = ADFLAGS_DF | ADFLAGS_HF | ADFLAGS_NOHF;
     } else {
         eid = ADEID_RFORK;
-        adflags = ADFLAGS_HF;
+        adflags = ADFLAGS_RF | ADFLAGS_HF | ADFLAGS_NOHF;
+        if (!(access & OPENACC_WR))
+            adflags |= ADFLAGS_NORF;
     }
 
     path = s_path->m_name;
@@ -349,126 +341,123 @@ int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, si
         return( AFPERR_NFILE );
     }
 
+    LOG(log_debug, logtype_afpd, "afp_openfork(\"%s\", %s, %s)",
+        fullpathname(s_path->u_name),
+        (fork == OPENFORK_DATA) ? "data" : "reso",
+        !(access & OPENACC_WR) ? "O_RDONLY" : "O_RDWR");
+
     ret = AFPERR_NOOBJ;
     if (access & OPENACC_WR) {
         /* try opening in read-write mode */
-        if (ad_open(upath, adflags, O_RDWR, 0, ofork->of_ad) < 0) {
+        if (ad_open(ofork->of_ad, upath,
+                    adflags | ADFLAGS_RDWR | ADFLAGS_SETSHRMD) < 0) {
             switch ( errno ) {
             case EROFS:
                 ret = AFPERR_VLOCK;
             case EACCES:
                 goto openfork_err;
-                break;
             case ENOENT:
                 if (fork == OPENFORK_DATA) {
                     /* try to open only the data fork */
-                    if (ad_open(upath, ADFLAGS_DF, O_RDWR, 0, ofork->of_ad) < 0) {
+                    if (ad_open(ofork->of_ad, upath,
+                                ADFLAGS_DF | ADFLAGS_RDWR | ADFLAGS_SETSHRMD) < 0) {
                         goto openfork_err;
                     }
                     adflags = ADFLAGS_DF;
-                }
-                else {
+                } else {
                     /* here's the deal. we only try to create the resource
-                    * fork if the user wants to open it for write acess. */
-                    if (ad_open(upath, adflags, O_RDWR | O_CREAT, 0666, ofork->of_ad) < 0)
+                     * fork if the user wants to open it for write acess. */
+                    if (ad_open(ofork->of_ad, upath,
+                                adflags | ADFLAGS_RDWR | ADFLAGS_SETSHRMD | ADFLAGS_CREATE, 0666) < 0)
                         goto openfork_err;
-                    ofork->of_flags |= AFPFORK_OPEN;
+                    ofork->of_flags |= AFPFORK_META;
                 }
                 break;
             case EMFILE :
             case ENFILE :
                 ret = AFPERR_NFILE;
                 goto openfork_err;
-                break;
             case EISDIR :
                 ret = AFPERR_BADTYPE;
                 goto openfork_err;
-                break;
             default:
                 LOG(log_error, logtype_afpd, "afp_openfork(%s): ad_open: %s", s_path->m_name, strerror(errno) );
                 ret = AFPERR_PARAM;
                 goto openfork_err;
-                break;
             }
         }
         else {
             /* the ressource fork is open too */
-            ofork->of_flags |= AFPFORK_OPEN;
+            ofork->of_flags |= AFPFORK_META;
         }
     } else {
         /* try opening in read-only mode */
         ret = AFPERR_NOOBJ;
-        if (ad_open(upath, adflags, O_RDONLY, 0, ofork->of_ad) < 0) {
+        if (ad_open(ofork->of_ad, upath, adflags | ADFLAGS_RDONLY | ADFLAGS_SETSHRMD) < 0) {
             switch ( errno ) {
             case EROFS:
                 ret = AFPERR_VLOCK;
+                goto openfork_err;
             case EACCES:
                 goto openfork_err;
-                break;
             case ENOENT:
                 /* see if client asked for a read only data fork */
                 if (fork == OPENFORK_DATA) {
-                    if (ad_open(upath, ADFLAGS_DF, O_RDONLY, 0, ofork->of_ad) < 0) {
+                    if (ad_open(ofork->of_ad, upath, ADFLAGS_DF | ADFLAGS_RDONLY | ADFLAGS_SETSHRMD) < 0) {
                         goto openfork_err;
                     }
                     adflags = ADFLAGS_DF;
                 }
-                /* else we don't set AFPFORK_OPEN because there's no ressource fork file 
-                 * We need to check AFPFORK_OPEN in afp_closefork(). eg fork open read-only
+                /* else we don't set AFPFORK_META because there's no ressource fork file
+                 * We need to check AFPFORK_META in afp_closefork(). eg fork open read-only
                  * then create in open read-write.
                  * FIXME , it doesn't play well with byte locking example:
                  * ressource fork open read only
                  * locking set on it (no effect, there's no file!)
                  * ressource fork open read write now
-                */
+                 */
                 break;
             case EMFILE :
             case ENFILE :
                 ret = AFPERR_NFILE;
                 goto openfork_err;
-                break;
             case EISDIR :
                 ret = AFPERR_BADTYPE;
                 goto openfork_err;
-                break;
             default:
-                LOG(log_error, logtype_afpd, "afp_openfork('%s/%s'): ad_open: errno: %i (%s)",
-                    getcwdpath, s_path->m_name, errno, strerror(errno) );
+                LOG(log_error, logtype_afpd, "afp_openfork(\"%s\"): %s",
+                    fullpathname(s_path->m_name), strerror(errno) );
                 goto openfork_err;
-                break;
             }
-        }
-        else {
-            /* the ressource fork is open too */
-            ofork->of_flags |= AFPFORK_OPEN;
+        } else {
+            ofork->of_flags |= AFPFORK_META;
         }
     }
 
-    if ((adflags & ADFLAGS_HF) && (ad_get_HF_flags( ofork->of_ad) & O_CREAT)) {
+    if ((adflags & ADFLAGS_RF) && (ad_get_RF_flags( ofork->of_ad) & O_CREAT)) {
         if (ad_setname(ofork->of_ad, path)) {
             ad_flush( ofork->of_ad );
         }
     }
 
-    if (( ret = getforkparams(ofork, bitmap, rbuf + 2 * sizeof( u_int16_t ),
-                              &buflen )) != AFP_OK ) {
-        ad_close( ofork->of_ad, adflags );
+    if ((ret = getforkparams(obj, ofork, bitmap, rbuf + 2 * sizeof(int16_t), &buflen)) != AFP_OK) {
+        ad_close( ofork->of_ad, adflags | ADFLAGS_SETSHRMD);
         goto openfork_err;
     }
 
-    *rbuflen = buflen + 2 * sizeof( u_int16_t );
+    *rbuflen = buflen + 2 * sizeof( uint16_t );
     bitmap = htons( bitmap );
-    memcpy(rbuf, &bitmap, sizeof( u_int16_t ));
-    rbuf += sizeof( u_int16_t );
+    memcpy(rbuf, &bitmap, sizeof( uint16_t ));
+    rbuf += sizeof( uint16_t );
 
     /* check  WriteInhibit bit if we have a ressource fork
-     * the test is done here, after some Mac trafic capture 
+     * the test is done here, after some Mac trafic capture
      */
     if (ad_meta_fileno(ofork->of_ad) != -1) {   /* META */
         ad_getattr(ofork->of_ad, &bshort);
         if ((bshort & htons(ATTRBIT_NOWRITE)) && (access & OPENACC_WR)) {
-            ad_close( ofork->of_ad, adflags );
-            of_dealloc( ofork );
+            ad_close( ofork->of_ad, adflags | ADFLAGS_SETSHRMD);
+            of_dealloc(ofork);
             ofrefnum = 0;
             memcpy(rbuf, &ofrefnum, sizeof(ofrefnum));
             return(AFPERR_OLOCK);
@@ -480,14 +469,16 @@ int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, si
      */
 
     /* don't try to lock non-existent rforks. */
-    if ((eid == ADEID_DFORK) || (ad_meta_fileno(ofork->of_ad) != -1)) { /* META */
-
-        ret = fork_setmode(ofork->of_ad, eid, access, ofrefnum);
+    if ((eid == ADEID_DFORK)
+        || (ad_reso_fileno(ofork->of_ad) != -1)
+        || (ofork->of_ad->ad_vers == AD_VERSION_EA)) {
+        ret = fork_setmode(obj, ofork->of_ad, eid, access, ofrefnum);
         /* can we access the fork? */
         if (ret < 0) {
+            ofork->of_flags |= AFPFORK_ERROR;
             ret = errno;
-            ad_close( ofork->of_ad, adflags );
-            of_dealloc( ofork );
+            ad_close( ofork->of_ad, adflags | ADFLAGS_SETSHRMD);
+            of_dealloc(ofork);
             switch (ret) {
             case EAGAIN: /* return data anyway */
             case EACCES:
@@ -513,22 +504,22 @@ int afp_openfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, si
     return( AFP_OK );
 
 openfork_err:
-    of_dealloc( ofork );
+    of_dealloc(ofork);
     if (errno == EACCES)
         return (access & OPENACC_WR) ? AFPERR_LOCK : AFPERR_ACCESS;
     return ret;
 }
 
-int afp_setforkparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen, char *rbuf _U_, size_t *rbuflen)
+int afp_setforkparams(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf _U_, size_t *rbuflen)
 {
-    struct ofork       *ofork;
-    off_t              size;
-    u_int16_t          ofrefnum, bitmap;
+    struct ofork    *ofork;
+    off_t       size;
+    uint16_t       ofrefnum, bitmap;
     int                 err;
     int                 is64;
     int                 eid;
-    off_t              st_size;
-    
+    off_t       st_size;
+
     ibuf += 2;
 
     memcpy(&ofrefnum, ibuf, sizeof( ofrefnum ));
@@ -557,26 +548,26 @@ int afp_setforkparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen, char *rbuf _U
     } else
         return AFPERR_PARAM;
 
-    if ( ( (bitmap & ( (1<<FILPBIT_DFLEN) | (1<<FILPBIT_EXTDFLEN) )) 
-                  && eid == ADEID_RFORK 
-         ) ||
-         ( (bitmap & ( (1<<FILPBIT_RFLEN) | (1<<FILPBIT_EXTRFLEN) )) 
-                  && eid == ADEID_DFORK)) {
+    if ( ( (bitmap & ( (1<<FILPBIT_DFLEN) | (1<<FILPBIT_EXTDFLEN) ))
+           && eid == ADEID_RFORK
+             ) ||
+         ( (bitmap & ( (1<<FILPBIT_RFLEN) | (1<<FILPBIT_EXTRFLEN) ))
+           && eid == ADEID_DFORK)) {
         return AFPERR_BITMAP;
     }
-    
+
     is64 = 0;
     if ((bitmap & ( (1<<FILPBIT_EXTDFLEN) | (1<<FILPBIT_EXTRFLEN) ))) {
-        if (afp_version >= 30) {
+        if (obj->afp_version >= 30) {
             is64 = 4;
         }
-        else 
-           return AFPERR_BITMAP;
+        else
+            return AFPERR_BITMAP;
     }
 
     if (ibuflen < 2+ sizeof(ofrefnum) + sizeof(bitmap) + is64 +4)
         return AFPERR_PARAM ;
-    
+
     size = get_off_t(&ibuf, is64);
 
     if (size < 0)
@@ -584,29 +575,30 @@ int afp_setforkparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen, char *rbuf _U
 
 
     if (bitmap == (1<<FILPBIT_DFLEN) || bitmap == (1<<FILPBIT_EXTDFLEN)) {
-       st_size = ad_size(ofork->of_ad, eid);
-       err = -2;
-       if (st_size > size && 
-             ad_tmplock(ofork->of_ad, eid, ADLOCK_WR, size, st_size -size, ofork->of_refnum) < 0) 
+        st_size = ad_size(ofork->of_ad, eid);
+        err = -2;
+        if (st_size > size &&
+            ad_tmplock(ofork->of_ad, eid, ADLOCK_WR, size, st_size -size, ofork->of_refnum) < 0)
             goto afp_setfork_err;
 
         err = ad_dtruncate( ofork->of_ad, size );
         if (st_size > size)
-           ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, size, st_size -size, ofork->of_refnum);  
+            ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, size, st_size -size, ofork->of_refnum);
         if (err < 0)
             goto afp_setfork_err;
     } else if (bitmap == (1<<FILPBIT_RFLEN) || bitmap == (1<<FILPBIT_EXTRFLEN)) {
-        ad_refresh( ofork->of_ad );
+        ad_refresh(NULL, ofork->of_ad );
 
-       st_size = ad_size(ofork->of_ad, eid);
-       err = -2;
-       if (st_size > size && 
-              ad_tmplock(ofork->of_ad, eid, ADLOCK_WR, size, st_size -size, ofork->of_refnum) < 0) {
+        st_size = ad_size(ofork->of_ad, eid);
+        err = -2;
+        if (st_size > size &&
+            ad_tmplock(ofork->of_ad, eid, ADLOCK_WR, size, st_size -size, ofork->of_refnum) < 0) {
             goto afp_setfork_err;
-       }
+        }
+
         err = ad_rtruncate(ofork->of_ad, size);
         if (st_size > size)
-           ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, size, st_size -size, ofork->of_refnum);  
+            ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, size, st_size -size, ofork->of_refnum);
         if (err < 0)
             goto afp_setfork_err;
 
@@ -650,7 +642,7 @@ afp_setfork_err:
  * read and write. that's most easily handled by always doing an
  * appropriate check before each ad_read/ad_write. other things
  * that can change files like truncate are handled internally to those
- * functions. 
+ * functions.
  */
 #define ENDBIT(a)  ((a) & 0x80)
 #define UNLOCKBIT(a) ((a) & 0x01)
@@ -659,13 +651,13 @@ afp_setfork_err:
 /* ---------------------- */
 static int byte_lock(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen, int is64)
 {
-    struct ofork       *ofork;
+    struct ofork    *ofork;
     off_t               offset, length;
     int                 eid;
-    u_int16_t          ofrefnum;
-    u_int8_t            flags;
+    uint16_t       ofrefnum;
+    uint8_t            flags;
     int                 lockop;
-    
+
     *rbuflen = 0;
 
     /* figure out parameters */
@@ -676,7 +668,7 @@ static int byte_lock(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf
     ibuf += sizeof(ofrefnum);
 
     if (NULL == ( ofork = of_find( ofrefnum )) ) {
-        LOG(log_error, logtype_afpd, "afp_bytelock: of_find(%d) could not locate fork", ofrefnum );
+        LOG(log_error, logtype_afpd, "byte_lock: of_find(%d) could not locate fork", ofrefnum );
         return( AFPERR_PARAM );
     }
 
@@ -690,18 +682,17 @@ static int byte_lock(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf
     offset = get_off_t(&ibuf, is64);
     length = get_off_t(&ibuf, is64);
 
-    /* FIXME AD_FILELOCK test is surely wrong */
     if (length == -1)
         length = BYTELOCK_MAX;
-     else if (!length || is_neg(is64, length)) {
-       return AFPERR_PARAM;
-     } else if ((length >= AD_FILELOCK_BASE) && -1 == (ad_reso_fileno(ofork->of_ad))) { /* HF ?*/
+    else if (!length || is_neg(is64, length)) {
+        return AFPERR_PARAM;
+    } else if ((length >= AD_FILELOCK_BASE) && -1 == (ad_reso_fileno(ofork->of_ad))) { /* HF ?*/
         return AFPERR_LOCK;
     }
 
     if (ENDBIT(flags)) {
         offset += ad_size(ofork->of_ad, eid);
-        /* FIXME what do we do if file size > 2 GB and 
+        /* FIXME what do we do if file size > 2 GB and
            it's not byte_lock_ext?
         */
     }
@@ -738,41 +729,29 @@ static int byte_lock(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf
 /* --------------------------- */
 int afp_bytelock(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
 {
-   return byte_lock ( obj, ibuf, ibuflen, rbuf, rbuflen , 0);
+    return byte_lock ( obj, ibuf, ibuflen, rbuf, rbuflen , 0);
 }
 
 /* --------------------------- */
 int afp_bytelock_ext(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
 {
-   return byte_lock ( obj, ibuf, ibuflen, rbuf, rbuflen , 1);
+    return byte_lock ( obj, ibuf, ibuflen, rbuf, rbuflen , 1);
 }
 
 #undef UNLOCKBIT
 
-/* --------------------------- */
-static int crlf(struct ofork *of)
-{
-    struct extmap      *em;
-
-    if ( ad_meta_fileno( of->of_ad ) == -1 || !memcmp( ufinderi, ad_entry( of->of_ad, ADEID_FINDERI),8)) { /* META */
-        /* no resource fork or no finderinfo, use our files extension mapping */
-        if (!( em = getextmap( of_name(of) )) || memcmp( "TEXT", em->em_type, sizeof( em->em_type ))) {
-            return 0;
-        } 
-        /* file type is TEXT */
-        return 1;
-
-    } else if ( !memcmp( "TEXT", ad_entry( of->of_ad, ADEID_FINDERI ), 4 )) {
-        return 1;
-    }
-    return 0;
-}
-
-
-static ssize_t read_file(struct ofork *ofork, int eid,
-                                    off_t offset, u_char nlmask,
-                                    u_char nlchar, char *rbuf,
-                                    size_t *rbuflen, const int xlate)
+/*!
+ * Read *rbuflen bytes from fork at offset
+ *
+ * @param ofork    (r)  fork handle
+ * @param eid      (r)  data fork or ressource fork entry id
+ * @param offset   (r)  offset
+ * @param rbuf     (r)  data buffer
+ * @param rbuflen  (rw) in: number of bytes to read, out: bytes read
+ *
+ * @return         AFP status code
+ */
+static int read_file(const struct ofork *ofork, int eid, off_t offset, char *rbuf, size_t *rbuflen)
 {
     ssize_t cc;
     int eof = 0;
@@ -784,67 +763,23 @@ static ssize_t read_file(struct ofork *ofork, int eid,
         *rbuflen = 0;
         return( AFPERR_PARAM );
     }
-    if ( (size_t)cc < *rbuflen ) {
-        eof = 1;
-    }
-
-    /*
-     * Do Newline check.
-     */
-    if ( nlmask != 0 ) {
-        for ( p = rbuf, q = p + cc; p < q; ) {
-            if (( *p++ & nlmask ) == nlchar ) {
-                break;
-            }
-        }
-        if ( p != q ) {
-            cc = p - rbuf;
-            eof = 0;
-        }
-    }
-
-    /*
-     * If this file is of type TEXT, then swap \012 to \015.
-     */
-    if (xlate) {
-        for ( p = rbuf, q = p + cc; p < q; p++ ) {
-            if ( *p == '\012' ) {
-                *p = '\015';
-            } else if ( *p == '\015' ) {
-                *p = '\012';
-            }
-
-        }
-    }
-
     *rbuflen = cc;
-    if ( eof ) {
-        return( AFPERR_EOF );
-    }
+
+    if ((size_t)cc < *rbuflen)
+        return AFPERR_EOF;
     return AFP_OK;
 }
 
-/* -----------------------------
- * with ddp, afp_read can return fewer bytes than in reqcount 
- * so return EOF only if read actually past end of file not
- * if offset +reqcount > size of file
- * e.g.:
- * getfork size ==> 10430
- * read fork offset 0 size 10752 ????  ==> 4264 bytes (without EOF)
- * read fork offset 4264 size 6128 ==> 4264 (without EOF)
- * read fork offset 9248 size 1508 ==> 1182 (EOF)
- * 10752 is a bug in Mac 7.5.x finder 
- *
- * with dsi, should we check that reqcount < server quantum? 
-*/
 static int read_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen, int is64)
 {
-    struct ofork       *ofork;
-    off_t              offset, saveoff, reqcount, savereqcount;
-    ssize_t            cc, err;
-    int                        eid, xlate = 0;
-    u_int16_t          ofrefnum;
-    u_char             nlmask, nlchar;
+    DSI          *dsi = obj->dsi;
+    struct ofork *ofork;
+    off_t        offset, saveoff, reqcount, savereqcount, size;
+    ssize_t      cc, err;
+    int          eid;
+    uint16_t     ofrefnum;
+
+    /* we break the AFP spec here by not supporting nlmask and nlchar anymore */
 
     ibuf += 2;
     memcpy(&ofrefnum, ibuf, sizeof( ofrefnum ));
@@ -860,27 +795,9 @@ static int read_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, si
         err = AFPERR_ACCESS;
         goto afp_read_err;
     }
-    offset   = get_off_t(&ibuf, is64);
-    reqcount = get_off_t(&ibuf, is64);
-
-    if (is64) {
-        nlmask = nlchar = 0;
-    }
-    else {
-        nlmask = *ibuf++;
-        nlchar = *ibuf++;
-    }
-    /* if we wanted to be picky, we could add in the following
-     * bit: if (afp_version == 11 && !(nlmask == 0xFF || !nlmask))
-     */
-    if (reqcount < 0 || offset < 0) {
-        err = AFPERR_PARAM;
-        goto afp_read_err;
-    }
 
     if ( ofork->of_flags & AFPFORK_DATA) {
         eid = ADEID_DFORK;
-        xlate = (ofork->of_vol->v_flags & AFPVOL_CRLF) ? crlf(ofork) : 0;
     } else if (ofork->of_flags & AFPFORK_RSRC) {
         eid = ADEID_RFORK;
     } else { /* fork wasn't opened. this should never really happen. */
@@ -888,104 +805,114 @@ static int read_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, si
         goto afp_read_err;
     }
 
+    offset   = get_off_t(&ibuf, is64);
+    reqcount = get_off_t(&ibuf, is64);
+
     /* zero request count */
     err = AFP_OK;
     if (!reqcount) {
         goto afp_read_err;
     }
 
-    LOG(log_debug, logtype_afpd, "afp_read(name: \"%s\", offset: %jd, reqcount: %jd)",
-        of_name(ofork), (intmax_t)offset, (intmax_t)reqcount);
+    /* reqcount isn't always truthful. we need to deal with that. */
+    size = ad_size(ofork->of_ad, eid);
+
+    LOG(log_debug, logtype_afpd,
+        "afp_read(off: %" PRIu64 ", len: %" PRIu64 ", fork: %s, size: %" PRIu64 ")",
+        offset, reqcount, (ofork->of_flags & AFPFORK_DATA) ? "d" : "r", size);
+
+    if (offset > size) {
+        err = AFPERR_EOF;
+        goto afp_read_err;
+    }
+
+    /* subtract off the offset */
+    if (reqcount + offset > size) {
+        reqcount = size - offset;
+        err = AFPERR_EOF;
+    }
 
     savereqcount = reqcount;
     saveoff = offset;
-    if (ad_tmplock(ofork->of_ad, eid, ADLOCK_RD, saveoff, savereqcount,ofork->of_refnum) < 0) {
-        err = AFPERR_LOCK;
+
+    LOG(log_debug, logtype_afpd,
+        "afp_read(off: %" PRIu64 ", len: %" PRIu64 ", fork: %s)",
+        offset, reqcount, (ofork->of_flags & AFPFORK_DATA) ? "d" : "r");
+
+    if (reqcount < 0 || offset < 0) {
+        err = AFPERR_PARAM;
         goto afp_read_err;
     }
 
+    LOG(log_debug, logtype_afpd, "afp_read(name: \"%s\", offset: %jd, reqcount: %jd)",
+        of_name(ofork), (intmax_t)offset, (intmax_t)reqcount);
+
+    if (obj->options.flags & OPTION_AFP_READ_LOCK) {
+        if (ad_tmplock(ofork->of_ad, eid, ADLOCK_RD, offset, reqcount, ofork->of_refnum) < 0) {
+            err = AFPERR_LOCK;
+            goto afp_read_err;
+        }
+    }
+
+#ifdef WITH_SENDFILE
+    if (!(eid == ADEID_DFORK && ad_data_fileno(ofork->of_ad) == AD_SYMLINK) &&
+        !(obj->options.flags & OPTION_NOSENDFILE)) {
+        int fd = ad_readfile_init(ofork->of_ad, eid, &offset, 0);
+        if (dsi_stream_read_file(dsi, fd, offset, reqcount, err) < 0) {
+            LOG(log_error, logtype_afpd, "afp_read(%s): ad_readfile: %s",
+                of_name(ofork), strerror(errno));
+            goto afp_read_exit;
+        }
+        goto afp_read_done;
+    }
+#endif
+
     *rbuflen = MIN(reqcount, *rbuflen);
-    LOG(log_debug, logtype_afpd, "afp_read(name: \"%s\", offset: %jd, reqcount: %jd): reading %jd bytes from file",
-        of_name(ofork), (intmax_t)offset, (intmax_t)reqcount, (intmax_t)*rbuflen);
-    err = read_file(ofork, eid, offset, nlmask, nlchar, rbuf, rbuflen, xlate);
+
+    err = read_file(ofork, eid, offset, rbuf, rbuflen);
     if (err < 0)
         goto afp_read_done;
-    LOG(log_debug, logtype_afpd, "afp_read(name: \"%s\", offset: %jd, reqcount: %jd): got %jd bytes from file",
+
+    LOG(log_debug, logtype_afpd,
+        "afp_read(name: \"%s\", offset: %jd, reqcount: %jd): got %jd bytes from file",
         of_name(ofork), (intmax_t)offset, (intmax_t)reqcount, (intmax_t)*rbuflen);
 
-    /* dsi can stream requests. we can only do this if we're not checking
-     * for an end-of-line character. oh well. */
-    if ((obj->proto == AFPPROTO_DSI) && (*rbuflen < reqcount) && !nlmask) {
-        DSI    *dsi = obj->handle;
-        off_t  size;
+    offset += *rbuflen;
 
-        /* reqcount isn't always truthful. we need to deal with that. */
-        size = ad_size(ofork->of_ad, eid);
+    /*
+     * dsi_readinit() returns size of next read buffer. by this point,
+     * we know that we're sending some data. if we fail, something
+     * horrible happened.
+     */
+    if ((cc = dsi_readinit(dsi, rbuf, *rbuflen, reqcount, err)) < 0)
+        goto afp_read_exit;
+    *rbuflen = cc;
 
-        /* subtract off the offset */
-        size -= offset;
-        if (reqcount > size) {
-          reqcount = size;
-           err = AFPERR_EOF;
-        }
+    while (*rbuflen > 0) {
+        cc = read_file(ofork, eid, offset, rbuf, rbuflen);
+        if (cc < 0)
+            goto afp_read_exit;
 
         offset += *rbuflen;
-
-        /* dsi_readinit() returns size of next read buffer. by this point,
-         * we know that we're sending some data. if we fail, something
-         * horrible happened. */
-        if ((cc = dsi_readinit(dsi, rbuf, *rbuflen, reqcount, err)) < 0)
+        /* dsi_read() also returns buffer size of next allocation */
+        cc = dsi_read(dsi, rbuf, *rbuflen); /* send it off */
+        if (cc < 0)
             goto afp_read_exit;
         *rbuflen = cc;
-        /* due to the nature of afp packets, we have to exit if we get
-           an error. we can't do this with translation on. */
-#ifdef WITH_SENDFILE 
-        if (!(xlate || Debug(obj) )) {
-            int fd;
-                        
-            fd = ad_readfile_init(ofork->of_ad, eid, &offset, 0);
-
-            if (dsi_stream_read_file(dsi, fd, offset, dsi->datasize) < 0) {
-                if (errno == EINVAL || errno == ENOSYS)
-                    goto afp_read_loop;
-                else {
-                    LOG(log_error, logtype_afpd, "afp_read(%s): ad_readfile: %s", of_name(ofork), strerror(errno));
-                    goto afp_read_exit;
-                }
-            }
-
-            dsi_readdone(dsi);
-            goto afp_read_done;
-        }
-
-afp_read_loop:
-#endif 
-
-        /* fill up our buffer. */
-        while (*rbuflen > 0) {
-            cc = read_file(ofork, eid, offset, nlmask, nlchar, rbuf,rbuflen, xlate);
-            if (cc < 0)
-                goto afp_read_exit;
-
-            offset += *rbuflen;
-            /* dsi_read() also returns buffer size of next allocation */
-            cc = dsi_read(dsi, rbuf, *rbuflen); /* send it off */
-            if (cc < 0)
-                goto afp_read_exit;
-            *rbuflen = cc;
-        }
-        dsi_readdone(dsi);
-        goto afp_read_done;
+    }
+    dsi_readdone(dsi);
+    goto afp_read_done;
 
 afp_read_exit:
-        LOG(log_error, logtype_afpd, "afp_read(%s): %s", of_name(ofork), strerror(errno));
-        dsi_readdone(dsi);
-        ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, savereqcount,ofork->of_refnum);
-        obj->exit(EXITERR_CLNT);
-    }
+    LOG(log_error, logtype_afpd, "afp_read(%s): %s", of_name(ofork), strerror(errno));
+    dsi_readdone(dsi);
+   if (obj->options.flags & OPTION_AFP_READ_LOCK)
+       ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, savereqcount, ofork->of_refnum);
+    obj->exit(EXITERR_CLNT);
 
 afp_read_done:
-    ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, savereqcount,ofork->of_refnum);
+    if (obj->options.flags & OPTION_AFP_READ_LOCK)
+        ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, savereqcount, ofork->of_refnum);
     return err;
 
 afp_read_err:
@@ -1009,7 +936,7 @@ int afp_read_ext(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rb
 int afp_flush(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
     struct vol *vol;
-    u_int16_t vid;
+    uint16_t vid;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -1023,10 +950,10 @@ int afp_flush(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, s
     return( AFP_OK );
 }
 
-int afp_flushfork(AFPObj *obj _U_, char        *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
+int afp_flushfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
-    struct ofork       *ofork;
-    u_int16_t          ofrefnum;
+    struct ofork    *ofork;
+    uint16_t       ofrefnum;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -1037,6 +964,9 @@ int afp_flushfork(AFPObj *obj _U_, char    *ibuf, size_t ibuflen _U_, char *rbuf _U
         return( AFPERR_PARAM );
     }
 
+    LOG(log_debug, logtype_afpd, "afp_flushfork(fork: %s)",
+        (ofork->of_flags & AFPFORK_DATA) ? "d" : "r");
+
     if ( flushfork( ofork ) < 0 ) {
         LOG(log_error, logtype_afpd, "afp_flushfork(%s): %s", of_name(ofork), strerror(errno) );
     }
@@ -1049,11 +979,11 @@ int afp_flushfork(AFPObj *obj _U_, char  *ibuf, size_t ibuflen _U_, char *rbuf _U
   There is a lot to tell about fsync, fdatasync, F_FULLFSYNC.
   fsync(2) on OSX is implemented differently than on other platforms.
   see: http://mirror.linux.org.au/pub/linux.conf.au/2007/video/talks/278.pdf.
- */
+*/
 int afp_syncfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
     struct ofork        *ofork;
-    u_int16_t           ofrefnum;
+    uint16_t           ofrefnum;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -1066,9 +996,12 @@ int afp_syncfork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_
         return( AFPERR_PARAM );
     }
 
+    LOG(log_debug, logtype_afpd, "afp_syncfork(fork: %s)",
+        (ofork->of_flags & AFPFORK_DATA) ? "d" : "r");
+
     if ( flushfork( ofork ) < 0 ) {
-       LOG(log_error, logtype_afpd, "flushfork(%s): %s", of_name(ofork), strerror(errno) );
-       return AFPERR_MISC;
+        LOG(log_error, logtype_afpd, "flushfork(%s): %s", of_name(ofork), strerror(errno) );
+        return AFPERR_MISC;
     }
 
     return( AFP_OK );
@@ -1082,17 +1015,17 @@ int flushfork(struct ofork *ofork)
     int err = 0, doflush = 0;
 
     if ( ad_data_fileno( ofork->of_ad ) != -1 &&
-            fsync( ad_data_fileno( ofork->of_ad )) < 0 ) {
+         fsync( ad_data_fileno( ofork->of_ad )) < 0 ) {
         LOG(log_error, logtype_afpd, "flushfork(%s): dfile(%d) %s",
             of_name(ofork), ad_data_fileno(ofork->of_ad), strerror(errno) );
         err = -1;
     }
 
     if ( ad_reso_fileno( ofork->of_ad ) != -1 &&  /* HF */
-        (ofork->of_flags & AFPFORK_RSRC)) {
+         (ofork->of_flags & AFPFORK_RSRC)) {
 
         /* read in the rfork length */
-        ad_refresh(ofork->of_ad);
+        ad_refresh(NULL, ofork->of_ad);
 
         /* set the date if we're dirty */
         if ((ofork->of_flags & AFPFORK_DIRTY) && !gettimeofday(&tv, NULL)) {
@@ -1103,7 +1036,7 @@ int flushfork(struct ofork *ofork)
 
         /* flush the header */
         if (doflush && ad_flush(ofork->of_ad) < 0)
-                err = -1;
+            err = -1;
 
         if (fsync( ad_reso_fileno( ofork->of_ad )) < 0)
             err = -1;
@@ -1116,10 +1049,10 @@ int flushfork(struct ofork *ofork)
     return( err );
 }
 
-int afp_closefork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
+int afp_closefork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
-    struct ofork       *ofork;
-    u_int16_t          ofrefnum;
+    struct ofork    *ofork;
+    uint16_t       ofrefnum;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -1129,7 +1062,11 @@ int afp_closefork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U
         LOG(log_error, logtype_afpd, "afp_closefork: of_find(%d) could not locate fork", ofrefnum );
         return( AFPERR_PARAM );
     }
-    if ( of_closefork( ofork ) < 0 ) {
+
+    LOG(log_debug, logtype_afpd, "afp_closefork(fork: %s)",
+        (ofork->of_flags & AFPFORK_DATA) ? "d" : "r");
+
+    if (of_closefork(obj, ofork) < 0 ) {
         LOG(log_error, logtype_afpd, "afp_closefork(%s): of_closefork: %s", of_name(ofork), strerror(errno) );
         return( AFPERR_PARAM );
     }
@@ -1139,24 +1076,14 @@ int afp_closefork(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U
 
 
 static ssize_t write_file(struct ofork *ofork, int eid,
-                                     off_t offset, char *rbuf,
-                                     size_t rbuflen, const int xlate)
+                          off_t offset, char *rbuf,
+                          size_t rbuflen)
 {
     char *p, *q;
     ssize_t cc;
 
-    /*
-     * If this file is of type TEXT, swap \015 to \012.
-     */
-    if (xlate) {
-        for ( p = rbuf, q = p + rbuflen; p < q; p++ ) {
-            if ( *p == '\015' ) {
-                *p = '\012';
-            } else if ( *p == '\012' ) {
-                *p = '\015';
-            }
-        }
-    }
+    LOG(log_debug, logtype_afpd, "write_file(off: %ju, size: %zu)",
+        (uintmax_t)offset, rbuflen);
 
     if (( cc = ad_write(ofork->of_ad, eid, offset, 0,
                         rbuf, rbuflen)) < 0 ) {
@@ -1178,16 +1105,21 @@ static ssize_t write_file(struct ofork *ofork, int eid,
 }
 
 
-/* FPWrite. NOTE: on an error, we always use afp_write_err as
- * the client may have sent us a bunch of data that's not reflected 
- * in reqcount et al. */
+/*
+ * FPWrite. NOTE: on an error, we always use afp_write_err as
+ * the client may have sent us a bunch of data that's not reflected
+ * in reqcount et al.
+ */
 static int write_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen, int is64)
 {
-    struct ofork       *ofork;
+    struct ofork    *ofork;
     off_t           offset, saveoff, reqcount, oldsize, newsize;
-    int                        endflag, eid, xlate = 0, err = AFP_OK;
-    u_int16_t          ofrefnum;
-    ssize_t             cc;
+    int             endflag, eid, err = AFP_OK;
+    uint16_t        ofrefnum;
+    ssize_t         cc;
+    DSI             *dsi = obj->dsi;
+    char            *rcvbuf = dsi->buffer;
+    size_t          rcvbuflen = dsi->dsireadbuf * dsi->server_quantum;
 
     /* figure out parameters */
     ibuf++;
@@ -1205,6 +1137,9 @@ static int write_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, s
         goto afp_write_err;
     }
 
+    LOG(log_debug, logtype_afpd, "afp_write(off: %" PRIu64 ", size: %" PRIu64 ", fork: %s)",
+        offset, reqcount, (ofork->of_flags & AFPFORK_DATA) ? "d" : "r");
+
     if ((ofork->of_flags & AFPFORK_ACCWR) == 0) {
         err = AFPERR_ACCESS;
         goto afp_write_err;
@@ -1216,7 +1151,6 @@ static int write_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, s
 
     if ( ofork->of_flags & AFPFORK_DATA) {
         eid = ADEID_DFORK;
-        xlate = (ofork->of_vol->v_flags & AFPVOL_CRLF) ? crlf(ofork) : 0;
     } else if (ofork->of_flags & AFPFORK_RSRC) {
         eid = ADEID_RFORK;
     } else {
@@ -1238,7 +1172,7 @@ static int write_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, s
 
     /* offset can overflow on 64-bit capable filesystems.
      * report disk full if that's going to happen. */
-     if (sum_neg(is64, offset, reqcount)) {
+    if (sum_neg(is64, offset, reqcount)) {
         LOG(log_error, logtype_afpd, "write_fork: DISK FULL");
         err = AFPERR_DFULL;
         goto afp_write_err;
@@ -1251,95 +1185,69 @@ static int write_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, s
     }
 
     saveoff = offset;
-    if (ad_tmplock(ofork->of_ad, eid, ADLOCK_WR, saveoff,
-                   reqcount, ofork->of_refnum) < 0) {
-        err = AFPERR_LOCK;
-        goto afp_write_err;
+    if (obj->options.flags & OPTION_AFP_READ_LOCK) {
+        if (ad_tmplock(ofork->of_ad, eid, ADLOCK_WR, saveoff, reqcount, ofork->of_refnum) < 0) {
+            err = AFPERR_LOCK;
+            goto afp_write_err;
+        }
     }
 
-    /* this is yucky, but dsi can stream i/o and asp can't */
-    switch (obj->proto) {
-#ifndef NO_DDP
-    case AFPPROTO_ASP:
-        if (asp_wrtcont(obj->handle, rbuf, rbuflen) < 0) {
-            *rbuflen = 0;
-            LOG(log_error, logtype_afpd, "afp_write: asp_wrtcont: %s", strerror(errno) );
-            return( AFPERR_PARAM );
-        }
+    /* find out what we have already */
+    cc = dsi_writeinit(dsi, rcvbuf, rcvbuflen);
 
-#ifdef DEBUG1
-        if (obj->options.flags & OPTION_DEBUG) {
-            printf("(write) len: %d\n", *rbuflen);
-            bprint(rbuf, *rbuflen);
-        }
-#endif
-        if ((cc = write_file(ofork, eid, offset, rbuf, *rbuflen,
-                             xlate)) < 0) {
-            *rbuflen = 0;
+    if (!cc || (cc = write_file(ofork, eid, offset, rcvbuf, cc)) < 0) {
+        dsi_writeflush(dsi);
+        *rbuflen = 0;
+        if (obj->options.flags & OPTION_AFP_READ_LOCK)
             ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, reqcount, ofork->of_refnum);
-            return cc;
-        }
-        offset += cc;
-        break;
-#endif /* no afp/asp */
-
-    case AFPPROTO_DSI:
-        {
-            DSI *dsi = obj->handle;
+        return cc;
+    }
 
-            /* find out what we have already and write it out. */
-            cc = dsi_writeinit(dsi, rbuf, *rbuflen);
-            if (!cc || (cc = write_file(ofork, eid, offset, rbuf, cc, xlate)) < 0) {
-                dsi_writeflush(dsi);
-                *rbuflen = 0;
-                ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, reqcount, ofork->of_refnum);
-                return cc;
-            }
-            offset += cc;
+    offset += cc;
 
 #if 0 /*def HAVE_SENDFILE_WRITE*/
-            if (!(xlate || obj->options.flags & OPTION_DEBUG)) {
-                if ((cc = ad_writefile(ofork->of_ad, eid, dsi->socket,
-                                       offset, dsi->datasize)) < 0) {
-                    switch (errno) {
-                    case EDQUOT :
-                    case EFBIG :
-                    case ENOSPC :
-                        cc = AFPERR_DFULL;
-                        break;
-                    default :
-                        LOG(log_error, logtype_afpd, "afp_write: ad_writefile: %s", strerror(errno) );
-                        goto afp_write_loop;
-                    }
-                    dsi_writeflush(dsi);
-                    *rbuflen = 0;
-                    ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff,
-                               reqcount,  ofork->of_refnum);
-                    return cc;
-                }
+    if ((cc = ad_writefile(ofork->of_ad, eid, dsi->socket, offset, dsi->datasize)) < 0) {
+        switch (errno) {
+        case EDQUOT:
+        case EFBIG:
+        case ENOSPC:
+            cc = AFPERR_DFULL;
+            break;
+        default:
+            LOG(log_error, logtype_afpd, "afp_write: ad_writefile: %s", strerror(errno) );
+            goto afp_write_loop;
+        }
+        dsi_writeflush(dsi);
+        *rbuflen = 0;
+        if (obj->options.flags & OPTION_AFP_READ_LOCK)
+            ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, reqcount,  ofork->of_refnum);
+        return cc;
+    }
 
-                offset += cc;
-                goto afp_write_done;
-            }
+    offset += cc;
+    goto afp_write_done;
 #endif /* 0, was HAVE_SENDFILE_WRITE */
 
-            /* loop until everything gets written. currently
-                    * dsi_write handles the end case by itself. */
-            while ((cc = dsi_write(dsi, rbuf, *rbuflen))) {
-                if ((cc = write_file(ofork, eid, offset, rbuf, cc, xlate)) < 0) {
-                    dsi_writeflush(dsi);
-                    *rbuflen = 0;
-                    ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff,
-                               reqcount,  ofork->of_refnum);
-                    return cc;
-                }
-                offset += cc;
-            }
+    /* loop until everything gets written. currently
+     * dsi_write handles the end case by itself. */
+    while ((cc = dsi_write(dsi, rcvbuf, rcvbuflen))) {
+
+        if ((cc = write_file(ofork, eid, offset, rcvbuf, cc)) < 0) {
+            dsi_writeflush(dsi);
+            *rbuflen = 0;
+            if (obj->options.flags & OPTION_AFP_READ_LOCK)
+                ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, reqcount,  ofork->of_refnum);
+            return cc;
         }
-        break;
+
+        LOG(log_debug, logtype_afpd, "afp_write: wrote: %jd, offset: %jd",
+            (intmax_t)cc, (intmax_t)offset);
+
+        offset += cc;
     }
 
-    ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, reqcount,  ofork->of_refnum);
+    if (obj->options.flags & OPTION_AFP_READ_LOCK)
+        ad_tmplock(ofork->of_ad, eid, ADLOCK_CLR, saveoff, reqcount,  ofork->of_refnum);
     if ( ad_meta_fileno( ofork->of_ad ) != -1 ) /* META */
         ofork->of_flags |= AFPFORK_DIRTY;
 
@@ -1353,10 +1261,9 @@ static int write_fork(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, s
     return( AFP_OK );
 
 afp_write_err:
-    if (obj->proto == AFPPROTO_DSI) {
-        dsi_writeinit(obj->handle, rbuf, *rbuflen);
-        dsi_writeflush(obj->handle);
-    }
+    dsi_writeinit(obj->dsi, rbuf, *rbuflen);
+    dsi_writeflush(obj->dsi);
+
     if (err != AFP_OK) {
         *rbuflen = 0;
     }
@@ -1369,20 +1276,20 @@ int afp_write(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbufl
     return write_fork(obj, ibuf, ibuflen, rbuf, rbuflen, 0);
 }
 
-/* ---------------------------- 
+/* ----------------------------
  * FIXME need to deal with SIGXFSZ signal
-*/
+ */
 int afp_write_ext(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
 {
     return write_fork(obj, ibuf, ibuflen, rbuf, rbuflen, 1);
 }
 
 /* ---------------------------- */
-int afp_getforkparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
+int afp_getforkparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
-    struct ofork       *ofork;
+    struct ofork    *ofork;
     int             ret;
-    u_int16_t          ofrefnum, bitmap;
+    uint16_t       ofrefnum, bitmap;
     size_t          buflen;
     ibuf += 2;
     memcpy(&ofrefnum, ibuf, sizeof( ofrefnum ));
@@ -1397,15 +1304,14 @@ int afp_getforkparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbu
         return( AFPERR_PARAM );
     }
 
-    if ( ad_meta_fileno( ofork->of_ad ) != -1 ) { /* META */
-        if ( ad_refresh( ofork->of_ad ) < 0 ) {
+    if (AD_META_OPEN(ofork->of_ad)) {
+        if ( ad_refresh(NULL, ofork->of_ad ) < 0 ) {
             LOG(log_error, logtype_afpd, "getforkparams(%s): ad_refresh: %s", of_name(ofork), strerror(errno) );
             return( AFPERR_PARAM );
         }
     }
 
-    if (AFP_OK != ( ret = getforkparams( ofork, bitmap,
-                               rbuf + sizeof( u_short ), &buflen ))) {
+    if (AFP_OK != (ret = getforkparams(obj, ofork, bitmap, rbuf + sizeof( u_short ), &buflen ))) {
         return( ret );
     }
 
index 0ad46a9779ff519afcac78183db69c9c8e24e33a..d7120e4778b163927bd17b31c2f5ffd4872aa3a9 100644 (file)
@@ -7,9 +7,8 @@
 #define AFPD_FORK_H 1
 
 #include <stdio.h>
-#include <sys/cdefs.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/adouble.h>
 #include "volume.h"
 #include "directory.h"
@@ -27,7 +26,6 @@ struct ofork {
     uint16_t            of_refnum;
     int                 of_flags;
     struct ofork        **prevp, *next;
-//    struct ofork        *of_d_prev, *of_d_next;
 };
 
 #define OPENFORK_DATA   (0)
@@ -39,39 +37,39 @@ struct ofork {
 #define OPENACC_DWR (1<<5)
 
 /* ofork.of_flags bits */
-#define AFPFORK_OPEN    (1<<0)
-#define AFPFORK_RSRC    (1<<1)
-#define AFPFORK_DATA    (1<<2)
+#define AFPFORK_DATA    (1<<0)  /* open datafork */
+#define AFPFORK_RSRC    (1<<1)  /* open rsrcfork */
+#define AFPFORK_META    (1<<2)  /* open metadata */
 #define AFPFORK_DIRTY   (1<<3)
 #define AFPFORK_ACCRD   (1<<4)
 #define AFPFORK_ACCWR   (1<<5)
 #define AFPFORK_ACCMASK (AFPFORK_ACCRD | AFPFORK_ACCWR)
 #define AFPFORK_MODIFIED (1<<6) /* used in FCE for modified files */
+#define AFPFORK_ERROR   (1<<7)  /* used to indicate an error in opening the fork */
 
 #ifdef AFS
 extern struct ofork *writtenfork;
 #endif
 
-#define of_name(a) (a)->of_ad->ad_m_name
+#define of_name(a) (a)->of_ad->ad_name
 /* in ofork.c */
 extern struct ofork *of_alloc    (struct vol *, struct dir *,
-                                                      char *, u_int16_t *, const int,
+                                                      char *, uint16_t *, const int,
                                                       struct adouble *,
                                                       struct stat *);
 extern void         of_dealloc   (struct ofork *);
-extern struct ofork *of_find     (const u_int16_t);
+extern struct ofork *of_find     (const uint16_t);
 extern struct ofork *of_findname (struct path *);
 extern int          of_rename    (const struct vol *,
                                           struct ofork *,
                                           struct dir *, const char *,
                                           struct dir *, const char *);
 extern int          of_flush     (const struct vol *);
-extern void         of_pforkdesc (FILE *);
 extern int          of_stat      (struct path *);
 extern int          of_statdir   (struct vol *vol, struct path *);
-extern int          of_closefork (struct ofork *ofork);
-extern void         of_closevol  (const struct vol *vol);
-extern void         of_close_all_forks(void);
+extern int          of_closefork (const AFPObj *obj, struct ofork *ofork);
+extern void         of_closevol  (const AFPObj *obj, const struct vol *vol);
+extern void         of_close_all_forks(const AFPObj *obj);
 extern struct adouble *of_ad     (const struct vol *, struct path *, struct adouble *);
 
 #ifdef HAVE_ATFUNCS
@@ -82,7 +80,6 @@ extern int of_fstatat(int dirfd, struct path *path);
 
 /* in fork.c */
 extern int          flushfork    (struct ofork *);
-extern int          getforkmode  (struct adouble *, int , off_t );
 
 /* FP functions */
 int afp_openfork (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf,  size_t *rbuflen);
index 6c9d473b34379f4741060826197e542dbf56b462..fd48db688e1a56b39ca2d817efe00a15c6cf9f06 100644 (file)
 #endif /* HAVE_CONFIG_H */
 
 #include <sys/param.h>
-
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
 #include <ctype.h>
 #include <pwd.h>
 
index c3214a0a762b71cc84e4f469f0c14d99dc95451a..ee0e56ca975e4c5d7fdd6546975e5e0516f10d5d 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: icon.h,v 1.5 2009-10-16 00:11:42 didg Exp $
- *
  * Copyright (c) 1990,1994 Regents of The University of Michigan.
  * All Rights Reserved.  See COPYRIGHT.
  */
@@ -8,227 +6,8 @@
 #ifndef AFPD_ICON_H
 #define AFPD_ICON_H 1
 
-#include <sys/cdefs.h>
 #include <atalk/globals.h>
 
-static const unsigned char apple_atalk_icon[] = { /* default appletalk icon */
-    0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,
-    0x00,  0x01,  0x00,  0x00,  0x00,  0x02,  0x9F,  0xE0,
-    0x00,  0x04,  0x50,  0x30,  0x00,  0x08,  0x30,  0x28,
-    0x00,  0x10,  0x10,  0x3C,  0x07,  0xA0,  0x08,  0x04,
-    0x18,  0x7F,  0x04,  0x04,  0x10,  0x00,  0x82,  0x04,
-    0x10,  0x00,  0x81,  0x04,  0x10,  0x00,  0x82,  0x04,
-    0x10,  0x00,  0x84,  0x04,  0x10,  0x00,  0x88,  0x04,
-    0x10,  0x00,  0x90,  0x04,  0x10,  0x00,  0xB0,  0x04,
-    0x10,  0x00,  0xD0,  0x04,  0xFF,  0xFF,  0xFF,  0xFF,
-    0x40,  0x00,  0x00,  0x02,  0x3F,  0xFF,  0xFF,  0xFC,
-    0x00,  0x00,  0x07,  0x00,  0x00,  0x00,  0x05,  0x00,
-    0x00,  0x00,  0x05,  0x00,  0x00,  0x00,  0x05,  0x00,
-    0x00,  0x00,  0x0F,  0x80,  0x00,  0x00,  0x08,  0x80,
-    0x00,  0x00,  0x08,  0x80,  0x00,  0x00,  0x0F,  0x80,
-    0x00,  0x00,  0x0A,  0x80,  0xBF,  0xFF,  0xF2,  0x74,
-    0x00,  0x00,  0x05,  0x00,  0xBF,  0xFF,  0xF8,  0xF4,
-    0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,  0x00,
-    0x00,  0x01,  0x00,  0x00,  0x00,  0x03,  0x9F,  0xE0,
-    0x00,  0x07,  0xDF,  0xF0,  0x00,  0x0F,  0xFF,  0xF8,
-    0x00,  0x1F,  0xFF,  0xFC,  0x07,  0xBF,  0xFF,  0xFC,
-    0x1F,  0xFF,  0xFF,  0xFC,  0x1F,  0xFF,  0xFF,  0xFC,
-    0x1F,  0xFF,  0xFF,  0xFC,  0x1F,  0xFF,  0xFF,  0xFC,
-    0x1F,  0xFF,  0xFF,  0xFC,  0x1F,  0xFF,  0xFF,  0xFC,
-    0x1F,  0xFF,  0xFF,  0xFC,  0x1F,  0xFF,  0xFF,  0xFC,
-    0x1F,  0xFF,  0xFF,  0xFC,  0xFF,  0xFF,  0xFF,  0xFF,
-    0x7F,  0xFF,  0xFF,  0xFE,  0x3F,  0xFF,  0xFF,  0xFC,
-    0x00,  0x00,  0x07,  0x00,  0x00,  0x00,  0x07,  0x00,
-    0x00,  0x00,  0x07,  0x00,  0x00,  0x00,  0x07,  0x00,
-    0x00,  0x00,  0x0F,  0x80,  0x00,  0x00,  0x0F,  0x80,
-    0x00,  0x00,  0x0F,  0x80,  0x00,  0x00,  0x0F,  0x80,
-    0x00,  0x00,  0x0F,  0x80,  0xBF,  0xFF,  0xFF,  0xF4,
-    0xBF,  0xFF,  0xFD,  0xF4,  0xBF,  0xFF,  0xF8,  0xF4
-};
-
-static const unsigned char apple_tcp_icon[] = { /* default asip icon */
-    0x30,  0x00,  0x8f,  0xf8,  0xcc,  0x01,  0x48,  0x0c,
-    0xb3,  0x32,  0x28,  0x0a,  0x8c,  0xcc,  0x7c,  0x0f,
-    0x83,  0x02,  0xff,  0x01,  0x80,  0xc3,  0xc3,  0x81,
-    0x80,  0x33,  0xe3,  0xc1,  0x80,  0x0b,  0xd3,  0xc1,
-    0x80,  0x0b,  0xb1,  0x61,  0x80,  0x0b,  0xe0,  0xe1,
-    0x80,  0x0b,  0xe1,  0xe1,  0x80,  0x0b,  0xd1,  0xe1,
-    0xc0,  0x0a,  0xc0,  0xe1,  0x70,  0x0b,  0x78,  0xc1,
-    0x1c,  0x0b,  0x79,  0xc1,  0x17,  0x0b,  0x33,  0xff,
-    0x21,  0xcb,  0xff,  0xc4,  0x40,  0x7f,  0xff,  0x02,
-    0x80,  0x1e,  0x00,  0x01,  0xff,  0xff,  0xff,  0xff,
-    0x80,  0x00,  0x00,  0x01,  0xff,  0xff,  0xff,  0xff,
-    0x00,  0x02,  0x80,  0x00,  0x00,  0x02,  0x80,  0x00,
-    0x00,  0x07,  0xc0,  0x00,  0x00,  0x04,  0x40,  0x00,
-    0x00,  0x04,  0x40,  0x00,  0x00,  0x07,  0xc0,  0x00,
-    0x00,  0x05,  0x40,  0x00,  0x0f,  0xf9,  0x3f,  0xfc,
-    0x00,  0x02,  0x80,  0x00,  0x0f,  0xfc,  0x7f,  0xfc,
-    0x30,  0x00,  0x8f,  0xf8,  0xfc,  0x01,  0xcf,  0xfc,
-    0xff,  0x33,  0xef,  0xfe,  0xff,  0xff,  0xff,  0xff,
-    0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,
-    0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,
-    0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,
-    0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,
-    0xff,  0xff,  0xff,  0xff,  0x7f,  0xff,  0xff,  0xff,
-    0x1f,  0xff,  0xff,  0xff,  0x1f,  0xff,  0xff,  0xff,
-    0x3f,  0xff,  0xff,  0xfc,  0x7f,  0xff,  0xff,  0xfe,
-    0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,
-    0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,  0xff,
-    0x00,  0x03,  0x80,  0x00,  0x00,  0x03,  0x80,  0x00,
-    0x00,  0x07,  0xc0,  0x00,  0x00,  0x07,  0xc0,  0x00,
-    0x00,  0x07,  0xc0,  0x00,  0x00,  0x07,  0xc0,  0x00,
-    0x00,  0x07,  0xc0,  0x00,  0xff,  0xff,  0xff,  0xff,
-    0x3f,  0xfe,  0xff,  0xff,  0xff,  0xfc,  0x7f,  0xff
-};
-
-#if defined( ultrix )
-static const unsigned char icon[] = { /* declogo */
-    0x0, 0x80, 0x0, 0x0, 0x1, 0xC0, 0x0, 0x0,
-    0x3, 0xE0, 0x0, 0x0, 0x7, 0xF0, 0x0, 0x0,
-    0xF, 0xB0, 0x0, 0x0, 0x13, 0x6C, 0x0, 0x0,
-    0x2C, 0xDE, 0x0, 0x0, 0x6D, 0xBB, 0x0, 0x0,
-    0xF3, 0x7F, 0x80, 0x0, 0x7E, 0xEF, 0x40, 0x0,
-    0x3D, 0xDE, 0xE0, 0x0, 0x1B, 0xBD, 0xF0, 0x0,
-    0x7, 0x7B, 0xF8, 0x0, 0x7, 0xF7, 0xF8, 0x0,
-    0x3, 0xEC, 0xF6, 0x0, 0x1, 0xDB, 0x6F, 0x0,
-    0x0, 0xBB, 0x5D, 0x80, 0x0, 0x6C, 0xBF, 0xC0,
-    0x0, 0x2D, 0x77, 0xA0, 0x0, 0x12, 0xEF, 0x70,
-    0x0, 0xD, 0xDE, 0xF8, 0x7F, 0xFF, 0xFF, 0xFE,
-    0x20, 0x0, 0x0, 0x4, 0x1F, 0xFF, 0xFF, 0xF8,
-    0x0, 0x4, 0x40, 0x0, 0x0, 0x4, 0x40, 0x0,
-    0x0, 0x3, 0x80, 0x0, 0x0, 0x4, 0x40, 0x0,
-    0xAF, 0xF9, 0x3F, 0xF5, 0x0, 0x2, 0x80, 0x0,
-    0xAF, 0xFC, 0x7F, 0xF5, 0x0, 0x0, 0x0, 0x0,
-    0x0, 0x80, 0x0, 0x0, 0x1, 0xC0, 0x0, 0x0,
-    0x3, 0xE0, 0x0, 0x0, 0x7, 0xF0, 0x0, 0x0,
-    0xF, 0xF8, 0x0, 0x0, 0x1F, 0xFC, 0x0, 0x0,
-    0x3F, 0xFE, 0x0, 0x0, 0x7F, 0xFF, 0x0, 0x0,
-    0xFF, 0xFF, 0x80, 0x0, 0x7F, 0xFF, 0xC0, 0x0,
-    0x3F, 0xFF, 0xE0, 0x0, 0x1F, 0xFF, 0xF0, 0x0,
-    0xF, 0xFF, 0xF8, 0x0, 0x7, 0xFF, 0xFC, 0x0,
-    0x3, 0xFF, 0xFE, 0x0, 0x1, 0xFF, 0xFF, 0x0,
-    0x0, 0xFF, 0xFF, 0x80, 0x0, 0x7F, 0xFF, 0xC0,
-    0x0, 0x3F, 0xFF, 0xE0, 0x0, 0x1F, 0xFF, 0xF0,
-    0x0, 0xF, 0xFF, 0xF8, 0x7F, 0xFF, 0xFF, 0xFE,
-    0x3F, 0xFF, 0xFF, 0xFC, 0x1F, 0xFF, 0xFF, 0xF8,
-    0x0, 0x7, 0xC0, 0x0, 0x0, 0x7, 0xC0, 0x0,
-    0x0, 0x3, 0x80, 0x0, 0x0, 0x7, 0xC0, 0x0,
-    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
-    0xFF, 0xFC, 0x7F, 0xFF, 0x0, 0x0, 0x0, 0x0
-};
-
-#else
-#if defined( vax )
-static const unsigned char icon[] = { /* daemon */
-    0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x2, 0x0,
-    0x1, 0x80, 0x3, 0x0, 0x2, 0x80, 0x2, 0x80,
-    0x2, 0x80, 0x2, 0x80, 0x4, 0x80, 0x2, 0x40,
-    0x4, 0x87, 0xC2, 0x40, 0x4, 0x58, 0x34, 0x40,
-    0x4, 0x20, 0x8, 0x40, 0x2, 0x16, 0xD0, 0x80,
-    0x1, 0x1, 0x1, 0x0, 0x2, 0x80, 0x2, 0x80,
-    0x2, 0x9C, 0x72, 0x80, 0x4, 0x22, 0x88, 0x40,
-    0x4, 0x41, 0x4, 0x40, 0x4, 0x41, 0x4, 0x40,
-    0x4, 0x41, 0x4, 0x40, 0x4, 0x49, 0x24, 0x40,
-    0xE, 0x55, 0x54, 0xE0, 0x10, 0x5D, 0x74, 0x10,
-    0x10, 0x3E, 0xF8, 0x10, 0x7F, 0xFC, 0x7F, 0xFE,
-    0x20, 0x4, 0x40, 0x4, 0x1F, 0xFC, 0x7F, 0xF8,
-    0x0, 0x7, 0xC0, 0x0, 0x0, 0x4, 0x40, 0x0,
-    0x0, 0x3, 0x80, 0x0, 0x0, 0x4, 0x40, 0x0,
-    0xAF, 0xF9, 0x3F, 0xF5, 0x0, 0x2, 0x80, 0x0,
-    0xAF, 0xFC, 0x7F, 0xF5, 0x0, 0x0, 0x0, 0x0,
-    0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x2, 0x0,
-    0x1, 0x80, 0x3, 0x0, 0x3, 0x80, 0x3, 0x80,
-    0x3, 0x80, 0x3, 0x80, 0x7, 0x80, 0x3, 0xC0,
-    0x7, 0x87, 0xC3, 0xC0, 0x7, 0xDF, 0xF7, 0xC0,
-    0x7, 0xFF, 0xFF, 0xC0, 0x3, 0xFF, 0xFF, 0x80,
-    0x1, 0xFF, 0xFF, 0x0, 0x3, 0xFF, 0xFF, 0x80,
-    0x3, 0xFF, 0xFF, 0x80, 0x7, 0xFF, 0xFF, 0xC0,
-    0x7, 0xFF, 0xFF, 0xC0, 0x7, 0xFF, 0xFF, 0xC0,
-    0x7, 0xFF, 0xFF, 0xC0, 0x7, 0xFF, 0xFF, 0xC0,
-    0xF, 0xFF, 0xFF, 0xE0, 0x1F, 0xFF, 0xFF, 0xF0,
-    0x1F, 0xFF, 0xFF, 0xF0, 0x7F, 0xFF, 0xFF, 0xFE,
-    0x3F, 0xFF, 0xFF, 0xFC, 0x1F, 0xFF, 0xFF, 0xF8,
-    0x0, 0x7, 0xC0, 0x0, 0x0, 0x7, 0xC0, 0x0,
-    0x0, 0x3, 0x80, 0x0, 0x0, 0x4, 0x40, 0x0,
-    0xAF, 0xF9, 0x3F, 0xF5, 0x0, 0x2, 0x80, 0x0,
-    0xAF, 0xFC, 0x7F, 0xF5, 0x0, 0x0, 0x0, 0x0
-};
-
-#else
-#if defined( sun )
-static const unsigned char icon[] = { /* sunlogo */
-    0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x80, 0x0,
-    0x0, 0x2, 0x40, 0x0, 0x0, 0x2, 0x20, 0x0,
-    0x0, 0x9, 0x10, 0x0, 0x0, 0x4, 0x88, 0x0,
-    0x0, 0x22, 0x44, 0x0, 0x0, 0x11, 0x20, 0x0,
-    0x0, 0x88, 0x91, 0x0, 0x1, 0x4, 0x42, 0x0,
-    0x2, 0x22, 0x44, 0x40, 0x4, 0x41, 0x88, 0x80,
-    0x8, 0x98, 0x11, 0x30, 0x11, 0x24, 0x22, 0x48,
-    0x12, 0x44, 0x24, 0x88, 0xC, 0x88, 0x19, 0x10,
-    0x1, 0x11, 0x82, 0x20, 0x2, 0x22, 0x44, 0x40,
-    0x0, 0x42, 0x20, 0x80, 0x0, 0x89, 0x11, 0x0,
-    0x0, 0x4, 0x88, 0x0, 0x7F, 0xFF, 0xFF, 0xFE,
-    0x20, 0x0, 0x0, 0x4, 0x1F, 0xFF, 0xFF, 0xF8,
-    0x0, 0x4, 0x40, 0x0, 0x0, 0x4, 0x40, 0x0,
-    0x0, 0x3, 0x80, 0x0, 0x0, 0x4, 0x40, 0x0,
-    0xAF, 0xF9, 0x3F, 0xF5, 0x0, 0x2, 0x80, 0x0,
-    0xAF, 0xFC, 0x7F, 0xF5, 0x0, 0x0, 0x0, 0x0,
-    0x0, 0x1, 0x80, 0x0, 0x0, 0x3, 0xC0, 0x0,
-    0x0, 0x7, 0xE0, 0x0, 0x0, 0xF, 0xF0, 0x0,
-    0x0, 0x1F, 0xF8, 0x0, 0x0, 0x3F, 0xFC, 0x0,
-    0x0, 0x7F, 0xFE, 0x0, 0x0, 0xFF, 0xFF, 0x0,
-    0x1, 0xFF, 0xFF, 0x80, 0x3, 0xFF, 0xFF, 0xC0,
-    0x7, 0xFF, 0xFF, 0xE0, 0xF, 0xFF, 0xFF, 0xF0,
-    0x1F, 0xFF, 0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xFC,
-    0x3F, 0xFF, 0xFF, 0xFC, 0x1F, 0xFF, 0xFF, 0xF8,
-    0xF, 0xFF, 0xFF, 0xF0, 0x7, 0xFF, 0xFF, 0xE0,
-    0x3, 0xFF, 0xFF, 0xC0, 0x1, 0xFF, 0xFF, 0x80,
-    0x0, 0xFF, 0xFF, 0x0, 0x7F, 0xFF, 0xFF, 0xFE,
-    0x3F, 0xFF, 0xFF, 0xFC, 0x1F, 0xFF, 0xFF, 0xF8,
-    0x0, 0x7, 0xC0, 0x0, 0x0, 0x7, 0xC0, 0x0,
-    0x0, 0x3, 0x80, 0x0, 0x0, 0x7, 0xC0, 0x0,
-    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-    0xFF, 0xFC, 0x7F, 0xFF, 0x0, 0x0, 0x0, 0x0
-};
-
-#else
-#if defined( _IBMR2 )
-static const unsigned char icon[] = { /* hagar */
-    0x0, 0x0, 0x0, 0x0, 0x18, 0x0, 0x0, 0x18,
-    0x24, 0x0, 0x0, 0x24, 0x44, 0x3, 0xC0, 0x22,
-    0x44, 0xC, 0x30, 0x22, 0x42, 0x30, 0xC, 0x42,
-    0x41, 0x40, 0x2, 0x82, 0x41, 0x80, 0x1, 0x82,
-    0x21, 0x0, 0x0, 0x84, 0x11, 0x41, 0x2, 0x88,
-    0xE, 0xA2, 0x85, 0x70, 0x4, 0x41, 0x2, 0x20,
-    0x4, 0x0, 0x0, 0x20, 0x3, 0xFF, 0xFF, 0xC0,
-    0x3, 0xC0, 0x3, 0xC0, 0x3, 0x82, 0x41, 0xC0,
-    0x7, 0x81, 0x81, 0xE0, 0x7, 0xC2, 0x43, 0xE0,
-    0x7, 0xFC, 0x3F, 0xE0, 0x7, 0xFC, 0x3F, 0xE0,
-    0x7F, 0xFC, 0x3F, 0xFE, 0x20, 0x3, 0xC0, 0x4,
-    0x1F, 0xFF, 0xFF, 0xF8, 0x0, 0x2, 0x40, 0x0,
-    0x0, 0x2, 0x40, 0x0, 0x0, 0x3, 0xC0, 0x0,
-    0x0, 0x4, 0x20, 0x0, 0xAF, 0xF9, 0x9F, 0xF5,
-    0x0, 0x2, 0x40, 0x0, 0xAF, 0xFC, 0x3F, 0xF5,
-    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
-    0x0, 0x0, 0x0, 0x0, 0x18, 0x0, 0x0, 0x18,
-    0x3C, 0x0, 0x0, 0x3C, 0x7C, 0x3, 0xC0, 0x3E,
-    0x7C, 0xF, 0xF0, 0x3E, 0x7E, 0x3F, 0xFC, 0x7E,
-    0x7F, 0x7F, 0xFE, 0xFE, 0x7F, 0xFF, 0xFF, 0xFE,
-    0x3F, 0xFF, 0xFF, 0xFC, 0x1F, 0xFF, 0xFF, 0xF8,
-    0xF, 0xFF, 0xFF, 0xF0, 0x7, 0xFF, 0xFF, 0xE0,
-    0x7, 0xFF, 0xFF, 0xE0, 0x3, 0xFF, 0xFF, 0xC0,
-    0x3, 0xFF, 0xFF, 0xC0, 0x3, 0xFF, 0xFF, 0xC0,
-    0x7, 0xFF, 0xFF, 0xE0, 0x7, 0xFF, 0xFF, 0xE0,
-    0x7, 0xFF, 0xFF, 0xE0, 0x7, 0xFF, 0xFF, 0xE0,
-    0x7F, 0xFF, 0xFF, 0xFE, 0x3F, 0xFF, 0xFF, 0xFC,
-    0x1F, 0xFF, 0xFF, 0xF8, 0x0, 0x3, 0xC0, 0x0,
-    0x0, 0x3, 0xC0, 0x0, 0x0, 0x3, 0xC0, 0x0,
-    0x0, 0x7, 0xE0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF,
-    0xFF, 0xFE, 0x7F, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF,
-    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
-};
-
-#else
 static const unsigned char icon[] = { /* globe */
     0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0xF0, 0x0,
     0x0, 0x30, 0xC, 0x0, 0x0, 0xC0, 0x3, 0x0,
@@ -263,9 +42,5 @@ static const unsigned char icon[] = { /* globe */
     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF,
     0xFF, 0xFC, 0x7F, 0xFF, 0x0, 0x0, 0x0, 0x0
 };
-#endif /*_IBMR2*/
-#endif /*sun*/
-#endif /*vax*/
-#endif /*ultrix*/
 
 #endif
index e23d5570db2f4114ce28c06cc7bb287435447359..e89d0a2e9e58d6aacf2e2cc5af061a56959bb5dc 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <signal.h>
-
 #include <sys/param.h>
 #include <sys/uio.h>
-#include <atalk/logger.h>
 #include <sys/time.h>
 #include <sys/socket.h>
 #include <sys/poll.h>
 #include <sys/wait.h>
 #include <sys/resource.h>
 
+#include <atalk/logger.h>
 #include <atalk/adouble.h>
-
-#include <netatalk/at.h>
 #include <atalk/compat.h>
 #include <atalk/dsi.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
 #include <atalk/afp.h>
 #include <atalk/paths.h>
 #include <atalk/util.h>
 #include <atalk/server_child.h>
 #include <atalk/server_ipc.h>
+#include <atalk/errchk.h>
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
 
 #include "afp_config.h"
 #include "status.h"
 #include "uam_auth.h"
 #include "afp_zeroconf.h"
 
-#ifdef TRU64
-#include <sys/security.h>
-#include <prot.h>
-#include <sia.h>
-
-static int argc = 0;
-static char **argv = NULL;
-#endif /* TRU64 */
-
 #define AFP_LISTENERS 32
 #define FDSET_SAFETY  5
 
-unsigned char  nologin = 0;
-struct afp_options default_options;
-static AFPConfig *configs;
+unsigned char nologin = 0;
+
+static AFPObj obj;
 static server_child *server_children;
 static sig_atomic_t reloadconfig = 0;
 static sig_atomic_t gotsigchld = 0;
@@ -68,45 +56,34 @@ static int fdset_size;          /* current allocated size */
 static int fdset_used;          /* number of used elements */
 static int disasociated_ipc_fd; /* disasociated sessions uses this fd for IPC */
 
-#ifdef TRU64
-void afp_get_cmdline( int *ac, char ***av)
-{
-    *ac = argc;
-    *av = argv;
-}
-#endif /* TRU64 */
+static afp_child_t *dsi_start(AFPObj *obj, DSI *dsi, server_child *server_children);
 
-/* This is registered with atexit() */
-static void afp_exit(void)
+static void afp_exit(int ret)
 {
-    if (parent_or_child == 0)
-        /* Only do this in the parent */
-        server_unlock(default_options.pidfile);
+    exit(ret);
 }
 
 
 /* ------------------
    initialize fd set we are waiting for.
 */
-static void fd_set_listening_sockets(void)
+static void fd_set_listening_sockets(const AFPObj *config)
 {
-    AFPConfig   *config;
+    DSI *dsi;
 
-    for (config = configs; config; config = config->next) {
-        if (config->fd < 0) /* for proxies */
-            continue;
-        fdset_add_fd(default_options.connections + AFP_LISTENERS + FDSET_SAFETY,
+    for (dsi = config->dsi; dsi; dsi = dsi->next) {
+        fdset_add_fd(config->options.connections + AFP_LISTENERS + FDSET_SAFETY,
                      &fdset,
                      &polldata,
                      &fdset_used,
                      &fdset_size,
-                     config->fd,
+                     dsi->serversock,
                      LISTEN_FD,
-                     config);
+                     dsi);
     }
 
-    if (default_options.flags & OPTION_KEEPSESSIONS)
-        fdset_add_fd(default_options.connections + AFP_LISTENERS + FDSET_SAFETY,
+    if (config->options.flags & OPTION_KEEPSESSIONS)
+        fdset_add_fd(config->options.connections + AFP_LISTENERS + FDSET_SAFETY,
                      &fdset,
                      &polldata,
                      &fdset_used,
@@ -116,29 +93,21 @@ static void fd_set_listening_sockets(void)
                      NULL);
 }
  
-static void fd_reset_listening_sockets(void)
+static void fd_reset_listening_sockets(const AFPObj *config)
 {
-    AFPConfig   *config;
+    const DSI *dsi;
 
-    for (config = configs; config; config = config->next) {
-        if (config->fd < 0) /* for proxies */
-            continue;
-        fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, config->fd);
+    for (dsi = config->dsi; dsi; dsi = dsi->next) {
+        fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, dsi->serversock);
     }
 
-    if (default_options.flags & OPTION_KEEPSESSIONS)
+    if (config->options.flags & OPTION_KEEPSESSIONS)
         fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, disasociated_ipc_fd);
 }
 
 /* ------------------ */
 static void afp_goaway(int sig)
 {
-        AFPConfig *config;
-
-#ifndef NO_DDP
-    asp_kill(sig);
-#endif /* ! NO_DDP */
-
     switch( sig ) {
 
     case SIGTERM:
@@ -148,7 +117,7 @@ static void afp_goaway(int sig)
             LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGTERM");
             break;
         case SIGQUIT:
-            if (default_options.flags & OPTION_KEEPSESSIONS) {
+            if (obj.options.flags & OPTION_KEEPSESSIONS) {
                 LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGQUIT, NOT disconnecting clients");
             } else {
                 LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGQUIT");
@@ -159,11 +128,7 @@ static void afp_goaway(int sig)
         if (server_children)
             server_child_kill(server_children, CHILD_DSIFORK, sig);
 
-        for (config = configs; config; config = config->next)
-            if (config->server_cleanup)
-                config->server_cleanup(config);
-        server_unlock(default_options.pidfile);
-        exit(0);
+        _exit(0);
         break;
 
     case SIGUSR1 :
@@ -245,53 +210,37 @@ static int setlimits(void)
 
 int main(int ac, char **av)
 {
-    AFPConfig           *config;
     fd_set              rfds;
     void                *ipc;
     struct sigaction   sv;
     sigset_t            sigs;
     int                 ret;
 
-#ifdef TRU64
-    argc = ac;
-    argv = av;
-    set_auth_parameters( ac, av );
-#endif /* TRU64 */
-
     /* Parse argv args and initialize default options */
-    afp_options_init(&default_options);
-    if (!afp_options_parse(ac, av, &default_options))
-        exit(EXITERR_CONF);
-
-    if (check_lockfile("afpd", default_options.pidfile) != 0)
-        exit(EXITERR_SYS);
-
-    if (!(default_options.flags & OPTION_DEBUG) && (daemonize(0, 0) != 0))
-        exit(EXITERR_SYS);
+    afp_options_parse_cmdline(&obj, ac, av);
 
-    if (create_lockfile("afpd", default_options.pidfile) != 0)
+    if (!(obj.cmdlineflags & OPTION_DEBUG) && (daemonize(0, 0) != 0))
         exit(EXITERR_SYS);
 
     /* Log SIGBUS/SIGSEGV SBT */
     fault_setup(NULL);
 
-    /* Default log setup: log to syslog */
-    set_processname("afpd");
-    setuplog("default log_note");
+    if (afp_config_parse(&obj, "afpd") != 0)
+        afp_exit(EXITERR_CONF);
 
     /* Save the user's current umask */
-    default_options.save_mask = umask( default_options.umask );
-
-    atexit(afp_exit);
+    obj.options.save_mask = umask(obj.options.umask);
 
     /* install child handler for asp and dsi. we do this before afp_goaway
      * as afp_goaway references stuff from here. 
      * XXX: this should really be setup after the initial connections. */
-    if (!(server_children = server_child_alloc(default_options.connections,
-                            CHILD_NFORKS))) {
+    if (!(server_children = server_child_alloc(obj.options.connections, CHILD_NFORKS))) {
         LOG(log_error, logtype_afpd, "main: server_child alloc: %s", strerror(errno) );
-        exit(EXITERR_SYS);
+        afp_exit(EXITERR_SYS);
     }
+    
+    sigemptyset(&sigs);
+    pthread_sigmask(SIG_SETMASK, &sigs, NULL);
 
     memset(&sv, 0, sizeof(sv));    
     /* linux at least up to 2.4.22 send a SIGXFZ for vfat fs,
@@ -301,7 +250,7 @@ int main(int ac, char **av)
     sigemptyset( &sv.sa_mask );
     if (sigaction(SIGXFSZ, &sv, NULL ) < 0 ) {
         LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
-        exit(EXITERR_SYS);
+        afp_exit(EXITERR_SYS);
     }
 #endif
     
@@ -316,7 +265,7 @@ int main(int ac, char **av)
     sv.sa_flags = SA_RESTART;
     if ( sigaction( SIGCHLD, &sv, NULL ) < 0 ) {
         LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
-        exit(EXITERR_SYS);
+        afp_exit(EXITERR_SYS);
     }
 
     sigemptyset( &sv.sa_mask );
@@ -328,7 +277,7 @@ int main(int ac, char **av)
     sv.sa_flags = SA_RESTART;
     if ( sigaction( SIGUSR1, &sv, NULL ) < 0 ) {
         LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
-        exit(EXITERR_SYS);
+        afp_exit(EXITERR_SYS);
     }
 
     sigemptyset( &sv.sa_mask );
@@ -340,10 +289,9 @@ int main(int ac, char **av)
     sv.sa_flags = SA_RESTART;
     if ( sigaction( SIGHUP, &sv, NULL ) < 0 ) {
         LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
-        exit(EXITERR_SYS);
+        afp_exit(EXITERR_SYS);
     }
 
-
     sigemptyset( &sv.sa_mask );
     sigaddset(&sv.sa_mask, SIGALRM);
     sigaddset(&sv.sa_mask, SIGHUP);
@@ -353,7 +301,7 @@ int main(int ac, char **av)
     sv.sa_flags = SA_RESTART;
     if ( sigaction( SIGTERM, &sv, NULL ) < 0 ) {
         LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
-        exit(EXITERR_SYS);
+        afp_exit(EXITERR_SYS);
     }
 
     sigemptyset( &sv.sa_mask );
@@ -365,10 +313,10 @@ int main(int ac, char **av)
     sv.sa_flags = SA_RESTART;
     if (sigaction(SIGQUIT, &sv, NULL ) < 0 ) {
         LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
-        exit(EXITERR_SYS);
+        afp_exit(EXITERR_SYS);
     }
 
-    /* afpd.conf: not in config file: lockfile, connections, configfile
+    /* afp.conf:  not in config file: lockfile, configfile
      *            preference: command-line provides defaults.
      *                        config file over-writes defaults.
      *
@@ -387,23 +335,23 @@ int main(int ac, char **av)
     sigaddset(&sigs, SIGCHLD);
 
     pthread_sigmask(SIG_BLOCK, &sigs, NULL);
-    if (!(configs = configinit(&default_options))) {
+    if (configinit(&obj) != 0) {
         LOG(log_error, logtype_afpd, "main: no servers configured");
-        exit(EXITERR_CONF);
+        afp_exit(EXITERR_CONF);
     }
     pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
 
-    /* Register CNID  */
+    /* Initialize */
     cnid_init();
-
+    
     /* watch atp, dsi sockets and ipc parent/child file descriptor. */
 
-    if (default_options.flags & OPTION_KEEPSESSIONS) {
+    if (obj.options.flags & OPTION_KEEPSESSIONS) {
         LOG(log_note, logtype_afpd, "Activating continous service");
         disasociated_ipc_fd = ipc_server_uds(_PATH_AFP_IPC);
     }
 
-    fd_set_listening_sockets();
+    fd_set_listening_sockets(&obj);
 
     /* set limits */
     (void)setlimits();
@@ -435,22 +383,17 @@ int main(int ac, char **av)
         if (reloadconfig) {
             nologin++;
             auth_unload();
-            fd_reset_listening_sockets();
+            fd_reset_listening_sockets(&obj);
 
             LOG(log_info, logtype_afpd, "re-reading configuration file");
-            for (config = configs; config; config = config->next)
-                if (config->server_cleanup)
-                    config->server_cleanup(config);
-
-            /* configfree close atp socket used for DDP tickle, there's an issue
-             * with atp tid. */
-            configfree(configs, NULL);
-            if (!(configs = configinit(&default_options))) {
+
+            configfree(&obj, NULL);
+            if (configinit(&obj) != 0) {
                 LOG(log_error, logtype_afpd, "config re-read: no servers configured");
-                exit(EXITERR_CONF);
+                afp_exit(EXITERR_CONF);
             }
 
-            fd_set_listening_sockets();
+            fd_set_listening_sockets(&obj);
 
             nologin = 0;
             reloadconfig = 0;
@@ -469,15 +412,13 @@ int main(int ac, char **av)
         }
 
         for (int i = 0; i < fdset_used; i++) {
-            if (fdset[i].revents & (POLLIN | POLLERR | POLLHUP)) {
+            if (fdset[i].revents & (POLLIN | POLLERR | POLLHUP | POLLNVAL)) {
                 switch (polldata[i].fdtype) {
 
                 case LISTEN_FD:
-                    config = (AFPConfig *)polldata[i].data;
-                    /* config->server_start is afp_config.c:dsi_start() for DSI */
-                    if (child = config->server_start(config, configs, server_children)) {
+                    if (child = dsi_start(&obj, (DSI *)polldata[i].data, server_children)) {
                         /* Add IPC fd to select fd set */
-                        fdset_add_fd(default_options.connections + AFP_LISTENERS + FDSET_SAFETY,
+                        fdset_add_fd(obj.options.connections + AFP_LISTENERS + FDSET_SAFETY,
                                      &fdset,
                                      &polldata,
                                      &fdset_used,
@@ -496,7 +437,7 @@ int main(int ac, char **av)
                         fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, child->ipc_fd);
                         close(child->ipc_fd);
                         child->ipc_fd = -1;
-                        if ((default_options.flags & OPTION_KEEPSESSIONS) && child->disasociated) {
+                        if ((obj.options.flags & OPTION_KEEPSESSIONS) && child->disasociated) {
                             LOG(log_note, logtype_afpd, "main: removing reattached child[%u]", child->pid);
                             server_child_remove(server_children, CHILD_DSIFORK, child->pid);
                         }
@@ -522,7 +463,7 @@ int main(int ac, char **av)
                         break;
                     }
                     child->disasociated = 1;
-                    fdset_add_fd(default_options.connections + AFP_LISTENERS + FDSET_SAFETY,
+                    fdset_add_fd(obj.options.connections + AFP_LISTENERS + FDSET_SAFETY,
                                  &fdset,
                                  &polldata,
                                  &fdset_used,
@@ -542,3 +483,22 @@ int main(int ac, char **av)
 
     return 0;
 }
+
+static afp_child_t *dsi_start(AFPObj *obj, DSI *dsi, server_child *server_children)
+{
+    afp_child_t *child = NULL;
+
+    if (dsi_getsession(dsi, server_children, obj->options.tickleval, &child) != 0) {
+        LOG(log_error, logtype_afpd, "dsi_start: session error: %s", strerror(errno));
+        return NULL;
+    }
+
+    /* we've forked. */
+    if (child == NULL) {
+        configfree(obj, dsi);
+        afp_over_dsi(obj); /* start a session */
+        exit (0);
+    }
+
+    return child;
+}
index cb2b60ed0c15e5bd63bb0cb1ca1c66e7a02089ba..21bd80f30037c9bba3bd61b9b834c02b1c911089 100644 (file)
@@ -30,7 +30,7 @@ static size_t mangle_extension(const struct vol *vol, const char* uname,
   char *p = strrchr(uname, '.');
 
   if (p && p != uname) {
-    u_int16_t flags = CONV_FORCE | CONV_UNESCAPEHEX;
+    uint16_t flags = CONV_FORCE | CONV_UNESCAPEHEX;
     size_t len = convert_charset(vol->v_volcharset, charset,
                                 vol->v_maccharset, p, strlen(p),
                                 extension, MAX_EXT_LENGTH, &flags);
@@ -42,7 +42,7 @@ static size_t mangle_extension(const struct vol *vol, const char* uname,
 
 static char *demangle_checks(const struct vol *vol, char* uname, char * mfilename, size_t prefix, char * ext)
 {
-    u_int16_t flags;
+    uint16_t flags;
     static char buffer[MAXPATHLEN +2];  /* for convert_charset dest_len parameter +2 */
     size_t len;
     size_t mfilenamelen;
@@ -136,7 +136,7 @@ private_demangle(const struct vol *vol, char *mfilename, cnid_t did, cnid_t *osx
 {
     char *t;
     char *u_name;
-    u_int32_t id, file_id;
+    uint32_t id, file_id;
     static char buffer[12 + MAXPATHLEN + 1];
     int len = 12 + MAXPATHLEN + 1;
     struct dir *dir;
@@ -193,7 +193,7 @@ private_demangle(const struct vol *vol, char *mfilename, cnid_t did, cnid_t *osx
         }
         if (!osx) {
             /* convert back to mac name and check it's the same */
-            t = utompath(vol, u_name, file_id, utf8_encoding());
+            t = utompath(vol, u_name, file_id, utf8_encoding(vol->v_obj));
             if (!strcmp(t, mfilename)) {
                 return u_name;
             }
@@ -266,7 +266,7 @@ mangle(const struct vol *vol, char *filename, size_t filenamelen, char *uname, c
     k = sprintf(mangle_suffix, "%c%X", MANGLE_CHAR, ntohl(id));
 
     if (filenamelen + k + ext_len > maxlen) {
-      u_int16_t opt = CONV_FORCE | CONV_UNESCAPEHEX;
+      uint16_t opt = CONV_FORCE | CONV_UNESCAPEHEX;
       size_t n = convert_charset(vol->v_volcharset,
                                 (flags & 2) ? CH_UTF8_MAC : vol->v_maccharset,
                                 vol->v_maccharset, uname, strlen(uname),
index 2784e8260280ee20e3af9298dd903decb2e3c75b..241f0d08166a166ed2a4b22f8d8b5e088c0b7876 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: messages.c,v 1.23 2009-11-24 15:44:40 didg Exp $
- *
  * Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu)
  * All Rights Reserved.  See COPYRIGHT.
  */
@@ -9,9 +7,7 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>
@@ -24,7 +20,6 @@
 
 #include "misc.h"
 
-
 #define MAXMESGSIZE 199
 
 /* this is only used by afpd children, so it's okay. */
@@ -46,9 +41,9 @@ void readmessage(AFPObj *obj)
     int rc;
     static int c;
     uid_t euid;
-    u_int32_t maxmsgsize;
+    uint32_t maxmsgsize;
 
-    maxmsgsize = (obj->proto == AFPPROTO_DSI)?MIN(MAX(((DSI*)obj->handle)->attn_quantum, MAXMESGSIZE),MAXPATHLEN):MAXMESGSIZE;
+    maxmsgsize = MIN(MAX(obj->dsi->attn_quantum, MAXMESGSIZE), MAXPATHLEN);
 
     i=0;
     /* Construct file name SERVERTEXT/message.[pid] */
@@ -117,15 +112,15 @@ void readmessage(AFPObj *obj)
 int afp_getsrvrmesg(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
     char *message;
-    u_int16_t type, bitmap;
-    u_int16_t msgsize;
+    uint16_t type, bitmap;
+    uint16_t msgsize;
     size_t outlen = 0;
     size_t msglen = 0;
     int utf8 = 0;
 
     *rbuflen = 0;
 
-    msgsize = (obj->proto == AFPPROTO_DSI)?MAX(((DSI*)obj->handle)->attn_quantum, MAXMESGSIZE):MAXMESGSIZE;
+    msgsize = MAX(obj->dsi->attn_quantum, MAXMESGSIZE);
 
     memcpy(&type, ibuf + 2, sizeof(type));
     memcpy(&bitmap, ibuf + 4, sizeof(bitmap));
@@ -138,10 +133,11 @@ int afp_getsrvrmesg(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, siz
          * it has asked the login msg...
          * Workaround: concatenate the two if any, ugly.
          */
-        if (*message && *obj->options.loginmesg) {
-            strlcat(message, " - ", MAXMESGSIZE);
+        if (obj->options.loginmesg) {
+            if (*message)
+                strlcat(message, " - ", MAXMESGSIZE);
+            strlcat(message, obj->options.loginmesg, MAXMESGSIZE);
         }
-        strlcat(message, obj->options.loginmesg, MAXMESGSIZE);
         break;
     case AFPMESG_SERVER: /* server */
         break;
index 9f3d70bfc71df244b58189f45ab5c5f5854cdb82..b18826df7be9cb2907672161f5ce0ca38df362cb 100644 (file)
@@ -1,11 +1,6 @@
-/*
- * $Id: misc.h,v 1.5 2009-10-15 10:43:13 didg Exp $
- */
-
 #ifndef AFPD_MISC_H
 #define AFPD_MISC_H 1
 
-#include <sys/cdefs.h>
 #include <atalk/globals.h>
 
 /* FP functions */
index 28e61695722f402dc6bb1e8c806d62da60be3243..b250c16633991d0a6a36a365f1cd48c585220bdb 100644 (file)
 
 #if !defined(NO_QUOTA_SUPPORT) && !defined(HAVE_LIBQUOTA)
 #include <stdio.h>
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/param.h> /* for DEV_BSIZE */
@@ -104,7 +91,7 @@ callaurpc(struct vol *vol,
 #define GQR_RQUOTA getquota_rslt_u.gqr_rquota
 #endif /* USE_OLD_RQUOTA */
 
-int getnfsquota(struct vol *vol, const int uid, const u_int32_t bsize,
+int getnfsquota(struct vol *vol, const int uid, const uint32_t bsize,
                 struct dqblk *dqp)
 {
 
index 2d2600895cb5cc37a730a84a5bb1bdb1b9c6380e..3d690079ba84f7136575afa593e79ad2a3c6425a 100644 (file)
@@ -62,22 +62,6 @@ static void of_unhash(struct ofork *of)
     }
 }
 
-#ifdef DEBUG1
-void of_pforkdesc( FILE *f)
-{
-    int ofrefnum;
-
-    if (!oforks)
-        return;
-
-    for ( ofrefnum = 0; ofrefnum < nforks; ofrefnum++ ) {
-        if ( oforks[ ofrefnum ] != NULL ) {
-            fprintf( f, "%hu <%s>\n", ofrefnum, of_name(oforks[ ofrefnum ]));
-        }
-    }
-}
-#endif
-
 int of_flush(const struct vol *vol)
 {
     int refnum;
@@ -114,7 +98,9 @@ int of_rename(const struct vol *vol,
             && s_of->key.dev == of->key.dev
             && s_of->key.inode == of->key.inode ) {
             if (!done) {
-                strlcpy( of_name(of), newpath, of->of_ad->ad_m_namelen);
+                free(of_name(of));
+                if ((of_name(of) = strdup(newpath)) == NULL)
+                    return AFPERR_MISC;
                 done = 1;
             }
             if (newdir != olddir)
@@ -131,13 +117,13 @@ struct ofork *
 of_alloc(struct vol *vol,
          struct dir    *dir,
          char      *path,
-         u_int16_t     *ofrefnum,
+         uint16_t     *ofrefnum,
          const int      eid,
          struct adouble *ad,
          struct stat    *st)
 {
     struct ofork        *of;
-    u_int16_t       refnum, of_refnum;
+    uint16_t       refnum, of_refnum;
 
     int         i;
 
@@ -202,24 +188,18 @@ of_alloc(struct vol *vol,
 
         /* initialize to zero. This is important to ensure that
            ad_open really does reinitialize the structure. */
-        ad_init(ad, vol->v_adouble, vol->v_ad_options);
-
-        ad->ad_m_namelen = UTF8FILELEN_EARLY +1;
-        /* here's the deal: we allocate enough for the standard mac file length.
-         * in the future, we'll reallocate in fairly large jumps in case
-         * of long unicode names */
-        if (( ad->ad_m_name =(char *)malloc( ad->ad_m_namelen )) == NULL ) {
+        ad_init(ad, vol);
+        if ((ad->ad_name = strdup(path)) == NULL) {
             LOG(log_error, logtype_afpd, "of_alloc: malloc: %s", strerror(errno) );
             free(ad);
             free(of);
             oforks[ of_refnum ] = NULL;
             return NULL;
         }
-        strlcpy( ad->ad_m_name, path, ad->ad_m_namelen);
     } else {
         /* Increase the refcount on this struct adouble. This is
            decremented again in oforc_dealloc. */
-        ad->ad_refcount++;
+        ad_ref(ad);
     }
 
     of->of_ad = ad;
@@ -239,7 +219,7 @@ of_alloc(struct vol *vol,
     return( of );
 }
 
-struct ofork *of_find(const u_int16_t ofrefnum )
+struct ofork *of_find(const uint16_t ofrefnum )
 {
     if (!oforks || !nforks)
         return NULL;
@@ -384,7 +364,7 @@ struct ofork *of_findnameat(int dirfd, struct path *path)
 }
 #endif
 
-void of_dealloc( struct ofork *of)
+void of_dealloc(struct ofork *of)
 {
     if (!oforks)
         return;
@@ -396,40 +376,32 @@ void of_dealloc( struct ofork *of)
     of->of_ad->ad_refcount--;
 
     if ( of->of_ad->ad_refcount <= 0) {
-        free( of->of_ad->ad_m_name );
+        free( of->of_ad->ad_name );
         free( of->of_ad);
-    } else {/* someone's still using it. just free this user's locks */
-        ad_unlock(of->of_ad, of->of_refnum);
     }
 
     free( of );
 }
 
 /* --------------------------- */
-int of_closefork(struct ofork *ofork)
+int of_closefork(const AFPObj *obj, struct ofork *ofork)
 {
     struct timeval      tv;
-    int         adflags, doflush = 0;
+    int         adflags = 0;
     int                 ret;
 
     adflags = 0;
-    if ((ofork->of_flags & AFPFORK_DATA) && (ad_data_fileno( ofork->of_ad ) != -1)) {
+    if (ofork->of_flags & AFPFORK_DATA)
         adflags |= ADFLAGS_DF;
-    }
-    if ( (ofork->of_flags & AFPFORK_OPEN) && ad_reso_fileno( ofork->of_ad ) != -1 ) {
+    if (ofork->of_flags & AFPFORK_META)
         adflags |= ADFLAGS_HF;
-        /*
-         * Only set the rfork's length if we're closing the rfork.
-         */
-        if ((ofork->of_flags & AFPFORK_RSRC)) {
-            ad_refresh( ofork->of_ad );
-            if ((ofork->of_flags & AFPFORK_DIRTY) && !gettimeofday(&tv, NULL)) {
-                ad_setdate(ofork->of_ad, AD_DATE_MODIFY | AD_DATE_UNIX,tv.tv_sec);
-                doflush++;
-            }
-            if ( doflush ) {
-                ad_flush( ofork->of_ad );
-            }
+    if (ofork->of_flags & AFPFORK_RSRC) {
+        adflags |= ADFLAGS_RF;
+        /* Only set the rfork's length if we're closing the rfork. */
+        ad_refresh(NULL, ofork->of_ad );
+        if ((ofork->of_flags & AFPFORK_DIRTY) && !gettimeofday(&tv, NULL)) {
+            ad_setdate(ofork->of_ad, AD_DATE_MODIFY | AD_DATE_UNIX,tv.tv_sec);
+            ad_flush( ofork->of_ad );
         }
     }
 
@@ -438,12 +410,26 @@ int of_closefork(struct ofork *ofork)
         fce_register_file_modification(ofork);
     }
 
+    ad_unlock(ofork->of_ad, ofork->of_refnum, ofork->of_flags & AFPFORK_ERROR ? 0 : 1);
+
+#ifdef HAVE_FSHARE_T
+    if (obj->options.flags & OPTION_SHARE_RESERV) {
+        fshare_t shmd;
+        shmd.f_id = ofork->of_refnum;
+        if (AD_DATA_OPEN(ofork->of_ad))
+            fcntl(ad_data_fileno(ofork->of_ad), F_UNSHARE, &shmd);
+        if (AD_RSRC_OPEN(ofork->of_ad))
+            fcntl(ad_reso_fileno(ofork->of_ad), F_UNSHARE, &shmd);
+    }
+#endif
+
     ret = 0;
-    if ( ad_close( ofork->of_ad, adflags ) < 0 ) {
+    if ( ad_close( ofork->of_ad, adflags | ADFLAGS_SETSHRMD) < 0 ) {
         ret = -1;
     }
 
-    of_dealloc( ofork );
+    of_dealloc(ofork);
+
     return ret;
 }
 
@@ -458,7 +444,7 @@ struct adouble *of_ad(const struct vol *vol, struct path *path, struct adouble *
     if ((of = of_findname(path))) {
         adp = of->of_ad;
     } else {
-        ad_init(ad, vol->v_adouble, vol->v_ad_options);
+        ad_init(ad, vol);
         adp = ad;
     }
     return adp;
@@ -467,7 +453,7 @@ struct adouble *of_ad(const struct vol *vol, struct path *path, struct adouble *
 /* ----------------------
    close all forks for a volume
 */
-void of_closevol(const struct vol *vol)
+void of_closevol(const AFPObj *obj, const struct vol *vol)
 {
     int refnum;
 
@@ -476,7 +462,7 @@ void of_closevol(const struct vol *vol)
 
     for ( refnum = 0; refnum < nforks; refnum++ ) {
         if (oforks[ refnum ] != NULL && oforks[refnum]->of_vol == vol) {
-            if (of_closefork( oforks[ refnum ]) < 0 ) {
+            if (of_closefork(obj, oforks[ refnum ]) < 0 ) {
                 LOG(log_error, logtype_afpd, "of_closevol: %s", strerror(errno) );
             }
         }
@@ -487,7 +473,7 @@ void of_closevol(const struct vol *vol)
 /* ----------------------
    close all forks for a volume
 */
-void of_close_all_forks(void)
+void of_close_all_forks(const AFPObj *obj)
 {
     int refnum;
 
@@ -496,7 +482,7 @@ void of_close_all_forks(void)
 
     for ( refnum = 0; refnum < nforks; refnum++ ) {
         if (oforks[ refnum ] != NULL) {
-            if (of_closefork( oforks[ refnum ]) < 0 ) {
+            if (of_closefork(obj, oforks[ refnum ]) < 0 ) {
                 LOG(log_error, logtype_afpd, "of_close_all_forks: %s", strerror(errno) );
             }
         }
index 577ddab795961a2fd35be68614ba9745ba20011f..4953d798f06d43c7e34da0b337a0bb80036533b2 100644 (file)
 #include <string.h>
 #include <errno.h>
 #include <sys/types.h>
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
 #include <sys/stat.h>
 #include <sys/time.h>
 #include <sys/param.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 
 #include <atalk/logger.h>
 #include <atalk/afp.h>
@@ -51,8 +34,8 @@ char *strchr (), *strrchr ();
 #include <quota/quota.h>
 
 static int
-getfreespace(struct vol *vol, VolSpace *bfree, VolSpace *btotal,
-    uid_t uid, const char *classq)
+getfreespace(const AFPObj *obj, struct vol *vol, VolSpace *bfree, VolSpace *btotal,
+            uid_t uid, const char *classq)
 {
        int retq;
        struct ufs_quota_entry ufsq[QUOTA_NLIMITS];
@@ -69,7 +52,7 @@ getfreespace(struct vol *vol, VolSpace *bfree, VolSpace *btotal,
                    strerror(errno));
                return -1;
        }
-       if ((retq = getfsquota(vol->v_path, ufsq, uid, classq)) < 0) {
+       if ((retq = getfsquota(obj, vol, ufsq, uid, classq)) < 0) {
                LOG(log_info, logtype_afpd, "getfsquota(%s, %s): %s",
                    vol->v_path, classq, strerror(errno));
        }
@@ -95,19 +78,19 @@ getfreespace(struct vol *vol, VolSpace *bfree, VolSpace *btotal,
        return 1;
 }
 
-int uquota_getvolspace( struct vol *vol, VolSpace *bfree, VolSpace *btotal, const u_int32_t bsize)
+int uquota_getvolspace(const AFPObj *obj, struct vol *vol, VolSpace *bfree, VolSpace *btotal, const u_int32_t bsize)
 {
        int uretq, gretq;
        VolSpace ubfree, ubtotal;
        VolSpace gbfree, gbtotal;
 
-       uretq = getfreespace(vol, &ubfree, &ubtotal,
-           uuid, QUOTADICT_CLASS_USER);
+       uretq = getfreespace(obj, vol, &ubfree, &ubtotal,
+                            uuid, QUOTADICT_CLASS_USER);
        LOG(log_info, logtype_afpd, "getfsquota(%s): %d %d",
            vol->v_path, (int)ubfree, (int)ubtotal);
-       if (ngroups >= 1) {
+       if (obj->ngroups >= 1) {
                gretq = getfreespace(vol, &ubfree, &ubtotal,
-                   groups[0], QUOTADICT_CLASS_GROUP);
+                   obj->groups[0], QUOTADICT_CLASS_GROUP);
        } else
                gretq = -1;
        if (uretq < 1 && gretq < 1) { /* no quota for this fs */
@@ -292,13 +275,13 @@ static int get_linux_xfs_quota(int what, char *path, uid_t euser_id, struct dqbl
        if ((ret = quotactl(QCMD(Q_XGETQUOTA,(what ? GRPQUOTA : USRQUOTA)), path, euser_id, (caddr_t)&D)))
                return ret;
 
-       dqb->bsize = (u_int64_t)512;
-        dqb->dqb_bsoftlimit  = (u_int64_t)D.d_blk_softlimit;
-        dqb->dqb_bhardlimit  = (u_int64_t)D.d_blk_hardlimit;
-        dqb->dqb_ihardlimit  = (u_int64_t)D.d_ino_hardlimit;
-        dqb->dqb_isoftlimit  = (u_int64_t)D.d_ino_softlimit;
-        dqb->dqb_curinodes   = (u_int64_t)D.d_icount;
-        dqb->dqb_curblocks   = (u_int64_t)D.d_bcount; 
+       dqb->bsize = (uint64_t)512;
+        dqb->dqb_bsoftlimit  = (uint64_t)D.d_blk_softlimit;
+        dqb->dqb_bhardlimit  = (uint64_t)D.d_blk_hardlimit;
+        dqb->dqb_ihardlimit  = (uint64_t)D.d_ino_hardlimit;
+        dqb->dqb_isoftlimit  = (uint64_t)D.d_ino_softlimit;
+        dqb->dqb_curinodes   = (uint64_t)D.d_icount;
+        dqb->dqb_curblocks   = (uint64_t)D.d_bcount; 
 #endif
        return ret;
 }
@@ -518,7 +501,7 @@ special(char *file, int *nfs)
 #endif /* __svr4__ */
 
 
-static int getfsquota(struct vol *vol, const int uid, struct dqblk *dq)
+static int getfsquota(const AFPObj *obj, struct vol *vol, const int uid, struct dqblk *dq)
 
 {
        struct dqblk dqg;
@@ -562,9 +545,9 @@ static int getfsquota(struct vol *vol, const int uid, struct dqblk *dq)
         if ( quotactl( vol->v_path, QCMD(Q_GETQUOTA,USRQUOTA),
                        uid, (char *)dq ) != 0 ) {
             /* try group quotas */
-            if (ngroups >= 1) {
+            if (obj->ngroups >= 1) {
                 if ( quotactl(vol->v_path, QCMD(Q_GETQUOTA, GRPQUOTA),
-                              groups[0], (char *) &dqg) != 0 ) {
+                              obj->groups[0], (char *) &dqg) != 0 ) {
                     seteuid( uid );
                     return( AFPERR_PARAM );
                 }
@@ -607,12 +590,12 @@ static int getfsquota(struct vol *vol, const int uid, struct dqblk *dq)
     if( 
         /* if overquota, free space is 0 otherwise hard-current */
         ( overquota( dq ) ? 0 : ( dq->dqb_bhardlimit ? dq->dqb_bhardlimit - 
-                                  dq->dqb_curblocks : ~((u_int64_t) 0) ) )
+                                  dq->dqb_curblocks : ~((uint64_t) 0) ) )
 
       >
         
         ( overquota( &dqg ) ? 0 : ( dqg.dqb_bhardlimit ? dqg.dqb_bhardlimit - 
-                                    dqg.dqb_curblocks : ~((u_int64_t) 0) ) )
+                                    dqg.dqb_curblocks : ~((uint64_t) 0) ) )
 
       ) /* if */
     {
@@ -632,7 +615,7 @@ static int getfsquota(struct vol *vol, const int uid, struct dqblk *dq)
 }
 
 
-static int getquota( struct vol *vol, struct dqblk *dq, const u_int32_t bsize)
+static int getquota(const AFPObj *obj, struct vol *vol, struct dqblk *dq, const uint32_t bsize)
 {
     char *p;
 
@@ -707,11 +690,11 @@ static int getquota( struct vol *vol, struct dqblk *dq, const u_int32_t bsize)
            return getnfsquota(vol, uuid, bsize, dq);
     } else
        /* local filesystem */
-       return getfsquota(vol, uuid, dq);
+      return getfsquota(obj, vol, obj->uid, dq);
           
 #else /* TRU64 */
-    return vol->v_nfs ? getnfsquota(vol, uuid, bsize, dq) :
-           getfsquota(vol, uuid, dq);
+    return vol->v_nfs ? getnfsquota(vol, obj->uid, bsize, dq) :
+      getfsquota(obj, vol, obj->uid, dq);
 #endif /* TRU64 */
 }
 
@@ -770,14 +753,14 @@ static int overquota( struct dqblk *dqblk)
 #define tobytes(a, b)  dbtob((VolSpace) (a))
 #endif
 
-int uquota_getvolspace( struct vol *vol, VolSpace *bfree, VolSpace *btotal, const u_int32_t bsize)
+int uquota_getvolspace(const AFPObj *obj, struct vol *vol, VolSpace *bfree, VolSpace *btotal, const uint32_t bsize)
 {
-       u_int64_t this_bsize;
+       uint64_t this_bsize;
        struct dqblk dqblk;
 
        this_bsize = bsize;
                        
-       if (getquota( vol, &dqblk, bsize) != 0 ) {
+       if (getquota(obj, vol, &dqblk, bsize) != 0 ) {
                return( AFPERR_PARAM );
        }
 
index acb363a3e9d4ef8ecb9076e79ab93894b0ffce2e..f42bf5ec0ef97d657caca080f4a095b36f3db6b4 100644 (file)
@@ -7,6 +7,7 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #endif /* BSD4_4 */
 #endif
 
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
+#ifdef HAVE_KERBEROS
+#ifdef HAVE_KRB5_KRB5_H
+#include <krb5/krb5.h>
+#else
+#include <krb5.h>
+#endif /* HAVE_KRB5_KRB5_H */
+#endif /* HAVE_KERBEROS */
+
 #include <atalk/dsi.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-#include <atalk/nbp.h>
 #include <atalk/unicode.h>
 #include <atalk/util.h>
 #include <atalk/globals.h>
 #include "status.h"
 #include "afp_config.h"
 #include "icon.h"
+#include "uam_auth.h"
 
 static   size_t maxstatuslen = 0;
 
-static void status_flags(char *data, const int notif, const int ipok,
-                         const unsigned char passwdbits, const int dirsrvcs _U_, int flags)
+static int uam_gss_enabled()
+{
+    /* XXX: must be a better way to find out if uam_gss is active */
+    return auth_uamfind(UAM_SERVER_LOGIN_EXT,
+                        "Client Krb v2",
+                        sizeof("Client Krb v2")) != NULL;
+}
+
+static void status_flags(char *data,
+                         const int notif,
+                         const int ipok,
+                         const unsigned char passwdbits,
+                         const int dirsrvcs,
+                         int flags)
 {
     uint16_t           status;
 
@@ -53,7 +72,6 @@ static void status_flags(char *data, const int notif, const int ipok,
            | AFPSRVRINFO_SRVSIGNATURE
            | AFPSRVRINFO_SRVMSGS
            | AFPSRVRINFO_FASTBOZO
-           | AFPSRVRINFO_SRVRDIR
            | AFPSRVRINFO_SRVUTF8
            | AFPSRVRINFO_EXTSLEEP;
 
@@ -61,10 +79,12 @@ static void status_flags(char *data, const int notif, const int ipok,
         status |= AFPSRVRINFO_PASSWD;
     if (passwdbits & PASSWD_NOSAVE)
         status |= AFPSRVRINFO_NOSAVEPASSWD;
-    if (ipok) /* only advertise tcp/ip if we have a valid address */        
+    if (ipok) /* only advertise tcp/ip if we have a valid address */
         status |= AFPSRVRINFO_TCPIP;
-    if (notif) /* Default is yes */        
+    if (notif) /* Default is yes */
         status |= AFPSRVRINFO_SRVNOTIFY;
+    if (dirsrvcs)
+        status |= AFPSRVRINFO_SRVRDIR;
     if (flags & OPTION_UUID)
         status |= AFPSRVRINFO_UUID;
 
@@ -77,7 +97,7 @@ static int status_server(char *data, const char *server, const struct afp_option
     char                *start = data;
     char                *Obj, *Type, *Zone;
     char               buf[32];
-    u_int16_t           status;
+    uint16_t           status;
     size_t             len;
 
     /* make room for all offsets before server name */
@@ -85,9 +105,6 @@ static int status_server(char *data, const char *server, const struct afp_option
 
     /* extract the obj part of the server */
     Obj = (char *) server;
-#ifndef NO_DDP
-    nbp_name(server, &Obj, &Type, &Zone);
-#endif
     if ((size_t)-1 == (len = convert_string( 
                            options->unixcharset, options->maccharset, 
                            Obj, -1, buf, sizeof(buf))) ) {
@@ -125,7 +142,7 @@ static int status_server(char *data, const char *server, const struct afp_option
 static void status_machine(char *data)
 {
     char                *start = data;
-    u_int16_t           status;
+    uint16_t           status;
     int                        len;
 #ifdef AFS
     const char         *machine = "afs";
@@ -160,11 +177,11 @@ static void status_machine(char *data)
 }
 
 /* server signature is a 16-byte quantity */
-static u_int16_t status_signature(char *data, int *servoffset,
+static uint16_t status_signature(char *data, int *servoffset,
                                   const struct afp_options *options)
 {
     char                 *status;
-    u_int16_t            offset, sigoff;
+    uint16_t            offset, sigoff;
 
     status = data;
 
@@ -187,14 +204,11 @@ static u_int16_t status_signature(char *data, int *servoffset,
 }
 
 static size_t status_netaddress(char *data, int *servoffset,
-#ifndef NO_DDP
-                                const ASP asp,
-#endif
-                                const DSI *dsi,
-                                const struct afp_options *options)
+                             const DSI *dsi,
+                             const struct afp_options *options)
 {
     char               *begin;
-    u_int16_t          offset;
+    uint16_t          offset;
     size_t             addresses_len = 0;
 
     begin = data;
@@ -215,9 +229,6 @@ static size_t status_netaddress(char *data, int *servoffset,
        connection, but we don't have the ip address. to get around this,
        we turn off the status flag for tcp/ip. */
     *data++ = ((options->fqdn && dsi)? 1 : 0) + (dsi ? 1 : 0) +
-#ifndef NO_DDP
-        (asp ? 1 : 0) +
-#endif
               (((options->flags & OPTION_ANNOUNCESSH) && options->fqdn && dsi)? 1 : 0);
 
     /* ip address */
@@ -291,23 +302,6 @@ static size_t status_netaddress(char *data, int *servoffset,
         }
     }
 
-#ifndef NO_DDP
-    if (asp) {
-        const struct sockaddr_at *ddpaddr = atp_sockaddr(asp->asp_atp);
-
-        /* ddp address */
-        *data++ = 6;
-        *data++ = 0x03; /* ddp address */
-        memcpy(data, &ddpaddr->sat_addr.s_net, sizeof(ddpaddr->sat_addr.s_net));
-        data += sizeof(ddpaddr->sat_addr.s_net);
-        memcpy(data, &ddpaddr->sat_addr.s_node,
-               sizeof(ddpaddr->sat_addr.s_node));
-        data += sizeof(ddpaddr->sat_addr.s_node);
-        memcpy(data, &ddpaddr->sat_port, sizeof(ddpaddr->sat_port));
-        data += sizeof(ddpaddr->sat_port);
-    }
-#endif /* ! NO_DDP */
-
     /* calculate/store Directory Services Names offset */
     offset = htons(data - begin); 
     *servoffset += sizeof(offset);
@@ -317,54 +311,184 @@ static size_t status_netaddress(char *data, int *servoffset,
     return (data - begin);
 }
 
-static size_t status_directorynames(char *data, int *diroffset, 
-                                const DSI *dsi _U_, 
-                                const struct afp_options *options)
+static bool append_directoryname(char **pdata,
+                                 size_t offset,
+                                 size_t *size,
+                                 char* DirectoryNamesCount,
+                                 size_t len,
+                                 char *principal)
+{
+    if (sizeof(uint8_t) + len  > maxstatuslen - offset - *size) {
+        LOG(log_error, logtype_afpd,
+            "status:DirectoryNames: out of space for principal '%s' (len=%d)",
+            principal, len);
+        return false;
+    } else if (len > 255) {
+        LOG(log_error, logtype_afpd,
+            "status:DirectoryNames: principal '%s' (len=%d) too long (max=255)",
+            principal, len);
+        return false;
+    }
+
+    LOG(log_info, logtype_afpd,
+        "DirectoryNames[%d]=%s",
+        *DirectoryNamesCount, principal);
+
+    *DirectoryNamesCount += 1;
+    char *data = *pdata;
+    *data++ = len;
+    strncpy(data, principal, len);
+
+    *pdata += len + 1;
+    *size += sizeof(uint8_t) + len;
+
+    return true;
+}
+
+/**
+ * DirectoryNamesCount offset: uint16_t
+ * ...
+ * DirectoryNamesCount: uint8_t
+ * DirectoryNames: list of UTF-8 Pascal strings (uint8_t + char[1,255])
+ */
+static size_t status_directorynames(char *data,
+                                    int *diroffset,
+                                    const DSI *dsi _U_,
+                                    const struct afp_options *options _U_)
 {
     char *begin = data;
-    u_int16_t offset;
-    memcpy(&offset, data + *diroffset, sizeof(offset));
+    uint16_t offset;
+
+    memcpy(&offset, begin + *diroffset, sizeof(offset));
     offset = ntohs(offset);
     data += offset;
 
-    /* I can not find documentation of any other purpose for the
-     * DirectoryNames field.
-     */
-    /*
-     * Try to synthesize a principal:
-     * service '/' fqdn '@' realm
-     */
-    if (options->k5service && options->k5realm && options->fqdn) {
-       /* should k5princ be utf8 encoded? */
-       size_t len;
-       char *p = strchr( options->fqdn, ':' );
-       if (p) 
-           *p = '\0';
-       len = strlen( options->k5service ) 
-                       + strlen( options->fqdn )
-                       + strlen( options->k5realm );
-       len+=2; /* '/' and '@' */
-       if ( len > 255 || len+2 > maxstatuslen - offset) {
-           *data++ = 0;
-           LOG ( log_error, logtype_afpd, "status: could not set directory service list, no more room");
-       }        
-       else {
-           *data++ = 1; /* DirectoryNamesCount */
-           *data++ = len;
-           snprintf( data, len + 1, "%s/%s@%s", options->k5service,
-                               options->fqdn, options->k5realm );
-           data += len;
-           if (p)
-               *p = ':';
-       }
+    char *DirectoryNamesCount = data++;
+    char *DirectoryNames = data;
+    size_t size = sizeof(uint8_t);
+    *DirectoryNamesCount = 0;
+
+    if (!uam_gss_enabled())
+        goto offset_calc;
+
+#ifdef HAVE_KERBEROS
+    krb5_context context;
+    krb5_error_code ret;
+    const char *error_msg;
+
+    if (krb5_init_context(&context)) {
+        LOG(log_error, logtype_afpd,
+            "status:DirectoryNames failed to intialize a krb5_context");
+        goto offset_calc;
+    }
+
+    krb5_keytab keytab;
+    if ((ret = krb5_kt_default(context, &keytab)))
+        goto krb5_error;
+
+    // figure out which service principal to use
+    krb5_keytab_entry entry;
+    char *principal;
+    if (options->k5service && options->fqdn && options->k5realm) {
+        LOG(log_debug, logtype_afpd,
+            "status:DirectoryNames: using service principal specified in options");
+
+        krb5_principal service_principal;
+        if ((ret = krb5_build_principal(context,
+                                        &service_principal,
+                                        strlen(options->k5realm),
+                                        options->k5realm,
+                                        options->k5service,
+                                        options->fqdn,
+                                        NULL)))
+            goto krb5_error;
+
+        // try to get the given service principal from keytab
+        ret = krb5_kt_get_entry(context,
+                                keytab,
+                                service_principal,
+                                0, // kvno - wildcard
+                                0, // enctype - wildcard
+                                &entry);
+        if (ret == KRB5_KT_NOTFOUND) {
+            krb5_unparse_name(context, service_principal, &principal);
+            LOG(log_error, logtype_afpd,
+                "status:DirectoryNames: specified service principal '%s' not found in keytab",
+                principal);
+            // XXX: should this be krb5_xfree?
+#ifdef HAVE_KRB5_FREE_UNPARSED_NAME
+            krb5_free_unparsed_name(context, principal);
+#else
+           krb5_xfree(principal);
+#endif
+            goto krb5_cleanup;
+        }
+        krb5_free_principal(context, service_principal);
+        if (ret)
+            goto krb5_error;
     } else {
-       *data++ = 0;
+        LOG(log_debug, logtype_afpd,
+            "status:DirectoryNames: using first entry from keytab as service principal");
+
+        krb5_kt_cursor cursor;
+        if ((ret = krb5_kt_start_seq_get(context, keytab, &cursor)))
+            goto krb5_error;
+
+        ret = krb5_kt_next_entry(context, keytab, &entry, &cursor);
+        krb5_kt_end_seq_get(context, keytab, &cursor);
+        if (ret)
+            goto krb5_error;
     }
 
+    krb5_unparse_name(context, entry.principal, &principal);
+    krb5_kt_free_entry(context, &entry);
+
+    append_directoryname(&data,
+                         offset,
+                         &size,
+                         DirectoryNamesCount,
+                         strlen(principal),
+                         principal);
+
+    free(principal);
+    goto krb5_cleanup;
+
+krb5_error:
+    if (ret) {
+        error_msg = krb5_get_error_message(context, ret);
+        LOG(log_note, logtype_afpd, "Can't get principal from default keytab: %s",
+            (char *)error_msg);
+#ifdef HAVE_KRB5_FREE_ERROR_MESSAGE
+        krb5_free_error_message(context, error_msg);
+#else
+       krb5_xfree(error_msg);
+#endif
+    }
+
+krb5_cleanup:
+    krb5_kt_close(context, keytab);
+    krb5_free_context(context);
+#else
+    if (!options->k5service || !options->fqdn || !options->k5realm)
+        goto offset_calc;
+
+    char principal[255];
+    size_t len = snprintf(principal, sizeof(principal), "%s/%s@%s",
+                          options->k5service, options->fqdn, options->k5realm);
+
+    append_directoryname(&data,
+                         offset,
+                         &size,
+                         DirectoryNamesCount,
+                         strlen(principal),
+                         principal);
+#endif // HAVE_KERBEROS
+
+offset_calc:
     /* Calculate and store offset for UTF8ServerName */
-    *diroffset += sizeof(u_int16_t);
+    *diroffset += sizeof(uint16_t);
     offset = htons(data - begin);
-    memcpy(begin + *diroffset, &offset, sizeof(u_int16_t));
+    memcpy(begin + *diroffset, &offset, sizeof(uint16_t));
 
     /* return length of buffer */
     return (data - begin);
@@ -374,45 +498,35 @@ static size_t status_utf8servername(char *data, int *nameoffset,
                                 const DSI *dsi _U_,
                                 const struct afp_options *options)
 {
-    char *Obj, *Type, *Zone;
-    u_int16_t namelen;
+    uint16_t namelen;
     size_t len;
     char *begin = data;
-    u_int16_t offset, status;
+    uint16_t offset, status;
 
     memcpy(&offset, data + *nameoffset, sizeof(offset));
     offset = ntohs(offset);
     data += offset;
 
-    /* FIXME:
-     * What is the valid character range for an nbpname?
-     *
-     * Apple's server likes to use the non-qualified hostname
-     * This obviously won't work very well if multiple servers are running
-     * on the box.
-     */
+    LOG(log_info, logtype_afpd, "servername: %s", options->hostname);
 
-    /* extract the obj part of the server */
-    Obj = (char *) (options->server ? options->server : options->hostname);
-#ifndef NO_DDP
-    nbp_name(options->server ? options->server : options->hostname, &Obj, &Type, &Zone);
-#endif
-    if ((size_t) -1 == (len = convert_string (
-                                       options->unixcharset, CH_UTF8_MAC, 
-                                       Obj, -1, data+sizeof(namelen), maxstatuslen-offset )) ) {
-       LOG ( log_error, logtype_afpd, "Could not set utf8 servername");
+    if ((len = convert_string(options->unixcharset,
+                              CH_UTF8_MAC, 
+                              options->hostname,
+                              -1,
+                              data + sizeof(namelen),
+                              maxstatuslen-offset)) == (size_t)-1) {
+        LOG(log_error, logtype_afpd, "Could not set utf8 servername");
 
-       /* set offset to 0 */
-       memset(begin + *nameoffset, 0, sizeof(offset));
+        /* set offset to 0 */
+        memset(begin + *nameoffset, 0, sizeof(offset));
         data = begin + offset;
-    }
-    else {
+    } else {
        namelen = htons(len);
        memcpy( data, &namelen, sizeof(namelen));
        data += sizeof(namelen);
        data += len;
        offset = htons(offset);
-       memcpy(begin + *nameoffset, &offset, sizeof(u_int16_t));
+       memcpy(begin + *nameoffset, &offset, sizeof(uint16_t));
     }
 
     /* return length of buffer */
@@ -426,7 +540,7 @@ static void status_icon(char *data, const unsigned char *icondata,
 {
     char                *start = data;
     char                *sigdata = data + sigoffset;
-    u_int16_t          ret, status;
+    uint16_t           ret, status;
 
     memcpy(&status, start + AFPSTATUS_ICONOFF, sizeof(status));
     if ( icondata == NULL ) {
@@ -446,48 +560,27 @@ static void status_icon(char *data, const unsigned char *icondata,
 
 /* ---------------------
  */
-void status_init(AFPConfig *aspconfig, AFPConfig *dsiconfig,
-                 const struct afp_options *options)
+void status_init(AFPObj *obj, DSI *dsi)
 {
-#ifndef NO_DDP
-    ASP asp;
-#endif
-    DSI *dsi;
-    char *status = NULL;
+    char *status = dsi->status;
     size_t statuslen;
-    int c, sigoff, ipok;
-
-    if (!(aspconfig || dsiconfig) || !options)
-        return;
-
-#ifndef NO_DDP
-    if (aspconfig) {
-        status = aspconfig->status;
-        maxstatuslen=sizeof(aspconfig->status);
-        asp = aspconfig->obj.handle;
-    } else
-        asp = NULL;
-#endif
-       
-    ipok = 0;
-    if (dsiconfig) {
-        status = dsiconfig->status;
-        maxstatuslen=sizeof(dsiconfig->status);
-        dsi = dsiconfig->obj.handle;
-        if (dsi->server.ss_family == AF_INET) { /* IPv4 */
-            const struct sockaddr_in *sa4 = (struct sockaddr_in *)&dsi->server;
-            ipok = sa4->sin_addr.s_addr ? 1 : 0;
-        } else { /* IPv6 */
-            const struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&dsi->server;
-            for (int i=0; i<16; i++) {
-                if (sa6->sin6_addr.s6_addr[i]) {
-                    ipok = 1;
-                    break;
-                }
+    int c, sigoff, ipok = 0;
+    const struct afp_options *options = &obj->options;
+
+    maxstatuslen = sizeof(dsi->status);
+
+    if (dsi->server.ss_family == AF_INET) { /* IPv4 */
+        const struct sockaddr_in *sa4 = (struct sockaddr_in *)&dsi->server;
+        ipok = sa4->sin_addr.s_addr ? 1 : 0;
+    } else { /* IPv6 */
+        const struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&dsi->server;
+        for (int i=0; i<16; i++) {
+            if (sa6->sin6_addr.s6_addr[i]) {
+                ipok = 1;
+                break;
             }
         }
-    } else
-        dsi = NULL;
+    }
 
     /*
      * These routines must be called in order -- earlier calls
@@ -510,34 +603,22 @@ void status_init(AFPConfig *aspconfig, AFPConfig *dsiconfig,
      */
 
     status_flags(status,
-                 options->server_notif,
+                 options->flags & OPTION_SERVERNOTIF,
                  (options->fqdn || ipok),
                  options->passwdbits, 
-                 (options->k5service && options->k5realm && options->fqdn),
+                 1,
                  options->flags);
     /* returns offset to signature offset */
-    c = status_server(status, options->server ? options->server :
-                      options->hostname, options);
+    c = status_server(status, options->hostname, options);
     status_machine(status);
-    status_versions(status,
-#ifndef NO_DDP
-                    asp,
-#endif
-                    dsi);
+    status_versions(status, dsi);
     status_uams(status, options->uamlist);
-    if (options->flags & OPTION_CUSTOMICON)
-        status_icon(status, icon, sizeof(icon), c);
-    else
-        status_icon(status, apple_atalk_icon, sizeof(apple_atalk_icon), c);
+    status_icon(status, icon, sizeof(icon), c);
 
     sigoff = status_signature(status, &c, options);
     /* c now contains the offset where the netaddress offset lives */
 
-    status_netaddress(status, &c,
-#ifndef NO_DDP
-                      asp,
-#endif
-                      dsi, options);
+    status_netaddress(status, &c, dsi, options);
     /* c now contains the offset where the Directory Names Count offset lives */
 
     statuslen = status_directorynames(status, &c, dsi, options);
@@ -546,24 +627,8 @@ void status_init(AFPConfig *aspconfig, AFPConfig *dsiconfig,
     if ( statuslen < maxstatuslen) 
         statuslen = status_utf8servername(status, &c, dsi, options);
 
-#ifndef NO_DDP
-    if (aspconfig) {
-        if (dsiconfig) /* status is dsiconfig->status */
-            memcpy(aspconfig->status, status, statuslen);
-        asp_setstatus(asp, status, statuslen);
-        aspconfig->signature = status + sigoff;
-        aspconfig->statuslen = statuslen;
-    }
-#endif /* ! NO_DDP */
-
-    if (dsiconfig) {
-        if ((options->flags & OPTION_CUSTOMICON) == 0) {
-            status_icon(status, apple_tcp_icon, sizeof(apple_tcp_icon), 0);
-        }
-        dsi_setstatus(dsi, status, statuslen);
-        dsiconfig->signature = status + sigoff;
-        dsiconfig->statuslen = statuslen;
-    }
+    dsi->signature = status + sigoff;
+    dsi->statuslen = statuslen;
 }
 
 /* set_signature()                                                    */
@@ -572,10 +637,9 @@ void status_init(AFPConfig *aspconfig, AFPConfig *dsiconfig,
 /* If not found in conf file, genarate and append in conf file.       */
 /* If conf file don't exist, create and genarate.                     */
 /* If cannot open conf file, use one-time signature.                  */
-/* If -signature user:xxxxx, use it.                                  */
+/* If signature = xxxxx, use it.                                      */
 
 void set_signature(struct afp_options *options) {
-    char *usersign;
     int fd, i;
     struct stat tmpstat;
     char *servername_conf;
@@ -585,39 +649,27 @@ void set_signature(struct afp_options *options) {
     size_t len;
     char *server_tmp;
     
-    server_tmp = (options->server ? options->server : options->hostname);
-    if (strcmp(options->signatureopt, "auto") == 0) {
+    server_tmp = options->hostname;
+    len = strlen(options->signatureopt);
+    if (len == 0) {
         goto server_signature_auto;   /* default */
-    } else if (strcmp(options->signatureopt, "host") == 0) {
-        LOG(log_warning, logtype_afpd, "WARNING: option \"-signature host\" is obsoleted. Switching back to auto.", options->signatureopt);
-        goto server_signature_auto;   /* same as auto */
-    } else if (strncmp(options->signatureopt, "user", 4) == 0) {
-        goto server_signature_user;   /*  user string */
+    } else if (len < 3) {
+        LOG(log_warning, logtype_afpd, "WARNING: signature string %s is very short !", options->signatureopt);
+        goto server_signature_user;
+    } else if (len > 16) {
+        LOG(log_warning, logtype_afpd, "WARNING: signature string %s is very long !", options->signatureopt);
+        len = 16;
+        goto server_signature_user;
     } else {
-        LOG(log_error, logtype_afpd, "ERROR: option \"-signature %s\" is not valid. Switching back to auto.", options->signatureopt);
-        goto server_signature_auto;   /* switch back to auto*/
+        LOG(log_info, logtype_afpd, "signature string is %s.", options->signatureopt);
+        goto server_signature_user;
     }
     
 server_signature_user:
     
-    /* Signature type is user string */
-    len = strlen(options->signatureopt);
-    if (len <= 5) {
-        LOG(log_warning, logtype_afpd, "WARNING: option \"-signature %s\" is not valid. Switching back to auto.", options->signatureopt);
-        goto server_signature_auto;
-    }
-    usersign = options->signatureopt + 5;
-    len = len - 5;
-    if (len > 16) {
-        LOG(log_warning, logtype_afpd, "WARNING: signature user string %s is very long !",  usersign);
-        len = 16;
-    } else if (len >= 3) {
-        LOG(log_info, logtype_afpd, "signature user string is %s.", usersign);
-    } else {
-        LOG(log_warning, logtype_afpd, "WARNING: signature user string %s is very short !",  usersign);
-    }
+    /* Signature is defined in afp.conf */
     memset(options->signature, 0, 16);
-    memcpy(options->signature, usersign, len);
+    memcpy(options->signature, options->signatureopt, len);
     goto server_signature_done;
     
 server_signature_auto:
@@ -712,7 +764,7 @@ server_signature_random:
         fprintf(fp, "# ServerSignature is unique identifier used to prevent logging on to\n");
         fprintf(fp, "# the same server twice.\n");
         fprintf(fp, "# \n");
-        fprintf(fp, "# If setting \"-signature user:xxxxx\" in afpd.conf, this file is not used.\n\n");
+        fprintf(fp, "# If setting \"signature = xxxxx\" in afp.conf, this file is not used.\n\n");
     }
     
     if (fp) {
@@ -728,8 +780,7 @@ server_signature_done:
     
     /* retrun */
     LOG(log_info, logtype_afpd,
-        " \"%s\"'s signature is  %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
-        server_tmp,
+        "signature is %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
         (options->signature)[ 0], (options->signature)[ 1],
         (options->signature)[ 2], (options->signature)[ 3],
         (options->signature)[ 4], (options->signature)[ 5],
@@ -745,9 +796,8 @@ server_signature_done:
 /* this is the same as asp/dsi_getstatus */
 int afp_getsrvrinfo(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
-    AFPConfig *config = obj->config;
+    memcpy(rbuf, obj->dsi->status, obj->dsi->statuslen);
+    *rbuflen = obj->dsi->statuslen;
 
-    memcpy(rbuf, config->status, config->statuslen);
-    *rbuflen = config->statuslen;
     return AFP_OK;
 }
index 17753f95c77211a78a987f3621101272ee5cd3e2..343774aebb9681df85c00244f875e409f5263822 100644 (file)
@@ -1,9 +1,7 @@
 #ifndef AFPD_STATUS_H
 #define AFPD_STATUS_H 1
 
-#include <sys/cdefs.h>
 #include <atalk/dsi.h>
-#include <atalk/asp.h>
 #include <atalk/globals.h>
 
 #include "afp_config.h"
 /* AFPSTATUS_MACHLEN is the number of characters for the MachineType. */
 #define AFPSTATUS_MACHLEN     16
 
-
-#define PASSWD_NONE     0
-#define PASSWD_SET     (1 << 0)
-#define PASSWD_NOSAVE  (1 << 1)
-#define PASSWD_ALL     (PASSWD_SET | PASSWD_NOSAVE)
-
-extern void status_versions (char * /*status*/,
-#ifndef NO_DDP
-                             const ASP,
-#endif
-                             const DSI *);
+extern void status_versions (char * /*status*/, const DSI *);
 extern void status_uams (char * /*status*/, const char * /*authlist*/);
-extern void status_init (AFPConfig *, AFPConfig *,
-                                 const struct afp_options *);
+extern void status_init (AFPObj *, DSI *dsi);
 extern void set_signature(struct afp_options *);
 
 /* FP functions */
index 7a1c034e317ab6119042f405650ab9678f2d36bf..d99d381edd38cc4408a5076039ef47f53d4e7899 100644 (file)
 
 #include <stdio.h>
 #include <stdlib.h>
-
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <ctype.h>
 #include <atalk/logger.h>
 #include <sys/param.h>
@@ -45,19 +26,16 @@ char *strchr (), *strrchr ();
 #include <netinet/in.h>
 #include <arpa/inet.h>
 
-#include <netatalk/endian.h>
-#include <atalk/asp.h>
 #include <atalk/dsi.h>
 #include <atalk/afp.h>
 #include <atalk/util.h>
 #include <atalk/globals.h>
+#include <atalk/volume.h>
 
 #include "afp_config.h"
 #include "auth.h"
 #include "uam_auth.h"
 
-#define utf8_encoding() (afp_version >= 30)
-
 #ifdef TRU64
 #include <netdb.h>
 #include <sia.h>
@@ -254,7 +232,7 @@ struct passwd *uam_getname(void *private, char *name, const int len)
     }
 #ifndef NO_REAL_USER_NAME
 
-    if ( (size_t) -1 == (namelen = convert_string((utf8_encoding())?CH_UTF8_MAC:obj->options.maccharset,
+    if ( (size_t) -1 == (namelen = convert_string((utf8_encoding(obj))?CH_UTF8_MAC:obj->options.maccharset,
                                CH_UCS2, name, -1, username, sizeof(username))))
        return NULL;
 
@@ -317,7 +295,7 @@ int uam_checkuser(const struct passwd *pwd)
 
 int uam_random_string (AFPObj *obj, char *buf, int len)
 {
-    u_int32_t result;
+    uint32_t result;
     int ret;
     int fd;
 
@@ -332,7 +310,7 @@ int uam_random_string (AFPObj *obj, char *buf, int len)
 
         if (gettimeofday(&tv, &tz) < 0)
             return -1;
-        srandom(tv.tv_sec + (unsigned long) obj + (unsigned long) obj->handle);
+        srandom(tv.tv_sec + (unsigned long) obj + (unsigned long) obj->dsi);
         for (i = 0; i < len; i += sizeof(result)) {
             result = random();
             memcpy(buf + i, &result, sizeof(result));
@@ -359,7 +337,7 @@ int uam_afpserver_option(void *private, const int what, void *option,
 
     switch (what) {
     case UAM_OPTION_USERNAME:
-        *buf = obj->username;
+        *buf = &(obj->username[0]);
         if (len)
             *len = sizeof(obj->username) - 1;
         break;
@@ -385,11 +363,6 @@ int uam_afpserver_option(void *private, const int what, void *option,
             *len = sizeof(obj->options.passwdminlen);
             break;
 
-        case UAM_PASSWD_MAXFAIL:
-            *((int *) option) = obj->options.loginmaxfail;
-            *len = sizeof(obj->options.loginmaxfail);
-            break;
-
         case UAM_PASSWD_EXPIRETIME: /* not implemented */
         default:
             return -1;
@@ -398,7 +371,7 @@ int uam_afpserver_option(void *private, const int what, void *option,
         break;
 
     case UAM_OPTION_SIGNATURE:
-        *buf = (void *) (((AFPConfig *)obj->config)->signature);
+        *buf = (void *)obj->dsi->signature;
         if (len)
             *len = 16;
         break;
@@ -416,13 +389,9 @@ int uam_afpserver_option(void *private, const int what, void *option,
             *len = strlen(obj->options.hostname);
         break;
 
-    case UAM_OPTION_PROTOCOL:
-        *((int *) option) = obj->proto;
-        break;
-        
     case UAM_OPTION_CLIENTNAME:
     {
-        struct DSI *dsi = obj->handle;
+        struct DSI *dsi = obj->dsi;
         const struct sockaddr *sa;
         static char hbuf[NI_MAXHOST];
         
@@ -487,31 +456,18 @@ int uam_afp_read(void *handle, char *buf, size_t *buflen,
     if (!obj)
         return AFPERR_PARAM;
 
-    switch (obj->proto) {
-#ifndef NO_DDP
-    case AFPPROTO_ASP:
-        if ((len = asp_wrtcont(obj->handle, buf, buflen )) < 0)
-            goto uam_afp_read_err;
-        return action(handle, buf, *buflen);
-        break;
-#endif
-    case AFPPROTO_DSI:
-        len = dsi_writeinit(obj->handle, buf, *buflen);
+        len = dsi_writeinit(obj->dsi, buf, *buflen);
         if (!len || ((len = action(handle, buf, len)) < 0)) {
-            dsi_writeflush(obj->handle);
+            dsi_writeflush(obj->dsi);
             goto uam_afp_read_err;
         }
 
-        while ((len = (dsi_write(obj->handle, buf, *buflen)))) {
+        while ((len = (dsi_write(obj->dsi, buf, *buflen)))) {
             if ((len = action(handle, buf, len)) < 0) {
-                dsi_writeflush(obj->handle);
+                dsi_writeflush(obj->dsi);
                 goto uam_afp_read_err;
             }
         }
-        break;
-    default:
-        return -1;
-    }
     return 0;
 
 uam_afp_read_err:
index 18f010bbb0b81ddebb5c2570a2753e96c3022002..a553ffabff4aaac03c3f787c4e42b77d27c69a39 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: uam_auth.h,v 1.7 2009-10-22 12:35:38 franklahm Exp $
- *
  * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
  * All Rights Reserved.  See COPYRIGHT.
  *
@@ -10,7 +8,6 @@
 #ifndef AFPD_UAM_AUTH_H
 #define AFPD_UAM_AUTH_H 1
 
-#include <sys/cdefs.h>
 #include <pwd.h>
 
 #include <atalk/uam.h>
index 817ac6590802568e718675b67d954a052838a160..e26e6d1f1b50f702da0fb3ea0d9786937b275e99 100644 (file)
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-/* don't compile this file at all unless FORCE_UIDGID is set */
-#ifdef FORCE_UIDGID
-
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-#include <atalk/logger.h>
-
-/* functions for username and group */
-#include <pwd.h>
-#include <grp.h>
-#include "uid.h"
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-
-extern uid_t    uuid; 
-
-void save_uidgid ( pair )
-uidgidset *pair;
-{
-    pair->uid = geteuid ();
-    pair->gid = getegid ();
-} 
-
-void restore_uidgid ( pair )
-uidgidset *pair;
-{
-    uid_t uid
-    gid_t gid;   
-    
-    uid = geteuid ();
-    gid = getegid ();
-
-    if (uid == pair->uid && gid == pair->gid)
-       return;
-
-    if (seteuid(0) < 0) {
-        LOG(log_error, logtype_afpd, "set_uidgid: Could not switch back to root: %s",
-                               strerror(errno));
-    }
-
-    if ( setegid ( pair->gid ) < 0 )
-        LOG(log_error, logtype_afpd, "restore_uidgid: unable to setegid '%s': %s",
-            pair->gid, strerror(errno) );
-
-    if ( seteuid ( pair->uid ) < 0 )
-        LOG(log_error, logtype_afpd, "restore_uidgid: unable to seteuid '%s': %s",
-            pair->uid, strerror(errno) );
-    else
-       uuid = pair->uid;       /* ugly hack for utommode */
-}
-
-void set_uidgid ( this_volume )
-const struct vol       *this_volume;
-{
-    int                uid, gid;   /* derived ones go in here */
-
-    /* check to see if we have to switch users */
-    uid = user_to_uid ( (this_volume)->v_forceuid);
-    gid = group_to_gid ( (this_volume)->v_forcegid);
-
-    if ((!uid || uid == geteuid()) && (!gid || gid == getegid()))
-       return;
-
-    if ( seteuid(0) < 0) {
-        LOG(log_error, logtype_afpd, "set_uidgid: Could not switch back to root: %s",
-                               strerror(errno));
-       return;
-    }
-
-    /* check to see if we have to switch groups */
-    if ( gid ) {
-        if ( setegid ( gid ) < 0 )
-            LOG(log_error, logtype_afpd, "set_uidgid: unable to setegid '%s': %s",
-                (this_volume)->v_forcegid, strerror(errno) );
-    } /* end of checking for (this_volume)->v_forcegid */
-
-    if ( uid) {
-        if ( seteuid ( uid ) < 0 )
-            LOG(log_error, logtype_afpd, "set_uidgid: unable to seteuid '%s': %s",
-                (this_volume)->v_forceuid, strerror(errno) );
-       else
-           uuid = uid; /* ugly hack for utommode */
-
-    } /* end of checking for (this_volume)->v_forceuid */
-
-} /* end function void set_uidgid ( username, group ) */
-
-int user_to_uid ( username )
-char   *username;
-{
-    struct passwd *this_passwd;
-
-    /* check for anything */
-    if ( !username || strlen ( username ) < 1 ) return 0;
-
-    /* grab the /etc/passwd record relating to username */
-    this_passwd = getpwnam ( username );
-
-    /* return false if there is no structure returned */
-    if (this_passwd == NULL) return 0;
-
-    /* return proper uid */
-    return this_passwd->pw_uid;
-
-} /* end function int user_to_uid ( username ) */
-
-int group_to_gid ( group )
-char   *group;
-{
-    struct group *this_group;
-
-    /* check for anything */
-    if ( !group || strlen ( group ) < 1 ) return 0;
-
-    /* grab the /etc/groups record relating to group */
-    this_group = getgrnam ( group );
-
-    /* return false if there is no structure returned */
-    if (this_group == NULL) return 0;
-
-    /* return proper gid */
-    return this_group->gr_gid;
-
-} /* end function int group_to_gid ( group ) */
-
-#endif /* FORCE_UIDGID */
index 7f00b20676a73bf74705a0e6cb4dc7d964d6c5e0..647cbd8d164a76182953c420c3650ae773f2a2a2 100644 (file)
@@ -6,20 +6,4 @@
 #ifndef AFPD_UID_H
 #define AFPD_UID_H 1
 
-#ifdef FORCE_UIDGID
-
-/* have to make sure struct vol is defined */
-#include "volume.h"
-
-/* functions to save and restore uid/gid pairs */
-extern void save_uidgid    ( uidgidset * );
-extern void restore_uidgid ( uidgidset * );
-extern void set_uidgid     ( const struct vol * );
-
-/* internal functions to convert user and group names to ids */
-extern int  user_to_uid  ( char * );
-extern int  group_to_gid ( char * );
-
-#endif /* FORCE_UIDGID */
-
 #endif
index cc10d97ba02dbf39e58118eed7b6a4bba75503ec..16562f3b757b1d0912d09e221a2d52b5144aee33 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <inttypes.h>
-
-/* STDC check */
-#ifdef STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
 #include <errno.h>
 #include <limits.h>
 #include <sys/param.h>
@@ -51,7 +34,7 @@ char *strchr (), *strrchr ();
 /*
  * Get the free space on a partition.
  */
-int ustatfs_getvolspace(const struct vol *vol, VolSpace *bfree, VolSpace *btotal, u_int32_t *bsize)
+int ustatfs_getvolspace(const struct vol *vol, VolSpace *bfree, VolSpace *btotal, uint32_t *bsize)
 {
     VolSpace maxVolSpace = UINT64_MAX;
 
@@ -115,9 +98,9 @@ static int utombits(mode_t bits)
 /* --------------------------------
     cf AFP 3.0 page 63
 */
-void utommode(struct stat *stat, struct maccess *ma)
+static void utommode(const AFPObj *obj, const struct stat *stat, struct maccess *ma)
 {
-mode_t mode;
+    mode_t mode;
 
     mode = stat->st_mode;
     ma->ma_world = utombits( mode );
@@ -131,10 +114,10 @@ mode_t mode;
     /* ma_user is a union of all permissions but we must follow
      * unix perm
     */
-    if ( (uuid == stat->st_uid) || (uuid == 0)) {
+    if ( (obj->uid == stat->st_uid) || (obj->uid == 0)) {
         ma->ma_user = ma->ma_owner | AR_UOWN;
     }
-    else if ( gmem( stat->st_gid )) {
+    else if (gmem(stat->st_gid, obj->ngroups, obj->groups)) {
         ma->ma_user = ma->ma_group;
     }
     else {
@@ -169,7 +152,7 @@ mode_t mode;
  *
  * dir parameter is used by AFS
  */
-void accessmode(const struct vol *vol, char *path, struct maccess *ma, struct dir *dir _U_, struct stat *st)
+void accessmode(const AFPObj *obj, const struct vol *vol, char *path, struct maccess *ma, struct dir *dir _U_, struct stat *st)
 {
     struct stat     sb;
 
@@ -179,24 +162,12 @@ void accessmode(const struct vol *vol, char *path, struct maccess *ma, struct di
             return;
         st = &sb;
     }
-    utommode( st, ma );
+    utommode(obj, st, ma );
 #ifdef HAVE_ACLS
-    acltoownermode(vol, path, st, ma);
+    acltoownermode(obj, vol, path, st, ma);
 #endif
 }
 
-int gmem(const gid_t gid)
-{
-    int                i;
-
-    for ( i = 0; i < ngroups; i++ ) {
-        if ( groups[ i ] == gid ) {
-            return( 1 );
-        }
-    }
-    return( 0 );
-}
-
 static mode_t mtoubits(u_char bits)
 {
     mode_t     mode;
@@ -232,83 +203,6 @@ mode_t mtoumode(struct maccess *ma)
     return( mode );
 }
 
-#define EXEC_MODE (S_IXGRP | S_IXUSR | S_IXOTH)
-
-int setdeskmode(const mode_t mode)
-{
-    char               wd[ MAXPATHLEN + 1];
-    struct stat         st;
-    char               modbuf[ 12 + 1], *m;
-    struct dirent      *deskp, *subp;
-    DIR                        *desk, *sub;
-
-    if (!dir_rx_set(mode)) {
-        /* want to remove read and search access to owner it will screw the volume */
-        return -1 ;
-    }
-    if ( getcwd( wd , MAXPATHLEN) == NULL ) {
-        return( -1 );
-    }
-    if ( chdir( ".AppleDesktop" ) < 0 ) {
-        return( -1 );
-    }
-    if (( desk = opendir( "." )) == NULL ) {
-        if ( chdir( wd ) < 0 ) {
-            LOG(log_error, logtype_afpd, "setdeskmode: chdir %s: %s", wd, strerror(errno) );
-        }
-        return( -1 );
-    }
-    for ( deskp = readdir( desk ); deskp != NULL; deskp = readdir( desk )) {
-        if ( strcmp( deskp->d_name, "." ) == 0 ||
-                strcmp( deskp->d_name, ".." ) == 0 || strlen( deskp->d_name ) > 2 ) {
-            continue;
-        }
-        strcpy( modbuf, deskp->d_name );
-        strcat( modbuf, "/" );
-        m = strchr( modbuf, '\0' );
-        if (( sub = opendir( deskp->d_name )) == NULL ) {
-            continue;
-        }
-        for ( subp = readdir( sub ); subp != NULL; subp = readdir( sub )) {
-            if ( strcmp( subp->d_name, "." ) == 0 ||
-                    strcmp( subp->d_name, ".." ) == 0 ) {
-                continue;
-            }
-            *m = '\0';
-            strcat( modbuf, subp->d_name );
-            /* XXX: need to preserve special modes */
-            if (lstat(modbuf, &st) < 0) {
-                LOG(log_error, logtype_afpd, "setdeskmode: stat %s: %s",fullpathname(modbuf), strerror(errno) );
-                continue;
-            }
-
-            if (S_ISDIR(st.st_mode)) {
-                if ( chmod_acl( modbuf,  (DIRBITS | mode) & ~default_options.umask ) < 0 && errno != EPERM ) {
-                     LOG(log_error, logtype_afpd, "setdeskmode: chmod %s: %s",fullpathname(modbuf), strerror(errno) );
-                }
-            } else if ( chmod_acl( modbuf,  mode & ~(default_options.umask | EXEC_MODE) ) < 0 && errno != EPERM ) {
-                LOG(log_error, logtype_afpd, "setdeskmode: chmod %s: %s",fullpathname(modbuf), strerror(errno) );
-            }
-
-        }
-        closedir( sub );
-        /* XXX: need to preserve special modes */
-        if ( chmod_acl( deskp->d_name,  (DIRBITS | mode) & ~default_options.umask ) < 0 && errno != EPERM ) {
-            LOG(log_error, logtype_afpd, "setdeskmode: chmod %s: %s",fullpathname(deskp->d_name), strerror(errno) );
-        }
-    }
-    closedir( desk );
-    if ( chdir( wd ) < 0 ) {
-        LOG(log_error, logtype_afpd, "setdeskmode: chdir %s: %s", wd, strerror(errno) );
-        return -1;
-    }
-    /* XXX: need to preserve special modes */
-    if ( chmod_acl( ".AppleDesktop",  (DIRBITS | mode) & ~default_options.umask ) < 0 && errno != EPERM ) {
-        LOG(log_error, logtype_afpd, "setdeskmode: chmod %s: %s", fullpathname(".AppleDesktop"),strerror(errno) );
-    }
-    return( 0 );
-}
-
 /* --------------------- */
 int setfilunixmode (const struct vol *vol, struct path* path, mode_t mode)
 {
@@ -332,9 +226,6 @@ int setfilunixmode (const struct vol *vol, struct path* path, mode_t mode)
 /* --------------------- */
 int setdirunixmode(const struct vol *vol, const char *name, mode_t mode)
 {
-
-    int dropbox = (vol->v_flags & AFPVOL_DROPBOX);
-
     LOG(log_debug, logtype_afpd, "setdirunixmode('%s', mode:%04o) {v_dperm:%04o}",
         fullpathname(name), mode, vol->v_dperm);
 
@@ -342,157 +233,29 @@ int setdirunixmode(const struct vol *vol, const char *name, mode_t mode)
 
     if (dir_rx_set(mode)) {
        /* extending right? dir first then .AppleDouble in rf_setdirmode */
-       if ( stickydirmode(name, DIRBITS | mode, dropbox, vol->v_umask) < 0 )
+       if (chmod_acl(name, (DIRBITS | mode) & ~vol->v_umask) < 0 )
                return -1;
     }
-    if (vol->vfs->vfs_setdirunixmode(vol, name, mode, NULL) < 0 && !vol_noadouble(vol)) {
+    if (vol->vfs->vfs_setdirunixmode(vol, name, mode, NULL) < 0) {
         return  -1 ;
     }
     if (!dir_rx_set(mode)) {
-       if ( stickydirmode(name, DIRBITS | mode, dropbox, vol->v_umask) < 0 )
+       if (chmod_acl(name, (DIRBITS | mode) & ~vol->v_umask) < 0 )
             return -1;
     }
     return 0;
 }
 
-/* --------------------- */
-int setdirmode(const struct vol *vol, const char *name, mode_t mode)
-{
-    struct stat                st;
-    struct dirent      *dirp;
-    DIR                        *dir;
-    mode_t              hf_mode;
-    int                 osx = vol->v_adouble == AD_VERSION2_OSX;
-    int                 dropbox = (vol->v_flags & AFPVOL_DROPBOX);
-    
-    mode |= vol->v_dperm;
-    hf_mode = ad_hf_mode(mode);
-
-    if (dir_rx_set(mode)) {
-       /* extending right? dir first */
-       if ( stickydirmode(name, DIRBITS | mode, dropbox, vol->v_umask) < 0 )
-               return -1;
-    }
-    
-    if (( dir = opendir( name )) == NULL ) {
-        LOG(log_error, logtype_afpd, "setdirmode: opendir: %s", fullpathname(name), strerror(errno) );
-        return( -1 );
-    }
-
-    for ( dirp = readdir( dir ); dirp != NULL; dirp = readdir( dir )) {
-        /* FIXME */
-        if ( *dirp->d_name == '.' && (!osx || dirp->d_name[1] != '_')) {
-            continue;
-        }
-        if ( lstat( dirp->d_name, &st ) < 0 ) {
-            LOG(log_error, logtype_afpd, "setdirmode: stat %s: %s",dirp->d_name, strerror(errno) );
-            continue;
-        }
-
-        if (!S_ISDIR(st.st_mode)) {
-           int setmode = (osx && *dirp->d_name == '.')?hf_mode:mode;
-
-           if (setfilmode(dirp->d_name, setmode, &st, vol->v_umask) < 0) {
-               closedir( dir );
-                LOG(log_error, logtype_afpd, "setdirmode: chmod %s: %s",dirp->d_name, strerror(errno) );
-                return -1;
-           }
-        }
-    }
-    closedir( dir );
-    
-    if (vol->vfs->vfs_setdirmode(vol, name, mode, NULL) < 0 && !vol_noadouble(vol)) {
-        return  -1 ;
-    }
-
-    if (!dir_rx_set(mode)) {
-       if ( stickydirmode(name, DIRBITS | mode, dropbox, vol->v_umask) < 0 )
-               return -1;
-    }
-    return( 0 );
-}
-
-/* ----------------------------- */
-int setdeskowner(const uid_t uid, const gid_t gid)
-{
-    char               wd[ MAXPATHLEN + 1];
-    char               modbuf[12 + 1], *m;
-    struct dirent      *deskp, *subp;
-    DIR                        *desk, *sub;
-
-    if ( getcwd( wd, MAXPATHLEN ) == NULL ) {
-        return( -1 );
-    }
-    if ( chdir( ".AppleDesktop" ) < 0 ) {
-        return( -1 );
-    }
-    if (( desk = opendir( "." )) == NULL ) {
-        if ( chdir( wd ) < 0 ) {
-            LOG(log_error, logtype_afpd, "setdeskowner: chdir %s: %s", wd, strerror(errno) );
-        }
-        return( -1 );
-    }
-    for ( deskp = readdir( desk ); deskp != NULL; deskp = readdir( desk )) {
-        if ( strcmp( deskp->d_name, "." ) == 0 ||
-                strcmp( deskp->d_name, ".." ) == 0 ||
-                strlen( deskp->d_name ) > 2 ) {
-            continue;
-        }
-        strcpy( modbuf, deskp->d_name );
-        strcat( modbuf, "/" );
-        m = strchr( modbuf, '\0' );
-        if (( sub = opendir( deskp->d_name )) == NULL ) {
-            continue;
-        }
-        for ( subp = readdir( sub ); subp != NULL; subp = readdir( sub )) {
-            if ( strcmp( subp->d_name, "." ) == 0 ||
-                    strcmp( subp->d_name, ".." ) == 0 ) {
-                continue;
-            }
-            *m = '\0';
-            strcat( modbuf, subp->d_name );
-            /* XXX: add special any uid, ignore group bits */
-            if ( chown( modbuf, uid, gid ) < 0 && errno != EPERM ) {
-                LOG(log_error, logtype_afpd, "setdeskown: chown %s: %s", fullpathname(modbuf), strerror(errno) );
-            }
-        }
-        closedir( sub );
-        /* XXX: add special any uid, ignore group bits */
-        if ( chown( deskp->d_name, uid, gid ) < 0 && errno != EPERM ) {
-            LOG(log_error, logtype_afpd, "setdeskowner: chown %s: %s",
-                deskp->d_name, strerror(errno) );
-        }
-    }
-    closedir( desk );
-    if ( chdir( wd ) < 0 ) {
-        LOG(log_error, logtype_afpd, "setdeskowner: chdir %s: %s", wd, strerror(errno) );
-        return -1;
-    }
-    if ( chown( ".AppleDesktop", uid, gid ) < 0 && errno != EPERM ) {
-        LOG(log_error, logtype_afpd, "setdeskowner: chown %s: %s", fullpathname(".AppleDouble"), strerror(errno) );
-    }
-    return( 0 );
-}
-
 /* ----------------------------- */
 int setfilowner(const struct vol *vol, const uid_t uid, const gid_t gid, struct path* path)
 {
-
-    if (!path->st_valid) {
-        of_stat(path);
-    }
-
-    if (path->st_errno) {
-        return -1;
-    }
-
-    if ( lchown( path->u_name, uid, gid ) < 0 && errno != EPERM ) {
+    if (lchown(path->u_name, uid, gid) < 0 && errno != EPERM) {
         LOG(log_debug, logtype_afpd, "setfilowner: chown %d/%d %s: %s",
-            uid, gid, path->u_name, strerror(errno) );
-       return -1;
+            uid, gid, path->u_name, strerror(errno));
+        return -1;
     }
 
-    if (vol->vfs->vfs_chown(vol, path->u_name, uid, gid ) < 0 && errno != EPERM) {
+    if (vol->vfs->vfs_chown(vol, path->u_name, uid, gid) < 0 && errno != EPERM) {
         LOG(log_debug, logtype_afpd, "setfilowner: rf_chown %d/%d %s: %s",
             uid, gid, path->u_name, strerror(errno) );
         return -1;
@@ -508,92 +271,14 @@ int setfilowner(const struct vol *vol, const uid_t uid, const gid_t gid, struct
  * co-opting some bits. */
 int setdirowner(const struct vol *vol, const char *name, const uid_t uid, const gid_t gid)
 {
-    struct stat                st;
-    struct dirent      *dirp;
-    DIR                        *dir;
-    int                 osx = vol->v_adouble == AD_VERSION2_OSX;
-
-    if (( dir = opendir( name )) == NULL ) {
-        return( -1 );
-    }
-    for ( dirp = readdir( dir ); dirp != NULL; dirp = readdir( dir )) {
-        if ( *dirp->d_name == '.' && (!osx || dirp->d_name[1] != '_')) {
-            continue;
-        }
-        if ( lstat( dirp->d_name, &st ) < 0 ) {
-            LOG(log_error, logtype_afpd, "setdirowner: stat %s: %s",
-                fullpathname(dirp->d_name), strerror(errno) );
-            continue;
-        }
-        if (( st.st_mode & S_IFMT ) == S_IFREG ) {
-            if ( lchown( dirp->d_name, uid, gid ) < 0 && errno != EPERM ) {
-                LOG(log_debug, logtype_afpd, "setdirowner: chown %s: %s",
-                    fullpathname(dirp->d_name), strerror(errno) );
-                /* return ( -1 ); Sometimes this is okay */
-            }
-        }
+    if (lchown(name, uid, gid ) < 0 && errno != EPERM ) {
+        LOG(log_debug, logtype_afpd, "setdirowner: chown %d/%d %s: %s",
+            uid, gid, fullpathname(name), strerror(errno) );
     }
-    closedir( dir );
 
-    if (vol->vfs->vfs_setdirowner(vol, name, uid, gid) < 0) {
+    if (vol->vfs->vfs_setdirowner(vol, name, uid, gid) < 0)
         return -1;
-    }
-    
-    if ( lstat( ".", &st ) < 0 ) {
-        return( -1 );
-    }
-    if ( gid && gid != st.st_gid && lchown( ".", uid, gid ) < 0 && errno != EPERM ) {
-        LOG(log_debug, logtype_afpd, "setdirowner: chown %d/%d %s: %s",
-            uid, gid, fullpathname("."), strerror(errno) );
-    }
 
     return( 0 );
 }
 
-#if 0
-/* recursive chown()ing of a directory */
-static int recursive_chown(const char *path, uid_t uid, gid_t gid) {
-    struct stat sbuf;
-    DIR *odir = NULL;
-    struct dirent *entry;
-    char *name;
-    int ret = 0;
-    char newpath[PATH_MAX+1];
-    newpath[PATH_MAX] = '\0';
-    
-    if (chown(path, uid, gid) < 0) {
-        LOG(log_error, logtype_afpd, "cannot chown() file [%s] (uid = %d): %s", path, uid, strerror(errno));
-       return -1;
-    }
-
-    if (lstat(path, &sbuf) < 0) {
-       LOG(log_error, logtype_afpd, "cannot chown() file [%s] (uid = %d): %s", path, uid, strerror(errno));
-       return -1;
-    }
-       
-    if (S_ISDIR(sbuf.st_mode)) {
-       odir = opendir(path);
-       if (odir == NULL) {
-           LOG(log_error, logtype_afpd, "cannot opendir() [%s] (uid = %d): %s", path, uid, strerror(errno));
-           goto recursive_chown_end;
-       }
-       while (NULL != (entry=readdir(odir)) ) {
-           name = entry->d_name;
-           if (name[0] == '.' && name[1] == '\0')
-               continue;
-           if (name[0] == '.' && name[1] == '.' && name[2] == '\0')
-               continue;
-           sprintf(newpath, "%s/%s", path, name);
-           if (recursive_chown(newpath, uid, gid) < 0)
-               ret = -1;
-       } /* while */
-    } /* if */
-
-recursive_chown_end:
-    if (odir != NULL) {
-       closedir(odir);
-    }
-    return ret;
-}
-#endif
-
index 54ebf3d69bfac079b576a6eae4f00edaf757181f..73a515b2dcf357496ffec0ae57aa67ca11f13422 100644 (file)
@@ -1,14 +1,8 @@
-/*
- * $Id: unix.h,v 1.23 2010-04-12 14:28:47 franklahm Exp $
- */
-
 #ifndef AFPD_UNIX_H
 #define AFPD_UNIX_H
 
-#ifdef HAVE_SYS_CDEFS_H
-#include <sys/cdefs.h>
-#endif /* HAVE_SYS_CDEFS_H */
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include "config.h"
 #include "volume.h"
 
@@ -209,25 +203,22 @@ extern long quotactl (unsigned int, const char *, int, caddr_t);
 
 #endif /* linux */
 
-extern int getnfsquota (struct vol *, const int, const u_int32_t,
-                                struct dqblk *);
+extern int getnfsquota (struct vol *, const int, const uint32_t,
+                        struct dqblk *);
 
 #endif /* ! HAVE_LIBQUOTA */
-extern int uquota_getvolspace (struct vol *, VolSpace *, VolSpace *,
-                                       const u_int32_t);
+extern int uquota_getvolspace (const AFPObj *obj, struct vol *, VolSpace *, VolSpace *,
+                               const uint32_t);
 #endif /* NO_QUOTA_SUPPORT */
 
 extern struct afp_options default_options;
 
-extern int gmem            (const gid_t);
-extern int setdeskmode      (const mode_t);
 extern int setdirunixmode   (const struct vol *, const char *, mode_t);
 extern int setdirmode       (const struct vol *, const char *, mode_t);
-extern int setdeskowner     (const uid_t, const gid_t);
 extern int setdirowner      (const struct vol *, const char *, const uid_t, const gid_t);
 extern int setfilunixmode   (const struct vol *, struct path*, const mode_t);
 extern int setfilowner      (const struct vol *, const uid_t, const gid_t, struct path*);
-extern void accessmode      (const struct vol *, char *, struct maccess *, struct dir *, struct stat *);
+extern void accessmode      (const AFPObj *obj, const struct vol *, char *, struct maccess *, struct dir *, struct stat *);
 
 #ifdef AFS     
     #define accessmode afsmode
index 50bafbe55b555e5aa0d12d89721a714b7d344879..3b02b2390a467dd81de3319fa757ceb709434844 100644 (file)
 #include <grp.h>
 #include <utime.h>
 #include <errno.h>
-#ifdef HAVE_STRINGS_H
-#include <strings.h>
-#endif
-/* STDC check */
-#if STDC_HEADERS
-#include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <inttypes.h>
-#include <time.h>
-
-#include <atalk/asp.h>
-#include <atalk/dsi.h>
-#include <atalk/adouble.h>
-#include <atalk/afp.h>
-#include <atalk/util.h>
-#include <atalk/volinfo.h>
-#include <atalk/logger.h>
-#include <atalk/vfs.h>
-#include <atalk/uuid.h>
-#include <atalk/bstrlib.h>
-#include <atalk/bstradd.h>
-#include <atalk/ftw.h>
-#include <atalk/globals.h>
-#include <atalk/fce_api.h>
-#include <atalk/errchk.h>
-
-#ifdef CNID_DB
-#include <atalk/cnid.h>
-#endif /* CNID_DB*/
-
-#include "directory.h"
-#include "file.h"
-#include "volume.h"
-#include "unix.h"
-#include "mangle.h"
-#include "fork.h"
-#include "hash.h"
-#include "acls.h"
-
-extern int afprun(int root, char *cmd, int *outfd);
-
-#ifndef MIN
-#define MIN(a, b) ((a) < (b) ? (a) : (b))
-#endif /* ! MIN */
-
-#ifndef UUID_PRINTABLE_STRING_LENGTH
-#define UUID_PRINTABLE_STRING_LENGTH 37
-#endif
-
-/* Globals */
-struct vol *current_vol;        /* last volume from getvolbyvid() */
-
-static struct vol *Volumes = NULL;
-static u_int16_t    lastvid = 0;
-static char     *Trash = "\02\024Network Trash Folder";
-
-static struct extmap    *Extmap = NULL, *Defextmap = NULL;
-static int              Extmap_cnt;
-static void             free_extmap(void);
-
-#define VOLOPT_ALLOW      0  /* user allow list */
-#define VOLOPT_DENY       1  /* user deny list */
-#define VOLOPT_RWLIST     2  /* user rw list */
-#define VOLOPT_ROLIST     3  /* user ro list */
-#define VOLOPT_PASSWORD   4  /* volume password */
-#define VOLOPT_CASEFOLD   5  /* character case mangling */
-#define VOLOPT_FLAGS      6  /* various flags */
-#define VOLOPT_DBPATH     7  /* path to database */
-#define VOLOPT_LIMITSIZE  8  /* Limit the size of the volume */
-/* Usable slot: 9 */
-#define VOLOPT_VETO          10  /* list of veto filespec */
-#define VOLOPT_PREEXEC       11  /* preexec command */
-#define VOLOPT_ROOTPREEXEC   12  /* root preexec command */
-#define VOLOPT_POSTEXEC      13  /* postexec command */
-#define VOLOPT_ROOTPOSTEXEC  14  /* root postexec command */
-#define VOLOPT_ENCODING      15  /* mac encoding (pre OSX)*/
-#define VOLOPT_MACCHARSET    16
-#define VOLOPT_CNIDSCHEME    17
-#define VOLOPT_ADOUBLE       18  /* adouble version */
-
-#ifdef FORCE_UIDGID
-#warning UIDGID
-#include "uid.h"
-
-#define VOLOPT_FORCEUID      19  /* force uid for username x */
-#define VOLOPT_FORCEGID      20  /* force gid for group x */
-#endif /* FORCE_UIDGID */
-
-#define VOLOPT_UMASK         21
-#define VOLOPT_ALLOWED_HOSTS 22
-#define VOLOPT_DENIED_HOSTS  23
-#define VOLOPT_DPERM         24  /* dperm default directories perms */
-#define VOLOPT_FPERM         25  /* fperm default files perms */
-#define VOLOPT_DFLTPERM      26  /* perm */
-#define VOLOPT_EA_VFS        27  /* Extended Attributes vfs indirection */
-#define VOLOPT_CNIDSERVER    28  /* CNID Server ip address*/
-#define VOLOPT_CNIDPORT      30  /* CNID server tcp port */
-
-#define VOLOPT_MAX           31  /* <== IMPORTANT !!!!!! */
-#define VOLOPT_NUM           (VOLOPT_MAX + 1)
-
-#define VOLPASSLEN  8
-#define VOLOPT_DEFAULT     ":DEFAULT:"
-#define VOLOPT_DEFAULT_LEN 9
-
-struct vol_option {
-    char *c_value;
-    int i_value;
-};
-
-typedef struct _special_folder {
-    const char *name;
-    int precreate;
-    mode_t mode;
-    int hide;
-} _special_folder;
-
-static const _special_folder special_folders[] = {
-    {"Network Trash Folder",     1,  0777,  1},
-    {"Temporary Items",          1,  0777,  1},
-    {".AppleDesktop",            1,  0777,  0},
-#if 0
-    {"TheFindByContentFolder",   0,     0,  1},
-    {"TheVolumeSettingsFolder",  0,     0,  1},
-#endif
-    {NULL, 0, 0, 0}};
-
-/* Forward declarations */
-static void handle_special_folders (const struct vol *);
-static void deletevol(struct vol *vol);
-static void volume_free(struct vol *vol);
-static void check_ea_sys_support(struct vol *vol);
-static char *get_vol_uuid(const AFPObj *obj, const char *volname);
-static int readvolfile(AFPObj *obj, struct afp_volume_name *p1,char *p2, int user, struct passwd *pwent);
-
-static void volfree(struct vol_option *options, const struct vol_option *save)
-{
-    int i;
-
-    if (save) {
-        for (i = 0; i < VOLOPT_MAX; i++) {
-            if (options[i].c_value && (options[i].c_value != save[i].c_value))
-                free(options[i].c_value);
-        }
-    } else {
-        for (i = 0; i < VOLOPT_MAX; i++) {
-            if (options[i].c_value)
-                free(options[i].c_value);
-        }
-    }
-}
-
-
-#define is_var(a, b) (strncmp((a), (b), 2) == 0)
-
-/*
- * Handle variable substitutions. here's what we understand:
- * $b   -> basename of path
- * $c   -> client ip/appletalk address
- * $d   -> volume pathname on server
- * $f   -> full name (whatever's in the gecos field)
- * $g   -> group
- * $h   -> hostname
- * $i   -> client ip/appletalk address without port
- * $s   -> server name (hostname if it doesn't exist)
- * $u   -> username (guest is usually nobody)
- * $v   -> volume name or basename if null
- * $z   -> zone (may not exist)
- * $$   -> $
- *
- * This get's called from readvolfile with
- * path = NULL, volname = NULL for xlating the volumes path
- * path = path, volname = NULL for xlating the volumes name
- * ... and from volumes options parsing code when xlating eg dbpath with
- * path = path, volname = volname
- *
- * Using this information we can reject xlation of any variable depeninding on a login
- * context which is not given in the afp master, where we must evaluate this whole stuff
- * too for the Zeroconf announcements.
- */
-static char *volxlate(AFPObj *obj,
-                      char *dest,
-                      size_t destlen,
-                      char *src,
-                      struct passwd *pwd,
-                      char *path,
-                      char *volname)
-{
-    char *p, *r;
-    const char *q;
-    int len;
-    char *ret;
-    int afpmaster = 0;
-    int xlatevolname = 0;
-
-    if (parent_or_child == 0)
-        afpmaster = 1;
-
-    if (path && !volname)
-        /* cf above */
-        xlatevolname = 1;
-
-    if (!src) {
-        return NULL;
-    }
-    if (!dest) {
-        dest = calloc(destlen +1, 1);
-    }
-    ret = dest;
-    if (!ret) {
-        return NULL;
-    }
-    strlcpy(dest, src, destlen +1);
-    if ((p = strchr(src, '$')) == NULL) /* nothing to do */
-        return ret;
-
-    /* first part of the path. just forward to the next variable. */
-    len = MIN((size_t)(p - src), destlen);
-    if (len > 0) {
-        destlen -= len;
-        dest += len;
-    }
-
-    while (p && destlen > 0) {
-        /* now figure out what the variable is */
-        q = NULL;
-        if (is_var(p, "$b")) {
-            if (afpmaster && xlatevolname)
-                return NULL;
-            if (path) {
-                if ((q = strrchr(path, '/')) == NULL)
-                    q = path;
-                else if (*(q + 1) != '\0')
-                    q++;
-            }
-        } else if (is_var(p, "$c")) {
-            if (afpmaster && xlatevolname)
-                return NULL;
-#ifndef NO_DDP
-            if (obj->proto == AFPPROTO_ASP) {
-                ASP asp = obj->handle;
-
-                len = sprintf(dest, "%u.%u", ntohs(asp->asp_sat.sat_addr.s_net),
-                              asp->asp_sat.sat_addr.s_node);
-                dest += len;
-                destlen -= len;
-
-            }
-#endif
-            if (obj->proto == AFPPROTO_DSI) {
-                DSI *dsi = obj->handle;
-                len = sprintf(dest, "%s:%u",
-                              getip_string((struct sockaddr *)&dsi->client),
-                              getip_port((struct sockaddr *)&dsi->client));
-                dest += len;
-                destlen -= len;
-            }
-        } else if (is_var(p, "$d")) {
-            if (afpmaster && xlatevolname)
-                return NULL;
-            q = path;
-        } else if (pwd && is_var(p, "$f")) {
-            if (afpmaster && xlatevolname)
-                return NULL;
-            if ((r = strchr(pwd->pw_gecos, ',')))
-                *r = '\0';
-            q = pwd->pw_gecos;
-        } else if (pwd && is_var(p, "$g")) {
-            if (afpmaster && xlatevolname)
-                return NULL;
-            struct group *grp = getgrgid(pwd->pw_gid);
-            if (grp)
-                q = grp->gr_name;
-        } else if (is_var(p, "$h")) {
-            q = obj->options.hostname;
-        } else if (is_var(p, "$i")) {
-            if (afpmaster && xlatevolname)
-                return NULL;
-#ifndef NO_DDP
-            if (obj->proto == AFPPROTO_ASP) {
-                ASP asp = obj->handle;
-                len = sprintf(dest, "%u", ntohs(asp->asp_sat.sat_addr.s_net));
-                dest += len;
-                destlen -= len;
-
-            }
-#endif
-            if (obj->proto == AFPPROTO_DSI) {
-                DSI *dsi = obj->handle;
-                q = getip_string((struct sockaddr *)&dsi->client);
-            }
-        } else if (is_var(p, "$s")) {
-            if (obj->Obj)
-                q = obj->Obj;
-            else if (obj->options.server) {
-                q = obj->options.server;
-            } else
-                q = obj->options.hostname;
-        } else if (obj->username && is_var(p, "$u")) {
-            if (afpmaster && xlatevolname)
-                return NULL;
-            char* sep = NULL;
-            if ( obj->options.ntseparator && (sep = strchr(obj->username, obj->options.ntseparator[0])) != NULL)
-                q = sep+1;
-            else
-                q = obj->username;
-        } else if (is_var(p, "$v")) {
-            if (afpmaster && xlatevolname)
-                return NULL;
-            if (volname) {
-                q = volname;
-            }
-            else if (path) {
-                if ((q = strrchr(path, '/')) == NULL)
-                    q = path;
-                else if (*(q + 1) != '\0')
-                    q++;
-            }
-        } else if (is_var(p, "$z")) {
-            q = obj->Zone;
-        } else if (is_var(p, "$$")) {
-            q = "$";
-        } else
-            q = p;
-
-        /* copy the stuff over. if we don't understand something that we
-         * should, just skip it over. */
-        if (q) {
-            len = MIN(p == q ? 2 : strlen(q), destlen);
-            strncpy(dest, q, len);
-            dest += len;
-            destlen -= len;
-        }
-
-        /* stuff up to next $ */
-        src = p + 2;
-        p = strchr(src, '$');
-        len = p ? MIN((size_t)(p - src), destlen) : destlen;
-        if (len > 0) {
-            strncpy(dest, src, len);
-            dest += len;
-            destlen -= len;
-        }
-    }
-    return ret;
-}
-
-/* to make sure that val is valid, make sure to select an opt that
-   includes val */
-static int optionok(const char *buf, const char *opt, const char *val)
-{
-    if (!strstr(buf,opt))
-        return 0;
-    if (!val[1])
-        return 0;
-    return 1;
-}
-
-
-/* -------------------- */
-static void setoption(struct vol_option *options, struct vol_option *save, int opt, const char *val)
-{
-    if (options[opt].c_value && (!save || options[opt].c_value != save[opt].c_value))
-        free(options[opt].c_value);
-    options[opt].c_value = strdup(val + 1);
-}
-
-/* ------------------------------------------
-   handle all the options. tmp can't be NULL. */
-static void volset(struct vol_option *options, struct vol_option *save,
-                   char *volname, int vlen,
-                   const char *tmp)
-{
-    char *val;
-
-    val = strchr(tmp, ':');
-    if (!val) {
-        /* we'll assume it's a volume name. */
-        strncpy(volname, tmp, vlen);
-        volname[vlen] = 0;
-        return;
-    }
-#if 0
-    LOG(log_debug, logtype_afpd, "Parsing volset %s", val);
-#endif
-    if (optionok(tmp, "allow:", val)) {
-        setoption(options, save, VOLOPT_ALLOW, val);
-
-    } else if (optionok(tmp, "deny:", val)) {
-        setoption(options, save, VOLOPT_DENY, val);
-
-    } else if (optionok(tmp, "rwlist:", val)) {
-        setoption(options, save, VOLOPT_RWLIST, val);
-
-    } else if (optionok(tmp, "rolist:", val)) {
-        setoption(options, save, VOLOPT_ROLIST, val);
-
-    } else if (optionok(tmp, "codepage:", val)) {
-        LOG (log_error, logtype_afpd, "The old codepage system has been removed. Please make sure to read the documentation !!!!");
-        /* Make sure we don't screw anything */
-        exit (EXITERR_CONF);
-    } else if (optionok(tmp, "volcharset:", val)) {
-        setoption(options, save, VOLOPT_ENCODING, val);
-    } else if (optionok(tmp, "maccharset:", val)) {
-        setoption(options, save, VOLOPT_MACCHARSET, val);
-    } else if (optionok(tmp, "veto:", val)) {
-        setoption(options, save, VOLOPT_VETO, val);
-    } else if (optionok(tmp, "cnidscheme:", val)) {
-        setoption(options, save, VOLOPT_CNIDSCHEME, val);
-    } else if (optionok(tmp, "casefold:", val)) {
-        if (strcasecmp(val + 1, "tolower") == 0)
-            options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMLOWER;
-        else if (strcasecmp(val + 1, "toupper") == 0)
-            options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMUPPER;
-        else if (strcasecmp(val + 1, "xlatelower") == 0)
-            options[VOLOPT_CASEFOLD].i_value = AFPVOL_UUPPERMLOWER;
-        else if (strcasecmp(val + 1, "xlateupper") == 0)
-            options[VOLOPT_CASEFOLD].i_value = AFPVOL_ULOWERMUPPER;
-    } else if (optionok(tmp, "adouble:", val)) {
-        if (strcasecmp(val + 1, "v1") == 0)
-            options[VOLOPT_ADOUBLE].i_value = AD_VERSION1;
-#if AD_VERSION == AD_VERSION2
-        else if (strcasecmp(val + 1, "v2") == 0)
-            options[VOLOPT_ADOUBLE].i_value = AD_VERSION2;
-        else if (strcasecmp(val + 1, "osx") == 0)
-            options[VOLOPT_ADOUBLE].i_value = AD_VERSION2_OSX;
-        else if (strcasecmp(val + 1, "sfm") == 0)
-            options[VOLOPT_ADOUBLE].i_value = AD_VERSION1_SFM;
-#endif
-    } else if (optionok(tmp, "options:", val)) {
-        char *p;
-
-        if ((p = strtok(val + 1, ",")) == NULL) /* nothing */
-            return;
-
-        while (p) {
-            if (strcasecmp(p, "prodos") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_A2VOL;
-            else if (strcasecmp(p, "mswindows") == 0) {
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_MSWINDOWS | AFPVOL_USEDOTS;
-            } else if (strcasecmp(p, "crlf") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_CRLF;
-            else if (strcasecmp(p, "noadouble") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_NOADOUBLE;
-            else if (strcasecmp(p, "ro") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
-            else if (strcasecmp(p, "nohex") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_NOHEX;
-            else if (strcasecmp(p, "usedots") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_USEDOTS;
-            else if (strcasecmp(p, "invisibledots") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_USEDOTS | AFPVOL_INV_DOTS;
-            else if (strcasecmp(p, "limitsize") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_LIMITSIZE;
-            /* support for either "dropbox" or "dropkludge" */
-            else if (strcasecmp(p, "dropbox") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_DROPBOX;
-            else if (strcasecmp(p, "dropkludge") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_DROPBOX;
-            else if (strcasecmp(p, "nofileid") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_NOFILEID;
-            else if (strcasecmp(p, "nostat") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_NOSTAT;
-            else if (strcasecmp(p, "preexec_close") == 0)
-                options[VOLOPT_PREEXEC].i_value = 1;
-            else if (strcasecmp(p, "root_preexec_close") == 0)
-                options[VOLOPT_ROOTPREEXEC].i_value = 1;
-            else if (strcasecmp(p, "upriv") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_UNIX_PRIV;
-            else if (strcasecmp(p, "nodev") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_NODEV;
-            else if (strcasecmp(p, "caseinsensitive") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_CASEINSEN;
-            else if (strcasecmp(p, "illegalseq") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_EILSEQ;
-            else if (strcasecmp(p, "nocnidcache") == 0)
-                options[VOLOPT_FLAGS].i_value &= ~AFPVOL_CACHE;
-            else if (strcasecmp(p, "tm") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_TM;
-            else if (strcasecmp(p, "searchdb") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_SEARCHDB;
-            else if (strcasecmp(p, "nonetids") == 0)
-                options[VOLOPT_FLAGS].i_value |= AFPVOL_NONETIDS;
-            else if (strcasecmp(p, "noacls") == 0)
-                options[VOLOPT_FLAGS].i_value &= ~AFPVOL_ACLS;
-            p = strtok(NULL, ",");
-        }
-
-    } else if (optionok(tmp, "cnidserver:", val)) {
-        setoption(options, save, VOLOPT_CNIDSERVER, val);
-
-        char *p = strrchr(val + 1, ':');
-        if (p) {
-            *p = 0;
-            setoption(options, save, VOLOPT_CNIDPORT, p);
-        }
-
-        LOG(log_debug, logtype_afpd, "CNID Server for volume '%s': %s:%s",
-            volname, val + 1, p ? p + 1 : Cnid_port);
-
-    } else if (optionok(tmp, "dbpath:", val)) {
-        setoption(options, save, VOLOPT_DBPATH, val);
-
-    } else if (optionok(tmp, "umask:", val)) {
-        options[VOLOPT_UMASK].i_value = (int)strtol(val +1, NULL, 8);
-    } else if (optionok(tmp, "dperm:", val)) {
-        options[VOLOPT_DPERM].i_value = (int)strtol(val+1, NULL, 8);
-    } else if (optionok(tmp, "fperm:", val)) {
-        options[VOLOPT_FPERM].i_value = (int)strtol(val+1, NULL, 8);
-    } else if (optionok(tmp, "perm:", val)) {
-        options[VOLOPT_DFLTPERM].i_value = (int)strtol(val+1, NULL, 8);
-    } else if (optionok(tmp, "password:", val)) {
-        setoption(options, save, VOLOPT_PASSWORD, val);
-
-#ifdef FORCE_UIDGID
-
-        /* this code allows forced uid/gid per volume settings */
-    } else if (optionok(tmp, "forceuid:", val)) {
-        setoption(options, save, VOLOPT_FORCEUID, val);
-    } else if (optionok(tmp, "forcegid:", val)) {
-        setoption(options, save, VOLOPT_FORCEGID, val);
-
-#endif /* FORCE_UIDGID */
-    } else if (optionok(tmp, "root_preexec:", val)) {
-        setoption(options, save, VOLOPT_ROOTPREEXEC, val);
-
-    } else if (optionok(tmp, "preexec:", val)) {
-        setoption(options, save, VOLOPT_PREEXEC, val);
-
-    } else if (optionok(tmp, "root_postexec:", val)) {
-        setoption(options, save, VOLOPT_ROOTPOSTEXEC, val);
-
-    } else if (optionok(tmp, "postexec:", val)) {
-        setoption(options, save, VOLOPT_POSTEXEC, val);
-
-    } else if (optionok(tmp, "allowed_hosts:", val)) {
-        setoption(options, save, VOLOPT_ALLOWED_HOSTS, val);
-
-    } else if (optionok(tmp, "denied_hosts:", val)) {
-        setoption(options, save, VOLOPT_DENIED_HOSTS, val);
-
-    } else if (optionok(tmp, "ea:", val)) {
-        if (strcasecmp(val + 1, "ad") == 0)
-            options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AD;
-        else if (strcasecmp(val + 1, "sys") == 0)
-            options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_SYS;
-        else if (strcasecmp(val + 1, "none") == 0)
-            options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_NONE;
-
-    } else if (optionok(tmp, "volsizelimit:", val)) {
-        options[VOLOPT_LIMITSIZE].i_value = (uint32_t)strtoul(val + 1, NULL, 10);
-
-    } else {
-        /* ignore unknown options */
-        LOG(log_debug, logtype_afpd, "ignoring unknown volume option: %s", tmp);
-
-    }
-}
-
-/* ----------------- */
-static void showvol(const ucs2_t *name)
-{
-    struct vol  *volume;
-    for ( volume = Volumes; volume; volume = volume->v_next ) {
-        if (volume->v_hide && !strcasecmp_w( volume->v_name, name ) ) {
-            volume->v_hide = 0;
-            return;
-        }
-    }
-}
-
-/* ------------------------------- */
-static int creatvol(AFPObj *obj, struct passwd *pwd,
-                    char *path, char *name,
-                    struct vol_option *options,
-                    const int user /* user defined volume */
-    )
-{
-    struct vol  *volume;
-    int         suffixlen, vlen, tmpvlen, u8mvlen, macvlen;
-    int         hide = 0;
-    char        tmpname[AFPVOL_U8MNAMELEN+1];
-    ucs2_t      u8mtmpname[(AFPVOL_U8MNAMELEN+1)*2], mactmpname[(AFPVOL_MACNAMELEN+1)*2];
-    char        suffix[6]; /* max is #FFFF */
-    u_int16_t   flags;
-
-    LOG(log_debug, logtype_afpd, "createvol: Volume '%s'", name);
-
-    if ( name == NULL || *name == '\0' ) {
-        if ((name = strrchr( path, '/' )) == NULL) {
-            return -1;  /* Obviously not a fully qualified path */
-        }
-
-        /* if you wish to share /, you need to specify a name. */
-        if (*++name == '\0')
-            return -1;
-    }
-
-    /* suffix for mangling use (lastvid + 1)   */
-    /* because v_vid has not been decided yet. */
-    suffixlen = sprintf(suffix, "%c%X", MANGLE_CHAR, lastvid + 1 );
-
-    vlen = strlen( name );
-
-    /* Unicode Volume Name */
-    /* Firstly convert name from unixcharset to UTF8-MAC */
-    flags = CONV_IGNORE;
-    tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
-    if (tmpvlen <= 0) {
-        strcpy(tmpname, "???");
-        tmpvlen = 3;
-    }
-
-    /* Do we have to mangle ? */
-    if ( (flags & CONV_REQMANGLE) || (tmpvlen > obj->options.volnamelen)) {
-        if (tmpvlen + suffixlen > obj->options.volnamelen) {
-            flags = CONV_FORCE;
-            tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, obj->options.volnamelen - suffixlen, &flags);
-            tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
-        }
-        strcat(tmpname, suffix);
-        tmpvlen = strlen(tmpname);
-    }
-
-    /* Secondly convert name from UTF8-MAC to UCS2 */
-    if ( 0 >= ( u8mvlen = convert_string(CH_UTF8_MAC, CH_UCS2, tmpname, tmpvlen, u8mtmpname, AFPVOL_U8MNAMELEN*2)) )
-        return -1;
-
-    LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' -> UTF8-MAC Name: '%s'", name, tmpname);
-
-    /* Maccharset Volume Name */
-    /* Firsty convert name from unixcharset to maccharset */
-    flags = CONV_IGNORE;
-    tmpvlen = convert_charset(obj->options.unixcharset, obj->options.maccharset, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
-    if (tmpvlen <= 0) {
-        strcpy(tmpname, "???");
-        tmpvlen = 3;
-    }
-
-    /* Do we have to mangle ? */
-    if ( (flags & CONV_REQMANGLE) || (tmpvlen > AFPVOL_MACNAMELEN)) {
-        if (tmpvlen + suffixlen > AFPVOL_MACNAMELEN) {
-            flags = CONV_FORCE;
-            tmpvlen = convert_charset(obj->options.unixcharset,
-                                      obj->options.maccharset,
-                                      0,
-                                      name,
-                                      vlen,
-                                      tmpname,
-                                      AFPVOL_MACNAMELEN - suffixlen,
-                                      &flags);
-            tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
-        }
-        strcat(tmpname, suffix);
-        tmpvlen = strlen(tmpname);
-    }
-
-    /* Secondly convert name from maccharset to UCS2 */
-    if ( 0 >= ( macvlen = convert_string(obj->options.maccharset,
-                                         CH_UCS2,
-                                         tmpname,
-                                         tmpvlen,
-                                         mactmpname,
-                                         AFPVOL_U8MNAMELEN*2)) )
-        return -1;
-
-    LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' ->  Longname: '%s'", name, tmpname);
-
-    /* check duplicate */
-    for ( volume = Volumes; volume; volume = volume->v_next ) {
-        if ((utf8_encoding() && (strcasecmp_w(volume->v_u8mname, u8mtmpname) == 0))
-             ||
-            (!utf8_encoding() && (strcasecmp_w(volume->v_macname, mactmpname) == 0))) {
-            LOG (log_error, logtype_afpd,
-                 "Duplicate volume name, check AppleVolumes files: previous: \"%s\", new: \"%s\"",
-                 volume->v_localname, name);
-            if (volume->v_deleted) {
-                volume->v_new = hide = 1;
-            }
-            else {
-                return -1;  /* Won't be able to access it, anyway... */
-            }
-        }
-    }
-
-    if (!( volume = (struct vol *)calloc(1, sizeof( struct vol ))) ) {
-        LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
-        return -1;
-    }
-    if ( NULL == ( volume->v_localname = strdup(name))) {
-        LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
-        free(volume);
-        return -1;
-    }
-
-    if ( NULL == ( volume->v_u8mname = strdup_w(u8mtmpname))) {
-        LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
-        volume_free(volume);
-        free(volume);
-        return -1;
-    }
-    if ( NULL == ( volume->v_macname = strdup_w(mactmpname))) {
-        LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
-        volume_free(volume);
-        free(volume);
-        return -1;
-    }
-    if (!( volume->v_path = (char *)malloc( strlen( path ) + 1 )) ) {
-        LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
-        volume_free(volume);
-        free(volume);
-        return -1;
-    }
-
-    volume->v_name = utf8_encoding()?volume->v_u8mname:volume->v_macname;
-    volume->v_hide = hide;
-    strcpy( volume->v_path, path );
-
-#ifdef __svr4__
-    volume->v_qfd = -1;
-#endif /* __svr4__ */
-    /* os X start at 1 and use network order ie. 1 2 3 */
-    volume->v_vid = ++lastvid;
-    volume->v_vid = htons(volume->v_vid);
-#ifdef HAVE_ACLS
-    if (!check_vol_acl_support(volume)) {
-        LOG(log_debug, logtype_afpd, "creatvol(\"%s\"): disabling ACL support", volume->v_path);
-        options[VOLOPT_FLAGS].i_value &= ~AFPVOL_ACLS;
-    }
-#endif
-
-    /* handle options */
-    if (options) {
-        volume->v_casefold = options[VOLOPT_CASEFOLD].i_value;
-        volume->v_flags |= options[VOLOPT_FLAGS].i_value;
-
-        if (options[VOLOPT_EA_VFS].i_value)
-            volume->v_vfs_ea = options[VOLOPT_EA_VFS].i_value;
-
-        volume->v_ad_options = 0;
-        if ((volume->v_flags & AFPVOL_NODEV))
-            volume->v_ad_options |= ADVOL_NODEV;
-        if ((volume->v_flags & AFPVOL_CACHE))
-            volume->v_ad_options |= ADVOL_CACHE;
-        if ((volume->v_flags & AFPVOL_UNIX_PRIV))
-            volume->v_ad_options |= ADVOL_UNIXPRIV;
-        if ((volume->v_flags & AFPVOL_INV_DOTS))
-            volume->v_ad_options |= ADVOL_INVDOTS;
-        if ((volume->v_flags & AFPVOL_NOADOUBLE))
-            volume->v_ad_options |= ADVOL_NOADOUBLE;
-
-        if (options[VOLOPT_PASSWORD].c_value)
-            volume->v_password = strdup(options[VOLOPT_PASSWORD].c_value);
-
-        if (options[VOLOPT_VETO].c_value)
-            volume->v_veto = strdup(options[VOLOPT_VETO].c_value);
-
-        if (options[VOLOPT_ENCODING].c_value)
-            volume->v_volcodepage = strdup(options[VOLOPT_ENCODING].c_value);
-
-        if (options[VOLOPT_MACCHARSET].c_value)
-            volume->v_maccodepage = strdup(options[VOLOPT_MACCHARSET].c_value);
-
-        if (options[VOLOPT_DBPATH].c_value)
-            volume->v_dbpath = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_DBPATH].c_value, pwd, path, name);
-
-        if (options[VOLOPT_CNIDSCHEME].c_value)
-            volume->v_cnidscheme = strdup(options[VOLOPT_CNIDSCHEME].c_value);
-
-        if (options[VOLOPT_CNIDSERVER].c_value)
-            volume->v_cnidserver = strdup(options[VOLOPT_CNIDSERVER].c_value);
-
-        if (options[VOLOPT_CNIDPORT].c_value)
-            volume->v_cnidport = strdup(options[VOLOPT_CNIDPORT].c_value);
-
-        if (options[VOLOPT_UMASK].i_value)
-            volume->v_umask = (mode_t)options[VOLOPT_UMASK].i_value;
-
-        if (options[VOLOPT_DPERM].i_value)
-            volume->v_dperm = (mode_t)options[VOLOPT_DPERM].i_value;
-
-        if (options[VOLOPT_FPERM].i_value)
-            volume->v_fperm = (mode_t)options[VOLOPT_FPERM].i_value;
-
-        if (options[VOLOPT_DFLTPERM].i_value)
-            volume->v_perm = (mode_t)options[VOLOPT_DFLTPERM].i_value;
-
-        if (options[VOLOPT_ADOUBLE].i_value)
-            volume->v_adouble = options[VOLOPT_ADOUBLE].i_value;
-        else
-            volume->v_adouble = AD_VERSION;
-
-        if (options[VOLOPT_LIMITSIZE].i_value)
-            volume->v_limitsize = options[VOLOPT_LIMITSIZE].i_value;
-
-        /* Mac to Unix conversion flags*/
-        volume->v_mtou_flags = 0;
-        if (!(volume->v_flags & AFPVOL_NOHEX))
-            volume->v_mtou_flags |= CONV_ESCAPEHEX;
-        if (!(volume->v_flags & AFPVOL_USEDOTS))
-            volume->v_mtou_flags |= CONV_ESCAPEDOTS;
-        if ((volume->v_flags & AFPVOL_EILSEQ))
-            volume->v_mtou_flags |= CONV__EILSEQ;
-
-        if ((volume->v_casefold & AFPVOL_MTOUUPPER))
-            volume->v_mtou_flags |= CONV_TOUPPER;
-        else if ((volume->v_casefold & AFPVOL_MTOULOWER))
-            volume->v_mtou_flags |= CONV_TOLOWER;
-
-        /* Unix to Mac conversion flags*/
-        volume->v_utom_flags = CONV_IGNORE | CONV_UNESCAPEHEX;
-        if ((volume->v_casefold & AFPVOL_UTOMUPPER))
-            volume->v_utom_flags |= CONV_TOUPPER;
-        else if ((volume->v_casefold & AFPVOL_UTOMLOWER))
-            volume->v_utom_flags |= CONV_TOLOWER;
-
-        if ((volume->v_flags & AFPVOL_EILSEQ))
-            volume->v_utom_flags |= CONV__EILSEQ;
-
-#ifdef FORCE_UIDGID
-        if (options[VOLOPT_FORCEUID].c_value) {
-            volume->v_forceuid = strdup(options[VOLOPT_FORCEUID].c_value);
-        } else {
-            volume->v_forceuid = NULL; /* set as null so as to return 0 later on */
-        }
-
-        if (options[VOLOPT_FORCEGID].c_value) {
-            volume->v_forcegid = strdup(options[VOLOPT_FORCEGID].c_value);
-        } else {
-            volume->v_forcegid = NULL; /* set as null so as to return 0 later on */
-        }
-#endif
-        if (!user) {
-            if (options[VOLOPT_PREEXEC].c_value)
-                volume->v_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_PREEXEC].c_value, pwd, path, name);
-            volume->v_preexec_close = options[VOLOPT_PREEXEC].i_value;
-
-            if (options[VOLOPT_POSTEXEC].c_value)
-                volume->v_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_POSTEXEC].c_value, pwd, path, name);
-
-            if (options[VOLOPT_ROOTPREEXEC].c_value)
-                volume->v_root_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPREEXEC].c_value, pwd, path,  name);
-            volume->v_root_preexec_close = options[VOLOPT_ROOTPREEXEC].i_value;
-
-            if (options[VOLOPT_ROOTPOSTEXEC].c_value)
-                volume->v_root_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPOSTEXEC].c_value, pwd, path,  name);
-        }
-    }
-    volume->v_dperm |= volume->v_perm;
-    volume->v_fperm |= volume->v_perm;
-
-    /* Check EA support on volume */
-    if (volume->v_vfs_ea == AFPVOL_EA_AUTO)
-        check_ea_sys_support(volume);
-    initvol_vfs(volume);
-
-    /* get/store uuid from file in afpd master*/
-    if ((parent_or_child == 0) && (volume->v_flags & AFPVOL_TM)) {
-        char *uuid = get_vol_uuid(obj, volume->v_localname);
-        if (!uuid) {
-            LOG(log_error, logtype_afpd, "Volume '%s': couldn't get UUID",
-                volume->v_localname);
-        } else {
-            volume->v_uuid = uuid;
-            LOG(log_debug, logtype_afpd, "Volume '%s': UUID '%s'",
-                volume->v_localname, volume->v_uuid);
-        }
-    }
-
-    volume->v_next = Volumes;
-    Volumes = volume;
-    return 0;
-}
-
-/* ---------------- */
-static char *myfgets( char *buf, int size, FILE *fp)
-{
-    char    *p;
-    int     c;
-
-    p = buf;
-    while ((EOF != ( c = getc( fp )) ) && ( size > 1 )) {
-        if ( c == '\n' || c == '\r' ) {
-            if (p != buf && *(p -1) == '\\') {
-                p--;
-                size++;
-                continue;
-            }
-            *p++ = '\n';
-            break;
-        } else {
-            *p++ = c;
-        }
-        size--;
-    }
-
-    if ( p == buf ) {
-        return( NULL );
-    } else {
-        *p = '\0';
-        return( buf );
-    }
-}
-
-
-/* check access list. this function wants something of the following
- * form:
- *        @group,name,name2,@group2,name3
- *
- * a NULL argument allows everybody to have access.
- * we return three things:
- *     -1: no list
- *      0: list exists, but name isn't in it
- *      1: in list
- */
-
-#ifndef NO_REAL_USER_NAME
-/* authentication is case insensitive
- * FIXME should we do the same with group name?
- */
-#define access_strcmp strcasecmp
-
-#else
-#define access_strcmp strcmp
-
-#endif
-
-static int accessvol(const char *args, const char *name)
-{
-    char buf[MAXPATHLEN + 1], *p;
-    struct group *gr;
-
-    if (!args)
-        return -1;
-
-    strlcpy(buf, args, sizeof(buf));
-    if ((p = strtok(buf, ",")) == NULL) /* nothing, return okay */
-        return -1;
-
-    while (p) {
-        if (*p == '@') { /* it's a group */
-            if ((gr = getgrnam(p + 1)) && gmem(gr->gr_gid))
-                return 1;
-        } else if (access_strcmp(p, name) == 0) /* it's a user name */
-            return 1;
-        p = strtok(NULL, ",");
-    }
-
-    return 0;
-}
-
-static int hostaccessvol(int type, const char *volname, const char *args, const AFPObj *obj)
-{
-    int mask_int;
-    char buf[MAXPATHLEN + 1], *p, *b;
-    DSI *dsi = obj->handle;
-    struct sockaddr_storage client;
-
-    if (!args)
-        return -1;
-
-    strlcpy(buf, args, sizeof(buf));
-    if ((p = strtok_r(buf, ",", &b)) == NULL) /* nothing, return okay */
-        return -1;
-
-    if (obj->proto != AFPPROTO_DSI)
-        return -1;
-
-    while (p) {
-        int ret;
-        char *ipaddr, *mask_char;
-        struct addrinfo hints, *ai;
-
-        ipaddr = strtok(p, "/");
-        mask_char = strtok(NULL,"/");
-
-        /* Get address from string with getaddrinfo */
-        memset(&hints, 0, sizeof hints);
-        hints.ai_family = AF_UNSPEC;
-        hints.ai_socktype = SOCK_STREAM;
-        if ((ret = getaddrinfo(ipaddr, NULL, &hints, &ai)) != 0) {
-            LOG(log_error, logtype_afpd, "hostaccessvol: getaddrinfo: %s\n", gai_strerror(ret));
-            continue;
-        }
-
-        /* netmask */
-        if (mask_char != NULL)
-            mask_int = atoi(mask_char); /* apply_ip_mask does range checking on it */
-        else {
-            if (ai->ai_family == AF_INET) /* IPv4 */
-                mask_int = 32;
-            else                          /* IPv6 */
-                mask_int = 128;
-        }
-
-        /* Apply mask to addresses */
-        client = dsi->client;
-        apply_ip_mask((struct sockaddr *)&client, mask_int);
-        apply_ip_mask(ai->ai_addr, mask_int);
-
-        if (compare_ip((struct sockaddr *)&client, ai->ai_addr) == 0) {
-            if (type == VOLOPT_DENIED_HOSTS)
-                LOG(log_info, logtype_afpd, "AFP access denied for client IP '%s' to volume '%s' by denied list",
-                    getip_string((struct sockaddr *)&client), volname);
-            freeaddrinfo(ai);
-            return 1;
-        }
-
-        /* next address */
-        freeaddrinfo(ai);
-        p = strtok_r(NULL, ",", &b);
-    }
-
-    if (type == VOLOPT_ALLOWED_HOSTS)
-        LOG(log_info, logtype_afpd, "AFP access denied for client IP '%s' to volume '%s', not in allowed list",
-            getip_string((struct sockaddr *)&dsi->client), volname);
-    return 0;
-}
-
-static void setextmap(char *ext, char *type, char *creator, int user)
-{
-    struct extmap   *em;
-    int                 cnt;
-
-    if (Extmap == NULL) {
-        if (( Extmap = calloc(1, sizeof( struct extmap ))) == NULL ) {
-            LOG(log_error, logtype_afpd, "setextmap: calloc: %s", strerror(errno) );
-            return;
-        }
-    }
-    ext++;
-    for ( em = Extmap, cnt = 0; em->em_ext; em++, cnt++) {
-        if ( (strdiacasecmp( em->em_ext, ext )) == 0 ) {
-            break;
-        }
-    }
-
-    if ( em->em_ext == NULL ) {
-        if (!(Extmap  = realloc( Extmap, sizeof( struct extmap ) * (cnt +2))) ) {
-            LOG(log_error, logtype_afpd, "setextmap: realloc: %s", strerror(errno) );
-            return;
-        }
-        (Extmap +cnt +1)->em_ext = NULL;
-        em = Extmap +cnt;
-    } else if ( !user ) {
-        return;
-    }
-    if (em->em_ext)
-        free(em->em_ext);
-
-    if (!(em->em_ext = strdup(  ext))) {
-        LOG(log_error, logtype_afpd, "setextmap: strdup: %s", strerror(errno) );
-        return;
-    }
-
-    if ( *type == '\0' ) {
-        memcpy(em->em_type, "\0\0\0\0", sizeof( em->em_type ));
-    } else {
-        memcpy(em->em_type, type, sizeof( em->em_type ));
-    }
-    if ( *creator == '\0' ) {
-        memcpy(em->em_creator, "\0\0\0\0", sizeof( em->em_creator ));
-    } else {
-        memcpy(em->em_creator, creator, sizeof( em->em_creator ));
-    }
-}
-
-/* -------------------------- */
-static int extmap_cmp(const void *map1, const void *map2)
-{
-    const struct extmap *em1 = map1;
-    const struct extmap *em2 = map2;
-    return strdiacasecmp(em1->em_ext, em2->em_ext);
-}
-
-static void sortextmap( void)
-{
-    struct extmap   *em;
-
-    Extmap_cnt = 0;
-    if ((em = Extmap) == NULL) {
-        return;
-    }
-    while (em->em_ext) {
-        em++;
-        Extmap_cnt++;
-    }
-    if (Extmap_cnt) {
-        qsort(Extmap, Extmap_cnt, sizeof(struct extmap), extmap_cmp);
-        if (*Extmap->em_ext == 0) {
-            /* the first line is really "." the default entry,
-             * we remove the leading '.' in setextmap
-             */
-            Defextmap = Extmap;
-        }
-    }
-}
-
-/* ----------------------
- */
-static void free_extmap( void)
-{
-    struct extmap   *em;
-
-    if (Extmap) {
-        for ( em = Extmap; em->em_ext; em++) {
-            free (em->em_ext);
-        }
-        free(Extmap);
-        Extmap = NULL;
-        Defextmap = Extmap;
-        Extmap_cnt = 0;
-    }
-}
-
-/* ----------------------
- */
-static int volfile_changed(struct afp_volume_name *p)
-{
-    struct stat      st;
-    char *name;
-
-    if (p->full_name)
-        name = p->full_name;
-    else
-        name = p->name;
-
-    if (!stat( name, &st) && st.st_mtime > p->mtime) {
-        p->mtime = st.st_mtime;
-        return 1;
-    }
-    return 0;
-}
-
-/* ----------------------
- * Read a volume configuration file and add the volumes contained within to
- * the global volume list. This gets called from the forked afpd childs.
- * The master now reads this too for Zeroconf announcements.
- *
- * If p2 is non-NULL, the file that is opened is
- * p1/p2
- *
- * Lines that begin with # and blank lines are ignored.
- * Volume lines are of the form:
- *      <unix path> [<volume name>] [allow:<user>,<@group>,...] \
- *                           [codepage:<file>] [casefold:<num>]
- *      <extension> TYPE [CREATOR]
- *
- */
-static int readvolfile(AFPObj *obj, struct afp_volume_name *p1, char *p2, int user, struct passwd *pwent)
-{
-    FILE        *fp;
-    char        path[MAXPATHLEN + 1];
-    char        tmp[MAXPATHLEN + 1];
-    char        volname[AFPVOL_U8MNAMELEN + 1];
-    char        buf[BUFSIZ];
-    char        type[5], creator[5];
-    char        *u, *p;
-    int         fd;
-    int         i;
-    struct passwd   *pw;
-    struct vol_option   save_options[VOLOPT_NUM];
-    struct vol_option   default_options[VOLOPT_NUM];
-    struct vol_option   options[VOLOPT_NUM];
-    struct stat         st;
-
-    if (!p1->name)
-        return -1;
-    p1->mtime = 0;
-    strcpy( path, p1->name );
-    if ( p2 != NULL ) {
-        strcat( path, "/" );
-        strcat( path, p2 );
-        if (p1->full_name) {
-            free(p1->full_name);
-        }
-        p1->full_name = strdup(path);
-    }
-
-    if (NULL == ( fp = fopen( path, "r" )) ) {
-        return( -1 );
-    }
-    fd = fileno(fp);
-    if (fd != -1 && !fstat( fd, &st) ) {
-        p1->mtime = st.st_mtime;
-    }
-
-    /* try putting a read lock on the volume file twice, sleep 1 second if first attempt fails */
-    int retries = 2;
-    while (1) {
-        if ((read_lock(fd, 0, SEEK_SET, 0)) != 0) {
-            retries--;
-            if (!retries) {
-                LOG(log_error, logtype_afpd, "readvolfile: can't lock volume file \"%s\"", path);
-                if ( fclose( fp ) != 0 ) {
-                    LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
-                }
-                return -1;
-            }
-            sleep(1);
-            continue;
-        }
-        break;
-    }
-
-    memset(default_options, 0, sizeof(default_options));
-
-    /* Enable some default options for all volumes */
-    default_options[VOLOPT_FLAGS].i_value |= AFPVOL_CACHE;
-#ifdef HAVE_ACLS
-    default_options[VOLOPT_FLAGS].i_value |= AFPVOL_ACLS;
-#endif
-    default_options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AUTO;
-    LOG(log_maxdebug, logtype_afpd, "readvolfile: seeding default umask: %04o",
-        obj->options.umask);
-    default_options[VOLOPT_UMASK].i_value = obj->options.umask;
-    memcpy(save_options, default_options, sizeof(options));
-
-    LOG(log_debug, logtype_afpd, "readvolfile: \"%s\"", path);
-
-    while ( myfgets( buf, sizeof( buf ), fp ) != NULL ) {
-        initline( strlen( buf ), buf );
-        parseline( sizeof( path ) - 1, path );
-        switch ( *path ) {
-        case '\0' :
-        case '#' :
-            continue;
-
-        case ':':
-            /* change the default options for this file */
-            if (strncmp(path, VOLOPT_DEFAULT, VOLOPT_DEFAULT_LEN) == 0) {
-                volfree(default_options, save_options);
-                memcpy(default_options, save_options, sizeof(options));
-                *tmp = '\0';
-                for (i = 0; i < VOLOPT_NUM; i++) {
-                    if (parseline( sizeof( path ) - VOLOPT_DEFAULT_LEN - 1,
-                                   path + VOLOPT_DEFAULT_LEN) < 0)
-                        break;
-                    volset(default_options, NULL, tmp, sizeof(tmp) - 1,
-                           path + VOLOPT_DEFAULT_LEN);
-                }
-            }
-            break;
-
-        case '~' :
-            if (( p = strchr( path, '/' )) != NULL ) {
-                *p++ = '\0';
-            }
-            u = path;
-            u++;
-            if ( *u == '\0' ) {
-                u = obj->username;
-            }
-            if ( u == NULL || *u == '\0' || ( pw = getpwnam( u )) == NULL ) {
-                continue;
-            }
-            strcpy( tmp, pw->pw_dir );
-            if ( p != NULL && *p != '\0' ) {
-                strcat( tmp, "/" );
-                strcat( tmp, p );
-            }
-            /* fall through */
-
-        case '/' :
-            /* send path through variable substitution */
-            if (*path != '~') /* need to copy path to tmp */
-                strcpy(tmp, path);
-            if (!pwent && obj->username)
-                pwent = getpwnam(obj->username);
-
-            if (volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL) == NULL)
-                continue;
-
-            /* this is sort of braindead. basically, i want to be
-             * able to specify things in any order, but i don't want to
-             * re-write everything. */
-
-            memcpy(options, default_options, sizeof(options));
-            *volname = '\0';
-
-            /* read in up to VOLOP_NUM possible options */
-            for (i = 0; i < VOLOPT_NUM; i++) {
-                if (parseline( sizeof( tmp ) - 1, tmp ) < 0)
-                    break;
-
-                volset(options, default_options, volname, sizeof(volname) - 1, tmp);
-            }
-
-            /* check allow/deny lists (if not afpd master loading volumes for Zeroconf reg.):
-               allow -> either no list (-1), or in list (1)
-               deny -> either no list (-1), or not in list (0) */
-            if (parent_or_child == 0
-                ||
-                (accessvol(options[VOLOPT_ALLOW].c_value, obj->username) &&
-                 (accessvol(options[VOLOPT_DENY].c_value, obj->username) < 1) &&
-                 hostaccessvol(VOLOPT_ALLOWED_HOSTS, volname, options[VOLOPT_ALLOWED_HOSTS].c_value, obj) &&
-                 (hostaccessvol(VOLOPT_DENIED_HOSTS, volname, options[VOLOPT_DENIED_HOSTS].c_value, obj) < 1))) {
-
-                /* handle read-only behaviour. semantics:
-                 * 1) neither the rolist nor the rwlist exist -> rw
-                 * 2) rolist exists -> ro if user is in it.
-                 * 3) rwlist exists -> ro unless user is in it. */
-                if (parent_or_child == 1
-                    &&
-                    ((options[VOLOPT_FLAGS].i_value & AFPVOL_RO) == 0)
-                    &&
-                    ((accessvol(options[VOLOPT_ROLIST].c_value, obj->username) == 1) ||
-                     !accessvol(options[VOLOPT_RWLIST].c_value, obj->username)))
-                    options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
-
-                /* do variable substitution for volname */
-                if (volxlate(obj, tmp, sizeof(tmp) - 1, volname, pwent, path, NULL) == NULL)
-                    continue;
-
-                creatvol(obj, pwent, path, tmp, options, p2 != NULL);
-            }
-            volfree(options, default_options);
-            break;
-
-        case '.' :
-            parseline( sizeof( type ) - 1, type );
-            parseline( sizeof( creator ) - 1, creator );
-            setextmap( path, type, creator, user);
-            break;
-
-        default :
-            break;
-        }
-    }
-    volfree(save_options, NULL);
-    sortextmap();
-    if ( fclose( fp ) != 0 ) {
-        LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
-    }
-    p1->loaded = 1;
-    return( 0 );
-}
-
-/* ------------------------------- */
-static void volume_free(struct vol *vol)
-{
-    free(vol->v_localname);
-    vol->v_localname = NULL;
-    free(vol->v_u8mname);
-    vol->v_u8mname = NULL;
-    free(vol->v_macname);
-    vol->v_macname = NULL;
-    free(vol->v_path);
-    free(vol->v_password);
-    free(vol->v_veto);
-    free(vol->v_volcodepage);
-    free(vol->v_maccodepage);
-    free(vol->v_cnidscheme);
-    free(vol->v_dbpath);
-    free(vol->v_gvs);
-#ifdef FORCE_UIDGID
-    free(vol->v_forceuid);
-    free(vol->v_forcegid);
-#endif /* FORCE_UIDGID */
-    if (vol->v_uuid)
-        free(vol->v_uuid);
-}
-
-/* ------------------------------- */
-static void free_volumes(void )
-{
-    struct vol  *vol;
-    struct vol  *nvol, *ovol;
+#include <string.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <inttypes.h>
+#include <time.h>
 
-    for ( vol = Volumes; vol; vol = vol->v_next ) {
-        if (( vol->v_flags & AFPVOL_OPEN ) ) {
-            vol->v_deleted = 1;
-            continue;
-        }
-        volume_free(vol);
-    }
+#include <atalk/dsi.h>
+#include <atalk/adouble.h>
+#include <atalk/afp.h>
+#include <atalk/util.h>
+#include <atalk/logger.h>
+#include <atalk/vfs.h>
+#include <atalk/uuid.h>
+#include <atalk/ea.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
+#include <atalk/ftw.h>
+#include <atalk/globals.h>
+#include <atalk/fce_api.h>
+#include <atalk/errchk.h>
+#include <atalk/iniparser.h>
+#include <atalk/unix.h>
+#include <atalk/netatalk_conf.h>
 
-    for ( vol = Volumes, ovol = NULL; vol; vol = nvol) {
-        nvol = vol->v_next;
+#ifdef CNID_DB
+#include <atalk/cnid.h>
+#endif /* CNID_DB*/
 
-        if (vol->v_localname == NULL) {
-            if (Volumes == vol) {
-                Volumes = nvol;
-                ovol = Volumes;
-            }
-            else {
-                ovol->v_next = nvol;
-            }
-            free(vol);
-        }
-        else {
-            ovol = vol;
-        }
-    }
-}
+#include "directory.h"
+#include "file.h"
+#include "volume.h"
+#include "unix.h"
+#include "mangle.h"
+#include "fork.h"
+#include "hash.h"
+#include "acls.h"
 
-/* ------------------------------- */
-static void volume_unlink(struct vol *volume)
-{
-    struct vol *vol, *ovol, *nvol;
+#define VOLPASSLEN  8
 
-    if (volume == Volumes) {
-        Volumes = Volumes->v_next;
-        return;
-    }
-    for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
-        nvol = vol->v_next;
+extern int afprun(int root, char *cmd, int *outfd);
 
-        if (vol == volume) {
-            ovol->v_next = nvol;
-            break;
-        }
-        else {
-            ovol = vol;
-        }
-    }
-}
 /*!
  * Read band-size info from Info.plist XML file of an TM sparsebundle
  *
@@ -1594,12 +206,12 @@ EC_CLEANUP:
     EC_EXIT;
 }
 
-static int getvolspace(struct vol *vol,
-                       u_int32_t *bfree, u_int32_t *btotal,
-                       VolSpace *xbfree, VolSpace *xbtotal, u_int32_t *bsize)
+static int getvolspace(const AFPObj *obj, struct vol *vol,
+                       uint32_t *bfree, uint32_t *btotal,
+                       VolSpace *xbfree, VolSpace *xbtotal, uint32_t *bsize)
 {
     int         spaceflag, rc;
-    u_int32_t   maxsize;
+    uint32_t   maxsize;
     VolSpace    used;
 #ifndef NO_QUOTA_SUPPORT
     VolSpace    qfree, qtotal;
@@ -1607,9 +219,7 @@ static int getvolspace(struct vol *vol,
 
     spaceflag = AFPVOL_GVSMASK & vol->v_flags;
     /* report up to 2GB if afp version is < 2.2 (4GB if not) */
-    maxsize = (vol->v_flags & AFPVOL_A2VOL) ? 0x01fffe00 :
-        (((afp_version < 22) || (vol->v_flags & AFPVOL_LIMITSIZE))
-         ? 0x7fffffffL : 0xffffffffL);
+    maxsize = (obj->afp_version < 22) ? 0x7fffffffL : 0xffffffffL;
 
 #ifdef AFS
     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_AFSGVS ) {
@@ -1626,7 +236,7 @@ static int getvolspace(struct vol *vol,
 
 #ifndef NO_QUOTA_SUPPORT
     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_UQUOTA ) {
-        if ( uquota_getvolspace( vol, &qfree, &qtotal, *bsize ) == AFP_OK ) {
+        if ( uquota_getvolspace(obj, vol, &qfree, &qtotal, *bsize ) == AFP_OK ) {
             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_UQUOTA;
             *xbfree = MIN(*xbfree, qfree);
             *xbtotal = MIN(*xbtotal, qtotal);
@@ -1659,7 +269,7 @@ void vol_fce_tm_event(void)
 {
     static time_t last;
     time_t now = time(NULL);
-    struct vol  *vol = Volumes;
+    struct vol  *vol = getvolumes();
 
     if ((last + FCE_TM_DELTA) < now) {
         last = now;
@@ -1674,18 +284,18 @@ void vol_fce_tm_event(void)
  * set volume creation date
  * avoid duplicate, well at least it tries
  */
-static void vol_setdate(u_int16_t id, struct adouble *adp, time_t date)
+static void vol_setdate(uint16_t id, struct adouble *adp, time_t date)
 {
     struct vol  *volume;
-    struct vol  *vol = Volumes;
+    struct vol  *vol = getvolumes();
 
-    for ( volume = Volumes; volume; volume = volume->v_next ) {
+    for ( volume = getvolumes(); volume; volume = volume->v_next ) {
         if (volume->v_vid == id) {
             vol = volume;
         }
         else if ((time_t)(AD_DATE_FROM_UNIX(date)) == volume->v_ctime) {
             date = date+1;
-            volume = Volumes; /* restart */
+            volume = getvolumes(); /* restart */
         }
     }
     vol->v_ctime = AD_DATE_FROM_UNIX(date);
@@ -1693,13 +303,13 @@ static void vol_setdate(u_int16_t id, struct adouble *adp, time_t date)
 }
 
 /* ----------------------- */
-static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, char *buf, size_t *buflen)
+static int getvolparams(const AFPObj *obj, uint16_t bitmap, struct vol *vol, struct stat *st, char *buf, size_t *buflen)
 {
     struct adouble  ad;
     int         bit = 0, isad = 1;
-    u_int32_t       aint;
+    uint32_t       aint;
     u_short     ashort;
-    u_int32_t       bfree, btotal, bsize;
+    uint32_t       bfree, btotal, bsize;
     VolSpace            xbfree, xbtotal; /* extended bytes */
     char        *data, *nameoff = NULL;
     char                *slash;
@@ -1710,8 +320,11 @@ static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, cha
      * For MacOS8.x support we need to create the
      * .Parent file here if it doesn't exist. */
 
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
-    if ( ad_open_metadata( vol->v_path, ADFLAGS_DIR, O_CREAT, &ad) < 0 ) {
+    /* Convert adouble:v2 to adouble:ea on the fly */
+    (void)ad_convert(vol->v_path, st, vol, NULL);
+
+    ad_init(&ad, vol);
+    if (ad_open(&ad, vol->v_path, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) != 0 ) {
         isad = 0;
         vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
 
@@ -1739,7 +352,7 @@ static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, cha
     if (( bitmap & ( (1<<VOLPBIT_BFREE)|(1<<VOLPBIT_BTOTAL) |
                      (1<<VOLPBIT_XBFREE)|(1<<VOLPBIT_XBTOTAL) |
                      (1<<VOLPBIT_BSIZE)) ) != 0 ) {
-        if ( getvolspace( vol, &bfree, &btotal, &xbfree, &xbtotal,
+        if ( getvolspace(obj, vol, &bfree, &btotal, &xbfree, &xbtotal,
                           &bsize) != AFP_OK ) {
             if ( isad ) {
                 ad_close( &ad, ADFLAGS_HF );
@@ -1767,14 +380,12 @@ static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, cha
                 ashort |= VOLPBIT_ATTR_RO;
             }
             /* prior 2.1 only VOLPBIT_ATTR_RO is defined */
-            if (afp_version > 20) {
-                if (0 == (vol->v_flags & AFPVOL_NOFILEID) && vol->v_cdb != NULL &&
-                    (vol->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
+            if (obj->afp_version > 20) {
+                if (vol->v_cdb != NULL && (vol->v_cdb->flags & CNID_FLAG_PERSISTENT))
                     ashort |= VOLPBIT_ATTR_FILEID;
-                }
                 ashort |= VOLPBIT_ATTR_CATSEARCH;
 
-                if (afp_version >= 30) {
+                if (obj->afp_version >= 30) {
                     ashort |= VOLPBIT_ATTR_UTF8;
                     if (vol->v_flags & AFPVOL_UNIX_PRIV)
                         ashort |= VOLPBIT_ATTR_UNIXPRIV;
@@ -1782,7 +393,7 @@ static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, cha
                         ashort |= VOLPBIT_ATTR_TM;
                     if (vol->v_flags & AFPVOL_NONETIDS)
                         ashort |= VOLPBIT_ATTR_NONETIDS;
-                    if (afp_version >= 32) {
+                    if (obj->afp_version >= 32) {
                         if (vol->v_vfs_ea)
                             ashort |= VOLPBIT_ATTR_EXT_ATTRS;
                         if (vol->v_flags & AFPVOL_ACLS)
@@ -1843,28 +454,20 @@ static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, cha
 #ifndef NO_LARGE_VOL_SUPPORT
         case VOLPBIT_XBFREE :
             xbfree = hton64( xbfree );
-#if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
-            bcopy(&xbfree, data, sizeof(xbfree));
-#else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
             memcpy(data, &xbfree, sizeof( xbfree ));
-#endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
             data += sizeof( xbfree );
             break;
 
         case VOLPBIT_XBTOTAL :
             xbtotal = hton64( xbtotal );
-#if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
-            bcopy(&xbtotal, data, sizeof(xbtotal));
-#else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
             memcpy(data, &xbtotal, sizeof( xbtotal ));
-#endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
             data += sizeof( xbfree );
             break;
 #endif /* ! NO_LARGE_VOL_SUPPORT */
 
         case VOLPBIT_NAME :
             nameoff = data;
-            data += sizeof( u_int16_t );
+            data += sizeof( uint16_t );
             break;
 
         case VOLPBIT_BSIZE:  /* block size */
@@ -1896,14 +499,14 @@ static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, cha
         data += aint;
     }
     if ( isad ) {
-        ad_close_metadata( &ad);
+        ad_close(&ad, ADFLAGS_HF);
     }
     *buflen = data - buf;
     return( AFP_OK );
 }
 
 /* ------------------------- */
-static int stat_vol(u_int16_t bitmap, struct vol *vol, char *rbuf, size_t *rbuflen)
+static int stat_vol(const AFPObj *obj, uint16_t bitmap, struct vol *vol, char *rbuf, size_t *rbuflen)
 {
     struct stat st;
     int     ret;
@@ -1917,7 +520,7 @@ static int stat_vol(u_int16_t bitmap, struct vol *vol, char *rbuf, size_t *rbufl
     vol->v_dev = st.st_dev;
 
     buflen = *rbuflen - sizeof( bitmap );
-    if (( ret = getvolparams( bitmap, vol, &st,
+    if (( ret = getvolparams(obj, bitmap, vol, &st,
                               rbuf + sizeof( bitmap ), &buflen )) != AFP_OK ) {
         *rbuflen = 0;
         return( ret );
@@ -1929,80 +532,6 @@ static int stat_vol(u_int16_t bitmap, struct vol *vol, char *rbuf, size_t *rbufl
 
 }
 
-/* ------------------------------- */
-void load_volumes(AFPObj *obj)
-{
-    struct passwd   *pwent;
-
-    if (Volumes) {
-        int changed = 0;
-
-        /* check files date */
-        if (obj->options.defaultvol.loaded) {
-            changed = volfile_changed(&obj->options.defaultvol);
-        }
-        if (obj->options.systemvol.loaded) {
-            changed |= volfile_changed(&obj->options.systemvol);
-        }
-        if (obj->options.uservol.loaded) {
-            changed |= volfile_changed(&obj->options.uservol);
-        }
-        if (!changed)
-            return;
-
-        free_extmap();
-        free_volumes();
-    }
-
-    if (parent_or_child == 0) {
-        LOG(log_debug, logtype_afpd, "load_volumes: AFP MASTER");
-    } else {
-        LOG(log_debug, logtype_afpd, "load_volumes: user: %s", obj->username);
-    }
-
-    pwent = getpwnam(obj->username);
-    if ( (obj->options.flags & OPTION_USERVOLFIRST) == 0 ) {
-        readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent);
-    }
-
-    if ((*obj->username == '\0') || (obj->options.flags & OPTION_NOUSERVOL)) {
-        readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent);
-    } else if (pwent) {
-        /*
-         * Read user's AppleVolumes or .AppleVolumes file
-         * If neither are readable, read the default volumes file. if
-         * that doesn't work, create a user share.
-         */
-        if (obj->options.uservol.name) {
-            free(obj->options.uservol.name);
-        }
-        obj->options.uservol.name = strdup(pwent->pw_dir);
-        if ( readvolfile(obj, &obj->options.uservol,    "AppleVolumes", 1, pwent) < 0 &&
-             readvolfile(obj, &obj->options.uservol, ".AppleVolumes", 1, pwent) < 0 &&
-             readvolfile(obj, &obj->options.uservol, "applevolumes", 1, pwent) < 0 &&
-             readvolfile(obj, &obj->options.uservol, ".applevolumes", 1, pwent) < 0 &&
-             obj->options.defaultvol.name != NULL ) {
-            if (readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent) < 0)
-                creatvol(obj, pwent, pwent->pw_dir, NULL, NULL, 1);
-        }
-    }
-    if ( obj->options.flags & OPTION_USERVOLFIRST ) {
-        readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent );
-    }
-
-    if ( obj->options.closevol ) {
-        struct vol *vol;
-
-        for ( vol = Volumes; vol; vol = vol->v_next ) {
-            if (vol->v_deleted && !vol->v_new ) {
-                of_closevol(vol);
-                deletevol(vol);
-                vol = Volumes;
-            }
-        }
-    }
-}
-
 /* ------------------------------- */
 int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
 {
@@ -2014,10 +543,10 @@ int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf
     int         vcnt;
     size_t      len;
 
-    load_volumes(obj);
+    load_volumes(obj, closevol);
 
     data = rbuf + 5;
-    for ( vcnt = 0, volume = Volumes; volume; volume = volume->v_next ) {
+    for ( vcnt = 0, volume = getvolumes(); volume; volume = volume->v_next ) {
         if (!(volume->v_flags & AFPVOL_NOSTAT)) {
             struct maccess ma;
 
@@ -2029,16 +558,13 @@ int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf
             if (!S_ISDIR(st.st_mode)) {
                 continue;       /* not a dir */
             }
-            accessmode(volume, volume->v_path, &ma, NULL, &st);
+            accessmode(obj, volume, volume->v_path, &ma, NULL, &st);
             if ((ma.ma_user & (AR_UREAD | AR_USEARCH)) != (AR_UREAD | AR_USEARCH)) {
                 continue;   /* no r-x access */
             }
         }
-        if (volume->v_hide) {
-            continue;       /* config file changed but the volume was mounted */
-        }
 
-        if (utf8_encoding()) {
+        if (utf8_encoding(obj)) {
             len = ucs2_to_charset_allocate(CH_UTF8_MAC, &namebuf, volume->v_u8mname);
         } else {
             len = ucs2_to_charset_allocate(obj->options.maccharset, &namebuf, volume->v_macname);
@@ -2050,13 +576,6 @@ int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf
         /* set password bit if there's a volume password */
         *data = (volume->v_password) ? AFPSRVR_PASSWD : 0;
 
-        /* Apple 2 clients running ProDOS-8 expect one volume to have
-           bit 0 of this byte set.  They will not recognize anything
-           on the server unless this is the case.  I have not
-           completely worked this out, but it's related to booting
-           from the server.  Support for that function is a ways
-           off.. <shirsch@ibm.net> */
-        *data |= (volume->v_flags & AFPVOL_A2VOL) ? AFPSRVR_CONFIGINFO : 0;
         *data++ |= 0; /* UNIX PRIVS BIT ..., OSX doesn't seem to use it, so we don't either */
         *data++ = len;
         memcpy(data, namebuf, len );
@@ -2073,8 +592,8 @@ int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf
         return AFPERR_PARAM;
     }
     tv.tv_sec = AD_DATE_FROM_UNIX(tv.tv_sec);
-    memcpy(data, &tv.tv_sec, sizeof( u_int32_t));
-    data += sizeof( u_int32_t);
+    memcpy(data, &tv.tv_sec, sizeof( uint32_t));
+    data += sizeof( uint32_t);
     *data = vcnt;
     return( AFP_OK );
 }
@@ -2114,7 +633,7 @@ static int volume_codepage(AFPObj *obj, struct vol *volume)
 }
 
 /* ------------------------- */
-static int volume_openDB(struct vol *volume)
+static int volume_openDB(const AFPObj *obj, struct vol *volume)
 {
     int flags = 0;
 
@@ -2122,44 +641,14 @@ static int volume_openDB(struct vol *volume)
         flags |= CNID_FLAG_NODEV;
     }
 
-    if (volume->v_cnidscheme == NULL) {
-        volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
-        LOG(log_info, logtype_afpd, "Volume %s use CNID scheme %s.",
-            volume->v_path, volume->v_cnidscheme);
-    }
-
-    LOG(log_info, logtype_afpd, "CNID server: %s:%s",
-        volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
-        volume->v_cnidport ? volume->v_cnidport : Cnid_port);
-
-#if 0
-/* Found this in branch dir-rewrite, maybe we want to use it sometimes */
-
-    /* Legacy pre 2.1 way of sharing eg CD-ROM */
-    if (strcmp(volume->v_cnidscheme, "last") == 0) {
-        /* "last" is gone. We support it by switching to in-memory "tdb" */
-        volume->v_cnidscheme = strdup("tdb");
-        flags |= CNID_FLAG_MEMORY;
-    }
-
-    /* New way of sharing CD-ROM */
-    if (volume->v_flags & AFPVOL_CDROM) {
-        flags |= CNID_FLAG_MEMORY;
-        if (strcmp(volume->v_cnidscheme, "tdb") != 0) {
-            free(volume->v_cnidscheme);
-            volume->v_cnidscheme = strdup("tdb");
-            LOG(log_info, logtype_afpd, "Volume %s is ejectable, switching to scheme %s.",
-                volume->v_path, volume->v_cnidscheme);
-        }
-    }
-#endif
+    LOG(log_debug, logtype_afpd, "CNID server: %s:%s", volume->v_cnidserver, volume->v_cnidport);
 
     volume->v_cdb = cnid_open(volume->v_path,
                               volume->v_umask,
                               volume->v_cnidscheme,
                               flags,
-                              volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
-                              volume->v_cnidport ? volume->v_cnidport : Cnid_port);
+                              volume->v_cnidserver,
+                              volume->v_cnidport);
 
     if ( ! volume->v_cdb && ! (flags & CNID_FLAG_MEMORY)) {
         /* The first attempt failed and it wasn't yet an attempt to open in-memory */
@@ -2176,7 +665,6 @@ static int volume_openDB(struct vol *volume)
                        "Check server messages for details!");
             kill(getpid(), SIGUSR2);
             /* deactivate cnid caching/storing in AppleDouble files */
-            volume->v_flags &= ~AFPVOL_CACHE;
         }
 #endif
     }
@@ -2184,53 +672,6 @@ static int volume_openDB(struct vol *volume)
     return (!volume->v_cdb)?-1:0;
 }
 
-/*
-  Check if the underlying filesystem supports EAs for ea:sys volumes.
-  If not, switch to ea:ad.
-  As we can't check (requires write access) on ro-volumes, we switch ea:auto
-  volumes that are options:ro to ea:none.
-*/
-static void check_ea_sys_support(struct vol *vol)
-{
-    uid_t process_uid = 0;
-    char eaname[] = {"org.netatalk.supports-eas.XXXXXX"};
-    const char *eacontent = "yes";
-
-    if (vol->v_vfs_ea == AFPVOL_EA_AUTO) {
-
-        if ((vol->v_flags & AFPVOL_RO) == AFPVOL_RO) {
-            LOG(log_info, logtype_afpd, "read-only volume '%s', can't test for EA support, disabling EAs", vol->v_localname);
-            vol->v_vfs_ea = AFPVOL_EA_NONE;
-            return;
-        }
-
-        mktemp(eaname);
-
-        process_uid = geteuid();
-        if (process_uid)
-            if (seteuid(0) == -1) {
-                LOG(log_error, logtype_afpd, "check_ea_sys_support: can't seteuid(0): %s", strerror(errno));
-                exit(EXITERR_SYS);
-            }
-
-        if ((sys_setxattr(vol->v_path, eaname, eacontent, 4, 0)) == 0) {
-            sys_removexattr(vol->v_path, eaname);
-            vol->v_vfs_ea = AFPVOL_EA_SYS;
-        } else {
-            LOG(log_warning, logtype_afpd, "volume \"%s\" does not support Extended Attributes, using ea:ad instead",
-                vol->v_localname);
-            vol->v_vfs_ea = AFPVOL_EA_AD;
-        }
-
-        if (process_uid) {
-            if (seteuid(process_uid) == -1) {
-                LOG(log_error, logtype_afpd, "can't seteuid back %s", strerror(errno));
-                exit(EXITERR_SYS);
-            }
-        }
-    }
-}
-
 /* -------------------------
  * we are the user here
  */
@@ -2244,7 +685,7 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
     struct dir  *dir;
     int     len, ret;
     size_t  namelen;
-    u_int16_t   bitmap;
+    uint16_t   bitmap;
     char        path[ MAXPATHLEN + 1];
     char        *vol_uname;
     char        *vol_mname;
@@ -2266,7 +707,7 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
     if ((volname_tmp = strchr(volname,'+')) != NULL)
         volname = volname_tmp+1;
 
-    if (utf8_encoding()) {
+    if (utf8_encoding(obj)) {
         namelen = convert_string(CH_UTF8_MAC, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
     } else {
         namelen = convert_string(obj->options.maccharset, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
@@ -2280,9 +721,9 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
     if ((len + 1) & 1) /* pad to an even boundary */
         ibuf++;
 
-    load_volumes(obj);
+    load_volumes(obj, closevol);
 
-    for ( volume = Volumes; volume; volume = volume->v_next ) {
+    for ( volume = getvolumes(); volume; volume = volume->v_next ) {
         if ( strcasecmp_w( (ucs2_t*) volname, volume->v_name ) == 0 ) {
             break;
         }
@@ -2299,10 +740,7 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
 
     if (( volume->v_flags & AFPVOL_OPEN  ) ) {
         /* the volume is already open */
-#ifdef FORCE_UIDGID
-        set_uidgid ( volume );
-#endif
-        return stat_vol(bitmap, volume, rbuf, rbuflen);
+        return stat_vol(obj, bitmap, volume, rbuf, rbuflen);
     }
 
     if (volume->v_root_preexec) {
@@ -2312,10 +750,6 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
         }
     }
 
-#ifdef FORCE_UIDGID
-    set_uidgid ( volume );
-#endif
-
     if (volume->v_preexec) {
         if ((ret = afprun(0, volume->v_preexec, NULL)) && volume->v_preexec_close) {
             LOG(log_error, logtype_afpd, "afp_openvol(%s): preexec : %d", volume->v_path, ret );
@@ -2366,7 +800,7 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
     /* initialize volume variables
      * FIXME file size
      */
-    if (utf8_encoding()) {
+    if (utf8_encoding(obj)) {
         volume->max_filename = UTF8FILELEN_EARLY;
     }
     else {
@@ -2376,7 +810,7 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
     volume->v_flags |= AFPVOL_OPEN;
     volume->v_cdb = NULL;
 
-    if (utf8_encoding()) {
+    if (utf8_encoding(obj)) {
         len = convert_string_allocate(CH_UCS2, CH_UTF8_MAC, volume->v_u8mname, namelen, &vol_mname);
     } else {
         len = convert_string_allocate(CH_UCS2, obj->options.maccharset, volume->v_macname, namelen, &vol_mname);
@@ -2408,22 +842,16 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
     volume->v_root = dir;
     curdir = dir;
 
-    if (volume_openDB(volume) < 0) {
+    if (volume_openDB(obj, volume) < 0) {
         LOG(log_error, logtype_afpd, "Fatal error: cannot open CNID or invalid CNID backend for %s: %s",
             volume->v_path, volume->v_cnidscheme);
         ret = AFPERR_MISC;
         goto openvol_err;
     }
 
-    ret  = stat_vol(bitmap, volume, rbuf, rbuflen);
+    ret  = stat_vol(obj, bitmap, volume, rbuf, rbuflen);
 
     if (ret == AFP_OK) {
-        handle_special_folders(volume);
-        savevolinfo(volume,
-                    volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
-                    volume->v_cnidport   ? volume->v_cnidport   : Cnid_port);
-
-
         /*
          * If you mount a volume twice, the second time the trash appears on
          * the desk-top.  That's because the Mac remembers the DID for the
@@ -2443,10 +871,11 @@ int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t
                 goto openvol_err;
             }
         }
-        else {
-            p = Trash;
-            cname( volume, volume->v_root, &p );
-        }
+
+        const char *msg;
+        if ((msg = iniparser_getstring(obj->iniconfig, volume->v_configname, "login message",  NULL)) != NULL)
+            setmessage(msg);
+
         return( AFP_OK );
     }
 
@@ -2465,12 +894,15 @@ openvol_err:
     return ret;
 }
 
-/* ------------------------- */
-static void closevol(struct vol *vol)
+void closevol(const AFPObj *obj, struct vol *vol)
 {
     if (!vol)
         return;
 
+    vol->v_flags &= ~AFPVOL_OPEN;
+
+    of_closevol(obj, vol);
+
     dir_free( vol->v_root );
     vol->v_root = NULL;
     if (vol->v_cdb != NULL) {
@@ -2487,50 +919,23 @@ static void closevol(struct vol *vol)
 }
 
 /* ------------------------- */
-void close_all_vol(void)
+void close_all_vol(const AFPObj *obj)
 {
     struct vol  *ovol;
     curdir = NULL;
-    for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
+    for ( ovol = getvolumes(); ovol; ovol = ovol->v_next ) {
         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
             ovol->v_flags &= ~AFPVOL_OPEN;
-            closevol(ovol);
-        }
-    }
-}
-
-/* ------------------------- */
-static void deletevol(struct vol *vol)
-{
-    struct vol  *ovol;
-
-    vol->v_flags &= ~AFPVOL_OPEN;
-    for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
-        if ( (ovol->v_flags & AFPVOL_OPEN) ) {
-            break;
+            closevol(obj, ovol);
         }
     }
-    if ( ovol != NULL ) {
-        /* Even if chdir fails, we can't say afp_closevol fails. */
-        if ( chdir( ovol->v_path ) == 0 ) {
-            curdir = ovol->v_root;
-        }
-    }
-
-    closevol(vol);
-    if (vol->v_deleted) {
-        showvol(vol->v_name);
-        volume_free(vol);
-        volume_unlink(vol);
-        free(vol);
-    }
 }
 
 /* ------------------------- */
-int afp_closevol(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
+int afp_closevol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
 {
     struct vol  *vol;
-    u_int16_t   vid;
+    uint16_t   vid;
 
     *rbuflen = 0;
     ibuf += 2;
@@ -2539,68 +944,13 @@ int afp_closevol(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_
         return( AFPERR_PARAM );
     }
 
-    deletevol(vol);
-    current_vol = NULL;
+    (void)chdir("/");
+    curdir = NULL;
+    closevol(obj, vol);
 
     return( AFP_OK );
 }
 
-/* ------------------------- */
-struct vol *getvolbyvid(const u_int16_t vid )
-{
-    struct vol  *vol;
-
-    for ( vol = Volumes; vol; vol = vol->v_next ) {
-        if ( vid == vol->v_vid ) {
-            break;
-        }
-    }
-    if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
-        return( NULL );
-    }
-
-#ifdef FORCE_UIDGID
-    set_uidgid ( vol );
-#endif /* FORCE_UIDGID */
-
-    current_vol = vol;
-
-    return( vol );
-}
-
-/* ------------------------ */
-static int ext_cmp_key(const void *key, const void *obj)
-{
-    const char          *p = key;
-    const struct extmap *em = obj;
-    return strdiacasecmp(p, em->em_ext);
-}
-struct extmap *getextmap(const char *path)
-{
-    char      *p;
-    struct extmap *em;
-
-    if (!Extmap_cnt || NULL == ( p = strrchr( path, '.' )) ) {
-        return( Defextmap );
-    }
-    p++;
-    if (!*p) {
-        return( Defextmap );
-    }
-    em = bsearch(p, Extmap, Extmap_cnt, sizeof(struct extmap), ext_cmp_key);
-    if (em) {
-        return( em );
-    } else {
-        return( Defextmap );
-    }
-}
-
-/* ------------------------- */
-struct extmap *getdefextmap(void)
-{
-    return( Defextmap );
-}
-
 /* --------------------------
    poll if a volume is changed by other processes.
    return
@@ -2620,17 +970,17 @@ int  pollvoltime(AFPObj *obj)
     struct timeval   tv;
     struct stat      st;
 
-    if (!(afp_version > 21 && obj->options.server_notif))
+    if (!(obj->afp_version > 21 && obj->options.flags & OPTION_SERVERNOTIF))
         return 0;
 
     if ( gettimeofday( &tv, NULL ) < 0 )
         return 0;
 
-    for ( vol = Volumes; vol; vol = vol->v_next ) {
+    for ( vol = getvolumes(); vol; vol = vol->v_next ) {
         if ( (vol->v_flags & AFPVOL_OPEN)  && vol->v_mtime + 30 < tv.tv_sec) {
             if ( !stat( vol->v_path, &st ) && vol->v_mtime != st.st_mtime ) {
                 vol->v_mtime = st.st_mtime;
-                if (!obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
+                if (!obj->attention(obj->dsi, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
                     return -1;
                 return 1;
             }
@@ -2660,17 +1010,17 @@ void setvoltime(AFPObj *obj, struct vol *vol)
         /* or finder doesn't update free space
          * AFP 3.2 and above clients seem to be ok without so many notification
          */
-        if (afp_version < 32 && obj->options.server_notif) {
-            obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
+        if (obj->afp_version < 32 && obj->options.flags & OPTION_SERVERNOTIF) {
+            obj->attention(obj->dsi, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
         }
     }
 }
 
 /* ------------------------- */
-int afp_getvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,char *rbuf, size_t *rbuflen)
+int afp_getvolparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_,char *rbuf, size_t *rbuflen)
 {
     struct vol  *vol;
-    u_int16_t   vid, bitmap;
+    uint16_t   vid, bitmap;
 
     ibuf += 2;
     memcpy(&vid, ibuf, sizeof( vid ));
@@ -2683,7 +1033,7 @@ int afp_getvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,char *rbuf,
         return( AFPERR_PARAM );
     }
 
-    return stat_vol(bitmap, vol, rbuf, rbuflen);
+    return stat_vol(obj, bitmap, vol, rbuf, rbuflen);
 }
 
 /* ------------------------- */
@@ -2691,8 +1041,8 @@ int afp_setvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf
 {
     struct adouble ad;
     struct vol  *vol;
-    u_int16_t   vid, bitmap;
-    u_int32_t   aint;
+    uint16_t   vid, bitmap;
+    uint32_t   aint;
 
     ibuf += 2;
     *rbuflen = 0;
@@ -2714,9 +1064,8 @@ int afp_setvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf
     if (bitmap != (1 << VOLPBIT_BDATE))
         return AFPERR_BITMAP;
 
-    ad_init(&ad, vol->v_adouble, vol->v_ad_options);
-    if ( ad_open( vol->v_path, ADFLAGS_HF|ADFLAGS_DIR, O_RDWR,
-                  0666, &ad) < 0 ) {
+    ad_init(&ad, vol);
+    if ( ad_open(&ad,  vol->v_path, ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_RDWR) < 0 ) {
         if (errno == EROFS)
             return AFPERR_VLOCK;
 
@@ -2729,244 +1078,3 @@ int afp_setvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf
     ad_close(&ad, ADFLAGS_HF);
     return( AFP_OK );
 }
-
-/* ------------------------- */
-int wincheck(const struct vol *vol, const char *path)
-{
-    int len;
-
-    if (!(vol->v_flags & AFPVOL_MSWINDOWS))
-        return 1;
-
-    /* empty paths are not allowed */
-    if ((len = strlen(path)) == 0)
-        return 0;
-
-    /* leading or trailing whitespaces are not allowed, carriage returns
-     * and probably other whitespace is okay, tabs are not allowed
-     */
-    if ((path[0] == ' ') || (path[len-1] == ' '))
-        return 0;
-
-    /* certain characters are not allowed */
-    if (strpbrk(path, MSWINDOWS_BADCHARS))
-        return 0;
-
-    /* everything else is okay */
-    return 1;
-}
-
-
-/*
- * precreate a folder
- * this is only intended for folders in the volume root
- * It will *not* work if the folder name contains extended characters
- */
-static int create_special_folder (const struct vol *vol, const struct _special_folder *folder)
-{
-    char        *p,*q,*r;
-    struct adouble  ad;
-    u_int16_t   attr;
-    struct stat st;
-    int     ret;
-
-
-    p = (char *) malloc ( strlen(vol->v_path)+strlen(folder->name)+2);
-    if ( p == NULL) {
-        LOG(log_error, logtype_afpd,"malloc failed");
-        exit (EXITERR_SYS);
-    }
-
-    q=strdup(folder->name);
-    if ( q == NULL) {
-        LOG(log_error, logtype_afpd,"malloc failed");
-        exit (EXITERR_SYS);
-    }
-
-    strcpy(p, vol->v_path);
-    strcat(p, "/");
-
-    r=q;
-    while (*r) {
-        if ((vol->v_casefold & AFPVOL_MTOUUPPER))
-            *r=toupper(*r);
-        else if ((vol->v_casefold & AFPVOL_MTOULOWER))
-            *r=tolower(*r);
-        r++;
-    }
-    strcat(p, q);
-
-    if ( (ret = stat( p, &st )) < 0 ) {
-        if (folder->precreate) {
-            if (ad_mkdir(p, folder->mode)) {
-                LOG(log_debug, logtype_afpd,"Creating '%s' failed in %s: %s", p, vol->v_path, strerror(errno));
-                free(p);
-                free(q);
-                return -1;
-            }
-            ret = 0;
-        }
-    }
-
-    if ( !ret && folder->hide) {
-        /* Hide it */
-        ad_init(&ad, vol->v_adouble, vol->v_ad_options);
-        if (ad_open_metadata( p, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
-            free (p);
-            free(q);
-            return (-1);
-        }
-
-        ad_setname(&ad, folder->name);
-
-        ad_getattr(&ad, &attr);
-        attr |= htons( ntohs( attr ) | ATTRBIT_INVISIBLE );
-        ad_setattr(&ad, attr);
-
-        /* do the same with the finder info */
-        if (ad_entry(&ad, ADEID_FINDERI)) {
-            memcpy(&attr, ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, sizeof(attr));
-            attr   |= htons(FINDERINFO_INVISIBLE);
-            memcpy(ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,&attr, sizeof(attr));
-        }
-
-        ad_flush( &ad );
-        ad_close_metadata( &ad);
-    }
-    free(p);
-    free(q);
-    return 0;
-}
-
-static void handle_special_folders (const struct vol * vol)
-{
-    const _special_folder *p = &special_folders[0];
-    uid_t process_uid;
-
-    process_uid = geteuid();
-    if (process_uid) {
-        if (seteuid(0) == -1) {
-            process_uid = 0;
-        }
-    }
-
-    for (; p->name != NULL; p++) {
-        create_special_folder (vol, p);
-    }
-
-    if (process_uid) {
-        if (seteuid(process_uid) == -1) {
-            LOG(log_error, logtype_logger, "can't seteuid back %s", strerror(errno));
-            exit(EXITERR_SYS);
-        }
-    }
-}
-
-const struct vol *getvolumes(void)
-{
-    return Volumes;
-}
-
-void unload_volumes_and_extmap(void)
-{
-    LOG(log_debug, logtype_afpd, "unload_volumes_and_extmap");
-    free_extmap();
-    free_volumes();
-}
-
-/* 
- * Get a volumes UUID from the config file.
- * If there is none, it is generated and stored there.
- *
- * Returns pointer to allocated storage on success, NULL on error.
- */
-static char *get_vol_uuid(const AFPObj *obj, const char *volname)
-{
-    char *volname_conf;
-    char buf[1024], uuid[UUID_PRINTABLE_STRING_LENGTH], *p;
-    FILE *fp;
-    struct stat tmpstat;
-    int fd;
-    
-    if ((fp = fopen(obj->options.uuidconf, "r")) != NULL) {  /* read open? */
-        /* scan in the conf file */
-        while (fgets(buf, sizeof(buf), fp) != NULL) { 
-            p = buf;
-            while (p && isblank(*p))
-                p++;
-            if (!p || (*p == '#') || (*p == '\n'))
-                continue;                             /* invalid line */
-            if (*p == '"') {
-                p++;
-                if ((volname_conf = strtok( p, "\"" )) == NULL)
-                    continue;                         /* syntax error */
-            } else {
-                if ((volname_conf = strtok( p, " \t" )) == NULL)
-                    continue;                         /* syntax error: invalid name */
-            }
-            p = strchr(p, '\0');
-            p++;
-            if (*p == '\0')
-                continue;                             /* syntax error */
-            
-            if (strcmp(volname, volname_conf) != 0)
-                continue;                             /* another volume name */
-                
-            while (p && isblank(*p))
-                p++;
-
-            if (sscanf(p, "%36s", uuid) == 1 ) {
-                for (int i=0; uuid[i]; i++)
-                    uuid[i] = toupper(uuid[i]);
-                LOG(log_debug, logtype_afpd, "get_uuid('%s'): UUID: '%s'", volname, uuid);
-                fclose(fp);
-                return strdup(uuid);
-            }
-        }
-    }
-
-    if (fp)
-        fclose(fp);
-
-    /*  not found or no file, reopen in append mode */
-
-    if (stat(obj->options.uuidconf, &tmpstat)) {                /* no file */
-        if (( fd = creat(obj->options.uuidconf, 0644 )) < 0 ) {
-            LOG(log_error, logtype_afpd, "ERROR: Cannot create %s (%s).",
-                obj->options.uuidconf, strerror(errno));
-            return NULL;
-        }
-        if (( fp = fdopen( fd, "w" )) == NULL ) {
-            LOG(log_error, logtype_afpd, "ERROR: Cannot fdopen %s (%s).",
-                obj->options.uuidconf, strerror(errno));
-            close(fd);
-            return NULL;
-        }
-    } else if ((fp = fopen(obj->options.uuidconf, "a+")) == NULL) { /* not found */
-        LOG(log_error, logtype_afpd, "Cannot create or append to %s (%s).",
-            obj->options.uuidconf, strerror(errno));
-        return NULL;
-    }
-    fseek(fp, 0L, SEEK_END);
-    if(ftell(fp) == 0) {                     /* size = 0 */
-        fprintf(fp, "# DON'T TOUCH NOR COPY THOUGHTLESSLY!\n");
-        fprintf(fp, "# This file is auto-generated by afpd\n");
-        fprintf(fp, "# and stores UUIDs for TM volumes.\n\n");
-    } else {
-        fseek(fp, -1L, SEEK_END);
-        if(fgetc(fp) != '\n') fputc('\n', fp); /* last char is \n? */
-    }                    
-    
-    /* generate uuid and write to file */
-    atalk_uuid_t id;
-    const char *cp;
-    randombytes((void *)id, 16);
-    cp = uuid_bin2string(id);
-
-    LOG(log_debug, logtype_afpd, "get_uuid('%s'): generated UUID '%s'", volname, cp);
-
-    fprintf(fp, "\"%s\"\t%36s\n", volname, cp);
-    fclose(fp);
-    
-    return strdup(cp);
-}
index eedc622bd275107758b7522e570f6e37eb278b4c..3bca88214bfee50687bc7dc052d5e70a9bb8c948 100644 (file)
@@ -6,24 +6,19 @@
 #ifndef AFPD_VOLUME_H
 #define AFPD_VOLUME_H 1
 
-#include <sys/cdefs.h>
 #include <sys/types.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 
 #include <atalk/volume.h>
 #include <atalk/cnid.h>
 #include <atalk/unicode.h>
 #include <atalk/globals.h>
 
-extern struct vol       *getvolbyvid (const u_int16_t);
 extern int              ustatfs_getvolspace (const struct vol *,
-            VolSpace *, VolSpace *,
-            u_int32_t *);
+                                             VolSpace *, VolSpace *,
+                                             uint32_t *);
 extern void             setvoltime (AFPObj *, struct vol *);
 extern int              pollvoltime (AFPObj *);
-extern void             load_volumes (AFPObj *obj);
-extern const struct vol *getvolumes(void);
-extern void             unload_volumes_and_extmap(void);
 extern void             vol_fce_tm_event(void);
 
 /* FP functions */
@@ -34,8 +29,6 @@ int afp_getsrvrparms (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf,  size
 int afp_closevol     (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf,  size_t *rbuflen);
 
 /* netatalk functions */
-extern void     close_all_vol   (void);
-
-struct vol *current_vol;        /* last volume from getvolbyvid() */
-
+extern void close_all_vol(const AFPObj *obj);
+extern void closevol(const AFPObj *obj, struct vol *vol);
 #endif
diff --git a/etc/atalkd/.gitignore b/etc/atalkd/.gitignore
deleted file mode 100644 (file)
index 681f201..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Makefile
-Makefile.in
-atalkd
-.deps
-.libs
-.gitignore
-aep.o config.o main.o multicast.o nbp.o route.o rtmp.o zip.o
diff --git a/etc/atalkd/Makefile.am b/etc/atalkd/Makefile.am
deleted file mode 100644 (file)
index 098a529..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-# Makefile.am for etc/atalkd/
-
-pkgconfdir = @PKGCONFDIR@
-
-sbin_PROGRAMS = atalkd
-
-atalkd_SOURCES = aep.c config.c main.c multicast.c nbp.c route.c rtmp.c zip.c 
-atalkd_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-noinst_HEADERS =       \
-       atserv.h        \
-       gate.h          \
-       interface.h     \
-       list.h          \
-       main.h          \
-       multicast.h     \
-       nbp.h           \
-       route.h         \
-       rtmp.h          \
-       zip.h
-
-AM_CFLAGS = -D_PATH_ATALKDCONF=\"$(pkgconfdir)/atalkd.conf\"
diff --git a/etc/atalkd/aep.c b/etc/atalkd/aep.c
deleted file mode 100644 (file)
index 6d3ace9..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * $Id: aep.c,v 1.9 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <errno.h>
-
-#include <atalk/logger.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netatalk/at.h>
-#include <atalk/aep.h>
-#include <atalk/ddp.h>
-
-#include "atserv.h"
-
-int aep_packet(
-    struct atport      *ap,
-    struct sockaddr_at *from,
-    char               *data,
-    int                        len)
-{
-    char               *end;
-
-    end = data + len;
-    if ( data + 2 > end || *data != DDPTYPE_AEP ||
-           *( data + 1 ) != AEPOP_REQUEST ) {
-       LOG(log_info, logtype_atalkd, "aep_packet malformed packet" );
-       return 1;
-    }
-
-    *( data + 1 ) = AEPOP_REPLY;
-    if ( sendto( ap->ap_fd, data, len, 0, (struct sockaddr *)from,
-           sizeof( struct sockaddr_at )) < 0 ) {
-       LOG(log_error, logtype_atalkd, "aep sendto: %s", strerror(errno) );
-       return 1;
-    }
-
-    return 0;
-}
diff --git a/etc/atalkd/atserv.h b/etc/atalkd/atserv.h
deleted file mode 100644 (file)
index 9052ab3..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * $Id: atserv.h,v 1.4 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1992 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-#ifndef ATALKD_ATSERV_H
-#define ATALKD_ATSERV_H 1
-
-struct atport {
-    int                        ap_fd;
-    struct atport      *ap_next;
-    struct interface   *ap_iface;
-    u_char             ap_port;
-    int                        (*ap_packet)(struct atport *ap, struct sockaddr_at *from, char *data, int len);
-};
-
-struct atserv {
-    char       *as_name;
-    u_char     as_port;                /* Used as a fall back */
-    int                (*as_packet)(struct atport *ap, struct sockaddr_at *from, char *data, int len);
-};
-
-#endif
diff --git a/etc/atalkd/config.c b/etc/atalkd/config.c
deleted file mode 100644 (file)
index 4005d69..0000000
+++ /dev/null
@@ -1,880 +0,0 @@
-/*
- * $Id: config.c,v 1.20 2009-10-29 11:35:58 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/socket.h>
-#include <sys/ioctl.h>
-#include <atalk/logger.h>
-#include <sys/param.h>
-#ifdef TRU64
-#include <sys/mbuf.h>
-#include <net/route.h>
-#endif /* TRU64 */
-#include <net/if.h>
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <atalk/paths.h>
-#include <atalk/util.h>
-#include <assert.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <ctype.h>
-
-/* STDC check */
-#if STDC_HEADERS
-#include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-
-#ifdef __svr4__
-#include <sys/sockio.h>
-#include <sys/stropts.h>
-#endif /* __svr4__ */
-
-#include <atalk/unicode.h>
-#include "interface.h"
-#include "multicast.h"
-#include "rtmp.h"
-#include "zip.h"
-#include "list.h"
-#include "main.h"
-
-#ifndef IFF_SLAVE /* a little backward compatibility */
-#define IFF_SLAVE 0
-#endif /* IFF_SLAVE */
-
-int router(struct interface *iface, char **av);
-int dontroute(struct interface *iface, char **av);
-int seed(struct interface *iface, char **av);
-int phase(struct interface *iface, char **av); 
-int net(struct interface *iface, char **av);
-int addr(struct interface *iface, char **av); 
-int zone(struct interface *iface, char **av);
-int noallmulti(struct interface *iface, char **av);
-
-static const struct param {
-    char       *p_name;
-    int                (*p_func)(struct interface *iface, char **av);
-} params[] = {
-    { "router", router },
-    { "dontroute", dontroute },
-    { "seed",  seed },
-    { "phase", phase },
-    { "net",   net },
-    { "addr",  addr },
-    { "zone",  zone },
-    { "noallmulti", noallmulti }
-};
-
-#define ARGV_CHUNK_SIZE 128
-#define MAXLINELEN 2048
-static char **parseline(const char *line)
-{
-    const char  *p;
-    int                  argc = 0;
-    char        *buffer, *tmpbuf;
-    char       **argv;
-
-    /* Ignore empty lines and lines with leading hash marks. */
-    p = line;
-    while ( isspace( *p ) ) {
-       p++;
-    }
-    if ( *p == '#' || *p == '\0' ) {
-       return NULL;
-    }
-
-    buffer = (char *) malloc( strlen( p ) + 1 );
-    if ( !buffer ) {
-       /* FIXME: error handling */
-       return NULL;
-    }
-    strcpy( buffer, p );
-    tmpbuf = buffer;
-
-    argv = (char **) malloc( ARGV_CHUNK_SIZE * sizeof( char * ) );
-    if ( !argv ) {
-       /* FIXME: error handling */
-       free( buffer );
-       return NULL;
-    }
-
-    /*
-     * This parser should be made more powerful -- it should
-     * handle various escapes, e.g. \" and \031.
-     */
-    do {
-       if ( *tmpbuf == '"' ) {
-           argv[ argc++ ] = ++tmpbuf;
-           while ( *tmpbuf != '\0' && *tmpbuf != '"' ) {
-               tmpbuf++;
-           }
-           if ( *tmpbuf == '"' ) {
-               /* FIXME: error handling */
-           }
-       } else {
-           argv[ argc++ ] = tmpbuf;
-           while ( *tmpbuf != '\0' && !isspace( *tmpbuf )) {
-               tmpbuf++;
-           }
-       }
-       *tmpbuf++ = '\0';
-
-       /* Make room for a NULL pointer and our special pointer (s.b.) */
-       if ( (argc + 1) % ARGV_CHUNK_SIZE == 0 ) {
-           char **tmp;
-           tmp = (char **) realloc( argv, argc + 1 + ARGV_CHUNK_SIZE * sizeof( char * ) );
-           if ( !tmp ) {
-               /* FIXME: error handling */
-               free( argv );
-               free( buffer );
-               return NULL;
-           }
-           argv = tmp;
-       }
-
-       /* Skip white spaces. */
-        while ( isspace( *tmpbuf ) ) {
-            tmpbuf++;
-        }
-    } while ( *tmpbuf != '\0' );
-
-    argv[ argc++ ] = NULL;
-    /* We store our buffer pointer in argv, too, so we can free it later.
-     * (But don't tell anyone.)
-     */
-    argv[ argc ] = buffer;
-
-    return argv;
-}
-
-static void freeline( char **argv )
-{
-    char **tmp = argv;
-
-    if ( argv ) {
-       while ( *tmp ) {
-           tmp++;
-       }
-       free( *++tmp );
-       free( argv );
-    }
-}
-
-int writeconf(char *cf)
-{
-    struct stat                st;
-    char               *path, *p, newpath[ MAXPATHLEN ], line[ MAXLINELEN ];
-    char               **argv;
-    FILE               *conf, *newconf;
-    struct interface   *iface;
-    struct list                *l;
-    int                        mode = 0644, fd;
-    size_t             len;
-    char               *zonename;
-
-    if ( cf == NULL ) {
-       path = _PATH_ATALKDCONF;
-    } else {
-       path = cf;
-    }
-
-    /* check if old conf is writable */
-    if ( stat( path, &st ) == 0 ) {
-       if (( st.st_mode & S_IWUSR ) == 0 ) {
-           LOG(log_info, logtype_atalkd, "%s not writable, won't rewrite", path );
-           return( -1 );
-       }
-        mode = st.st_mode;
-    }
-
-    if (( p = strrchr( path, '/' )) == NULL ) {
-       strcpy( newpath, _PATH_ATALKDTMP );
-    } else {
-       sprintf( newpath, "%.*s/%s", (int)(p - path), path, _PATH_ATALKDTMP );
-    }
-    if (( fd = open( newpath, O_WRONLY|O_CREAT|O_TRUNC, mode )) < 0 ) {
-       LOG(log_error, logtype_atalkd, "%s: %s", newpath, strerror(errno) );
-       return( -1 );
-    }
-    if (( newconf = fdopen( fd, "w" )) == NULL ) {
-       LOG(log_error, logtype_atalkd, "fdreopen %s: %s", newpath, strerror(errno) );
-       return( -1 );
-    }
-
-    if (( conf = fopen( path, "r" )) == NULL && cf ) {
-       LOG(log_error, logtype_atalkd, "%s: %s", path, strerror(errno) );
-       return( -1 );
-    }
-
-    iface = interfaces->i_next;
-
-    while ( conf == NULL || fgets( line, sizeof( line ), conf ) != NULL ) {
-       if ( conf != NULL && ( argv = parseline( line )) == NULL ) {
-           if ( fputs( line, newconf ) == EOF ) {
-               LOG(log_error, logtype_atalkd, "fputs: %s", strerror(errno) );
-               return( -1 );
-           }
-           freeline( argv );
-           continue;
-       }
-
-       /* write real lines */
-       if ( iface ) {
-           fprintf( newconf, "%s", iface->i_name );
-           if ( iface->i_flags & IFACE_RSEED ) {
-               fprintf( newconf, " -router" );
-           } else if ( iface->i_flags & IFACE_SEED ) {
-               fprintf( newconf, " -seed" );
-           }
-           if ( iface->i_flags & IFACE_DONTROUTE) {
-               fprintf( newconf, " -dontroute");
-           }
-#ifdef linux
-            if ( !(iface->i_flags & IFACE_ALLMULTI)) {
-               fprintf( newconf, " -noallmulti");
-            }
-#endif
-
-           fprintf( newconf, " -phase %d",
-                   ( iface->i_flags & IFACE_PHASE1 ) ? 1 : 2 );
-           fprintf( newconf, " -net %d", ntohs( iface->i_rt->rt_firstnet ));
-           if ( iface->i_rt->rt_lastnet != iface->i_rt->rt_firstnet ) {
-               fprintf( newconf, "-%d", ntohs( iface->i_rt->rt_lastnet ));
-           }
-           fprintf( newconf, " -addr %u.%u",
-                   ntohs( iface->i_addr.sat_addr.s_net ),
-                   iface->i_addr.sat_addr.s_node );
-           for ( l = iface->i_rt->rt_zt; l; l = l->l_next ) {
-                /* codepage conversion */
-                if ((size_t)(-1) == (len = convert_string_allocate(CH_MAC, CH_UNIX, 
-                                      ((struct ziptab *)l->l_data)->zt_name,
-                                      ((struct ziptab *)l->l_data)->zt_len,
-                                      &zonename)) ) {
-                    if ( NULL == 
-                      (zonename = strdup(((struct ziptab *)l->l_data)->zt_name))) {
-                       LOG(log_error, logtype_atalkd, "malloc: %s",  strerror(errno) );
-                       return( -1 );
-                    }
-                    len = ((struct ziptab *)l->l_data)->zt_len;
-                } 
-               fprintf( newconf, " -zone \"%.*s\"", (int)len, zonename);
-                free(zonename);
-           }
-           fprintf( newconf, "\n" );
-
-           iface = iface->i_next;
-           if ( conf == NULL && iface == NULL ) {
-               break;
-           }
-       }
-    }
-    if ( conf != NULL ) {
-       fclose( conf );
-    }
-    fclose( newconf );
-
-    if ( rename( newpath, path ) < 0 ) {
-       LOG(log_error, logtype_atalkd, "rename %s to %s: %s", newpath, path, strerror(errno) );
-       return( -1 );
-    }
-    return( 0 );
-}
-
-/*
- * Read our config file. If it's not there, return -1. If it is there,
- * but has syntax errors, exit. Format of the file is as follows:
- *
- *     interface [ -seed ] [ -phase number ] [ -net net-range ]
- *     [ -addr net.node ] [ -zone zonename ]...
- * e.g.
- *     le0 -phase 1 -net 7938 -zone Argus
- * or
- *     le0 -phase 2 -net 8043-8044 -zone Argus -zone "Research Systems"
- *     le0 -phase 1 -net 7938 -zone Argus
- *
- * Pretty much everything is optional. Anything that is unspecified is
- * searched for on the network.  If -seed is not specified, the
- * configuration is assumed to be soft, i.e. it can be overridden by
- * another router. If -seed is specified, atalkd will exit if another
- * router disagrees.  If the phase is unspecified, it defaults to phase
- * 2 (the default can be overridden on the command line).  -addr can
- * replace -net, if the network in question isn't a range.  The default
- * zone for an interface is the first zone encountered for that
- * interface.
- */
-int readconf(char *cf)
-{
-    struct ifreq       ifr;
-    struct interface   *iface, *niface;
-    char               line[ MAXLINELEN ], **argv, *p;
-    unsigned int       i, j;
-    int                        s, cc = 0;
-    FILE               *conf;
-
-    if ( cf == NULL ) {
-       p = _PATH_ATALKDCONF;
-    } else {
-       p = cf;
-    }
-    if (( conf = fopen( p, "r" )) == NULL ) {
-        return( -1 );
-    }
-
-#ifndef __svr4__
-    if (( s = socket( AF_APPLETALK, SOCK_DGRAM, 0 )) < 0 ) {
-       perror( "socket" );
-       fclose(conf);
-       return -1;
-    }
-#endif /* __svr4__ */
-
-    while ( fgets( line, sizeof( line ), conf ) != NULL ) {
-       if (( argv = parseline( line )) == NULL ) {
-           continue;
-       }
-
-#ifndef __svr4__
-       /*
-        * Check that av[ 0 ] is a valid interface.
-        * Not possible under sysV.
-        */
-       strlcpy( ifr.ifr_name, argv[ 0 ], sizeof(ifr.ifr_name) );
-
-       /* for devices that don't support appletalk */
-       if ((ioctl(s, SIOCGIFADDR, &ifr) < 0) && (errno == ENODEV)) {
-         perror(argv[0]);
-         goto read_conf_err;
-       }
-
-       if ( ioctl( s, SIOCGIFFLAGS, &ifr ) < 0 ) {
-           perror( argv[ 0 ] );
-           goto read_conf_err;
-       }
-
-       if (ifr.ifr_flags & (IFF_LOOPBACK | IFF_POINTOPOINT |IFF_SLAVE)) {
-           fprintf( stderr, "%s: can't configure.\n", ifr.ifr_name );
-           goto read_conf_err;
-       }
-
-#ifdef IFF_MULTICAST
-       if ((ifr.ifr_flags & IFF_MULTICAST) == 0)
-           fprintf(stderr, "%s: multicast may not work properly.\n",
-                   ifr.ifr_name);
-#endif /* IFF_MULTICAST */
-
-       /* configure hw multicast for this interface. */
-       if (addmulti(ifr.ifr_name, NULL) < 0) {
-         perror(ifr.ifr_name);
-         fprintf(stderr, "Can't configure multicast.\n");
-         goto read_conf_err;
-       }
-
-#endif /* __svr4__ */
-
-       if (( niface = newiface( argv[ 0 ] )) == NULL ) {
-           perror( "newiface" );
-           goto read_conf_err;
-       }
-
-       for ( i = 1; argv[ i ]; i += cc ) {
-           if ( argv[ i ][ 0 ] == '-' ) {
-               argv[ i ]++;
-           }
-           for ( j = 0; j < sizeof( params ) / sizeof( params[ 0 ] ); j++ ) {
-               if ( strcmp( argv[ i ], params[ j ].p_name ) == 0 ) {
-                   if ( params[ j ].p_func != NULL ) {
-                       cc = (*params[ j ].p_func)( niface, &argv[ i + 1 ] );
-                       if (cc < 0) 
-                         goto read_conf_err;
-                       break;
-                   }
-               }
-           }
-           if ( j >= sizeof( params ) / sizeof( params[ 0 ] )) {
-               fprintf( stderr, "%s: attribute not found.\n", argv[ i ] );
-               goto read_conf_err;
-           }
-       }
-
-       for ( iface = interfaces; iface; iface = iface->i_next ) {
-           if ( strcmp( niface->i_name, iface->i_name ) == 0 &&
-                   ((( niface->i_flags & iface->i_flags &
-                   ( IFACE_PHASE1|IFACE_PHASE2 )) != 0 ) ||
-                   niface->i_flags == 0 || iface->i_flags == 0 )) {
-               break;
-           }
-       }
-       if ( iface ) {  /* Already have this interface and phase */
-           fprintf( stderr, "%s already configured!\n", niface->i_name );
-           goto read_conf_err;
-       }
-
-#ifdef linux
-       /* Don't set interface to allmulti if it already is, or -noallmulti was given */
-       if ((ifr.ifr_flags & IFF_ALLMULTI))
-               niface->i_flags |= IFACE_WASALLMULTI; 
-
-       if ((niface->i_flags & IFACE_ALLMULTI) && !(niface->i_flags & IFACE_WASALLMULTI))
-               ifsetallmulti(ifr.ifr_name, 1);
-#endif
-
-       if ( interfaces == NULL ) {
-           interfaces = niface;
-       } else {
-           for ( iface = interfaces; iface->i_next; iface = iface->i_next )
-               ;
-           iface->i_next = niface;
-       }
-       niface->i_next = NULL;
-    }
-
-#ifndef __svr4__
-    close( s );
-#endif /* __svr4__ */
-
-    fclose( conf );
-
-    /*
-     * Note: we've added lo0 to the interface list previously, so we must
-     * have configured more than one interface...
-     */
-    for ( iface = interfaces, cc = 0; iface; iface = iface->i_next, cc++ )
-       ;
-    if ( cc >= IFBASE ) {
-       return( 0 );
-    } else {
-       return( -1 );
-    }
-
-read_conf_err:
-#ifndef __svr4__
-    close(s);
-#endif /* __svr4__ */
-    fclose(conf);
-    return -1;
-}
-
-int noallmulti( struct interface *iface, char **av _U_)
-{
-    /* Linux specific, no effect on other platforms */
-    iface->i_flags &= !IFACE_ALLMULTI;
-
-    return (1);
-}
-       
-/*ARGSUSED*/
-int router(struct interface *iface, char **av _U_)
-{
-    /* make sure "-router" and "-dontroute" aren't both on the same line. */
-    if (iface->i_flags & IFACE_DONTROUTE) {
-       fprintf( stderr, "Can't specify both -router and -dontroute.\n");
-       return -1;
-    }
-
-    /*
-     * Check to be sure "-router" is before "-zone".
-     */
-    if ( iface->i_czt ) {
-       fprintf( stderr, "Must specify -router before -zone.\n");
-       return -1;
-    }
-
-    /* -router also implies -seed */
-    iface->i_flags |= IFACE_RSEED | IFACE_SEED | IFACE_ISROUTER;
-    return( 1 );
-}
-
-/*ARGSUSED*/
-int dontroute(struct interface *iface, char **av _U_)
-{
-    /* make sure "-router" and "-dontroute" aren't both on the same line. */
-    if (iface->i_flags & IFACE_RSEED) {
-       fprintf( stderr, "Can't specify both -router and -dontroute.\n");
-       return -1;
-    }
-
-    iface->i_flags |= IFACE_DONTROUTE;
-    return( 1 );
-}
-
-/*ARGSUSED*/
-int seed( struct interface *iface, char **av _U_)
-{
-    /*
-     * Check to be sure "-seed" is before "-zone". we keep the old
-     * semantics of just ignoring this in a routerless world.
-     */
-    if ( iface->i_czt ) {
-       fprintf( stderr, "Must specify -seed before -zone(%s).\n",
-                iface->i_czt->zt_name);
-       return -1;
-    }
-
-    iface->i_flags |= IFACE_SEED;
-    return( 1 );
-}
-
-int phase(struct interface *iface, char **av)
-{
-    int                        n;
-    char               *pnum;
-
-    if (( pnum = av[ 0 ] ) == NULL ) {
-       fprintf( stderr, "No phase.\n" );
-       return -1;
-    }
-
-    switch ( n = atoi( pnum )) {
-    case 1 :
-       iface->i_flags |= IFACE_PHASE1;
-       break;
-
-    case 2 :
-       iface->i_flags |= IFACE_PHASE2;
-       break;
-
-    default :
-       fprintf( stderr, "No phase %d.\n", n );
-       return -1;
-    }
-    return( 2 );
-}
-
-int net(struct interface *iface, char **av)
-{
-    char               *nrange;
-    char               *stop;
-    int                        net;
-
-    if (( nrange = av[ 0 ] ) == NULL ) {
-       fprintf( stderr, "No network.\n" );
-       return -1;
-    }
-
-    if (( stop = strchr( nrange, '-' )) != NULL ) {
-       stop++;
-    }
-    net = atoi( nrange );
-    if ( net < 0 || net >= 0xffff ) {
-       fprintf( stderr, "Bad network: %d\n", net );
-       return -1;
-    }
-
-    if ( iface->i_rt == NULL && ( iface->i_rt = newrt(iface)) == NULL ) {
-       perror( "newrt" );
-       return -1;
-    }
-
-    if ( iface->i_flags & IFACE_PHASE1 ) {
-       if ( stop != NULL ) {
-           fprintf( stderr, "Phase 1 doesn't use an address range.\n" );
-           return -1;
-       }
-       if ( iface->i_caddr.sat_addr.s_net != ATADDR_ANYNET &&
-               ntohs( iface->i_caddr.sat_addr.s_net ) != net ) {
-           fprintf( stderr, "Net-range (%u) doesn't match net %u.\n",
-                   net, ntohs( iface->i_caddr.sat_addr.s_net ));
-           return -1;
-       }
-       iface->i_rt->rt_firstnet = iface->i_rt->rt_lastnet = htons( net );
-    } else if ( iface->i_flags & IFACE_PHASE2 ) {
-       iface->i_rt->rt_firstnet = htons( net );
-       if ( stop != NULL ) {
-           net = atoi( stop );
-           if ( net < 0 || net >= 0xffff ) {
-               fprintf( stderr, "Bad network: %d\n", net );
-               return -1;
-           }
-       }
-       iface->i_rt->rt_lastnet = htons( net );
-       if ( iface->i_caddr.sat_addr.s_net != ATADDR_ANYNET &&
-               ( ntohs( iface->i_rt->rt_firstnet ) >
-               ntohs( iface->i_caddr.sat_addr.s_net ) ||
-               ntohs( iface->i_rt->rt_lastnet ) <
-               ntohs( iface->i_caddr.sat_addr.s_net ))) {
-           fprintf( stderr, "Net-range (%u-%u) doesn't contain net (%u).\n",
-                   ntohs( iface->i_rt->rt_firstnet ),
-                   ntohs( iface->i_rt->rt_lastnet ),
-                   ntohs( iface->i_caddr.sat_addr.s_net ));
-           return -1;
-       }
-       if ( iface->i_rt->rt_firstnet != iface->i_rt->rt_lastnet ) {
-           iface->i_rt->rt_flags |= RTMPTAB_EXTENDED;
-       }
-    } else {
-       fprintf( stderr, "Must specify phase before networks.\n" );
-       return -1;
-    }
-    return( 2 );
-}
-
-int addr(struct interface *iface, char **av)
-{
-    if ( av[ 0 ] == NULL ) {
-       fprintf( stderr, "No address.\n" );
-       return -1;
-    }
-    if ( atalk_aton( av[ 0 ], &iface->i_caddr.sat_addr ) == 0 ) {
-       fprintf( stderr, "Bad address, %s\n", av[ 0 ] );
-       return -1;
-    }
-
-    if ( iface->i_rt ) {
-       if ( ntohs( iface->i_rt->rt_firstnet ) >
-               ntohs( iface->i_caddr.sat_addr.s_net ) ||
-               ntohs( iface->i_rt->rt_lastnet ) <
-               ntohs( iface->i_caddr.sat_addr.s_net )) {
-           fprintf( stderr, "Net (%u) not in net-range (%u-%u).\n",
-                   ntohs( iface->i_caddr.sat_addr.s_net ),
-                   ntohs( iface->i_rt->rt_firstnet ),
-                   ntohs( iface->i_rt->rt_lastnet ));
-           return -1;
-       }
-    } else {
-       if (( iface->i_rt = newrt(iface)) == NULL ) {
-           perror( "newrt" );
-           return -1;
-       }
-       iface->i_rt->rt_firstnet = iface->i_rt->rt_lastnet =
-               iface->i_caddr.sat_addr.s_net;
-    }
-
-    return( 2 );
-}
-
-int zone(struct interface *iface, char **av)
-{
-    struct ziptab      *zt;
-    char               *zname;
-
-    if ( av[ 0 ]  == NULL ) {
-       fprintf( stderr, "No zone.\n" );
-       return -1;
-    }
-
-    /* codepage conversion */
-    if ((size_t)(-1) == convert_string_allocate(CH_UNIX, CH_MAC, av[0], -1, &zname)) {
-       zname = strdup(av[0]);
-    }
-
-    /*
-     * Only process "-zone" if this interface has "-seed".  We keep our
-     * list of configured zones in the interface structure.  Then we can
-     * check that the network has given us good zones.
-     */
-    if ( iface->i_flags & IFACE_SEED ) {
-        if ( iface->i_rt == NULL ) {
-           fprintf( stderr, "Must specify net-range before zones.\n" );
-           return -1;
-        }
-
-       if (( zt = newzt( strlen( zname ), zname )) == NULL ) {
-           perror( "newzt" );
-           return -1;
-       }
-       if ( iface->i_czt == NULL ) {
-           iface->i_czt = zt;
-       } else {
-           zt->zt_next = iface->i_czt->zt_next;
-           iface->i_czt->zt_next = zt;
-       }
-    }
-    free(zname);
-
-    return( 2 );
-}
-
-/*
- * Get the configuration from the kernel. Only called if there's no
- * configuration.
- */
-int getifconf(void)
-{
-    struct interface   *iface, *niface;
-    struct ifreq        ifr;
-    char                **start, **list;
-    int                        s;
-
-    if (( s = socket( AF_APPLETALK, SOCK_DGRAM, 0 )) < 0 ) {
-       perror( "socket" );
-       return -1;
-    }
-
-    start = list = getifacelist();
-    while (list && *list) {
-        strlcpy(ifr.ifr_name, *list, sizeof(ifr.ifr_name));
-       list++;
-
-       if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0)
-         continue;
-
-       if (ifr.ifr_flags & (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_SLAVE))
-         continue;
-
-       if ((ifr.ifr_flags & IFF_UP) == 0)
-         continue;
-
-       /* for devices that don't support appletalk */
-       if (ioctl(s, SIOCGIFADDR, &ifr) < 0 && (errno == ENODEV))
-         continue;
-
-       for ( iface = interfaces; iface; iface = iface->i_next ) {
-           if ( strcmp( iface->i_name, ifr.ifr_name ) == 0 ) {
-               break;
-           }
-       }
-       if ( iface ) {  /* Already have this interface name */
-           continue;
-       }
-
-
-#ifdef IFF_MULTICAST
-       if ((ifr.ifr_flags & IFF_MULTICAST) == 0)
-         fprintf(stderr, "%s: multicast may not work correctly.\n",
-                 ifr.ifr_name);
-#endif /* IFF_MULTICAST */
-
-       if (addmulti(ifr.ifr_name, NULL) < 0) {
-         fprintf(stderr, "%s: disabled.\n", ifr.ifr_name);
-         continue;
-       }
-       
-       if (( niface = newiface( ifr.ifr_name )) == NULL ) {
-           perror( "newiface" );
-           close(s);
-           freeifacelist(start);
-           return -1;
-       }
-       /*
-        * Could try to get the address from the kernel...
-        */
-
-       if ( interfaces == NULL ) {
-           interfaces = niface;
-       } else {
-           for ( iface = interfaces; iface->i_next; iface = iface->i_next )
-               ;
-           iface->i_next = niface;
-       }
-       niface->i_next = NULL;
-    }
-    freeifacelist(start);
-    (void)close( s );
-    return( 0 );
-}
-
-/*
- * Allocate a new interface structure.  Centralized here so we can change
- * the interface structure and have it updated nicely.
- */
-
-struct interface *newiface( const char *name)
-{
-    struct interface   *niface;
-
-    if (( niface = (struct interface *)calloc(1, sizeof( struct interface )))
-           == NULL ) {
-       return( NULL );
-    }
-    strlcpy( niface->i_name, name, sizeof(niface->i_name));
-#ifdef BSD4_4
-    niface->i_addr.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    niface->i_addr.sat_family = AF_APPLETALK;
-#ifdef BSD4_4
-    niface->i_caddr.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    niface->i_caddr.sat_family = AF_APPLETALK;
-#ifdef linux
-    niface->i_flags = IFACE_ALLMULTI;
-#endif
-    return( niface );
-}
-
-#ifdef __svr4__
-int plumb(void)
-{
-    struct interface   *iface;
-    char               device[ MAXPATHLEN + 1], *p, *t;
-    int                        fd, ppa;
-    int                        digits = 0;
-
-    for ( iface = interfaces; iface != NULL; iface = iface->i_next ) {
-       if ( strcmp( iface->i_name, LOOPIFACE ) == 0 ) {
-           continue;
-       }
-
-       strcpy( device, "/dev/" );
-       strcat( device, iface->i_name );
-       for (t = device; *t != '\0' ; ++t) {
-           if (isdigit(*t) == 0) {
-               p = t + 1;
-           }
-           else {
-               digits++;
-           }
-       }
-
-       if (digits == 0) {
-           LOG(log_error, logtype_atalkd, "plumb: invalid device: %s", device );
-           return -1;
-       }
-       ppa = atoi( p );
-       *p = '\0';
-
-       if (( fd = open( device, O_RDWR, 0 )) < 0 ) {
-           LOG(log_error, logtype_atalkd, "%s: %s", device, strerror(errno) );
-           return -1;
-       }
-       if ( ioctl( fd, I_PUSH, "ddp" ) < 0 ) {
-           LOG(log_error, logtype_atalkd, "I_PUSH: %s", strerror(errno) );
-           close(fd);
-           return -1;
-       }
-       if ( ioctl( fd, IF_UNITSEL, ppa ) < 0 ) {
-           LOG(log_error, logtype_atalkd, "IF_UNITSEL: %s", strerror(errno) );
-           close(fd);
-           return -1;
-       }
-
-       /* configure multicast. */
-       if (addmulti(iface->i_name, NULL) < 0) {
-         perror(iface->i_name);
-         fprintf(stderr,"Can't configure multicast.\n");
-         close(fd);
-         return -1;
-       }
-
-       LOG(log_info, logtype_atalkd, "plumbed %s%d", device, ppa );
-
-    close(fd);
-    }
-
-    return( 0 );
-}
-#endif /* __svr4__ */
diff --git a/etc/atalkd/gate.h b/etc/atalkd/gate.h
deleted file mode 100644 (file)
index 9d2869f..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-/*
- * $Id: gate.h,v 1.2 2001-06-25 20:13:45 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-struct gate {
-    struct gate                *g_next,
-                       *g_prev;
-    int                        g_state;
-    struct interface   *g_iface;
-    struct rtmptab     *g_rt;
-    struct sockaddr_at g_sat;
-};
diff --git a/etc/atalkd/interface.h b/etc/atalkd/interface.h
deleted file mode 100644 (file)
index eaefae5..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * $Id: interface.h,v 1.6 2009-12-13 02:21:47 didg Exp $
- * Copyright (c) 1990,1992 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifndef ATALKD_INTERFACE_H
-#define ATALKD_INTERFACE_H 1
-
-#include <sys/cdefs.h>
-
-struct interface {
-    struct interface   *i_next;
-    char               i_name[ IFNAMSIZ ];
-    int                        i_flags;
-    int                        i_time;
-    int                 i_group; /* for isolated appletalk domains */
-    struct sockaddr_at i_addr;
-    struct sockaddr_at i_caddr;
-    struct ziptab      *i_czt;
-    struct rtmptab     *i_rt;
-    struct gate                *i_gate;
-    struct atport      *i_ports;
-};
-
-#define IFACE_PHASE1   0x001
-#define IFACE_PHASE2   0x002
-#define IFACE_LOOPBACK 0x004           /* is the loopback interface */
-#define IFACE_SEED     0x008           /* act as seed */
-#define IFACE_ADDR     0x010           /* has an address set */
-#define IFACE_CONFIG   0x020           /* has been configured */
-#define IFACE_NOROUTER 0x040           /* no router on interface */
-#define IFACE_LOOP     0x080           /* has a loopback route */
-#define IFACE_RSEED     0x100           /* almost the same as seed. RSEED
-                                          says that we should try to 
-                                          do routing. */
-#define IFACE_DONTROUTE 0x200           /* don't route this interface */
-#define IFACE_ISROUTER  0x400           /* act as a router. */
-#define IFACE_ALLMULTI  0x800          /* set allmulti on this interface, linux only */
-#define IFACE_WASALLMULTI 0x1000       /* don't unset allmulti on this interface on shutdown, linux only */
-#define IFACE_ERROR    0x2000          /* sendto returned an error */
-
-#define UNSTABLE       2
-#define STABLE         0
-#define STABLEANYWAY   -2
-
-#define IFBASE         2       /* base number of interfaces */
-
-#ifdef linux
-#define LOOPIFACE      "lo"
-#else /* !linux */
-#define LOOPIFACE      "lo0"
-#endif /* linux */
-
-extern struct interface        *interfaces;
-extern struct interface        *ciface;
-struct interface       *newiface (const char *);
-
-#endif /* ATALKD_INTERFACE_H */
diff --git a/etc/atalkd/list.h b/etc/atalkd/list.h
deleted file mode 100644 (file)
index 17b7cce..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
- * $Id: list.h,v 1.2 2001-06-25 20:13:45 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1992 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-struct list {
-    void       *l_data;
-    struct list        *l_next,
-               *l_prev;
-};
diff --git a/etc/atalkd/main.c b/etc/atalkd/main.c
deleted file mode 100644 (file)
index 469678d..0000000
+++ /dev/null
@@ -1,1559 +0,0 @@
-/*
- * $Id: main.c,v 1.25 2009-12-13 02:21:47 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/file.h>
-#include <sys/time.h>
-#include <sys/resource.h>
-#include <sys/ioctl.h>
-
-/* POSIX.1 check */
-#include <sys/types.h>
-#ifdef HAVE_SYS_WAIT_H
-#include <sys/wait.h>
-#endif /* HAVE_SYS_WAIT_H */
-#ifndef WEXITSTATUS 
-#define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
-#endif /* ! WEXITSTATUS */
-#ifndef WIFEXITED
-#define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
-#endif /* ! WIFEXITED */
-#ifndef WIFSTOPPED
-#define WIFSTOPPED(status) (((status) & 0xff) == 0x7f)
-#endif
-
-#include <errno.h>
-#ifdef TRU64
-#include <sys/mbuf.h>
-#include <net/route.h>
-#endif /* TRU64 */
-#include <net/if.h>
-#include <net/route.h>
-
-#include <netinet/in.h>
-
-#include <signal.h>
-#include <atalk/logger.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <netdb.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/compat.h>
-#include <atalk/zip.h>
-#include <atalk/rtmp.h>
-#include <atalk/nbp.h>
-#include <atalk/ddp.h>
-#include <atalk/atp.h>
-#include <atalk/paths.h>
-#include <atalk/util.h>
-
-#ifdef __svr4__
-#include <sys/sockio.h>
-#include <termios.h>
-#endif /* __svr4__ */
-
-#include "interface.h"
-#include "gate.h"
-#include "list.h"
-#include "rtmp.h"
-#include "zip.h"
-#include "nbp.h"
-#include "atserv.h"
-#include "main.h"
-
-/* Forward Declarations */
-int ifconfig(const char *iname, unsigned long cmd, struct sockaddr_at *sa);
-
-/* FIXME/SOCKLEN_T: socklen_t is a unix98 feature */
-#ifndef SOCKLEN_T
-#define SOCKLEN_T unsigned int
-#endif /* SOCKLEN_T */
-
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(x) ((x).w_retcode)
-#endif /* WEXITSTATUS */
-
-/* linux has a special ioctl for appletalk device destruction.  as of
- * 2.1.57, SIOCDIFADDR works w/ linux. okay, we need to deal with the
- * fact that SIOCDIFADDR may be defined on linux despite the fact that
- * it doesn't work. */
-#if !defined(SIOCDIFADDR) && defined(SIOCATALKDIFADDR)
-#define SIOCDIFADDR SIOCATALKDIFADDR
-#endif
-
-#define elements(a)    (sizeof(a)/sizeof((a)[0]))
-
-#define PKTSZ  1024
-
-extern int aep_packet(struct atport *ap, struct sockaddr_at *from, char *data, int len);
-
-int            rtfd;
-int            transition = 0;
-int            stabletimer, newrtmpdata = 0;
-
-static struct atserv   atserv[] = {
-    { "rtmp",          1,      rtmp_packet },          /* 0 */
-    { "nbp",           2,      nbp_packet },           /* 1 */
-    { "echo",          4,      aep_packet },           /* 2 */
-    { "zip",           6,      zip_packet },           /* 3 */
-};
-static int             atservNATSERV = elements( atserv );
-
-struct interface       *interfaces = NULL, *ciface = NULL;
-
-static int             debug = 0, quiet = 0, chatty = 0;
-static char            *configfile = NULL;
-static int             ziptimeout = 0;
-static int             stable = 0, noparent = 0;
-static int             ninterfaces;
-static int             defphase = IFACE_PHASE2;
-static int             nfds = 0;
-static fd_set          fds;
-static char            Packet[ PKTSZ ];
-static char            *version = VERSION;
-static char            *pidfile = _PATH_ATALKDLOCK;
-
-
-/* from config.c */
-
-int readconf( char * );
-int getifconf( void );
-int writeconf( char * );
-
-/* this is the messiest of the bunch as atalkd can exit pretty much
- * everywhere. we delete interfaces here instead of in as_down. */
-static void atalkd_exit(const int i)
-{
-#ifdef SIOCDIFADDR
-  struct interface *iface;
-
-  for (iface = interfaces; iface; iface = iface->i_next) {
-    if (ifconfig( iface->i_name, SIOCDIFADDR, &iface->i_addr)) {
-#ifdef SIOCATALKDIFADDR
-#if (SIOCDIFADDR != SIOCATALKDIFADDR)
-      if (!ifconfig(iface->i_name, SIOCATALKDIFADDR, &iface->i_addr)) 
-       continue;
-#endif /* SIOCDIFADDR != SIOCATALKDIFADDR */
-#endif /* SIOCATALKIFADDR */
-      LOG(log_error, logtype_atalkd, "difaddr(%u.%u): %s", 
-             ntohs(iface->i_addr.sat_addr.s_net), 
-             iface->i_addr.sat_addr.s_node, strerror(errno));
-    }
-#ifdef linux
-    if (!(iface->i_flags & IFACE_WASALLMULTI) && (iface->i_flags & IFACE_ALLMULTI))
-        ifsetallmulti(iface->i_name, 0);
-#endif /* linux */
-  }
-#endif /* SOPCDOFADDR */
-
-  server_unlock(pidfile);
-  exit(i);
-}
-
-/* XXX need better error handling for gone interfaces, delete routes and so on 
- * moreover there's no way to put an interface back short of restarting atalkd
- * thus after the first time, silently fail
-*/
-static ssize_t sendto_iface(struct interface *iface, int sockfd, const void *buf, size_t len, 
-                       const struct sockaddr_at         *dest_addr)
-{
-    ssize_t ret = sendto( sockfd, buf, len, 0, (struct sockaddr *)dest_addr, sizeof( struct sockaddr_at ));
-
-    if (ret < 0 ) {
-        if (!(iface->i_flags & IFACE_ERROR)) {
-            LOG(log_error, logtype_atalkd, "as_timer sendto %u.%u (%u): %s",
-                                   ntohs( dest_addr->sat_addr.s_net ),
-                                   dest_addr->sat_addr.s_node,
-                                   ntohs( iface->i_rt->rt_firstnet ),
-                                   strerror(errno) );
-        }
-        iface->i_flags |= IFACE_ERROR;
-    }
-    else {
-        iface->i_flags &= ~IFACE_ERROR;
-    }
-    return ret;
-}
-
-static void as_timer(int sig _U_)
-{
-    struct sockaddr_at sat;
-    struct ziphdr      zh;
-    struct rtmp_head   rh;
-    struct rtmp_tuple  rt;
-    struct atport      *ap, *zap, *rap;
-    struct interface   *iface, *iface2;
-    struct gate                *gate, *fgate = NULL;
-    struct rtmptab     *rtmp, *frtmp;
-    struct ziptab      *zt;
-    char               *data, *end, packet[ ATP_BUFSIZ ];
-    int                        sentzipq = 0;
-    int                        n, cc;
-
-    ap=zap=rap=NULL;
-
-    memset(&sat, 0, sizeof( struct sockaddr_at ));
-
-    for ( iface = interfaces; iface; iface = iface->i_next ) {
-       if ( iface->i_flags & IFACE_LOOPBACK ) {
-           continue;
-       }
-       for ( ap = iface->i_ports; ap; ap = ap->ap_next ) {
-           if ( ap->ap_packet == zip_packet ) {
-               zap = ap;
-           }
-           if ( ap->ap_packet == rtmp_packet ) {
-               rap = ap;
-           }
-       }
-
-       if (( iface->i_flags & ( IFACE_ADDR|IFACE_CONFIG|IFACE_NOROUTER )) == IFACE_ADDR ) {
-           if ( iface->i_time < 3 ) {
-               if ( iface->i_flags & IFACE_PHASE1 ) {
-                 if (rtmp_request( iface ) < 0) {
-                     LOG(log_error, logtype_atalkd, "rtmp_request: %s", strerror(errno));
-                     atalkd_exit(1);
-                 }
-                   newrtmpdata = 1;
-               } else {
-                 if (zip_getnetinfo( iface ) < 0) {
-                   LOG(log_error, logtype_atalkd, "zip_getnetinfo: %s", strerror(errno));
-                   atalkd_exit(1);
-                 }
-                 sentzipq = 1;
-               }
-               iface->i_time++;
-           } else {
-               iface->i_flags |= IFACE_NOROUTER;
-               if ((iface->i_flags & IFACE_ISROUTER)) {
-                   if (( iface->i_flags & IFACE_SEED ) == 0 ) {
-                       /*
-                        * No seed info, and we've got multiple interfaces.
-                        * Wait forever.
-                        */
-                       LOG(log_info, logtype_atalkd, "as_timer multiple interfaces, no seed" );
-                       LOG(log_info, logtype_atalkd, "as_timer can't configure %s", iface->i_name );
-                       LOG(log_info, logtype_atalkd, "as_timer waiting for router" );
-                       iface->i_time = 0;
-                       continue;
-                   } else {
-                       /*
-                        * Complete configuration for iface, and boot next
-                        * interface.
-                        */
-                       iface->i_flags |= IFACE_CONFIG;
-                       for ( zt = iface->i_czt; zt; zt = zt->zt_next ) {
-                           if (addzone( iface->i_rt, zt->zt_len, zt->zt_name) < 0) {
-                             LOG(log_error, logtype_atalkd, "addzone: %s", strerror(errno));
-                             atalkd_exit(1);
-                           }
-                       }
-                       if ( iface->i_rt->rt_zt ) {
-                           iface->i_rt->rt_flags &= ~RTMPTAB_ZIPQUERY;
-                           iface->i_rt->rt_flags |= RTMPTAB_HASZONES;
-                       }
-                       if ( iface->i_flags & IFACE_PHASE1 ) {
-                           LOG(log_info, logtype_atalkd, "as_timer configured %s phase 1 from seed", iface->i_name );
-                           setaddr( iface, IFACE_PHASE1,
-                                   iface->i_caddr.sat_addr.s_net,
-                                   iface->i_addr.sat_addr.s_node,
-                                   iface->i_caddr.sat_addr.s_net,
-                                   iface->i_caddr.sat_addr.s_net );
-                       } else {
-                           LOG(log_info, logtype_atalkd, "as_timer configured %s phase 2 from seed", iface->i_name );
-                       }
-
-                       if ( looproute( iface, RTMP_ADD )) { /* -1 or 1 */
-                           LOG(log_error, logtype_atalkd, "as_timer: can't route %u.%u to loop: %s", 
-                                   ntohs( iface->i_addr.sat_addr.s_net ),
-                                   iface->i_addr.sat_addr.s_node, strerror(errno) );
-                           atalkd_exit( 1 );
-                       }
-                       if ( iface == ciface ) {
-                           ciface = ciface->i_next;
-                           bootaddr( ciface );
-                       }
-                   }
-               } else {
-                   /*
-                    * Configure for no router operation.  Wait for a route
-                    * to become available in rtmp_packet().
-                    */
-                   LOG(log_info, logtype_atalkd, "config for no router" );
-                     
-                   if ( iface->i_flags & IFACE_PHASE2 ) {
-                       iface->i_rt->rt_firstnet = 0;
-                       iface->i_rt->rt_lastnet = htons( STARTUP_LASTNET );
-                       setaddr( iface, IFACE_PHASE2, iface->i_addr.sat_addr.s_net, iface->i_addr.sat_addr.s_node,
-                               0, htons( STARTUP_LASTNET ));
-                   }
-                   if ( looproute( iface, RTMP_ADD ) ) { /* -1 or 1 */
-                       LOG(log_error, logtype_atalkd, "as_timer: can't route %u.%u to loopback: %s",
-                               ntohs( iface->i_addr.sat_addr.s_net ), iface->i_addr.sat_addr.s_node,
-                               strerror(errno) );
-                       atalkd_exit( 1 );
-                   }
-
-                   if ( iface == ciface ) {
-                     ciface = ciface->i_next;
-                     bootaddr( ciface );
-                   }
-               }
-           }
-       }
-
-       for ( gate = iface->i_gate; gate; gate = gate->g_next ) {
-           if ( fgate ) {
-               free( (caddr_t)fgate );
-               fgate = NULL;
-           }
-
-           n = 0;
-           data = packet + 1 + sizeof( struct ziphdr );
-           end = packet + sizeof( packet );
-
-           sat = gate->g_sat;
-           sat.sat_port = zap->ap_port;
-
-           /*
-            * Perform timeouts on routers.  If we've only got one
-            * interface, we'll use these timeouts to decide that
-            * our zone has gone away.
-            */
-           if ( ++gate->g_state >= RTMPTAB_BAD ) {
-               LOG(log_info, logtype_atalkd, "as_timer gateway %u.%u down", ntohs( gate->g_sat.sat_addr.s_net ),
-                       gate->g_sat.sat_addr.s_node );
-               rtmp = gate->g_rt;
-               while ( rtmp ) {
-                   frtmp = rtmp->rt_next;
-                   if ( rtmp->rt_hops == RTMPHOPS_POISON || rtmp->rt_iprev == NULL ) {
-                       rtmp_free( rtmp );
-                   } else {
-                       rtmp->rt_hops = RTMPHOPS_POISON;
-                       if ((cc = rtmp_replace( rtmp )) < 0) {
-                         LOG(log_error, logtype_atalkd, "rtmp_replace: %s", strerror(errno));
-                         atalkd_exit(1);
-                       }
-                       if (cc) {
-                           gate->g_state = rtmp->rt_state = RTMPTAB_GOOD;
-                       }
-                   }
-                   rtmp = frtmp;
-               }
-               if ( gate->g_rt == NULL ) {
-                   if ( gate->g_prev == NULL ) {
-                       gate->g_iface->i_gate = gate->g_next;
-                   } else {
-                       gate->g_prev->g_next = gate->g_next;
-                   }
-                   if ( gate->g_next != NULL ) {
-                       gate->g_next->g_prev = gate->g_prev;
-                   }
-                   fgate = gate;       /* can't free here, just mark it */
-               }
-               /*
-                * If this is the last router on the only interface,
-                * reconfigure our netrange.  By marking the interface
-                * as having no router, we will notice when a router
-                * comes back up.
-                *
-                * XXX: actually, we always reconfigure an interface
-                * if we're not a seed router.
-                */
-
-               if ( gate->g_iface->i_gate == NULL && ((iface->i_flags & IFACE_SEED) == 0)) {
-                   gate->g_iface->i_flags |= IFACE_NOROUTER;
-                   gate->g_iface->i_flags &= ~IFACE_CONFIG;
-
-                   /* get rid of any zones associated with this iface */
-                   if (gate->g_iface->i_rt->rt_zt) {
-                     rtmp_delzonemap(gate->g_iface->i_rt);
-                     gate->g_iface->i_rt->rt_flags &= ~RTMPTAB_HASZONES;
-                   }
-
-                   LOG(log_info, logtype_atalkd, "as_timer last gateway down" );
-
-                   /* Set netrange to 0-fffe.  */
-                   if ( gate->g_iface->i_flags & IFACE_PHASE2 ) {
-                       gate->g_iface->i_rt->rt_firstnet = 0;
-                       gate->g_iface->i_rt->rt_lastnet =
-                               htons( STARTUP_LASTNET );
-                       setaddr( iface, IFACE_PHASE2,
-                               iface->i_addr.sat_addr.s_net,
-                               iface->i_addr.sat_addr.s_node,
-                               0, htons( STARTUP_LASTNET ));
-                   }
-               }
-               continue;
-           }
-
-           /*
-            * If we don't have a zone for our interface yet, ask for
-            * it from any router (all routers) on the interface.
-            */
-           if (( iface->i_rt->rt_flags & RTMPTAB_HASZONES ) == 0 ) {
-               iface->i_rt->rt_flags |= RTMPTAB_ZIPQUERY;
-               memcpy( data, &iface->i_rt->rt_firstnet, sizeof( u_short ));
-               data += sizeof( u_short );
-               n++;
-           }
-
-           rtmp = gate->g_rt;
-           while ( rtmp ) {
-               /*
-                * Delete old routing tuples.
-                */
-               if ( rtmp->rt_state != RTMPTAB_PERM ) {
-                   rtmp->rt_state++;
-               }
-
-               /*
-                * We've not been updated for this route in a while.  If
-                * it's not in use, go ahead and remove it.  If it is in
-                * use, mark the route as down (POISON), and look for a
-                * better route.  If one is found, delete this route and use
-                * the new one.  If it's not found, mark the route as GOOD
-                * (so we'll propogate our poison) and delete it the next
-                * time it becomes BAD.
-                */
-               if ( rtmp->rt_state >= RTMPTAB_BAD ) {
-                   frtmp = rtmp->rt_next;
-                   if ( rtmp->rt_iprev == NULL ) {     /* not in use */
-                       rtmp_free( rtmp );
-                   } else {                            /* in use */
-                       if ( rtmp->rt_hops == RTMPHOPS_POISON ) {
-                           rtmp_free( rtmp );
-                       } else {
-                           rtmp->rt_hops = RTMPHOPS_POISON;
-                           if ((cc = rtmp_replace( rtmp )) < 0) {
-                               LOG(log_error, logtype_atalkd, "rtmp_replace: %s", strerror(errno));
-                               atalkd_exit(1);
-                           }
-                           if (cc)
-                               rtmp->rt_state = RTMPTAB_GOOD;
-                       }
-                   }
-                   rtmp = frtmp;
-                   continue;
-               }
-
-               /*
-                * Do ZIP lookups.
-                */
-               if ( rtmp->rt_iprev && ( rtmp->rt_flags & RTMPTAB_HASZONES ) == 0 ) {
-                   if ( data + sizeof( u_short ) > end || n == 255 ) {
-                       /* send what we've got */
-                       zh.zh_op = ZIPOP_QUERY;
-                       zh.zh_count = n;
-                       cc = data - packet;
-                       data = packet;
-                       *data++ = DDPTYPE_ZIP;
-                       memcpy( data, &zh, sizeof( struct ziphdr ));
-
-                       sendto_iface(iface,  zap->ap_fd, packet, cc, &sat);
-                       sentzipq = 1;
-
-                       n = 0;
-                       data = packet + 1 + sizeof( struct ziphdr );
-                       end = packet + sizeof( packet );
-                   }
-
-                   /*
-                    * rt_nzq is number of ZIP Queries we've issued for a
-                    * given netrange.  If we've got ziptimeout on, we
-                    * will only ask 3 times for any given netrange.
-                    * Interestingly enough, since rt_nzq is a u_char,
-                    * it will overflow after a while.  This means we will
-                    * periodically ask for nets that we've decided not to
-                    * ask about, and warn that we can't get it's zone.
-                    */
-                   if ( rtmp->rt_nzq++ == 3 ) {
-                       LOG(log_info, logtype_atalkd, "as_timer can't get zone for %u", ntohs( rtmp->rt_firstnet ));
-                   }
-                   if ( rtmp->rt_nzq > 3 ) {
-                       if ( ziptimeout ) {
-                           rtmp = rtmp->rt_next;
-                           continue;
-                       }
-                   } else {
-                       sentzipq = 1;
-                   }
-                   rtmp->rt_flags |= RTMPTAB_ZIPQUERY;
-                   memcpy( data, &rtmp->rt_firstnet, sizeof( u_short ));
-                   data += sizeof( u_short );
-                   n++;
-               }
-               rtmp = rtmp->rt_next;
-           }
-
-           /* send what we've got */
-           if ( n > 0 ) {
-               zh.zh_op = ZIPOP_QUERY;
-               zh.zh_count = n;
-               cc = data - packet;
-               data = packet;
-               *data++ = DDPTYPE_ZIP;
-               memcpy( data, &zh, sizeof( struct ziphdr ));
-
-               sendto_iface( iface, zap->ap_fd, packet, cc, &sat);
-           }
-       }
-       if ( fgate ) {
-           free( (caddr_t)fgate );
-           fgate = NULL;
-       }
-
-       /*
-        * Send RTMP broadcasts if we have multiple interfaces or our 
-        * interface is configured as a router.  
-        */
-       if ((iface->i_flags & IFACE_ISROUTER)) {
-#ifdef BSD4_4
-           sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-           sat.sat_family = AF_APPLETALK;
-           sat.sat_addr.s_net = ATADDR_ANYNET;
-           sat.sat_addr.s_node = ATADDR_BCAST;
-           sat.sat_port = rap->ap_port;
-
-           data = packet;
-           end = data + sizeof( packet );
-           *data++ = DDPTYPE_RTMPRD;
-           rh.rh_net = iface->i_addr.sat_addr.s_net;
-           rh.rh_nodelen = 8;
-           rh.rh_node = iface->i_addr.sat_addr.s_node;
-           memcpy( data, &rh, sizeof( struct rtmp_head ));
-           data += sizeof( struct rtmp_head );
-           n = 0;
-
-
-           if ( iface->i_flags & IFACE_PHASE1 ) {
-               rt.rt_net = 0;
-               rt.rt_dist = 0x82;
-               memcpy( data, &rt, SZ_RTMPTUPLE );
-               data += SZ_RTMPTUPLE;
-           } else {
-               rt.rt_net = iface->i_rt->rt_firstnet;
-               rt.rt_dist = 0x80;
-               memcpy( data, &rt, SZ_RTMPTUPLE );
-               data += SZ_RTMPTUPLE;
-
-               rt.rt_net = iface->i_rt->rt_lastnet;
-               rt.rt_dist = 0x82;
-               memcpy( data, &rt, SZ_RTMPTUPLE );
-               data += SZ_RTMPTUPLE;
-           }
-
-           for ( iface2 = interfaces; iface2; iface2 = iface2->i_next ) {
-
-             /* XXX: there used to be a bit checking against iface ==
-                iface2. also, we don't want to send an rtmp broadcast
-                to an interface that doesn't want it.  */
-               if ((( iface2->i_flags & IFACE_CONFIG ) == 0) ||
-                   ((iface2->i_flags & IFACE_ISROUTER) == 0)) {
-                   continue;
-               }
-               /*
-                * Fill in tuples.  Always send the same thing, regardless
-                * of the phase of the destination.  Routers who don't
-                * understand extended rtmp packets will toss extended
-                * tuples because their distance will have the high bit set.
-                */
-               for ( rtmp = iface2->i_rt; rtmp; rtmp = rtmp->rt_inext ) {
-                   /* don't broadcast routes we have no zone for */
-                   if ( rtmp->rt_zt == NULL ||
-                           ( rtmp->rt_flags & RTMPTAB_ZIPQUERY ) ||
-                           ( rtmp->rt_flags & RTMPTAB_HASZONES ) == 0 ) {
-                       continue;
-                   }
-
-                   /* split horizon */
-                   if (rtmp->rt_iface == iface) {
-                       continue;
-                   }
-
-                   if ((( rtmp->rt_flags & RTMPTAB_EXTENDED ) &&
-                           data + 2 * SZ_RTMPTUPLE > end ) ||
-                           data + SZ_RTMPTUPLE > end ) {
-
-                       sendto_iface(iface,rap->ap_fd, packet, data - packet, &sat);
-
-                       if ( iface->i_flags & IFACE_PHASE2 ) {
-                           data = packet + 1 + sizeof( struct rtmp_head ) + 2 * SZ_RTMPTUPLE;
-                       } else {
-                           data = packet + 1 + sizeof( struct rtmp_head ) + SZ_RTMPTUPLE;
-                       }
-                       n = 0;
-                   }
-
-                   rt.rt_net = rtmp->rt_firstnet;
-                   rt.rt_dist = rtmp->rt_hops;
-                   if ( rtmp->rt_flags & RTMPTAB_EXTENDED ) {
-                       rt.rt_dist |= 0x80;
-                   }
-                   memcpy( data, &rt, SZ_RTMPTUPLE );
-                   data += SZ_RTMPTUPLE;
-
-                   if ( rtmp->rt_flags & RTMPTAB_EXTENDED ) {
-                       rt.rt_net = rtmp->rt_lastnet;
-                       rt.rt_dist = 0x82;
-                       memcpy( data, &rt, SZ_RTMPTUPLE );
-                       data += SZ_RTMPTUPLE;
-                   }
-                   n++;
-               }
-           }
-
-           /* send rest */
-           if ( n ) {
-               sendto_iface(iface, rap->ap_fd, packet, data - packet, &sat);
-           }
-       }
-    }
-
-    /*
-     * Check if we're stable.  Each time we configure an interface, we
-     * sent stabletimer to UNSTABLE.  If stabletimer ever gets to
-     * STABLEANYWAY, we give up and decide to "be" stable anyway.
-     * Normally, we wait for stabletimer get <= STABLE with no new rtmp
-     * data and all zip data complete.
-     */
-    if ( !stable ) {
-       if ( stabletimer <= STABLE && !newrtmpdata && !sentzipq ) {
-           /* write out config file */
-           stable = 1;
-           writeconf( configfile );
-       } else {
-           if ( stabletimer-- <= STABLEANYWAY ) {
-               stable = 1;
-           }
-       }
-       newrtmpdata = 0;
-
-       if ( stable && !noparent ) {
-           noparent = 1;
-           LOG(log_info, logtype_atalkd, "ready %d/%d/%d", stabletimer, newrtmpdata,
-                   sentzipq );
-           if ( !debug ) {
-               /*
-                * Seems like we could get here more than once...
-                */
-               if ( kill( getpid(), SIGSTOP ) < 0 ) {
-                   LOG(log_error, logtype_atalkd, "as_timer: kill-self failed!" );
-                   atalkd_exit( 1 );
-               }
-           }
-       }
-    }
-
-#ifdef DEBUG
-    consistency();
-#endif /* DEBUG */
-}
-
-#ifdef DEBUG
-/*
-* Consistency check...
-*/
-consistency()
-{
-    struct rtmptab     *rtmp;
-    struct list                *lr, *lz;
-    struct ziptab      *zt;
-
-    for ( zt = ziptab; zt; zt = zt->zt_next ) {
-       for ( lr = zt->zt_rt; lr; lr = lr->l_next ) {
-           rtmp = (struct rtmptab *)lr->l_data;
-           if ( rtmp->rt_iprev == 0 && rtmp->rt_gate != 0 ) {
-               LOG(log_error, logtype_atalkd, "%.*s has %u-%u (unused)",
-                       zt->zt_len, zt->zt_name, ntohs( rtmp->rt_firstnet ),
-                       ntohs( rtmp->rt_lastnet ));
-               atalkd_exit(1);
-           }
-           for ( lz = rtmp->rt_zt; lz; lz = lz->l_next ) {
-               if ( zt == (struct ziptab *)lz->l_data ) {
-                   break;
-               }
-           }
-           if ( lz == 0 ) {
-               LOG(log_error, logtype_atalkd, "no map from %u-%u to %.*s", 
-                       ntohs( rtmp->rt_firstnet ),
-                       ntohs( rtmp->rt_lastnet ),
-                       zt->zt_len, zt->zt_name );
-               atalkd_exit(1);
-           }
-       }
-    }
-}
-#endif /* DEBUG */
-
-static void
-as_debug(int sig _U_)
-{
-    struct interface   *iface;
-    struct list                *l;
-    struct ziptab      *zt;
-    struct gate                *gate;
-    struct rtmptab     *rt;
-    FILE               *rtmpdebug;
-
-    if (( rtmpdebug = fopen( _PATH_ATALKDEBUG, "w" )) == NULL ) {
-       LOG(log_error, logtype_atalkd, "rtmp: %s", strerror(errno) );
-    }
-
-    for ( iface = interfaces; iface; iface = iface->i_next ) {
-       fprintf( rtmpdebug, "interface %s %u.%u ", iface->i_name,
-               ntohs( iface->i_addr.sat_addr.s_net ),
-               iface->i_addr.sat_addr.s_node );
-       if ( iface->i_flags & IFACE_PHASE1 ) {
-           putc( '1', rtmpdebug );
-       }
-       if ( iface->i_flags & IFACE_PHASE2 ) {
-           putc( '2', rtmpdebug );
-       }
-       if ( iface->i_flags & IFACE_RSEED ) {
-           putc( 'R', rtmpdebug );
-       }
-       if ( iface->i_flags & IFACE_SEED ) {
-           putc( 'S', rtmpdebug );
-       }
-       if ( iface->i_flags & IFACE_DONTROUTE ) {
-           putc( 'D', rtmpdebug );
-       }
-       if ( iface->i_flags & IFACE_ADDR ) {
-           putc( 'A', rtmpdebug );
-       }
-       if ( iface->i_flags & IFACE_CONFIG ) {
-           putc( 'C', rtmpdebug );
-       }
-       if ( iface->i_flags & IFACE_NOROUTER ) {
-           putc( 'N', rtmpdebug );
-       }
-       if ( iface->i_flags & IFACE_LOOP ) {
-           putc( 'L', rtmpdebug );
-       }
-       putc( '\n', rtmpdebug );
-
-       if ( iface->i_rt ) {
-           fprintf( rtmpdebug, "\t%u-%u ",
-                   ntohs( iface->i_rt->rt_firstnet ),
-                   ntohs( iface->i_rt->rt_lastnet ));
-           if ( iface->i_rt->rt_flags & RTMPTAB_ZIPQUERY ) {
-               putc( 'q', rtmpdebug );
-           }
-           if ( iface->i_rt->rt_flags & RTMPTAB_HASZONES ) {
-               putc( 'z', rtmpdebug );
-           }
-           if ( iface->i_rt->rt_flags & RTMPTAB_EXTENDED ) {
-               putc( 'x', rtmpdebug );
-           }
-           putc( 'i', rtmpdebug );
-           for ( l = iface->i_rt->rt_zt; l; l = l->l_next ) {
-               zt = (struct ziptab *)l->l_data;
-               fprintf( rtmpdebug, " '%.*s'", zt->zt_len, zt->zt_name );
-           }
-           fprintf( rtmpdebug, "\n" );
-       }
-
-       for ( gate = iface->i_gate; gate; gate = gate->g_next ) {
-           fprintf( rtmpdebug, "gate %u.%u %X\n",
-                   ntohs( gate->g_sat.sat_addr.s_net ),
-                   gate->g_sat.sat_addr.s_node, gate->g_state );
-           for ( rt = gate->g_rt; rt; rt = rt->rt_next ) {
-               fprintf( rtmpdebug, "\t%u-%u ", ntohs( rt->rt_firstnet ),
-                       ntohs( rt->rt_lastnet ));
-               if ( rt->rt_flags & RTMPTAB_ZIPQUERY ) {
-                   putc( 'q', rtmpdebug );
-               }
-               if ( rt->rt_flags & RTMPTAB_HASZONES ) {
-                   putc( 'z', rtmpdebug );
-               }
-               if ( rt->rt_flags & RTMPTAB_EXTENDED ) {
-                   putc( 'x', rtmpdebug );
-               }
-               if ( rt->rt_iprev ) {
-                   putc( 'i', rtmpdebug );
-               }
-               for ( l = rt->rt_zt; l; l = l->l_next ) {
-                   zt = (struct ziptab *)l->l_data;
-                   fprintf( rtmpdebug, " '%.*s'", zt->zt_len, zt->zt_name );
-               }
-               fprintf( rtmpdebug, "\n" );
-           }
-       }
-    }
-
-    fclose( rtmpdebug );
-}
-
-/*
- * Called when SIGTERM is recieved.  Remove all routes and then exit.
- */
-static void
-as_down(int sig _U_)
-{
-    struct interface   *iface;
-    struct gate                *gate;
-    struct rtmptab     *rt;
-
-    for ( iface = interfaces; iface; iface = iface->i_next ) {
-       for ( gate = iface->i_gate; gate; gate = gate->g_next ) {
-           for ( rt = gate->g_rt; rt; rt = rt->rt_next ) {
-               if ( rt->rt_iprev ) {
-                   if ( gateroute( RTMP_DEL, rt ) < 0 ) {
-                       LOG(log_error, logtype_atalkd, "as_down remove %u-%u failed: %s",
-                               ntohs( rt->rt_firstnet ),
-                               ntohs( rt->rt_lastnet ),
-                               strerror(errno) );
-                   }
-               }
-           }
-       }
-       if ( iface->i_flags & IFACE_LOOP ) {
-         if (looproute( iface, RTMP_DEL )) {
-           LOG(log_error, logtype_atalkd, "as_down remove %s %u.%u failed: %s",
-                   iface->i_name, ntohs( iface->i_addr.sat_addr.s_net ),
-                   iface->i_addr.sat_addr.s_node,
-                   strerror(errno) );
-         }
-       }
-    }
-
-    LOG(log_info, logtype_atalkd, "done" );
-    atalkd_exit( 0 );
-}
-
-int main( int ac, char **av)
-{
-    extern char         *optarg;
-    extern int          optind;
-
-    struct sockaddr_at sat;
-    struct sigaction   sv;
-    struct itimerval   it;
-    sigset_t            signal_set, old_set;
-    
-    struct interface   *iface;
-    int                        status;
-    struct atport      *ap;
-    fd_set             readfds;
-    int                        i, c;
-    SOCKLEN_T          fromlen;
-    char               *prog;
-
-    while (( c = getopt( ac, av, "12qsdtf:P:v" )) != EOF ) {
-       switch ( c ) {
-       case '1' :
-           defphase = IFACE_PHASE1;
-           break;
-
-       case '2' :
-           defphase = IFACE_PHASE2;
-           break;
-
-       case 'd' :
-           debug++;
-           break;
-
-       case 'f' :
-           configfile = optarg;
-           break;
-
-       case 'q' :      /* don't seed */
-           quiet++;
-           break;
-
-       case 's' :      /* seed */
-           chatty++;
-           break;
-
-       case 't' :      /* transition */
-           transition++;
-           break;
-
-       case 'P' :      /* pid file */
-           pidfile = optarg;
-           break;
-
-       case 'v' :      /* version */
-           printf( "atalkd (version %s)\n", version );
-           exit ( 1 );
-           break;
-
-       default :
-           fprintf( stderr, "Unknown option -- '%c'\n", c );
-           exit( 1 );
-       }
-    }
-    if ( optind != ac ) {
-       fprintf( stderr, "Too many arguments.\n" );
-       exit( 1 );
-    }
-
-    if (( prog = strrchr( av[ 0 ], '/' )) == NULL ) {
-       prog = av[ 0 ];
-    } else {
-       prog++;
-    }
-
-    /*
-     * Configure loop back address first, so appearances of "lo0" in
-     * the config file fail.  Also insures that lo0 gets configured,
-     * even if there's some hangup during configuration of some
-     * other interface.
-     */
-    if (( interfaces = newiface( LOOPIFACE )) == NULL ) {
-       perror( "newiface" );
-       exit( 1 );
-    }
-    interfaces->i_flags |= IFACE_PHASE2 | IFACE_LOOPBACK;
-
-    /*
-     * Check our initial configuration before we fork. This way we can
-     * complain about syntax errors on stdout.
-     *
-     * Basically, if we're going to read our config file, we should read
-     * it and initialize our data structures. If we're not going to read
-     * our config file, use GIFCONF to initialize our data structures.
-     */
-    if ( readconf( configfile ) < 0 && getifconf() < 0 ) {
-       fprintf( stderr, "%s: can't get interfaces, exiting.\n", prog );
-       exit( 1 );
-    }
-
-    /* we need to count up our interfaces so that we can simplify things
-     * later. we also need to figure out if we have more than one interface
-     * that is routing. */
-    for (i = 0, ninterfaces = 0, iface = interfaces; iface;
-        iface=iface->i_next) {
-      if (iface->i_flags & IFACE_DONTROUTE)
-       i++;
-      ninterfaces++;
-    }
-    i = ninterfaces - i; /* number of routable interfaces */
-
-    /*
-     * At this point, we have (at least partially) initialized data
-     * structures. Fill in what we can and verify that nothing is obviously
-     * broken.
-     */
-    for (iface = interfaces; iface; iface = iface->i_next) {
-       /* Apply the default phase */
-       if (( iface->i_flags & IFACE_PHASE1 ) == 0 &&
-               ( iface->i_flags & IFACE_PHASE2 ) == 0 ) {
-           iface->i_flags |= defphase;
-       }
-
-        /* set up router flag information. if we have multiple interfaces
-        * and DONTROUTE isn't set, set up ROUTER. i is the number of 
-        * interfaces that don't have the DONTROUTE flag set. */
-       if ((i > IFBASE) && ((iface->i_flags & IFACE_DONTROUTE) == 0)) {
-         iface->i_flags |= IFACE_ISROUTER;
-       }
-
-       /* Set default addresses */
-       if ( iface->i_rt == NULL ) {
-           if (( iface->i_rt = newrt(iface)) == NULL ) {
-               perror( "newrt" );
-               exit( 1 );
-           }
-
-           if ( iface->i_flags & IFACE_PHASE1 ) {
-               iface->i_rt->rt_firstnet = iface->i_rt->rt_lastnet =
-                       iface->i_caddr.sat_addr.s_net;
-           } else {
-               if ( iface->i_caddr.sat_addr.s_net != ATADDR_ANYNET ||
-                       ( iface->i_flags & IFACE_LOOPBACK )) {
-                   iface->i_rt->rt_firstnet = iface->i_rt->rt_lastnet =
-                           iface->i_caddr.sat_addr.s_net;
-               } else {
-                   iface->i_rt->rt_firstnet = htons( STARTUP_FIRSTNET );
-                   iface->i_rt->rt_lastnet = htons( STARTUP_LASTNET );
-               }
-           }
-       }
-       
-       if (( iface->i_flags & IFACE_PHASE1 ) == 0 ) {
-           iface->i_rt->rt_flags |= RTMPTAB_EXTENDED;
-       }
-
-       if ( iface->i_caddr.sat_addr.s_net == ATADDR_ANYNET ) {
-           iface->i_caddr.sat_addr.s_net = iface->i_rt->rt_firstnet;
-       }
-
-       if ( debug ) {
-           dumpconfig( iface );        /* probably needs args */
-       }
-    }
-
-    /*
-     * A little consistency check...
-     */
-    if ( ninterfaces < IFBASE ) {
-       fprintf( stderr, "%s: zero interfaces, exiting.\n", prog );
-       exit( 1 );
-    }
-
-    /*
-     * Set process name for logging
-     */
-
-    set_processname("atalkd");
-
-    /* do this here so that we can use ifconfig */
-#ifdef __svr4__
-    if ( plumb() < 0 ) {
-       fprintf(stderr, "can't establish STREAMS plumbing, exiting.\n" );
-       atalkd_exit( 1 );
-    }
-#endif /* __svr4__ */
-
-    /* delete pre-existing interface addresses. */
-#ifdef SIOCDIFADDR
-    for (iface = interfaces; iface; iface = iface->i_next) {
-      if (ifconfig(iface->i_name, SIOCDIFADDR, &iface->i_addr)) {
-#ifdef SIOCATALKDIFADDR
-#if (SIOCDIFADDR != SIOCATALKDIFADDR)
-       ifconfig(iface->i_name, SIOCATALKDIFADDR, &iface->i_addr);
-#endif /* SIOCDIFADDR != SIOCATALKDIFADDR */
-#endif /* SIOCATALKDIFADDR */
-      }
-    }
-#endif /* SIOCDIFADDR */
-
-    /*
-     * Disassociate. The child will send itself a signal when it is
-     * stable. This indicates that other processes may begin using
-     * AppleTalk.
-     */
-    switch (i = server_lock("atalkd", pidfile, debug)) {
-    case -1:
-      exit(1);
-    case 0: /* child */
-      break;
-    default: /* parent */
-      /*
-       * Wait for the child to send itself a SIGSTOP, after which
-       * we send it a SIGCONT and exit ourself.
-       */
-      if ( wait3( &status, WUNTRACED, (struct rusage *)0 ) != i) {
-       perror( "wait3" );      /* Child died? */
-       atalkd_exit( 1 );
-      }
-      if ( !WIFSTOPPED( status )) {
-       fprintf( stderr, "AppleTalk not up! Check your syslog for the reason." );
-       if ( WIFEXITED( status )) {
-         fprintf( stderr, " Child exited with %d.\n",
-                  WEXITSTATUS( status ));
-       } else {
-         fprintf( stderr, " Child died.\n" );
-       }
-       atalkd_exit( 1 );
-      }
-      if ( kill(i, SIGCONT ) < 0 ) {
-       perror( "kill" );
-       atalkd_exit( 1 );
-      }
-      exit( 0 );
-    }
-
-#ifdef ultrix
-    openlog( prog, LOG_PID );
-#else /* ultrix */
-    set_processname(prog);
-    syslog_setup(log_debug, logtype_default, logoption_pid, logfacility_daemon );
-#endif /* ultrix */
-
-    LOG(log_info, logtype_atalkd, "restart (%s)", version );
-
-    /*
-     * Socket for use in routing ioctl()s. Can't add routes to our
-     * interfaces until we have our routing socket.
-     */
-#ifdef BSD4_4
-    if (( rtfd = socket( PF_ROUTE, SOCK_RAW, AF_APPLETALK )) < 0 ) {
-       LOG(log_error, logtype_atalkd, "route socket: %s", strerror(errno) );
-       atalkd_exit( 1 );
-    }
-    if ( shutdown( rtfd, 0 ) < 0 ) {
-       LOG(log_error, logtype_atalkd, "route shutdown: %s", strerror(errno) );
-       atalkd_exit( 1 );
-    }
-#else /* BSD4_4 */
-    if (( rtfd = socket( AF_APPLETALK, SOCK_DGRAM, 0 )) < 0 ) {
-       LOG(log_error, logtype_atalkd, "route socket: %s", strerror(errno) );
-       atalkd_exit( 1 );
-    }
-#endif /* BSD4_4 */
-
-    ciface = interfaces;
-    bootaddr( ciface );
-
-    memset(&sv, 0, sizeof(sv));
-    sv.sa_handler = as_down;
-    sigemptyset( &sv.sa_mask );
-    sigaddset( &sv.sa_mask, SIGUSR1 );
-    sigaddset( &sv.sa_mask, SIGALRM );
-    sigaddset( &sv.sa_mask, SIGTERM );
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGTERM, &sv, NULL) < 0 ) {
-       LOG(log_error, logtype_atalkd, "sigterm: %s", strerror(errno) );
-       atalkd_exit( 1 );
-    }
-
-    sv.sa_handler = as_debug;
-    sigemptyset( &sv.sa_mask );
-    sigaddset( &sv.sa_mask, SIGUSR1 );
-    sigaddset( &sv.sa_mask, SIGALRM );
-    sigaddset( &sv.sa_mask, SIGTERM );
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGUSR1, &sv, NULL) < 0 ) {
-       LOG(log_error, logtype_atalkd, "sigusr1: %s", strerror(errno) );
-       atalkd_exit( 1 );
-    }
-
-    sv.sa_handler = as_timer;
-    sigemptyset( &sv.sa_mask );
-    sigaddset( &sv.sa_mask, SIGUSR1 );
-    sigaddset( &sv.sa_mask, SIGALRM );
-    sigaddset( &sv.sa_mask, SIGTERM );
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGALRM, &sv, NULL) < 0 ) {
-       LOG(log_error, logtype_atalkd, "sigalrm: %s", strerror(errno) );
-       atalkd_exit( 1 );
-    }
-
-    it.it_interval.tv_sec = 10L;
-    it.it_interval.tv_usec = 0L;
-    it.it_value.tv_sec = 10L;
-    it.it_value.tv_usec = 0L;
-    if ( setitimer( ITIMER_REAL, &it, NULL) < 0 ) {
-       LOG(log_error, logtype_atalkd, "setitimer: %s", strerror(errno) );
-       atalkd_exit( 1 );
-    }
-
-    sigemptyset( &signal_set );
-    sigaddset(&signal_set, SIGALRM);
-#if 0
-    /* don't block SIGTERM */
-    sigaddset(&signal_set, SIGTERM);
-#endif
-    sigaddset(&signal_set, SIGUSR1);
-
-    for (;;) {
-       readfds = fds;
-       if ( select( nfds, &readfds, NULL, NULL, NULL) < 0 ) {
-           if ( errno == EINTR ) {
-               errno = 0;
-               continue;
-           } else {
-               LOG(log_error, logtype_atalkd, "select: %s", strerror(errno) );
-               atalkd_exit( 1 );
-           }
-       }
-
-       for ( iface = interfaces; iface; iface = iface->i_next ) {
-           for ( ap = iface->i_ports; ap; ap = ap->ap_next ) {
-               if ( FD_ISSET( ap->ap_fd, &readfds )) {
-                   if ( ap->ap_packet ) {
-                       fromlen = sizeof( struct sockaddr_at );
-                       if (( c = recvfrom( ap->ap_fd, Packet, sizeof( Packet ),
-                               0, (struct sockaddr *)&sat, &fromlen )) < 0 ) {
-                           LOG(log_error, logtype_atalkd, "recvfrom: %s", strerror(errno) );
-                           continue;
-                       }
-#ifdef DEBUG1
-                       if ( debug ) {
-                           printf( "packet from %u.%u on %s (%x) %d (%d)\n",
-                                   ntohs( sat.sat_addr.s_net ),
-                                   sat.sat_addr.s_node, iface->i_name,
-                                   iface->i_flags, ap->ap_port, ap->ap_fd );
-                           bprint( Packet, c );
-                       }
-#endif 
-                       if (sigprocmask(SIG_BLOCK, &signal_set, &old_set) < 0) {
-                           LOG(log_error, logtype_atalkd, "sigprocmask: %s", strerror(errno) );
-                           atalkd_exit( 1 );
-                       }
-
-                       if (( *ap->ap_packet )( ap, &sat, Packet, c ) < 0) {
-                         LOG(log_error, logtype_atalkd, "ap->ap_packet: %s", strerror(errno));
-                         atalkd_exit(1);
-                       }
-
-#ifdef DEBUG
-                       consistency();
-#endif 
-                       if (sigprocmask(SIG_SETMASK, &old_set, NULL) < 0) {
-                           LOG(log_error, logtype_atalkd, "sigprocmask old set: %s", strerror(errno) );
-                           atalkd_exit( 1 );
-                       }
-
-                   }
-               }
-           }
-       }
-    }
-}
-
-/*
- * This code is called (from main(), as_timer(), zip_packet(),
- * and rtmp_packet()) to set the initial "bootstrapping" address
- * on an interface.
- */
-void bootaddr(struct interface *iface)
-{
-    if ( iface == NULL ) {
-       return;
-    }
-
-    /* consistency */
-    if ( iface->i_flags & IFACE_ADDR ) {
-       LOG(log_error, logtype_atalkd, "bootaddr OOPS!" );
-       atalkd_exit(1);
-    }
-
-    if ( iface->i_flags & IFACE_PHASE1 ) {
-       setaddr( iface, IFACE_PHASE1, 0,
-               iface->i_caddr.sat_addr.s_node, 0, 0 );
-
-       if ( iface->i_flags & IFACE_LOOPBACK ) {
-           iface->i_flags |= IFACE_CONFIG | IFACE_ADDR;
-           if ( ciface == iface ) {
-               ciface = ciface->i_next;
-               bootaddr( ciface );
-           }
-
-       } else if (rtmp_request( iface ) < 0) {
-         LOG(log_error, logtype_atalkd, "bootaddr (rtmp_request): %s", strerror(errno));
-         atalkd_exit(1);
-       }
-
-    } else {
-       setaddr( iface, IFACE_PHASE2, iface->i_caddr.sat_addr.s_net,
-               iface->i_caddr.sat_addr.s_node,
-               iface->i_rt->rt_firstnet, iface->i_rt->rt_lastnet );
-
-       if ( iface->i_flags & IFACE_LOOPBACK ) {
-           iface->i_flags |= IFACE_CONFIG | IFACE_ADDR;
-           if ( ciface == iface ) {
-               ciface = ciface->i_next;
-               bootaddr( ciface );
-           }
-           
-       } else if (zip_getnetinfo( iface ) < 0) {
-         LOG(log_error, logtype_atalkd, "bootaddr (zip_getnetinfo): %s", strerror(errno));
-         atalkd_exit(1);
-       }
-    }
-    ++iface->i_time;
-    iface->i_flags |= IFACE_ADDR;
-    stabletimer = UNSTABLE;
-}
-
-
-/*
- * Change setaddr()
- * to manage the i_ports field and the fds for select().
- */
-void setaddr(struct interface *iface,
-             u_int8_t  phase, u_int16_t net, u_int8_t node,
-            u_int16_t first, u_int16_t last)
-{
-    int                        i;
-    struct atserv      *as;
-    struct atport      *ap;
-    struct servent     *se;
-    struct sockaddr_at sat;
-    struct netrange    nr;
-
-    if ( iface->i_ports == NULL ) {    /* allocate port structures */
-       for ( i = 0, as = atserv; i < atservNATSERV; i++, as++ ) {
-           if (( se = getservbyname( as->as_name, "ddp" )) == NULL ) {
-               LOG(log_info, logtype_atalkd, "%s: service unknown", as->as_name );
-           } else {
-               as->as_port = ntohs( se->s_port );
-           }
-           if (( ap = (struct atport *)malloc( sizeof( struct atport ))) ==
-                   NULL ) {
-               LOG(log_error, logtype_atalkd, "malloc: %s", strerror(errno) );
-               atalkd_exit( 1 );
-           }
-           ap->ap_fd = 0;
-           ap->ap_next = iface->i_ports;
-           ap->ap_iface = iface;
-           ap->ap_port = as->as_port;
-           ap->ap_packet = as->as_packet;
-
-           iface->i_ports = ap;
-       }
-    } else {                           /* close ports */
-       for ( ap = iface->i_ports; ap; ap = ap->ap_next ) {
-           (void)close( ap->ap_fd );
-       }
-    }
-
-#ifdef BSD4_4
-    iface->i_addr.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    iface->i_addr.sat_family = AF_APPLETALK;
-    iface->i_addr.sat_addr.s_net = net;
-    iface->i_addr.sat_addr.s_node = node;
-
-    nr.nr_phase = phase;
-    nr.nr_firstnet = first;
-    nr.nr_lastnet = last;
-    memcpy( iface->i_addr.sat_zero, &nr, sizeof( struct netrange ));
-
-    if ( ifconfig( iface->i_name, SIOCSIFADDR, &iface->i_addr )) {
-      LOG(log_error, logtype_atalkd, "setifaddr: %s (%u-%u): %s. try specifying a \
-smaller net range.", iface->i_name, ntohs(first), ntohs(last), strerror(errno));
-       atalkd_exit( 1 );
-    }
-    if ( ifconfig( iface->i_name, SIOCGIFADDR, &iface->i_addr )) {
-       LOG(log_error, logtype_atalkd, "getifaddr: %s: %s", iface->i_name, strerror(errno) );
-       atalkd_exit( 1 );
-    }
-
-    /* open ports */
-    i = 1; /* enable broadcasts */
-#if 0
-    /* useless message, no? */
-    LOG(log_info, logtype_atalkd, "setsockopt incompatible w/ Solaris STREAMS module.");
-#endif /* __svr4__ */
-    for ( ap = iface->i_ports; ap; ap = ap->ap_next ) {
-       if (( ap->ap_fd = socket( AF_APPLETALK, SOCK_DGRAM, 0 )) < 0 ) {
-           LOG(log_error, logtype_atalkd, "socket: %s", strerror(errno) );
-           atalkd_exit( 1 );
-       }
-#ifndef __svr4__
-       setsockopt(ap->ap_fd, SOL_SOCKET, SO_BROADCAST, &i, sizeof(i));
-#endif /* ! __svr4 */
-
-       memset( &sat, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-       sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-       sat.sat_family = AF_APPLETALK;
-       sat.sat_addr.s_net = iface->i_addr.sat_addr.s_net;
-       sat.sat_addr.s_node = iface->i_addr.sat_addr.s_node;
-       sat.sat_port = ap->ap_port;
-
-       if ( bind( ap->ap_fd, (struct sockaddr *)&sat,
-               sizeof( struct sockaddr_at )) < 0 ) {
-           LOG(log_error, logtype_atalkd, "bind %u.%u:%u: %s",
-                   ntohs( sat.sat_addr.s_net ),
-                   sat.sat_addr.s_node, sat.sat_port, strerror(errno) );
-#ifdef SIOCDIFADDR
-           /* remove all interfaces if we have a problem with bind */
-           for (iface = interfaces; iface; iface = iface->i_next) {
-             if (ifconfig( iface->i_name, SIOCDIFADDR, &iface->i_addr )) {
-#ifdef SIOCATALKDIFADDR
-#if (SIOCDIFADDR != SIOCATALKDIFADDR)
-               ifconfig( iface->i_name, SIOCATALKDIFADDR, &iface->i_addr );
-#endif /* SIOCDIFADDR != SIOCATALKDIFADDR */
-#endif /* SIOCATALKDIFADDR */
-             }
-           }
-#endif /* SIOCDIFADDR */
-           atalkd_exit( 1 );
-       }
-    }
-
-    /* recalculate nfds and fds */
-    FD_ZERO( &fds );
-    for ( nfds = 0, iface = interfaces; iface; iface = iface->i_next ) {
-       for ( ap = iface->i_ports; ap; ap = ap->ap_next ) {
-           FD_SET( ap->ap_fd, &fds );
-           if ( ap->ap_fd > nfds ) {
-               nfds = ap->ap_fd;
-           }
-       }
-    }
-    nfds++;
-}
-
-int ifsetallmulti (const char *iname, int set)
-{
-    int sock;
-    struct ifreq ifr;
-
-    memset(&ifr, 0, sizeof(ifr));
-
-    if (( sock = socket( AF_APPLETALK, SOCK_DGRAM, 0 )) < 0 ) {
-        return( -1 );
-    }
-
-    /* get interface config */
-    strlcpy(ifr.ifr_name, iname, sizeof(ifr.ifr_name));
-    if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
-        close(sock);
-        return (-1);
-    }
-
-    /* should we set or unset IFF_ALLMULTI */
-    if (set)
-           ifr.ifr_flags |= IFF_ALLMULTI;
-    else
-           ifr.ifr_flags &= ~IFF_ALLMULTI;
-
-    /* set interface config */
-    strlcpy(ifr.ifr_name, iname, sizeof(ifr.ifr_name));
-    if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) {
-        close(sock);   
-        return -1;
-    }
-
-    close(sock);
-    return (0);
-}
-
-int ifconfig( const char *iname, unsigned long cmd, struct sockaddr_at *sa)
-{
-    struct ifreq       ifr;
-    int                        s;
-
-    memset(&ifr, 0, sizeof(ifr));
-    strcpy( ifr.ifr_name, iname );
-    ifr.ifr_addr = *(struct sockaddr *)sa;
-
-    if (( s = socket( AF_APPLETALK, SOCK_DGRAM, 0 )) < 0 ) {
-       return( 1 );
-    }
-    if ( ioctl( s, cmd, &ifr ) < 0 ) {
-       close(s);
-       return( 1 );
-    }
-    close( s );
-    if ( cmd == SIOCGIFADDR ) {
-       *(struct sockaddr *)sa = ifr.ifr_addr;
-    }
-    return( 0 );
-}
-
-void dumpconfig( struct interface *iface)
-{
-    struct list                *l;
-
-    printf( "%s", iface->i_name );
-    if ( iface->i_flags & IFACE_RSEED ) {
-       printf( " -router" );
-    } else if ( iface->i_flags & IFACE_SEED ) {
-       printf( " -seed" );
-    }
-
-    if ( iface->i_flags & IFACE_DONTROUTE) 
-        printf( " -dontroute");
-
-    printf( " -phase" );
-    if ( iface->i_flags & IFACE_PHASE1 ) {
-       printf( " 1" );
-    } else {
-       printf( " 2" );
-    }
-    printf( " -net %d", ntohs( iface->i_rt->rt_firstnet ));
-    if ( iface->i_rt->rt_lastnet != iface->i_rt->rt_firstnet ) {
-       printf( "-%d", ntohs( iface->i_rt->rt_lastnet ));
-    }
-    printf( " -addr %u.%u", ntohs( iface->i_addr.sat_addr.s_net ),
-           iface->i_addr.sat_addr.s_node );
-    printf( " -caddr %u.%u", ntohs( iface->i_caddr.sat_addr.s_net ),
-           iface->i_caddr.sat_addr.s_node );
-    for ( l = iface->i_rt->rt_zt; l; l = l->l_next ) {
-       printf( " -zone %.*s", ((struct ziptab *)l->l_data)->zt_len,
-               ((struct ziptab *)l->l_data)->zt_name );
-    }
-    printf( "\n" );
-}
-
-#ifdef DEBUG
-void dumproutes(void)
-{
-    struct interface   *iface;
-    struct rtmptab     *rtmp;
-    struct list                *l;
-    struct ziptab      *zt;
-
-    for ( iface = interfaces; iface; iface = iface->i_next ) {
-       for ( rtmp = iface->i_rt; rtmp; rtmp = rtmp->rt_inext ) {
-           if ( rtmp->rt_gate == 0 ) {
-               if ( rtmp->rt_flags & RTMPTAB_EXTENDED ) {
-                   printf( "%u-%u", ntohs( rtmp->rt_firstnet ),
-                           ntohs( rtmp->rt_lastnet ));
-               } else {
-                   printf( "%u", ntohs( rtmp->rt_firstnet ));
-               }
-           } else {
-               if ( rtmp->rt_flags & RTMPTAB_EXTENDED ) {
-                   printf( "%u.%u for %u-%u",
-                           ntohs( rtmp->rt_gate->g_sat.sat_addr.s_net ),
-                           rtmp->rt_gate->g_sat.sat_addr.s_node,
-                           ntohs( rtmp->rt_firstnet ),
-                           ntohs( rtmp->rt_lastnet ));
-               } else {
-                   printf( "%u.%u for %u",
-                           ntohs( rtmp->rt_gate->g_sat.sat_addr.s_net ),
-                           rtmp->rt_gate->g_sat.sat_addr.s_node,
-                           ntohs( rtmp->rt_firstnet ));
-               }
-           }
-
-           if ( rtmp->rt_iprev == 0 && rtmp != iface->i_rt ) {
-               printf( " *" );
-           }
-
-           for ( l = rtmp->rt_zt; l; l = l->l_next ) {
-               zt = (struct ziptab *)l->l_data;
-               printf( " %.*s", zt->zt_len, zt->zt_name );
-           }
-
-           printf( "\n" );
-       }
-    }
-
-    printf( "\n" );
-    fflush( stdout );
-}
-
-void dumpzones(void)
-{
-    struct interface   *iface;
-    struct rtmptab     *rtmp;
-    struct list                *l;
-    struct ziptab      *zt;
-
-    for ( zt = ziptab; zt; zt = zt->zt_next ) {
-       printf( "%.*s", zt->zt_len, zt->zt_name );
-       for ( l = zt->zt_rt; l; l = l->l_next ) {
-           rtmp = (struct rtmptab *)l->l_data;
-           if ( rtmp->rt_flags & RTMPTAB_EXTENDED ) {
-               printf( " %u-%u", ntohs( rtmp->rt_firstnet ),
-                       ntohs( rtmp->rt_lastnet ));
-           } else {
-               printf( " %u", ntohs( rtmp->rt_firstnet ));
-           }
-           if ( rtmp->rt_iprev == 0 && rtmp->rt_gate != 0 ) {
-               printf( "*" );
-           }
-       }
-       printf( "\n" );
-    }
-
-    printf( "\n" );
-    fflush( stdout );
-}
-#endif /* DEBUG */
diff --git a/etc/atalkd/main.h b/etc/atalkd/main.h
deleted file mode 100644 (file)
index 39e6b52..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * $Id: main.h,v 1.6 2009-10-14 01:38:28 didg Exp $
- */
-
-#ifndef ATALKD_MAIN_H
-#define ATALKD_MAIN_H
-
-#include <sys/cdefs.h>
-#include "config.h"
-
-extern int transition;
-extern int stabletimer, newrtmpdata;
-
-int ifconfig ( const char *, unsigned long, struct sockaddr_at * );
-void setaddr ( struct interface *, u_int8_t, u_int16_t,
-        u_int8_t, u_int16_t, u_int16_t );
-void bootaddr ( struct interface * );
-void dumpconfig ( struct interface * );
-
-#ifdef linux
-int ifsetallmulti ( const char *, int);
-#endif
-
-#endif /* ATALKD_MAIN_H */
diff --git a/etc/atalkd/multicast.c b/etc/atalkd/multicast.c
deleted file mode 100644 (file)
index 3b7785c..0000000
+++ /dev/null
@@ -1,381 +0,0 @@
-/*
- * $Id: multicast.c,v 1.13 2009-10-14 01:38:28 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#ifdef TRU64
-#include <sys/mbuf.h>
-#include <net/route.h>
-#endif /* TRU64 */
-#include <net/if.h>
-#include <atalk/logger.h>
-
-/* work around for FreeBSD */
-#if defined(__FreeBSD__) && (__FreeBSD__ >= 2)
-#include <osreldate.h>
-#if __FreeBSD_version >= 300000
-#include <net/if_dl.h>
-#define NO_DATA_LINK_PASSTHROUGH
-#endif /* __FreeBSD_version >= 300000 */
-#endif /* __FreeBSD__ */
-
-#ifdef __svr4__
-#include <sys/sockio.h>
-#endif /* __svr4__ */
-
-#include <atalk/util.h>
-#include <netatalk/endian.h>
-#include "rtmp.h"
-#include "zip.h"
-#include "main.h"
-#include "multicast.h"
-
-
-static const unsigned char     ethermulti[ 6 ] = {
-    0x09, 0x00, 0x07, 0xff, 0xff, 0xff,
-};
-
-static const unsigned char     ethermultitab[ 253 ][ 6 ] = {
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x00, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x01, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x02, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x03, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x04, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x05, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x06, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x07, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x08, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x09, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x0a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x0b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x0c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x0d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x0e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x0f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x10, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x11, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x12, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x13, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x14, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x15, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x16, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x17, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x18, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x19, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x1a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x1b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x1c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x1d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x1e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x1f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x20, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x21, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x22, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x23, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x24, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x25, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x26, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x27, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x28, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x29, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x2a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x2b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x2c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x2d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x2e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x2f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x30, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x31, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x32, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x33, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x34, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x35, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x36, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x37, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x38, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x39, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x3a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x3b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x3c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x3d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x3e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x3f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x40, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x41, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x42, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x43, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x44, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x45, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x46, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x47, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x48, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x49, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x4a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x4b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x4c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x4d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x4e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x4f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x50, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x51, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x52, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x53, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x54, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x55, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x56, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x57, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x58, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x59, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x5a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x5b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x5c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x5d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x5e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x5f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x60, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x61, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x62, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x63, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x64, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x65, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x66, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x67, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x68, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x69, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x6a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x6b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x6c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x6d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x6e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x6f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x70, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x71, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x72, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x73, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x74, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x75, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x76, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x77, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x78, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x79, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x7a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x7b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x7c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x7d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x7e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x7f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x80, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x81, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x82, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x83, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x84, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x85, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x86, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x87, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x88, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x89, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x8a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x8b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x8c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x8d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x8e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x8f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x90, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x91, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x92, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x93, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x94, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x95, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x96, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x97, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x98, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x99, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x9a, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x9b, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x9c, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x9d, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x9e, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0x9f, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa0, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa1, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa2, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa3, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa4, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa5, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa6, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa7, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa8, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xa9, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xaa, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xab, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xac, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xad, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xae, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xaf, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb0, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb1, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb2, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb3, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb4, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb5, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb6, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb7, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb8, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xb9, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xba, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xbb, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xbc, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xbd, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xbe, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xbf, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc0, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc1, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc2, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc3, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc4, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc5, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc6, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc7, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc8, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xc9, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xca, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xcb, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xcc, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xcd, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xce, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xcf, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd0, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd1, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd2, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd3, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd4, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd5, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd6, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd7, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd8, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xd9, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xda, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xdb, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xdc, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xdd, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xde, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xdf, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe0, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe1, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe2, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe3, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe4, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe5, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe6, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe7, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe8, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xe9, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xea, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xeb, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xec, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xed, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xee, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xef, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf0, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf1, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf2, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf3, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf4, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf5, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf6, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf7, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf8, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xf9, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xfa, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xfb, },
-    { 0x09, 0x00, 0x07, 0x00, 0x00, 0xfc, },
-};
-
-
-
-/* configure multicast for a given named interface */
-int addmulti(const char *name, const unsigned char *data)
-{
-#ifdef NO_DATA_LINK_PASSTHROUGH
-    struct sockaddr_dl sa;
-#else /* NO_DATA_LINK_PASSTHROUGH */
-    struct sockaddr sa;
-#endif /* NO_DATA_LINK_PASSTHROUGH */
-
-    memset(&sa, 0, sizeof(sa));
-#ifdef NO_DATA_LINK_PASSTHROUGH
-    sa.sdl_family = AF_LINK;
-    memcpy(LLADDR(&sa), data ? data : ethermulti, sizeof(ethermulti));
-    sa.sdl_alen = sizeof(ethermulti);
-    sa.sdl_len = sizeof(sa);
-#else /* NO_DATA_LINK_PASSTHROUGH */
-    memcpy(sa.sa_data, data ? data : ethermulti, sizeof(ethermulti));
-#endif /* NO_DATA_LINK_PASSTHROUGH */
-    if (ifconfig(name, SIOCADDMULTI, (struct sockaddr_at *)&sa))
-      return -1;
-
-    return 0;
-}
-
-static u_int16_t
-atalk_cksum( u_char *data, int len)
-{
-    u_char     *end;
-    u_int32_t  cksum = 0;
-
-    for ( end = data + len; data < end; data++ ) {
-       cksum = ( cksum + *data ) << 1;
-       if ( cksum & 0x00010000 ) {
-           cksum++;
-       }
-       cksum &= 0x0000ffff;
-    }
-
-    if ( cksum == 0 ) {
-       cksum = 0x0000ffff;
-    }
-
-    return( (u_int16_t) cksum );
-}
-
-/*
- * Fill in multicast for zone.  There is a general issue here:  how can
- * we tell the type of interface we're configuring for?  E.g.  Is it
- * ethernet, tokenring, or FDDI?  (Of course, FDDI and Ethernet look just
- * alike.)
- */
-int
-zone_bcast( struct ziptab *zt)
-{
-    u_char             uname[ 32 ];
-    u_int16_t          cksum;
-    int                        i;
-
-    if (!zt->zt_bcast &&
-       (zt->zt_bcast = (u_char *) malloc(sizeof( ethermulti ))) == NULL) {
-       LOG(log_error, logtype_atalkd, "zone_bcast malloc: %s", strerror(errno) );
-       return -1;
-     }
-
-    for ( i = 0; i < zt->zt_len; i++ ) {
-       uname[ i ] = diatoupper((int) zt->zt_name[ i ]);
-    }
-    cksum = atalk_cksum( uname, zt->zt_len );
-#define elements(a)   (sizeof(a)/sizeof((a)[0]))
-    memcpy(zt->zt_bcast, ethermultitab[ cksum % elements( ethermultitab ) ],
-          sizeof( ethermulti ));
-    return 0;
-}
diff --git a/etc/atalkd/multicast.h b/etc/atalkd/multicast.h
deleted file mode 100644 (file)
index 988b189..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * $Id: multicast.h,v 1.5 2009-10-14 01:38:28 didg Exp $
- *
- * Copyright (c) 1990,1997 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifndef ATALKD_MULTICAST_H
-#define ATALKD_MULTICAST_H 1
-
-#include <sys/cdefs.h>
-#include "zip.h"
-
-int addmulti (const char *, const unsigned char *);
-int zone_bcast (struct ziptab *);
-
-#endif /* atalkd/multicast.h */
diff --git a/etc/atalkd/nbp.c b/etc/atalkd/nbp.c
deleted file mode 100644 (file)
index 2d2e5b0..0000000
+++ /dev/null
@@ -1,650 +0,0 @@
-/*
- * $Id: nbp.c,v 1.13 2009-10-14 02:24:05 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <atalk/logger.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/ioctl.h>
-#ifdef TRU64
-#include <sys/mbuf.h>
-#include <net/route.h>
-#endif /* TRU64 */
-#include <net/if.h>
-#include <netatalk/at.h>
-#include <atalk/ddp.h>
-#include <atalk/atp.h>
-#include <atalk/nbp.h>
-#include <atalk/util.h>
-
-#ifdef __svr4__
-#include <sys/sockio.h>
-#endif /* __svr4__ */
-
-#include "atserv.h"
-#include "interface.h"
-#include "list.h"
-#include "rtmp.h"
-#include "gate.h"
-#include "zip.h"
-#include "nbp.h"
-#include "multicast.h"
-
-extern int  transition;
-
-struct nbptab   *nbptab = NULL;
-
-static
-void nbp_ack( int fd, int nh_op, int nh_id, struct sockaddr_at *to)
-{
-    struct nbphdr   nh;
-    char        *data, packet[ SZ_NBPHDR + 1 ];
-
-    nh.nh_op = nh_op;
-    nh.nh_cnt = 0;
-    nh.nh_id = nh_id;
-    data = packet;
-    *data++ = DDPTYPE_NBP;
-    memcpy( data, &nh, SZ_NBPHDR );
-    data += SZ_NBPHDR;
-    if ( sendto( fd, packet, data - packet, 0, (struct sockaddr *)to,
-                 sizeof( struct sockaddr_at )) < 0 ) {
-        LOG(log_error, logtype_atalkd, "sendto: %s", strerror(errno) );
-    }
-}
-
-int nbp_packet(struct atport *ap, struct sockaddr_at *from, char *data, int len)
-{
-    struct nbphdr   nh;
-    struct nbptuple nt;
-    struct nbpnve   nn;
-    struct sockaddr_at  sat;
-    struct nbptab   *ntab;
-    struct ziptab   *zt=NULL;
-    struct interface    *iface;
-    struct list     *l;
-    struct rtmptab  *rtmp;
-    char        *end, *nbpop, *zonep, packet[ ATP_BUFSIZ ];
-    int         n, i, cc, locallkup;
-    u_char      tmplen;
-
-    end = data + len;
-    if ( data >= end ) {
-        LOG(log_info, logtype_atalkd, "nbp_packet malformed packet" );
-        return 1;
-    }
-    if ( *data++ != DDPTYPE_NBP ) {
-        LOG(log_info, logtype_atalkd, "nbp_packet bad ddp type" );
-        return 1;
-    }
-
-    if ( data + SZ_NBPHDR + SZ_NBPTUPLE > end ) {
-        LOG(log_info, logtype_atalkd, "nbp_packet: malformed packet" );
-        return 1;
-    }
-    memcpy( &nh, data, SZ_NBPHDR );
-    nbpop = data;           /* remember for fwd and brrq */
-    data += SZ_NBPHDR;
-    if ( nh.nh_cnt != 1 ) {
-        LOG(log_info, logtype_atalkd, "nbp_packet: bad tuple count (%d/%d)", nh.nh_cnt,
-            nh.nh_op );
-        return 1;
-    }
-
-    memcpy( &nt, data, SZ_NBPTUPLE );
-    data += SZ_NBPTUPLE;
-
-    memset( &nn.nn_sat, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    nn.nn_sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    nn.nn_sat.sat_family = AF_APPLETALK;
-    nn.nn_sat.sat_addr.s_net = nt.nt_net;
-    nn.nn_sat.sat_addr.s_node = nt.nt_node;
-    nn.nn_sat.sat_port = nt.nt_port;
-
-    /* object */
-    tmplen = (u_char) *data;
-    if ( data >= end || tmplen > 32 || data + tmplen > end ) {
-        LOG(log_info, logtype_atalkd, "nbp_packet: malformed packet" );
-        return 1;
-    }
-    nn.nn_objlen = tmplen;
-    data++;
-    memcpy( nn.nn_obj, data, nn.nn_objlen );
-    data += nn.nn_objlen;
-
-    /* type */
-    tmplen = (u_char) *data;
-    if ( data >= end || tmplen > 32 || data + tmplen > end ) {
-        LOG(log_info, logtype_atalkd, "nbp_packet: malformed packet" );
-        return 1;
-    }
-    nn.nn_typelen = tmplen;
-    data++;
-    memcpy( nn.nn_type, data, nn.nn_typelen );
-    data += nn.nn_typelen;
-
-    /* zone */
-    tmplen = (u_char) *data;
-    if ( data >= end || tmplen > 32 || data + tmplen > end ) {
-        LOG(log_info, logtype_atalkd, "nbp_packet: malformed packet" );
-        return 1;
-    }
-    zonep = data;           /* remember for fwd */
-    nn.nn_zonelen = tmplen;
-    data++;
-    memcpy( nn.nn_zone, data, nn.nn_zonelen );
-    data += nn.nn_zonelen;
-
-    if ( data != end ) {
-        LOG(log_info, logtype_atalkd, "nbp_packet: malformed packet" );
-        return 1;
-    }
-
-    locallkup = 0;
-    switch ( nh.nh_op ) {
-
-    case NBPOP_RGSTR :
-        /*
-         * Find the ziptab entry for the zone we're trying to register in.
-         */
-        if ( nn.nn_zonelen == 0 ||
-             ( nn.nn_zonelen == 1 && *nn.nn_zone == '*' )) {
-            if ( interfaces->i_next->i_rt->rt_zt ) {
-                zt = (struct ziptab *)interfaces->i_next->i_rt->rt_zt->l_data;
-            } else {
-                zt = NULL;
-            }
-        } else {
-            for ( zt = ziptab; zt; zt = zt->zt_next ) {
-                if ( zt->zt_len == nn.nn_zonelen && strndiacasecmp( zt->zt_name,
-                                                                    nn.nn_zone, zt->zt_len ) == 0 ) {
-                    break;
-                }
-            }
-            if ( zt == NULL ) {
-                nbp_ack( ap->ap_fd, NBPOP_ERROR, (int)nh.nh_id, from );
-                return 0;
-            }
-        }
-
-        /*
-         * Observe that we don't have to do any local-zone verification
-         * if the zone aleady has a multicast address set.
-         */
-        if ( zt != NULL && zt->zt_bcast == NULL ) {
-            /*
-             * Check if zone is associated with any of our local interfaces.
-             */
-            for ( iface = interfaces; iface; iface = iface->i_next ) {
-                for ( l = iface->i_rt->rt_zt; l; l = l->l_next ) {
-                    if ( zt == (struct ziptab *)l->l_data ) {
-                        break;
-                    }
-                }
-                if ( l != NULL ) {
-                    break;
-                }
-            }
-            if ( iface == NULL ) {
-                nbp_ack( ap->ap_fd, NBPOP_ERROR, (int)nh.nh_id, from );
-                return 0;
-            }
-
-            /* calculate and save multicast address */
-            if (zone_bcast(zt) < 0) {
-                LOG(log_error, logtype_atalkd, "nbp_packet: zone_bcast");
-                return -1;
-            }
-
-            for ( iface = interfaces; iface; iface = iface->i_next ) {
-                if (( iface->i_flags & IFACE_PHASE2 ) == 0 ) {
-                    continue;
-                }
-                for ( l = iface->i_rt->rt_zt; l; l = l->l_next ) {
-                    if ( zt == (struct ziptab *)l->l_data ) {
-                        /* add multicast */
-                        if (addmulti(iface->i_name, zt->zt_bcast) < 0) {
-                            LOG(log_error, logtype_atalkd, "nbp_packet: addmulti: %s",
-                                strerror(errno) );
-                            return -1;
-                        }
-                    }
-                }
-            }
-        }
-
-        if (( ntab = (struct nbptab *)malloc( sizeof( struct nbptab )))
-            == NULL ) {
-            LOG(log_error, logtype_atalkd, "nbp_packet: malloc: %s", strerror(errno) );
-            return -1;
-        }
-        memcpy( &ntab->nt_nve, &nn, sizeof( struct nbpnve ));
-        ntab->nt_iface = ap->ap_iface;
-        ntab->nt_next = nbptab;
-        ntab->nt_prev = NULL;
-        if ( nbptab ) {
-            nbptab->nt_prev = ntab;
-        }
-        nbptab = ntab;
-
-        nbp_ack( ap->ap_fd, NBPOP_OK, (int)nh.nh_id, from );
-        break;
-
-    case NBPOP_UNRGSTR :
-        /* deal with local zone info */
-        if (( nn.nn_zonelen == 1 && *nn.nn_zone == '*' ) ||
-            ( nn.nn_zonelen == 0 )) {
-            locallkup = 1;
-            if ( interfaces->i_next->i_rt->rt_zt ) {
-                zt = (struct ziptab *)interfaces->i_next->i_rt->rt_zt->l_data;
-            } else {
-                zt = NULL;
-            }
-        }
-
-        /* remove from our data, perhaps removing a multicast address */
-        for ( ntab = nbptab; ntab; ntab = ntab->nt_next ) {
-            if ( ntab->nt_nve.nn_objlen != nn.nn_objlen ||
-                 strndiacasecmp( ntab->nt_nve.nn_obj, nn.nn_obj,
-                                 nn.nn_objlen )) {
-                continue;
-            }
-            if ( ntab->nt_nve.nn_typelen != nn.nn_typelen ||
-                 strndiacasecmp( ntab->nt_nve.nn_type, nn.nn_type,
-                                 nn.nn_typelen )) {
-                continue;
-            }
-            /*
-             * I *think* we really do check the zone, here.
-             *
-             * i changed it to better handle local zone cases as well.
-             * -- asun
-             */
-
-            /* match local zones */
-            if (locallkup) {
-                /* ntab is also local zone */
-                if (( ntab->nt_nve.nn_zonelen == 1 &&
-                      *ntab->nt_nve.nn_zone == '*' ) ||
-                    (ntab->nt_nve.nn_zonelen == 0))
-                    break;
-
-                /* ntab is default zone */
-                if (zt && (zt->zt_len == ntab->nt_nve.nn_zonelen) &&
-                    (strndiacasecmp(ntab->nt_nve.nn_zone, zt->zt_name,
-                                    zt->zt_len) == 0)) {
-                    break;
-                }
-            }
-
-            /* match particular zone */
-            if ((ntab->nt_nve.nn_zonelen == nn.nn_zonelen) &&
-                (strndiacasecmp( ntab->nt_nve.nn_zone, nn.nn_zone,
-                                 nn.nn_zonelen ) == 0)) {
-                break;
-            }
-        }
-        if ( ntab == NULL ) {
-            nbp_ack( ap->ap_fd, NBPOP_ERROR, (int)nh.nh_id, from );
-            return 0;
-        }
-
-        if ( ntab->nt_next != NULL ) {
-            ntab->nt_next->nt_prev = ntab->nt_prev;
-        }
-        if ( ntab->nt_prev != NULL ) {
-            ntab->nt_prev->nt_next = ntab->nt_next;
-        }
-        if ( ntab == nbptab ) {
-            nbptab = ntab->nt_next;
-        }
-
-        /*
-         * Check for another nbptab entry with the same zone.  If
-         * there isn't one, find the ziptab entry for the zone and
-         * remove the multicast address from the appropriate interfaces.
-         * XXX
-         */
-
-        nbp_ack( ap->ap_fd, NBPOP_OK, (int)nh.nh_id, from );
-        break;
-
-    case NBPOP_BRRQ :
-        /*
-         * Couple of things:  1. Unless we have the -t flag (which is sort
-         * of a misnomer, since you need it if you're doing any phase 1
-         * work), always send NBPOP_FWD.  2. If we get a zone of '*',
-         * and we know what the sender meant by '*', we copy the real
-         * zone into the packet.
-         */
-        if ( nn.nn_zonelen == 0 ||
-             ( nn.nn_zonelen == 1 && *nn.nn_zone == '*' )) {
-            iface = ap->ap_iface;
-            if ( iface && iface->i_rt->rt_zt ) {
-                zt = (struct ziptab *)iface->i_rt->rt_zt->l_data;
-            } else if ( interfaces->i_next->i_rt->rt_zt ) {
-                zt = (struct ziptab *)interfaces->i_next->i_rt->rt_zt->l_data;
-            } else {
-                zt = NULL;
-            }
-
-            /*
-             * Copy zone into packet.  Note that we're changing len, data, and
-             * nbpop.  Later, we'll use ( data - len ) to mean the beginning
-             * of this packet.
-             */
-            if ( zt ) {
-                memcpy( packet, data - len, len );
-                nbpop = packet + ( len - ( data - nbpop ));
-                data = packet + ( len - ( data - zonep ));
-                *data++ = zt->zt_len;
-                memcpy( data, zt->zt_name, zt->zt_len );
-                data += zt->zt_len;
-                len = data - packet;
-            }
-        } else {
-            for ( zt = ziptab; zt; zt = zt->zt_next ) {
-                if ( zt->zt_len == nn.nn_zonelen && strndiacasecmp( zt->zt_name,
-                                                                    nn.nn_zone, zt->zt_len ) == 0 ) {
-                    break;
-                }
-            }
-            if ( zt == NULL ) {
-                nbp_ack( ap->ap_fd, NBPOP_ERROR, (int)nh.nh_id, from );
-                return 0;
-            }
-        }
-
-        /*
-         * If we've got no zones, send out LKUP on the local net.
-         * Otherwise, look through the zone table.
-         */
-        if ( zt == NULL ) {
-#ifdef BSD4_4
-            sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-            sat.sat_family = AF_APPLETALK;
-            sat.sat_port = ap->ap_port;
-
-            nh.nh_op = NBPOP_LKUP;
-            memcpy( nbpop, &nh, SZ_NBPHDR );
-            sat.sat_addr.s_net = 0;         /* XXX */
-            sat.sat_addr.s_node = ATADDR_BCAST;
-
-            /* Find the first non-loopback ap */
-            for ( iface = interfaces; iface; iface = iface->i_next ) {
-                if ((( iface->i_flags & IFACE_LOOPBACK ) == 0) &&
-                    (iface == ap->ap_iface ||
-                     (iface->i_flags & IFACE_ISROUTER))) {
-                    break;
-                }
-            }
-            if ( iface == NULL ) {
-                return 0;
-            }
-            for ( ap = iface->i_ports; ap; ap = ap->ap_next ) {
-                if ( ap->ap_packet == nbp_packet ) {
-                    break;
-                }
-            }
-            if (ap == NULL)
-                return 0;
-
-            if ( sendto( ap->ap_fd, data - len, len, 0, (struct sockaddr *)&sat,
-                         sizeof( struct sockaddr_at )) < 0 ) {
-                LOG(log_error, logtype_atalkd, "nbp brrq sendto: %s", strerror(errno) );
-            }
-
-            locallkup = 1;
-        } else {
-#ifdef BSD4_4
-            sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-            sat.sat_family = AF_APPLETALK;
-            sat.sat_port = ap->ap_port;
-            for ( l = zt->zt_rt; l; l = l->l_next ) {
-                rtmp = (struct rtmptab *)l->l_data;
-
-                if ( rtmp->rt_gate == NULL ) {
-                    for ( iface = interfaces; iface;
-                          iface = iface->i_next ) {
-                        if ( iface->i_rt == rtmp ) {
-                            break;
-                        }
-                    }
-                    if ( !iface ) {
-                        LOG(log_error, logtype_atalkd, "nbp_packet: \
-Can't find route's interface!" );
-                        return -1;
-                    }
-                    ap = iface->i_ports;
-                } else {
-                    ap = rtmp->rt_gate->g_iface->i_ports;
-                }
-                for ( ; ap; ap = ap->ap_next ) {
-                    if ( ap->ap_packet == nbp_packet ) {
-                        break;
-                    }
-                }
-                if ( !ap ) {
-                    LOG(log_error, logtype_atalkd, "nbp_packet: Can't find port!" );
-                    return -1;
-                }
-
-                if ( transition &&
-                     ( rtmp->rt_flags & RTMPTAB_EXTENDED ) == 0 ) {
-                    if ( rtmp->rt_gate == NULL ) {
-                        locallkup = 1;
-                    }
-                    nh.nh_op = NBPOP_LKUP;
-                    memcpy( nbpop, &nh, SZ_NBPHDR );
-                    sat.sat_addr.s_net = rtmp->rt_firstnet;
-                    sat.sat_addr.s_node = ATADDR_BCAST;
-                } else {
-                    if ( rtmp->rt_gate == NULL ) {
-                        nh.nh_op = NBPOP_LKUP;
-                        memcpy( nbpop, &nh, SZ_NBPHDR );
-                        sat.sat_addr.s_net = 0;
-                        sat.sat_addr.s_node = ATADDR_BCAST;
-                        locallkup = 1;
-                    } else {
-                        nh.nh_op = NBPOP_FWD;
-                        memcpy( nbpop, &nh, SZ_NBPHDR );
-                        sat.sat_addr.s_net = rtmp->rt_firstnet;
-                        sat.sat_addr.s_node = 0;
-                    }
-                }
-
-                if ( sendto( ap->ap_fd, data - len, len, 0,
-                             (struct sockaddr *)&sat,
-                             sizeof( struct sockaddr_at )) < 0 ) {
-                    LOG(log_error, logtype_atalkd, "nbp brrq sendto %u.%u: %s",
-                        ntohs( sat.sat_addr.s_net ), sat.sat_addr.s_node,
-                        strerror(errno) );
-                    continue;
-                }
-            }
-        }
-
-        if ( !locallkup ) {
-            break;
-        }
-        /*FALL THROUGH*/
-
-    case NBPOP_FWD :
-        /* send lkup on net. we need to make sure we're a router. */
-        if ( !locallkup && (ap->ap_iface->i_flags & IFACE_ISROUTER)) {
-            nh.nh_op = NBPOP_LKUP;
-            memcpy( nbpop, &nh, SZ_NBPHDR );
-            from->sat_addr.s_net = 0;
-            from->sat_addr.s_node = ATADDR_BCAST;
-            if ( sendto( ap->ap_fd, data - len, len, 0, (struct sockaddr *)from,
-                         sizeof( struct sockaddr_at )) < 0 ) {
-                LOG(log_error, logtype_atalkd, "nbp fwd sendto %u.%u: %s",
-                    ntohs( from->sat_addr.s_net ), from->sat_addr.s_node,
-                    strerror(errno) );
-                return 0;
-            }
-        }
-        /*FALL THROUGH*/
-
-    case NBPOP_LKUP :
-        /* search our data */
-        n = i = 0;
-        data = packet + 1 + SZ_NBPHDR;
-        end = packet + sizeof( packet );
-
-        for ( ntab = nbptab; ntab; ntab = ntab->nt_next ) {
-            /* don't send out entries if we don't want to route. */
-            if ((ap->ap_iface != ntab->nt_iface) &&
-                (ntab->nt_iface->i_flags & IFACE_ISROUTER) == 0) {
-                continue;
-            }
-
-            if ( nn.nn_objlen != 1 || *nn.nn_obj != '=' ) {
-                if ( ntab->nt_nve.nn_objlen != nn.nn_objlen ||
-                     strndiacasecmp( ntab->nt_nve.nn_obj, nn.nn_obj,
-                                     nn.nn_objlen )) {
-                    continue;
-                }
-            }
-
-            if ( nn.nn_typelen != 1 || *nn.nn_type != '=' ) {
-                if ( ntab->nt_nve.nn_typelen != nn.nn_typelen ||
-                     strndiacasecmp( ntab->nt_nve.nn_type, nn.nn_type,
-                                     nn.nn_typelen )) {
-                    continue;
-                }
-            }
-
-            if ( nn.nn_zonelen != 0 &&
-                 ( nn.nn_zonelen != 1 || *nn.nn_zone != '*' )) {
-                if ( ntab->nt_nve.nn_zonelen == 0 ||
-                     ( ntab->nt_nve.nn_zonelen == 1 &&
-                       *ntab->nt_nve.nn_zone == '*' )) {
-                    if ( interfaces->i_next->i_rt->rt_zt ) {
-                        zt = (struct ziptab *)interfaces->i_next->i_rt->
-                            rt_zt->l_data;
-                        if ( zt->zt_len != nn.nn_zonelen ||
-                             strndiacasecmp( zt->zt_name, nn.nn_zone,
-                                             zt->zt_len )) {
-                            continue;
-                        }
-                    }
-                } else {
-                    if ( ntab->nt_nve.nn_zonelen != nn.nn_zonelen ||
-                         strndiacasecmp( ntab->nt_nve.nn_zone, nn.nn_zone,
-                                         nn.nn_zonelen )) {
-                        continue;
-                    }
-                }
-            }
-
-            /*
-             * Another tuple won't fit. Send what we've already
-             * got, and start the next packet.
-             */
-            if ( n > 14 || data + SZ_NBPTUPLE + 3 + ntab->nt_nve.nn_objlen +
-                 ntab->nt_nve.nn_typelen + ntab->nt_nve.nn_zonelen > end ) {
-                nh.nh_op = NBPOP_LKUPREPLY;
-                nh.nh_cnt = n;
-                cc = data - packet;
-                data = packet;
-                *data++ = DDPTYPE_NBP;
-                memcpy( data, &nh, SZ_NBPHDR );
-
-                if ( sendto( ap->ap_fd, packet, cc, 0,
-                             (struct sockaddr *)&nn.nn_sat,
-                             sizeof( struct sockaddr_at )) < 0 ) {
-                    LOG(log_error, logtype_atalkd, "nbp lkup sendto %u.%u: %s",
-                        ntohs( nn.nn_sat.sat_addr.s_net ),
-                        nn.nn_sat.sat_addr.s_node,
-                        strerror(errno) );
-                    return 0;
-                }
-
-                n = 0;
-                data = packet + 1 + SZ_NBPHDR;
-                end = packet + sizeof( packet );
-            }
-
-            nt.nt_net = ntab->nt_nve.nn_sat.sat_addr.s_net;
-            nt.nt_node = ntab->nt_nve.nn_sat.sat_addr.s_node;
-            nt.nt_port = ntab->nt_nve.nn_sat.sat_port;
-            /*
-             * Right now, we'll just give each name a unique enum.  In
-             * the future, we might need to actually assign and save
-             * an enum, based on the associated address.  For the moment,
-             * the enums will be unique and constant, since the order
-             * is fixed.
-             */
-            nt.nt_enum = i++;
-
-            memcpy( data, &nt, SZ_NBPTUPLE );
-            data += SZ_NBPTUPLE;
-
-            *data++ = ntab->nt_nve.nn_objlen;
-            memcpy( data, ntab->nt_nve.nn_obj, ntab->nt_nve.nn_objlen );
-            data += ntab->nt_nve.nn_objlen;
-
-            *data++ = ntab->nt_nve.nn_typelen;
-            memcpy(data, ntab->nt_nve.nn_type, ntab->nt_nve.nn_typelen );
-            data += ntab->nt_nve.nn_typelen;
-
-            /*
-             * Macs won't see something with a zone of 0 length.  We
-             * will always return '*' instead.  Perhaps we should
-             * unconditionally return the real zone?
-             */
-            if ( ntab->nt_nve.nn_zonelen ) {
-                *data++ = ntab->nt_nve.nn_zonelen;
-                memcpy( data, ntab->nt_nve.nn_zone, ntab->nt_nve.nn_zonelen );
-                data += ntab->nt_nve.nn_zonelen;
-            } else {
-                *data++ = 1;
-                *data++ = '*';
-            }
-
-            n++;
-        }
-
-        if ( n != 0 ) {
-            nh.nh_op = NBPOP_LKUPREPLY;
-            nh.nh_cnt = n;
-            cc = data - packet;
-            data = packet;
-            *data++ = DDPTYPE_NBP;
-            memcpy( data, &nh, SZ_NBPHDR );
-
-            if ( sendto( ap->ap_fd, packet, cc, 0,
-                         (struct sockaddr *)&nn.nn_sat,
-                         sizeof( struct sockaddr_at )) < 0 ) {
-                LOG(log_error, logtype_atalkd, "nbp lkup sendto %u.%u: %s",
-                    ntohs( nn.nn_sat.sat_addr.s_net ),
-                    nn.nn_sat.sat_addr.s_node,
-                    strerror(errno) );
-                return 0;
-            }
-        }
-        break;
-
-    default :
-        LOG(log_info, logtype_atalkd, "nbp_packet: bad op (%d)", nh.nh_op );
-        return 1;
-    }
-
-    return 0;
-}
diff --git a/etc/atalkd/nbp.h b/etc/atalkd/nbp.h
deleted file mode 100644 (file)
index 13f511d..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * $Id: nbp.h,v 1.3 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifndef ATALKD_NBP_H
-#define ATALKD_NBP_H 1
-
-struct nbptab {
-    struct nbptab      *nt_prev, *nt_next;
-    struct nbpnve      nt_nve;
-    struct interface    *nt_iface;
-};
-
-extern struct nbptab   *nbptab;
-
-int nbp_packet(struct atport *ap, struct sockaddr_at *from, char *data, int len);
-
-#endif
diff --git a/etc/atalkd/route.c b/etc/atalkd/route.c
deleted file mode 100644 (file)
index 4e7dfac..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * $Id: route.c,v 1.8 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1996 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <string.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <net/route.h>
-#include <sys/ioctl.h>
-#include <netatalk/at.h>
-
-#include "rtmp.h"
-#include "route.h"
-
-#ifndef BSD4_4
-int route( int message, struct sockaddr *dst, struct sockaddr *gate, int flags)
-{
-#ifdef TRU64
-    struct ortentry    rtent;
-#else /* TRU64 */
-    struct rtentry     rtent;
-#endif /* TRU64 */
-
-    memset( &rtent, 0, sizeof( struct rtentry ));
-    rtent.rt_dst = *dst;
-    rtent.rt_gateway = *gate;
-    rtent.rt_flags = flags;
-    return( ioctl( rtfd, message, &rtent ));
-}
-
-#else /* BSD4_4 */
-
-struct sockaddr_m {
-    u_char     sam_len;
-    u_char     sam_family;
-    u_short    sam_pad;
-    u_short    sam_mask;
-    u_short    sam_pad2;
-} mask = { sizeof( struct sockaddr_m ), 0, 0, 0xffff, 0 };
-
-struct rt_msg_at {
-    struct rt_msghdr   rtma_rtm;
-    struct sockaddr_at rtma_dst;
-    struct sockaddr_at rtma_gate;
-    struct sockaddr_m  rtma_mask;
-} rtma;
-
-route( int message, struct sockaddr_at *dst, struct sockaddr_at *gate, int flags)
-{
-    int                        rc;
-
-    memset( &rtma, 0, sizeof( struct rt_msg_at ));
-    rtma.rtma_rtm.rtm_msglen = sizeof( struct rt_msg_at );
-    rtma.rtma_rtm.rtm_version = RTM_VERSION;
-    rtma.rtma_rtm.rtm_type = message;
-    rtma.rtma_rtm.rtm_pid = getpid();
-    rtma.rtma_rtm.rtm_addrs = RTA_DST|RTA_GATEWAY;
-    if ( flags & RTF_HOST ) {
-       rtma.rtma_rtm.rtm_msglen = sizeof( struct rt_msg_at ) -
-               sizeof( struct sockaddr_m );
-    } else {
-       rtma.rtma_rtm.rtm_msglen = sizeof( struct rt_msg_at );
-       rtma.rtma_rtm.rtm_addrs |= RTA_NETMASK;
-       rtma.rtma_mask = mask;
-    }
-
-    rtma.rtma_rtm.rtm_flags = flags;
-    rtma.rtma_dst = *dst;
-    rtma.rtma_gate = *gate;
-    if (( rc = write( rtfd, &rtma, rtma.rtma_rtm.rtm_msglen )) !=
-           rtma.rtma_rtm.rtm_msglen ) {
-       return( -1 );
-    }
-    return( 0 );
-}
-#endif /* BSD4_4 */
diff --git a/etc/atalkd/route.h b/etc/atalkd/route.h
deleted file mode 100644 (file)
index 5f3c0f9..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * $Id: route.h,v 1.3 2009-10-13 22:55:37 didg Exp $
- */
-
-#ifndef ATALKD_ROUTE_H
-#define ATALKD_ROUTE_H 1
-
-#include <sys/cdefs.h>
-
-#ifndef BSD4_4
-int route ( int, struct sockaddr *, struct sockaddr *, int );
-#else /* BSD4_4 */
-int route ( int, struct sockaddr_at *, struct sockaddr_at *, int);
-#endif /* BSD4_4 */
-
-#endif /* ATALKD_ROUTE_H */
diff --git a/etc/atalkd/rtmp.c b/etc/atalkd/rtmp.c
deleted file mode 100644 (file)
index 727562b..0000000
+++ /dev/null
@@ -1,997 +0,0 @@
-/*
- * $Id: rtmp.c,v 1.17 2009-12-08 03:21:16 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <atalk/logger.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/ioctl.h>
-#ifdef TRU64
-#include <sys/mbuf.h>
-#include <net/route.h>
-#endif /* TRU64 */
-#include <net/if.h>
-#include <net/route.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-
-#ifdef __svr4__
-#include <sys/sockio.h>
-#endif /* __svr4__ */
-
-#include <atalk/ddp.h>
-#include <atalk/atp.h>
-#include <atalk/rtmp.h>
-
-#include "interface.h"
-#include "gate.h"
-#include "rtmp.h"
-#include "zip.h"
-#include "list.h"
-#include "atserv.h"
-#include "route.h"
-#include "main.h"
-
-void rtmp_delzonemap(struct rtmptab *rtmp)
-{
-    struct list                *lz, *flz, *lr, *flr;
-    struct ziptab      *zt;
-
-    lz = rtmp->rt_zt;
-    while ( lz ) {                                     /* for each zone */
-       zt = (struct ziptab *)lz->l_data;
-       lr = zt->zt_rt;
-       while ( lr ) {                                  /* for each route */
-           if ( (struct rtmptab *)lr->l_data == rtmp ) {
-               if ( lr->l_prev == NULL ) {             /* head */
-                   if ( lr->l_next == NULL ) {         /* last route in zone */
-                       if ( zt->zt_prev == NULL ) {
-                           ziptab = zt->zt_next;
-                       } else {
-                           zt->zt_prev->zt_next = zt->zt_next;
-                       }
-                       if ( zt->zt_next == NULL ) {
-                           ziplast = zt->zt_prev;
-                       } else {
-                           zt->zt_next->zt_prev = zt->zt_prev;
-                       }
-                       free( zt->zt_bcast );
-                       free( zt->zt_name );
-                       free( zt );
-                   } else {
-                       zt->zt_rt = lr->l_next;
-                   }
-               } else {
-                   lr->l_prev->l_next = lr->l_next;
-               }
-               if ( lr->l_next != NULL ) {
-                   lr->l_next->l_prev = lr->l_prev;
-               }
-               flr = lr;
-               lr = lr->l_next;
-               free( flr );
-           } else {
-               lr = lr->l_next;
-           }
-       }
-       flz = lz;
-       lz = lz->l_next;
-       free( flz );
-    }
-    rtmp->rt_zt = NULL;
-}
-
-
-/*
- * Complete configuration for phase 1 interface using RTMP information.
- */
-static int rtmp_config( struct rtmp_head *rh, struct interface *iface)
-{
-    extern int         stabletimer;
-    int cc;
-
-    /*
-     * If we're configuring a phase 2 interface, don't complete
-     * configuration with RTMP.
-     */
-    if ( iface->i_flags & IFACE_PHASE2 ) {
-       LOG(log_info, logtype_atalkd, "rtmp_config ignoring data" );
-       return 0;
-    }
-
-    /*
-     * Check our seed information, and reconfigure.
-     */
-    if ( rh->rh_net != iface->i_addr.sat_addr.s_net ) {
-       if (( iface->i_flags & IFACE_SEED ) &&
-               rh->rh_net != iface->i_caddr.sat_addr.s_net) {
-           LOG(log_error, logtype_atalkd, "rtmp_config net mismatch %u != %u",
-                   ntohs( rh->rh_net ),
-                   ntohs( iface->i_addr.sat_addr.s_net ));
-           return 1;
-       }
-       iface->i_addr.sat_addr.s_net = rh->rh_net;
-
-       /*
-        * It is possible that we will corrupt our route database
-        * by just forcing this change.  XXX
-        */
-       iface->i_rt->rt_firstnet = iface->i_rt->rt_lastnet = rh->rh_net;
-
-       setaddr( iface, IFACE_PHASE1, iface->i_addr.sat_addr.s_net,
-               iface->i_addr.sat_addr.s_node, rh->rh_net, rh->rh_net );
-       stabletimer = UNSTABLE;
-    }
-
-    /* add addr to loopback route */
-    if ((cc = looproute( iface, RTMP_ADD )) < 0 )
-      return -1;
-
-    if (cc) {
-       LOG(log_error, logtype_atalkd, "rtmp_config: can't route %u.%u to loopback: %s",
-               ntohs( iface->i_addr.sat_addr.s_net ),
-               iface->i_addr.sat_addr.s_node,
-               strerror(errno) );
-    }
-
-    LOG(log_info, logtype_atalkd, "rtmp_config configured %s", iface->i_name );
-    iface->i_flags |= IFACE_CONFIG;
-    if ( iface == ciface ) {
-       ciface = ciface->i_next;
-       bootaddr( ciface );
-    }
-
-    return 0;
-}
-
-/*
- * Delete rtmp from the per-interface in-use table, remove all
- * zone references, and remove the route from the kernel.
- */
-static void rtmp_delinuse(struct rtmptab *rtmp)
-{
-    struct rtmptab     *irt;
-
-    irt = rtmp->rt_gate->g_iface->i_rt;
-    if ( irt->rt_inext == rtmp ) {                     /* first */
-       if ( rtmp->rt_iprev == rtmp ) {                 /* only */
-           irt->rt_inext = NULL;
-       } else {
-           irt->rt_inext = rtmp->rt_inext;
-           rtmp->rt_inext->rt_iprev = rtmp->rt_iprev;
-       }
-    } else {
-       if ( rtmp->rt_inext == NULL ) {                 /* last */
-           rtmp->rt_iprev->rt_inext = NULL;
-           irt->rt_inext->rt_iprev = rtmp->rt_iprev;
-       } else {
-           rtmp->rt_iprev->rt_inext = rtmp->rt_inext;
-           rtmp->rt_inext->rt_iprev = rtmp->rt_iprev;
-       }
-    }
-    rtmp->rt_iprev = NULL;
-    rtmp->rt_inext = NULL;
-
-    /* remove zone map */
-    rtmp_delzonemap(rtmp);
-
-    /* remove old route */
-    gateroute( RTMP_DEL, rtmp );
-}
-
-/*
- * Add rtmp to the per-interface in-use table.  No verification is done...
- */
-static void rtmp_addinuse( struct rtmptab *rtmp)
-{
-    struct rtmptab     *irt;
-
-    gateroute( RTMP_ADD, rtmp );
-
-    irt = rtmp->rt_gate->g_iface->i_rt;
-    if ( irt->rt_inext == NULL ) {     /* empty list */
-       rtmp->rt_inext = NULL;
-       rtmp->rt_iprev = rtmp;
-       irt->rt_inext = rtmp;
-    } else {
-       rtmp->rt_inext = irt->rt_inext;
-       rtmp->rt_iprev = irt->rt_inext->rt_iprev;
-       irt->rt_inext->rt_iprev = rtmp;
-       irt->rt_inext = rtmp;
-    }
-}
-
-
-/*
- * Change the zone mapping to replace "from" with "to".  This code assumes
- * the consistency of both the route -> zone map and the zone -> route map.
- * This is probably a bad idea.  How can we insure that the data is good
- * at this point?  What do we do if we get several copies of a route in
- * an RTMP packet?
- */
-static int rtmp_copyzones( struct rtmptab *to,struct rtmptab *from)
-{
-    struct list                *lz, *lr;
-
-    to->rt_zt = from->rt_zt;
-    from->rt_zt = NULL;
-    if ( from->rt_flags & RTMPTAB_HASZONES ) {
-       to->rt_flags |= RTMPTAB_HASZONES;
-    }
-    for ( lz = to->rt_zt; lz; lz = lz->l_next ) {
-       for ( lr = ((struct ziptab *)lz->l_data)->zt_rt; lr; lr = lr->l_next ) {
-           if ( (struct rtmptab *)lr->l_data == from ) {
-               lr->l_data = (void *)to;        /* cast BS */
-               break;
-           }
-       }
-       if ( lr == NULL ) {
-           LOG(log_error, logtype_atalkd, "rtmp_copyzones z -> r without r -> z, abort" );
-           return -1;
-       }
-    }
-
-    return 0;
-}
-
-
-/*
- * Remove rtmp from the in-use table and the per-gate table.
- * Free any associated space.
- */
-void rtmp_free( struct rtmptab *rtmp)
-{
-    struct gate                *gate;
-
-    LOG(log_info, logtype_atalkd, "rtmp_free: %u-%u", ntohs(rtmp->rt_firstnet),
-          ntohs(rtmp->rt_lastnet));
-    if ( rtmp->rt_iprev ) {
-       rtmp_delinuse( rtmp );
-    }
-
-    /* remove from per-gate */
-    gate = rtmp->rt_gate;
-    if ( gate->g_rt == rtmp ) {                                /* first */
-       if ( rtmp->rt_prev == rtmp ) {                  /* only */
-           gate->g_rt = NULL;
-       } else {
-           gate->g_rt = rtmp->rt_next;
-           rtmp->rt_next->rt_prev = rtmp->rt_prev;
-       }
-    } else {
-       if ( rtmp->rt_next == NULL ) {                  /* last */
-           rtmp->rt_prev->rt_next = NULL;
-           gate->g_rt->rt_prev = rtmp->rt_prev;
-       } else {
-           rtmp->rt_prev->rt_next = rtmp->rt_next;
-           rtmp->rt_next->rt_prev = rtmp->rt_prev;
-       }
-    }
-
-    free( rtmp );
-}
-
-
-/*
- * Find a replacement for "replace".  If we can't find a replacement,
- * return 1.  If we do find a replacement, return 0. -1 on error.
- */
-int rtmp_replace(struct rtmptab *replace)
-{
-    struct interface   *iface;
-    struct gate                *gate;
-    struct rtmptab     *rtmp, *found = NULL;
-
-    LOG(log_info, logtype_atalkd, "rtmp_replace %u-%u", ntohs(replace->rt_firstnet),
-          ntohs(replace->rt_lastnet));
-    for ( iface = interfaces; iface; iface = iface->i_next ) {
-        if ((replace->rt_iface != iface) && 
-           ((iface->i_flags & IFACE_ISROUTER) == 0))
-         continue;
-
-       for ( gate = iface->i_gate; gate; gate = gate->g_next ) {
-           for ( rtmp = gate->g_rt; rtmp; rtmp = rtmp->rt_next ) {
-               if ( rtmp->rt_firstnet == replace->rt_firstnet &&
-                       rtmp->rt_lastnet == replace->rt_lastnet ) {
-                   if ( found == NULL || rtmp->rt_hops < found->rt_hops ) {
-                       found = rtmp;
-                   }
-                   break;
-               }
-           }
-       }
-    }
-
-    if ( found != replace ) {
-       if (rtmp_copyzones( found, replace ) < 0)
-         return -1;
-       rtmp_delinuse( replace );
-       rtmp_addinuse( found );
-       if ( replace->rt_state == RTMPTAB_BAD ) {
-           rtmp_free( replace );
-       }
-       return( 0 );
-    } else {
-       if ( replace->rt_hops == RTMPHOPS_POISON ) {
-           gateroute( RTMP_DEL, replace );
-       }
-       return( 1 );
-    }
-}
-
-
-static int rtmp_new(struct rtmptab *rtmp)
-{
-    struct interface   *i;
-    struct rtmptab     *r;
-    extern int         newrtmpdata;
-
-    newrtmpdata = 1;
-
-    /*
-     * Do we already have a gateway for this route?
-     */
-    for ( i = interfaces; i; i = i->i_next ) {
-        if ((rtmp->rt_iface != i) && 
-           ((i->i_flags & IFACE_ISROUTER) == 0))
-         continue;
-
-       for ( r = i->i_rt; r; r = r->rt_inext ) {
-           /* Should check RTMPTAB_EXTENDED here. XXX */
-           if (( ntohs( r->rt_firstnet ) <= ntohs( rtmp->rt_firstnet ) &&
-                   ntohs( r->rt_lastnet ) >= ntohs( rtmp->rt_firstnet )) ||
-                   ( ntohs( r->rt_firstnet ) <= ntohs( rtmp->rt_lastnet ) &&
-                   ntohs( r->rt_lastnet ) >= ntohs( rtmp->rt_lastnet ))) {
-               break;
-           }
-       }
-       if ( r ) {
-           break;
-       }
-    }
-
-    /*
-     * This part of this routine is almost never run.
-     */
-    if ( i ) { /* can we get here without r being set? */
-       if ( r->rt_firstnet != rtmp->rt_firstnet ||
-               r->rt_lastnet != rtmp->rt_lastnet ) {
-           LOG(log_info, logtype_atalkd, "rtmp_new netrange mismatch %u-%u != %u-%u",
-                   ntohs( r->rt_firstnet ), ntohs( r->rt_lastnet ),
-                   ntohs( rtmp->rt_firstnet ), ntohs( rtmp->rt_lastnet ));
-           return 1;
-       }
-
-       /*
-        * Note that our whole methodology is wrong, if we want to do
-        * route "load balancing."  This entails changing our route
-        * each time we receive a tuple of equal value.  In fact, we can't
-        * do this, using our method, since we only check against in-use
-        * routes when a tuple is new from a router.
-        */
-       if ( r->rt_hops < rtmp->rt_hops ) {
-           return 1;
-       }
-
-       if (rtmp_copyzones( rtmp, r ) < 0)
-         return -1;
-       rtmp_delinuse( r );
-    }
-
-    rtmp_addinuse( rtmp );
-    return 0;
-}
-
-
-int rtmp_packet(struct atport *ap, struct sockaddr_at *from, char *data, int len)
-{
-    struct rtmp_head   rh;
-    struct rtmp_tuple  rt, xrt;
-    struct gate                *gate;
-    struct interface   *iface;
-    struct interface   *iface2;
-    struct rtmptab     *rtmp;
-    char               *end, packet[ ATP_BUFSIZ ];
-    int                 cc;
-
-    end = data + len;
-
-    if ( data >= end ) {
-       LOG(log_info, logtype_atalkd, "rtmp_packet no data" );
-       return 1;
-    }
-
-    iface = ap->ap_iface;
-
-    /* linux 2.6 sends broadcast queries to the first available socket 
-       (in our case the last configured) 
-       try to find the right one.
-       Note: now a misconfigured or plugged router can broadcast
-       a wrong route
-    */
-    for ( iface2 = interfaces; iface2; iface2 = iface2->i_next ) {
-        if ( iface2->i_rt && from->sat_addr.s_net >= iface2->i_rt->rt_firstnet && 
-                from->sat_addr.s_net <= iface2->i_rt->rt_lastnet) 
-        {
-              iface = iface2;
-        }
-    }
-    /* end of linux 2.6 workaround */
-    
-    /* ignore our own packets */
-    if ( from->sat_addr.s_net == iface->i_addr.sat_addr.s_net &&
-           from->sat_addr.s_node == iface->i_addr.sat_addr.s_node  ) {
-       return 0;
-    }
-
-    switch( *data++ ) {
-    case DDPTYPE_RTMPRD :
-       /*
-        * Response and Data.
-        */
-       if ( data + sizeof( struct rtmprdhdr ) > end ) {
-           LOG(log_info, logtype_atalkd, "rtmp_packet no data header" );
-           return 1;
-       }
-       memcpy( &rh, data, sizeof( struct rtmprdhdr ));
-       data += sizeof( struct rtmprdhdr );
-
-       /* check rh address against from address */
-       if ( rh.rh_nodelen != 8 ) {
-           LOG(log_info, logtype_atalkd, "rtmp_packet bad node len (%d)", rh.rh_nodelen );
-           return 1;
-       }
-       if (( from->sat_addr.s_net != 0 && 
-             from->sat_addr.s_net != rh.rh_net ) ||
-             from->sat_addr.s_node != rh.rh_node ) {
-           LOG(log_info, logtype_atalkd, "rtmp_packet address mismatch" );
-           return 1;
-       }
-
-       if (( iface->i_flags & ( IFACE_ADDR|IFACE_CONFIG )) == IFACE_ADDR ) {
-           if ( iface->i_flags & IFACE_NOROUTER ) {
-               /* remove addr to loopback route */
-               if ((cc = looproute( iface, RTMP_DEL )) < 0) {
-                 LOG(log_error, logtype_atalkd, "rtmp_packet: looproute");
-                 return -1;
-               } 
-
-               if (cc)
-                 LOG(log_error, logtype_atalkd, "rtmp_packet: can't remove loopback: %s",
-                         strerror(errno) );
-
-               iface->i_flags &= ~IFACE_NOROUTER;
-               iface->i_time = 0;
-               LOG(log_info, logtype_atalkd, "rtmp_packet router has become available" );
-           }
-           if ( iface->i_flags & IFACE_PHASE1 ) {
-             if (rtmp_config( &rh, iface ) < 0) {
-                 LOG(log_error, logtype_atalkd, "rtmp_packet: rtmp_config");
-                 return -1;
-             }
-           } else if (zip_getnetinfo( iface ) < 0) {
-             LOG(log_error, logtype_atalkd, "rtmp_packet: zip_getnetinfo");
-             return -1;
-           }
-           return 0;
-       }
-
-       if (( iface->i_flags & IFACE_CONFIG ) == 0 ) {
-           return 0;
-       }
-
-       /*
-        * Parse first tuple.  For phase 2, verify that net is correct.
-        */
-       if ( data + SZ_RTMPTUPLE > end ) {
-           LOG(log_info, logtype_atalkd, "rtmp_packet missing first tuple" );
-           return 1;
-       }
-       memcpy( &rt, data, SZ_RTMPTUPLE );
-       data += SZ_RTMPTUPLE;
-
-       if ( rt.rt_net == 0 ) {
-           if ( rt.rt_dist != 0x82 ) {
-               LOG(log_info, logtype_atalkd, "rtmp_packet bad phase 1 version" );
-               return 1;
-           }
-
-           /*
-            * Grab the next tuple, since we don't want to pass the version
-            * number to the parsing code.  We're assuming that there are
-            * no extended tuples in this packet.
-            */
-           if ( data + SZ_RTMPTUPLE > end ) {
-               LOG(log_info, logtype_atalkd, "rtmp_packet missing second tuple" );
-               return 1;
-           }
-           memcpy( &rt, data, SZ_RTMPTUPLE );
-           data += SZ_RTMPTUPLE;
-       } else if ( rt.rt_dist & 0x80 ) {
-           if ( data + SZ_RTMPTUPLE > end ) {
-               LOG(log_info, logtype_atalkd, "rtmp_packet missing first range-end" );
-               return 1;
-           }
-           memcpy( &xrt, data, SZ_RTMPTUPLE );
-           data += SZ_RTMPTUPLE;
-
-           if ( xrt.rt_dist != 0x82 ) {
-               LOG(log_info, logtype_atalkd, "rtmp_packet bad phase 2 version" );
-               return 1;
-           }
-
-           /*
-            * Check for net range conflict.
-            */
-           if ( rt.rt_net != iface->i_rt->rt_firstnet ||
-                   xrt.rt_net != iface->i_rt->rt_lastnet ) {
-               LOG(log_info, logtype_atalkd, "rtmp_packet interface mismatch" );
-               return 1;
-           }
-       } else {
-#ifdef PHASE1NET
-           /*
-            * Gatorboxes put a net number in the first tuple, even on
-            * phase 1 nets.  This is wrong, but since we've got it, we
-            * might just as well check it.
-           if ( rt.rt_net != iface->i_rt->rt_firstnet ||
-                   rt.rt_net != iface->i_rt->rt_lastnet ) {
-               LOG(log_info, logtype_atalkd, "rtmp_packet phase 1 interface mismatch" );
-               return 1;
-           }
-            */
-#else /* PHASE1NET */
-           LOG(log_info, logtype_atalkd, "rtmp_packet bad first tuple" );
-           return 1;
-#endif /* PHASE1NET */
-       }
-
-       /*
-        * Find gateway.
-        */
-       for ( gate = iface->i_gate; gate; gate = gate->g_next ) {
-           if ( gate->g_sat.sat_addr.s_net == from->sat_addr.s_net &&
-                   gate->g_sat.sat_addr.s_node == from->sat_addr.s_node ) {
-               break;
-           }
-       }
-       if ( !gate ) {  /* new gateway */
-           if (( gate = (struct gate *)malloc( sizeof( struct gate ))) == NULL ) {
-               LOG(log_error, logtype_atalkd, "rtmp_packet: malloc: %s", strerror(errno) );
-               return -1;
-           }
-           gate->g_next = iface->i_gate;
-           gate->g_prev = NULL;
-           gate->g_rt = NULL;
-           gate->g_iface = iface;      /* need this? */
-           gate->g_sat = *from;
-           if ( iface->i_gate ) {
-               iface->i_gate->g_prev = gate;
-           }
-           iface->i_gate = gate;
-           LOG(log_info, logtype_atalkd, "rtmp_packet gateway %u.%u up",
-                   ntohs( gate->g_sat.sat_addr.s_net ),
-                   gate->g_sat.sat_addr.s_node );
-       }
-
-       /*
-        * Reset the timeout on this gateway.  We'll remove the gateway
-        * entry, if the timeout gets to RTMPTAB_BAD.
-        */
-       gate->g_state = RTMPTAB_GOOD;
-
-       /*
-        * Parse remaining tuples.
-        */
-       for (;;) {
-           /*
-            * Is route on this gateway?
-            */
-           for ( rtmp = gate->g_rt; rtmp; rtmp = rtmp->rt_next ) {
-               if ( ntohs( rtmp->rt_firstnet ) <= ntohs( rt.rt_net ) &&
-                       ntohs( rtmp->rt_lastnet ) >= ntohs( rt.rt_net )) {
-                   break;
-               }
-               if (( rt.rt_dist & 0x80 ) &&
-                       ntohs( rtmp->rt_firstnet ) <= ntohs( xrt.rt_net ) &&
-                       ntohs( rtmp->rt_lastnet ) >= ntohs( xrt.rt_net )) {
-                   break;
-               }
-           }
-
-           if ( rtmp ) {       /* found it */
-               /*
-                * Check for range conflicts.  (This is getting a little
-                * ugly.)
-                */
-               if ( rtmp->rt_firstnet != rt.rt_net ) {
-                   LOG(log_info, logtype_atalkd, "rtmp_packet firstnet mismatch %u!=%u",
-                           ntohs( rtmp->rt_firstnet ), ntohs( rt.rt_net ));
-                   return 1;
-               }
-               if ( rt.rt_dist & 0x80 ) {
-                   if (( rtmp->rt_flags & RTMPTAB_EXTENDED ) == 0 ) {
-                       LOG(log_info, logtype_atalkd, "rtmp_packet extended mismatch %u",
-                               ntohs( rtmp->rt_firstnet ));
-                       return 1;
-                   }
-                   if ( rtmp->rt_lastnet != xrt.rt_net ) {
-                       LOG(log_info, logtype_atalkd, "rtmp_packet lastnet mismatch %u!=%u",
-                           ntohs( rtmp->rt_lastnet ), ntohs( xrt.rt_net ));
-                       return 1;
-                   }
-               } else {
-                   if ( rtmp->rt_flags & RTMPTAB_EXTENDED ) {
-                       LOG(log_info, logtype_atalkd, "rtmp_packet !extended mismatch %u",
-                               ntohs( rtmp->rt_firstnet ));
-                       return 1;
-                   }
-                   if ( rtmp->rt_lastnet != rt.rt_net ) {
-                       LOG(log_info, logtype_atalkd, "rtmp_packet lastnet mismatch %u!=%u",
-                           ntohs( rtmp->rt_lastnet ), ntohs( rt.rt_net ));
-                       return 1;
-                   }
-               }
-
-               rtmp->rt_state = RTMPTAB_GOOD;
-
-               /*
-                * Check hop count.  If the count has changed, update
-                * the routing database.
-                */
-               if (( rtmp->rt_hops != ( rt.rt_dist & 0x7f ) + 1 ) &&
-                       ( rtmp->rt_hops != RTMPHOPS_POISON ||
-                       ( rt.rt_dist & 0x7f ) + 1 <= RTMPHOPS_MAX )) {
-                   if ( rtmp->rt_iprev ) {     /* route is in use */
-                       if ( rtmp->rt_hops > ( rt.rt_dist & 0x7f ) + 1 ) {
-                           /*
-                            * If this was POISON, we've deleted it from
-                            * the kernel.  Add it back in.
-                            */
-                           if ( rtmp->rt_hops == RTMPHOPS_POISON ) {
-                               gateroute( RTMP_ADD, rtmp );
-                           }
-                           rtmp->rt_hops = ( rt.rt_dist & 0x7f ) + 1;
-                       } else {
-                           /*
-                            * Hop count has gone up for this route.
-                            * Search for a new best route.  If we can't
-                            * find one, just keep this route.  "poison"
-                            * route are deleted in as_timer().
-                            */
-                           if (( rt.rt_dist & 0x7f ) + 1 > RTMPHOPS_MAX ) {
-                               rtmp->rt_hops = RTMPHOPS_POISON;
-                           } else {
-                               rtmp->rt_hops = ( rt.rt_dist & 0x7f ) + 1;
-                           }
-                           if (rtmp_replace( rtmp ) < 0) {
-                             LOG(log_error, logtype_atalkd, "rtmp_packet: rtmp_replace");
-                             return -1;
-                           }
-                       }
-                   } else {                    /* route not in use */
-                       rtmp->rt_hops = ( rt.rt_dist & 0x7f ) + 1;
-                       if ( rtmp->rt_hops > ( rt.rt_dist & 0x7f ) + 1 ) {
-                         if (rtmp_new( rtmp ) < 0) {
-                             LOG(log_error, logtype_atalkd, "rtmp_packet: rtmp_new");
-                             return -1;
-                         }
-                       }
-                   }
-               }
-
-               /*
-                * Make the *next* node the head, since
-                * we're not likely to be asked for the same tuple twice
-                * in a row.
-                */
-               if ( rtmp->rt_next != NULL ) {
-                   gate->g_rt->rt_prev->rt_next = gate->g_rt;
-                   gate->g_rt = rtmp->rt_next;
-                   rtmp->rt_next = NULL;
-               }
-           } else if (( rt.rt_dist & 0x7f ) + 1 > RTMPHOPS_MAX ) {
-               LOG(log_info, logtype_atalkd, "rtmp_packet bad hop count from %u.%u for %u",
-                       ntohs( from->sat_addr.s_net ), from->sat_addr.s_node,
-                       ntohs( rt.rt_net ));
-           } else {            /* new for router */
-               if (( rtmp = newrt(iface)) == NULL ) {
-                   LOG(log_error, logtype_atalkd, "rtmp_packet: newrt: %s", strerror(errno) );
-                   return -1;
-               }
-               rtmp->rt_firstnet = rt.rt_net;
-               if ( rt.rt_dist & 0x80 ) {
-                   rtmp->rt_lastnet = xrt.rt_net;
-                   rtmp->rt_flags = RTMPTAB_EXTENDED;
-               } else {
-                   rtmp->rt_lastnet = rt.rt_net;
-               }
-               rtmp->rt_hops = ( rt.rt_dist & 0x7f ) + 1;
-               rtmp->rt_state = RTMPTAB_GOOD;
-               rtmp->rt_gate = gate;
-
-               /*
-                * Add rtmptab entry to end of list (leave head alone).
-                */
-               if ( gate->g_rt == NULL ) {
-                   rtmp->rt_prev = rtmp;
-                   gate->g_rt = rtmp;
-               } else {
-                   rtmp->rt_prev = gate->g_rt->rt_prev;
-                   gate->g_rt->rt_prev->rt_next = rtmp;
-                   gate->g_rt->rt_prev = rtmp;
-               }
-               
-               if (rtmp_new( rtmp ) < 0) {
-                   LOG(log_error, logtype_atalkd, "rtmp_packet: rtmp_new");
-                   return -1;
-               }
-           }
-
-           if ( data + SZ_RTMPTUPLE > end ) {
-               break;
-           }
-           memcpy( &rt, data, SZ_RTMPTUPLE );
-           data += SZ_RTMPTUPLE;
-           if ( rt.rt_dist & 0x80 ) {
-               if ( data + SZ_RTMPTUPLE > end ) {
-                   LOG(log_info, logtype_atalkd, "rtmp_packet missing range-end" );
-                   return 1;
-               }
-               memcpy( &xrt, data, SZ_RTMPTUPLE );
-               data += SZ_RTMPTUPLE;
-           }
-       }
-
-       /*
-        * Make sure we've processed the whole packet.
-        */
-       if ( data != end ) {
-           LOG(log_info, logtype_atalkd, "rtmp_packet length and count mismatch" );
-       }
-       break;
-
-    case DDPTYPE_RTMPR :
-       /*
-        * Request and RDR.
-        */
-        if (((iface->i_flags & IFACE_ISROUTER) == 0) ||
-           iface->i_rt->rt_zt == NULL ||
-           ( iface->i_flags & IFACE_CONFIG ) == 0 ) {
-           return 0;
-       }
-       if ( *data == 1 ) {
-           data = packet;
-           *data++ = DDPTYPE_RTMPRD;
-           rh.rh_net = iface->i_addr.sat_addr.s_net;
-           rh.rh_nodelen = 8;
-           rh.rh_node = iface->i_addr.sat_addr.s_node;
-           memcpy( data, &rh, sizeof( struct rtmp_head ));
-           data += sizeof( struct rtmp_head );
-
-           if ( iface->i_flags & IFACE_PHASE2 ) {
-               rt.rt_net = iface->i_rt->rt_firstnet;
-               rt.rt_dist = 0x80;
-               memcpy( data, &rt, SZ_RTMPTUPLE );
-               data += SZ_RTMPTUPLE;
-
-               rt.rt_net = iface->i_rt->rt_lastnet;
-               rt.rt_dist = 0x82;
-               memcpy( data, &rt, SZ_RTMPTUPLE );
-               data += SZ_RTMPTUPLE;
-           }
-           if ( sendto( ap->ap_fd, packet, data - packet, 0,
-                   (struct sockaddr *)from,
-                   sizeof( struct sockaddr_at )) < 0 ) {
-               LOG(log_error, logtype_atalkd, "as_timer sendto: %s", strerror(errno) );
-           }
-       } else if ( *data == 2 || *data == 3 ) {
-#ifdef DEBUG
-           printf( "rtmp_packet rdr (%d) from %u.%u\n",
-                   *data, ntohs( from->sat_addr.s_net ),
-                   from->sat_addr.s_node );
-#endif /* DEBUG */
-       } else {
-           LOG(log_info, logtype_atalkd, "rtmp_packet unknown request from %u.%u",
-                   ntohs( from->sat_addr.s_net ), from->sat_addr.s_node );
-       }
-       break;
-
-    default :
-       LOG(log_info, logtype_atalkd, "rtmp_packet bad ddp type from %u.%u",
-                   ntohs( from->sat_addr.s_net ), from->sat_addr.s_node );
-       return 0;
-    }
-
-    return 0;
-}
-
-int rtmp_request( struct interface *iface)
-{
-    struct sockaddr_at sat;
-    struct atport      *ap;
-    char               *data, packet[ 2 ];
-
-    LOG(log_info, logtype_atalkd, "rtmp_request for %s", iface->i_name );
-
-    for ( ap = iface->i_ports; ap; ap = ap->ap_next ) {
-       if ( ap->ap_packet == rtmp_packet ) {
-           break;
-       }
-    }
-    if ( ap == NULL ) {
-       LOG(log_error, logtype_atalkd, "rtmp_request can't find rtmp socket!" );
-       return -1;
-    }
-
-    data = packet;
-    *data++ = DDPTYPE_RTMPR;
-    *data++ = RTMPROP_REQUEST;
-
-    /*
-     * There is a problem with the net zero "hint" hack.
-     */
-    memset( &sat, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    sat.sat_family = AF_APPLETALK;
-    sat.sat_addr.s_net = iface->i_addr.sat_addr.s_net;
-    sat.sat_addr.s_node = ATADDR_BCAST;
-    sat.sat_port = ap->ap_port;
-    if ( sendto( ap->ap_fd, packet, data - packet, 0, (struct sockaddr *)&sat,
-           sizeof( struct sockaddr_at )) < 0 ) {
-       LOG(log_error, logtype_atalkd, "rtmp_request sendto: %s", strerror(errno) );
-       return -1;
-    }
-    return 0;
-}
-
-
-int looproute(struct interface *iface, unsigned int cmd)
-{
-    struct sockaddr_at dst, loop;
-
-    if ( cmd == RTMP_DEL && ( iface->i_flags & IFACE_LOOP ) == 0 ) {
-       LOG(log_error, logtype_atalkd, "looproute panic no route" );
-       return -1;
-    }
-
-    if ( cmd == RTMP_ADD && ( iface->i_flags & IFACE_LOOP )) {
-       LOG(log_error, logtype_atalkd, "looproute panic two routes" );
-       return -1;
-    }
-
-    memset( &dst, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    dst.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    dst.sat_family = AF_APPLETALK;
-    dst.sat_addr.s_net = iface->i_addr.sat_addr.s_net;
-    dst.sat_addr.s_node = iface->i_addr.sat_addr.s_node;
-    memset( &loop, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    loop.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    loop.sat_family = AF_APPLETALK;
-    loop.sat_addr.s_net = htons( ATADDR_ANYNET );
-    loop.sat_addr.s_node = ATADDR_ANYNODE;
-
-#ifndef BSD4_4
-    if ( route( cmd,
-               (struct sockaddr *) &dst,
-               (struct sockaddr *) &loop,
-               RTF_UP | RTF_HOST ) ) {
-       return( 1 );
-    }
-#else /* ! BSD4_4 */
-    if ( route( cmd,
-               (struct sockaddr_at *) &dst,
-               (struct sockaddr_at *) &loop,
-               RTF_UP | RTF_HOST ) ) {
-       return ( 1);
-    }
-#endif /* BSD4_4 */
-    if ( cmd == RTMP_ADD ) {
-       iface->i_flags |= IFACE_LOOP;
-    }
-    if ( cmd == RTMP_DEL ) {
-       iface->i_flags &= ~IFACE_LOOP;
-    }
-    return( 0 );
-}
-
-int gateroute(unsigned int command, struct rtmptab *rtmp)
-{
-    struct sockaddr_at dst, gate;
-    unsigned short     net;
-
-    if ( command == RTMP_DEL && ( rtmp->rt_flags & RTMPTAB_ROUTE ) == 0 ) {
-       return( -1 );
-    }
-    if ( command == RTMP_ADD && ( rtmp->rt_flags & RTMPTAB_ROUTE )) {
-       return( -1 );
-    }
-
-    net = ntohs( rtmp->rt_firstnet );
-    /*
-     * Since we will accept routes from gateways who advertise their
-     * address as 0.YY, we must munge the gateway address we give to
-     * the kernel.  Otherwise, we'll get a bunch of routes to the loop
-     * back interface, and who wants that?
-     */
-    memset( &gate, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    gate.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    gate.sat_family = AF_APPLETALK;
-    gate.sat_addr.s_net = rtmp->rt_gate->g_sat.sat_addr.s_net;
-    gate.sat_addr.s_node = rtmp->rt_gate->g_sat.sat_addr.s_node;
-    if ( gate.sat_addr.s_net == 0 ) {
-       gate.sat_addr.s_net = net;
-    }
-
-    memset( &dst, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    dst.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    dst.sat_family = AF_APPLETALK;
-    dst.sat_addr.s_node = ATADDR_ANYNODE;
-
-    do {
-       dst.sat_addr.s_net = htons( net );
-#ifndef BSD4_4
-       if ( route( command,
-                   (struct sockaddr *) &dst,
-                   (struct sockaddr *) &gate,
-                   RTF_UP | RTF_GATEWAY )) {
-           LOG(log_error, logtype_atalkd, "route: %u -> %u.%u: %s", net,
-                   ntohs( gate.sat_addr.s_net ), gate.sat_addr.s_node,
-                   strerror(errno) );
-           continue;
-       }
-#else /* ! BSD4_4 */
-       if ( route( command,
-                   (struct sockaddr_at *) &dst,
-                   (struct sockaddr_at *) &gate,
-                   RTF_UP | RTF_GATEWAY )) {
-           LOG(log_error, logtype_atalkd, "route: %u -> %u.%u: %s", net,
-                   ntohs( gate.sat_addr.s_net ), gate.sat_addr.s_node, strerror(errno) );
-           continue;
-       }
-#endif /* ! BSD4_4 */
-    } while ( net++ < ntohs( rtmp->rt_lastnet ));
-
-    if ( command == RTMP_ADD ) {
-       rtmp->rt_flags |= RTMPTAB_ROUTE;
-    }
-    if ( command == RTMP_DEL ) {
-       rtmp->rt_flags &= ~RTMPTAB_ROUTE;
-    }
-
-    return( 0 );
-}
-
-    struct rtmptab *
-newrt(const struct interface *iface)
-{
-    struct rtmptab     *rtmp;
-
-    if (( rtmp = (struct rtmptab *)calloc(1, sizeof(struct rtmptab))) == NULL ) {
-       return( NULL );
-    }
-
-    rtmp->rt_iface = iface;
-    return( rtmp );
-}
diff --git a/etc/atalkd/rtmp.h b/etc/atalkd/rtmp.h
deleted file mode 100644 (file)
index 99e15db..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * $Id: rtmp.h,v 1.5 2009-10-13 22:55:37 didg Exp $
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * We have an rtmptab circular linked list for each gateway.  Entries
- * are inserted in the order we get them.  The expectation is that
- * we will get a complexity of N for the stable case.  If we have N
- * existing entries, and M new entries, we'll have on the order of
- * N + ( M * N ) complexity (really it will be something more than
- * that, maybe N + ( M * ( N + 1/2 M )).  Note that having a list to
- * search is superior to a hash table if you are expecting bad data:
- * you have the opportunity to range-check the incoming data.
- *
- * We keep several ZIP related flags and counters here.  For ZIP Extended
- * Replies, we must keep a flag indicating that the zone is up or down.
- * This flag is necessary for ZIP Extended Replies which cross packet
- * boundaries: even tho the rtmptab entry has data, it is not yet
- * complete.  For ZIP in general, we keep a flag indicating that we've
- * asked for a ZIP (E)Reply.  If this flag is not set, we won't process
- * ZIP Reply data for given rtmptab entries.  Lastly, we keep a count of
- * the number of times we've asked for ZIP Reply data.  When this value
- * reaches some value (3?), we can optionally stop asking.
- */
-
-#ifndef ATALKD_RTMP_H
-#define ATALKD_RTMP_H 1
-
-#include <sys/cdefs.h>
-
-struct rtmptab {
-    struct rtmptab     *rt_next,
-                       *rt_prev;
-    struct rtmptab     *rt_inext,
-                       *rt_iprev;
-    u_short            rt_firstnet, rt_lastnet;
-    u_char             rt_hops;
-    u_char             rt_state;
-    u_char             rt_flags;
-    u_char             rt_nzq;         /* number of zip queries issued */
-    struct gate                *rt_gate;       /* gate is NULL for interfaces */
-    struct list                *rt_zt;
-    const struct interface    *rt_iface;
-};
-
-struct rtmp_head {
-    u_short    rh_net;
-    u_char     rh_nodelen;
-    u_char     rh_node;
-};
-
-struct rtmp_tuple {
-    u_short    rt_net;
-    u_char     rt_dist;
-};
-#define SZ_RTMPTUPLE   3
-
-#define RTMPTAB_PERM   0
-#define RTMPTAB_GOOD   1
-#define RTMPTAB_SUSP1  2
-#define RTMPTAB_SUSP2  3
-#define RTMPTAB_BAD    4
-
-#define RTMPTAB_ZIPQUERY       0x01
-#define RTMPTAB_HASZONES       0x02
-#define RTMPTAB_EXTENDED       0x04
-#define RTMPTAB_ROUTE          0x08
-
-#ifndef BSD4_4
-#define RTMP_ADD       SIOCADDRT
-#define RTMP_DEL       SIOCDELRT
-#else /* BSD4_4 */
-#define RTMP_ADD       RTM_ADD
-#define RTMP_DEL       RTM_DELETE
-#endif /* BSD4_4 */
-
-#define STARTUP_FIRSTNET       0xff00
-#define STARTUP_LASTNET                0xfffe
-
-extern int     rtfd;
-struct rtmptab *newrt (const struct interface *);
-void rtmp_delzonemap  (struct rtmptab *);
-
-int rtmp_request ( struct interface * );
-void rtmp_free ( struct rtmptab * );
-int rtmp_replace ( struct rtmptab * );
-int looproute ( struct interface *, unsigned int );
-int gateroute ( unsigned int, struct rtmptab * );
-
-struct atport;
-
-int rtmp_packet(struct atport *ap, struct sockaddr_at *from, char *data, int len);
-
-#endif /* atalkd/rtmp.h */
diff --git a/etc/atalkd/zip.c b/etc/atalkd/zip.c
deleted file mode 100644 (file)
index 23d8188..0000000
+++ /dev/null
@@ -1,1055 +0,0 @@
-/*
- * $Id: zip.c,v 1.15 2009-12-13 00:31:50 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <atalk/logger.h>
-#include <sys/socket.h>
-#include <sys/ioctl.h>
-#include <sys/time.h>
-#ifdef TRU64
-#include <sys/mbuf.h>
-#include <net/route.h>
-#endif /* TRU64 */
-#include <net/if.h>
-#include <net/route.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-
-#ifdef __svr4__
-#include <sys/sockio.h>
-#endif /* __svr4__ */
-
-#include <atalk/ddp.h>
-#include <atalk/zip.h>
-#include <atalk/atp.h>
-#include <atalk/util.h>
-
-#include "atserv.h"
-#include "interface.h"
-#include "gate.h"
-#include "zip.h"
-#include "rtmp.h"
-#include "list.h"
-#include "multicast.h"
-#include "main.h"
-
-struct ziptab  *ziptab = NULL, *ziplast = NULL;
-
-
-static int zonecheck(struct rtmptab *rtmp, struct interface *iface)
-{
-    struct list                *l;
-    struct ziptab      *czt, *zt;
-    int                        cztcnt, ztcnt;
-
-    if (( iface->i_flags & IFACE_SEED ) == 0 ) {
-       return( 0 );
-    }
-
-    for ( cztcnt = 0, czt = iface->i_czt; czt; czt = czt->zt_next, cztcnt++ ) {
-       for ( l = rtmp->rt_zt; l; l = l->l_next ) {
-           zt = (struct ziptab *)l->l_data;
-           if ( czt->zt_len == zt->zt_len &&
-                   !strndiacasecmp( czt->zt_name, zt->zt_name, czt->zt_len )) {
-               break;
-           }
-       }
-       if ( l == NULL ) {
-           LOG(log_error, logtype_atalkd, "zonecheck: %.*s not in zone list", czt->zt_len,
-                   czt->zt_name );
-           return( -1 );       /* configured zone not found in net zones */
-       }
-    }
-
-    for ( ztcnt = 0, l = rtmp->rt_zt; l; l = l->l_next, ztcnt++ )
-       ;
-
-    if ( cztcnt != ztcnt ) {
-       LOG(log_error, logtype_atalkd, "zonecheck: %d configured zones, %d zones found",
-               cztcnt, ztcnt );
-       return( -1 );           /* more net zones than configured zones */
-    }
-
-    return( 0 );
-}
-
-
-int zip_packet(struct atport *ap,struct sockaddr_at *from, char *data, int len)
-{
-    struct ziphdr      zh;
-    struct atphdr      ah;
-    struct interface   *iface;
-    struct gate                *gate;
-    struct rtmptab     *rtmp = NULL;
-    struct list                *l;
-    struct ziptab      *zt;
-    u_short            firstnet, lastnet, index, nz;
-    char               *end, zname[ 32 ], packet[ ATP_BUFSIZ ], *nzones, *lastflag;
-    char               *reply, *rend, *ziphdr;
-    int                        zlen, n, zipop, rcnt, qcnt, zcnt, zsz;
-    extern int         stabletimer;
-
-    end = data + len;
-
-    if ( data >= end ) {
-       LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-       return 1;
-    }
-
-    /* get interface */
-    iface = ap->ap_iface;
-
-    switch( *data++ ) {
-    case DDPTYPE_ZIP :
-       if ( data + sizeof( struct ziphdr ) > end ) {
-           LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-           return 1;
-       }
-       memcpy( &zh, data, sizeof( struct ziphdr ));
-       data += sizeof( struct ziphdr );
-
-       switch ( zh.zh_op ) {
-       case ZIPOP_QUERY :
-           /* set up reply */
-           reply = packet;
-           rend = packet + sizeof( packet );
-           *reply++ = DDPTYPE_ZIP;
-           ziphdr = reply;
-           reply += 2;
-           rcnt = 0;
-
-           qcnt = zh.zh_count;
-
-           while ( data + sizeof( u_short ) <= end && qcnt-- > 0 ) {
-               memcpy( &firstnet, data, sizeof( u_short ));
-               data += sizeof( u_short );
-
-               /*
-                * Look for the given network number (firstnet).
-                * Perhaps we could do better than brute force?
-                */
-               for ( iface = interfaces; iface; iface = iface->i_next ) {
-                   for ( rtmp = iface->i_rt; rtmp; rtmp = rtmp->rt_inext ) {
-                       if ( firstnet == rtmp->rt_firstnet ) {
-                           break;
-                       }
-                   }
-                   if ( rtmp ) {
-                       break;
-                   }
-               }
-               if ( rtmp == NULL ) {
-                   continue;
-               }
-
-               /*
-                * Count the number of zones in this list, and the
-                * number of byte it will consume in a reply.
-                */
-               for ( zsz = 0, zcnt = 0, l = rtmp->rt_zt; l; l = l->l_next ) {
-                   zcnt++;
-                   zt = (struct ziptab *)l->l_data;
-                   zsz += sizeof( u_short ) + 1 + zt->zt_len;
-               }
-
-               /*
-                * We might send this list in the current reply, as the
-                * first thing in the next reply, or as an extended packet.
-                */
-               if ( reply + zsz > rend ) {
-                   if ( rcnt > 0 ) {
-                       zh.zh_op = ZIPOP_REPLY;
-                       zh.zh_cnt = rcnt;
-                       memcpy( ziphdr, &zh, sizeof( struct ziphdr ));
-                       if ( sendto( ap->ap_fd, packet, reply - packet, 0,
-                               (struct sockaddr *)from,
-                               sizeof( struct sockaddr_at )) < 0 ) {
-                           LOG(log_error, logtype_atalkd, "zip reply sendto: %s",
-                                   strerror(errno) );
-                       }
-
-                       reply = packet + 3;
-                       rcnt = 0;
-                   }
-
-                   if ( reply + zsz > rend ) {
-                       /* ereply */
-                       for ( l = rtmp->rt_zt; l; l = l->l_next, rcnt++ ) {
-                           zt = (struct ziptab *)l->l_data;
-                           if ( reply + sizeof( u_short ) + 1 + zt->zt_len >
-                                   rend ) {
-                               zh.zh_op = ZIPOP_EREPLY;
-                               zh.zh_cnt = zcnt;
-                               memcpy( ziphdr, &zh, sizeof( struct ziphdr ));
-                               if ( sendto( ap->ap_fd, packet, reply - packet,
-                                       0, (struct sockaddr *)from,
-                                       sizeof( struct sockaddr_at )) < 0 ) {
-                                   LOG(log_error, logtype_atalkd, "zip reply sendto: %s",
-                                           strerror(errno) );
-                               }
-
-                               reply = packet + 3;
-                               rcnt = 0;
-                           }
-
-                           memcpy( reply, &firstnet, sizeof( u_short ));
-                           reply += sizeof( u_short );
-                           *reply++ = zt->zt_len;
-                           memcpy( reply, zt->zt_name, zt->zt_len );
-                           reply += zt->zt_len;
-                       }
-
-                       if ( rcnt > 0 ) {
-                           zh.zh_op = ZIPOP_EREPLY;
-                           zh.zh_cnt = zcnt;
-                           memcpy( ziphdr, &zh, sizeof( struct ziphdr ));
-                           if ( sendto( ap->ap_fd, packet, reply - packet, 0,
-                                   (struct sockaddr *)from,
-                                   sizeof( struct sockaddr_at )) < 0 ) {
-                               LOG(log_error, logtype_atalkd, "zip reply sendto: %s",
-                                       strerror(errno) );
-                           }
-
-                           reply = packet + 3;
-                           rcnt = 0;
-                       }
-                       continue;
-                   }
-               }
-
-               for ( l = rtmp->rt_zt; l; l = l->l_next, rcnt++ ) {
-                   zt = (struct ziptab *)l->l_data;
-                   memcpy( reply, &firstnet, sizeof( u_short ));
-                   reply += sizeof( u_short );
-                   *reply++ = zt->zt_len;
-                   memcpy( reply, zt->zt_name, zt->zt_len );
-                   reply += zt->zt_len;
-               }
-           }
-
-           if ( rcnt > 0 ) {
-               zh.zh_op = ZIPOP_REPLY;
-               zh.zh_cnt = rcnt;
-               memcpy( ziphdr, &zh, sizeof( struct ziphdr ));
-               if ( sendto( ap->ap_fd, packet, reply - packet, 0,
-                       (struct sockaddr *)from,
-                       sizeof( struct sockaddr_at )) < 0 ) {
-                   LOG(log_error, logtype_atalkd, "zip reply sendto: %s",
-                           strerror(errno) );
-               }
-           }
-           break;
-
-       case ZIPOP_REPLY :
-           for ( gate = iface->i_gate; gate; gate = gate->g_next ) {
-               if (( from->sat_addr.s_net == 0 ||
-                       gate->g_sat.sat_addr.s_net == from->sat_addr.s_net ) &&
-                       gate->g_sat.sat_addr.s_node == from->sat_addr.s_node ) {
-                   break;
-               }
-           }
-           if ( gate == NULL ) {
-               LOG(log_info, logtype_atalkd, "zip reply from non-gateway %u.%u", 
-                   ntohs( from->sat_addr.s_net ), from->sat_addr.s_node );
-               return 1;
-           }
-
-           rtmp = NULL;
-
-           do {
-               if ( data + sizeof( u_short ) + 1 > end ) {     /* + strlen */
-                   LOG(log_info, logtype_atalkd, "zip reply short (%d)", len );
-                   return 1;
-               }
-               memcpy( &firstnet, data, sizeof( u_short ));
-               data += sizeof( u_short );
-
-               if ( rtmp && rtmp->rt_firstnet != firstnet ) {
-                   /* XXX */
-                   if ( rtmp->rt_gate == NULL &&
-                           zonecheck( rtmp, gate->g_iface ) != 0 ) {
-                       LOG(log_error, logtype_atalkd, "zip_packet seed zonelist mismatch" );
-                       return -1;
-                   }
-                   rtmp->rt_flags &= ~RTMPTAB_ZIPQUERY;
-               }
-
-               /* Check if this is the interface's route. */
-               if ( firstnet == gate->g_iface->i_rt->rt_firstnet ) {
-                   rtmp = gate->g_iface->i_rt;
-               } else {
-                   for ( rtmp = gate->g_rt; rtmp; rtmp = rtmp->rt_next ) {
-                       if ( rtmp->rt_firstnet == firstnet ) {
-                           break;
-                       }
-                   }
-
-                   /*
-                    * Update head to this rtmp entry.
-                    */
-                   if ( rtmp != NULL && gate->g_rt != rtmp ) {
-                       gate->g_rt->rt_prev->rt_next = gate->g_rt;
-                       gate->g_rt = rtmp;
-                       rtmp->rt_prev->rt_next = NULL;
-                   }
-               }
-
-               zlen = *data++;
-               if ( zlen > 32 || zlen <= 0 ) {
-                   LOG(log_info, logtype_atalkd, "zip reply bad packet" );
-                   return 1;
-               }
-               if ( data + zlen > end ) {
-                   LOG(log_info, logtype_atalkd, "zip reply short (%d)", len );
-                   return 1;
-               }
-               memcpy( zname, data, zlen );
-               data += zlen;
-
-               /*
-                * We won't find any rtmp entry if the gateway is no longer
-                * telling us about the entry.
-                */
-               if ( rtmp == NULL ) {
-                   LOG(log_info, logtype_atalkd, "zip skip reply %u from %u.%u (no rtmp)",
-                           ntohs( firstnet ), ntohs( from->sat_addr.s_net ),
-                           from->sat_addr.s_node );
-               /*
-                * Check if the route is still in use (the iprev check is
-                * no good if rtmp is the interface's route).
-                */
-               } else if ( rtmp->rt_iprev == NULL && rtmp->rt_prev != NULL ) {
-                   LOG(log_info, logtype_atalkd,
-                           "zip skip reply %u-%u from %u.%u (rtmp not in use)",
-                           ntohs( rtmp->rt_firstnet ),
-                           ntohs( rtmp->rt_lastnet ),
-                           ntohs( from->sat_addr.s_net ),
-                           from->sat_addr.s_node );
-               /*
-                * Check if we've got an outstanding query for this route.
-                * We will often get this, since we ask every router on a
-                * net to verify our interface's zone(s).
-                */
-               } else if (( rtmp->rt_flags & RTMPTAB_ZIPQUERY ) == 0 ) {
-                   LOG(log_info, logtype_atalkd,
-                           "zip skip reply %u-%u from %u.%u (no query)",
-                           ntohs( rtmp->rt_firstnet ),
-                           ntohs( rtmp->rt_lastnet ),
-                           ntohs( from->sat_addr.s_net ),
-                           from->sat_addr.s_node );
-               } else {
-                   if (addzone( rtmp, zlen, zname ) < 0) {
-                       LOG(log_error, logtype_atalkd, "zip_packet: addzone");
-                       return -1;
-                   }
-                   rtmp->rt_flags |= RTMPTAB_HASZONES;
-               }
-           } while ( data < end );
-
-           if ( rtmp && rtmp->rt_flags & RTMPTAB_HASZONES ) {
-               /* XXX */
-               if ( rtmp->rt_gate == NULL &&
-                       zonecheck( rtmp, gate->g_iface ) != 0 ) {
-                   LOG(log_error, logtype_atalkd, "zip_packet seed zonelist mismatch" );
-                   return -1;
-               }
-               rtmp->rt_flags &= ~RTMPTAB_ZIPQUERY;
-           }
-           break;
-
-       case ZIPOP_EREPLY :
-           for ( gate = iface->i_gate; gate; gate = gate->g_next ) {
-               if (( from->sat_addr.s_net == 0 ||
-                       gate->g_sat.sat_addr.s_net == from->sat_addr.s_net ) &&
-                       gate->g_sat.sat_addr.s_node == from->sat_addr.s_node ) {
-                   break;
-               }
-           }
-           if ( gate == NULL ) {
-               LOG(log_info, logtype_atalkd, "zip ereply from non-gateway %u.%u", 
-                   ntohs( from->sat_addr.s_net ), from->sat_addr.s_node );
-               return 1;
-           }
-
-           /*
-            * Note that we're not advancing "data" here.  We do that
-            * at the top of the do-while loop, below.
-            */
-           if ( data + sizeof( u_short ) + 1 > end ) { /* + strlen */
-               LOG(log_info, logtype_atalkd, "zip ereply short (%d)", len );
-               return 1;
-           }
-           memcpy( &firstnet, data, sizeof( u_short ));
-
-           /* Check if this is the interface's route. */
-           if ( firstnet == gate->g_iface->i_rt->rt_firstnet ) {
-               rtmp = gate->g_iface->i_rt;
-           } else {
-               for ( rtmp = gate->g_rt; rtmp; rtmp = rtmp->rt_next ) {
-                   if ( rtmp->rt_firstnet == firstnet ) {
-                       break;
-                   }
-               }
-               if ( rtmp == NULL ) {
-                   LOG(log_info, logtype_atalkd, "zip ereply %u from %u.%u (no rtmp)",
-                           ntohs( firstnet ), ntohs( from->sat_addr.s_net ),
-                           from->sat_addr.s_node );
-                   return 1;
-               }
-               if ( rtmp->rt_iprev == NULL ) {
-                   LOG(log_info, logtype_atalkd,
-                           "zip ereply %u-%u from %u.%u (rtmp not in use)",
-                           ntohs( rtmp->rt_firstnet ),
-                           ntohs( rtmp->rt_lastnet ),
-                           ntohs( from->sat_addr.s_net ),
-                           from->sat_addr.s_node );
-               }
-
-               /* update head to *next* rtmp entry */
-               if ( rtmp->rt_next != NULL ) {
-                   gate->g_rt->rt_prev->rt_next = gate->g_rt;
-                   gate->g_rt = rtmp->rt_next;
-                   rtmp->rt_next = NULL;
-               }
-           }
-
-           if (( rtmp->rt_flags & RTMPTAB_ZIPQUERY ) == 0 ) {
-               LOG(log_info, logtype_atalkd, "zip ereply %u-%u from %u.%u (no query)",
-                       ntohs( rtmp->rt_firstnet ),
-                       ntohs( rtmp->rt_lastnet ),
-                       ntohs( from->sat_addr.s_net ),
-                       from->sat_addr.s_node );
-               return 0;
-           }
-
-           do {
-               /*
-                * We copy out firstnet, twice (see above).  Not
-                * a big deal, and it makes the end condition cleaner.
-                */
-               if ( data + sizeof( u_short ) + 1 > end ) {     /* + strlen */
-                   LOG(log_info, logtype_atalkd, "zip ereply short (%d)", len );
-                   return 1;
-               }
-               memcpy( &firstnet, data, sizeof( u_short ));
-               data += sizeof( u_short );
-
-               /* check route */
-               if ( firstnet != rtmp->rt_firstnet ) {
-                   LOG(log_info, logtype_atalkd, "zip ereply with multiple nets" );
-                   return 1;
-               }
-
-               zlen = *data++;
-               if ( zlen > 32 || zlen <= 0 ) {
-                   LOG(log_info, logtype_atalkd, "zip ereply bad zone length (%d)", zlen );
-                   return 1;
-               }
-               if ( data + zlen > end ) {
-                   LOG(log_info, logtype_atalkd, "zip ereply short (%d)", len );
-                   return 1;
-               }
-               memcpy( zname, data, zlen );
-               data += zlen;
-               if (addzone( rtmp, zlen, zname ) < 0) {
-                   LOG(log_error, logtype_atalkd, "zip_packet: addzone");
-                   return -1;
-               }
-           } while ( data < end );
-
-           if ( rtmp ) {
-               /*
-                * Count zones for rtmptab entry.
-                */
-               for ( n = 0, l = rtmp->rt_zt; l; l = l->l_next, n++ )
-                   ;
-               if ( n == zh.zh_count ) {
-                   rtmp->rt_flags |= RTMPTAB_HASZONES;
-                   /* XXX */
-                   if ( rtmp->rt_gate == NULL &&
-                           zonecheck( rtmp, gate->g_iface ) != 0 ) {
-                       LOG(log_error, logtype_atalkd, "zip_packet seed zonelist mismatch" );
-                       return -1;
-                   }
-                   rtmp->rt_flags &= ~RTMPTAB_ZIPQUERY;
-               }
-           }
-           break;
-
-       case ZIPOP_GNI :
-           /*
-            * Don't answer with bogus information.
-            */
-           if (((iface->i_flags & IFACE_ISROUTER) == 0) ||
-               iface->i_rt->rt_zt == NULL ||
-               ( iface->i_flags & IFACE_CONFIG ) == 0 ) {
-               return 0;
-           }
-
-           if ( zh.zh_zero != 0 || data + 2 * sizeof( u_short ) > end ) {
-               LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-               return 1;
-           }
-
-           memcpy( &firstnet, data, sizeof( u_short ));
-           data += sizeof( u_short );
-           memcpy( &lastnet, data, sizeof( u_short ));
-           data += sizeof( u_short );
-           if ( firstnet != 0 || lastnet != 0 || data >= end ) {
-               LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-               return 1;
-           }
-
-           zlen = *data++;
-           if ( zlen < 0 || zlen > 32 ) {
-               LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-               return 1;
-           }
-           memcpy( zname, data, zlen );
-
-           data = packet;
-           end = data + sizeof( packet );
-           zh.zh_op = ZIPOP_GNIREPLY;
-           zh.zh_flags = 0;
-
-           /*
-            * Skip to the nets.  Fill in header when we're done.
-            */
-           data += 1 + sizeof( struct ziphdr );
-           memcpy( data, &iface->i_rt->rt_firstnet, sizeof( u_short ));
-           data += sizeof( u_short );
-           memcpy( data, &iface->i_rt->rt_lastnet, sizeof( u_short ));
-           data += sizeof( u_short );
-
-           *data++ = zlen;
-           memcpy( data, zname, zlen );
-           data += zlen;
-
-           /*
-            * Check if the given zone is valid.  If it's valid, just fill in
-            * the multicast address.  If it's not, fill the multicast address
-            * in with the default zone and return the default zone.
-            */
-           for ( l = iface->i_rt->rt_zt; l; l = l->l_next ) {
-               zt = (struct ziptab *)l->l_data;
-               if ( zt->zt_len == zlen &&
-                       strndiacasecmp( zname, zt->zt_name, zlen ) == 0 ) {
-                   break;
-               }
-           }
-           if ( l == NULL ) {
-               zt = (struct ziptab *)iface->i_rt->rt_zt->l_data;
-               zh.zh_flags |= ZIPGNI_INVALID;
-           }
-
-           for ( n = 0, l = iface->i_rt->rt_zt; l; l = l->l_next, n++ )
-               ;
-           if ( n == 1 ) {
-               zh.zh_flags |= ZIPGNI_ONEZONE;
-           }
-
-           /* multicast */
-           *data++ = 6;        /* sizeof ??? */
-           if (zone_bcast(zt) < 0) {
-             LOG(log_error, logtype_atalkd, "zip_packet: zone_bcast");
-             return -1;
-           }
-           memcpy(data, zt->zt_bcast, 6);
-           data += 6;
-
-           /*
-            * Add default zone.
-            */
-           if ( zh.zh_flags & ZIPGNI_INVALID ) {
-               *data++ = zt->zt_len;
-               memcpy( data, zt->zt_name, zt->zt_len );
-               data += zt->zt_len;
-           }
-
-           /* fill in header */
-           *packet = DDPTYPE_ZIP;
-           memcpy( packet + 1, &zh, sizeof( struct ziphdr ));
-
-           /*
-            * If the address we received this request from isn't correct
-            * for the net we received it on, send a broadcast.
-            */
-           if ( ntohs( from->sat_addr.s_net ) <
-                   ntohs( iface->i_rt->rt_firstnet ) ||
-                   ntohs( from->sat_addr.s_net ) >
-                   ntohs( iface->i_rt->rt_lastnet )) {
-               from->sat_addr.s_net = 0;
-               from->sat_addr.s_node = ATADDR_BCAST;
-           }
-
-           if ( sendto( ap->ap_fd, packet, data - packet, 0,
-                   (struct sockaddr *)from,
-                   sizeof( struct sockaddr_at )) < 0 ) {
-               LOG(log_error, logtype_atalkd, "zip gni sendto %u.%u: %s",
-                       ntohs( from->sat_addr.s_net ), from->sat_addr.s_node,
-                       strerror(errno) );
-               return 1;
-           }
-           break;
-
-       case ZIPOP_GNIREPLY :
-           /*
-            * Ignore ZIP GNIReplys which are either late or unsolicited.
-            */
-           LOG(log_debug, logtype_atalkd, "zip gnireply from %u.%u (%s %x)",
-                   ntohs( from->sat_addr.s_net ), from->sat_addr.s_node,
-                   iface->i_name, iface->i_flags );
-
-           if (( iface->i_flags & ( IFACE_CONFIG|IFACE_PHASE1 )) ||
-                   ( iface->i_flags & IFACE_ADDR ) == 0 ) {
-               LOG(log_debug, logtype_atalkd, "zip ignoring gnireply" );
-               return 1;
-           }
-
-           if ( data + 2 * sizeof( u_short ) > end ) {
-               LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-               return 1;
-           }
-           memcpy( &firstnet, data, sizeof( u_short ));
-           data += sizeof( u_short );
-           memcpy( &lastnet, data, sizeof( u_short ));
-           data += sizeof( u_short );
-
-           /*
-            * We never ask for a zone, so we can get back what the
-            * default zone is.
-            */
-           if ( data >= end || data + *data > end ) {
-               LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-               return 1;
-           }
-           if ( *data++ != 0 ) {
-               LOG(log_info, logtype_atalkd, "zip_packet unsolicited zone" );
-               return 1;
-           }
-
-           /* skip multicast (should really check it) */
-           if ( data >= end || data + *data > end ) {
-               LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-               return 1;
-           }
-           data += *data + 1;
-
-           if ( data >= end || data + *data > end ) {
-               LOG(log_info, logtype_atalkd, "zip_packet malformed packet" );
-               return 1;
-           }
-
-           /*
-            * First, if we're not seed, we always get our zone information
-            * from the net -- we don't even save what was in the file.
-            * Second, if we are seed, we keep our zone list in the
-            * interface structure, not in the zone table.  This allows us
-            * to check that the net is giving us good zones.
-            */
-           if ( (iface->i_flags & IFACE_SEED) && iface->i_czt) {
-               if ( iface->i_czt->zt_len != *data ||
-                       strndiacasecmp( iface->i_czt->zt_name,
-                       data + 1, *data ) != 0 ) {
-                   LOG(log_error, logtype_atalkd, "default zone mismatch on %s",
-                           iface->i_name );
-                   LOG(log_error, logtype_atalkd, "%.*s != %.*s",
-                           iface->i_czt->zt_len, iface->i_czt->zt_name,
-                           *data, data + 1 );
-                   LOG(log_error, logtype_atalkd, "Seed error! Exiting!" );
-                   return -1;
-               }
-           }
-
-           if (addzone( iface->i_rt, *data, data + 1 ) < 0) {
-               LOG(log_error, logtype_atalkd, "zip_packet: addzone");
-               return -1;
-           }
-           
-           /*
-            * The netrange we received from the router doesn't match the
-            * range we have locally. This is not a problem, unless we
-            * have seed information.
-            */
-           if ( firstnet != iface->i_rt->rt_firstnet ||
-                   lastnet != iface->i_rt->rt_lastnet ) {
-               if ( iface->i_flags & IFACE_SEED ) {
-                   LOG(log_error, logtype_atalkd, "netrange mismatch on %s",
-                           iface->i_name );
-                   LOG(log_error, logtype_atalkd, "%u-%u != %u-%u",
-                           ntohs( firstnet ), ntohs( lastnet ),
-                           ntohs( iface->i_rt->rt_firstnet ),
-                           ntohs( iface->i_rt->rt_lastnet ));
-                   LOG(log_error, logtype_atalkd, "Seed error! Exiting!" );
-                   return -1;
-               }
-
-
-               /*
-                * It is possible that we will corrupt our route database
-                * by just forcing this change.  A better solution would
-                * be to search all of our current routes, looking for
-                * this new route, and delete any old versions.  Also, we
-                * would call rtmp_delete() on the old net range, in case
-                * there is some other net which actually had that range.  XXX
-                */
-               iface->i_rt->rt_firstnet = firstnet;
-               iface->i_rt->rt_lastnet = lastnet;
-
-               if ( ntohs( iface->i_addr.sat_addr.s_net ) <
-                       ntohs( firstnet ) ||
-                       ntohs( iface->i_addr.sat_addr.s_net ) >
-                       ntohs( lastnet )) {
-                   iface->i_addr.sat_addr.s_net = 0;   /* ATADDR_ANYNET? */
-               }
-               setaddr( iface, IFACE_PHASE2, iface->i_addr.sat_addr.s_net,
-                       iface->i_addr.sat_addr.s_node, firstnet, lastnet );
-               stabletimer = UNSTABLE;
-           }
-
-           /* add addr to loopback route */
-           if ( looproute( iface, RTMP_ADD )) { /* -1 or 1 */
-               LOG(log_error, logtype_atalkd,
-                       "zip_packet: can't route %u.%u to loopback: %s",
-                       ntohs( iface->i_addr.sat_addr.s_net ),
-                       iface->i_addr.sat_addr.s_node,
-                       strerror(errno) );
-               return -1;
-           }
-
-           LOG(log_info, logtype_atalkd, "zip_packet configured %s from %u.%u",
-                   iface->i_name, ntohs( from->sat_addr.s_net ),
-                   from->sat_addr.s_node );
-           iface->i_flags |= IFACE_CONFIG;
-           if ( iface == ciface ) {
-               ciface = ciface->i_next;
-               bootaddr( ciface );
-           }
-           break;
-
-       case ZIPOP_NOTIFY :
-#ifdef DEBUG
-           printf( "zip notify from %u.%u\n", ntohs( from->sat_addr.s_net ),
-                   from->sat_addr.s_node );
-#endif /* DEBUG */
-           break;
-
-       default :
-           LOG(log_info, logtype_atalkd, "zip_packet bad zip op from %u.%u",
-                   ntohs( from->sat_addr.s_net ), from->sat_addr.s_node );
-       }
-       break;
-
-    case DDPTYPE_ATP :
-       if ( data + sizeof( struct atphdr ) > end ) {
-           LOG(log_info, logtype_atalkd, "zip atp malformed packet" );
-           return 1;
-       }
-       memcpy( &ah, data, sizeof( struct atphdr ));
-       data += sizeof( struct atphdr );
-       if ( ah.atphd_ctrlinfo != ATP_TREQ ) {
-           LOG(log_info, logtype_atalkd, "zip atp bad control" );
-           return 1;
-       }
-       ah.atphd_ctrlinfo = ATP_TRESP | ATP_EOM;
-       if ( ah.atphd_bitmap != 1 ) {
-           LOG(log_error, logtype_atalkd, "zip atp bad bitmap" );
-           return 1;
-       }
-       ah.atphd_bitmap = 0;
-
-       zipop = *data++;
-       data++;
-       memcpy( &index, data, sizeof( u_short ));
-       data += sizeof( u_short );
-       index = ntohs( index );
-       if ( data != end ) {
-           LOG(log_info, logtype_atalkd, "zip atp malformed packet" );
-           return 1;
-       }
-
-       data = packet;
-       end = data + sizeof( packet );
-       *data++ = DDPTYPE_ATP;
-       memcpy( data, &ah, sizeof( struct atphdr ));
-       data += sizeof( struct atphdr );
-       lastflag = data++;              /* mark and space for last flag */
-       *data++ = 0;
-       nzones = data;                  /* mark and space for zone count */
-       data += sizeof( u_short );
-
-       switch ( zipop ) {
-       case ZIPOP_GETMYZONE :
-           if ( index != 0 ) {
-               LOG(log_info, logtype_atalkd, "zip atp gmz bad index" );
-               return 1;
-           }
-
-           if ( iface->i_flags & IFACE_LOOPBACK ) {
-               iface = interfaces->i_next;     /* first interface */
-           } else if ( ntohs( iface->i_rt->rt_firstnet ) >
-                   ntohs( from->sat_addr.s_net ) ||
-                   ntohs( iface->i_rt->rt_lastnet ) <
-                   ntohs( from->sat_addr.s_net )) {
-               return 0;
-           }
-
-           if ( iface->i_rt->rt_zt == NULL ) {
-               return 0;
-           }
-           zt = (struct ziptab *)iface->i_rt->rt_zt->l_data;
-           if ( data + 1 + zt->zt_len > end ) {
-               LOG(log_info, logtype_atalkd, "zip atp gmz reply too long" );
-               return 1;
-           }
-           *data++ = zt->zt_len;
-           memcpy( data, zt->zt_name, zt->zt_len );
-           data += zt->zt_len;
-
-           *lastflag = 0;
-           nz = 1;
-           break;
-
-       case ZIPOP_GETZONELIST :
-           for ( zt = ziptab; zt && ( index > 1 ); zt = zt->zt_next, index-- )
-               ;
-           for ( nz = 0; zt; zt = zt->zt_next, nz++ ) {
-               if ( data + 1 + zt->zt_len > end ) {
-                   break;
-               }
-               *data++ = zt->zt_len;
-               memcpy( data, zt->zt_name, zt->zt_len );
-               data += zt->zt_len;
-           }
-
-           *lastflag = ( zt == NULL );         /* Too clever? */
-           break;
-
-       case ZIPOP_GETLOCALZONES :
-           if ( iface->i_flags & IFACE_LOOPBACK ) {
-               iface = interfaces->i_next;     /* first interface */
-           } else if ( ntohs( iface->i_rt->rt_firstnet ) >
-                   ntohs( from->sat_addr.s_net ) ||
-                   ntohs( iface->i_rt->rt_lastnet ) <
-                   ntohs( from->sat_addr.s_net )) {
-               return 0;
-           }
-
-           for ( l = iface->i_rt->rt_zt; l && ( index > 1 );
-                   l = l->l_next, index-- )
-               ;
-           for ( nz = 0; l; l = l->l_next, nz++ ) {
-               zt = (struct ziptab *)l->l_data;
-               if ( data + 1 + zt->zt_len > end ) {
-                   break;
-               }
-               *data++ = zt->zt_len;
-               memcpy( data, zt->zt_name, zt->zt_len );
-               data += zt->zt_len;
-           }
-
-           *lastflag = ( l == NULL );
-           break;
-
-       default :
-           LOG(log_info, logtype_atalkd, "zip atp bad option" );
-           return 1;
-       }
-
-       /* send reply */
-       if ( nz > 0 ) {
-           nz = htons( nz );
-           memcpy( nzones, &nz, sizeof( u_short ));
-           if ( sendto( ap->ap_fd, packet, data - packet, 0,
-                   (struct sockaddr *)from,
-                   sizeof( struct sockaddr_at )) < 0 ) {
-               LOG(log_error, logtype_atalkd, "zip atp sendto %u.%u: %s",
-                       ntohs( from->sat_addr.s_net ), from->sat_addr.s_node,
-                       strerror(errno) );
-               return 1;
-           }
-       }
-       break;
-
-    default :
-       LOG(log_info, logtype_atalkd, "zip_packet bad ddp type from %u.%u",
-               ntohs( from->sat_addr.s_net ), from->sat_addr.s_node );
-       return 1;
-    }
-
-    return 0;
-}
-
-int zip_getnetinfo(struct interface *iface)
-{
-    struct atport      *ap;
-    struct ziphdr      zh;
-    struct sockaddr_at sat;
-    char               *data, packet[ 40 ];
-    u_short            net;
-
-    LOG(log_info, logtype_atalkd, "zip_getnetinfo for %s", iface->i_name );
-
-    for ( ap = iface->i_ports; ap; ap = ap->ap_next ) {
-       if ( ap->ap_packet == zip_packet ) {
-           break;
-       }
-    }
-    if ( ap == NULL ) {
-       LOG(log_error, logtype_atalkd, "zip_getnetinfo can't find zip socket!" );
-       return -1;
-    }
-
-    data = packet;
-
-    *data++ = DDPTYPE_ZIP;
-
-    zh.zh_op = ZIPOP_GNI;
-    zh.zh_zero = 0;
-    memcpy( data, &zh, sizeof( struct ziphdr ));
-    data += sizeof( struct ziphdr );
-    net = 0;
-    memcpy( data, &net, sizeof( u_short ));
-    data += sizeof( u_short );
-    memcpy( data, &net, sizeof( u_short ));
-    data += sizeof( u_short );
-
-    /*
-     * Set our requesting zone to NULL, so the response will contain
-     * the default zone.
-     */
-    *data++ = 0;
-
-#ifdef BSD4_4
-    sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    sat.sat_family = AF_APPLETALK;
-    sat.sat_addr.s_net = 0;
-    sat.sat_addr.s_node = ATADDR_BCAST;
-    sat.sat_port = ap->ap_port;
-
-    if ( sendto( ap->ap_fd, packet, data - packet, 0, (struct sockaddr *)&sat,
-           sizeof( struct sockaddr_at )) < 0 ) {
-       LOG(log_error, logtype_atalkd, "zip_getnetinfo sendto: %s", strerror(errno) );
-       return -1;
-    }
-    return 0;
-}
-
-struct ziptab *newzt(const int len, const char *name)
-{
-    struct ziptab      *zt;
-
-    if (( zt = (struct ziptab *)calloc(1, sizeof( struct ziptab ))) == NULL ) {
-       return( NULL );
-    }
-
-    zt->zt_len = len;
-    if (( zt->zt_name = (char *)malloc( len )) == NULL ) {
-       free(zt);
-       return( NULL );
-    }
-
-    memcpy( zt->zt_name, name, len );
-    return( zt );
-}
-
-
-/*
- * Insert at the end.  Return 1 if a mapping already exists, 0 otherwise.
- * -1 on error.
- */
-static int add_list(struct list **head, void *data)
-{
-    struct list        *l, *l2;
-
-    for ( l = *head; l; l = l->l_next ) {
-       if ( l->l_data == data ) {
-           return( 1 );
-       }
-    }
-    if (( l = (struct list *)malloc( sizeof( struct list ))) == NULL ) {
-       LOG(log_error, logtype_atalkd, "add_list malloc: %s", strerror(errno) );
-       return -1;
-    }
-
-    l->l_data = data;
-    l->l_next = NULL;
-    if ( *head == NULL ) {
-       l->l_prev = NULL;
-       *head = l;
-    } else {
-       /* find end of list */
-       for ( l2 = *head; l2->l_next; l2 = l2->l_next )
-           ;
-       l->l_prev = l2;
-       l2->l_next = l;
-    }
-    return( 0 );
-}
-
-int addzone(struct rtmptab *rt, int len, char *zone)
-{
-    struct ziptab      *zt;
-    int                        cc, exists = 0;
-
-    for ( zt = ziptab; zt; zt = zt->zt_next ) {
-       if ( zt->zt_len == len &&
-               strndiacasecmp( zt->zt_name, zone, len ) == 0 ) {
-           break;
-       }
-    }
-    if ( zt == NULL ) {
-       if (( zt = newzt( len, zone )) == NULL ) {
-           LOG(log_error, logtype_atalkd, "addzone newzt: %s", strerror(errno) );
-           return -1;
-       }
-       if ( ziptab == NULL ) {
-           zt->zt_prev = NULL;
-           ziptab = zt;
-       } else {
-           zt->zt_prev = ziplast;
-           ziplast->zt_next = zt;
-       }
-       ziplast = zt;
-    }
-
-    if ((cc = add_list( &zt->zt_rt, rt )) < 0) 
-      return -1;
-
-    if (cc)
-      exists++;
-
-    if ((cc = add_list( &rt->rt_zt, zt )) < 0 )
-      return -1;
-
-    if (cc) {
-        if ( !exists ) {
-           LOG(log_error, logtype_atalkd, "addzone corrupted route/zone mapping" );
-           return -1;
-       }
-       /*
-        * We get the repeat for local nets which have zone information
-        * already: we ask anyway, just to make sure.
-        */
-       
-       return 0;
-    }
-    if ( exists ) {
-       LOG(log_error, logtype_atalkd, "addzone corrupted zone/route mapping" );
-       return -1;
-    }
-    return 0;
-}
diff --git a/etc/atalkd/zip.h b/etc/atalkd/zip.h
deleted file mode 100644 (file)
index e8bf1db..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * $Id: zip.h,v 1.4 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifndef ATALKD_ZIP_H
-#define ATALKD_ZIP_H 1
-
-#include <sys/cdefs.h>
-
-struct ziptab {
-    struct ziptab      *zt_next,
-                       *zt_prev;
-    u_char             zt_len;
-    char               *zt_name;
-    u_char             *zt_bcast;
-    struct list                *zt_rt;
-};
-
-extern struct ziptab   *ziptab, *ziplast;
-struct ziptab  *newzt (const int, const char *);
-
-int addzone ( struct rtmptab *, int, char * );
-int zip_getnetinfo ( struct interface * );
-int zip_packet(struct atport *ap,struct sockaddr_at *from, char *data, int len);
-
-#endif /* atalkd/zip.h */
index 802ad3abb64e90f620a319a678a22d25599a9978..3ebcbebb465d858df205e0acdbad2f68a2173e8d 100644 (file)
@@ -30,6 +30,4 @@ dbd_LDADD = $(top_builddir)/libatalk/libatalk.la @BDB_LIBS@ @ACL_LIBS@
 
 noinst_HEADERS = dbif.h pack.h db_param.h dbd.h usockfd.h comm.h cmd_dbd.h
 
-EXTRA_DIST = README
-
 AM_CFLAGS = @BDB_CFLAGS@ -D_PATH_CNID_DBD=\"$(sbindir)/cnid_dbd\"
diff --git a/etc/cnid_dbd/README b/etc/cnid_dbd/README
deleted file mode 100644 (file)
index cbd2f9f..0000000
+++ /dev/null
@@ -1,90 +0,0 @@
-This is a implementation of the netatalk CNID database support that
-attempts to put all functionality into a separate daemon called cnid_dbd.
-There is one such daemon per netatalk volume. The underlying database
-structure is based on Berkeley DB and the database format is the same
-as in the cdb CNID backend, so this can be used as a drop-in replacement.
-
-Advantages: 
-
-- No locking issues or leftover locks due to crashed afpd daemons any
-  more. Since there is only one thread of control accessing the
-  database, no locking is needed and changes appear atomic.
-
-- Berkeley DB transactions are difficult to get right with several
-  processes attempting to access the CNID database simultanously. This 
-  is much easier with a single process and the database can be made nearly 
-  crashproof this way (at a performance cost).
-
-- No problems with user permissions and access to underlying database
-  files, the cnid_dbd process runs under a configurable user
-  ID that normally also owns the underlying database
-  and can be contacted by whatever afpd daemon accesses a volume.
-
-- If an afpd process crashes, the CNID database is unaffected. If the
-  process was making changes to the database at the time of the crash,
-  those changes will be rolled back entirely (transactions).
-  If the process was not using the database at the time of the crash,
-  no corrective action is necessary. In any case, database consistency
-  is assured.
-
-Disadvantages:
-
-- Performance in an environment of processes sharing the database
-  (files) is potentially better for two reasons:
-
-  i)  IPC overhead.
-  ii) r/o access to database pages is possible by more than one
-      process at once, r/w access is possible for nonoverlapping regions.
-
-  The current implementation of cnid_dbd uses unix domain sockets as
-  the IPC mechanism. While this is not the fastest possible method, it
-  is very portable and the cnid_dbd IPC mechanisms can be extended to
-  use faster IPC (like mmap) on architectures where it is
-  supported. As a ballpark figure, 20000 requests/replies to the cnid_dbd
-  daemon take about 0.6 seconds on a Pentium III 733 Mhz running Linux
-  Kernel 2.4.18 using unix domain sockets. The requests are "empty"
-  (no database lookups/changes), so this is just the IPC
-  overhead.
-  
-  I have not measured the effects of the advantages of simultanous
-  database access.
-
-
-Installation and configuration
-
-cnid_dbd is part of the CNID framework whereby various CNID backends
-can be selected for afpd as a runtime option for a given volume.
-By default only last and dbd backend are built and dbd is the default.
-
-There are two executeables that will be built in etc/cnid_dbd and
-installed into the systems binaries directories of netatalk
-(e.g. /usr/local/netatalk/sbin or whatever you specify with --sbindir
-to configure): cnid_metad and cnid_dbd. cnid_metad should run all the
-time with root permissions. It will be notified when an instance of
-afpd starts up and will in turn make sure that a cnid_dbd daemon is
-started for the volume that afpd wishes to access. The daemon runs as
-long as necessary (see the idle_timeout option below) and services any
-other instances of afpd that access the volume. You can safely kill it
-with SIGTERM, it will be restarted automatically by cnid_metad as soon
-as the volume is accessed again.
-
-cnid_dbd changes to the Berkeley DB directory on startup and sets
-effective UID and GID to owner and group of that directory. Database and
-supporting files should therefore be writeable by that user/group.
-
-Current shortcomings:
-
-- The parameter file parsing of db_param is very simpleminded. It is
-easy to cause buffer overruns and the like.
-Also, there is no support for blanks (or weird characters) in
-filenames for the usock_file parameter.
-
-- There is no protection against a malicious user connecting to the
-cnid_dbd socket and changing the database.
-
-Please feel free to grep the source in etc/cnid_dbd and the file
-libatalk/cnid/dbd/cnid_dbd.c for the string TODO, which indicates
-comments that adress other, less important points.
-
-
-The Netatalk Team
index 3b81b8b59df3fdeb428444ffb42837f9f817afdb..91a3ac3504695fddf839ad03869cb2d1bfd3d6ab 100644 (file)
    GNU General Public License for more details.
 */
 
-/*
-  dbd specs and implementation progress
-  =====================================
-
-  St := Status
-
-  Force option
-  ------------
-  
-  St Spec
-  -- ----
-  OK If -f is requested, ensure -e is too.
-     Check if volumes is using AFPVOL_CACHE, then wipe db from disk. Rebuild from ad-files.
-
-  1st pass: Scan volume
-  --------------------
-
-  St Type Check
-  -- ---- -----
-  OK F/D  Make sure ad file exists
-  OK D    Make sure .AppleDouble dir exist, create if missing. Error creating
-          it is fatal as that shouldn't happen as root.
-  OK F/D  Delete orphaned ad-files, log dirs in ad-dir
-  OK F/D  Check name encoding by roundtripping, log on error
-  OK F/D  try: read CNID from ad file (if cnid caching is on)
-          try: fetch CNID from database
-          -> on mismatch: use CNID from file, update database (deleting both found CNIDs first)
-          -> if no CNID in ad file: write CNID from database to ad file
-          -> if no CNID in database: add CNID from ad file to database
-          -> on no CNID at all: create one and store in both places
-  OK F/D  Add found CNID, DID, filename, dev/inode, stamp to rebuild database
-  OK F/D  Check/update stamp (implicitly done while checking CNIDs)
-
-
-  2nd pass: Delete unused CNIDs
-  -----------------------------
-
-  St Spec
-  -- ----
-  OK Step through dbd (the one on disk) and rebuild-db from pass 1 and delete any CNID from
-     dbd not in rebuild db. This in only done in exclusive mode.
-*/
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
 #include <atalk/logger.h>
 #include <atalk/cnid_dbd_private.h>
-#include <atalk/volinfo.h>
+#include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
 #include <atalk/util.h>
 
 #include "cmd_dbd.h"
 #include "dbd.h"
 #include "dbif.h"
 #include "db_param.h"
+#include "pack.h"
 
 #define DBOPTIONS (DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN)
 
 int nocniddb = 0;               /* Dont open CNID database, only scan filesystem */
-struct volinfo volinfo; /* needed by pack.c:idxname() */
 volatile sig_atomic_t alarmed;  /* flags for signals */
 int db_locked;                  /* have we got the fcntl lock on lockfile ? */
 
@@ -171,47 +129,29 @@ static void set_signal(void)
 static void usage (void)
 {
     printf("dbd (Netatalk %s)\n"
-           "Usage: dbd [-e|-t|-v|-x] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
+           "Usage: dbd [-CeFtvx] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
            "dbd must be run with appropiate permissions i.e. as root.\n\n"
            "Main commands are:\n"
            "   -d Dump CNID database\n"
            "      Option: -i dump indexes too\n\n"
            "   -s Scan volume:\n"
-           "      1. Compare CNIDs in database with volume\n"
-           "      2. Check if .AppleDouble dirs exist\n"
-           "      3. Check if  AppleDouble file exist\n"
-           "      4. Report orphaned AppleDouble files\n"
-           "      5. Check for directories inside AppleDouble directories\n"
-           "      6. Check name encoding by roundtripping, log on error\n"
-           "      7. Check for orphaned CNIDs in database (requires -e)\n"
-           "      8. Open and close adouble files\n"
            "      Options: -c Don't check .AppleDouble stuff, only ckeck orphaned.\n"
            "               -n Don't open CNID database, skip CNID checks.\n\n"
            "   -r Rebuild volume:\n"
-           "      1. Sync CNIDSs in database with volume\n"
-           "      2. Make sure .AppleDouble dir exist, create if missing\n"
-           "      3. Make sure AppleDouble file exists, create if missing\n"
-           "      4. Delete orphaned AppleDouble files\n"
-           "      5. Check for directories inside AppleDouble directories\n"
-           "      6. Check name encoding by roundtripping, log on error\n"
-           "      7. Check for orphaned CNIDs in database (requires -e)\n"
-           "      8. Open and close adouble files\n"
            "      Options: -c Don't create .AppleDouble stuff, only cleanup orphaned.\n"
            "               -f wipe database and rebuild from IDs stored in AppleDouble\n"
-           "                  files, only available for volumes without 'nocnidcache'\n"
-           "                  option. Implies -e.\n\n"
+           "                  metadata file or EA. Implies -e.\n\n"
            "   -u Upgrade:\n"
            "      Opens the database which triggers any necessary upgrades,\n"
            "      then closes and exits.\n\n"
            "General options:\n"
+           "   -C convert from adouble:v2 to adouble:ea (use with -r)\n"
+           "   -F location of the afp.conf config file\n"
            "   -e only work on inactive volumes and lock them (exclusive)\n"
            "   -x rebuild indexes (just for completeness, mostly useless!)\n"
            "   -t show statistics while running\n"
            "   -v verbose\n\n"
-           "WARNING:\n"
-           "For -r -f restore of the CNID database from the adouble files,\n"
-           "the CNID must of course be synched to them files first with a plain -r rebuild!\n"
            , VERSION
         );
 }
@@ -223,6 +163,8 @@ int main(int argc, char **argv)
     dbd_flags_t flags = 0;
     char *volpath;
     int cdir;
+    AFPObj obj = { 0 };
+    struct vol *vol;
 
     if (geteuid() != 0) {
         usage();
@@ -231,11 +173,14 @@ int main(int argc, char **argv)
     /* Inhereting perms in ad_mkdir etc requires this */
     ad_setfuid(0);
 
-    while ((c = getopt(argc, argv, ":cdefinrstuvx")) != -1) {
+    while ((c = getopt(argc, argv, ":cCdefFinrstuvx")) != -1) {
         switch(c) {
         case 'c':
             flags |= DBD_FLAGS_CLEANUP;
             break;
+        case 'C':
+            flags |= DBD_FLAGS_V2TOEA;
+            break;
         case 'd':
             dump = 1;
             break;
@@ -273,6 +218,9 @@ int main(int argc, char **argv)
             exclusive = 1;
             flags |= DBD_FLAGS_FORCE | DBD_FLAGS_EXCL;
             break;
+        case 'F':
+            obj.cmdlineconfigfile = strdup(optarg);
+            break;
         case ':':
         case '?':
             usage();
@@ -305,45 +253,73 @@ int main(int argc, char **argv)
 
     /* Setup logging. Should be portable among *NIXes */
     if (!verbose)
-        setuplog("default log_info /dev/tty");
+        setuplog("default:info", "/dev/tty");
     else
-        setuplog("default log_debug /dev/tty");
+        setuplog("default:debug", "/dev/tty");
+
+    /* Load config */
+    if (afp_config_parse(&obj, "dbd") != 0) {
+        dbd_log( LOGSTD, "Couldn't load afp.conf");
+        exit(EXIT_FAILURE);
+    }
 
-    /* Load .volinfo file */
-    if (loadvolinfo(volpath, &volinfo) == -1) {
-        dbd_log( LOGSTD, "Not a Netatalk volume at '%s', no .volinfo file at '%s/.AppleDesktop/.volinfo' or unknown volume options", volpath, volpath);
+    if (load_volumes(&obj, NULL) != 0) {
+        dbd_log( LOGSTD, "Couldn't load volumes");
         exit(EXIT_FAILURE);
     }
-    if (vol_load_charsets(&volinfo) == -1) {
-        dbd_log( LOGSTD, "Error loading charsets!");
+
+    if ((vol = getvolbypath(&obj, volpath)) == NULL) {
+        dbd_log( LOGSTD, "Couldn't find volume for '%s'", volpath);
+        exit(EXIT_FAILURE);
+    }
+
+    if (load_charset(vol) != 0) {
+        dbd_log( LOGSTD, "Couldn't load charsets for '%s'", volpath);
+        exit(EXIT_FAILURE);
+    }
+
+    pack_setvol(vol);
+
+    if (vol->v_adouble == AD_VERSION_EA)
+        dbd_log( LOGDEBUG, "adouble:ea volume");
+    else if (vol->v_adouble == AD_VERSION2)
+        dbd_log( LOGDEBUG, "adouble:v2 volume");
+    else {
+        dbd_log( LOGSTD, "unknown adouble volume");
+        exit(EXIT_FAILURE);
+    }
+
+    /* -C v2 to ea conversion only on adouble:ea volumes */
+    if ((flags & DBD_FLAGS_V2TOEA) && (vol->v_adouble!= AD_VERSION_EA)) {
+        dbd_log( LOGSTD, "Can't run adouble:v2 to adouble:ea conversion because not an adouble:ea volume");
         exit(EXIT_FAILURE);
     }
 
     /* Sanity checks to ensure we can touch this volume */
-    if (volinfo.v_vfs_ea != AFPVOL_EA_AD && volinfo.v_vfs_ea != AFPVOL_EA_SYS) {
-        dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", volinfo.v_vfs_ea);
+    if (vol->v_vfs_ea != AFPVOL_EA_AD && vol->v_vfs_ea != AFPVOL_EA_SYS) {
+        dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", vol->v_vfs_ea);
         exit(EXIT_FAILURE);        
     }
 
     /* Enuser dbpath is there, create if necessary */
     struct stat st;
-    if (stat(volinfo.v_dbpath, &st) != 0) {
+    if (stat(vol->v_dbpath, &st) != 0) {
         if (errno != ENOENT) {
-            dbd_log( LOGSTD, "Can't stat dbpath \"%s\": %s", volinfo.v_dbpath, strerror(errno));
+            dbd_log( LOGSTD, "Can't stat dbpath \"%s\": %s", vol->v_dbpath, strerror(errno));
             exit(EXIT_FAILURE);        
         }
-        if ((mkdir(volinfo.v_dbpath, 0755)) != 0) {
-            dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", dbpath, strerror(errno));
+        if ((mkdir(vol->v_dbpath, 0755)) != 0) {
+            dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", vol->v_dbpath, strerror(errno));
             exit(EXIT_FAILURE);
         }        
     }
 
     /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
-    if ( (strlen(volinfo.v_dbpath) + strlen("/.AppleDB")) > MAXPATHLEN ) {
+    if ( (strlen(vol->v_dbpath) + strlen("/.AppleDB")) > MAXPATHLEN ) {
         dbd_log( LOGSTD, "Volume pathname too long");
         exit(EXIT_FAILURE);        
     }
-    strncpy(dbpath, volinfo.v_dbpath, MAXPATHLEN - strlen("/.AppleDB"));
+    strncpy(dbpath, vol->v_dbpath, MAXPATHLEN - strlen("/.AppleDB"));
     strcat(dbpath, "/.AppleDB");
 
     /* Check or create dbpath */
@@ -376,7 +352,7 @@ int main(int argc, char **argv)
     }
 
     /* Check if -f is requested and wipe db if yes */
-    if ((flags & DBD_FLAGS_FORCE) && rebuild && (volinfo.v_flags & AFPVOL_CACHE)) {
+    if ((flags & DBD_FLAGS_FORCE) && rebuild) {
         char cmd[8 + MAXPATHLEN];
         if ((db_locked = get_lock(LOCK_FREE, NULL)) != 0)
             goto exit_noenv;
@@ -436,7 +412,7 @@ int main(int argc, char **argv)
             dbd_log( LOGSTD, "Error dumping database");
         }
     } else if ((rebuild && ! nocniddb) || scan) {
-        if (cmd_dbd_scanvol(dbd, &volinfo, flags) < 0) {
+        if (cmd_dbd_scanvol(dbd, vol, flags) < 0) {
             dbd_log( LOGSTD, "Error repairing database.");
         }
     }
index ef7829881b28a851cc335998b6db8dfacdac7da6..efec636b482e464f40a1bda7ebc469dd420acb70 100644 (file)
@@ -4,7 +4,7 @@
 #include <signal.h>
 #include <limits.h>
 
-#include <atalk/volinfo.h>
+#include <atalk/netatalk_conf.h>
 #include "dbif.h"
 
 enum logtype {LOGSTD, LOGDEBUG};
@@ -15,6 +15,7 @@ typedef unsigned int dbd_flags_t;
 #define DBD_FLAGS_EXCL     (1 << 2)
 #define DBD_FLAGS_CLEANUP  (1 << 3) /* Dont create AD stuff, but cleanup orphaned */
 #define DBD_FLAGS_STATS    (1 << 4)
+#define DBD_FLAGS_V2TOEA   (1 << 5) /* Convert adouble:v2 to adouble:ea */
 
 #define ADv2_DIRNAME ".AppleDouble"
 
@@ -29,7 +30,7 @@ extern int db_locked; /* have we got the fcntl lock on lockfd ? */
 extern volatile sig_atomic_t alarmed;
 
 extern void dbd_log(enum logtype lt, char *fmt, ...);
-extern int cmd_dbd_scanvol(DBD *dbd, struct volinfo *volinfo, dbd_flags_t flags);
+extern int cmd_dbd_scanvol(DBD *dbd, struct vol *vol, dbd_flags_t flags);
 
 /*
   Functions for querying the database which couldn't be reused from the existing
index 50433c66de807a1dab6888ad7ca815a4cbd9729b..dcbd4c74779161acb4be4f3b3feda12bc6bec771 100644 (file)
 
 #include <atalk/adouble.h>
 #include <atalk/unicode.h>
-#include <atalk/volinfo.h>
+#include <atalk/netatalk_conf.h>
 #include <atalk/cnid_dbd_private.h>
 #include <atalk/volume.h>
 #include <atalk/ea.h>
 #include <atalk/util.h>
 #include <atalk/acl.h>
+#include <atalk/compat.h>
 
 #include "cmd_dbd.h"
 #include "dbif.h"
@@ -45,7 +46,7 @@
 #define ADFILE_OK (adfile_ok == 0)
 
 
-static struct volinfo *myvolinfo;
+static struct vol     *myvol;
 static char           cwdbuf[MAXPATHLEN+1];
 static DBD            *dbd;
 static DBD            *dbd_rebuild;
@@ -63,7 +64,6 @@ static char           *special_dirs[] = {
 static struct cnid_dbd_rqst rqst;
 static struct cnid_dbd_rply rply;
 static jmp_buf jmp;
-static struct vol volume; /* fake it for ea_open */
 static char pname[MAXPATHLEN] = "../";
 
 /*
@@ -83,22 +83,22 @@ static char *utompath(char *upath)
     u = upath;
     outlen = strlen(upath);
 
-    if ((myvolinfo->v_casefold & AFPVOL_UTOMUPPER))
+    if ((myvol->v_casefold & AFPVOL_UTOMUPPER))
         flags |= CONV_TOUPPER;
-    else if ((myvolinfo->v_casefold & AFPVOL_UTOMLOWER))
+    else if ((myvol->v_casefold & AFPVOL_UTOMLOWER))
         flags |= CONV_TOLOWER;
 
-    if ((myvolinfo->v_flags & AFPVOL_EILSEQ)) {
+    if ((myvol->v_flags & AFPVOL_EILSEQ)) {
         flags |= CONV__EILSEQ;
     }
 
     /* convert charsets */
-    if ((size_t)-1 == ( outlen = convert_charset(myvolinfo->v_volcharset,
+    if ((size_t)-1 == ( outlen = convert_charset(myvol->v_volcharset,
                                                  CH_UTF8_MAC,
-                                                 myvolinfo->v_maccharset,
+                                                 myvol->v_maccharset,
                                                  u, outlen, mpath, MAXPATHLEN, &flags)) ) {
         dbd_log( LOGSTD, "Conversion from %s to %s for %s failed.",
-                 myvolinfo->v_volcodepage, myvolinfo->v_maccodepage, u);
+                 myvol->v_volcodepage, myvol->v_maccodepage, u);
         return NULL;
     }
 
@@ -124,17 +124,12 @@ static char *mtoupath(char *mpath)
     }
 
     /* set conversion flags */
-    if (!(myvolinfo->v_flags & AFPVOL_NOHEX))
-        flags |= CONV_ESCAPEHEX;
-    if (!(myvolinfo->v_flags & AFPVOL_USEDOTS))
-        flags |= CONV_ESCAPEDOTS;
-
-    if ((myvolinfo->v_casefold & AFPVOL_MTOUUPPER))
+    if ((myvol->v_casefold & AFPVOL_MTOUUPPER))
         flags |= CONV_TOUPPER;
-    else if ((myvolinfo->v_casefold & AFPVOL_MTOULOWER))
+    else if ((myvol->v_casefold & AFPVOL_MTOULOWER))
         flags |= CONV_TOLOWER;
 
-    if ((myvolinfo->v_flags & AFPVOL_EILSEQ)) {
+    if ((myvol->v_flags & AFPVOL_EILSEQ)) {
         flags |= CONV__EILSEQ;
     }
 
@@ -145,118 +140,17 @@ static char *mtoupath(char *mpath)
     outlen = MAXPATHLEN;
 
     if ((size_t)-1 == (outlen = convert_charset(CH_UTF8_MAC,
-                                                myvolinfo->v_volcharset,
-                                                myvolinfo->v_maccharset,
+                                                myvol->v_volcharset,
+                                                myvol->v_maccharset,
                                                 m, inplen, u, outlen, &flags)) ) {
         dbd_log( LOGSTD, "conversion from UTF8-MAC to %s for %s failed.",
-                 myvolinfo->v_volcodepage, mpath);
+                 myvol->v_volcodepage, mpath);
         return NULL;
     }
 
     return( upath );
 }
 
-#if 0
-/* 
-   Check if "name" is pointing to
-   a) an object inside the current volume (return 0)
-   b) an object outside the current volume (return 1)
-   Then stats the pointed to object and if it is a dir ors ADFLAGS_DIR to *adflags
-   Return -1 on any serious error.
- */
-static int check_symlink(const char *name, int *adflags)
-{
-    int cwd;
-    ssize_t len;
-    char pathbuf[MAXPATHLEN + 1];
-    char *sep;
-    struct stat st;
-
-    if ((len = readlink(name, pathbuf, MAXPATHLEN)) == -1) {
-        dbd_log(LOGSTD, "Error reading link info for '%s/%s': %s", 
-                cwdbuf, name, strerror(errno));
-        return -1;
-    }
-    pathbuf[len] = 0;
-
-    if ((stat(pathbuf, &st)) != 0) {
-        dbd_log(LOGSTD, "stat error '%s': %s", pathbuf, strerror(errno));
-    }
-
-    /* Remember cwd */
-    if ((cwd = open(".", O_RDONLY)) < 0) {
-        dbd_log(LOGSTD, "error opening cwd '%s': %s", cwdbuf, strerror(errno));
-        return -1;
-    }
-
-    if (S_ISDIR(st.st_mode)) {
-        *adflags |= ADFLAGS_DIR;
-    } else { /* file */
-        /* get basename from path */
-        if ((sep = strrchr(pathbuf, '/')) == NULL)
-            /* just a file at the same level */
-            return 0;
-        sep = 0; /* pathbuf now contains the directory*/
-    }
-
-    /* fchdir() to pathbuf so we can easily get its path with getcwd() */
-    if ((chdir(pathbuf)) != 0) {
-        dbd_log(LOGSTD, "Cant chdir to '%s': %s", pathbuf, strerror(errno));
-        return -1;
-    }
-
-    if ((getcwd(pathbuf, MAXPATHLEN)) == NULL) {
-        dbd_log(LOGSTD, "Cant get symlink'ed dir '%s/%s': %s", cwdbuf, pathbuf, strerror(errno));
-        if ((fchdir(cwd)) != 0)
-            /* We're foobared */
-            longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
-        return -1;
-    }
-
-    if ((fchdir(cwd)) != 0)
-        /* We're foobared */
-        longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
-
-    /*
-      We now have the symlink target dir as absoulte path in pathbuf
-      and can compare it with the currents volume path
-    */
-    int i = 0;
-    while (myvolinfo->v_path[i]) {
-        if ((pathbuf[i] == 0) || (myvolinfo->v_path[i] != pathbuf[i])) {
-            dbd_log( LOGDEBUG, "extra-share symlink '%s/%s', following", cwdbuf, name);
-            return 1;
-        }
-        i++;
-    }
-
-    dbd_log( LOGDEBUG, "intra-share symlink '%s/%s', not following", cwdbuf, name);
-    return 0;
-}
-#endif
-
-/*
-  Check for wrong encoding e.g. "." at the beginning is not CAP encoded (:2e) although volume is default !AFPVOL_USEDOTS.
-  We do it by roundtripiping from volcharset to UTF8-MAC and back and then compare the result.
-*/
-static int check_name_encoding(char *uname)
-{
-    char *roundtripped;
-
-    roundtripped = mtoupath(utompath(uname));
-    if (!roundtripped) {
-        dbd_log( LOGSTD, "Error checking encoding for '%s/%s'", cwdbuf, uname);
-        return -1;
-    }
-
-    if ( STRCMP(uname, !=, roundtripped)) {
-        dbd_log( LOGSTD, "Bad encoding for '%s/%s'", cwdbuf, uname);
-        return -1;
-    }
-
-    return 0;
-}
-
 /*
   Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop"
   Returns pointer to name or NULL.
@@ -287,24 +181,90 @@ static const char *check_special_dirs(const char *name)
     return NULL;
 }
 
+/*
+ * We unCAPed a name, update CNID db
+ */
+static int update_cnid(cnid_t did, const struct stat *sp, const char *oldname, const char *newname)
+{
+    int ret;
+    cnid_t id;
+
+    /* Prepare request data */
+    memset(&rqst, 0, sizeof(struct cnid_dbd_rqst));
+    memset(&rply, 0, sizeof(struct cnid_dbd_rply));
+    rqst.did = did;
+    rqst.cnid = 0;
+    if ( ! (myvol->v_flags & AFPVOL_NODEV))
+        rqst.dev = sp->st_dev;
+    rqst.ino = sp->st_ino;
+    rqst.type = S_ISDIR(sp->st_mode) ? 1 : 0;
+    rqst.name = (char *)oldname;
+    rqst.namelen = strlen(oldname);
+
+    /* Query the database */
+    ret = dbd_lookup(dbd, &rqst, &rply, (dbd_flags & DBD_FLAGS_SCAN) ? 1 : 0);
+    if (dbif_txn_close(dbd, ret) != 0)
+        return -1;
+    if (rply.result != CNID_DBD_RES_OK)
+        return 0;
+    id = rply.cnid;
+
+    /* Prepare request data */
+    memset(&rqst, 0, sizeof(struct cnid_dbd_rqst));
+    memset(&rply, 0, sizeof(struct cnid_dbd_rply));
+    rqst.did = did;
+    rqst.cnid = id;
+    if ( ! (myvol->v_flags & AFPVOL_NODEV))
+        rqst.dev = sp->st_dev;
+    rqst.ino = sp->st_ino;
+    rqst.type = S_ISDIR(sp->st_mode) ? 1 : 0;
+    rqst.name = (char *)newname;
+    rqst.namelen = strlen(newname);
+
+    /* Update the database */
+    ret = dbd_update(dbd, &rqst, &rply);
+    if (dbif_txn_close(dbd, ret) != 0)
+        return -1;
+    if (rply.result != CNID_DBD_RES_OK)
+        return -1;
+
+    return 0;
+}
+
 /*
   Check for .AppleDouble file, create if missing
 */
-static int check_adfile(const char *fname, const struct stat *st)
+static int check_adfile(const char *fname, const struct stat *st, const char **newname)
 {
-    int ret, adflags;
+    int ret;
+    int adflags = ADFLAGS_HF;
     struct adouble ad;
-    char *adname;
+    const char *adname;
 
+    *newname = NULL;
+
+    if (myvol->v_adouble == AD_VERSION_EA) {
+        if (!(dbd_flags & DBD_FLAGS_V2TOEA))
+            return 0;
+        if (ad_convert(fname, st, myvol, newname) != 0) {
+            switch (errno) {
+            case ENOENT:
+                break;
+            default:
+                dbd_log(LOGSTD, "Conversion error for \"%s/%s\": %s", cwdbuf, fname, strerror(errno));
+                break;
+            }
+        }
+        return 0;
+    }
+    
     if (dbd_flags & DBD_FLAGS_CLEANUP)
         return 0;
 
-    if (S_ISREG(st->st_mode))
-        adflags = 0;
-    else
-        adflags = ADFLAGS_DIR;
+    if (S_ISDIR(st->st_mode))
+        adflags |= ADFLAGS_DIR;
 
-    adname = myvolinfo->ad_path(fname, adflags);
+    adname = myvol->ad_path(fname, adflags);
 
     if ((ret = access( adname, F_OK)) != 0) {
         if (errno != ENOENT) {
@@ -320,9 +280,9 @@ static int check_adfile(const char *fname, const struct stat *st)
             return -1;
 
         /* Create ad file */
-        ad_init(&ad, myvolinfo->v_adouble, myvolinfo->v_ad_options);
+        ad_init(&ad, myvol);
 
-        if ((ret = ad_open_metadata( fname, adflags, O_CREAT, &ad)) != 0) {
+        if ((ret = ad_open(&ad, fname, adflags | ADFLAGS_CREATE | ADFLAGS_RDWR, 0666)) != 0) {
             dbd_log( LOGSTD, "Error creating AppleDouble file '%s/%s': %s",
                      cwdbuf, adname, strerror(errno));
 
@@ -332,7 +292,7 @@ static int check_adfile(const char *fname, const struct stat *st)
         /* Set name in ad-file */
         ad_setname(&ad, utompath((char *)fname));
         ad_flush(&ad);
-        ad_close_metadata(&ad);
+        ad_close(&ad, ADFLAGS_HF);
 
         chown(adname, st->st_uid, st->st_gid);
         /* FIXME: should we inherit mode too here ? */
@@ -340,12 +300,12 @@ static int check_adfile(const char *fname, const struct stat *st)
         chmod(adname, st->st_mode);
 #endif
     } else {
-        ad_init(&ad, myvolinfo->v_adouble, myvolinfo->v_ad_options);
-        if (ad_open_metadata( fname, adflags, O_RDONLY, &ad) != 0) {
+        ad_init(&ad, myvol);
+        if (ad_open(&ad, fname, adflags | ADFLAGS_RDONLY) != 0) {
             dbd_log( LOGSTD, "Error opening AppleDouble file for '%s/%s'", cwdbuf, fname);
             return -1;
         }
-        ad_close_metadata(&ad);
+        ad_close(&ad, ADFLAGS_HF);
     }
     return 0;
 }
@@ -409,7 +369,7 @@ static int check_eafiles(const char *fname)
     struct stat st;
     char *eaname;
 
-    if ((ret = ea_open(&volume, fname, EA_RDWR, &ea)) != 0) {
+    if ((ret = ea_open(myvol, fname, EA_RDWR, &ea)) != 0) {
         if (errno == ENOENT)
             return 0;
         dbd_log(LOGSTD, "Error calling ea_open for file: %s/%s, removing EA files", cwdbuf, fname);
@@ -465,6 +425,9 @@ static int check_addir(int volroot)
     if (dbd_flags & DBD_FLAGS_CLEANUP)
         return 0;
 
+    if (myvol->v_adouble == AD_VERSION_EA)
+        return 0;
+
     /* Check for ad-dir */
     if ( (addir_ok = access(ADv2_DIRNAME, F_OK)) != 0) {
         if (errno != ENOENT) {
@@ -475,10 +438,10 @@ static int check_addir(int volroot)
     }
 
     /* Check for ".Parent" */
-    if ( (adpar_ok = access(myvolinfo->ad_path(".", ADFLAGS_DIR), F_OK)) != 0) {
+    if ( (adpar_ok = access(myvol->ad_path(".", ADFLAGS_DIR), F_OK)) != 0) {
         if (errno != ENOENT) {
             dbd_log(LOGSTD, "Access error on '%s/%s': %s",
-                    cwdbuf, myvolinfo->ad_path(".", ADFLAGS_DIR), strerror(errno));
+                    cwdbuf, myvol->ad_path(".", ADFLAGS_DIR), strerror(errno));
             return -1;
         }
         dbd_log(LOGSTD, "Missing .AppleDouble/.Parent for '%s'", cwdbuf);
@@ -497,9 +460,9 @@ static int check_addir(int volroot)
         }
 
         /* Create ad dir and set name */
-        ad_init(&ad, myvolinfo->v_adouble, myvolinfo->v_ad_options);
+        ad_init(&ad, myvol);
 
-        if (ad_open_metadata( ".", ADFLAGS_DIR, O_CREAT, &ad) != 0) {
+        if (ad_open(&ad, ".", ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_CREATE | ADFLAGS_RDWR, 0777) != 0) {
             dbd_log( LOGSTD, "Error creating AppleDouble dir in %s: %s", cwdbuf, strerror(errno));
             return -1;
         }
@@ -510,7 +473,7 @@ static int check_addir(int volroot)
         /* Update name in ad file */
         ad_setname(&ad, mname);
         ad_flush(&ad);
-        ad_close_metadata(&ad);
+        ad_close(&ad, ADFLAGS_HF);
 
         /* Inherit owner/group from "." to ".AppleDouble" and ".Parent" */
         if ((lstat(".", &st)) != 0) {
@@ -518,7 +481,7 @@ static int check_addir(int volroot)
             return -1;
         }
         chown(ADv2_DIRNAME, st.st_uid, st.st_gid);
-        chown(myvolinfo->ad_path(".", ADFLAGS_DIR), st.st_uid, st.st_gid);
+        chown(myvol->ad_path(".", ADFLAGS_DIR), st.st_uid, st.st_gid);
     }
 
     return 0;
@@ -537,7 +500,7 @@ static int check_eafile_in_adouble(const char *name)
     char *namep, *namedup = NULL;
 
     /* Check if this is an AFPVOL_EA_AD vol */
-    if (myvolinfo->v_vfs_ea == AFPVOL_EA_AD) {
+    if (myvol->v_vfs_ea == AFPVOL_EA_AD) {
         /* Does the filename contain "::EA" ? */
         namedup = strdup(name);
         if ((namep = strstr(namedup, "::EA")) == NULL) {
@@ -596,6 +559,9 @@ static int read_addir(void)
     struct stat st;
 
     if ((chdir(ADv2_DIRNAME)) != 0) {
+        if (myvol->v_adouble == AD_VERSION_EA) {
+            return 0;
+        }
         dbd_log(LOGSTD, "Couldn't chdir to '%s/%s': %s",
                 cwdbuf, ADv2_DIRNAME, strerror(errno));
         return -1;
@@ -611,6 +577,7 @@ static int read_addir(void)
         /* Check if its "." or ".." */
         if (DIR_DOT_OR_DOTDOT(ep->d_name))
             continue;
+
         /* Skip ".Parent" */
         if (STRCMP(ep->d_name, ==, ".Parent"))
             continue;
@@ -674,12 +641,14 @@ static int read_addir(void)
 
   @return Correct CNID of object or CNID_INVALID (ie 0) on error
 */
-static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfile_ok, int adflags)
+static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfile_ok)
 {
-    int ret;
+    int ret, adflags = ADFLAGS_HF;
     cnid_t db_cnid, ad_cnid;
     struct adouble ad;
 
+    adflags = ADFLAGS_HF | (S_ISDIR(st->st_mode) ? ADFLAGS_DIR : 0);
+
     /* Force checkout every X items */
     static int cnidcount = 0;
     cnidcount++;
@@ -691,34 +660,37 @@ static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfi
         }
     }
 
-    /* Get CNID from ad-file if volume is using AFPVOL_CACHE */
+    /* Get CNID from ad-file */
     ad_cnid = 0;
-    if ( (myvolinfo->v_flags & AFPVOL_CACHE) && ADFILE_OK) {
-        ad_init(&ad, myvolinfo->v_adouble, myvolinfo->v_ad_options);
-        if (ad_open_metadata( name, adflags, O_RDWR, &ad) != 0) {
+    if (ADFILE_OK) {
+        ad_init(&ad, myvol);
+        if (ad_open(&ad, name, adflags | ADFLAGS_RDWR) != 0) {
             
             if (dbd_flags & DBD_FLAGS_CLEANUP)
                 return CNID_INVALID;
 
-            dbd_log( LOGSTD, "Error opening AppleDouble file for '%s/%s': %s", cwdbuf, name, strerror(errno));
-            return CNID_INVALID;
-        }
-
-        if (dbd_flags & DBD_FLAGS_FORCE) {
-            ad_cnid = ad_forcegetid(&ad);
-            /* This ensures the changed stamp is written */
-            ad_setid( &ad, st->st_dev, st->st_ino, ad_cnid, did, stamp);
-            ad_flush(&ad);
-        }
-        else
-            ad_cnid = ad_getid(&ad, st->st_dev, st->st_ino, 0, stamp);
+            if (myvol->v_adouble != AD_VERSION_EA) {
+                dbd_log( LOGSTD, "Error opening AppleDouble file for '%s/%s': %s", cwdbuf, name, strerror(errno));
+                return CNID_INVALID;
+            }
+            dbd_log( LOGDEBUG, "File without meta EA: \"%s/%s\"", cwdbuf, name);
+            adfile_ok = 1;
+        } else {
 
-        if (ad_cnid == 0)
-            dbd_log( LOGSTD, "Bad CNID in adouble file of '%s/%s'", cwdbuf, name);
-        else
-            dbd_log( LOGDEBUG, "CNID from .AppleDouble file for '%s/%s': %u", cwdbuf, name, ntohl(ad_cnid));
+            if (dbd_flags & DBD_FLAGS_FORCE) {
+                ad_cnid = ad_forcegetid(&ad);
+                /* This ensures the changed stamp is written */
+                ad_setid( &ad, st->st_dev, st->st_ino, ad_cnid, did, stamp);
+                ad_flush(&ad);
+            } else
+                ad_cnid = ad_getid(&ad, st->st_dev, st->st_ino, 0, stamp);
 
-        ad_close_metadata(&ad);
+            if (ad_cnid == 0)
+                dbd_log( LOGSTD, "Bad CNID in adouble file of '%s/%s'", cwdbuf, name);
+            else
+                dbd_log( LOGDEBUG, "CNID from .AppleDouble file for '%s/%s': %u", cwdbuf, name, ntohl(ad_cnid));
+            ad_close(&ad, ADFLAGS_HF);
+        }
     }
 
     /* Get CNID from database */
@@ -728,7 +700,7 @@ static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfi
     memset(&rply, 0, sizeof(struct cnid_dbd_rply));
     rqst.did = did;
     rqst.cnid = ad_cnid;
-    if ( ! (myvolinfo->v_flags & AFPVOL_NODEV))
+    if ( ! (myvol->v_flags & AFPVOL_NODEV))
         rqst.dev = st->st_dev;
     rqst.ino = st->st_ino;
     rqst.type = S_ISDIR(st->st_mode)?1:0;
@@ -760,15 +732,15 @@ static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfi
         if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
             dbd_log(LOGSTD, "Updating AppleDouble file for '%s/%s' with CNID: %u from database",
                             cwdbuf, name, ntohl(db_cnid));
-            ad_init(&ad, myvolinfo->v_adouble, myvolinfo->v_ad_options);
-            if (ad_open_metadata( name, adflags, O_RDWR, &ad) != 0) {
+            ad_init(&ad, myvol);
+            if (ad_open(&ad, name, adflags | ADFLAGS_HF | ADFLAGS_RDWR) != 0) {
                 dbd_log(LOGSTD, "Error opening AppleDouble file for '%s/%s': %s",
                         cwdbuf, name, strerror(errno));
                 return CNID_INVALID;
             }
             ad_setid( &ad, st->st_dev, st->st_ino, db_cnid, did, stamp);
             ad_flush(&ad);
-            ad_close_metadata(&ad);
+            ad_close(&ad, ADFLAGS_HF);
         }
         return db_cnid;
     } else if (ad_cnid && (db_cnid == 0)) {
@@ -788,20 +760,18 @@ static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfi
                 db_cnid = rply.cnid;
                 dbd_log(LOGSTD, "New CNID for '%s/%s': %u", cwdbuf, name, ntohl(db_cnid));
 
-                if ((myvolinfo->v_flags & AFPVOL_CACHE)
-                    && ADFILE_OK
-                    && ( ! (dbd_flags & DBD_FLAGS_SCAN))) {
+                if (ADFILE_OK && ( ! (dbd_flags & DBD_FLAGS_SCAN))) {
                     dbd_log(LOGSTD, "Writing CNID data for '%s/%s' to AppleDouble file",
                             cwdbuf, name, ntohl(db_cnid));
-                    ad_init(&ad, myvolinfo->v_adouble, myvolinfo->v_ad_options);
-                    if (ad_open_metadata( name, adflags, O_RDWR, &ad) != 0) {
+                    ad_init(&ad, myvol);
+                    if (ad_open(&ad, name, adflags | ADFLAGS_RDWR) != 0) {
                         dbd_log(LOGSTD, "Error opening AppleDouble file for '%s/%s': %s",
                                 cwdbuf, name, strerror(errno));
                         return CNID_INVALID;
                     }
                     ad_setid( &ad, st->st_dev, st->st_ino, db_cnid, did, stamp);
                     ad_flush(&ad);
-                    ad_close_metadata(&ad);
+                    ad_close(&ad, ADFLAGS_HF);
                 }
                 return db_cnid;
             }
@@ -828,21 +798,19 @@ static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfi
     }
 
     if ((ad_cnid == 0) && db_cnid) {
-        /* in db but zeroID in ad-file, write it to ad-file if AFPVOL_CACHE */
-        if ((myvolinfo->v_flags & AFPVOL_CACHE) && ADFILE_OK) {
-            if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
-                dbd_log(LOGSTD, "Writing CNID data for '%s/%s' to AppleDouble file",
-                        cwdbuf, name, ntohl(db_cnid));
-                ad_init(&ad, myvolinfo->v_adouble, myvolinfo->v_ad_options);
-                if (ad_open_metadata( name, adflags, O_RDWR, &ad) != 0) {
-                    dbd_log(LOGSTD, "Error opening AppleDouble file for '%s/%s': %s",
-                            cwdbuf, name, strerror(errno));
-                    return CNID_INVALID;
-                }
-                ad_setid( &ad, st->st_dev, st->st_ino, db_cnid, did, stamp);
-                ad_flush(&ad);
-                ad_close_metadata(&ad);
+        /* in db but zeroID in ad-file, write it to ad-file */
+        if (ADFILE_OK && ! (dbd_flags & DBD_FLAGS_SCAN)) {            
+            dbd_log(LOGSTD, "Writing CNID data for '%s/%s' to AppleDouble file",
+                    cwdbuf, name, ntohl(db_cnid));
+            ad_init(&ad, myvol);
+            if (ad_open(&ad, name, adflags | ADFLAGS_RDWR) != 0) {
+                dbd_log(LOGSTD, "Error opening AppleDouble file for '%s/%s': %s",
+                        cwdbuf, name, strerror(errno));
+                return CNID_INVALID;
             }
+            ad_setid( &ad, st->st_dev, st->st_ino, db_cnid, did, stamp);
+            ad_flush(&ad);
+            ad_close(&ad, ADFLAGS_HF);
         }
         return db_cnid;
     }
@@ -858,7 +826,7 @@ static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfi
 */
 static int dbd_readdir(int volroot, cnid_t did)
 {
-    int cwd, ret = 0, adflags, adfile_ok, addir_ok, encoding_ok;
+    int cwd, ret = 0, adfile_ok, addir_ok, encoding_ok;
     cnid_t cnid = 0;
     const char *name;
     DIR *dp;
@@ -911,6 +879,11 @@ static int dbd_readdir(int volroot, cnid_t did)
         if (STRCMP(ep->d_name, == , ADv2_DIRNAME))
             continue;
 
+        if (!myvol->vfs->vfs_validupath(myvol, ep->d_name)) {
+            dbd_log(LOGDEBUG, "Ignoring \"%s\"", ep->d_name);
+            continue;
+        }
+
         if ((ret = lstat(ep->d_name, &st)) < 0) {
             dbd_log( LOGSTD, "Lost file while reading dir '%s/%s', probably removed: %s",
                      cwdbuf, ep->d_name, strerror(errno));
@@ -919,20 +892,10 @@ static int dbd_readdir(int volroot, cnid_t did)
         
         switch (st.st_mode & S_IFMT) {
         case S_IFREG:
-            adflags = 0;
-            break;
         case S_IFDIR:
-            adflags = ADFLAGS_DIR;
             break;
         case S_IFLNK:
             dbd_log(LOGDEBUG, "Ignoring symlink %s/%s", cwdbuf, ep->d_name);
-#if 0
-            ret = check_symlink(ep->d_name, &adflags);
-            if (ret == 1)
-                break;
-            if (ret == -1)
-                dbd_log(LOGSTD, "Error checking symlink %s/%s", cwdbuf, ep->d_name);
-#endif
             continue;
         default:
             dbd_log(LOGSTD, "Bad filetype: %s/%s", cwdbuf, ep->d_name);
@@ -964,21 +927,21 @@ static int dbd_readdir(int volroot, cnid_t did)
            Tests
         **************************************************************************/
 
-        /* Check encoding */
-        if ( -1 == (encoding_ok = check_name_encoding(ep->d_name)) ) {
-            /* If its a file: skipp all other tests now ! */
-            /* For dirs we could try to get a CNID for it and recurse, but currently I prefer not to */
-            continue;
-        }
-
         /* Check for appledouble file, create if missing, but only if we have addir */
+        const char *name = NULL;
         adfile_ok = -1;
         if (ADDIR_OK)
-            adfile_ok = check_adfile(ep->d_name, &st);
+            adfile_ok = check_adfile(ep->d_name, &st, &name);
+
+        if (name == NULL) {
+            name = ep->d_name;
+        } else {
+            update_cnid(did, &st, ep->d_name, name);
+        }
 
         if ( ! nocniddb) {
             /* Check CNIDs */
-            cnid = check_cnid(ep->d_name, did, &st, adfile_ok, adflags);
+            cnid = check_cnid(name, did, &st, adfile_ok);
 
             /* Now add this object to our rebuild dbd */
             if (cnid && dbd_rebuild) {
@@ -989,7 +952,7 @@ static int dbd_readdir(int volroot, cnid_t did)
                     return -1;
                 if (rply.result != CNID_DBD_RES_OK) {
                     dbd_log( LOGSTD, "Fatal error adding CNID: %u for '%s/%s' to in-memory rebuild-db",
-                             cnid, cwdbuf, ep->d_name);
+                             cnid, cwdbuf, name);
                     return -1;
                 }
                 count++;
@@ -1004,21 +967,21 @@ static int dbd_readdir(int volroot, cnid_t did)
         }
 
         /* Check EA files */
-        if (myvolinfo->v_vfs_ea == AFPVOL_EA_AD)
-            check_eafiles(ep->d_name);
+        if (myvol->v_vfs_ea == AFPVOL_EA_AD)
+            check_eafiles(name);
 
         /**************************************************************************
           Recursion
         **************************************************************************/
         if (S_ISDIR(st.st_mode) && (cnid || nocniddb)) { /* If we have no cnid for it we cant recur */
             strcat(cwdbuf, "/");
-            strcat(cwdbuf, ep->d_name);
+            strcat(cwdbuf, name);
             dbd_log( LOGDEBUG, "Entering directory: %s", cwdbuf);
             if (-1 == (cwd = open(".", O_RDONLY))) {
                 dbd_log( LOGSTD, "Cant open directory '%s': %s", cwdbuf, strerror(errno));
                 continue;
             }
-            if (0 != chdir(ep->d_name)) {
+            if (0 != chdir(name)) {
                 dbd_log( LOGSTD, "Cant chdir to directory '%s': %s", cwdbuf, strerror(errno));
                 close(cwd);
                 continue;
@@ -1037,36 +1000,48 @@ static int dbd_readdir(int volroot, cnid_t did)
     /*
       Use results of previous checks
     */
-
+    if ((myvol->v_adouble == AD_VERSION_EA) && (dbd_flags & DBD_FLAGS_V2TOEA)) {
+        if (rmdir(ADv2_DIRNAME) != 0) {
+            switch (errno) {
+            case ENOENT:
+                break;
+            default:
+                dbd_log(LOGSTD, "Error removing adouble dir \"%s/%s\": %s", cwdbuf, ADv2_DIRNAME, strerror(errno));
+                break;
+            }
+        }
+    }
     closedir(dp);
     return ret;
 }
 
-static int scanvol(struct volinfo *vi, dbd_flags_t flags)
+static int scanvol(struct vol *vol, dbd_flags_t flags)
 {
-    /* Dont scanvol on no-appledouble vols */
-    if (vi->v_flags & AFPVOL_NOADOUBLE) {
-        dbd_log( LOGSTD, "Volume without AppleDouble support: skipping volume scanning.");
-        return 0;
-    }
+    struct stat st;
 
     /* Make this stuff accessible from all funcs easily */
-    myvolinfo = vi;
+    myvol = vol;
     dbd_flags = flags;
 
-    /* Init a fake struct vol with just enough so we can call ea_open and friends */
-    volume.v_adouble = AD_VERSION2;
-    volume.v_vfs_ea = myvolinfo->v_vfs_ea;
-    initvol_vfs(&volume);
-
     /* Run with umask 0 */
     umask(0);
 
-    /* Remove trailing slash from volume, chdir to vol */
-    if (myvolinfo->v_path[strlen(myvolinfo->v_path) - 1] == '/')
-        myvolinfo->v_path[strlen(myvolinfo->v_path) - 1] = 0;
-    strcpy(cwdbuf, myvolinfo->v_path);
-    chdir(myvolinfo->v_path);
+    strcpy(cwdbuf, myvol->v_path);
+    chdir(myvol->v_path);
+
+    if ((myvol->v_adouble == AD_VERSION_EA) && (dbd_flags & DBD_FLAGS_V2TOEA)) {
+        if (lstat(".", &st) != 0)
+            return -1;
+        if (ad_convert(".", &st, vol, NULL) != 0) {
+            switch (errno) {
+            case ENOENT:
+                break;
+            default:
+                dbd_log(LOGSTD, "Conversion error for \"%s\": %s", myvol->v_path, strerror(errno));
+                break;
+            }
+        }
+    }
 
     /* Start recursion */
     if (dbd_readdir(1, htonl(2)) < 0)  /* 2 = volumeroot CNID */
@@ -1189,7 +1164,7 @@ static const char *get_tmpdb_path(void)
 /*
   Main func called from cmd_dbd.c
 */
-int cmd_dbd_scanvol(DBD *dbd_ref, struct volinfo *vi, dbd_flags_t flags)
+int cmd_dbd_scanvol(DBD *dbd_ref, struct vol *vol, dbd_flags_t flags)
 {
     int ret = 0;
     struct db_param db_param = { 0 };
@@ -1205,8 +1180,8 @@ int cmd_dbd_scanvol(DBD *dbd_ref, struct volinfo *vi, dbd_flags_t flags)
     dbd = dbd_ref;
 
     /* We only support unicode volumes ! */
-    if ( vi->v_volcharset != CH_UTF8) {
-        dbd_log( LOGSTD, "Not a Unicode volume: %s, %u != %u", vi->v_volcodepage, vi->v_volcharset, CH_UTF8);
+    if (vol->v_volcharset != CH_UTF8) {
+        dbd_log( LOGSTD, "Not a Unicode volume: %s, %u != %u", vol->v_volcodepage, vol->v_volcharset, CH_UTF8);
         return -1;
     }
 
@@ -1250,7 +1225,7 @@ int cmd_dbd_scanvol(DBD *dbd_ref, struct volinfo *vi, dbd_flags_t flags)
     }
 
     /* scanvol */
-    if ( (scanvol(vi, flags)) != 0) {
+    if ((scanvol(vol, flags)) != 0) {
         ret = -1;
         goto exit;
     }
index f44d70b89b9c7c905f372ed15a3b9eb0074a4d88..dcf7d5faaa78b89fb68f866a979d3f5c55d7b4af 100644 (file)
@@ -44,7 +44,7 @@
 #include <sys/wait.h>
 #include <sys/uio.h>
 #include <sys/un.h>
-#define _XPG4_2 1
+// #define _XPG4_2 1
 #include <sys/socket.h>
 #include <stdio.h>
 #include <time.h>
 #include <atalk/logger.h>
 #include <atalk/cnid_dbd_private.h>
 #include <atalk/paths.h>
-#include <atalk/volinfo.h>
+#include <atalk/compat.h>
+#include <atalk/errchk.h>
+#include <atalk/bstrlib.h>
+#include <atalk/netatalk_conf.h>
+#include <atalk/volume.h>
 
 #include "usockfd.h"
 
@@ -109,7 +113,7 @@ static uint maxvol;
 #define DEFAULTPORT  "4700"
 
 struct server {
-    struct volinfo *volinfo;
+    char *v_path;
     pid_t pid;
     time_t tm;                    /* When respawned last */
     unsigned int count;           /* Times respawned in the last TESTTIME secondes */
@@ -118,21 +122,19 @@ struct server {
 
 static struct server srv[MAXVOLS];
 
-/* Default logging config: log to syslog with level log_note */
-static char logconfig[MAXPATHLEN + 21 + 1] = "default log_note";
-
 static void daemon_exit(int i)
 {
-    server_unlock(_PATH_CNID_METAD_LOCK);
     exit(i);
 }
 
 /* ------------------ */
-static void sigterm_handler(int sig)
+static void sig_handler(int sig)
 {
     switch( sig ) {
-    case SIGTERM :
-        LOG(log_info, logtype_afpd, "shutting down on signal %d", sig );
+    case SIGTERM:
+    case SIGQUIT:
+        LOG(log_note, logtype_afpd, "shutting down on %s",
+            sig == SIGTERM ? "SIGTERM" : "SIGQUIT");
         break;
     default :
         LOG(log_error, logtype_afpd, "unexpected signal: %d", sig);
@@ -140,19 +142,20 @@ static void sigterm_handler(int sig)
     daemon_exit(0);
 }
 
-static struct server *test_usockfn(struct volinfo *volinfo)
+static struct server *test_usockfn(const char *path)
 {
     int i;
+
     for (i = 0; i < maxvol; i++) {
-        if ((srv[i].volinfo) && (strcmp(srv[i].volinfo->v_path, volinfo->v_path) == 0)) {
+        if (srv[i].v_path && STRCMP(path, ==, srv[i].v_path))
             return &srv[i];
-        }
     }
+
     return NULL;
 }
 
 /* -------------------- */
-static int maybe_start_dbd(char *dbdpn, struct volinfo *volinfo)
+static int maybe_start_dbd(const AFPObj *obj, char *dbdpn, const char *volpath)
 {
     pid_t pid;
     struct server *up;
@@ -161,13 +164,13 @@ static int maybe_start_dbd(char *dbdpn, struct volinfo *volinfo)
     time_t t;
     char buf1[8];
     char buf2[8];
-    char *volpath = volinfo->v_path;
 
-    LOG(log_debug, logtype_cnid, "maybe_start_dbd: Volume: \"%s\"", volpath);
+    LOG(log_debug, logtype_cnid, "maybe_start_dbd(\"%s\"): BEGIN", volpath);
 
-    up = test_usockfn(volinfo);
+    up = test_usockfn(volpath);
     if (up && up->pid) {
         /* we already have a process, send our fd */
+        LOG(log_debug, logtype_cnid, "maybe_start_dbd: cnid_dbd[%d] already serving", up->pid);
         if (send_fd(up->control_fd, rqstfd) < 0) {
             /* FIXME */
             return -1;
@@ -175,16 +178,16 @@ static int maybe_start_dbd(char *dbdpn, struct volinfo *volinfo)
         return 0;
     }
 
-    LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: no cnid_dbd for that volume yet");
+    LOG(log_debug, logtype_cnid, "maybe_start_dbd: no cnid_dbd serving yet");
 
     time(&t);
     if (!up) {
         /* find an empty slot (i < maxvol) or the first free slot (i == maxvol)*/
         for (i = 0; i <= maxvol; i++) {
-            if (srv[i].volinfo == NULL && i < MAXVOLS) {
+            if (srv[i].v_path == NULL && i < MAXVOLS) {
                 up = &srv[i];
-                up->volinfo = volinfo;
-                retainvolinfo(volinfo);
+                if ((up->v_path = strdup(volpath)) == NULL)
+                    return -1;
                 up->tm = t;
                 up->count = 0;
                 if (i == maxvol)
@@ -261,10 +264,10 @@ static int maybe_start_dbd(char *dbdpn, struct volinfo *volinfo)
             /* there's a pb with the db inform child, it will delete the db */
             LOG(log_warning, logtype_cnid,
                 "Multiple attempts to start CNID db daemon for \"%s\" failed, wiping the slate clean...",
-                up->volinfo->v_path);
-            ret = execlp(dbdpn, dbdpn, "-d", volpath, buf1, buf2, logconfig, NULL);
+                up->v_path);
+            ret = execlp(dbdpn, dbdpn, "-F", obj->options.configfile, "-p", volpath, "-t", buf1, "-l", buf2, "-d", NULL);
         } else {
-            ret = execlp(dbdpn, dbdpn, volpath, buf1, buf2, logconfig, NULL);
+            ret = execlp(dbdpn, dbdpn, "-F", obj->options.configfile, "-p", volpath, "-t", buf1, "-l", buf2, NULL);
         }
         /* Yikes! We're still here, so exec failed... */
         LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
@@ -280,28 +283,47 @@ static int maybe_start_dbd(char *dbdpn, struct volinfo *volinfo)
 }
 
 /* ------------------ */
-static int set_dbdir(char *dbdir)
+static int set_dbdir(const char *dbdir, const char *vpath)
 {
-    int len;
+    EC_INIT;
+    int status;
     struct stat st;
+    bstring oldpath, newpath;
+    char *cmd_argv[4];
+
+    LOG(log_debug, logtype_cnid, "set_dbdir: volume: %s, db path: %s", vpath, dbdir);
 
-    len = strlen(dbdir);
+    EC_NULL_LOG( oldpath = bformat("%s/%s/", vpath, DBHOME) );
+    EC_NULL_LOG( newpath = bformat("%s/%s/", dbdir, DBHOME) );
 
-    if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
+    if (lstat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
-        return -1;
+        EC_FAIL;
     }
 
-    if (dbdir[len - 1] != '/') {
-        strcat(dbdir, "/");
-        len++;
+    if (lstat(bdata(oldpath), &st) == 0 && lstat(bdata(newpath), &st) != 0 && errno == ENOENT) {
+        /* There's an .AppleDB in the volume root, we move it */
+        cmd_argv[0] = "mv";
+        cmd_argv[1] = bdata(oldpath);
+        cmd_argv[2] = (char *)dbdir;
+        cmd_argv[3] = NULL;
+        if (run_cmd("mv", cmd_argv) != 0) {
+            LOG(log_error, logtype_cnid, "set_dbdir: moving CNID db from \"%s\" to \"%s\" failed",
+                bdata(oldpath), dbdir);
+            EC_FAIL;
+        }
+
     }
-    strcpy(dbdir + len, DBHOME);
-    if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755 ) < 0) {
-        LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
-        return -1;
+
+    if (lstat(bdata(newpath), &st) < 0 && mkdir(bdata(newpath), 0755 ) < 0) {
+        LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", bdata(newpath));
+        EC_FAIL;
     }
-    return 0;
+
+EC_CLEANUP:
+    bdestroy(oldpath);
+    bdestroy(newpath);
+    EC_EXIT;
 }
 
 /* ------------------ */
@@ -365,13 +387,17 @@ static void set_signal(void)
         daemon_exit(EXITERR_SYS);
     }
 
-    /* Catch SIGTERM */
-    sv.sa_handler = sigterm_handler;
+    /* Catch SIGTERM and SIGQUIT */
+    sv.sa_handler = sig_handler;
     sigfillset(&sv.sa_mask );
     if (sigaction(SIGTERM, &sv, NULL ) < 0 ) {
         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
         daemon_exit(EXITERR_SYS);
     }
+    if (sigaction(SIGQUIT, &sv, NULL ) < 0 ) {
+        LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
+        daemon_exit(EXITERR_SYS);
+    }
 
     /* Ignore the rest */
     sv.sa_handler = SIG_IGN;
@@ -408,7 +434,7 @@ static void set_signal(void)
     /* block everywhere but in pselect */
     sigemptyset(&set);
     sigaddset(&set, SIGCHLD);
-    sigprocmask(SIG_BLOCK, &set, NULL);
+    sigprocmask(SIG_SETMASK, &set, NULL);
 }
 
 static int setlimits(void)
@@ -439,8 +465,8 @@ int main(int argc, char *argv[])
     pid_t pid;
     int   status;
     char  *dbdpn = _PATH_CNID_DBD;
-    char  *host = DEFAULTHOST;
-    char  *port = DEFAULTPORT;
+    char  *host;
+    char  *port;
     int    i;
     int    cc;
     uid_t  uid = 0;
@@ -448,89 +474,49 @@ int main(int argc, char *argv[])
     int    err = 0;
     int    debug = 0;
     int    ret;
-    char   *loglevel = NULL;
-    char   *logfile  = NULL;
     sigset_t set;
-    struct volinfo *volinfo;
-
-    set_processname("cnid_metad");
+    AFPObj obj = { 0 };
+    struct vol *vol;
 
-    while (( cc = getopt( argc, argv, "vVds:p:h:u:g:l:f:")) != -1 ) {
+    while (( cc = getopt( argc, argv, "dF:vV")) != -1 ) {
         switch (cc) {
-        case 'v':
-        case 'V':
-            printf("cnid_metad (Netatalk %s)\n", VERSION);
-            return -1;
         case 'd':
             debug = 1;
             break;
-        case 'h':
-            host = strdup(optarg);
-            break;
-        case 'u':
-            uid = user_to_uid (optarg);
-            if (!uid) {
-                LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
-                err++;
-            }
-            break;
-        case 'g':
-            gid =group_to_gid (optarg);
-            if (!gid) {
-                LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
-                err++;
-            }
-            break;
-        case 'p':
-            port = strdup(optarg);
-            break;
-        case 's':
-            dbdpn = strdup(optarg);
-            break;
-        case 'l':
-            loglevel = strdup(optarg);
-            break;
-        case 'f':
-            logfile = strdup(optarg);
+        case 'F':
+            obj.cmdlineconfigfile = strdup(optarg);
             break;
+        case 'v':
+        case 'V':
+            printf("cnid_metad (Netatalk %s)\n", VERSION);
+            return -1;
         default:
-            err++;
-            break;
+            printf("cnid_metad [-dvV] [-F alternate configfile ]\n");
+            return -1;
         }
     }
 
-    /* Check for PID lockfile */
-    if (check_lockfile("cnid_metad", _PATH_CNID_METAD_LOCK))
-        return -1;
-
     if (!debug && daemonize(0, 0) != 0)
         exit(EXITERR_SYS);
 
-    /* Create PID lockfile */
-    if (create_lockfile("cnid_metad", _PATH_CNID_METAD_LOCK))
-        return -1;
-
-    if (loglevel) {
-        strlcpy(logconfig + 8, loglevel, 13);
-        free(loglevel);
-        strcat(logconfig, " ");
-    }
-    if (logfile) {
-        strlcat(logconfig, logfile, MAXPATHLEN);
-        free(logfile);
-    }
-    setuplog(logconfig);
+    if (afp_config_parse(&obj, "cnid_metad") != 0)
+        daemon_exit(1);
 
-    if (err) {
-        LOG(log_error, logtype_cnid, "main: bad arguments");
+    if (load_volumes(&obj, NULL) != 0)
         daemon_exit(1);
-    }
 
     (void)setlimits();
 
+    host = iniparser_getstrdup(obj.iniconfig, INISEC_GLOBAL, "cnid listen", "localhost:4700");
+    if (port = strrchr(host, ':'))
+        *port++ = 0;
+    else
+        port = DEFAULTPORT;
     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
         daemon_exit(1);
 
+    LOG(log_note, logtype_afpd, "CNID Server listening on %s:%s", host, port);
+
     /* switch uid/gid */
     if (uid || gid) {
         LOG(log_debug, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
@@ -574,7 +560,7 @@ int main(int argc, char *argv[])
                 srv[i].count = 0;
             }
             if (WIFSIGNALED(status)) {
-                LOG(log_info, logtype_cnid, "cnid_dbd[%i] received signal %i",
+                LOG(log_info, logtype_cnid, "cnid_dbd[%i] got signal %i",
                     pid, WTERMSIG(status));
             }
             sigchild = 0;
@@ -616,21 +602,25 @@ int main(int argc, char *argv[])
         }
         volpath[len] = '\0';
 
-        /* Load .volinfo file */
-        if ((volinfo = allocvolinfo(volpath)) == NULL) {
-            LOG(log_severe, logtype_cnid, "allocvolinfo(\"%s\"): %s",
-                volpath, strerror(errno));
+        LOG(log_debug, logtype_cnid, "main: request for volume: %s", volpath);
+
+        if (load_volumes(&obj, NULL) != 0) {
+            LOG(log_severe, logtype_cnid, "main: error reloading config");
             goto loop_end;
         }
 
-        if (set_dbdir(volinfo->v_dbpath) < 0) {
+        if ((vol = getvolbypath(&obj, volpath)) == NULL) {
+            LOG(log_severe, logtype_cnid, "main: no volume for path \"%s\"", volpath);
             goto loop_end;
         }
 
-        maybe_start_dbd(dbdpn, volinfo);
+        LOG(log_maxdebug, logtype_cnid, "main: dbpath: %s", vol->v_dbpath);
 
-        (void)closevolinfo(volinfo);
+        if (set_dbdir(vol->v_dbpath, volpath) < 0) {
+            goto loop_end;
+        }
 
+        maybe_start_dbd(&obj, dbdpn, vol->v_path);
     loop_end:
         close(rqstfd);
     }
index 6df044624662f0e678cf079b78f5c196cc5b7481..7cd8f5598c7cff49930ac147f799e7dea1d210bb 100644 (file)
@@ -211,7 +211,7 @@ int comm_rcv(struct cnid_dbd_rqst *rqst, time_t timeout, const sigset_t *sigmask
         return -1;
     }
 
-    nametmp = rqst->name;
+    nametmp = (char *)rqst->name;
     if ((b = readt(cur_fd, rqst, sizeof(struct cnid_dbd_rqst), 1, CNID_DBD_TIMEOUT))
         != sizeof(struct cnid_dbd_rqst)) {
         if (b)
@@ -221,7 +221,7 @@ int comm_rcv(struct cnid_dbd_rqst *rqst, time_t timeout, const sigset_t *sigmask
         return 0;
     }
     rqst->name = nametmp;
-    if (rqst->namelen && readt(cur_fd, rqst->name, rqst->namelen, 1, CNID_DBD_TIMEOUT)
+    if (rqst->namelen && readt(cur_fd, (char *)rqst->name, rqst->namelen, 1, CNID_DBD_TIMEOUT)
         != rqst->namelen) {
         LOG(log_error, logtype_cnid, "error reading message name: %s", strerror(errno));
         invalidate_fd(cur_fd);
@@ -229,7 +229,7 @@ int comm_rcv(struct cnid_dbd_rqst *rqst, time_t timeout, const sigset_t *sigmask
     }
     /* We set this to make life easier for logging. None of the other stuff
        needs zero terminated strings. */
-    rqst->name[rqst->namelen] = '\0';
+    ((char *)(rqst->name))[rqst->namelen] = '\0';
 
     LOG(log_maxdebug, logtype_cnid, "comm_rcv: got %u bytes", b + rqst->namelen);
 
index 37ca4b6758374b906e6e81cd9d9843dd79d1b003..0d6e9b9eb7b2b28d0599886d3c71703defc3e569 100644 (file)
@@ -8,7 +8,6 @@
 #define CNID_DBD_DB_PARAM_H 1
 
 #include <sys/param.h>
-#include <sys/cdefs.h>
 
 #define DEFAULT_LOGFILE_AUTOREMOVE 1
 #define DEFAULT_CACHESIZE          (8 * 1024) /* KB, so 8 MB */
index b4f7e5d4a0013adfa8f50be1825d0e9ed7f664bc..bfa60954037c19bbfca7d998ab34d9725f50792a 100644 (file)
@@ -7,6 +7,8 @@
 #ifndef CNID_DBD_DBD_H
 #define CNID_DBD_DBD_H 1
 
+#include <arpa/inet.h>
+
 #include <atalk/cnid_dbd_private.h>
 
 extern int add_cnid(DBD *dbd, struct cnid_dbd_rqst *rqst, struct cnid_dbd_rply *rply);
index 6a818a3b325063f27fe37a0a412d6081bf6bb0b8..418a10f9da9a22919780b5ade075c5e35eecac1f 100644 (file)
@@ -9,16 +9,10 @@
 #endif /* HAVE_CONFIG_H */
 
 #include <string.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <errno.h>
-#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
-#endif /* HAVE_SYS_TIME_H */
 
 #include <atalk/logger.h>
 #include <atalk/cnid_dbd_private.h>
index 3ea137e463dea4ff23aa12a50ae404966062a162..e621704f9339305aeac21c9e1e35555c65bdcb30 100644 (file)
@@ -9,12 +9,12 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-
 #include <stdio.h>
 #include <string.h>
 #include <sys/param.h>
 #include <errno.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/logger.h>
 #include <atalk/cnid_dbd_private.h>
 
index dbbe521c85f9e1c2b4641188f7f30ee1fc65d46f..a4a3ca63e29a8c58aad3b15a1ace3e66a2793701 100644 (file)
@@ -11,7 +11,8 @@
 
 #include <string.h>
 #include <errno.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/logger.h>
 #include <atalk/cnid_dbd_private.h>
 
index 9c07c40519799f4ad3ef94524a2d6c07c3ba0dea..0ef71b19670c8c734ec34d3f825604559a41e682 100644 (file)
@@ -13,7 +13,8 @@
 #include <sys/param.h>
 #include <atalk/logger.h>
 #include <errno.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/cnid_dbd_private.h>
 
 
index ea75c4aba67799356636162a70c5c0a4194c63a4..b805d42863366310bc803a0178518c6794a0de3b 100644 (file)
@@ -13,7 +13,8 @@
 #include <string.h>
 #include <atalk/logger.h>
 #include <errno.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/cnid_dbd_private.h>
 
 #include "dbif.h"
index cd60223ed80ec5c90d224516971a9bfbdc69149d..6169738b5f66e3230bb55fbb246eb38b08259d0f 100644 (file)
@@ -10,8 +10,8 @@
 CNID salvation spec:
 general rule: better safe then sorry, so we always delete CNIDs and assign
 new ones in case of a lookup mismatch. afpd also sends us the CNID found
-in the adouble file (for AFPVOL_CACHE volumes). In certain cases we can
-use this hint to determince the right CNID.
+in the adouble file. In certain cases we can use this hint to determince
+the right CNID.
 
 
 The lines...
@@ -116,7 +116,8 @@ to be safe we must assign new CNIDs to both files.
 #include <string.h>
 #include <sys/param.h>
 #include <errno.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/logger.h>
 #include <atalk/cnid_dbd_private.h>
 
index f3a93e4ca54d3d9ae03fb3bd0f60771f3551542e..562838b384a28dacc46873f8742a8296a6a2eba1 100644 (file)
 
 #include <stdio.h>
 #include <string.h>
+#include <arpa/inet.h>
+
 #include <atalk/logger.h>
-#include <netatalk/endian.h>
 #include <atalk/cnid_dbd_private.h>
 
-
 #include "pack.h"
 #include "dbif.h"
 #include "dbd.h"
index 1c2e2da914bc0143df5d1c54f523be86c99e5281..bb3561caba7a1018605be36649d85b13abb8ab29 100644 (file)
@@ -12,7 +12,8 @@
 #include <string.h>
 #include <atalk/logger.h>
 #include <errno.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/cnid_dbd_private.h>
 
 #include "dbif.h"
index a2efc33cfa6520071f302ee1f4947c4793638bf0..66979424f868f8507c5ba0368d6c330067cb43a3 100644 (file)
@@ -9,7 +9,8 @@
 
 #include <string.h>
 #include <errno.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/logger.h>
 #include <atalk/cnid_dbd_private.h>
 
@@ -29,7 +30,7 @@ int dbd_search(DBD *dbd, struct cnid_dbd_rqst *rqst, struct cnid_dbd_rply *rply)
     rply->name = resbuf;
     rply->namelen = 0;
 
-    key.data = rqst->name;
+    key.data = (char *)rqst->name;
     key.size = rqst->namelen;
 
     if ((results = dbif_search(dbd, &key, resbuf)) < 0) {
index d2ce83eca388ae6381be8ed2fa030a43dae58f0b..e8abf5d23dd3df7ee946b7ea8e362b2c62b4485e 100644 (file)
@@ -11,7 +11,8 @@
 #include <string.h>
 #include <errno.h>
 #include <atalk/logger.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/cnid_dbd_private.h>
 
 
index fc251a7698241292815c29c85b78bbf3019f103a..e0860cbfdf322faf80badf659e9f4e3bf2a75242 100644 (file)
@@ -14,8 +14,8 @@
 #include <string.h>
 #include <sys/types.h>
 #include <sys/stat.h>
-#include <sys/cdefs.h>
 #include <unistd.h>
+#include <arpa/inet.h>
 
 #include <db.h>
 
index c936a2b93705daf7b5bf1a8061131f7a3174dd37..8c71de36b96221f598f64f4943b0878e7906f444 100644 (file)
@@ -53,7 +53,6 @@
 #ifndef CNID_DBD_DBIF_H
 #define CNID_DBD_DBIF_H 1
 
-#include <sys/cdefs.h>
 #include <db.h>
 #include <atalk/adouble.h>
 #include "db_param.h"
index a4883d8264f6b26d6afb3e5aa627ffc75361a160..8ed0e5ff2bcd37796511c3094689ce3b7dfb6da8 100644 (file)
@@ -8,36 +8,31 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <stdio.h>
 #include <stdlib.h>
 #include <errno.h>
 #include <signal.h>
 #include <string.h>
-#ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
-#endif /* HAVE_SYS_TYPES_H */
 #include <sys/param.h>
-#ifdef HAVE_SYS_STAT_H
 #include <sys/stat.h>
-#endif /* HAVE_SYS_STAT_H */
 #include <time.h>
 #include <sys/file.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/cnid_dbd_private.h>
 #include <atalk/logger.h>
-#include <atalk/volinfo.h>
+#include <atalk/errchk.h>
+#include <atalk/bstrlib.h>
+#include <atalk/netatalk_conf.h>
 
 #include "db_param.h"
 #include "dbif.h"
 #include "dbd.h"
 #include "comm.h"
+#include "pack.h"
 
 /* 
    Note: DB_INIT_LOCK is here so we can run the db_* utilities while netatalk is running.
@@ -45,9 +40,6 @@
  */
 #define DBOPTIONS (DB_CREATE | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_LOCK | DB_INIT_TXN)
 
-/* Global, needed by pack.c:idxname() */
-struct volinfo volinfo;
-
 static DBD *dbd;
 static int exit_sig = 0;
 static int db_locked;
@@ -281,77 +273,79 @@ static void set_signal(void)
 /* ------------------------ */
 int main(int argc, char *argv[])
 {
+    EC_INIT;
     struct db_param *dbp;
-    int err = 0, ret, delete_bdb = 0;
-    int ctrlfd, clntfd;
+    int delete_bdb = 0;
+    int ctrlfd = -1, clntfd = -1;
     char *logconfig;
+    AFPObj obj = { 0 };
+    struct vol *vol;
+    char *volpath = NULL;
+    bstring dbpath;
 
-    set_processname("cnid_dbd");
-
-    while (( ret = getopt( argc, argv, "vVd")) != -1 ) {
+    while (( ret = getopt( argc, argv, "dF:l:p:t:vV")) != -1 ) {
         switch (ret) {
+        case 'd':
+            delete_bdb = 1;
+            break;
+        case 'F':
+            obj.cmdlineconfigfile = strdup(optarg);
+            break;
+        case 'p':
+            volpath = strdup(optarg);
+            break;
+        case 'l':
+            clntfd = atoi(optarg);
+            break;
+        case 't':
+            ctrlfd = atoi(optarg);
+            break;
         case 'v':
         case 'V':
             printf("cnid_dbd (Netatalk %s)\n", VERSION);
             return -1;
-        case 'd':
-            delete_bdb = 1;
-            break;
         }
     }
 
-    if (argc - optind != 4) {
-        LOG(log_error, logtype_cnid, "main: not enough arguments");
+    if (ctrlfd == -1 || clntfd == -1 || !volpath) {
+        LOG(log_error, logtype_cnid, "main: bad IPC fds");
         exit(EXIT_FAILURE);
     }
 
-    /* Load .volinfo file */
-    if (loadvolinfo(argv[optind], &volinfo) == -1) {
-        LOG(log_error, logtype_cnid, "Cant load volinfo for \"%s\"", argv[1]);
-        exit(EXIT_FAILURE);
-    }
-    /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
-    char dbpath[MAXPATHLEN+1];
-    if ((strlen(volinfo.v_dbpath) + strlen("/.AppleDB")) > MAXPATHLEN ) {
-        LOG(log_error, logtype_cnid, "CNID db pathname too long: \"%s\"", volinfo.v_dbpath);
-        exit(EXIT_FAILURE);
-    }
-    strncpy(dbpath, volinfo.v_dbpath, MAXPATHLEN - strlen("/.AppleDB"));
-    strcat(dbpath, "/.AppleDB");
+    EC_ZERO( afp_config_parse(&obj, "cnid_dbd") );
 
-    ctrlfd = atoi(argv[optind + 1]);
-    clntfd = atoi(argv[optind + 2]);
-    logconfig = strdup(argv[optind + 3]);
-    setuplog(logconfig);
+    EC_ZERO( load_volumes(&obj, NULL) );
+    EC_NULL( vol = getvolbypath(&obj, volpath) );
+    EC_ZERO( load_charset(vol) );
+    pack_setvol(vol);
 
-    if (vol_load_charsets(&volinfo) == -1) {
-        LOG(log_error, logtype_cnid, "Error loading charsets!");
-        exit(EXIT_FAILURE);
-    }
-    LOG(log_debug, logtype_cnid, "db dir: \"%s\"", dbpath);
+    EC_NULL( dbpath = bfromcstr(vol->v_dbpath) );
+    EC_ZERO( bcatcstr(dbpath, "/.AppleDB") );
 
-    switch_to_user(dbpath);
+    LOG(log_debug, logtype_cnid, "db dir: \"%s\"", bdata(dbpath));
+
+    switch_to_user(bdata(dbpath));
 
     /* Get db lock */
-    if ((db_locked = get_lock(LOCK_EXCL, dbpath)) == -1) {
+    if ((db_locked = get_lock(LOCK_EXCL, bdata(dbpath))) == -1) {
         LOG(log_error, logtype_cnid, "main: fatal db lock error");
-        exit(1);
+        EC_FAIL;
     }
     if (db_locked != LOCK_EXCL) {
         /* Couldn't get exclusive lock, try shared lock  */
         if ((db_locked = get_lock(LOCK_SHRD, NULL)) != LOCK_SHRD) {
             LOG(log_error, logtype_cnid, "main: fatal db lock error");
-            exit(1);
+            EC_FAIL;
         }
     }
 
     if (delete_bdb && (db_locked == LOCK_EXCL)) {
         LOG(log_warning, logtype_cnid, "main: too many CNID db opening attempts, wiping the slate clean");
-        chdir(dbpath);
+        chdir(bdata(dbpath));
         system("rm -f cnid2.db lock log.* __db.*");
-        if ((db_locked = get_lock(LOCK_EXCL, dbpath)) != LOCK_EXCL) {
+        if ((db_locked = get_lock(LOCK_EXCL, bdata(dbpath))) != LOCK_EXCL) {
             LOG(log_error, logtype_cnid, "main: fatal db lock error");
-            exit(EXIT_FAILURE);
+            EC_FAIL;
         }
     }
 
@@ -360,59 +354,66 @@ int main(int argc, char *argv[])
     /* SIGINT and SIGTERM are always off, unless we are in pselect */
     block_sigs_onoff(1);
 
-    if ((dbp = db_param_read(dbpath)) == NULL)
-        exit(1);
+    if ((dbp = db_param_read(bdata(dbpath))) == NULL)
+        EC_FAIL;
     LOG(log_maxdebug, logtype_cnid, "Finished parsing db_param config file");
 
-    if (NULL == (dbd = dbif_init(dbpath, "cnid2.db")))
-        exit(2);
+    if (NULL == (dbd = dbif_init(bdata(dbpath), "cnid2.db")))
+        EC_FAIL;
 
     /* Only recover if we got the lock */
     if (dbif_env_open(dbd,
                       dbp,
                       (db_locked == LOCK_EXCL) ? DBOPTIONS | DB_RECOVER : DBOPTIONS) < 0)
-        exit(2); /* FIXME: same exit code as failure for dbif_open() */
+        EC_FAIL;
     LOG(log_debug, logtype_cnid, "Finished initializing BerkeleyDB environment");
 
     if (dbif_open(dbd, dbp, 0) < 0) {
-        dbif_close(dbd);
-        exit(2);
+        ret = -1;
+        goto close_db;
     }
+
     LOG(log_debug, logtype_cnid, "Finished opening BerkeleyDB databases");
 
     /* Downgrade db lock  */
     if (db_locked == LOCK_EXCL) {
         if (get_lock(LOCK_UNLOCK, NULL) != 0) {
-            dbif_close(dbd);
-            exit(2);
+            ret = -1;
+            goto close_db;
         }
+
         if (get_lock(LOCK_SHRD, NULL) != LOCK_SHRD) {
-            dbif_close(dbd);
-            exit(2);
+            ret = -1;
+            goto close_db;
         }
     }
 
 
     if (comm_init(dbp, ctrlfd, clntfd) < 0) {
-        dbif_close(dbd);
-        exit(3);
+        ret = -1;
+        goto close_db;
     }
 
-    if (loop(dbp) < 0)
-        err++;
+    if (loop(dbp) < 0) {
+        ret = -1;
+        goto close_db;
+    }
 
+close_db:
     if (dbif_close(dbd) < 0)
-        err++;
+        ret = -1;
+
+    if (dbif_env_remove(bdata(dbpath)) < 0)
+        ret = -1;
 
-    if (dbif_env_remove(dbpath) < 0)
-        err++;
+EC_CLEANUP:
+    if (ret != 0)
+        exit(1);
 
-    if (err)
-        exit(4);
-    else if (exit_sig)
+    if (exit_sig)
         LOG(log_info, logtype_cnid, "main: Exiting on signal %i", exit_sig);
     else
         LOG(log_info, logtype_cnid, "main: Idle timeout, exiting");
 
-    return 0;
+    EC_EXIT;
 }
index 2612469415eaa5582d71712bca82dc5b63c33770..2e9a32eec6a62234ad6cee93f084794d9accd620 100644 (file)
@@ -8,22 +8,20 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 
 #include <string.h>
 #include <inttypes.h>
 #include <sys/param.h>
-#include <sys/cdefs.h>
 #include <db.h>
 
 #include <atalk/unicode.h>
-#include <atalk/volinfo.h>
 #include <atalk/logger.h>
 #include <atalk/cnid_dbd_private.h>
+#include <atalk/volume.h>
 #include "pack.h"
 
-/* in main.c for `cnid_dbd` or cmd_dbd.c for `dbd` */
-extern struct volinfo volinfo;
+static const struct vol *volume;
 
 /* --------------- */
 /*
@@ -82,9 +80,9 @@ int idxname(DB *dbp _U_, const DBT *pkey _U_,  const DBT *pdata, DBT *skey)
     uint16_t flags = CONV_TOLOWER;
     memset(skey, 0, sizeof(DBT));
 
-    if (convert_charset(volinfo.v_volcharset,
-                        volinfo.v_volcharset,
-                        volinfo.v_maccharset,
+    if (convert_charset(volume->v_volcharset,
+                        volume->v_volcharset,
+                        volume->v_maccharset,
                         (char *)pdata->data + CNID_NAME_OFS,
                         strlen((char *)pdata->data + CNID_NAME_OFS),
                         buffer,
@@ -98,6 +96,11 @@ int idxname(DB *dbp _U_, const DBT *pkey _U_,  const DBT *pdata, DBT *skey)
     return (0);
 }
 
+void pack_setvol(const struct vol *vol)
+{
+    volume = vol;
+}
+
 /* The equivalent to make_cnid_data in the cnid library. Non re-entrant. We
    differ from make_cnid_data in that we never return NULL, rqst->name cannot
    ever cause start[] to overflow because name length is checked in libatalk. */
index fc3d65b1575b584c180e0fe06cb3da3955f87c49..9894d49a0a32a38aa27b2549227517b404af4d10 100644 (file)
@@ -14,5 +14,5 @@ extern unsigned char *pack_cnid_data(struct cnid_dbd_rqst *);
 extern int didname(DB *dbp, const DBT *pkey, const DBT *pdata, DBT *skey);
 extern int devino(DB *dbp, const DBT *pkey, const DBT *pdata, DBT *skey);
 extern int idxname(DB *dbp, const DBT *pkey, const DBT *pdata, DBT *skey);
-
+extern void pack_setvol(const struct vol *vol);
 #endif /* CNID_DBD_PACK_H */
index 0b119209cf987929f3e268f441584a5d95619d6e..f5cdea4d22fa7c7ecd80e3ff1461f0d9dfa4c8f1 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <sys/un.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
 #include <netdb.h>
-
-#ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
-#endif /* HAVE_SYS_TYPES_H */
-#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
-#endif /* HAVE_SYS_TIME_H */
-
 
 #include <atalk/logger.h>
 #include <atalk/compat.h>
@@ -93,7 +85,7 @@ int tsockfd_create(char *host, char *port, int backlog)
     hints.ai_socktype = SOCK_STREAM;
 
     if ((ret = getaddrinfo(host, port, &hints, &servinfo)) != 0) {
-        LOG(log_error, logtype_default, "tsockfd_create: getaddrinfo: %s\n", gai_strerror(ret));
+        LOG(log_error, logtype_cnid, "tsockfd_create: getaddrinfo: %s\n", gai_strerror(ret));
         return 0;
     }
 
@@ -101,7 +93,7 @@ int tsockfd_create(char *host, char *port, int backlog)
     /* loop through all the results and bind to the first we can */
     for (p = servinfo; p != NULL; p = p->ai_next) {
         if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
-            LOG(log_info, logtype_default, "tsockfd_create: socket: %s", strerror(errno));
+            LOG(log_info, logtype_cnid, "tsockfd_create: socket: %s", strerror(errno));
             continue;
         }
 
@@ -125,13 +117,13 @@ int tsockfd_create(char *host, char *port, int backlog)
             
         if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
             close(sockfd);
-            LOG(log_info, logtype_default, "tsockfd_create: bind: %s\n", strerror(errno));
+            LOG(log_info, logtype_cnid, "tsockfd_create: bind: %s\n", strerror(errno));
             continue;
         }
 
         if (listen(sockfd, backlog) < 0) {
             close(sockfd);
-            LOG(log_info, logtype_default, "tsockfd_create: listen: %s\n", strerror(errno));
+            LOG(log_info, logtype_cnid, "tsockfd_create: listen: %s\n", strerror(errno));
             continue;
         }
 
@@ -140,7 +132,7 @@ int tsockfd_create(char *host, char *port, int backlog)
     }
 
     if (p == NULL)  {
-        LOG(log_error, logtype_default, "tsockfd_create: no suitable network config %s:%s", host, port);
+        LOG(log_error, logtype_cnid, "tsockfd_create: no suitable network config %s:%s", host, port);
         freeaddrinfo(servinfo);
         return -1;
     }
diff --git a/etc/netatalk/.gitignore b/etc/netatalk/.gitignore
new file mode 100644 (file)
index 0000000..7e242d0
--- /dev/null
@@ -0,0 +1,6 @@
+Makefile
+Makefile.in
+netatalk
+.deps
+.libs
+*.o
diff --git a/etc/netatalk/Makefile.am b/etc/netatalk/Makefile.am
new file mode 100644 (file)
index 0000000..10f90ce
--- /dev/null
@@ -0,0 +1,23 @@
+# Makefile.am for etc/netatlk/
+
+pkgconfdir = @PKGCONFDIR@
+
+sbin_PROGRAMS = netatalk
+
+netatalk_SOURCES = netatalk.c
+netatalk_CFLAGS = \
+       -D_PATH_CONFDIR=\"$(pkgconfdir)/\" \
+       -D_PATH_AFPD=\"$(sbindir)/afpd\" \
+       -D_PATH_CNID_METAD=\"$(sbindir)/cnid_metad\"
+
+netatalk_LDADD = \
+       $(top_builddir)/libatalk/libatalk.la
+
+if USE_BUILTIN_LIBEVENT
+netatalk_CFLAGS += \
+       -I$(top_srcdir)/libevent/include \
+       -I$(top_builddir)/libevent/include
+
+netatalk_LDADD += \
+       $(top_builddir)/libevent/libevent.la
+endif
\ No newline at end of file
diff --git a/etc/netatalk/netatalk.c b/etc/netatalk/netatalk.c
new file mode 100644 (file)
index 0000000..b35d264
--- /dev/null
@@ -0,0 +1,330 @@
+/*
+ * Copyright (c) 1990,1993 Regents of The University of Michigan.
+ * All Rights Reserved.  See COPYRIGHT.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <sys/param.h>
+#include <sys/uio.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+#include <sys/poll.h>
+#include <errno.h>
+#include <sys/wait.h>
+#include <sys/resource.h>
+
+#include <atalk/logger.h>
+#include <atalk/adouble.h>
+#include <atalk/compat.h>
+#include <atalk/dsi.h>
+#include <atalk/afp.h>
+#include <atalk/paths.h>
+#include <atalk/util.h>
+#include <atalk/server_child.h>
+#include <atalk/server_ipc.h>
+#include <atalk/errchk.h>
+#include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
+
+#include <event2/event.h>
+
+/* how many seconds we wait to shutdown from SIGTERM before we send SIGKILL */
+#define KILL_GRACETIME 5
+
+/* forward declaration */
+static pid_t run_process(const char *path, ...);
+static void kill_childs(int sig, ...);
+
+/* static variables */
+static AFPObj obj;
+static sig_atomic_t got_chldsig;
+static pid_t afpd_pid = -1,  cnid_metad_pid = -1;
+static uint afpd_restarts, cnid_metad_restarts;
+static struct event_base *base;
+struct event *sigterm_ev, *sigquit_ev, *sigchld_ev, *timer_ev;
+static int in_shutdown;
+
+/******************************************************************
+ * libevent helper functions
+ ******************************************************************/
+
+/* libevent logging callback */
+static void libevent_logmsg_cb(int severity, const char *msg)
+{
+    switch (severity) {
+    case _EVENT_LOG_DEBUG:
+        LOG(log_debug, logtype_default, "libevent: %s", msg);
+        break;
+    case _EVENT_LOG_MSG:
+        LOG(log_info, logtype_default, "libevent: %s", msg);
+        break;
+    case _EVENT_LOG_WARN:
+        LOG(log_warning, logtype_default, "libevent: %s", msg);
+        break;
+    case _EVENT_LOG_ERR:
+        LOG(log_error, logtype_default, "libevent: %s", msg);
+        break;
+    default:
+        LOG(log_error, logtype_default, "libevent: %s", msg);
+        break; /* never reached */
+    }
+}
+
+/******************************************************************
+ * libevent event callbacks
+ ******************************************************************/
+
+/* SIGTERM callback */
+static void sigterm_cb(evutil_socket_t fd, short what, void *arg)
+{
+    sigset_t sigs;
+    struct timeval tv;
+
+    LOG(log_info, logtype_afpd, "Exiting on SIGTERM");
+
+    if (in_shutdown)
+        return;
+    in_shutdown = 1;
+
+    /* block any signal but SIGCHLD */
+    sigfillset(&sigs);
+    sigdelset(&sigs, SIGCHLD);
+    sigprocmask(SIG_SETMASK, &sigs, NULL);
+
+    /* add 10 sec timeout timer, remove all events but SIGCHLD */
+    tv.tv_sec = KILL_GRACETIME;
+    tv.tv_usec = 0;
+    event_base_loopexit(base, &tv);
+    event_del(sigterm_ev);
+    event_del(sigquit_ev);
+    event_del(timer_ev);
+
+    kill_childs(SIGTERM, &afpd_pid, &cnid_metad_pid, NULL);
+}
+
+/* SIGQUIT callback */
+static void sigquit_cb(evutil_socket_t fd, short what, void *arg)
+{
+    LOG(log_note, logtype_afpd, "Exiting on SIGQUIT");
+    kill_childs(SIGQUIT, &afpd_pid, &cnid_metad_pid, NULL);
+}
+
+/* SIGCHLD callback */
+static void sigchld_cb(evutil_socket_t fd, short what, void *arg)
+{
+    int status, i;
+    pid_t pid;
+
+    LOG(log_debug, logtype_afpd, "Got SIGCHLD event");
+  
+    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
+        if (WIFEXITED(status)) {
+            if (WEXITSTATUS(status))
+                LOG(log_info, logtype_afpd, "child[%d]: exited %d", pid, WEXITSTATUS(status));
+            else
+                LOG(log_info, logtype_afpd, "child[%d]: done", pid);
+        } else {
+            if (WIFSIGNALED(status))
+                LOG(log_info, logtype_afpd, "child[%d]: killed by signal %d", pid, WTERMSIG(status));
+            else
+                LOG(log_info, logtype_afpd, "child[%d]: died", pid);
+        }
+
+        if (pid == afpd_pid)
+            afpd_pid = -1;
+        else if (pid = cnid_metad_pid)
+            cnid_metad_pid = -1;
+        else
+            LOG(log_error, logtype_afpd, "Bad pid: %d", pid);
+    }
+
+    if (in_shutdown && afpd_pid == -1 && cnid_metad_pid == -1)
+        event_base_loopbreak(base);
+}
+
+/* timer callback */
+static void timer_cb(evutil_socket_t fd, short what, void *arg)
+{
+    static int i = 0;
+
+    if (in_shutdown)
+        return;
+
+    if (afpd_pid == -1) {
+        afpd_restarts++;
+        LOG(log_note, logtype_afpd, "Restarting 'afpd' (restarts: %u)", afpd_restarts);
+        if ((afpd_pid = run_process(_PATH_AFPD, "-d", "-F", obj.options.configfile, NULL)) == -1) {
+            LOG(log_error, logtype_afpd, "Error starting 'afpd'");
+        }
+    }
+
+    if (cnid_metad_pid == -1) {
+        cnid_metad_restarts++;
+        LOG(log_note, logtype_afpd, "Restarting 'cnid_metad' (restarts: %u)", cnid_metad_restarts);
+        if ((cnid_metad_pid = run_process(_PATH_CNID_METAD, "-d", "-F", obj.options.configfile, NULL)) == -1) {
+            LOG(log_error, logtype_afpd, "Error starting 'cnid_metad'");
+        }
+    }
+}
+
+/******************************************************************
+ * helper functions
+ ******************************************************************/
+
+/* kill processes passed as varargs of type "pid_t *", terminate list with NULL */
+static void kill_childs(int sig, ...)
+{
+    va_list args;
+    pid_t *pid;
+
+    va_start(args, sig);
+
+    while ((pid = va_arg(args, pid_t *)) != NULL) {
+        if (*pid == -1)
+            continue;
+        kill(*pid, sig);
+    }
+    va_end(args);
+}
+
+/* this get called when error conditions are met that require us to exit gracefully */
+static void netatalk_exit(int ret)
+{
+    server_unlock(_PATH_NETATALK_LOCK);
+    exit(ret);
+}
+
+/* this forks() and exec() "path" with varags as argc[] */
+static pid_t run_process(const char *path, ...)
+{
+    int ret, i = 0;
+    char *myargv[10];
+    va_list args;
+    pid_t pid;
+
+    if ((pid = fork()) < 0) {
+        LOG(log_error, logtype_cnid, "error in fork: %s", strerror(errno));
+        return -1;
+    }
+
+    if (pid == 0) {
+        myargv[i++] = (char *)path;
+        va_start(args, path);
+        while ((myargv[i++] = va_arg(args, char *)) != NULL)
+            ;
+        va_end(args);
+
+        ret = execv(path, myargv);
+
+        /* Yikes! We're still here, so exec failed... */
+        LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
+        exit(1);
+    }
+    return pid;
+}
+
+static void usage(void)
+{
+    printf("usage: netatalk [-F configfile] \n");
+}
+
+int main(int argc, char **argv)
+{
+    const char *configfile = NULL;
+    int c, ret, debug = 0;
+    sigset_t blocksigs;
+    struct timeval tv;
+
+    /* Log SIGBUS/SIGSEGV SBT */
+    fault_setup(NULL);
+
+    while ((c = getopt(argc, argv, ":dF:")) != -1) {
+        switch(c) {
+        case 'd':
+            debug = 1;
+            break;
+        case 'F':
+            obj.cmdlineconfigfile = strdup(optarg);
+            break;
+        default:
+            usage();
+            exit(EXIT_FAILURE);
+        }
+    }
+
+    if (check_lockfile("netatalk", _PATH_NETATALK_LOCK) != 0)
+        exit(EXITERR_SYS);
+
+    if (!debug && daemonize(0, 0) != 0)
+        exit(EXITERR_SYS);
+
+    if (create_lockfile("netatalk", _PATH_NETATALK_LOCK) != 0)
+        exit(EXITERR_SYS);
+
+    sigfillset(&blocksigs);
+    sigprocmask(SIG_SETMASK, &blocksigs, NULL);
+    
+    if (afp_config_parse(&obj, "netatalk") != 0)
+        netatalk_exit(EXITERR_CONF);
+
+    event_set_log_callback(libevent_logmsg_cb);
+    event_set_fatal_callback(netatalk_exit);
+
+    LOG(log_note, logtype_default, "Netatalk AFP server starting");
+
+    if ((afpd_pid = run_process(_PATH_AFPD, "-d", "-F", obj.options.configfile, NULL)) == -1) {
+        LOG(log_error, logtype_afpd, "Error starting 'cnid_metad'");
+        netatalk_exit(EXITERR_CONF);
+    }
+
+    if ((cnid_metad_pid = run_process(_PATH_CNID_METAD, "-d", "-F", obj.options.configfile, NULL)) == -1) {
+        LOG(log_error, logtype_afpd, "Error starting 'cnid_metad'");
+        netatalk_exit(EXITERR_CONF);
+    }
+
+    if ((base = event_base_new()) == NULL) {
+        LOG(log_error, logtype_afpd, "Error starting event loop");
+        netatalk_exit(EXITERR_CONF);
+    }
+
+    sigterm_ev = event_new(base, SIGTERM, EV_SIGNAL, sigterm_cb, NULL);
+    sigquit_ev = event_new(base, SIGQUIT, EV_SIGNAL | EV_PERSIST, sigquit_cb, NULL);
+    sigchld_ev = event_new(base, SIGCHLD, EV_SIGNAL | EV_PERSIST, sigchld_cb, NULL);
+    timer_ev = event_new(base, -1, EV_PERSIST, timer_cb, NULL);
+
+    tv.tv_sec = 1;
+    tv.tv_usec = 0;
+
+    event_add(sigterm_ev, NULL);
+    event_add(sigquit_ev, NULL);
+    event_add(sigchld_ev, NULL);
+    event_add(timer_ev, &tv);
+
+    sigfillset(&blocksigs);
+    sigdelset(&blocksigs, SIGTERM);
+    sigdelset(&blocksigs, SIGQUIT);
+    sigdelset(&blocksigs, SIGCHLD);
+    sigprocmask(SIG_SETMASK, &blocksigs, NULL);
+
+    /* run the event loop */
+    ret = event_base_dispatch(base);
+
+    if (afpd_pid != -1 || cnid_metad_pid != -1) {
+        if (afpd_pid != -1)
+            LOG(log_error, logtype_afpd, "AFP service did not shutdown, killing it");
+        if (cnid_metad_pid != -1)
+            LOG(log_error, logtype_afpd, "CNID database service did not shutdown, killing it");
+        kill_childs(SIGKILL, &afpd_pid, &cnid_metad_pid, NULL);
+    }
+
+    LOG(log_note, logtype_afpd, "Netatalk AFP server exiting");
+
+    netatalk_exit(ret);
+}
diff --git a/etc/papd/.gitignore b/etc/papd/.gitignore
deleted file mode 100644 (file)
index b15fd9a..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Makefile
-Makefile.in
-papd
-showppd
-.deps
-.libs
-.gitignore
-auth.o comment.o file.o headers.o lp.o magics.o main.o ppd.o printcap.o print_cups.o queries.o session.o showppd-ppd.o showppd-showppd.o uam.o
diff --git a/etc/papd/Makefile.am b/etc/papd/Makefile.am
deleted file mode 100644 (file)
index 6a09abd..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-# Makefile.am for etc/papd/
-
-pkgconfdir = @PKGCONFDIR@
-spooldir = @SPOOLDIR@
-
-sbin_PROGRAMS = papd
-bin_PROGRAMS = showppd
-
-papd_SOURCES = main.c printcap.c session.c file.c comment.c lp.c ppd.c \
-              magics.c headers.c queries.c auth.c uam.c print_cups.c
-
-papd_LDADD = $(top_builddir)/libatalk/libatalk.la @CUPS_LIBS@ @LIBADD_DL@
-papd_LDFLAGS = -export-dynamic @CUPS_LDFLAGS@
-
-showppd_SOURCES = showppd.c ppd.c
-showppd_CFLAGS = -DSHOWPPD
-showppd_LDADD = $(top_builddir)/libatalk/libatalk.la
-
-noinst_HEADERS =       \
-       comment.h       \
-       file.h          \
-       lp.h            \
-       ppd.h           \
-       printcap.h      \
-       printer.h       \
-       session.h       \
-       print_cups.h    \
-       uam_auth.h
-
-AM_CFLAGS = \
-       -I$(top_srcdir)/include -I$(top_srcdir)/sys \
-       @CUPS_CFLAGS@\
-       -D_PATH_PAPDCONF=\"$(pkgconfdir)/papd.conf\" \
-       -D_PATH_PAPDUAMPATH=\"$(UAMS_PATH)/\" \
-       -DSPOOLDIR=\"$(spooldir)/\"
-
-if USE_SPOOLDIR
-install-exec-hook:
-       echo "Creating SPOOLDIR $(DESTDIR)$(spooldir)..."
-       $(mkinstalldirs) $(DESTDIR)$(spooldir)
-       chmod 0777 $(DESTDIR)$(spooldir)
-
-else
-install-exec-hook:
-
-endif
diff --git a/etc/papd/auth.c b/etc/papd/auth.c
deleted file mode 100644 (file)
index a8ba6fd..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * $Id: auth.c,v 1.9 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <stdlib.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <netatalk/endian.h>
-#include <atalk/afp.h>
-#include <atalk/compat.h>
-#include <atalk/util.h>
-#include <limits.h>
-#include <string.h>
-#include <ctype.h>
-#include <pwd.h>
-#include <grp.h>
-#include <atalk/logger.h>
-
-#include "uam_auth.h"
-
-static struct uam_mod uam_modules = {NULL, NULL, &uam_modules, &uam_modules};
-static struct uam_obj uam_login = {"", "", 0, {{NULL, NULL, NULL}}, &uam_login,
-                                  &uam_login};
-static struct uam_obj uam_changepw = {"", "", 0, {{NULL, NULL, NULL}}, &uam_changepw, 
-                                     &uam_changepw};
-static struct uam_obj uam_printer = {"", "", 0, {{NULL, NULL, NULL}}, &uam_printer,
-                                       &uam_printer};
-
-
-/*
- * Return a list of names for loaded uams
- */
-int getuamnames(const int type, char *uamnames)
-{
-    struct uam_obj *prev, *start;
-  
-    if (!(start = UAM_LIST(type)))
-        return(-1);
-  
-    prev = start;
-      
-    while((prev = prev->uam_prev) != start) {
-        strcat(uamnames, prev->uam_name);
-        strcat(uamnames, "\n");
-    }
-    strcat(uamnames, "*\n");
-    return(0);
-}
-  
-
-/* just do a linked list search. this could be sped up with a hashed
- * list, but i doubt anyone's going to have enough uams to matter. */
-struct uam_obj *auth_uamfind(const int type, const char *name, 
-                            const int len)
-{
-  struct uam_obj *prev, *start;
-
-  if (!name || !(start = UAM_LIST(type)))
-    return NULL;
-
-  prev = start;
-  while ((prev = prev->uam_prev) != start) 
-    if (strndiacasecmp(prev->uam_name, name, len) == 0)
-      return prev;
-
-  return NULL;
-}
-
-int auth_register(const int type, struct uam_obj *uam)
-{
-  struct uam_obj *start;
-
-  if (!uam || !uam->uam_name || (*uam->uam_name == '\0'))
-    return -1;
-
-  if (!(start = UAM_LIST(type)))
-    return 1; 
-
-  uam_attach(start, uam);
-  return 0;
-}
-
-/* load all of the modules */
-int auth_load(const char *path, const char *list)
-{
-  char name[MAXPATHLEN + 1], buf[MAXPATHLEN + 1], *p; 
-  struct uam_mod *mod;
-  struct stat st;
-  size_t len;
-  
-  if (!path || !list || (len = strlen(path)) > sizeof(name) - 2)
-    return -1;
-
-  strlcpy(buf, list, sizeof(buf));
-  if ((p = strtok(buf, ",")) == NULL)
-    return -1;
-
-  strcpy(name, path);
-  if (name[len - 1] != '/') {
-    strcat(name, "/");
-    len++;
-  }
-
-  while (p) {
-    strlcpy(name + len, p, sizeof(name) - len);
-    if ((stat(name, &st) == 0) && (mod = uam_load(name, p))) {
-      uam_attach(&uam_modules, mod);
-      LOG(log_info, logtype_papd, "uam: %s loaded", p);
-    }
-    p = strtok(NULL, ",");
-  }
-  return 0;
-}
-
-/* get rid of all of the uams */
-void auth_unload(void)
-{
-  struct uam_mod *mod, *prev, *start = &uam_modules;
-
-  prev = start->uam_prev;
-  while ((mod = prev) != start) {
-    prev = prev->uam_prev;
-    uam_detach(mod);
-    uam_unload(mod);
-  }
-}
diff --git a/etc/papd/comment.c b/etc/papd/comment.c
deleted file mode 100644 (file)
index 1a2964d..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * $Id: comment.c,v 1.10 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <atalk/logger.h>
-#include <sys/param.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-
-#include "comment.h"
-
-struct comstate        *comstate;
-
-char   *comcont = "%%+";
-
-void compop( void )
-{
-    struct comstate    *cs;
-
-    cs = comstate;
-    comstate = cs->cs_prev;
-    free( cs );
-}
-
-void compush(struct papd_comment *comment)
-{
-    struct comstate    *cs;
-
-    if (( cs = (struct comstate *)malloc( sizeof( struct comstate ))) ==
-           NULL ) {
-       LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-       exit( 1 );
-    }
-
-    cs->cs_comment = comment;
-    cs->cs_prev = comstate;
-    cs->cs_flags = 0;
-    comstate = cs;
-}
-
-int comswitch(struct papd_comment *comments, int (*handler)())
-{
-    struct papd_comment        *c, *comment = NULL;
-
-    for ( c = comments; c->c_begin; c++ ) {
-       if ( c->c_handler == handler ) {
-           comment = c;
-       }
-    }
-    if ( comment == NULL || comment->c_handler != handler ) {
-       LOG(log_error, logtype_papd, "comswitch: can't find handler!" );
-       return( -1 );
-    }
-    compop();
-    compush( comment );
-    return( 0 );
-}
-
-int comcmp( char *start, char *stop, char *str,int how)
-{
-    int                cc, len;
-
-    len = stop - start;
-    cc = strlen( str );
-    if ( how & C_FULL ) {
-       if ( (cc == len) && (strncmp( str, start, cc ) == 0) ) {
-           return( 0 );
-       }
-    } else {
-       if ( (cc <= len) && (strncmp( str, start, cc ) == 0) ) {
-           return( 0 );
-       }
-    }
-
-    return( 1 );
-}
-
-struct papd_comment *commatch( char *start, char *stop, struct papd_comment comments[])
-{
-    struct papd_comment        *comment;
-
-    for ( comment = comments; comment->c_begin; comment++ ) {
-       if ( comcmp( start, stop, comment->c_begin, comment->c_flags ) == 0 ) {
-           break;
-       }
-    }
-    if ( comment->c_begin ) {
-       return( comment );
-    } else {
-       return( NULL );
-    }
-}
-
-char *comtoken( char *start, char *stop, char *pos, char *delim)
-{
-    if ( pos < start || pos > stop ) {
-       abort();
-    }
-
-    for ( ; pos < stop; pos++ ) {
-       if ( index( delim, *pos )) {
-           break;
-       }
-    }
-    if ( ++pos < stop ) {
-       return( pos );
-    } else {
-       return( NULL );
-    }
-}
diff --git a/etc/papd/comment.h b/etc/papd/comment.h
deleted file mode 100644 (file)
index 1cac2d0..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * $Id: comment.h,v 1.6 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifndef PAPD_COMMENT_H
-#define PAPD_COMMENT_H 1
-
-#include <sys/cdefs.h>
-
-struct papd_comment {
-    char               *c_begin;
-    char               *c_end;
-    int                        (*c_handler)();
-    int                        c_flags;
-};
-
-#define CH_DONE                0
-#define CH_MORE                1
-#define CH_ERROR       -1
-
-struct comstate {
-    struct papd_comment        *cs_comment;
-    struct comstate    *cs_prev;
-    int                        cs_flags;
-};
-
-extern struct papd_comment     *commatch();
-extern struct comstate         *comstate;
-extern struct papd_comment     magics[];
-extern struct papd_comment     queries[];
-extern struct papd_comment     headers[];
-extern char                    *comcont;
-
-#define compeek()      (comstate==NULL?NULL:(comstate->cs_comment))
-#define comgetflags()  (comstate->cs_flags)
-#define comsetflags(f) (comstate->cs_flags=(f))
-
-/*
- * Comment flags.  0-15 reserved for "global" flags, 16-31 for specific
- * subtypes.
- */
-#define C_FULL         (1<<0)                          /* or prefix */
-#define C_CONTINUE     (1<<1)
-
-/*
- * Query subtypes.
- */
-
-/*
- * Magic "number" subtypes.
- */
-#define CM_NOPRINT     (1<<16)                         /* or print */
-
-void compop ( void );
-void compush ( struct papd_comment * );
-int comswitch ( struct papd_comment *, int (*)() );
-int comcmp ( char *, char *, char *, int );
-struct papd_comment *commatch ( char *, char *, struct papd_comment * );
-char *comtoken ( char *, char *, char *, char * );
-
-#endif /* PAPD_COMMENT_H */
diff --git a/etc/papd/file.c b/etc/papd/file.c
deleted file mode 100644 (file)
index 068b5d7..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * $Id: file.c,v 1.12 2009-10-14 02:24:05 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <atalk/logger.h>
-#include <sys/param.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "file.h"
-
-/* 
-*/
-int markline( struct papfile *pf, char **start, int *linelength, int *crlflength )
-{
-    char               *p;
-
-    if ( pf->pf_datalen == 0 && ( pf->pf_state & PF_EOF )) {
-       return( 0 );
-    }
-
-    *start = pf->pf_data;
-
-    /* get a line */
-    for ( *linelength=0; *linelength < pf->pf_datalen; (*linelength)++) {
-       if (pf->pf_data[*linelength] == '\n' ||
-           pf->pf_data[*linelength] == '\r') {
-           break;
-       }
-    }
-
-    if ( *linelength >= pf->pf_datalen ) {
-       if ( pf->pf_state & PF_EOF ) {
-           append( pf, "\n", 1 );
-       } else if (*linelength < 1024) {
-           return( -1 );
-       }
-    }
-
-    p = pf->pf_data + *linelength;
-
-    *crlflength=0;
-    while(*crlflength < pf->pf_datalen-*linelength && 
-    (p[*crlflength]=='\r' || p[*crlflength]=='\n')) {
-       (*crlflength)++;
-    }
-    
-    if (!*crlflength) {
-        /* line is way too long, something fishy is going on, give up */
-        LOG(log_error, logtype_papd, "markline: no crlf in comment, give up" );
-        return( -2 );
-    }
-
-    /* success, return 1 */
-    return( 1 );
-}
-
-void morespace(struct papfile *pf, const char *data, int len)
-{
-    char               *nbuf;
-    int                        nsize;
-
-    if ( pf->pf_data != pf->pf_buf ) {                 /* pull up */
-       bcopy( pf->pf_data, pf->pf_buf, pf->pf_datalen);
-       pf->pf_data = pf->pf_buf;
-    }
-
-    if ( pf->pf_datalen + len > pf->pf_bufsize ) {     /* make more space */
-       nsize = (( pf->pf_bufsize + len ) / PF_MORESPACE +
-               (( pf->pf_bufsize + len ) % PF_MORESPACE != 0 )) * PF_MORESPACE;
-       if ( pf->pf_buf ) {
-           if (( nbuf = (char *)realloc( pf->pf_buf, nsize )) == NULL ) {
-               exit( 1 );
-           }
-       } else {
-           if (( nbuf = (char *)malloc( nsize )) == NULL ) {
-               exit( 1 );
-           }
-       }
-       pf->pf_bufsize = nsize;
-       pf->pf_data = nbuf + ( pf->pf_data - pf->pf_buf );
-       pf->pf_buf = nbuf;
-    }
-
-    bcopy( data, pf->pf_data + pf->pf_datalen, len );
-    pf->pf_datalen += len;
-}
-
-
-void append(struct papfile *pf, const char *data, int len)
-{
-    if ((pf->pf_data + pf->pf_datalen + len) >
-       (pf->pf_buf + pf->pf_bufsize)) {
-               morespace(pf, data, len);
-    } else {
-       memcpy(pf->pf_data + pf->pf_datalen, data, len);
-       pf->pf_datalen += len;
-    }
-}
-
-
-void spoolerror(struct papfile *out, char *str)
-{
-    char       *pserr1 = "%%[ Error: ";
-    char       *pserr2 = " ]%%\n";
-
-    if ( str == NULL ) {
-       str = "Spooler error.";
-    }
-
-    append( out, pserr1, strlen( pserr1 ));
-    append( out, str, strlen( str ));
-    append( out, pserr2, strlen( pserr2 ));
-}
diff --git a/etc/papd/file.h b/etc/papd/file.h
deleted file mode 100644 (file)
index 9f1f52d..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * $Id: file.h,v 1.8 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifndef PAPD_FILE_H
-#define PAPD_FILE_H 1
-
-#include <sys/cdefs.h>
-
-struct papfile {
-    int                        pf_state;
-    struct state       *pf_xstate;
-    int                        pf_bufsize;
-    int                        pf_datalen;
-    char               *pf_buf;
-    char               *pf_data;
-    int                origin;
-};
-
-#define PF_BOT         (1<<0)
-#define PF_EOF         (1<<1)
-#define PF_QUERY       (1<<2)
-#define PF_STW         (1<<3)
-#define PF_TRANSLATE   (1<<4)
-
-#define CONSUME( pf, len )  {   (pf)->pf_data += (len); \
-                               (pf)->pf_datalen -= (len); \
-                               if ((pf)->pf_datalen <= 0) { \
-                                   (pf)->pf_data = (pf)->pf_buf; \
-                                   (pf)->pf_datalen = 0; \
-                               } \
-                           }
-
-#define PF_MORESPACE   1024
-
-int markline ( struct papfile *, char **, int *, int * );
-void morespace ( struct papfile *, const char *, int );
-void append ( struct papfile *, const char *, int );
-void spoolerror ( struct papfile *, char * );
-
-#endif /* PAPD_FILE_H */
diff --git a/etc/papd/headers.c b/etc/papd/headers.c
deleted file mode 100644 (file)
index dd31539..0000000
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * $Id: headers.c,v 1.14 2009-10-29 13:38:15 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h" 
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/param.h>
-#include <string.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <netatalk/at.h>
-#include <atalk/logger.h>
-
-#include "file.h"
-#include "comment.h"
-#include "lp.h"
-
-int ch_title( struct papfile *, struct papfile * );
-int ch_for( struct papfile *, struct papfile * );
-
-static char *get_text(char *start, int linelength)
-{
-    char *p, *q;
-    char *t, *ret;
-    char *stop;
-    
-    /* 1023 is arbitrary 255 max for comment but some may be escape \xxx and space and keyword */
-
-    if (linelength > 1023)
-        return NULL;
-
-    t = ret = calloc(1, linelength +1);
-
-    if (!ret)
-        return NULL;
-
-    stop = start + linelength;
-    for ( p = start; p < stop; p++ ) {
-        if ( *p == ':' ) {
-            p++;
-            break;
-        }
-    }
-    
-    for ( ; p < stop; p++ ) {
-        if (*p != ' ' && *p != '\t') {
-            break;
-        }
-    }
-
-    if ( p < stop && *p == '(' ) {
-        int count;
-        /* start with ( then it's a <text> */ 
-        p++;
-        for ( q = p, count = 1; q < stop; q++, t++ ) {
-            if (*q == '(') {
-              count++;
-            }
-            else if ( *q == ')' ) {
-                count--;
-                if (!count) {
-                    break;
-                }
-            }
-            *t = *q;
-        }
-    }
-    else {
-        /* it's a textline */
-        for ( q = p; q < stop; q++, t++ ) {
-            *t = *q;
-        }
-    }
-    return ret;
-}
-
-int ch_for( struct papfile *in, struct papfile *out _U_)
-{
-    char                *start, *cmt;
-    int                 linelength, crlflength;
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-        return( 0 );
-
-    case -1 :
-        return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    cmt = get_text(start, linelength);
-
-    if ( cmt ) {
-       lp_for ( cmt );
-       free(cmt);
-    }
-
-    in->pf_state |= PF_TRANSLATE;
-    lp_write( in, start, linelength + crlflength );
-    in->pf_state &= ~PF_TRANSLATE;
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return( CH_DONE );
-}
-
-int ch_title( struct papfile *in, struct papfile *out _U_)
-{
-    char               *start, *cmt;
-    int                        linelength, crlflength;
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-       return( 0 );
-
-    case -1 :
-       return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-#ifdef DEBUG
-    LOG(log_debug9, logtype_papd, "Parsing %%Title");
-#endif
-
-    cmt = get_text(start, linelength);
-
-    if ( cmt ) {
-       lp_job( cmt );
-       free(cmt);
-    }
-
-    in->pf_state |= PF_TRANSLATE;
-    lp_write( in, start, linelength + crlflength );
-    in->pf_state &= ~PF_TRANSLATE;
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return( CH_DONE );
-}
-
-static int guess_creator ( char *creator )
-{
-       if (strstr(creator, "LaserWriter"))
-               return 1;
-       if (strstr(creator, "cgpdftops"))
-               return 2;
-
-       return 0;
-}
-
-
-int ch_creator( struct papfile *in, struct papfile *out _U_)
-{
-    char               *start, *cmt;
-    int                        linelength, crlflength;
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-       return( 0 );
-
-    case -1 :
-       return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    cmt = get_text(start, linelength);
-
-    if ( cmt ) {
-       in->origin = guess_creator ( cmt );
-       free(cmt);
-       lp_origin(in->origin);
-    }
-
-    in->pf_state |= PF_TRANSLATE;
-    lp_write( in, start, linelength + crlflength );
-    in->pf_state &= ~PF_TRANSLATE;
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return( CH_DONE );
-}
-
-int ch_endcomm( struct papfile *in, struct papfile *out _U_)
-{
-    char                *start;
-    int                 linelength, crlflength;
-
-#ifdef DEBUG
-    LOG(log_debug9, logtype_papd, "End Comment");
-#endif
-    in->pf_state |= PF_STW;
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-       return( 0 );
-
-    case -1 :
-       return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    in->pf_state |= PF_TRANSLATE;
-    lp_write( in, start, linelength + crlflength );
-    in->pf_state &= ~PF_TRANSLATE;
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return ( CH_DONE);
-}
-
-int ch_starttranslate( struct papfile *in, struct papfile *out _U_)
-{
-    char                *start;
-    int                 linelength, crlflength;
-
-#ifdef DEBUG
-    LOG(log_debug9, logtype_papd, "Start translate");
-#endif
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-        return( 0 );
-
-    case -1 :
-        return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    in->pf_state |= PF_TRANSLATE;
-    lp_write( in, start, linelength + crlflength );
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return ( CH_DONE);
-}
-
-int ch_endtranslate(struct papfile *in, struct papfile *out _U_)
-{
-    char                *start;
-    int                 linelength, crlflength;
-
-#ifdef DEBUG
-    LOG(log_debug9, logtype_papd, "EndTranslate");
-#endif
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-        return( 0 );
-
-    case -1 :
-        return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    lp_write( in, start, linelength + crlflength );
-    in->pf_state &= ~PF_TRANSLATE;
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return ( CH_DONE);
-}
-
-int ch_translateone( struct papfile *in, struct papfile *out _U_)
-{
-    char                *start;
-    int                 linelength, crlflength;
-
-#ifdef DEBUG
-    LOG(log_debug9, logtype_papd, "TranslateOne");
-#endif
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-        return( 0 );
-
-    case -1 :
-        return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    in->pf_state |= PF_TRANSLATE;
-    lp_write( in, start, linelength + crlflength );
-    in->pf_state &= ~PF_TRANSLATE;
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return ( CH_DONE);
-}
-
-
-
-
-/*
- * "Header" comments.
- */
-struct papd_comment    headers[] = {
-    { "%%Title:",                      NULL,           ch_title,       0 },
-    { "%%For:",                                NULL,           ch_for,         0 },
-    { "%%Creator:",                    NULL,           ch_creator,     0 },
-    { "%%EndComments",                 NULL,           ch_endcomm,     0 },
-    { "%%BeginFeature",                        NULL,           ch_starttranslate,  0 },
-    { "%%EndFeature",                  NULL,           ch_endtranslate,  0 },
-    { "%%BeginPageSetup",              NULL,           ch_starttranslate, 0 },
-    { "%%EndPageSetup",                        NULL,           ch_endtranslate, 0 },
-#if 0
-    { "%%BeginSetup",                  NULL,           ch_translateone,  0 },
-    { "%%EndSetup",                    NULL,           ch_translateone,  0 },
-    { "%%BeginProlog",                 NULL,           ch_translateone,  0 },
-    { "%%EndProlog",                   NULL,           ch_translateone,  0 },
-    { "%%Page:",                       NULL,           ch_translateone, 0 },
-    { "%%PageTrailer",                 NULL,           ch_translateone, 0 },
-    { "%%Trailer",                     NULL,           ch_translateone, 0 },
-    { "%%EOF",                         NULL,           ch_translateone, 0 },
-#endif
-    { "%%",                            NULL,           ch_translateone, 0 },
-    { NULL,                            NULL,           NULL,           0 },
-};
diff --git a/etc/papd/lp.c b/etc/papd/lp.c
deleted file mode 100644 (file)
index d315b12..0000000
+++ /dev/null
@@ -1,1153 +0,0 @@
-/*
- * $Id: lp.c,v 1.33 2009-10-29 13:38:15 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- *
- * Portions:
- * Copyright (c) 1983 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.
- */
-
-/*
- * Interface to lpr system.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/param.h>
-#include <sys/time.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <ctype.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-
-#include <sys/file.h>
-#include <sys/un.h>
-#include <netinet/in.h>
-#undef s_net
-
-#ifdef ABS_PRINT
-#include <math.h>
-#endif /* ABS_PRINT */
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <netdb.h>
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#include <pwd.h>
-
-#include <atalk/logger.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/paths.h>
-#include <atalk/unicode.h>
-
-#include "printer.h"
-#include "file.h"
-#include "lp.h"
-
-#ifdef HAVE_CUPS
-#include  "print_cups.h"
-#endif
-
-
-/* These functions aren't used outside of lp.c */
-int lp_conn_inet();
-int lp_disconn_inet( int );
-int lp_conn_unix();
-int lp_disconn_unix( int );
-
-static char hostname[ MAXHOSTNAMELEN ];
-
-extern struct sockaddr_at *sat;
-
-static struct lp {
-    int                        lp_flags;
-    FILE               *lp_stream;
-    int                        lp_seq;
-    int                lp_origin;
-    char               lp_letter;
-    char               *lp_person;
-    char               *lp_created_for; /* Holds the content of the Postscript %%For Comment if available */
-    char               *lp_host;
-    char               *lp_job;
-    char               *lp_spoolfile;
-} lp;
-#define LP_INIT                (1<<0)
-#define LP_OPEN                (1<<1)
-#define LP_PIPE                (1<<2)
-#define LP_CONNECT     (1<<3)
-#define LP_QUEUE       (1<<4)
-#define LP_JOBPENDING  (1<<5)
-
-void lp_origin (int origin)
-{
-    lp.lp_origin = origin;
-}
-
-/* the converted string should always be shorter, but ... FIXME! */
-static void convert_octal (char *string, charset_t dest)
-{
-    unsigned char *p, *q;
-    char temp[4];
-    long int ch;
-
-    q=p=(unsigned char *)string;
-    while ( *p != '\0' ) {
-        ch = 0;
-        if ( *p == '\\' ) {
-            p++;
-            if (dest && isdigit(*p) && isdigit(*(p+1)) && isdigit(*(p+2)) ) {
-                temp[0] = *p;
-                temp[1] = *(p+1);
-                temp[2] = *(p+2);
-                temp[3] = 0;
-                ch = strtol( temp, NULL, 8);
-                if ( ch && ch < 0xff)
-                    *q = ch;
-               else
-                    *q = '.';
-                p += 2;
-            }
-                   else 
-                *q = '.';
-       }
-       else {
-           *q = *p;
-       }
-           p++;
-           q++;
-    }
-    *q = 0;
-}
-
-
-static void translate(charset_t from, charset_t dest, char **option)
-{
-    char *translated;
-
-    if (*option != NULL) {
-        convert_octal(*option, from);
-        if (from) {
-             if ((size_t) -1 != (convert_string_allocate(from, dest, *option, -1, &translated)) ) {
-                 free (*option);
-                 *option = translated;
-             }
-        }
-    }
-}
-
-
-static void lp_setup_comments (charset_t dest)
-{
-    charset_t from=0;
-
-    switch (lp.lp_origin) {
-       case 1:
-               from=CH_MAC;
-               break;
-       case 2:
-               from=CH_UTF8_MAC;
-               break;
-    }
-
-    if (lp.lp_job) {
-#ifdef DEBUG1
-        LOG(log_debug9, logtype_papd, "job: %s", lp.lp_job );
-#endif
-        translate(from, dest, &lp.lp_job);
-    }
-    if (lp.lp_created_for) {
-#ifdef DEBUG1
-        LOG(log_debug9, logtype_papd, "for: %s", lp.lp_created_for );
-#endif
-        translate(from, dest, &lp.lp_created_for);
-    }
-    if (lp.lp_person) {
-#ifdef DEBUG1
-       LOG(log_debug9, logtype_papd, "person: %s", lp.lp_person );
-#endif
-       translate(from, dest, &lp.lp_person);
-    }
-}
-
-#define is_var(a, b) (strncmp((a), (b), 2) == 0)
-
-#if 0
-/* removed, it's not used and a pain to get it right from a security POV */
-static size_t quote(char *dest, char *src, const size_t bsize, size_t len)
-{
-size_t used = 0;
-
-    while (len && used < bsize ) {
-        switch (*src) {
-          case '$':
-          case '\\':
-          case '"':
-          case '`':
-            if (used + 2 > bsize )
-              return used;
-            *dest = '\\';
-            dest++;
-            used++;
-            break;
-        }
-        *dest = *src;
-        src++;
-        dest++;
-        len--;
-        used++;
-    }
-    return used;
-}
-
-static char* pipexlate(char *src)
-{
-    char *p, *q, *dest; 
-    static char destbuf[MAXPATHLEN +1];
-    size_t destlen = MAXPATHLEN;
-    int len = 0;
-   
-    dest = destbuf; 
-
-    if (!src)
-       return NULL;
-
-    memset(dest, 0, MAXPATHLEN +1);
-    if ((p = strchr(src, '%')) == NULL) { /* nothing to do */
-        strncpy(dest, src, MAXPATHLEN);
-        return destbuf;
-    }
-    /* first part of the path. copy and forward to the next variable. */
-    len = MIN((size_t)(p - src), destlen);
-    if (len > 0) {
-        strncpy(dest, src, len);
-        destlen -= len;
-        dest += len;
-    }
-
-    while (p && destlen > 0) {
-        /* now figure out what the variable is */
-        q = NULL;
-        if (is_var(p, "%U")) {
-           q = lp.lp_person;
-        } else if (is_var(p, "%C") || is_var(p, "%J") ) {
-            q = lp.lp_job;
-        } else if (is_var(p, "%F")) {
-            q =  lp.lp_created_for;
-        } else if (is_var(p, "%%")) {
-            q = "%";
-        } 
-
-        /* copy the stuff over. if we don't understand something that we
-         * should, just skip it over. */
-        if (q) {
-            len = MIN(strlen(q), destlen);
-            len = quote(dest, q, destlen, len);
-        }
-        else {
-            len = MIN(2, destlen);
-            strncpy(dest, q, len);
-        }
-        dest += len;
-        destlen -= len;
-
-        /* stuff up to next % */
-        src = p + 2;
-        p = strchr(src, '%');
-        len = p ? MIN((size_t)(p - src), destlen) : destlen;
-        if (len > 0) {
-            strncpy(dest, src, len);
-            dest += len;
-            destlen -= len;
-        }
-    }
-    if (!destlen) {
-        /* reach end of buffer, maybe prematurely, give up */
-        return NULL;
-    }
-    return destbuf;
-}
-#endif
-
-void lp_person(char *person)
-{
-    if ( lp.lp_person != NULL ) {
-       free( lp.lp_person );
-    }
-    if (( lp.lp_person = (char *)malloc( strlen( person ) + 1 )) == NULL ) {
-       LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-       exit( 1 );
-    }
-    strcpy( lp.lp_person, person );
-}
-
-#ifdef ABS_PRINT
-int lp_pagecost(void)
-{
-    char       cost[ 22 ];
-    char       balance[ 22 ];
-    int                err;
-
-    if ( lp.lp_person == NULL ) {
-       return( -1 );
-    }
-    err = ABS_canprint( lp.lp_person, printer->p_role, printer->p_srvid,
-           cost, balance );
-    printer->p_pagecost = floor( atof( cost ) * 10000.0 );
-    printer->p_balance = atof( balance ) + atof( cost );
-    return( err < 0 ? -1 : 0 );
-}
-#endif /* ABS_PRINT */
-
-void lp_host( char *host)
-{
-    if ( lp.lp_host != NULL ) {
-       free( lp.lp_host );
-    }
-    if (( lp.lp_host = (char *)malloc( strlen( host ) + 1 )) == NULL ) {
-       LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-       exit( 1 );
-    }
-    strcpy( lp.lp_host, host );
-    LOG(log_debug, logtype_papd, "host: %s", lp.lp_host );
-}
-
-/* Currently lp_job and lp_for will not handle the
- * conversion of macroman chars > 0x7f correctly
- * This should be added.
- */
-
-void lp_job(char *job)
-{
-    if ( lp.lp_job != NULL ) {
-       free( lp.lp_job );
-    }
-
-    lp.lp_job = strdup(job);
-#ifdef DEBUG
-    LOG(log_debug9, logtype_papd, "job: %s", lp.lp_job );
-#endif
-    
-}
-
-void lp_for (char *lpfor)
-{
-    if ( lp.lp_created_for != NULL ) {
-       free( lp.lp_created_for );
-    }
-
-    lp.lp_created_for = strdup(lpfor);
-}
-
-
-static int lp_init(struct papfile *out, struct sockaddr_at *sat)
-{
-    int                authenticated = 0;
-#ifndef HAVE_CUPS
-    int                fd, n, len;
-    char       *cp, buf[ BUFSIZ ];
-    struct stat        st;
-#endif /* HAVE_CUPS */
-#ifdef ABS_PRINT
-    char       cost[ 22 ];
-    char       balance[ 22 ];
-#endif /* ABS_PRINT */
-
-    if ( printer->p_flags & P_AUTH ) {
-       authenticated = 0;
-
-       /* cap style "log on to afp server before printing" authentication */
-
-       if ( printer->p_authprintdir && (printer->p_flags & P_AUTH_CAP) ) {
-           int addr_net = ntohs( sat->sat_addr.s_net );
-           int addr_node  = sat->sat_addr.s_node;
-           char addr_filename[256];
-           char auth_string[256];
-           char *username, *afpdpid;
-           struct stat cap_st;
-           FILE *cap_file;
-
-           memset( auth_string, 0, 256 );
-           sprintf(addr_filename, "%s/net%d.%dnode%d", 
-               printer->p_authprintdir, addr_net/256, addr_net%256, 
-               addr_node);
-           if (stat(addr_filename, &cap_st) == 0) {
-               if ((cap_file = fopen(addr_filename, "r")) != NULL) {
-                   if (fgets(auth_string, 256, cap_file) != NULL) {
-                       username = auth_string;
-                       if ((afpdpid = strrchr( auth_string, ':' )) != NULL) {
-                           *afpdpid = '\0';
-                           afpdpid++;
-                       }
-                       if (getpwnam(username) != NULL ) {
-                           LOG(log_info, logtype_papd, "CAP authenticated %s", username);
-                           lp_person(username);
-                           authenticated = 1;
-                       } else {
-                           LOG(log_info, logtype_papd, "CAP error: invalid username: '%s'", username);
-                       }
-                   } else {
-                       LOG(log_info, logtype_papd, "CAP error: could not read username");
-                   }
-               } else {
-                   LOG(log_info, logtype_papd, "CAP error: %s", strerror(errno));
-               }
-           } else {
-               LOG(log_info, logtype_papd, "CAP error: %s", strerror(errno));
-           }
-       }
-
-       if ( printer->p_flags & P_AUTH_PSSP ) {
-           if ( lp.lp_person != NULL ) {
-               authenticated = 1;
-           }
-       }
-
-       if ( authenticated == 0 ) {
-           LOG(log_error, logtype_papd, "lp_init: must authenticate" );
-           spoolerror( out, "Authentication required." );
-           return( -1 );
-       }
-
-#ifdef ABS_PRINT
-       if (( printer->p_flags & P_ACCOUNT ) && printer->p_pagecost > 0 &&
-               ! ABS_canprint( lp.lp_person, printer->p_role,
-               printer->p_srvid, cost, balance )) {
-           LOG(log_error, logtype_papd, "lp_init: no ABS funds" );
-           spoolerror( out, "No ABS funds available." );
-           return( -1 );
-       }
-#endif /* ABS_PRINT */
-    }
-
-    if ( gethostname( hostname, sizeof( hostname )) < 0 ) {
-       LOG(log_error, logtype_papd, "gethostname: %s", strerror(errno) );
-       exit( 1 );
-    }
-
-    if ( lp.lp_flags & LP_INIT ) {
-       LOG(log_error, logtype_papd, "lp_init: already inited, die!" );
-       abort();
-    }
-
-    lp.lp_flags = 0;
-    lp.lp_stream = NULL;
-    lp.lp_letter = 'A';
-
-    if ( printer->p_flags & P_SPOOLED ) {
-
-#ifndef HAVE_CUPS
-       /* check if queuing is enabled: mode & 010 on lock file */
-       if ( stat( printer->p_lock, &st ) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_init: %s: %s", printer->p_lock, strerror(errno) );
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-       if ( st.st_mode & 010 ) {
-           LOG(log_info, logtype_papd, "lp_init: queuing is disabled" );
-           spoolerror( out, "Queuing is disabled." );
-           return( -1 );
-       }
-
-       if (( fd = open( ".seq", O_RDWR|O_CREAT, 0661 )) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_init: can't create .seq" );
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-
-#ifndef SOLARIS /* flock is unsupported, I doubt this stuff works anyway with newer solaris so ignore for now */
-       if ( flock( fd, LOCK_EX ) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_init: can't lock .seq" );
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-#endif
-
-       n = 0;
-       if (( len = read( fd, buf, sizeof( buf ))) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_init read: %s", strerror(errno) );
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-       if ( len > 0 ) {
-           for ( cp = buf; len; len--, cp++ ) {
-               if ( *cp < '0' || *cp > '9' ) {
-                   break;
-               }
-               n = n * 10 + ( *cp - '0' );
-           }
-       }
-       lp.lp_seq = n;
-
-       n = ( n + 1 ) % 1000;
-       sprintf( buf, "%03d\n", n );
-       lseek( fd, 0L, 0 );
-       write( fd, buf, strlen( buf ));
-       close( fd );
-#else
-
-       if (cups_get_printer_status ( printer ) == 0)
-       {
-           spoolerror( out, "Queuing is disabled." );
-           return( -1 );
-       }
-
-       lp.lp_seq = getpid();
-#endif /* HAVE CUPS */
-    } else {
-       lp.lp_flags |= LP_PIPE;
-       lp.lp_seq = getpid();
-    }
-
-    lp.lp_flags |= LP_INIT;
-    return( 0 );
-}
-
-int lp_open(struct papfile *out, struct sockaddr_at *sat)
-{
-    char       name[ MAXPATHLEN ];
-    int                fd;
-    struct passwd      *pwent;
-
-#ifdef DEBUG
-    LOG (log_debug9, logtype_papd, "lp_open");
-#endif
-
-    if ( lp.lp_flags & LP_JOBPENDING ) {
-       lp_print();
-    }
-
-    if (( lp.lp_flags & LP_INIT ) == 0 && lp_init( out, sat ) != 0 ) {
-       return( -1 );
-    }
-    if ( lp.lp_flags & LP_OPEN ) {
-       /* LOG(log_error, logtype_papd, "lp_open already open" ); */
-       /* abort(); */
-       return (-1);
-    }
-
-    if ( lp.lp_flags & LP_PIPE ) {
-        char *pipe_cmd;
-
-       /* go right to program */
-       if (lp.lp_person != NULL) {
-           if((pwent = getpwnam(lp.lp_person)) != NULL) {
-               if(setreuid(pwent->pw_uid, pwent->pw_uid) != 0) {
-                   LOG(log_error, logtype_papd, "setreuid error: %s", strerror(errno));
-                   exit(1);
-               }
-           } else {
-               LOG(log_error, logtype_papd, "Error getting username (%s)", lp.lp_person);
-                exit(1);
-           }
-       }
-
-       lp_setup_comments(CH_UNIX);
-       pipe_cmd = printer->p_printer;
-       if (!pipe_cmd) {
-           LOG(log_error, logtype_papd, "lp_open: no pipe cmd" );
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-       if (( lp.lp_stream = popen(pipe_cmd, "w" )) == NULL ) {
-           LOG(log_error, logtype_papd, "lp_open popen %s: %s", printer->p_printer, strerror(errno) );
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-        LOG(log_debug, logtype_papd, "lp_open: opened %s",  pipe_cmd );
-    } else {
-       sprintf( name, "df%c%03d%s", lp.lp_letter++, lp.lp_seq, hostname );
-
-       if (( fd = open( name, O_WRONLY|O_CREAT|O_EXCL, 0660 )) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_open %s: %s", name, strerror(errno) );
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-
-       if ( NULL == (lp.lp_spoolfile = (char *) malloc (strlen (name) +1)) ) {
-           LOG(log_error, logtype_papd, "malloc: %s", strerror(errno));
-           exit(1);
-       }
-       strcpy ( lp.lp_spoolfile, name);        
-
-       if (lp.lp_person != NULL) {
-           if ((pwent = getpwnam(lp.lp_person)) == NULL) {
-               LOG(log_error, logtype_papd, "getpwnam %s: no such user", lp.lp_person);
-               spoolerror( out, NULL );
-               return( -1 );
-           }
-       } else {
-           if ((pwent = getpwnam(printer->p_operator)) == NULL) {
-               LOG(log_error, logtype_papd, "getpwnam %s: no such user", printer->p_operator);
-               spoolerror( out, NULL );
-               return( -1 );
-           }
-       }
-
-       if (fchown(fd, pwent->pw_uid, -1) < 0) {
-           LOG(log_error, logtype_papd, "chown %s %s: %s", pwent->pw_name, name, strerror(errno));
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-
-       if (( lp.lp_stream = fdopen( fd, "w" )) == NULL ) {
-           LOG(log_error, logtype_papd, "lp_open fdopen: %s", strerror(errno) );
-           spoolerror( out, NULL );
-           return( -1 );
-       }
-#ifdef DEBUG        
-        LOG(log_debug9, logtype_papd, "lp_open: opened %s", name );
-#endif 
-    }
-    lp.lp_flags |= LP_OPEN;
-    return( 0 );
-}
-
-int lp_close(void)
-{
-    if (( lp.lp_flags & LP_INIT ) == 0 || ( lp.lp_flags & LP_OPEN ) == 0 ) {
-       return 0;
-    }
-    fclose( lp.lp_stream );
-    lp.lp_stream = NULL;
-    lp.lp_flags &= ~LP_OPEN;
-    lp.lp_flags |= LP_JOBPENDING;
-    return 0;
-}
-
-
-
-int lp_write(struct papfile *in, char *buf, size_t len)
-{
-#define BUFSIZE 32768
-    static char tempbuf[BUFSIZE];
-    static char tempbuf2[BUFSIZE];
-    static size_t bufpos = 0;
-    static int last_line_translated = 1; /* if 0, append a \n a the start */
-    char *tbuf = buf;
-
-    /* Before we write out anything check for a pending job, e.g. cover page */
-    if (lp.lp_flags & LP_JOBPENDING)
-       lp_print();
-
-    /* foomatic doesn't handle mac line endings, so we convert them for 
-     * the Postscript headers
-     * REALLY ugly hack, remove ASAP again */
-    if ((printer->p_flags & P_FOOMATIC_HACK) && (in->pf_state & PF_TRANSLATE) && 
-        (buf[len-1] != '\n') ) {
-        if (len <= BUFSIZE) {
-           if (!last_line_translated) {
-               tempbuf2[0] = '\n';
-               memcpy(tempbuf2+1, buf, len++);
-           }
-           else
-               memcpy(tempbuf2, buf, len);
-               
-            if (tempbuf2[len-1] == '\r')
-               tempbuf2[len-1] = '\n';
-            tempbuf2[len] = 0;
-            tbuf = tempbuf2;
-            last_line_translated = 1;
-#ifdef DEBUG
-            LOG(log_debug9, logtype_papd, "lp_write: %s", tbuf );
-#endif
-        }
-        else {
-            LOG(log_error, logtype_papd, "lp_write: conversion buffer too small" );
-            abort();
-        }
-    }
-    else {
-        if (printer->p_flags & P_FOOMATIC_HACK && buf[len-1] == '\n') {
-            last_line_translated = 1;
-       }
-        else
-           last_line_translated = 0;
-    }
-
-    /* To be able to do commandline substitutions on piped printers
-     * we store the start of the print job in a buffer.
-     * %%EndComment triggers writing to file */
-    if (( lp.lp_flags & LP_OPEN ) == 0 ) {
-#ifdef DEBUG
-        LOG(log_debug9, logtype_papd, "lp_write: writing to temporary buffer" );
-#endif
-       if ((bufpos+len) > BUFSIZE) {
-            LOG(log_error, logtype_papd, "lp_write: temporary buffer too small" );
-            /* FIXME: call lp_open here? abort isn't nice... */
-            abort();
-        }
-       else {
-            memcpy(tempbuf + bufpos, tbuf, len);
-            bufpos += len;
-            if (bufpos > BUFSIZE/2)
-                in->pf_state |= PF_STW; /* we used half of the buffer, start writing */
-            return(0);
-       }
-    }
-    else if ( bufpos) {
-        if ( fwrite( tempbuf, 1, bufpos, lp.lp_stream ) != bufpos ) {
-            LOG(log_error, logtype_papd, "lp_write: %s", strerror(errno) );
-            abort();
-        }
-        bufpos=0;
-    }
-
-    if ( fwrite( tbuf, 1, len, lp.lp_stream ) != len ) {
-       LOG(log_error, logtype_papd, "lp_write: %s", strerror(errno) );
-       abort();
-    }
-    return( 0 );
-}
-
-int lp_cancel(void)
-{
-    char       name[ MAXPATHLEN ];
-    char       letter;
-
-    if (( lp.lp_flags & LP_INIT ) == 0 || lp.lp_letter == 'A' ) {
-       return 0;
-    }
-
-    if ( lp.lp_flags & LP_OPEN ) {
-       lp_close();
-    }
-
-    for ( letter = 'A'; letter < lp.lp_letter; letter++ ) {
-       sprintf( name, "df%c%03d%s", letter, lp.lp_seq, hostname );
-       if ( unlink( name ) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_cancel unlink %s: %s", name, strerror(errno) );
-       }
-    }
-
-    return 0;
-}
-
-/*
- * Create printcap control file, signal printer.  Errors here should
- * remove queue files.
- *
- * XXX piped?
- */
-int lp_print(void)
-{
-#ifndef HAVE_CUPS
-    char               buf[ MAXPATHLEN ];
-    char               tfname[ MAXPATHLEN ];
-    char               cfname[ MAXPATHLEN ];
-    char               letter;
-    int                        fd, n, s;
-    FILE               *cfile;
-#endif /* HAVE_CUPS */
-
-    if (( lp.lp_flags & LP_INIT ) == 0 || lp.lp_letter == 'A' ) {
-       return 0;
-    }
-    lp_close();
-    lp.lp_flags &= ~LP_JOBPENDING;
-
-    if ( printer->p_flags & P_SPOOLED ) {
-#ifndef HAVE_CUPS
-       sprintf( tfname, "tfA%03d%s", lp.lp_seq, hostname );
-       if (( fd = open( tfname, O_WRONLY|O_EXCL|O_CREAT, 0660 )) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_print %s: %s", tfname, strerror(errno) );
-           return 0;
-       }
-       if (( cfile = fdopen( fd, "w" )) == NULL ) {
-           LOG(log_error, logtype_papd, "lp_print %s: %s", tfname, strerror(errno) );
-           return 0;
-       }
-       fprintf( cfile, "H%s\n", hostname );    /* XXX lp_host? */
-
-       if ( lp.lp_person ) {
-           fprintf( cfile, "P%s\n", lp.lp_person );
-       } else {
-           fprintf( cfile, "P%s\n", printer->p_operator );
-       }
-
-       if ( lp.lp_job && *lp.lp_job ) {
-           fprintf( cfile, "J%s\n", lp.lp_job );
-           fprintf( cfile, "T%s\n", lp.lp_job );
-       } else {
-           fprintf( cfile, "JMac Job\n" );
-           fprintf( cfile, "TMac Job\n" );
-       }
-
-       fprintf( cfile, "C%s\n", hostname );    /* XXX lp_host? */
-
-       if ( lp.lp_person ) {
-           fprintf( cfile, "L%s\n", lp.lp_person );
-       } else {
-           fprintf( cfile, "L%s\n", printer->p_operator );
-       }
-
-       for ( letter = 'A'; letter < lp.lp_letter; letter++ ) {
-           fprintf( cfile, "fdf%c%03d%s\n", letter, lp.lp_seq, hostname );
-           fprintf( cfile, "Udf%c%03d%s\n", letter, lp.lp_seq, hostname );
-       }
-
-       if ( lp.lp_job && *lp.lp_job ) {
-           fprintf( cfile, "N%s\n", lp.lp_job );
-       } else {
-           fprintf( cfile, "NMac Job\n" );
-       }
-       fclose( cfile );
-
-       sprintf( cfname, "cfA%03d%s", lp.lp_seq, hostname );
-       if ( link( tfname, cfname ) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_print can't link %s to %s: %s", cfname,
-                   tfname, strerror(errno) );
-           return 0;
-       }
-       unlink( tfname );
-
-       if (( s = lp_conn_unix()) < 0 ) {
-           LOG(log_error, logtype_papd, "lp_print: lp_conn_unix: %s", strerror(errno) );
-           return 0;
-       }
-
-       sprintf( buf, "\1%s\n", printer->p_printer );
-       n = strlen( buf );
-       if ( write( s, buf, n ) != n ) {
-           LOG(log_error, logtype_papd, "lp_print write: %s" , strerror(errno));
-           return 0;
-       }
-       if ( read( s, buf, 1 ) != 1 ) {
-           LOG(log_error, logtype_papd, "lp_print read: %s" , strerror(errno));
-           return 0;
-       }
-
-       lp_disconn_unix( s );
-
-       if ( buf[ 0 ] != '\0' ) {
-           LOG(log_error, logtype_papd, "lp_print lpd said %c: %s", buf[ 0 ], strerror(errno) );
-           return 0;
-       }
-#else
-        if ( ! (lp.lp_job && *lp.lp_job) ) {
-            lp.lp_job = strdup("Mac Job");
-        }
-
-        lp_setup_comments(add_charset(cups_get_language ()));
-
-        if (lp.lp_person != NULL) {
-           cups_print_job ( printer->p_printer, lp.lp_spoolfile, lp.lp_job, lp.lp_person, printer->p_cupsoptions);
-        } else if (lp.lp_created_for != NULL) {
-            cups_print_job ( printer->p_printer, lp.lp_spoolfile, lp.lp_job, lp.lp_created_for, printer->p_cupsoptions);
-        } else {
-            cups_print_job ( printer->p_printer, lp.lp_spoolfile, lp.lp_job, printer->p_operator, printer->p_cupsoptions);
-        }
-
-       /*LOG(log_info, logtype_papd, "lp_print unlink %s", lp.lp_spoolfile );*/
-        unlink ( lp.lp_spoolfile );
-       return 0;
-#endif /* HAVE_CUPS*/
-    }
-    LOG(log_info, logtype_papd, "lp_print queued" );
-    return 0;
-}
-
-#ifndef HAVE_CUPS
-int lp_disconn_unix( int fd )
-{
-    return( close( fd ));
-}
-
-int lp_conn_unix(void)
-{
-    int                        s;
-    struct sockaddr_un saun;
-
-    if (( s = socket( AF_UNIX, SOCK_STREAM, 0 )) < 0 ) {
-       LOG(log_error, logtype_papd, "lp_conn_unix socket: %s", strerror(errno) );
-       return( -1 );
-    }
-    memset( &saun, 0, sizeof( struct sockaddr_un ));
-    saun.sun_family = AF_UNIX;
-    strcpy( saun.sun_path, _PATH_DEVPRINTER );
-    if ( connect( s, (struct sockaddr *)&saun,
-           strlen( saun.sun_path ) + 2 ) < 0 ) {
-       LOG(log_error, logtype_papd, "lp_conn_unix connect %s: %s", saun.sun_path, strerror(errno) );
-       close( s );
-       return( -1 );
-    }
-
-    return( s );
-}
-
-int lp_disconn_inet( int fd )
-{
-    return( close( fd ));
-}
-
-int lp_conn_inet(void)
-{
-    int                        privfd, port = IPPORT_RESERVED - 1;
-    struct sockaddr_in sin;
-    struct servent     *sp;
-    struct hostent     *hp;
-
-    if (( sp = getservbyname( "printer", "tcp" )) == NULL ) {
-       LOG(log_error, logtype_papd, "printer/tcp: unknown service" );
-       return( -1 );
-    }
-
-    if ( gethostname( hostname, sizeof( hostname )) < 0 ) {
-       LOG(log_error, logtype_papd, "gethostname: %s", strerror(errno) );
-       exit( 1 );
-    }
-
-    if (( hp = gethostbyname( hostname )) == NULL ) {
-       LOG(log_error, logtype_papd, "%s: unknown host", hostname );
-       return( -1 );
-    }
-
-    if (( privfd = rresvport( &port )) < 0 ) {
-       LOG(log_error, logtype_papd, "lp_connect: socket: %s", strerror(errno) );
-       close( privfd );
-       return( -1 );
-    }
-
-    memset( &sin, 0, sizeof( struct sockaddr_in ));
-    sin.sin_family = AF_INET;
-/*    sin.sin_addr.s_addr = htonl( INADDR_LOOPBACK ); */
-    memcpy( &sin.sin_addr, hp->h_addr, hp->h_length );
-    sin.sin_port = sp->s_port;
-
-    if ( connect( privfd, (struct sockaddr *)&sin,
-           sizeof( struct sockaddr_in )) < 0 ) {
-       LOG(log_error, logtype_papd, "lp_connect: %s", strerror(errno) );
-       close( privfd );
-       return( -1 );
-    }
-
-    return( privfd );
-}
-
-int lp_rmjob( int job)
-{
-    char       buf[ 1024 ];
-    int                n, s;
-
-    if (( s = lp_conn_inet()) < 0 ) {
-       LOG(log_error, logtype_papd, "lp_rmjob: %s", strerror(errno) );
-       return( -1 );
-    }
-
-    if ( lp.lp_person == NULL ) {
-       return( -1 );
-    }
-
-    sprintf( buf, "\5%s %s %d\n", printer->p_printer, lp.lp_person, job );
-    n = strlen( buf );
-    if ( write( s, buf, n ) != n ) {
-       LOG(log_error, logtype_papd, "lp_rmjob write: %s", strerror(errno) );
-       lp_disconn_inet( s );
-       return( -1 );
-    }
-    while (( n = read( s, buf, sizeof( buf ))) > 0 ) {
-       LOG(log_debug, logtype_papd, "read %.*s", n, buf );
-    }
-
-    lp_disconn_inet( s );
-    return( 0 );
-}
-
-char   *kw_rank = "Rank";
-char   *kw_active = "active";
-
-char   *tag_rank = "rank: ";
-char   *tag_owner = "owner: ";
-char   *tag_job = "job: ";
-char   *tag_files = "files: ";
-char   *tag_size = "size: ";
-char   *tag_status = "status: ";
-
-int lp_queue( struct papfile *out)
-{
-    char                       buf[ 1024 ], *start, *stop, *p, *q;
-    int                                linelength, crlflength;
-    static struct papfile      pf;
-    int                                s;
-    size_t                     len;
-    ssize_t                    n;
-       
-    if (( s = lp_conn_unix()) < 0 ) {
-       LOG(log_error, logtype_papd, "lp_queue: %s", strerror(errno) );
-       return( -1 );
-    }
-
-    sprintf( buf, "\3%s\n", printer->p_printer );
-    n = strlen( buf );
-    if ( write( s, buf, n ) != n ) {
-       LOG(log_error, logtype_papd, "lp_queue write: %s", strerror(errno) );
-       lp_disconn_unix( s );
-       return( -1 );
-    }
-    pf.pf_state = PF_BOT;
-
-    while (( n = read( s, buf, sizeof( buf ))) > 0 ) {
-       append( &pf, buf, n );
-    }
-
-    for (;;) {
-       if ( markline( &pf, &start, &linelength, &crlflength ) > 0 ) {
-           /* parse */
-           stop = start + linelength;
-           for ( p = start; p < stop; p++ ) {
-               if ( *p == ' ' || *p == '\t' ) {
-                   break;
-               }
-           }
-           if ( p >= stop ) {
-               CONSUME( &pf , linelength + crlflength);
-               continue;
-           }
-
-           /*
-            * Keys: "Rank", a number, "active"
-            * Anything else is status.
-            */
-           len = p - start;
-           if ( len == strlen( kw_rank ) &&
-                   strncmp( kw_rank, start, len ) == 0 ) {
-               CONSUME( &pf, linelength + crlflength );
-               continue;
-           }
-           if (( len == strlen( kw_active ) &&
-                   strncmp( kw_active, start, len ) == 0 ) ||
-                   isdigit( *start )) {                /* a job line */
-               append( out, tag_rank, strlen( tag_rank ));
-               append( out, start, p - start );
-               append( out, "\n", 1 );
-
-               for ( ; p < stop; p++ ) {
-                   if ( *p != ' ' && *p != '\t' ) {
-                       break;
-                   }
-               }
-               for ( q = p; p < stop; p++ ) {
-                   if ( *p == ' ' || *p == '\t' ) {
-                       break;
-                   }
-               }
-               if ( p >= stop ) {
-                   append( out, ".\n", 2 );
-                   CONSUME( &pf, linelength + crlflength );
-                   continue;
-               }
-               append( out, tag_owner, strlen( tag_owner ));
-               append( out, q, p - q );
-               append( out, "\n", 1 );
-
-               for ( ; p < stop; p++ ) {
-                   if ( *p != ' ' && *p != '\t' ) {
-                       break;
-                   }
-               }
-               for ( q = p; p < stop; p++ ) {
-                   if ( *p == ' ' || *p == '\t' ) {
-                       break;
-                   }
-               }
-               if ( p >= stop ) {
-                   append( out, ".\n", 2 );
-                   CONSUME( &pf , linelength + crlflength );
-                   continue;
-               }
-               append( out, tag_job, strlen( tag_job ));
-               append( out, q, p - q );
-               append( out, "\n", 1 );
-
-               for ( ; p < stop; p++ ) {
-                   if ( *p != ' ' && *p != '\t' ) {
-                       break;
-                   }
-               }
-               for ( q = p, p = stop; p > q; p-- ) {
-                   if ( *p == ' ' || *p == '\t' ) {
-                       break;
-                   }
-               }
-               for ( ; p > q; p-- ) {
-                   if ( *p != ' ' && *p != '\t' ) {
-                       break;
-                   }
-               }
-               for ( ; p > q; p-- ) {
-                   if ( *p == ' ' || *p == '\t' ) {
-                       break;
-                   }
-               }
-               if ( p <= q ) {
-                   append( out, ".\n", 2 );
-                   CONSUME( &pf, linelength + crlflength );
-                   continue;
-               }
-               append( out, tag_files, strlen( tag_files ));
-               append( out, q, p - q );
-               append( out, "\n", 1 );
-
-               for ( ; p < stop; p++ ) {
-                   if ( *p != ' ' && *p != '\t' ) {
-                       break;
-                   }
-               }
-               append( out, tag_size, strlen( tag_size ));
-               append( out, p, stop - p );
-               append( out, "\n.\n", 3 );
-
-               CONSUME( &pf, linelength + crlflength );
-               continue;
-           }
-
-           /* status */
-           append( out, tag_status, strlen( tag_status ));
-           append( out, start, linelength );
-           append( out, "\n.\n", 3 );
-
-           CONSUME( &pf, linelength + crlflength );
-       } else {
-           append( out, "*\n", 2 );
-           lp_disconn_unix( s );
-           return( 0 );
-       }
-    }
-}
-#endif /* HAVE_CUPS */
diff --git a/etc/papd/lp.h b/etc/papd/lp.h
deleted file mode 100644 (file)
index 6a3dd68..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * $Id: lp.h,v 1.6 2009-10-13 22:55:37 didg Exp $
- */
-
-#ifndef PAPD_LP_H
-#define PAPD_LP_H 1
-
-#include <sys/socket.h>
-#include <sys/cdefs.h>
-#include "file.h"
-
-void lp_person ( char * );
-int lp_pagecost ( void );
-void lp_host ( char * );
-void lp_job ( char * );
-void lp_for ( char * );
-void lp_origin ( int );
-int lp_rmjob ( int );
-int lp_queue ( struct papfile * );
-
-/* cancel current job */
-int lp_cancel ( void );
-/* print current job */
-int lp_print ( void );
-/* open a file for spooling */
-int lp_open ( struct papfile *, struct sockaddr_at * );
-/* open a buffer to the current open file */
-int lp_write ( struct papfile *,char *, size_t );
-/* close current spooling file */
-int lp_close ( void );
-
-#endif /* PAPD_LP_H */
diff --git a/etc/papd/magics.c b/etc/papd/magics.c
deleted file mode 100644 (file)
index 5e128e5..0000000
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * $Id: magics.c,v 1.15 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <atalk/logger.h>
-#include <sys/param.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include <netatalk/at.h>
-
-#include "file.h"
-#include "comment.h"
-#include "lp.h"
-
-static int state=0;
-
-static void parser_error(struct papfile *outfile)
-{
-                spoolerror( outfile, "Comments error, Ignoring job." );
-               outfile->pf_state |= PF_EOF;
-               lp_close();
-}
-
-int ps( struct papfile *infile, struct papfile *outfile, struct sockaddr_at *sat)
-{
-    char                       *start;
-    int                                linelength, crlflength;
-    struct papd_comment                *comment;
-
-    for (;;) {
-        if ( infile->pf_state & PF_STW ) {
-               infile->pf_state &= ~PF_STW;
-               /* set up spool file */
-               if ( lp_open( outfile, sat ) < 0 && !state) {
-                   LOG(log_error, logtype_papd, "lp_open failed" );
-                   spoolerror( outfile, "Ignoring job." );
-               }
-               state = 1;
-       }       
-       if ( (comment = compeek()) ) {
-           switch( (*comment->c_handler)( infile, outfile, sat )) {
-           case CH_DONE :
-               continue;
-
-           case CH_MORE :
-               return( CH_MORE );
-
-           case CH_ERROR :
-               parser_error(outfile);
-               return( 0 );
-
-           default :
-               return( CH_ERROR );
-           }
-       } else {
-           switch ( markline( infile, &start, &linelength, &crlflength )) {
-           case 0 :
-               /* eof on infile */
-               outfile->pf_state |= PF_EOF;
-               lp_close();
-               return( 0 );
-
-           case -2:
-               parser_error(outfile);
-               return( 0 );
-
-           case -1 :
-               return( 0 );
-           }
-
-           if ( infile->pf_state & PF_BOT ) {
-               if (( comment = commatch( start, start+linelength, magics )) != NULL ) {
-                   compush( comment );
-                   continue;   /* top of for (;;) */
-               }
-#if 0
-               infile->pf_state &= ~PF_BOT;
-
-               /* set up spool file */
-               if ( lp_open( outfile, sat ) < 0 ) {
-                   LOG(log_error, logtype_papd, "lp_open failed" );
-                   spoolerror( outfile, "Ignoring job." );
-               }
-#endif
-           }
-
-           /* write to file */
-           lp_write( infile, start, linelength + crlflength );
-           CONSUME( infile, linelength + crlflength );
-       }
-    }
-}
-
-int cm_psquery( struct papfile *in, struct papfile *out, struct sockaddr_at *sat _U_)
-{
-    struct papd_comment        *comment;
-    char               *start;
-    int                        linelength, crlflength;
-
-    for (;;) {
-       switch ( markline( in, &start, &linelength, &crlflength )) {
-       case 0 :
-           /* eof on infile */
-           out->pf_state |= PF_EOF;
-           compop();
-           return( CH_DONE );
-
-       case -1 :
-           return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-       }
-
-       if ( in->pf_state & PF_BOT ) {
-           in->pf_state &= ~PF_BOT;
-       } else {
-           if (( comment = commatch( start, start+linelength, queries )) != NULL ) {
-               compush( comment );
-               return( CH_DONE );
-           }
-       }
-
-       CONSUME( in, linelength + crlflength );
-    }
-}
-
-int cm_psadobe( struct papfile *in, struct papfile *out, struct sockaddr_at *sat _U_)
-{
-    char               *start;
-    int                        linelength, crlflength;
-    struct papd_comment        *comment = compeek();
-
-    for (;;) {
-       switch ( markline( in, &start, &linelength, &crlflength )) {
-       case 0 :
-           /* eof on infile */
-           out->pf_state |= PF_EOF;
-           compop();
-           return( CH_DONE );
-
-       case -1 :
-           return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-       }
-       if ( in->pf_state & PF_BOT ) {
-           in->pf_state &= ~PF_BOT;
-#if 0
-           if ( lp_open( out, sat ) < 0 ) {
-               LOG(log_error, logtype_papd, "lp_open failed" );
-               spoolerror( out, "Ignoring job." );
-           }
-#endif
-       } else {
-           if (( comment = commatch( start, start + linelength, headers )) != NULL ) {
-               compush( comment );
-               return( CH_DONE );
-           }
-       }
-
-       lp_write( in, start, linelength + crlflength );
-       CONSUME( in, linelength + crlflength );
-    }
-}
-
-char   *Query = "Query";
-
-int cm_psswitch(struct papfile *in, struct papfile *out, struct sockaddr_at *sat _U_)
-{
-    char               *start, *stop, *p;
-    int                        linelength, crlflength;
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-       /* eof on infile */
-       out->pf_state |= PF_EOF;
-       compop();
-       return( 0 );
-
-    case -1 :
-       return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    stop = start + linelength;
-    for ( p = start; p < stop; p++ ) {
-       if ( *p == ' ' || *p == '\t' ) {
-           break;
-       }
-    }
-    for ( ; p < stop; p++ ) {
-       if ( *p != ' ' && *p != '\t' ) {
-           break;
-       }
-    }
-
-    if ( (size_t)(stop - p) >= strlen( Query ) &&
-           strncmp( p, Query, strlen( Query )) == 0 ) {
-       if ( comswitch( magics, cm_psquery ) < 0 ) {
-           LOG(log_error, logtype_papd, "cm_psswitch: can't find psquery!" );
-           exit( 1 );
-       }
-    } else {
-       if ( comswitch( magics, cm_psadobe ) < 0 ) {
-           LOG(log_error, logtype_papd, "cm_psswitch: can't find psadobe!" );
-           exit( 1 );
-       }
-    }
-    return( CH_DONE );
-}
-
-
-struct papd_comment    magics[] = {
-    { "%!PS-Adobe-3.0 Query",  NULL,                   cm_psquery, C_FULL },
-    { "%!PS-Adobe-3.0",                NULL,                   cm_psadobe, C_FULL },
-    { "%!PS-Adobe-",           NULL,                   cm_psswitch,    0 },
-    { NULL,                    NULL,                   NULL,           0 },
-};
diff --git a/etc/papd/main.c b/etc/papd/main.c
deleted file mode 100644 (file)
index d0c4645..0000000
+++ /dev/null
@@ -1,950 +0,0 @@
-/*
- * $Id: main.c,v 1.31 2009-10-29 13:38:15 didg Exp $
- *
- * Copyright (c) 1990,1995 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-
-#include <sys/param.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/file.h>
-#include <sys/socket.h>
-#include <atalk/logger.h>
-
-/* POSIX.1 sys/wait.h check */
-#include <sys/types.h>
-#ifdef HAVE_SYS_WAIT_H
-#include <sys/wait.h>
-#endif /* HAVE_SYS_WAIT_H */
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
-#endif /* ! WEXITSTATUS */
-#ifndef WIFEXITED
-#define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
-#endif /* ! WIFEXITED */
-
-#include <errno.h>
-
-/* STDC check */
-#if STDC_HEADERS
-#include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <netdb.h>
-#include <fcntl.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/compat.h>
-#include <atalk/atp.h>
-#include <atalk/pap.h>
-#include <atalk/paths.h>
-#include <atalk/util.h>
-#include <atalk/nbp.h>
-#include <atalk/unicode.h>
-
-#include "printer.h"
-#include "printcap.h"
-#include "session.h"
-#include "uam_auth.h"
-#include "print_cups.h"
-
-
-#define PIPED_STATUS   "status: print spooler processing job"
-
-struct printer defprinter;
-struct printer *printers = NULL;
-
-int            debug = 0;
-static char    *conffile = _PATH_PAPDCONF;
-char           *printcap = _PATH_PAPDPRINTCAP;
-unsigned char  connid, quantum, sock, oquantum = PAP_MAXQUANTUM;
-char           *cannedstatus = PIPED_STATUS;
-struct printer *printer = NULL;
-char           *version = VERSION;
-static char    *pidfile = _PATH_PAPDLOCK;
-
-char           *uamlist;
-char           *uampath = _PATH_PAPDUAMPATH;
-
-/* Prototypes for locally used functions */
-int getstatus( struct printer *pr, char *buf );
-int rprintcap( struct printer *pr );
-static void getprinters( char *cf );
-
-
-/* this only needs to be used by the server process */
-static void papd_exit(const int i)
-{
-  server_unlock(pidfile);
-  auth_unload();
-  exit(i);
-}
-
-static void
-die(int n)
-{
-    struct printer     *pr;
-    struct at_addr     addr;
-
-    memset(&addr, 0, sizeof(addr));
-
-    for ( pr = printers; pr; pr = pr->p_next ) {
-       if ( pr->p_flags & P_REGISTERED ) {
-           if ( nbp_unrgstr( pr->p_name, pr->p_type, pr->p_zone, &addr ) < 0 ) {
-               LOG(log_error, logtype_papd, "can't unregister %s:%s@%s", pr->p_name,
-                       pr->p_type, pr->p_zone );
-               papd_exit( n + 1 );
-           }
-           LOG(log_info, logtype_papd, "unregister %s:%s@%s", pr->p_name, pr->p_type,
-                   pr->p_zone );
-       }
-#ifdef HAVE_CUPS
-       if ( pr->p_flags & P_SPOOLED && pr->p_flags & P_CUPS_PPD ) {
-               LOG(log_info, logtype_papd, "Deleting CUPS temp PPD file for %s (%s)", pr->p_name, pr->p_ppdfile);
-               unlink (pr->p_ppdfile);
-       }
-#endif /* HAVE_CUPS */
-
-    }
-    papd_exit( n );
-}
-
-static void
-reap(int sig _U_)
-{
-    int                status;
-    int                pid;
-
-    while (( pid = wait3( &status, WNOHANG, NULL )) > 0 ) {
-       if ( WIFEXITED( status )) {
-           if ( WEXITSTATUS( status )) {
-               LOG(log_error, logtype_papd, "child %d exited with %d", pid,
-                       WEXITSTATUS( status ));
-           } else {
-               LOG(log_info, logtype_papd, "child %d done", pid );
-           }
-       } else {
-           if ( WIFSIGNALED( status )) {
-               LOG(log_error, logtype_papd, "child %d killed with %d", pid,
-                       WTERMSIG( status ));
-           } else {
-               LOG(log_error, logtype_papd, "child %d died", pid );
-           }
-       }
-    }
-    return;
-}
-
-static char rbuf[ 255 + 1 + 8 ];
-
-int main(int ac, char **av)
-{
-    extern char         *optarg;
-
-    ATP                        atp;
-    struct atp_block   atpb;
-    struct sockaddr_at sat;
-    struct sigaction   sv;
-    struct iovec       iov;
-    fd_set             fdset;
-    struct printer     *pr;
-    char               *p, hostname[ MAXHOSTNAMELEN ];
-    char               cbuf[ 8 ];
-    int                        c;
-    char               *atname;
-
-    if ( gethostname( hostname, sizeof( hostname )) < 0 ) {
-       perror( "gethostname" );
-       exit( 1 );
-    }
-    if (( p = strchr( hostname, '.' )) != NULL ) {
-       *p = '\0';
-    }
-    if (( defprinter.p_name = (char *)malloc( strlen( hostname ) + 1 ))
-           == NULL ) {
-       perror( "malloc" );
-       exit( 1 );
-    }
-    strcpy( defprinter.p_name, hostname );
-    defprinter.p_type = "LaserWriter";
-    defprinter.p_zone = "*";
-    memset(&defprinter.p_addr, 0, sizeof(defprinter.p_addr));
-#ifdef __svr4__
-    defprinter.p_flags = P_PIPED;
-    defprinter.p_printer = "/usr/bin/lp -T PS";
-#else /* __svr4__ */
-    defprinter.p_flags = P_SPOOLED;
-    defprinter.p_printer = "lp";
-#endif /* __svr4__ */
-    defprinter.p_operator = "operator";
-    defprinter.p_spool = _PATH_PAPDSPOOLDIR;
-#ifdef ABS_PRINT
-    defprinter.p_role = NULL;
-    defprinter.p_srvid = 0;
-#endif /* ABS_PRINT */
-    defprinter.p_pagecost = 200;               /* default cost */
-    defprinter.p_pagecost_msg = NULL;
-    defprinter.p_lock = "lock";
-
-    while (( c = getopt( ac, av, "adf:p:P:v" )) != EOF ) {
-       switch ( c ) {
-       case 'a' :              /* for compatibility with old papd */
-           break;
-
-       case 'd' :              /* debug */
-           debug++;
-           break;
-
-       case 'f' :              /* conffile */
-           conffile = optarg;
-           break;
-
-       case 'p' :              /* printcap */
-           printcap = optarg;
-           break;
-
-       case 'P' :
-           pidfile = optarg;
-           break;
-
-       case 'v' :              /* version */
-           printf( "papd (version %s)\n", VERSION );
-           exit ( 1 );
-           break;
-
-       default :
-           fprintf( stderr,
-                   "Usage:\t%s [ -d ] [ -f conffile ] [ -p printcap ]\n",
-                   *av );
-           exit( 1 );
-       }
-    }
-
-
-    switch (server_lock("papd", pidfile, debug)) {
-    case 0: /* open a couple things again in the child */
-      if (!debug && (c = open("/", O_RDONLY)) >= 0) {
-       dup2(c, 1);
-       dup2(c, 2);
-      }
-      break;
-    case -1:
-      exit(1);
-    default:
-      exit(0);
-    }      
-
-#ifdef DEBUG1
-    fault_setup(NULL);
-#endif
-
-    /*
-     * Start logging.
-     */
-    if (( p = strrchr( av[ 0 ], '/' )) == NULL ) {
-       p = av[ 0 ];
-    } else {
-       p++;
-    }
-#ifdef ultrix
-    openlog( p, LOG_PID );
-#else /* ultrix */
-    set_processname(p);
-    syslog_setup(log_debug, logtype_default, logoption_ndelay | logoption_pid |
-               debug ? logoption_perror : 0, logfacility_lpr );
-#endif /* ultrix */
-
-    LOG(log_info, logtype_papd, "restart (%s)", version );
-#ifdef HAVE_CUPS
-    LOG(log_info, logtype_papd, "CUPS support enabled (%s)", CUPS_API_VERSION );
-#endif
-
-    getprinters( conffile );
-
-    for ( pr = printers; pr; pr = pr->p_next ) {
-       if (( pr->p_flags & P_SPOOLED ) && rprintcap( pr ) < 0 ) {
-           LOG(log_error, logtype_papd, "printcap problem: %s", pr->p_printer );
-       }
-
-       if (!(pr->p_flags & P_CUPS)) {
-               if ((size_t)-1 != convert_string_allocate(CH_UNIX, CH_MAC, pr->p_name, -1, &atname)) {
-                       pr->p_u_name = pr->p_name;
-                       pr->p_name = atname;
-               }
-       }
-                       
-       if (( pr->p_atp = atp_open( ATADDR_ANYPORT, &pr->p_addr )) == NULL ) {
-           LOG(log_error, logtype_papd, "atp_open: %s", strerror(errno) );
-           papd_exit( 1 );
-       }
-       if ( nbp_rgstr( atp_sockaddr( pr->p_atp ), pr->p_name, pr->p_type,
-               pr->p_zone ) < 0 ) {
-           LOG(log_error, logtype_papd, "can't register %s:%s@%s", pr->p_u_name, pr->p_type,
-                   pr->p_zone );
-           die( 1 );
-       }
-       if ( pr->p_flags & P_AUTH ) {
-               LOG(log_info, logtype_papd, "Authentication enabled: %s", pr->p_u_name );
-       }
-       else {
-               LOG(log_info, logtype_papd, "Authentication disabled: %s", pr->p_u_name );
-       }
-       LOG(log_info, logtype_papd, "register %s:%s@%s", pr->p_u_name, pr->p_type,
-               pr->p_zone );
-       pr->p_flags |= P_REGISTERED;
-    }
-
-    memset(&sv, 0, sizeof(sv));
-    sv.sa_handler = die;
-    sigemptyset( &sv.sa_mask );
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGTERM, &sv, NULL ) < 0 ) {
-       LOG(log_error, logtype_papd, "sigaction: %s", strerror(errno) );
-       papd_exit( 1 );
-    }
-
-    sv.sa_handler = reap;
-    sigemptyset( &sv.sa_mask );
-    sv.sa_flags = SA_RESTART;
-    if ( sigaction( SIGCHLD, &sv, NULL ) < 0 ) {
-       LOG(log_error, logtype_papd, "sigaction: %s", strerror(errno) );
-       papd_exit( 1 );
-    }
-
-    /*
-     * Load UAMS
-     */
-    auth_load(uampath, uamlist);
-
-    /*
-     * Begin accepting connections.
-     */
-    FD_ZERO( &fdset );
-    for (;;) {
-       for ( pr = printers; pr; pr = pr->p_next ) {
-           FD_SET( atp_fileno( pr->p_atp ), &fdset );
-       }
-       if (( c = select( FD_SETSIZE, &fdset, NULL, NULL, NULL )) < 0 ) {
-           if ( errno == EINTR ) {
-               continue;
-           }
-           LOG(log_error, logtype_papd, "select: %s", strerror(errno) );
-           papd_exit( 1 );
-       }
-
-       for ( pr = printers; pr; pr = pr->p_next ) {
-           if ( FD_ISSET( atp_fileno( pr->p_atp ), &fdset )) {
-               int             err = 0;
-
-               memset( &sat, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-               sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-               sat.sat_family = AF_APPLETALK;
-               sat.sat_addr.s_net = ATADDR_ANYNET;
-               sat.sat_addr.s_node = ATADDR_ANYNODE;
-               sat.sat_port = ATADDR_ANYPORT;
-               /* do an atp_rsel(), to prevent hangs */
-               if (( c = atp_rsel( pr->p_atp, &sat, ATP_TREQ )) != ATP_TREQ ) {
-                   continue;
-               }
-               atpb.atp_saddr = &sat;
-               atpb.atp_rreqdata = cbuf;
-               atpb.atp_rreqdlen = sizeof( cbuf );
-               if ( atp_rreq( pr->p_atp, &atpb ) < 0 ) {
-                   LOG(log_error, logtype_papd, "atp_rreq: %s", strerror(errno) );
-                   continue;
-               }
-
-               /* should check length of req buf */
-
-               switch( cbuf[ 1 ] ) {
-               case PAP_OPEN :
-                   connid = (unsigned char)cbuf[ 0 ];
-                   sock = (unsigned char)cbuf[ 4 ];
-                   quantum = (unsigned char)cbuf[ 5 ];
-                   rbuf[ 0 ] = cbuf[ 0 ];
-                   rbuf[ 1 ] = PAP_OPENREPLY;
-                   rbuf[ 2 ] = rbuf[ 3 ] = 0;
-
-                   if (( pr->p_flags & P_SPOOLED ) && rprintcap( pr ) != 0 ) {
-                       LOG(log_error, logtype_papd, "printcap problem: %s",
-                               pr->p_printer );
-                       rbuf[ 2 ] = rbuf[ 3 ] = 0xff;
-                       err = 1;
-                   }
-
-#ifdef HAVE_CUPS
-                  /*
-                   * If cups is not accepting jobs, we return
-                   * 0xffff to indicate we're busy
-                   */
-#ifdef DEBUG
-                    LOG(log_debug9, logtype_papd, "CUPS: PAP_OPEN");
-#endif
-                   if ( (pr->p_flags & P_SPOOLED) && (cups_get_printer_status ( pr ) == 0)) {
-                        LOG(log_error, logtype_papd, "CUPS_PAP_OPEN: %s is not accepting jobs",
-                                pr->p_printer );
-                        rbuf[ 2 ] = rbuf[ 3 ] = 0xff;
-                        err = 1;
-                    }
-#endif /* HAVE_CUPS */
-
-                   /*
-                    * If this fails, we've run out of sockets. Rather than
-                    * just die(), let's try to continue. Maybe some sockets
-                    * will close, and we can continue;
-                    */
-                   if (( atp = atp_open( ATADDR_ANYPORT, 
-                                         &pr->p_addr)) == NULL ) {
-                       LOG(log_error, logtype_papd, "atp_open: %s", strerror(errno) );
-                       rbuf[ 2 ] = rbuf[ 3 ] = 0xff;  /* printer busy */
-                       rbuf[ 4 ] = 0; /* FIXME is it right? */
-                       err = 1;
-                   }
-                   else {
-                      rbuf[ 4 ] = atp_sockaddr( atp )->sat_port;
-                    }
-                   rbuf[ 5 ] = oquantum;
-                   rbuf[ 6 ] = rbuf[ 7 ] = 0;
-
-                   iov.iov_base = rbuf;
-                   iov.iov_len = 8 + getstatus( pr, &rbuf[ 8 ] );
-                   atpb.atp_sresiov = &iov;
-                   atpb.atp_sresiovcnt = 1;
-                   /*
-                    * This may error out if we lose a route, so we won't die().
-                    */
-                   if ( atp_sresp( pr->p_atp, &atpb ) < 0 ) {
-                       LOG(log_error, logtype_papd, "atp_sresp: %s", strerror(errno) );
-                       err = 1;
-                   }
-
-                   if ( err ) {
-                       if (atp) {
-                          atp_close(atp);
-                        }
-                       continue;
-                   }
-
-                   switch ( c = fork()) {
-                   case -1 :
-                       LOG(log_error, logtype_papd, "fork: %s", strerror(errno) );
-                        atp_close(atp);
-                       continue;
-
-                   case 0 : /* child */
-                       printer = pr;
-
-                       #ifndef HAVE_CUPS
-                       if (( printer->p_flags & P_SPOOLED ) &&
-                               chdir( printer->p_spool ) < 0 ) {
-                           LOG(log_error, logtype_papd, "chdir %s: %s", printer->p_spool, strerror(errno) );
-                           exit( 1 );
-                       }
-                       #else
-                       if (( printer->p_flags & P_SPOOLED ) &&
-                               chdir( SPOOLDIR ) < 0 ) {
-                           LOG(log_error, logtype_papd, "chdir %s: %s", SPOOLDIR, strerror(errno) );
-                           exit( 1 );
-                       }
-
-                       #endif
-
-                       sv.sa_handler = SIG_DFL;
-                       sigemptyset( &sv.sa_mask );
-                       sv.sa_flags = SA_RESTART;
-                       if ( sigaction( SIGTERM, &sv, NULL ) < 0 ) {
-                           LOG(log_error, logtype_papd, "sigaction: %s", strerror(errno) );
-                           exit( 1 );
-                       }
-                       
-                       if ( sigaction( SIGCHLD, &sv, NULL ) < 0 ) {
-                           LOG(log_error, logtype_papd, "sigaction: %s", strerror(errno) );
-                           exit( 1 );
-                        }
-
-                       for ( pr = printers; pr; pr = pr->p_next ) {
-                           atp_close( pr->p_atp );
-                       }
-                       sat.sat_port = sock;
-                       if ( session( atp, &sat ) < 0 ) {
-                           LOG(log_error, logtype_papd, "bad session" );
-                           exit( 1 );
-                       }
-                       exit( 0 );
-                       break;
-
-                   default : /* parent */
-                       LOG(log_info, logtype_papd, "child %d for \"%s\" from %u.%u",
-                               c, pr->p_name, ntohs( sat.sat_addr.s_net ),
-                               sat.sat_addr.s_node);
-                       atp_close( atp );
-                   }
-                   break;
-
-               case PAP_SENDSTATUS :
-                   rbuf[ 0 ] = 0;
-                   rbuf[ 1 ] = PAP_STATUS;
-                   rbuf[ 2 ] = rbuf[ 3 ] = 0;
-                   rbuf[ 4 ] = rbuf[ 5 ] = 0;
-                   rbuf[ 6 ] = rbuf[ 7 ] = 0;
-
-                   iov.iov_base = rbuf;
-                   iov.iov_len = 8 + getstatus( pr, &rbuf[ 8 ] );
-                   atpb.atp_sresiov = &iov;
-                   atpb.atp_sresiovcnt = 1;
-                   /*
-                    * This may error out if we lose a route, so we won't die().
-                    */
-                   if ( atp_sresp( pr->p_atp, &atpb ) < 0 ) {
-                       LOG(log_error, logtype_papd, "atp_sresp: %s", strerror(errno) );
-                   }
-                   break;
-
-               default :
-                   LOG(log_error, logtype_papd, "Bad request from %u.%u!",
-                           ntohs( sat.sat_addr.s_net ), sat.sat_addr.s_node );
-                   continue;
-                   break;
-               }
-
-#ifdef notdef
-               /*
-                * Sometimes the child process will send its first READ
-                * before the parent has sent the OPEN REPLY.  Moving this
-                * code into the OPEN/STATUS switch fixes this problem.
-                */
-               iov.iov_base = rbuf;
-               iov.iov_len = 8 + getstatus( pr, &rbuf[ 8 ] );
-               atpb.atp_sresiov = &iov;
-               atpb.atp_sresiovcnt = 1;
-               /*
-                * This may error out if we lose a route, so we won't die().
-                */
-               if ( atp_sresp( pr->p_atp, &atpb ) < 0 ) {
-                   LOG(log_error, logtype_papd, "atp_sresp: %s", strerror(errno) );
-               }
-#endif /* notdef */
-           }
-       }
-    }
-    return 0;
-}
-
-/*
- * We assume buf is big enough for 255 bytes of data and a length byte.
- */
-
-int getstatus(struct printer *pr, char *buf)
-{
-
-#ifdef HAVE_CUPS
-    if ( pr->p_flags & P_PIPED ) {
-       *buf = strlen( cannedstatus );
-       strncpy( &buf[ 1 ], cannedstatus, *buf );
-       return( *buf + 1 );
-    } else {
-       cups_get_printer_status( pr );
-       *buf = strlen ( pr->p_status );
-       strncpy ( &buf[1], pr->p_status, *buf);
-       return ( *buf + 1);
-    }
-#else
-
-    char               path[ MAXPATHLEN ];
-    int                        fd = -1, rc;
-
-    if ( pr->p_flags & P_SPOOLED && ( pr->p_spool != NULL )) {
-       strcpy( path, pr->p_spool );
-       strcat( path, "/status" );
-       fd = open( path, O_RDONLY);
-    }
-
-    if (( pr->p_flags & P_PIPED ) || ( fd < 0 )) {
-       *buf = strlen( cannedstatus );
-       strncpy( &buf[ 1 ], cannedstatus, *buf );
-       return( *buf + 1 );
-    } else {
-       if (( rc = read( fd, &buf[ 1 ], 255 )) < 0 ) {
-           rc = 0;
-       }
-       close( fd );
-       if ( rc && buf[ rc ] == '\n' ) {        /* remove trailing newline */
-           rc--;
-       }
-       *buf = rc;
-       return( rc + 1 );
-    }
-#endif /* HAVE_CUPS */
-}
-
-char   *pgetstr(char *id, char **area);
-char   *getpname(char **area, int bufsize);
-
-#define PF_CONFBUFFER  1024
-
-static void getprinters( char *cf)
-{
-    char               buf[ PF_CONFBUFFER ], area[ PF_CONFBUFFER ], *a, *p, *name, *type, *zone;
-    struct printer     *pr;
-    int                        c;
-
-    while (( c = getprent( cf, buf, PF_CONFBUFFER )) > 0 ) {
-       a = area;
-       /*
-        * Get the printer's nbp name.
-        */
-       if (( p = getpname( &a, PF_CONFBUFFER )) == NULL ) {
-           fprintf( stderr, "No printer name\n" );
-           exit( 1 );
-       }
-
-       if (( pr = (struct printer *)malloc( sizeof( struct printer )))
-               == NULL ) {
-           perror( "malloc" );
-           exit( 1 );
-       }
-       memset( pr, 0, sizeof( struct printer ));
-
-       name = defprinter.p_name;
-       type = defprinter.p_type;
-       zone = defprinter.p_zone;
-       if ( nbp_name( p, &name, &type, &zone )) {
-           fprintf( stderr, "Can't parse \"%s\"\n", name );
-           exit( 1 );
-       }
-       if ( name != defprinter.p_name ) {
-           if (( pr->p_name = (char *)malloc( strlen( name ) + 1 )) == NULL ) {
-               perror( "malloc" );
-               exit( 1 );
-           }
-           strcpy( pr->p_name, name );
-       } else {
-           pr->p_name = name;
-       }
-       if ( type != defprinter.p_type ) {
-           if (( pr->p_type = (char *)malloc( strlen( type ) + 1 )) == NULL ) {
-               perror( "malloc" );
-               exit( 1 );
-           }
-           strcpy( pr->p_type, type );
-       } else {
-           pr->p_type = type;
-       }
-       if ( zone != defprinter.p_zone ) {
-           if (( pr->p_zone = (char *)malloc( strlen( zone ) + 1 )) == NULL ) {
-               perror( "malloc" );
-               exit( 1 );
-           }
-           strcpy( pr->p_zone, zone );
-       } else {
-           pr->p_zone = zone;
-       }
-
-       if ( pnchktc( cf ) != 1 ) {
-           fprintf( stderr, "Bad papcap entry\n" );
-           exit( 1 );
-       }
-
-       /*
-        * Get PPD file.
-        */
-       if (( p = pgetstr( "pd", &a ) )) {
-           if (( pr->p_ppdfile = (char *)malloc( strlen( p ) + 1 )) == NULL ) {
-               perror( "malloc" );
-               exit( 1 );
-           }
-           strcpy( pr->p_ppdfile, p );
-       }
-
-       /*
-        * Get lpd printer name.
-        */
-       if (( p = pgetstr( "pr", &a )) == NULL ) {
-           pr->p_printer = defprinter.p_printer;
-           pr->p_flags = defprinter.p_flags;
-       } else {
-           if ( *p == '|' ) {
-               p++;
-               pr->p_flags = P_PIPED;
-           } else {
-               pr->p_flags = P_SPOOLED;
-           }
-           if (( pr->p_printer = (char *)malloc( strlen( p ) + 1 )) == NULL ) {
-               perror( "malloc" );
-               exit( 1 );
-           }
-           strcpy( pr->p_printer, p );
-       }
-
-       /*
-        * Do we want authenticated printing?
-        */
-       if ((p = pgetstr( "ca", &a )) != NULL ) {
-           if ((pr->p_authprintdir = (char *)malloc(strlen(p)+1)) == NULL) {
-               perror( "malloc" );
-               exit(1);
-           }
-           strcpy( pr->p_authprintdir, p );
-           pr->p_flags |= P_AUTH;
-           pr->p_flags |= P_AUTH_CAP;
-       } else { pr->p_authprintdir = NULL; }
-
-       if ( pgetflag( "sp" ) == 1 ) {
-           pr->p_flags |= P_AUTH;
-           pr->p_flags |= P_AUTH_PSSP;
-       }
-
-       if ((p = pgetstr("am", &a)) != NULL ) {
-               if ((uamlist = (char *)malloc(strlen(p)+1)) == NULL ) {
-                       perror("malloc");
-                       exit(1);
-               }
-               strcpy(uamlist, p);
-       }
-
-       if ( pr->p_flags & P_SPOOLED ) {
-           /*
-            * Get operator name.
-            */
-           if (( p = pgetstr( "op", &a )) == NULL ) {
-               pr->p_operator = defprinter.p_operator;
-           } else {
-               if (( pr->p_operator = (char *)malloc( strlen( p ) + 1 ))
-                       == NULL ) {
-                   perror( "malloc" );
-                   exit( 1 );
-               }
-               strcpy( pr->p_operator, p );
-           }
-       }
-
-       /* get printer's appletalk address. */
-       if (( p = pgetstr( "pa", &a )) == NULL ) 
-           memcpy(&pr->p_addr, &defprinter.p_addr, sizeof(pr->p_addr));
-       else 
-           atalk_aton(p, &pr->p_addr);
-
-#ifdef HAVE_CUPS
-       if ((p = pgetstr("co", &a)) != NULL ) {
-            pr->p_cupsoptions = strdup(p);
-            LOG (log_error, logtype_papd, "enabling cups-options for %s: %s", pr->p_name, pr->p_cupsoptions);
-       }
-#endif
-
-       /* convert line endings for setup sections.
-           real ugly work around for foomatic deficiencies,
-          need to get rid of this */
-       if ( pgetflag("fo") == 1 ) {
-            pr->p_flags |= P_FOOMATIC_HACK;
-            LOG (log_error, logtype_papd, "enabling foomatic hack for %s", pr->p_name);
-       }
-
-       if (strncasecmp (pr->p_name, "cupsautoadd", 11) == 0)
-       {
-#ifdef HAVE_CUPS
-               pr = cups_autoadd_printers (pr, printers);
-               printers = pr;
-#else
-               LOG (log_error, logtype_papd, "cupsautoadd: Cups support not compiled in");
-#endif /* HAVE_CUPS */
-       }
-       else {
-#ifdef HAVE_CUPS
-               if ( cups_check_printer ( pr, printers, 1) == 0)
-               {
-                       pr->p_next = printers;
-                       printers = pr;
-               }
-#else
-               pr->p_next = printers;
-               printers = pr;
-#endif /* HAVE_CUPS */
-       }
-    }
-    if ( c == 0 ) {
-       endprent();
-    } else {                   /* No capability file, do default */
-       printers = &defprinter;
-    }
-}
-
-int rprintcap( struct printer *pr)
-{
-
-#ifdef HAVE_CUPS
-
-    char               *p;
-
-    if ( pr->p_flags & P_SPOOLED && !(pr->p_flags & P_CUPS_AUTOADDED) ) { /* Skip check if autoadded */
-       if ( cups_printername_ok ( pr->p_printer ) != 1) {
-           LOG(log_error, logtype_papd, "No such CUPS printer: '%s'", pr->p_printer );
-           return( -1 );
-       }
-    }
-
-    /*
-     * Check for ppd file, moved here because of cups_autoadd we cannot check at the usual location
-     */
-
-    if ( pr->p_ppdfile == NULL ) {
-       if ( (p = (char *) cups_get_printer_ppd ( pr->p_printer )) != NULL ) {
-           if (( pr->p_ppdfile = (char *)malloc( strlen( p ) + 1 )) == NULL ) {
-               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-               exit( 1 );
-           }
-           strcpy( pr->p_ppdfile, p );
-           pr->p_flags |= P_CUPS_PPD;
-           LOG(log_info, logtype_papd, "PPD File for %s set to %s", pr->p_printer, pr->p_ppdfile );
-       }
-    }
-
-
-#else
-
-    char               buf[ 1024 ], area[ 1024 ], *a, *p;
-    int                        c;
-
-    /*
-     * Spool directory from printcap file.
-     */
-    if ( pr->p_flags & P_SPOOLED ) {
-       if ( pgetent( printcap, buf, pr->p_printer ) != 1 ) {
-           LOG(log_error, logtype_papd, "No such printer: %s", pr->p_printer );
-           return( -1 );
-       }
-
-       /*
-        * Spool directory.
-        */
-       if ( pr->p_spool != NULL && pr->p_spool != defprinter.p_spool ) {
-           free( pr->p_spool );
-       }
-       a = area;
-       if (( p = pgetstr( "sd", &a )) == NULL ) {
-           pr->p_spool = defprinter.p_spool;
-       } else {
-           if (( pr->p_spool = (char *)malloc( strlen( p ) + 1 )) == NULL ) {
-               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-               exit( 1 );
-           }
-           strcpy( pr->p_spool, p );
-       }
-
-       /*
-        * Is accounting on?
-        */
-       a = area;
-       if ( pgetstr( "af", &a ) == NULL ) {
-           pr->p_flags &= ~P_ACCOUNT;
-       } else {
-           pr->p_flags |= P_ACCOUNT;
-#ifdef ABS_PRINT
-           if ( pr->p_role != NULL && pr->p_role != defprinter.p_role ) {
-               free( pr->p_role );
-           }
-           a = area;
-           if (( p = pgetstr( "ro", &a )) == NULL ) {
-               pr->p_role = defprinter.p_role;
-           } else {
-               if (( pr->p_role =
-                       (char *)malloc( strlen( p ) + 1 )) == NULL ) {
-                   LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-                   exit( 1 );
-               }
-               strcpy( pr->p_role, p );
-           }
-
-           if (( c = pgetnum( "si" )) < 0 ) {
-               pr->p_srvid = defprinter.p_srvid;
-           } else {
-               pr->p_srvid = c;
-           }
-#endif /* ABS_PRINT */
-       }
-
-
-       /*
-        * Cost of printer.
-        */
-       if ( pr->p_pagecost_msg != NULL &&
-               pr->p_pagecost_msg != defprinter.p_pagecost_msg ) {
-           free( pr->p_pagecost_msg );
-       }
-       a = area;
-       if (( p = pgetstr( "pc", &a )) != NULL ) {
-           if (( pr->p_pagecost_msg =
-                   (char *)malloc( strlen( p ) + 1 )) == NULL ) {
-               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-               exit( 1 );
-           }
-           strcpy( pr->p_pagecost_msg, p );
-           pr->p_pagecost = 0;
-       } else if ( pr->p_flags & P_ACCOUNT ) {
-           if (( c = pgetnum( "pc" )) < 0 ) {
-               pr->p_pagecost = defprinter.p_pagecost;
-           } else {
-               pr->p_pagecost = c;
-           }
-           pr->p_pagecost_msg = NULL;
-       }
-
-       /*
-        * Get lpd lock file.
-        */
-       if ( pr->p_lock != NULL && pr->p_lock != defprinter.p_lock ) {
-           free( pr->p_lock );
-       }
-       a = area;
-       if (( p = pgetstr( "lo", &a )) == NULL ) {
-           pr->p_lock = defprinter.p_lock;
-       } else {
-           if (( pr->p_lock = (char *)malloc( strlen( p ) + 1 )) == NULL ) {
-               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-               exit( 1 );
-           }
-           strcpy( pr->p_lock, p );
-       }
-
-#ifdef KRB
-       /*
-        * Must Kerberos authenticate?
-        */
-       if ( pgetflag( "ka" ) == 1 ) {
-           pr->p_flags |= P_KRB;
-       } else {
-           pr->p_flags &= ~P_KRB;
-       }
-#endif /* KRB */
-
-       endprent();
-    }
-#endif /* HAVE_CUPS */
-
-    return( 0 );
-}
diff --git a/etc/papd/ppd.c b/etc/papd/ppd.c
deleted file mode 100644 (file)
index f164692..0000000
+++ /dev/null
@@ -1,302 +0,0 @@
-/*
- * $Id: ppd.c,v 1.17 2009-10-14 02:24:05 didg Exp $
- *
- * Copyright (c) 1995 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <atalk/logger.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/time.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-
-#include "printer.h"
-#include "ppd.h"
-
-struct ppd_font                *ppd_fonts = NULL;
-
-struct ppd_feature     ppd_features[] = {
-    { "*LanguageLevel",        NULL },
-    { "*PSVersion",    NULL },
-#ifdef HAVE_CUPS
-    { "*FreeVM",       "33554432" },
-#else
-    { "*FreeVM",       NULL },
-#endif
-    { "*Product",      NULL },
-    { "*PCFileName",   NULL },
-    { "*ModelName",    NULL },
-    { "*NickName",     NULL },
-    { "*ColorDevice",  NULL },
-    { "*FaxSupport",   NULL },
-    { "*TTRasterizer", NULL },
-    { NULL, NULL },
-};
-
-struct ppdent {
-    char       *pe_main;
-    char       *pe_option;
-    char       *pe_translation;
-    char       *pe_value;
-};
-
-#ifndef SHOWPPD
-static int ppd_inited;
-
-static void ppd_init(void)
-{
-    if (ppd_inited)
-        return;
-
-    ppd_inited++;
-
-    if (printer->p_ppdfile)
-        read_ppd( printer->p_ppdfile, 0 );
-}
-#endif /* SHOWPPD */
-
-
-/* quick and ugly hack to be able to read
-   ppd files with Mac line ending */
-static char* my_fgets(char *buf, size_t bufsize, FILE *stream)
-{
-    int p;           /* uninitialized, OK 310105 */
-    size_t count = 0;
-    while (count < (bufsize - 1) && EOF != (p=fgetc(stream))) {
-        buf[count] = p;
-        count++;
-        if ( p == '\r' || p == '\n')
-           break;
-    }
-
-    if (p == EOF && count == 0)
-        return NULL;
-
-    /* translate line endings */
-    if ( buf[count - 1] == '\r')
-        buf[count - 1] = '\n';
-
-    buf[count] = 0;
-    return buf;
-}
-
-static struct ppdent *getppdent( FILE *stream)
-{
-    static char                        buf[ 1024 ];
-    static struct ppdent       ppdent;
-    char                       *p, *q;
-
-    ppdent.pe_main = ppdent.pe_option = ppdent.pe_translation =
-           ppdent.pe_value = NULL;
-
-    while (( p = my_fgets( buf, sizeof( buf ), stream )) != NULL ) {
-       if ( *p != '*' ) {      /* main key word */
-           continue;
-       }
-       if ( p[ strlen( p ) - 1 ] != '\n') {
-           LOG(log_error, logtype_papd, "getppdent: line too long" );
-           continue;
-       }
-
-       q = p;
-       while ( (*p != ' ') && (*p != '\t') && (*p != ':') && (*p != '\n') ) {
-           p++;
-       }
-       if ( (*( q + 1 ) == '%') || (*( q + 1 ) == '?') ) {     /* comments & queries */
-           continue;
-       }
-       ppdent.pe_main = q;
-       if ( *p == '\n' ) {
-           *p = '\0';
-           ppdent.pe_option = ppdent.pe_translation = ppdent.pe_value = NULL;
-           return( &ppdent );
-       }
-
-       if ( *p != ':' ) {      /* option key word */
-           *p++ = '\0';
-
-           while ( (*p == ' ') || (*p == '\t') ) {
-               p++;
-           }
-
-           q = p;
-           while ( (*p != ':') && (*p != '/') && (*p != '\n') ) {
-               p++;
-           }
-
-           if ( *p == '\n' ) {
-               continue;
-           }
-
-           ppdent.pe_option = q;
-           if ( *p == '/' ) {  /* translation string */
-               *p++ = '\0';
-               q = p;
-               while ( *p != ':' && *p != '\n' ) {
-                   p++;
-               }
-               if ( *p != ':' ) {
-                   continue;
-               }
-
-               ppdent.pe_translation = q;
-           } else {
-               ppdent.pe_translation = NULL;
-           }
-       }
-       *p++ = '\0';
-
-       while ( (*p == ' ') || (*p == '\t') ) {
-           p++;
-       }
-
-       /* value */
-       q = p;
-       while ( *p != '\n' ) {
-           p++;
-       }
-       *p = '\0';
-       ppdent.pe_value = q;
-
-       return( &ppdent );
-    }
-
-    return( NULL );
-}
-
-int read_ppd(char *file, int fcnt)
-{
-    FILE               *ppdfile;
-    struct ppdent      *pe;
-    struct ppd_feature *pfe;
-    struct ppd_font    *pfo;
-
-    if ( fcnt > 20 ) {
-       LOG(log_error, logtype_papd, "read_ppd: %s: Too many files!", file );
-       return( -1 );
-    }
-
-    if (( ppdfile = fopen( file, "r" )) == NULL ) {
-       LOG(log_error, logtype_papd, "read_ppd %s: %s", file, strerror(errno) );
-       return( -1 );
-    }
-
-    while (( pe = getppdent( ppdfile )) != NULL ) {
-       /* *Include files */
-       if ( strcmp( pe->pe_main, "*Include" ) == 0 ) {
-           read_ppd( pe->pe_value, fcnt + 1 );
-           continue;
-       }
-
-       /* *Font */
-       if ( strcmp( pe->pe_main, "*Font" ) == 0 && pe->pe_option ) {
-           for ( pfo = ppd_fonts; pfo; pfo = pfo->pd_next ) {
-               if ( strcmp( pfo->pd_font, pe->pe_option ) == 0 ) {
-                   break;
-               }
-           }
-           if ( pfo ) {
-               continue;
-           }
-
-           if (( pfo = (struct ppd_font *)malloc( sizeof( struct ppd_font )))
-                   == NULL ) {
-               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-               exit( 1 );
-           }
-           if (( pfo->pd_font =
-                   (char *)malloc( strlen( pe->pe_option ) + 1 )) == NULL ) {
-               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-               exit( 1 );
-           }
-           strcpy( pfo->pd_font, pe->pe_option );
-           pfo->pd_next = ppd_fonts;
-           ppd_fonts = pfo;
-           continue;
-       }
-
-
-       /* Features */
-       for ( pfe = ppd_features; pfe->pd_name; pfe++ ) {
-           if ( strcmp( pe->pe_main, pfe->pd_name ) == 0 ) {
-               break;
-           }
-       }
-       if ( pfe->pd_name && pe->pe_value ) { 
-           if (( pfe->pd_value =
-                   (char *)malloc( strlen( pe->pe_value ) + 1 )) == NULL ) {
-               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-               exit( 1 );
-           }
-
-           strcpy( pfe->pd_value, pe->pe_value );
-           continue;
-       }
-    }
-
-    fclose( ppdfile );
-    return( 0 );
-}
-
-struct ppd_font *ppd_font( char *font)
-{
-    struct ppd_font    *pfo;
-
-#ifndef SHOWPPD
-    if ( ! ppd_inited ) {
-       ppd_init();
-    }
-#endif /* SHOWPPD */
-
-    for ( pfo = ppd_fonts; pfo; pfo = pfo->pd_next ) {
-       if ( strcmp( pfo->pd_font, font ) == 0 ) {
-           return( pfo );
-       }
-    }
-    return( NULL );
-}
-
-struct ppd_feature *ppd_feature( const char *feature, int len)
-{
-    struct ppd_feature *pfe;
-    char               ppd_feature_main[ 256 ];
-    const char         *end, *p;
-    char               *q;
-
-#ifndef SHOWPPD
-    if ( ! ppd_inited ) {
-       ppd_init();
-    }
-#endif /* SHOWPPD */
-
-    if (len > sizeof(ppd_feature_main) -1)
-        return( NULL );
-        
-    for ( end = feature + len, p = feature, q = ppd_feature_main;
-           (p <= end) && (*p != '\n') && (*p != '\r'); p++, q++ ) {
-       *q = *p;
-    }
-    if ( p > end ) {
-       return( NULL );
-    }
-    *q = '\0';
-
-    for ( pfe = ppd_features; pfe->pd_name; pfe++ ) {
-       if ( (strcmp( pfe->pd_name, ppd_feature_main ) == 0) && pfe->pd_value ) {
-           return( pfe );
-       }
-    }
-
-    return( NULL );
-}
diff --git a/etc/papd/ppd.h b/etc/papd/ppd.h
deleted file mode 100644 (file)
index ad989dd..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * $Id: ppd.h,v 1.6 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1995 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifndef PAPD_PPD_H
-#define PAPD_PPD_H 1
-
-#include <sys/cdefs.h>
-
-struct ppd_font {
-    char               *pd_font;
-    struct ppd_font    *pd_next;
-};
-
-struct ppd_feature {
-    char       *pd_name;
-    char       *pd_value;
-};
-
-struct ppd_feature     *ppd_feature (const char *, int);
-struct ppd_font                *ppd_font (char *);
-int read_ppd (char *, int);
-
-#endif /* PAPD_PPD_H */
diff --git a/etc/papd/print_cups.c b/etc/papd/print_cups.c
deleted file mode 100644 (file)
index ca8644c..0000000
+++ /dev/null
@@ -1,646 +0,0 @@
-/*
- * $Id: print_cups.c,v 1.6 2010-01-26 20:43:11 didg Exp $
- *
- * Copyright 2004 Bjoern Fernhomberg.
- *
- * Some code copied or adapted from print_cups.c for samba
- * Copyright 1999-2003 by Michael R Sweet.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <sys/types.h>
-#include <sys/param.h>
-#include <errno.h>
-
-
-#ifdef HAVE_CUPS
-
-#include <cups/cups.h>
-#include <cups/language.h>
-#include <atalk/unicode.h>
-#include <atalk/logger.h>
-#include <atalk/atp.h>
-#include <atalk/pap.h>
-#include <atalk/util.h>
-
-#include "printer.h"
-#include "print_cups.h"
-
-#define MAXCHOOSERLEN 31
-#define HTTP_MAX_URI 1024
-
-static const char* cups_status_msg[] = {
-        "status: busy; info: \"%s\" is rejecting jobs; ",
-        "status: idle; info: \"%s\" is stopped, accepting jobs ;",
-        "status: idle; info: \"%s\" is ready ; ",
-};
-
-/* Local functions */
-static int     convert_to_mac_name ( const char *encoding, char * inptr, char * outptr, size_t outlen);
-static size_t  to_ascii ( char *inbuf, char **outbuf);
-static int     cups_mangle_printer_name ( struct printer *pr, struct printer *printers);
-static void     cups_free_printer ( struct printer *pr);
-
-
-const char * cups_get_language (void)
-{
-        cups_lang_t *language;
-
-        language = cupsLangDefault();           /* needed for conversion */
-        return cupsLangEncoding(language);
-}
-
-/*
- * 'cups_passwd_cb()' - The CUPS password callback...
- */
-
-static const char *                            /* O - Password or NULL */
-cups_passwd_cb(const char *prompt _U_)      /* I - Prompt */
-{
- /*
-  * Always return NULL to indicate that no password is available...
-  */
-  return (NULL);
-}
-
-
-/*
- * 'cups_printername_ok()' - Verify supplied printer name is a valid cups printer
- */
-
-int                                     /* O - 1 if printer name OK */
-cups_printername_ok(char *name)         /* I - Name of printer */
-{
-        http_t          *http;          /* HTTP connection to server */
-        ipp_t           *request,       /* IPP Request */
-                        *response;      /* IPP Response */
-        cups_lang_t     *language;      /* Default language */
-        char            uri[HTTP_MAX_URI]; /* printer-uri attribute */
-
-       /*
-        * Make sure we don't ask for passwords...
-        */
-
-        cupsSetPasswordCB(cups_passwd_cb);
-
-       /*
-        * Try to connect to the server...
-        */
-
-        if ((http = httpConnect(cupsServer(), ippPort())) == NULL)
-        {
-               LOG(log_error, logtype_papd, "Unable to connect to CUPS server %s - %s",
-                         cupsServer(), strerror(errno));
-                return (0);
-        }
-
-
-       /*
-        * Build an IPP_GET_PRINTER_ATTRS request, which requires the following
-        * attributes:
-        *
-        *    attributes-charset
-        *    attributes-natural-language
-        *    requested-attributes
-        *    printer-uri
-        */
-
-        request = ippNew();
-
-        request->request.op.operation_id = IPP_GET_PRINTER_ATTRIBUTES;
-        request->request.op.request_id   = 1;
-
-        language = cupsLangDefault();
-
-        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                     "attributes-charset", NULL, cupsLangEncoding(language));
-
-        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
-                     "attributes-natural-language", NULL, language->language);
-
-        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
-                     "requested-attributes", NULL, "printer-uri");
-
-        sprintf(uri, "ipp://localhost/printers/%s", name);
-
-        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
-                     "printer-uri", NULL, uri);
-
-       /*
-        * Do the request and get back a response...
-        */
-
-        if ((response = cupsDoRequest(http, request, "/")) == NULL)
-        {
-               LOG(log_error, logtype_papd, "Unable to get printer status for %s - %s", name,
-                         ippErrorString(cupsLastError()));
-                httpClose(http);
-                return (0);
-        }
-
-        httpClose(http);
-
-        if (response->request.status.status_code >= IPP_OK_CONFLICT)
-        {
-               LOG(log_error, logtype_papd, "Unable to get printer status for %s - %s", name,
-                         ippErrorString(response->request.status.status_code));
-                ippDelete(response);
-                return (0);
-        }
-        else
-        {
-                ippDelete(response);
-                return (1);
-        }
-
-       return (0);
-}
-
-const char * 
-cups_get_printer_ppd ( char * name)
-{
-       cupsSetPasswordCB(cups_passwd_cb);
-       return cupsGetPPD( name );
-}
-
-int
-cups_get_printer_status (struct printer *pr)
-{
-
-        http_t          *http;          /* HTTP connection to server */
-        ipp_t           *request,       /* IPP Request */
-                        *response;      /* IPP Response */
-        ipp_attribute_t *attr;          /* Current attribute */
-        cups_lang_t     *language;      /* Default language */
-        char            uri[HTTP_MAX_URI]; /* printer-uri attribute */
-       int             status = -1;
-
-        static const char *pattrs[] =   /* Requested printer attributes */
-                        {
-                          "printer-state",
-                          "printer-state-message",
-                         "printer-is-accepting-jobs"
-                        };
-
-       /*
-        * Make sure we don't ask for passwords...
-        */
-
-        cupsSetPasswordCB(cups_passwd_cb);
-
-       /*
-        * Try to connect to the server...
-        */
-
-        if ((http = httpConnect(cupsServer(), ippPort())) == NULL)
-        {
-               LOG(log_error, logtype_papd, "Unable to connect to CUPS server %s - %s",
-                         cupsServer(), strerror(errno));
-                return (0);
-        }
-
-       /*
-        * Generate the printer URI...
-        */
-
-        sprintf(uri, "ipp://localhost/printers/%s", pr->p_printer);
-
-
-
-       /*
-        * Build an IPP_GET_PRINTER_ATTRIBUTES request, which requires the
-        * following attributes:
-        *
-        *    attributes-charset
-        *    attributes-natural-language
-        *    requested-attributes
-        *    printer-uri
-        */
-
-        request = ippNew();
-
-        request->request.op.operation_id = IPP_GET_PRINTER_ATTRIBUTES;
-        request->request.op.request_id   = 1;
-
-        language = cupsLangDefault();
-
-        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                     "attributes-charset", NULL, cupsLangEncoding(language));
-
-        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
-                     "attributes-natural-language", NULL, language->language);
-
-        ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
-                      "requested-attributes",
-                      (sizeof(pattrs) / sizeof(pattrs[0])),
-                      NULL, pattrs);
-
-        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
-                     "printer-uri", NULL, uri);
-
-       /*
-        * Do the request and get back a response...
-        */
-
-        if ((response = cupsDoRequest(http, request, "/")) == NULL)
-        {
-               LOG(log_error, logtype_papd, "Unable to get printer status for %s - %s", pr->p_printer,
-                         ippErrorString(cupsLastError()));
-                httpClose(http);
-                return (0);
-        }
-
-        if (response->request.status.status_code >= IPP_OK_CONFLICT)
-        {
-               LOG(log_error, logtype_papd, "Unable to get printer status for %s - %s", pr->p_printer,
-                         ippErrorString(response->request.status.status_code));
-                ippDelete(response);
-                httpClose(http);
-                return (0);
-        }
-
-       /*
-        * Get the current printer status and convert it to the status values.
-        */
-
-       memset ( pr->p_status, 0 ,sizeof(pr->p_status));
-
-        if ((attr = ippFindAttribute(response, "printer-state", IPP_TAG_ENUM)) != NULL)
-        {
-                if (attr->values[0].integer == IPP_PRINTER_STOPPED)
-                       status = 1;
-                else if (attr->values[0].integer == IPP_NOT_ACCEPTING)
-                       status = 0;
-               else
-                       status = 2;
-        }
-
-       if ((attr = ippFindAttribute(response, "printer-is-accepting-jobs", IPP_TAG_BOOLEAN)) != NULL)
-       {
-               if ( attr->values[0].integer == 0 ) 
-                       status = 0;
-       }
-               
-       snprintf ( pr->p_status, 255, cups_status_msg[status], pr->p_printer );
-
-        if ((attr = ippFindAttribute(response, "printer-state-message", IPP_TAG_TEXT)) != NULL)
-               strncat ( pr->p_status, attr->values[0].string.text, 255-strlen(pr->p_status));
-
-        ippDelete(response);
-
-       /*
-        * Return the print status ...
-        */
-
-        httpClose(http);
-
-       return (status);
-}
-
-
-/*------------------------------------------------------------------------*/
-
-/* pass the job to cups */
-
-int cups_print_job ( char * name, char *filename, char *job, char *username, char * cupsoptions )
-{
-       int             jobid;
-       char            filepath[MAXPATHLEN];
-       int             num_options;
-       cups_option_t   *options;
-
-       /* Initialize the options array */
-       num_options = 0;
-       options     = (cups_option_t *)0;
-
-        cupsSetPasswordCB(cups_passwd_cb);
-
-       if ( username != NULL )
-       {
-               /* Add options using cupsAddOption() */
-               num_options = cupsAddOption("job-originating-user-name", username, num_options, &options);
-               num_options = cupsAddOption("originating-user-name", username, num_options, &options);
-               cupsSetUser ( username );
-       }
-
-       if (cupsoptions != NULL)
-       {
-              num_options = cupsParseOptions(cupsoptions, num_options, &options);
-       }
-       
-       strlcpy ( filepath, SPOOLDIR, sizeof(filepath));
-       strlcat ( filepath , "/", sizeof(filepath));
-       strlcat ( filepath , filename, sizeof(filepath));
-       
-       if ((jobid = cupsPrintFile( name, filepath, job, 0, options)) == 0)
-               LOG(log_error, logtype_papd, "Unable to print job '%s' (%s) to printer '%s' for user '%s' - CUPS error : '%s'", job, filepath, name, username, ippErrorString(cupsLastError()));
-       else 
-               LOG(log_info, logtype_papd, "Job '%s' queued to printer '%s' with id '%d'", job, name, jobid);
-
-       cupsFreeOptions(num_options, options);
-       return (jobid);
-}
-
-
-/*------------------------------------------------------------------------*/
-
-struct printer *
-cups_autoadd_printers ( struct printer *defprinter, struct printer *printers)
-{
-       struct printer  *pr;
-        int            num_dests,i;
-       int             ret;
-        cups_dest_t    *dests;
-        cups_lang_t    *language;
-       char            name[MAXCHOOSERLEN+1], *p;
-
-        language  = cupsLangDefault();         /* needed for conversion */
-        num_dests = cupsGetDests(&dests);      /* get the available destination from CUPS */
-
-        for  (i=0; i< num_dests; i++)
-        {
-               if (( pr = (struct printer *)malloc( sizeof( struct printer ))) == NULL ) {
-                       LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-                       exit( 1 );
-               }
-       
-               memcpy( pr, defprinter, sizeof( struct printer ) );
-
-               /* convert from CUPS to local encoding */
-                convert_string_allocate( add_charset(cupsLangEncoding(language)), CH_UNIX, 
-                                         dests[i].name, -1, &pr->p_u_name);
-
-               /* convert CUPS name to Mac charset */
-               if ( convert_to_mac_name ( cupsLangEncoding(language), dests[i].name, name, sizeof(name)) <= 0)
-               {
-                       LOG (log_error, logtype_papd, "Conversion from CUPS to MAC name failed for %s", dests[i].name);
-                       free (pr);
-                       continue;
-               }
-
-               if (( pr->p_name = (char *)malloc( strlen( name ) + 1 )) == NULL ) {
-                       LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-                       exit( 1 );
-               }
-               strcpy( pr->p_name, name );
-
-               /* set printer flags */
-               pr->p_flags &= ~P_PIPED;
-               pr->p_flags |= P_SPOOLED;
-               pr->p_flags |= P_CUPS;
-               pr->p_flags |= P_CUPS_AUTOADDED;
-                       
-               if (( pr->p_printer = (char *)malloc( strlen( dests[i].name ) + 1 )) == NULL ) {
-                       LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-                               exit( 1 );
-               }
-               strcpy( pr->p_printer, dests[i].name );                 
-
-               if ( (p = (char *) cups_get_printer_ppd ( pr->p_printer )) != NULL ) {
-                       if (( pr->p_ppdfile = (char *)malloc( strlen( p ) + 1 )) == NULL ) {
-                               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-                                       exit( 1 );
-                       }
-                       strcpy( pr->p_ppdfile, p );
-                       pr->p_flags |= P_CUPS_PPD;
-               }
-
-               if ( (ret = cups_check_printer ( pr, printers, 0)) == -1) 
-                       ret = cups_mangle_printer_name ( pr, printers );
-
-               if (ret) {
-                       cups_free_printer (pr);
-                       LOG(log_info, logtype_papd, "Printer %s not added: reason %d", name, ret);
-               }
-               else {
-                       pr->p_next = printers;
-                       printers = pr;
-               }
-       }
-        cupsFreeDests(num_dests, dests);
-        cupsLangFree(language);
-
-       return printers;
-}
-
-
-/*------------------------------------------------------------------------*/
-
-/* cups_mangle_printer_name
- *    Mangles the printer name if two CUPS printer provide the same Chooser Name
- *    Append '#nn' to the chooser name, if it is longer than 28 char we overwrite the last three chars
- * Returns: 0 on Success, 2 on Error
- */
-
-static int cups_mangle_printer_name ( struct printer *pr, struct printer *printers)
-{
-       size_t  count, name_len;
-       char    name[MAXCHOOSERLEN];
-
-       count = 1;
-       name_len = strlen (pr->p_name);
-       strncpy ( name, pr->p_name, MAXCHOOSERLEN-3);
-       
-       /* Reallocate necessary space */
-       (name_len >= MAXCHOOSERLEN-3) ? (name_len = MAXCHOOSERLEN+1) : (name_len = name_len + 4);
-       pr->p_name = (char *) realloc (pr->p_name, name_len );
-               
-       while ( ( cups_check_printer ( pr, printers, 0 )) && count < 100)
-       {
-               memset ( pr->p_name, 0, name_len);
-               strncpy ( pr->p_name, name, MAXCHOOSERLEN-3);
-               sprintf ( pr->p_name, "%s#%2.2u", pr->p_name, count++);
-       }
-
-       if ( count > 99) 
-               return (2);
-       
-       return (0);
-}      
-
-/*------------------------------------------------------------------------*/
-
-/* fallback ASCII conversion */
-
-static size_t
-to_ascii ( char  *inptr, char **outptr)
-{
-       char *out, *osav;
-
-       if ( NULL == (out = (char*) malloc ( strlen ( inptr) + 1 )) ) {
-               LOG(log_error, logtype_papd, "malloc: %s", strerror(errno) );
-               exit (1);
-       }
-
-       osav = out;
-
-       while ( *inptr != '\0' ) {
-               if ( *inptr & 0x80 ) {
-                       *out = '_';
-                       out++;
-                       inptr++;
-               }
-               else
-                       *out++ = *inptr++;
-       }
-       *out = '\0';
-       *outptr = osav;
-       return ( strlen (osav) );
-}
-
-
-/*------------------------------------------------------------------------*/
-
-/* convert_to_mac_name
- *     1) Convert from encoding to MacRoman
- *     2) Shorten to MAXCHOOSERLEN (31)
- *      3) Replace @ and _ as they are illegal
- * Returns: -1 on failure, length of name on success; outpr contains name in MacRoman
- */
-
-static int convert_to_mac_name ( const char * encoding, char * inptr, char * outptr, size_t outlen)
-{
-       char    *outbuf;
-       char    *soptr;
-       size_t  name_len = 0;
-       size_t  i;
-       charset_t chCups;
-
-       /* Change the encoding */
-       if ((charset_t)-1 != (chCups = add_charset(encoding))) {
-               name_len = convert_string_allocate( chCups, CH_MAC, inptr, -1, &outbuf);
-       }
-
-       if (name_len == 0 || name_len == (size_t)-1) {
-               /* charset conversion failed, use ascii fallback */
-               name_len = to_ascii ( inptr, &outbuf );
-       }
-       
-       soptr = outptr;
-
-       for ( i=0; i< name_len && i < outlen-1 ; i++)
-       {
-               if ( outbuf[i] == '_' ) 
-                       *soptr = ' '; /* Replace '_' with a space (just for the looks) */
-               else if ( outbuf[i] == '@' || outbuf[i] == ':' ) 
-                       *soptr = '_'; /* Replace @ and : with '_' as they are illegal chars */
-               else
-                       *soptr = outbuf[i];
-               soptr++;
-       }
-       *soptr = '\0';
-       free (outbuf);
-       return (i);
-}
-
-
-/*------------------------------------------------------------------------*/
-
-/*
- * cups_check_printer:
- * check if a printer with this name already exists.
- * if yes, and replace = 1 the existing printer is replaced with
- * the new one. This allows to overwrite printer settings
- * created by cupsautoadd. It also used by cups_mangle_printer.
- */
-
-int cups_check_printer ( struct printer *pr, struct printer *printers, int replace)
-{
-       struct printer *listptr, *listprev;
-
-       listptr = printers;
-       listprev = NULL;
-
-       while ( listptr != NULL) {
-               if ( strcasecmp (pr->p_name, listptr->p_name) == 0) {
-                       if ( pr->p_flags & P_CUPS_AUTOADDED ) {  /* Check if printer has been autoadded */
-                               if ( listptr->p_flags & P_CUPS_AUTOADDED )
-                                       return (-1);             /* Conflicting Cups Auto Printer (mangling issue?) */
-                               else
-                                       return (1);              /* Never replace a hand edited printer with auto one */
-                       }
-
-                       if ( replace ) {
-                               /* Replace printer */
-                               if ( listprev != NULL) {
-                                       pr->p_next = listptr->p_next;
-                                       listprev->p_next = pr;
-                                       cups_free_printer (listptr);
-                               }
-                               else {
-                                       printers = pr;
-                                       printers->p_next = listptr->p_next;
-                                       cups_free_printer (listptr);
-                               }
-                       }
-                       return (1);  /* Conflicting Printers */
-               }
-               listprev = listptr;
-               listptr = listptr->p_next;
-       }       
-       return (0);     /* No conflict */
-}
-
-
-/*------------------------------------------------------------------------*/
-
-
-void
-cups_free_printer ( struct printer *pr)
-{
-       if ( pr->p_name != NULL)
-               free (pr->p_name);
-       if ( pr->p_printer != NULL)
-               free (pr->p_printer);
-       if ( pr->p_ppdfile != NULL)
-               free (pr->p_ppdfile);
-       
-       /* CUPS autoadded printers share the other informations
-        * so if the printer is autoadded we won't free them.
-        * We might leak some bytes here though.
-        */
-       if ( pr->p_flags & P_CUPS_AUTOADDED ) {
-               free (pr);
-               return;
-       }
-
-       if ( pr->p_operator != NULL )
-               free (pr->p_operator);
-       if ( pr->p_zone != NULL )
-               free (pr->p_zone);
-       if ( pr->p_type != NULL )
-               free (pr->p_type);
-       if ( pr->p_authprintdir != NULL )
-               free (pr->p_authprintdir);
-       
-       free ( pr );
-       return;
-       
-}
-       
-#endif /* HAVE_CUPS*/
diff --git a/etc/papd/print_cups.h b/etc/papd/print_cups.h
deleted file mode 100644 (file)
index dd9e711..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-\r
-#ifndef PAPD_CUPS_H\r
-#define PAPD_CUPS_H 1\r
-\r
-#ifdef HAVE_CUPS\r
-#include <sys/cdefs.h>\r
-\r
-struct cups_status {\r
-       int     pr_status;\r
-       char *  status_message;\r
-};\r
-\r
-int            cups_printername_ok (char * );\r
-const char *   cups_get_printer_ppd ( char * );\r
-int            cups_get_printer_status (struct printer *pr);\r
-int            cups_print_job ( char *, char *, char *, char *, char *);\r
-struct printer * cups_autoadd_printers ( struct printer *, struct printer *);\r
-int            cups_check_printer ( struct printer *, struct printer *, int);\r
-const char     *cups_get_language ( void );\r
-#endif /* HAVE_CUPS */\r
-#endif /* PAPD_CUPS_H */\r
diff --git a/etc/papd/printcap.c b/etc/papd/printcap.c
deleted file mode 100644 (file)
index 9215a11..0000000
+++ /dev/null
@@ -1,528 +0,0 @@
-/*
- * $Id: printcap.c,v 1.12 2009-10-14 02:24:05 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- *
- * Copyright (c) 1983 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.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <ctype.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#include <atalk/paths.h>
-
-#include "printcap.h"
-
-#ifndef BUFSIZ
-#define        BUFSIZ  1024
-#endif /* ! BUFSIZ */
-#define MAXHOP 32      /* max number of tc= indirections */
-
-/*
- * termcap - routines for dealing with the terminal capability data base
- *
- * BUG:                Should use a "last" pointer in tbuf, so that searching
- *             for capabilities alphabetically would not be a n**2/2
- *             process when large numbers of capabilities are given.
- * Note:       If we add a last pointer now we will screw up the
- *             tc capability. We really should compile termcap.
- *
- * Essentially all the work here is scanning and decoding escapes
- * in string capabilities.  We don't use stdio because the editor
- * doesn't, and because living w/o it is not hard.
- */
-
-#define PRINTCAP
-
-#ifdef PRINTCAP
-#define tgetent        pgetent
-#define tskip  pskip
-#define tgetstr        pgetstr
-#define tdecode pdecode
-#define tgetnum        pgetnum
-#define        tgetflag pgetflag
-#define tdecode pdecode
-#define tnchktc        pnchktc
-#define        tnamatch pnamatch
-#define V6
-#endif /* PRINTCAP */
-
-static FILE *pfp = NULL;       /* printcap data base file pointer */
-static char *tbuf;
-static int hopcount;           /* detect infinite loops in termcap, init 0 */
-
-/*
- * Similar to tgetent except it returns the next entry instead of
- * doing a lookup.
- *
- * Added a "cap" parameter, so we can use these calls for printcap
- * and papd.conf.
- */
-int getprent( char *cap, char *bp, int bufsize)
-{
-       register int c, skip = 0, i;
-
-       if (pfp == NULL && (pfp = fopen( cap, "r")) == NULL)
-               return(-1);
-       tbuf = bp;
-       i = 0;
-       for (;;) {
-               switch (c = getc(pfp)) {
-               case EOF:
-                        if (bp != tbuf) {
-                               *bp = '\0';
-                               return(1);
-                       }
-                       fclose(pfp);
-                       pfp = NULL;
-                       return(0);
-               case '\n':
-                       if (bp == tbuf) {
-                               skip = 0;
-                               continue;
-                       }
-                       if (bp[-1] == '\\') {
-                               bp--;
-                               continue;
-                       }
-                       *bp = '\0';
-                       return(1);
-               case '#':
-                       if (bp == tbuf)
-                               skip++;
-               default:
-                       if (skip)
-                               continue;
-                       if (bp >= tbuf+BUFSIZ) {
-                               write(2, "Termcap entry too long\n", 23);
-                               *bp = '\0';
-                               return(1);
-                       }
-                       *bp++ = c;
-                       if (++i >= bufsize) {
-                               write(2, "config file too large\n", 22);
-                               fclose(pfp);
-                               pfp = NULL;
-                               *bp = '\0';
-                               return(1);
-                       }
-               }
-       }
-}
-
-void endprent(void)
-{
-       if (pfp != NULL)
-               fclose(pfp);
-}
-
-/*
- * Get an entry for terminal name in buffer bp,
- * from the termcap file.  Parse is very rudimentary;
- * we just notice escaped newlines.
- *
- * Added a "cap" parameter, so we can use these calls for printcap
- * and papd.conf.
- */
-int tgetent(char *cap, char *bp, char *name)
-{
-       register char *cp;
-       register int c;
-       register int i = 0, cnt = 0;
-       char ibuf[BUFSIZ];
-       int tf;
-       int skip;
-
-       hopcount = 0;
-       tbuf = bp;
-       tf = 0;
-#ifndef V6
-       cp = getenv("TERMCAP");
-       /*
-        * TERMCAP can have one of two things in it. It can be the
-        * name of a file to use instead of /etc/termcap. In this
-        * case it better start with a "/". Or it can be an entry to
-        * use so we don't have to read the file. In this case it
-        * has to already have the newlines crunched out.
-        */
-       if (cp && *cp) {
-               if (*cp!='/') {
-                       cp2 = getenv("TERM");
-                       if (cp2==(char *) 0 || strcmp(name,cp2)==0) {
-                               strcpy(bp,cp);
-                               return(tnchktc(cap));
-                       } else {
-                               tf = open(cap, 0);
-                       }
-               } else
-                       tf = open(cp, 0);
-       }
-       if (tf==0)
-               tf = open(cap, 0);
-#else /* V6 */
-       tf = open(cap, 0);
-#endif /* V6 */
-       if (tf < 0)
-               return (-1);
-       for (;;) {
-               cp = bp;
-               skip = 0;
-               for (;;) {
-                       if (i == cnt) {
-                               cnt = read(tf, ibuf, BUFSIZ);
-                               if (cnt <= 0) {
-                                       close(tf);
-                                       return (0);
-                               }
-                               i = 0;
-                       }
-                       c = ibuf[i++];
-                       if (c == '\n') {
-                               if (!skip && cp > bp && cp[-1] == '\\') {
-                                       cp--;
-                                       continue;
-                               }
-                               skip = 0;
-                               if (cp == bp)
-                                       continue;
-                               else
-                                       break;
-                       }
-                       if (c == '#' && cp == bp)
-                               skip++;
-                       if (skip)
-                               continue;
-                       if (cp >= bp+BUFSIZ) {
-                               write(2,"Termcap entry too long\n", 23);
-                               break;
-                       } else
-                               *cp++ = c;
-               }
-               *cp = 0;
-
-               /*
-                * The real work for the match.
-                */
-               if (tnamatch(name)) {
-                       close(tf);
-                       return(tnchktc(cap));
-               }
-       }
-}
-
-/*
- * tnchktc: check the last entry, see if it's tc=xxx. If so,
- * recursively find xxx and append that entry (minus the names)
- * to take the place of the tc=xxx entry. This allows termcap
- * entries to say "like an HP2621 but doesn't turn on the labels".
- * Note that this works because of the left to right scan.
- *
- * Added a "cap" parameter, so we can use these calls for printcap
- * and papd.conf.
- */
-int tnchktc( char *cap)
-{
-       register char *p, *q;
-       char tcname[16];        /* name of similar terminal */
-       char tcbuf[BUFSIZ];
-       char *holdtbuf = tbuf;
-       int l;
-
-       p = tbuf + strlen(tbuf) - 2;    /* before the last colon */
-       while (*--p != ':')
-               if (p<tbuf) {
-                       write(2, "Bad termcap entry\n", 18);
-                       return (0);
-               }
-       p++;
-       /* p now points to beginning of last field */
-       if (p[0] != 't' || p[1] != 'c')
-               return(1);
-       strcpy(tcname,p+3);
-       q = tcname;
-       while (q && *q != ':')
-               q++;
-       *q = 0;
-       if (++hopcount > MAXHOP) {
-               write(2, "Infinite tc= loop\n", 18);
-               return (0);
-       }
-       if (tgetent( cap, tcbuf, tcname) != 1)
-               return(0);
-       for (q=tcbuf; *q != ':'; q++)
-               ;
-       l = p - holdtbuf + strlen(q);
-       if (l > BUFSIZ) {
-               write(2, "Termcap entry too long\n", 23);
-               q[BUFSIZ - (p-tbuf)] = 0;
-       }
-       strcpy(p, q+1);
-       tbuf = holdtbuf;
-       return(1);
-}
-
-/*
- * Tnamatch deals with name matching.  The first field of the termcap
- * entry is a sequence of names separated by |'s, so we compare
- * against each such name.  The normal : terminator after the last
- * name (before the first field) stops us.
- */
-int tnamatch(char *np)
-{
-       register char *Np, *Bp;
-
-       Bp = tbuf;
-       if (*Bp == '#')
-               return(0);
-       for (;;) {
-               for (Np = np; *Np && *Bp == *Np; Bp++, Np++)
-                       continue;
-               if (*Np == 0 && (*Bp == '|' || *Bp == ':' || *Bp == 0))
-                       return (1);
-               while (*Bp && *Bp != ':' && *Bp != '|')
-                       Bp++;
-               if (*Bp == 0 || *Bp == ':')
-                       return (0);
-               Bp++;
-       }
-}
-
-/*
- * Skip to the next field.  Notice that this is very dumb, not
- * knowing about \: escapes or any such.  If necessary, :'s can be put
- * into the termcap file in octal.
- */
-static char *tskip(char *bp)
-{
-
-       while (*bp && *bp != ':')
-               bp++;
-       while (*bp && *bp == ':')
-               bp++;
-       return (bp);
-}
-
-/*
- * Return the (numeric) option id.
- * Numeric options look like
- *     li#80
- * i.e. the option string is separated from the numeric value by
- * a # character.  If the option is not found we return -1.
- * Note that we handle octal numbers beginning with 0.
- */
-int tgetnum(char *id)
-{
-       register int i, base;
-       register char *bp = tbuf;
-
-       for (;;) {
-               bp = tskip(bp);
-               if (*bp == 0)
-                       return (-1);
-               if (*bp++ != id[0] || *bp == 0 || *bp++ != id[1])
-                       continue;
-               if (*bp == '@')
-                       return(-1);
-               if (*bp != '#')
-                       continue;
-               bp++;
-               base = 10;
-               if (*bp == '0')
-                       base = 8;
-               i = 0;
-               while (isdigit(*bp))
-                       i *= base, i += *bp++ - '0';
-               return (i);
-       }
-}
-
-/*
- * Handle a flag option.
- * Flag options are given "naked", i.e. followed by a : or the end
- * of the buffer.  Return 1 if we find the option, or 0 if it is
- * not given.
- */
-int tgetflag(char *id)
-{
-       register char *bp = tbuf;
-
-       for (;;) {
-               bp = tskip(bp);
-               if (!*bp)
-                       return (0);
-               if (*bp++ == id[0] && *bp != 0 && *bp++ == id[1]) {
-                       if (!*bp || *bp == ':')
-                               return (1);
-                       else if (*bp == '@')
-                               return(0);
-               }
-       }
-}
-
-/*
- * Tdecode does the grung work to decode the
- * string capability escapes.
- */
-static char *
-tdecode(char *str, char **area)
-{
-       register char *cp;
-       register int c;
-       register char *dp;
-       int i;
-
-       cp = *area;
-       while ((c = *str++) && c != ':') {
-               switch (c) {
-
-               case '^':
-                       c = *str++ & 037;
-                       break;
-
-               case '\\':
-                       dp = "E\033^^\\\\::n\nr\rt\tb\bf\f";
-                       c = *str++;
-nextc:
-                       if (*dp++ == c) {
-                               c = *dp++;
-                               break;
-                       }
-                       dp++;
-                       if (*dp)
-                               goto nextc;
-                       if (isdigit(c)) {
-                               c -= '0', i = 2;
-                               do
-                                       c <<= 3, c |= *str++ - '0';
-                               while (--i && isdigit(*str));
-                       }
-                       break;
-               }
-               *cp++ = c;
-       }
-       *cp++ = 0;
-       str = *area;
-       *area = cp;
-       return (str);
-}
-
-/*
- * Get a string valued option.
- * These are given as
- *     cl=^Z
- * Much decoding is done on the strings, and the strings are
- * placed in area, which is a ref parameter which is updated.
- * No checking on area overflow.
- */
-char *
-tgetstr(char *id, char **area)
-{
-       register char *bp = tbuf;
-
-       for (;;) {
-               bp = tskip(bp);
-               if (!*bp)
-                       return (NULL);
-               if (*bp++ != id[0] || *bp == 0 || *bp++ != id[1])
-                       continue;
-               if (*bp == '@')
-                       return(NULL);
-               if (*bp != '=')
-                       continue;
-               bp++;
-               return (tdecode(bp, area));
-       }
-}
-
-static char *
-decodename(char *str, char **area, int bufsize)
-{
-       register char *cp;
-       register int c;
-       register char *dp;
-       int i;
-
-       cp = *area;
-       while ((c = *str++) && --bufsize && c != ':' && c != '|' ) {
-               switch (c) {
-
-               case '^':
-                       c = *str++ & 037;
-                       break;
-
-               case '\\':
-                       dp = "E\033^^\\\\::n\nr\rt\tb\bf\f";
-                       c = *str++;
-nextc:
-                       if (*dp++ == c) {
-                               c = *dp++;
-                               break;
-                       }
-                       dp++;
-                       if (*dp)
-                               goto nextc;
-                       if (isdigit(c)) {
-                               c -= '0', i = 2;
-                               do
-                                       c <<= 3, c |= *str++ - '0';
-                               while (--i && isdigit(*str));
-                       }
-                       break;
-               }
-               *cp++ = c;
-       }
-       *cp++ = 0;
-       str = *area;
-       *area = cp;
-       return (str);
-}
-
-char *
-getpname(char **area, int bufsize)
-{
-       return( decodename( tbuf, area, bufsize));
-}
diff --git a/etc/papd/printcap.h b/etc/papd/printcap.h
deleted file mode 100644 (file)
index d300d45..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * $Id: printcap.h,v 1.5 2009-10-13 22:55:37 didg Exp $
- */
-
-#ifndef PAPD_PRINTCAP_H
-#define PAPD_PRINTCAP_H 1
-
-#include <sys/cdefs.h>
-
-int getprent ( register char *, register char *, register int );
-int pnchktc ( char * );
-int pgetflag ( char * );
-void endprent ( void );
-int pgetent ( char *, char *, char * );
-int pgetnum ( char * );
-int pnamatch ( char * );
-
-#endif /* PAPD_PRINTCAP_H */
diff --git a/etc/papd/printer.h b/etc/papd/printer.h
deleted file mode 100644 (file)
index 7c56273..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * $Id: printer.h,v 1.6 2005-04-28 20:49:49 bfernhomberg Exp $
- *
- * Copyright (c) 1990,1995 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-struct printer {
-    char               *p_name;
-    char               *p_type;
-    char               *p_zone;
-    char               *p_u_name;
-#ifdef notdef
-    char               *p_fonts;
-    char               *p_psetdir;
-#endif /* notdef */
-    char               *p_ppdfile;
-    char               p_status[255];
-    char               *p_authprintdir;
-    int                        p_flags;
-    struct at_addr      p_addr;
-    union {
-       struct {
-           char                *pr_printer;
-           char                *pr_operator;
-           char                *pr_spool;
-#ifdef ABS_PRINT
-           char                *pr_role;
-           double              pr_balance;
-           int                 pr_srvid;
-#endif /* ABS_PRINT */
-           int                 pr_pagecost;
-           char                *pr_pagecost_msg;
-           char                *pr_lock;
-       } pu_pr;
-       char            *pu_cmd;
-    } p_un;
-    ATP                        p_atp;
-#ifdef HAVE_CUPS
-    char               *p_cupsoptions;
-#endif
-    struct printer     *p_next;
-};
-#define p_cmd          p_un.pu_cmd
-#define p_printer      p_un.pu_pr.pr_printer
-#define p_operator     p_un.pu_pr.pr_operator
-#define p_spool                p_un.pu_pr.pr_spool
-#ifdef ABS_PRINT
-#define p_role         p_un.pu_pr.pr_role
-#define p_balance      p_un.pu_pr.pr_balance
-#define p_srvid                p_un.pu_pr.pr_srvid
-#endif /* ABS_PRINT */
-#define p_pagecost     p_un.pu_pr.pr_pagecost
-#define p_pagecost_msg p_un.pu_pr.pr_pagecost_msg
-#define p_lock         p_un.pu_pr.pr_lock
-
-#define P_PIPED                (1<<0)
-#define P_SPOOLED      (1<<1)
-#define P_REGISTERED   (1<<2)
-#define P_ACCOUNT      (1<<3)
-#define P_KRB          (1<<4)
-#define P_AUTH         (1<<5)
-#define P_AUTH_PSSP    (1<<6)
-#define P_AUTH_CAP     (1<<7)
-#define P_CUPS         (1<<8)
-#define P_CUPS_PPD     (1<<9)
-#define P_CUPS_AUTOADDED (1<<10)
-#define P_FOOMATIC_HACK (1<<11)
-
-extern struct printer  *printer;
diff --git a/etc/papd/queries.c b/etc/papd/queries.c
deleted file mode 100644 (file)
index ef1c5a6..0000000
+++ /dev/null
@@ -1,790 +0,0 @@
-/*
- * $Id: queries.c,v 1.22 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <atalk/logger.h>
-#include <sys/param.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-
-#ifdef KRB
-#ifdef SOLARIS
-#include <kerberos/krb.h>
-#else /* SOLARIS */
-#include <krb.h>
-#endif /* SOLARIS */
-#endif /* KRB */
-
-#include "file.h"
-#include "comment.h"
-#include "printer.h"
-#include "ppd.h"
-#include "lp.h"
-#include "uam_auth.h"
-
-int cq_default( struct papfile *, struct papfile * );
-int cq_k4login( struct papfile *, struct papfile * );
-int cq_uameth( struct papfile *, struct papfile * );
-
-int gq_balance( struct papfile * );
-int gq_pagecost( struct papfile * );
-int gq_true( struct papfile * );
-int gq_rbispoolerid( struct papfile * );
-int gq_rbiuamlist( struct papfile * );
-
-int cq_query( struct papfile *, struct papfile * );
-void cq_font_answer( char *, char *, struct papfile * );
-int cq_font( struct papfile *, struct papfile * );
-int cq_feature( struct papfile *, struct papfile * );
-int cq_printer( struct papfile *, struct papfile * );
-int cq_rmjob( struct papfile *, struct papfile * );
-#ifndef HAVE_CUPS
-int cq_listq( struct papfile *, struct papfile * );
-int cq_rbilogin( struct papfile *, struct papfile * );
-#endif  /* HAVE_CUPS */
-
-
-
-int cq_default( struct papfile *in, struct papfile *out)
-{
-    char               *start, *stop, *p;
-    int                        linelength, crlflength;
-    struct papd_comment        *comment = compeek();
-
-    for (;;) {
-       switch ( markline( in, &start, &linelength, &crlflength )) {
-       case 0 :
-           return( 0 );
-
-       case -1 :
-           return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-       }
-
-       stop = start+linelength;
-
-       if ( comgetflags() == 0 ) {     /* started */
-           if ( comment->c_end ) {
-               comsetflags( 1 );
-           } else {
-               compop();
-               CONSUME( in, linelength + crlflength );
-               return( CH_DONE );
-           }
-       } else {
-           /* return default */
-           if ( comcmp( start, start+linelength, comment->c_end, 0 ) == 0 ) {
-               for ( p = start; p < stop; p++ ) {
-                   if ( *p == ':' ) {
-                       break;
-                   }
-               }
-               if (p < stop) {
-                   p++;
-                   while ( *p == ' ' ) {
-                       p++;
-                    }
-               }
-
-               append( out, p, stop - p + crlflength );
-               compop();
-               CONSUME( in, linelength + crlflength );
-               return( CH_DONE );
-           }
-       }
-
-       CONSUME( in, linelength + crlflength );
-    }
-}
-
-#ifdef KRB
-char   *LoginOK = "LoginOK\n";
-char   *LoginFailed = "LoginFailed\n";
-
-#define h2b(x) (isdigit((x))?(x)-'0':(isupper((x))?(x)-'A':(x)-'a')+10)
-
-int cq_k4login( struct papfile *in, struct papfile *out)
-{
-    char               *start, *p;
-    int                        linelength, crlflength;
-    unsigned char      *t;
-    struct papd_comment        *comment = compeek();
-    KTEXT_ST           tkt;
-    AUTH_DAT           ad;
-    int                        rc, i;
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-       return( 0 );
-
-    case -1 :
-       return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    p = start + strlen( comment->c_begin );
-    while ( *p == ' ' ) {
-       p++;
-    }
-
-    bzero( &tkt, sizeof( tkt ));
-    stop = start+linelength;
-    /* FIXME */
-    for ( i = 0, t = tkt.dat; p < stop; p += 2, t++, i++ ) {
-       *t = ( h2b( (unsigned char)*p ) << 4 ) +
-               h2b( (unsigned char)*( p + 1 ));
-    }
-    tkt.length = i;
-
-    if (( rc = krb_rd_req( &tkt, "LaserWriter", printer->p_name,
-           0, &ad, "" )) != RD_AP_OK ) {
-       LOG(log_error, logtype_papd, "cq_k4login: %s", krb_err_txt[ rc ] );
-       append( out, LoginFailed, strlen( LoginFailed ));
-       compop();
-       CONSUME( in, linelength + crlflength );
-       return( CH_DONE );
-    }
-    LOG(log_info, logtype_papd, "cq_k4login: %s.%s@%s", ad.pname, ad.pinst,
-           ad.prealm );
-    lp_person( ad.pname );
-    lp_host( ad.prealm );
-
-    append( out, LoginOK, strlen( LoginOK ));
-    compop();
-    CONSUME( in, linelength + crlflength);
-    return( CH_DONE );
-}
-
-char   *uameth = "UMICHKerberosIV\n*\n";
-
-int cq_uameth( struct papfile *in, struct papfile *out)
-{
-    char               *start;
-    int                        linelength, crlflength;
-    struct papd_comment        *c, *comment = compeek();
-
-    for (;;) {
-       switch ( markline( in, &start, &linelength, &crlflength )) {
-       case 0 :
-           return( 0 );
-
-       case -1 :
-           return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-       }
-
-       if ( comgetflags() == 0 ) {     /* start */
-           if (( printer->p_flags & P_KRB ) == 0 ) {   /* no kerberos */
-               if ( comswitch( queries, cq_default ) < 0 ) {
-                   LOG(log_error, logtype_papd, "cq_uameth: can't find default!" );
-                   exit( 1 );
-               }
-               return( CH_DONE );
-           }
-           comsetflags( 1 );
-       } else {
-           if ( comcmp( start, stop, comment->c_end, 0 ) == 0 ) { /* end */
-               append( out, uameth, strlen( uameth ));
-               compop();
-               return( CH_DONE );
-           }
-       }
-
-       CONSUME( in, linelength + crlflength );
-    }
-}
-#endif /* KRB */
-
-int gq_true( struct papfile *out)
-{
-    if ( printer->p_flags & P_SPOOLED ) {
-       append( out, "true\n", 5 );
-       return( 0 );
-    } else {
-       return( -1 );
-    }
-}
-
-int gq_pagecost( struct papfile *out)
-{
-    char               cost[ 60 ];
-
-    /* check for spooler? XXX */
-    if ( printer->p_pagecost_msg != NULL ) {
-       append( out, printer->p_pagecost_msg,
-               strlen( printer->p_pagecost_msg ));
-    } else if ( printer->p_flags & P_ACCOUNT ) {
-#ifdef ABS_PRINT
-       lp_pagecost();
-#endif /* ABS_PRINT */
-       sprintf( cost, "%d", printer->p_pagecost );
-       append( out, cost, strlen( cost ));
-    } else {
-       return( -1 );
-    }
-    append( out, "\n", 1 );
-    return( 0 );
-}
-
-#ifdef ABS_PRINT
-int gq_balance( struct papfile *out)
-{
-    char               balance[ 60 ];
-
-    if ( lp_pagecost() != 0 ) {
-       return( -1 );
-    }
-    sprintf( balance, "$%1.2f\n", printer->p_balance );
-    append( out, balance, strlen( balance ));
-    return( 0 );
-}
-#endif /* ABS_PRINT */
-
-
-/*
- * Handler for RBISpoolerID
- */
-
-static const char *spoolerid = "(PAPD Spooler) 1.0 (" VERSION ")\n";
-
-int gq_rbispoolerid( struct papfile *out)
-{
-    append( out, spoolerid, strlen( spoolerid ));
-    return(0);
-}
-
-
-
-/*
- * Handler for RBIUAMListQuery
- */
-
-static const char *nouams = "*\n";
-
-int gq_rbiuamlist( struct papfile *out)
-{
-    char uamnames[128] = "\0";
-
-    if (printer->p_flags & P_AUTH_PSSP) {
-       if (getuamnames(UAM_SERVER_PRINTAUTH, uamnames) < 0) {
-           append(out, nouams, strlen(nouams));
-           return(0);
-       } else {
-           append(out, uamnames, strlen(uamnames));
-           return(0);
-       }
-    } else {
-       append(out, nouams, strlen(nouams));
-       return(0);
-    }
-}
-
-
-struct genquery {
-    char       *gq_name;
-    int                (*gq_handler)();
-} genqueries[] = {
-    { "UMICHCostPerPage", gq_pagecost },
-#ifdef notdef
-    { "UMICHUserBalance", gq_balance },
-#endif /* notdef */
-    { "RBISpoolerID",  gq_rbispoolerid },
-    { "RBIUAMListQuery", gq_rbiuamlist },
-    { "ADOIsBinaryOK?", gq_true },
-    { "UMICHListQueue", gq_true },
-    { "UMICHDeleteJob", gq_true },
-    { NULL, NULL },
-};
-
-int cq_query( struct papfile *in, struct papfile *out)
-{
-    char               *start, *stop, *p, *q;
-    int                        linelength, crlflength;
-    struct papd_comment        *comment = compeek();
-    struct genquery    *gq;
-
-
-    for (;;) {
-       switch ( markline( in, &start, &linelength, &crlflength )) {
-       case 0 :
-           return( 0 );
-
-       case -1 :
-           return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-       }
-
-       stop = start+linelength;
-
-       if ( comgetflags() == 0 ) {     /* started */
-           comsetflags( 1 );
-
-           for ( p = start; p < stop; p++ ) {
-               if ( *p == ':' ) {
-                   break;
-               }
-           }
-
-           if (p < stop) for ( p++; p < stop; p++ ) {
-               if ( *p != ' ' && *p != '\t' ) {
-                   break;
-               }
-           }
-
-           for ( q = p; q < stop; q++ ) {
-               if ( *q == ' ' || *q == '\t' || *q == '\r' || *q == '\n' ) {
-                   break;
-               }
-           }
-
-           for ( gq = genqueries; gq->gq_name; gq++ ) {
-               if (( strlen( gq->gq_name ) == (size_t)(q - p) ) &&
-                       ( strncmp( gq->gq_name, p, q - p ) == 0 )) {
-                   break;
-               }
-           }
-           if ( gq->gq_name == NULL || gq->gq_handler == NULL ||
-                   (gq->gq_handler)( out ) < 0 ) {
-               if ( comswitch( queries, cq_default ) < 0 ) {
-                   LOG(log_error, logtype_papd, "cq_feature: can't find default!" );
-                   exit( 1 );
-               }
-               return( CH_DONE );
-           }
-       } else {
-           if ( comcmp( start, stop, comment->c_end, 0 ) == 0 ) {
-               compop();
-               CONSUME( in, linelength + crlflength );
-               return( CH_DONE );
-           }
-       }
-
-       CONSUME( in, linelength + crlflength );
-    }
-}
-
-void cq_font_answer( char *start, char *stop, struct papfile *out)
-{
-    char               *p, *q, buf[ 256 ];
-    struct ppd_font    *pfo;
-
-    p = start;
-    while ( p < stop ) {
-        unsigned int count = 0;
-       while (( *p == ' ' || *p == '\t' ) && p < stop ) {
-           p++;
-       }
-
-       q = buf;
-       while ( *p != ' ' && *p != '\t' &&
-               *p != '\n' && *p != '\r' && p < stop && count < sizeof(buf)) {
-           *q++ = *p++;
-           count++;
-       }
-
-       if ( q != buf ) {
-           *q = '\0';
-
-           append( out, "/", 1 );
-           append( out, buf, strlen( buf ));
-           append( out, ":", 1 );
-
-           if (( pfo = ppd_font( buf )) == NULL ) {
-               append( out, "No\n", 3 );
-           } else {
-               append( out, "Yes\n", 4 );
-           }
-       }
-    }
-
-    return;
-}
-
-int cq_font(struct papfile *in, struct papfile *out)
-{
-    char               *start, *stop, *p;
-    int                        linelength, crlflength;
-    struct papd_comment        *comment = compeek();
-
-    for (;;) {
-       switch ( markline( in, &start, &linelength, &crlflength )) {
-       case 0 :
-           return( 0 );
-
-       case -1 :
-           return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-       }
-
-       stop = start + linelength;
-
-       if ( comgetflags() == 0 ) {
-           comsetflags( 1 );
-
-           for ( p = start; p < stop; p++ ) {
-               if ( *p == ':' ) {
-                   break;
-               }
-           }
-           if (p < stop)
-               p++;
-
-           cq_font_answer( p, stop, out );
-       } else {
-           if ( comgetflags() == 1 &&
-                   comcmp( start, stop, comcont, 0 ) == 0 ) {
-               /* continuation */
-
-               for ( p = start; p < stop; p++ ) {
-                   if ( *p == ' ' ) {
-                       break;
-                   }
-               }
-               if (p < stop)
-                   p++;
-
-               cq_font_answer( p, stop, out );
-           } else {
-               comsetflags( 2 );
-               if ( comcmp( start, stop, comment->c_end, 0 ) == 0 ) {
-                   append( out, "*\n", 2 );
-                   compop();
-                   CONSUME( in, linelength + crlflength );
-                   return( CH_DONE );
-               }
-           }
-       }
-
-        CONSUME( in, linelength + crlflength );
-    }
-}
-
-int cq_feature( struct papfile *in, struct papfile *out)
-{
-    char               *start, *stop, *p;
-    int                        linelength, crlflength;
-    struct papd_comment        *comment = compeek();
-    struct ppd_feature *pfe;
-
-    for (;;) {
-       switch ( markline( in, &start, &linelength, &crlflength )) {
-       case 0 :
-           return( 0 );
-
-       case -1 :
-           return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-       }
-
-       stop = start + linelength;
-
-       if ( comgetflags() == 0 ) {
-           comsetflags( 1 );
-
-           /* parse for feature */
-           for ( p = start; p < stop; p++ ) {
-               if ( *p == ':' ) {
-                   break;
-               }
-           }
-           if (p < stop)
-               p++;
-           while ( *p == ' ' ) {
-               p++;
-           }
-
-           if (( pfe = ppd_feature( p, stop - p )) == NULL ) {
-               if ( comswitch( queries, cq_default ) < 0 ) {
-                   LOG(log_error, logtype_papd, "cq_feature: can't find default!" );
-                   exit( 1 );
-               }
-               return( CH_DONE );
-           }
-
-           append( out, pfe->pd_value, strlen( pfe->pd_value ));
-           append( out, "\r", 1 );
-       } else {
-           if ( comcmp( start, stop, comment->c_end, 0 ) == 0 ) {
-               compop();
-               CONSUME( in, linelength + crlflength );
-               return( CH_DONE );
-           }
-       }
-
-       CONSUME( in, linelength + crlflength );
-    }
-}
-
-static const char      *psver = "*PSVersion\n";
-static const char      *prod = "*Product\n";
-
-int cq_printer(struct papfile *in, struct papfile *out)
-{
-    char               *start, *p;
-    int                        linelength, crlflength;
-    struct papd_comment        *comment = compeek();
-    struct ppd_feature *pdpsver, *pdprod;
-
-    for (;;) {
-       switch ( markline( in, &start, &linelength, &crlflength )) {
-       case 0 :
-           return( 0 );
-
-       case -1 :
-           return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-       }
-
-       if ( comgetflags() == 0 ) {
-           comsetflags( 1 );
-
-           if (( pdpsver = ppd_feature( psver, strlen( psver ))) == NULL ) {
-               if ( comswitch( queries, cq_default ) < 0 ) {
-                   LOG(log_error, logtype_papd, "cq_printer: can't find default!" );
-                   exit( 1 );
-               }
-               return( CH_DONE );
-           }
-
-           for ( p = pdpsver->pd_value; *p != '\0'; p++ ) {
-               if ( *p == ' ' ) {
-                   break;
-               }
-           }
-           if ( *p == '\0' ) {
-               LOG(log_error, logtype_papd, "cq_printer: can't parse PSVersion!" );
-               if ( comswitch( queries, cq_default ) < 0 ) {
-                   LOG(log_error, logtype_papd, "cq_printer: can't find default!" );
-                   exit( 1 );
-               }
-               return( CH_DONE );
-           }
-
-           if (( pdprod = ppd_feature( prod, strlen( prod ))) == NULL ) {
-               if ( comswitch( queries, cq_default ) < 0 ) {
-                   LOG(log_error, logtype_papd, "cq_printer: can't find default!" );
-                   exit( 1 );
-               }
-               return( CH_DONE );
-           }
-
-           /* revision */
-           append( out, p + 1, strlen( p + 1 ));
-           append( out, "\r", 1 );
-
-           /* version */
-           append( out, pdpsver->pd_value, p - pdpsver->pd_value );
-           append( out, "\r", 1 );
-
-           /* product */
-           append( out, pdprod->pd_value, strlen( pdprod->pd_value ));
-           append( out, "\r", 1 );
-       } else {
-           if ( comcmp( start, start+linelength, comment->c_end, 0 ) == 0 ) {
-               compop();
-               CONSUME( in, linelength + crlflength );
-               return( CH_DONE );
-           }
-       }
-
-       CONSUME( in, linelength + crlflength );
-    }
-}
-
-#ifndef HAVE_CUPS
-
-static const char      *rmjobfailed = "Failed\n";
-static const char      *rmjobok = "Ok\n";
-
-int cq_rmjob( struct papfile *in, struct papfile *out)
-{
-    char               *start, *stop, *p;
-    int                        linelength, crlflength;
-    int                        job;
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-       return( 0 );
-
-    case -1 :
-       return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    stop = start + linelength;
-
-    for ( p = start; p < stop; p++ ) {
-       if ( *p == ' ' || *p == '\t' ) {
-           break;
-       }
-    }
-    for ( ; p < stop; p++ ) {
-       if ( *p != ' ' && *p != '\t' ) {
-           break;
-       }
-    }
-
-    *stop = '\0';
-    if ( p < stop && ( job = atoi( p )) > 0 ) {
-       lp_rmjob( job );
-       append( out, rmjobok, strlen( rmjobok ));
-    } else {
-       append( out, rmjobfailed, strlen( rmjobfailed ));
-    }
-
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return( CH_DONE );
-}
-
-int cq_listq( struct papfile *in, struct papfile *out)
-{
-    char               *start;
-    int                        linelength, crlflength;
-
-    switch ( markline( in, &start, &linelength, &crlflength )) {
-    case 0 :
-       return( 0 );
-
-    case -1 :
-       return( CH_MORE );
-
-    case -2 :
-        return( CH_ERROR );
-    }
-
-    if ( lp_queue( out )) {
-       LOG(log_error, logtype_papd, "cq_listq: lp_queue failed" );
-    }
-
-    compop();
-    CONSUME( in, linelength + crlflength );
-    return( CH_DONE );
-}
-#endif /* HAVE_CUPS */
-
-
-/*
- * Handler for RBILogin
- */
-
-static struct uam_obj *papd_uam = NULL;
-static const char *rbiloginok = "0\r";
-static const char *rbiloginbad = "-1\r";
-static const char *rbiloginerrstr = "%%[Error: SecurityError; \
-SecurityViolation: Unknown user, incorrect password or log on is \
-disabled ]%%\r%%[Flushing: rest of job (to end-of-file) will be \
-ignored ]%%\r";
-
-int cq_rbilogin( struct papfile *in, struct papfile *out)
-{
-    char               *start, *stop, *p, *begin;
-    int                        linelength, crlflength;
-    char               username[UAM_USERNAMELEN + 1] = "\0";
-    struct papd_comment        *comment = compeek();
-    char               uamtype[20];
-
-    for (;;) {
-        switch ( markline( in, &start, &linelength, &crlflength )) {
-        case 0 :
-            return( 0 );
-
-        case -1 :
-            return( CH_MORE );
-
-        case -2 :
-            return( CH_ERROR );
-        }
-
-       stop = start + linelength;
-
-        if ( comgetflags() == 0 ) { /* first line */
-           begin = start + strlen(comment->c_begin);
-           p = begin;
-
-           while (*p != ' ' && p < stop) {
-               p++;
-           }
-
-           memset(uamtype, 0, sizeof(uamtype));
-           if ((size_t)(p -begin) <= sizeof(uamtype) -1) {
-               strncpy(uamtype, begin, p - begin);
-            }
-
-           if ( !*uamtype || (papd_uam = auth_uamfind(UAM_SERVER_PRINTAUTH,
-                               uamtype, strlen(uamtype))) == NULL) {
-               LOG(log_info, logtype_papd, "Could not find uam: %s", uamtype);
-               append(out, rbiloginbad, strlen(rbiloginbad));
-               append(out, rbiloginerrstr, strlen(rbiloginerrstr));
-           } else {
-                if ( (papd_uam->u.uam_printer(p,stop,username,out)) == 0 ) {
-                    lp_person( username );
-                   append(out, rbiloginok, strlen( rbiloginok ));
-                   LOG(log_info, logtype_papd, "RBILogin: Logged in '%s'", username);
-                } else {
-                    append(out, rbiloginbad, strlen( rbiloginbad));
-                    append(out, rbiloginerrstr, strlen(rbiloginerrstr));
-                }
-           }
-            comsetflags( 1 );
-        } else {
-            if ( comcmp( start, stop, comment->c_end, 0 ) == 0 ) {
-                compop();
-                return( CH_DONE );
-            }
-        }
-
-        CONSUME( in, linelength + crlflength );
-    }
-}
-
-
-/*
- * All queries start with %%?Begin and end with %%?End.  Note that the
- * "Begin"/"End" general queries have to be last.
- */
-struct papd_comment    queries[] = {
-#ifdef KRB
-    { "%%Login: UMICHKerberosIV", NULL,                        cq_k4login,     0 },
-    { "%%?BeginUAMethodsQuery",        "%%?EndUAMethodsQuery:", cq_uameth,C_FULL },
-#endif /* KRB */
-#ifndef HAVE_CUPS
-    { "%UMICHListQueue",       NULL,                   cq_listq,  C_FULL },
-    { "%UMICHDeleteJob",       NULL,                   cq_rmjob,       0 },
-#endif /* HAVE_CUPS */
-    { "%%?BeginQuery: RBILogin ", "%%?EndQuery",       cq_rbilogin,    0 },
-    { "%%?BeginQuery",         "%%?EndQuery",          cq_query,       0 },
-    { "%%?BeginFeatureQuery",  "%%?EndFeatureQuery",   cq_feature,     0 },
-    { "%%?BeginFontQuery",     "%%?EndFontQuery",      cq_font,        0 },
-    { "%%?BeginPrinterQuery",  "%%?EndPrinterQuery",   cq_printer,C_FULL },
-    { "%%?Begin",              "%%?End",               cq_default,     0 },
-    { NULL,                    NULL,                   NULL,           0 },
-};
diff --git a/etc/papd/session.c b/etc/papd/session.c
deleted file mode 100644 (file)
index 7067f5f..0000000
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * $Id: session.c,v 1.20 2009-10-16 01:10:59 didg Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifdef HAVE_SYS_ERRNO_H
-#include <sys/errno.h>
-#endif /* HAVE_SYS_ERRNO_H */
-#ifdef HAVE_ERRNO_H
-#include <errno.h>
-#endif /* HAVE_ERRNO_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <atalk/logger.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/pap.h>
-
-#include "file.h"
-#include "lp.h"
-#include "session.h"
-
-int ps(struct papfile *infile, struct papfile *outfile, struct sockaddr_at *sat);
-
-extern unsigned char   connid, quantum, oquantum;
-
-static char            buf[ PAP_MAXQUANTUM ][ 4 + PAP_MAXDATA ];
-static struct iovec    niov[ PAP_MAXQUANTUM ] = {
-    { buf[ 0 ],        0 },
-    { buf[ 1 ],        0 },
-    { buf[ 2 ],        0 },
-    { buf[ 3 ],        0 },
-    { buf[ 4 ],        0 },
-    { buf[ 5 ],        0 },
-    { buf[ 6 ],        0 },
-    { buf[ 7 ],        0 },
-};
-
-/*
- * Accept files until the client closes the connection.
- * Read lines of a file, until the client sends eof, after
- * which we'll send eof also.
- */
-int session(ATP atp, struct sockaddr_at *sat)
-{
-    struct timeval     tv;
-    struct atp_block   atpb;
-    struct sockaddr_at ssat;
-    struct papfile     infile, outfile;
-    fd_set             fds;
-    char               cbuf[ 578 ];
-    int                        i, cc, timeout = 0, readpending = 0;
-    u_int16_t          seq = 0, rseq = 1, netseq;
-    u_char             readport; /* uninitialized, OK 310105 */
-
-    infile.pf_state = PF_BOT;
-    infile.pf_bufsize = 0;
-    infile.pf_datalen = 0;
-    infile.pf_buf = NULL;
-    infile.pf_data = NULL;
-
-    outfile.pf_state = PF_BOT;
-    outfile.pf_bufsize = 0;
-    outfile.pf_datalen = 0;
-    outfile.pf_buf = NULL;
-    outfile.pf_data = NULL;
-
-    /*
-     * Ask for data.
-     */
-    cbuf[ 0 ] = connid;
-    cbuf[ 1 ] = PAP_READ;
-    if (++seq == 0) seq = 1;
-    netseq = htons( seq );
-    memcpy( &cbuf[ 2 ], &netseq, sizeof( netseq ));
-    atpb.atp_saddr = sat;
-    atpb.atp_sreqdata = cbuf;
-    atpb.atp_sreqdlen = 4;             /* bytes in SendData request */
-    atpb.atp_sreqto = 5;               /* retry timer */
-    atpb.atp_sreqtries = -1;           /* infinite retries */
-    if ( atp_sreq( atp, &atpb, oquantum, ATP_XO )) {
-       LOG(log_error, logtype_papd, "atp_sreq: %s", strerror(errno) );
-       return( -1 );
-    }
-
-    for (;;) {
-       /*
-        * Time between tickles.
-        */
-       tv.tv_sec = 60;
-       tv.tv_usec = 0;
-
-       /*
-        * If we don't get anything for a while, time out.
-        */
-       FD_ZERO( &fds );
-       FD_SET( atp_fileno( atp ), &fds );
-
-       do { /* do list until success or an unrecoverable error occurs */
-         if (( cc = select( FD_SETSIZE, &fds, NULL, NULL, &tv )) < 0 )
-             LOG(log_error, logtype_papd, "select: %s", strerror(errno) ); /* log all errors */
-       } while (( cc < 0 ) && (errno == 4));
-
-       if ( cc < 0 ) {
-         LOG(log_error, logtype_papd, "select: Error is unrecoverable" );
-         return( -1 );
-       }
-       if ( cc == 0 ) {
-           if ( timeout++ > 2 ) {
-               LOG(log_error, logtype_papd, "connection timed out" );
-               lp_cancel();
-               return( -1 );
-           }
-
-           /*
-            * Send a tickle.
-            */
-           cbuf[ 0 ] = connid;
-           cbuf[ 1 ] = PAP_TICKLE;
-           cbuf[ 2 ] = cbuf[ 3 ] = 0;
-           atpb.atp_saddr = sat;
-           atpb.atp_sreqdata = cbuf;
-           atpb.atp_sreqdlen = 4;              /* bytes in Tickle request */
-           atpb.atp_sreqto = 0;                /* best effort */
-           atpb.atp_sreqtries = 1;             /* try once */
-           if ( atp_sreq( atp, &atpb, 0, 0 )) {
-               LOG(log_error, logtype_papd, "atp_sreq: %s", strerror(errno) );
-               return( -1 );
-           }
-           continue;
-       } else {
-           timeout = 0;
-       }
-
-       memset( &ssat, 0, sizeof( struct sockaddr_at ));
-       switch( atp_rsel( atp, &ssat, ATP_TRESP | ATP_TREQ )) {
-       case ATP_TREQ :
-           atpb.atp_saddr = &ssat;
-           atpb.atp_rreqdata = cbuf;
-           atpb.atp_rreqdlen = sizeof( cbuf );
-           if ( atp_rreq( atp, &atpb ) < 0 ) {
-               LOG(log_error, logtype_papd, "atp_rreq: %s", strerror(errno) );
-               return( -1 );
-           }
-           /* sanity */
-           if ( (unsigned char)cbuf[ 0 ] != connid ) {
-               LOG(log_error, logtype_papd, "Bad ATP request!" );
-               continue;
-           }
-
-           switch( cbuf[ 1 ] ) {
-           case PAP_READ :
-               /*
-                * Other side is ready for some data.
-                */
-               memcpy( &netseq, &cbuf[ 2 ], sizeof( netseq ));
-               if ( netseq != 0 ) {
-                   if ( rseq != ntohs( netseq )) {
-                       break;
-                   }
-                   if ( rseq++ == 0xffff ) rseq = 1;
-               }
-               readpending = 1;
-               readport = ssat.sat_port;
-               break;
-
-           case PAP_CLOSE :
-               /*
-                * Respond to the close request.
-                * If we're in the middle of a file, clean up.
-                */
-               if (( infile.pf_state & PF_BOT ) ||
-                       ( infile.pf_datalen == 0 &&
-                       ( infile.pf_state & PF_EOF ))) {
-                   lp_print();
-               } else {
-                   lp_cancel();
-               }
-
-               niov[ 0 ].iov_len = 4;
-               ((char *)niov[ 0 ].iov_base)[ 0 ] = connid;
-               ((char *)niov[ 0 ].iov_base)[ 1 ] = PAP_CLOSEREPLY;
-               ((char *)niov[ 0 ].iov_base)[ 2 ] =
-                       ((char *)niov[ 0 ].iov_base)[ 3 ] = 0;
-               atpb.atp_sresiov = niov;
-               atpb.atp_sresiovcnt = 1;
-               if ( atp_sresp( atp, &atpb ) < 0 ) {
-                   LOG(log_error, logtype_papd, "atp_sresp: %s", strerror(errno) );
-                   exit( 1 );
-               }
-               return( 0 );
-               break;
-
-           case PAP_TICKLE :
-               break;
-           default :
-               LOG(log_error, logtype_papd, "Bad PAP request!" );
-           }
-
-           break;
-
-       case ATP_TRESP :
-           atpb.atp_saddr = &ssat;
-           for ( i = 0; i < oquantum; i++ ) {
-               niov[ i ].iov_len = PAP_MAXDATA + 4;
-           }
-           atpb.atp_rresiov = niov;
-           atpb.atp_rresiovcnt = oquantum;
-           if ( atp_rresp( atp, &atpb ) < 0 ) {
-               LOG(log_error, logtype_papd, "atp_rresp: %s", strerror(errno) );
-               return( -1 );
-           }
-
-           /* sanity */
-           if ( ((unsigned char *)niov[ 0 ].iov_base)[ 0 ] != connid ||
-                   ((char *)niov[ 0 ].iov_base)[ 1 ] != PAP_DATA ) {
-               LOG(log_error, logtype_papd, "Bad data response!" );
-               continue;
-           }
-
-           for ( i = 0; i < atpb.atp_rresiovcnt; i++ ) {
-               append( &infile,
-                       (char *)niov[ i ].iov_base + 4, niov[ i ].iov_len - 4 );
-               if (( infile.pf_state & PF_EOF ) == 0 &&
-                       ((char *)niov[ 0 ].iov_base)[ 2 ] ) {
-                   infile.pf_state |= PF_EOF;
-               }
-           }
-
-           /* move data */
-           if ( ps( &infile, &outfile, sat ) < 0 ) {
-               LOG(log_error, logtype_papd, "parse: bad return" );
-               return( -1 );   /* really?  close? */
-           }
-
-           /*
-            * Ask for more data.
-            */
-           cbuf[ 0 ] = connid;
-           cbuf[ 1 ] = PAP_READ;
-           if ( ++seq == 0 ) seq = 1;
-           netseq = htons( seq );
-           memcpy( &cbuf[ 2 ], &netseq, sizeof( netseq ));
-           atpb.atp_saddr = sat;
-           atpb.atp_sreqdata = cbuf;
-           atpb.atp_sreqdlen = 4;              /* bytes in SendData request */
-           atpb.atp_sreqto = 5;                /* retry timer */
-           atpb.atp_sreqtries = -1;            /* infinite retries */
-           if ( atp_sreq( atp, &atpb, oquantum, ATP_XO )) {
-               LOG(log_error, logtype_papd, "atp_sreq: %s", strerror(errno) );
-               return( -1 );
-           }
-           break;
-
-       case 0:
-           break;
-
-       default :
-           LOG(log_error, logtype_papd, "atp_rsel: %s", strerror(errno) );
-           return( -1 );
-       }
-
-       /* send any data that we have */
-       if ( readpending &&
-               ( outfile.pf_datalen || ( outfile.pf_state & PF_EOF ))) {
-           for ( i = 0; i < quantum; i++ ) {
-               ((char *)niov[ i ].iov_base)[ 0 ] = connid;
-               ((char *)niov[ i ].iov_base)[ 1 ] = PAP_DATA;
-               ((char *)niov[ i ].iov_base)[ 2 ] =
-                       ((char *)niov[ i ].iov_base)[ 3 ] = 0;
-
-               if ( outfile.pf_datalen > PAP_MAXDATA  ) {
-                   cc = PAP_MAXDATA;
-               } else {
-                   cc = outfile.pf_datalen;
-                   if ( outfile.pf_state & PF_EOF ) {
-                       ((char *)niov[ 0 ].iov_base)[ 2 ] = 1;  /* eof */
-                       outfile.pf_state = PF_BOT;
-                       infile.pf_state = PF_BOT;
-                   }
-               }
-
-               niov[ i ].iov_len = 4 + cc;
-               memcpy( (char *)niov[ i ].iov_base + 4, outfile.pf_data, cc );
-               CONSUME( &outfile, cc );
-               if ( outfile.pf_datalen == 0 ) {
-                   i++;
-                   break;
-               }
-           }
-           ssat.sat_port = readport;
-           atpb.atp_saddr = &ssat;
-           atpb.atp_sresiov = niov;
-           atpb.atp_sresiovcnt = i;    /* reported by stevebn@pc1.eos.co.uk */
-           if ( atp_sresp( atp, &atpb ) < 0 ) {
-               LOG(log_error, logtype_papd, "atp_sresp: %s", strerror(errno) );
-               return( -1 );
-           }
-           readpending = 0;
-       }
-    }
-}
diff --git a/etc/papd/session.h b/etc/papd/session.h
deleted file mode 100644 (file)
index 86e830f..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
- * $Id: session.h,v 1.2 2001-06-25 20:13:45 rufustfirefly Exp $
- */
-
-#ifndef PAPD_SESSION_H
-#define PAPD_SESSION_H 1
-
-#include <atalk/atp.h>
-
-int session( ATP atp, struct sockaddr_at *sat );
-
-#endif /* PAPD_SESSION_H */
diff --git a/etc/papd/showppd.c b/etc/papd/showppd.c
deleted file mode 100644 (file)
index d023204..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * $Id: showppd.c,v 1.7 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1995 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <atalk/logger.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/time.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-
-#include "ppd.h"
-
-extern struct ppd_font         *ppd_fonts;
-
-extern struct ppd_feature      ppd_features[];
-
-
-int main(int ac, char **av)
-{
-    struct ppd_feature *pfe;
-    struct ppd_font    *pfo;
-
-    if ( ac != 2 ) {
-       fprintf( stderr, "Usage:\t%s ppdfile\n", av[ 0 ] );
-       exit( 1 );
-    }
-
-    read_ppd( av[ 1 ], 0 );
-    for ( pfo = ppd_fonts; pfo; pfo = pfo->pd_next ) {
-       printf( "Font: %s\n", pfo->pd_font );
-    }
-    for ( pfe = ppd_features; pfe->pd_name; pfe++ ) {
-       printf( "Feature: %s %s\n", pfe->pd_name, (pfe->pd_value)?pfe->pd_value:"NULL" );
-    }
-
-    exit ( 0 );
-}
diff --git a/etc/papd/uam.c b/etc/papd/uam.c
deleted file mode 100644 (file)
index 2962fad..0000000
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * $Id: uam.c,v 1.11 2009-10-15 11:39:48 didg Exp $
- *
- * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-/* STDC check */
-#if STDC_HEADERS
-#include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <fcntl.h>
-#include <ctype.h>
-#include <atalk/logger.h>
-#include <sys/param.h>
-#include <sys/time.h>
-
-#include <netatalk/endian.h>
-#include <atalk/asp.h>
-#include <atalk/dsi.h>
-#include <atalk/afp.h>
-#include <atalk/util.h>
-
-#include "uam_auth.h"
-
-/* --- server uam functions -- */
-
-/* uam_load. uams must have a uam_setup function. */
-struct uam_mod *uam_load(const char *path, const char *name)
-{
-  char buf[MAXPATHLEN + 1], *p;
-  struct uam_mod *mod;
-  void *module;
-
-  if ((module = mod_open(path)) == NULL) {
-    LOG(log_error, logtype_papd, "uam_load(%s): failed to load: %s", name, mod_error());
-    return NULL;
-  }
-
-  if ((mod = (struct uam_mod *) malloc(sizeof(struct uam_mod))) == NULL) {
-    LOG(log_error, logtype_papd, "uam_load(%s): malloc failed", name);
-    goto uam_load_fail;
-  }
-
-  strlcpy(buf, name, sizeof(buf));
-  if ((p = strchr(buf, '.')))
-    *p = '\0';
-  if ((mod->uam_fcn = mod_symbol(module, buf)) == NULL) {
-    goto uam_load_err;
-  }
-
-  if (mod->uam_fcn->uam_type != UAM_MODULE_SERVER) {
-    LOG(log_error, logtype_papd, "uam_load(%s): attempted to load a non-server module",
-          name);
-    goto uam_load_err;
-  }
-
-  /* version check would go here */
-
-  if (!mod->uam_fcn->uam_setup || 
-      ((*mod->uam_fcn->uam_setup)(name) < 0)) {
-    LOG(log_error, logtype_papd, "uam_load(%s): uam_setup failed", name);
-    goto uam_load_err;
-  }
-
-  mod->uam_module = module;
-  return mod;
-
-uam_load_err:
-  free(mod);
-uam_load_fail:
-  mod_close(module);
-  return NULL;
-}
-
-/* unload the module. we check for a cleanup function, but we don't
- * die if one doesn't exist. however, things are likely to leak without one.
- */
-void uam_unload(struct uam_mod *mod)
-{
-  if (mod->uam_fcn->uam_cleanup)
-    (*mod->uam_fcn->uam_cleanup)();
-  mod_close(mod->uam_module);
-  free(mod);
-}
-
-/* -- client-side uam functions -- */
-
-/* set up stuff for this uam. */
-int uam_register(const int type, const char *path, const char *name, ...)
-{
-  va_list ap;
-  struct uam_obj *uam;
-  int ret;
-
-  if (!name)
-    return -1;
-
-  /* see if it already exists. */
-  if ((uam = auth_uamfind(type, name, strlen(name)))) {
-    if (strcmp(uam->uam_path, path)) {
-      /* it exists, but it's not the same module. */
-      LOG(log_error, logtype_papd, "uam_register: \"%s\" already loaded by %s",
-            name, path);
-      return -1;
-    }
-    uam->uam_count++;
-    return 0;
-  }
-  
-  /* allocate space for uam */
-  if ((uam = calloc(1, sizeof(struct uam_obj))) == NULL)
-    return -1;
-
-  uam->uam_name = name;
-  uam->uam_path = strdup(path);
-  uam->uam_count++;
-
-  va_start(ap, name);
-  switch (type) {
-  case UAM_SERVER_LOGIN: /* expect three arguments */
-    uam->u.uam_login.login = va_arg(ap, void *);
-    uam->u.uam_login.logincont = va_arg(ap, void *);
-    uam->u.uam_login.logout = va_arg(ap, void *);
-    break;
-  case UAM_SERVER_CHANGEPW: /* one argument */
-    uam->u.uam_changepw = va_arg(ap, void *);
-    break;
-  case UAM_SERVER_PRINTAUTH: /* x arguments */
-    uam->u.uam_printer = va_arg(ap, void *);
-    break;
-  default:
-    break;
-  }
-  va_end(ap);
-
-  /* attach to other uams */
-  ret = auth_register(type, uam);
-  if (ret) {
-    free(uam->uam_path);
-    free(uam);
-  }
-
-  return ret;
-}
-
-void uam_unregister(const int type, const char *name)
-{
-  struct uam_obj *uam;
-
-  if (!name)
-    return;
-
-  uam = auth_uamfind(type, name, strlen(name));
-  if (!uam || --uam->uam_count > 0)
-    return;
-
-  auth_unregister(uam);
-  free(uam->uam_path);
-  free(uam);
-}
-
-/* Crap to support uams which call this afpd function */
-int uam_afpserver_option(void *private _U_, const int what _U_, void *option _U_,
-                         size_t *len _U_)
-{
-       return(0);
-}
-
-/* --- helper functions for plugin uams --- */
-
-struct passwd *uam_getname(void *dummy _U_, char *name, const int len)
-{
-  struct passwd *pwent;
-  char *user;
-  int i;
-
-  if ((pwent = getpwnam(name)))
-    return pwent;
-
-#ifndef NO_REAL_USER_NAME
-  for (i = 0; i < len; i++)
-    name[i] = tolower(name[i]);
-
-  setpwent();
-  while ((pwent = getpwent())) {
-    if ((user = strchr(pwent->pw_gecos, ','))) *user = '\0';
-    user = pwent->pw_gecos;
-
-    /* check against both the gecos and the name fields. the user
-     * might have just used a different capitalization. */
-    if ((strncasecmp(user, name, len) == 0) ||
-        (strncasecmp(pwent->pw_name, name, len) == 0)) {
-      strncpy(name, pwent->pw_name, len);
-      break;
-    }
-  }
-  endpwent();
-#endif /* NO_REAL_USER_NAME */
-
-  /* os x server doesn't keep anything useful if we do getpwent */
-  return pwent ? getpwnam(name) : NULL;
-}
-
-
-int uam_checkuser(const struct passwd *pwd)
-{
-  char *p;
-
-  if (!pwd || !pwd->pw_shell || (*pwd->pw_shell == '\0')) 
-    return -1;
-
-  while ((p = getusershell())) {
-    if ( strcmp( p, pwd->pw_shell ) == 0 ) 
-      break;
-  }
-  endusershell();
-
-#ifndef DISABLE_SHELLCHECK
-  if (!p) {
-    LOG(log_info, logtype_papd, "illegal shell %s for %s",pwd->pw_shell,pwd->pw_name);
-    return -1;
-  }
-#endif /* DISABLE_SHELLCHECK */
-
-  return 0;
-}
-
-
diff --git a/etc/papd/uam_auth.h b/etc/papd/uam_auth.h
deleted file mode 100644 (file)
index 0cc9156..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * $Id: uam_auth.h,v 1.4 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
- * All Rights Reserved.  See COPYRIGHT.
- *
- * interface between uam.c and auth.c
- */
-
-#ifndef PAPD_UAM_AUTH_H
-#define PAPD_UAM_AUTH_H 1
-
-#include <sys/cdefs.h>
-#include <pwd.h>
-
-#include <atalk/uam.h>
-
-#include "file.h"
-
-struct uam_mod {
-  void *uam_module;
-  struct uam_export *uam_fcn;
-  struct uam_mod *uam_prev, *uam_next;
-};
-
-struct uam_obj {
-  const char *uam_name; /* authentication method */
-  char *uam_path; /* where it's located */
-  int uam_count;
-  union {
-    struct {
-      int (*login) (void *, struct passwd **, 
-                       char *, int, char *, int *);
-      int (*logincont) (void *, struct passwd **, char *,
-                           int, char *, int *);
-      void (*logout) (void);
-    } uam_login;
-    int (*uam_changepw) (void *, char *, struct passwd *, char *,
-                            int, char *, int *);
-    int (*uam_printer) (char *, char *, char *, struct papfile *);
-  } u;
-  struct uam_obj *uam_prev, *uam_next;
-};
-
-#define uam_attach(a, b) do { \
-    (a)->uam_prev->uam_next = (b); \
-    (b)->uam_prev = (a)->uam_prev; \
-    (b)->uam_next = (a); \
-    (a)->uam_prev = (b); \
-} while (0)                                 
-
-#define uam_detach(a) do { \
-    (a)->uam_prev->uam_next = (a)->uam_next; \
-    (a)->uam_next->uam_prev = (a)->uam_prev; \
-} while (0)
-
-#define UAM_LIST(type) (((type) == UAM_SERVER_LOGIN) ? &uam_login : \
-                (((type) == UAM_SERVER_CHANGEPW) ? &uam_changepw : \
-                (((type) == UAM_SERVER_PRINTAUTH) ? &uam_printer : NULL)))
-
-
-extern struct uam_mod *uam_load (const char *, const char *);
-extern void uam_unload (struct uam_mod *);
-
-/* auth.c */
-int auth_load (const char *, const char *);
-int auth_register (const int, struct uam_obj *);
-#define auth_unregister(a) uam_detach(a)
-struct uam_obj *auth_uamfind (const int, const char *, const int);
-void auth_unload (void);
-int getuamnames (const int, char *);
-
-#endif /* uam_auth.h */
diff --git a/etc/psf/.gitignore b/etc/psf/.gitignore
deleted file mode 100644 (file)
index 5138d27..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Makefile
-Makefile.in
-psf
-psa
-.deps
-.libs
-.gitignore
-psa.o psf.o
diff --git a/etc/psf/Makefile.am b/etc/psf/Makefile.am
deleted file mode 100644 (file)
index 8cb795a..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-# Makefile.am for etc/psf/
-
-libexec_PROGRAMS = psf psa
-libexec_SCRIPTS = etc2ps.sh
-
-pkgdata_DATA = pagecount.ps
-
-psf_SOURCES = psf.c
-psa_SOURCES = psa.c
-
-AM_CFLAGS = -DZEROWIDTH \
-       -D_PATH_PAP=\"$(bindir)/pap\" \
-       -D_PATH_PSORDER=\"$(bindir)/psorder\" \
-       -D_PATH_PSA=\"$(libexecdir)/psa\" \
-       -D_PATH_PSFILTER=\"$(libexecdir)/etc2ps.sh\" \
-       -D_PATH_PAGECOUNT=\"$(pkgdatadir)/pagecount.ps\"
-
-EXTRA_DIST = $(libexec_SCRIPTS) $(pkgdata_DATA)
-
-# declare links
-psf_LINKS = ofpap ifpap tfpap ifpaprev tfpaprev ofwpap ifwpap \
-        tfwpap ifwpaprev tfwpaprev ofmpap ifmpap tfmpap ifmpaprev \
-        tfmpaprev ofwmpap ifwmpap tfwmpap ifwmpaprev tfwmpaprev
-
-
-#
-# install sections for links
-#
-
-install-exec-hook:
-       @list='$(psf_LINKS)'; for l in $$list; do \
-               rm $(DESTDIR)$(libexecdir)/$$l 2>/dev/null || true; \
-               (cd $(DESTDIR)$(libexecdir) && $(LN_S) psf $$l);  \
-       done
-
-#
-# uninstall sections for links
-#
-
-uninstall-hook:
-       @list='$(psf_LINKS)'; for l in $$list; do \
-               rm -f $(DESTDIR)$(libexecdir)/$$l; \
-       done
-
-#
-# cleanup
-#
-
-CLEANFILES = $(psf_LINKS)
diff --git a/etc/psf/etc2ps.sh b/etc/psf/etc2ps.sh
deleted file mode 100644 (file)
index 3f1637b..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/bin/sh
-#
-# This filter is called by psf to convert "other" formats to PostScript.
-# psf handles text and PostScript native.  "Other" formats, e.g. DVI, C/A/T,
-# need to be converted before the page reverser and the printer can use
-# them.
-#
-# $0 begins with the filter name, e.g. df, tf.  Each format is a separate
-# tag in the case.
-#
-
-DVIPSPATH=/usr/local/tex/bin
-DVIPS=/usr/local/tex/bin/dvips
-DVIPSARGS="-f -q"
-
-TROFF2PS=/usr/local/psroff/troff2/troff2ps
-TROFF2PSARGS="-Z -O-.10"
-
-PATH=/usr/bin:$DVIPSPATH; export PATH
-
-case $1 in
-
-#
-# Use "dvips" by Radical Eye Software to convert TeX DVI files to PostScript.
-# Note that you *must* have METAFONT, etc, in your path.
-#
-df*)
-    if [ -x "$DVIPS" ]; then
-       TEMPFILE=`mktemp -t psfilter.XXXXXX` || exit 1
-       cat > $TEMPFILE
-       $DVIPS $DVIPSARGS < $TEMPFILE
-       rm -f $TEMPFILE
-    else
-       echo "$0: filter dvips uninstalled" 1>&2
-       exit 2
-    fi
-    ;;
-
-#
-# troff2ps is from psroff by Chris Lewis.
-#
-tf*)
-    if [ -x "$TROFF2PS" ]; then
-       exec $TROFF2PS $TROFF2PSARGS
-    else
-       echo "$0: filter troff2ps uninstalled" 1>&2
-       exit 2
-    fi
-    ;;
-
-*)
-    echo "$0: filter $1 unavailable" 1>&2
-    exit 2
-    ;;
-esac
-
-exit 0
diff --git a/etc/psf/pagecount.ps b/etc/psf/pagecount.ps
deleted file mode 100644 (file)
index fe650e1..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-%!PS-Adobe-3.0 Query
-%%?BeginQuery: PageCount
-statusdict begin pagecount (*) print = flush end
-%%?EndQuery: Unknown
-%%EOF
diff --git a/etc/psf/psa.c b/etc/psf/psa.c
deleted file mode 100644 (file)
index 2606a7c..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * $Id: psa.c,v 1.5 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1995 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * PostScript Accounting, psa.
- *
- * psa is invoked by psf, as output for a communication program.  The
- * communication program is expected to send a small program before and
- * after each job, which causes the page count to be emitted in a well
- * known format.  psa reads its input, looking for page counts and other
- * interesting data.  Any data that it doesn't understand, it emits to
- * stderr, the lpd log file.  Data that it does understand may be written
- * to a status file or logged.  Once all input has been received, psa
- * subtracts the beginning and end page counts, and log an accounting
- * record in the accounting file.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-int main( int ac, char **av)
-{
-    FILE       *af;
-    char       *acc, *user, *host;
-    char       buf[ 1024 ], *p, *end;
-    int                cc, n, ipc = -1, fpc = -1;
-
-    if ( ac != 4 ) {
-       fprintf( stderr, "Usage:\t%s accounting-file user host\n", av[ 0 ] );
-       exit( 2 );
-    }
-
-    acc = av[ 1 ];
-    user = av[ 2 ];
-    host = av[ 3 ];
-
-    /*
-     * Explain n = !n ...  Is there no beauty in truth?
-     */
-    while (( cc = read( 0, buf, sizeof( buf ))) > 0 ) {
-       if ( ipc < 0 && *buf == '*' ) {
-           /* find initial pagecount */
-           for ( p = buf, end = buf + cc; p < end; p++ ) {
-               if ( *p == '\n' || *p == '\r' ) {
-                   break;
-               }
-           }
-           if ( p == end ) {
-               fprintf( stderr, "Can't find initial page count!\n" );
-               exit( 2 );
-           }
-
-           p++;
-           ipc = atoi( buf + 1 );
-           cc -= ( p - buf );
-           if ( cc != 0 ) {
-               bcopy( p, buf, cc );
-           }
-       } else {
-           /* find final pagecount */
-           for ( p = buf + cc - 1; p >= buf; p-- ) {
-               if ( *p != '\n' && *p != '\r' ) {
-                   break;
-               }
-           }
-           if ( p < buf ) {
-               fprintf( stderr, "Can't find final page count!\n" );
-               exit( 2 );
-           }
-
-           for ( ; p >= buf; p-- ) {
-               if ( *p == '\n' || *p == '\r' ) {
-                   break;
-               }
-           }
-
-           if ( p < buf ) {
-               p = buf;
-           } else {
-               cc -= p - buf;
-               p++;
-           }
-
-           if ( *p == '*' ) {
-               n = atoi( p + 1 );
-#define max(x,y)       ((x)>(y)?(x):(y))
-               fpc = max( n, fpc );
-           }
-       }
-       if ( cc != 0 && write( 2, buf, cc ) != cc ) {
-           fprintf( stderr, "write 1: 2 %p %d\n", buf, cc );
-           perror( "write" );
-           exit( 2 );
-       }
-    }
-    if ( cc < 0 ) {
-       perror( "read" );
-       exit( 2 );
-    }
-
-    if ( ipc < 0 ) {
-       fprintf( stderr, "Didn't find initial page count!\n" );
-       exit( 2 );
-    }
-
-    if ( fpc < 0 ) {
-       fprintf( stderr, "Didn't find final page count!\n" );
-       exit( 2 );
-    }
-
-    /*
-     * Write accounting record.
-     */
-    if (( af = fopen( acc, "a" )) != NULL ) {
-       fprintf( af, "%7.2f\t%s:%s\n", (float)( fpc - ipc ), host, user );
-    } else {
-       perror( acc );
-       exit( 2 );
-    }
-
-    exit( 0 );
-}
diff --git a/etc/psf/psf.c b/etc/psf/psf.c
deleted file mode 100644 (file)
index 535daee..0000000
+++ /dev/null
@@ -1,730 +0,0 @@
-/*
- * $Id: psf.c,v 1.13 2009-10-16 01:50:50 didg Exp $
- *
- * Copyright (c) 1990,1995 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * PostScript Filter, psf.
- *
- * Handles both PostScript files and text files.  Files with the
- * '%!' PostScript header are sent directly to the printer,
- * unmodified.  Text files are first converted to PostScript,
- * then sent.  Printers may be directly attached or on an AppleTalk
- * network.  Other media are possible.  Currently, psf invokes
- * pap to send files to AppleTalk-ed printers.  Replace the pap*
- * variables to use another program for communication.  psf only
- * converts plain-text.  If called as "tf" or "df", psf will invoke
- * a troff or dvi to PostScript converter.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#define FUCKED
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <sys/time.h>
-
-/* POSIX.1 sys/wait.h check */
-#include <sys/types.h>
-#ifdef HAVE_SYS_WAIT_H
-#include <sys/wait.h>
-#endif /* HAVE_SYS_WAIT_H */
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
-#endif /* ! WEXITSTATUS */
-#ifndef WIFEXITED
-#define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
-#endif /* ! WIFEXITED */
-
-#include <sys/file.h>
-#include <syslog.h>
-#include <atalk/paths.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <signal.h>
-#include <errno.h>
-
-/* Forward Declarations */
-int pexecv(char *path, char *argv[]);
-int copyio();
-int textps();
-
-static char            psapath[] = _PATH_PSA;
-static char            *psaargv[] = { "psa", NULL, NULL, NULL, NULL };
-
-/*
- * If we're not doing accounting, we just call pap as below.
- * If we are doing accounting, we call pap twice.  The first time,
- * we call it with "-E" in arg 2, pagecount.ps in arg 3, and "-" in
- * arg 4.  The second time, we call it with "-c" in arg 2, pagecount.ps
- * in arg 3, and 0 in arg 4.
- */
-static char            pappath[] = _PATH_PAP;
-static char            *papargv[] = { "pap", "-sstatus", NULL, NULL, NULL, NULL, NULL, NULL };
-
-static char            revpath[] = _PATH_PSORDER;
-static char            *revargv[] = { "psorder", "-d", NULL };
-
-static char            *filtargv[] = { NULL, NULL, NULL };
-
-static char            inbuf[ 1024 * 8 ];
-static int             inlen;
-
-static int             literal;
-static int             width = 80, length = 66, indent = 0;
-static char            *prog, *name, *host;
-
-static struct papersize {
-    int                width;
-    int                length;
-   float       win;
-    float      lin;
-} papersizes[] = {
-    { 80, 66, 8.5, 11.0 },                     /* US Letter */
-    { 80, 70, 8.27, 11.69 },                   /* A4 */
-};
-
-int main( int ac, char **av)
-{
-    int                        c, rc, children = 0;
-#ifdef FUCKED
-    int                        psafileno = 0, multiconn = 0, waitidle = 0, waitidle2 = 0;
-#endif /* FUCKED */
-    int                        status;
-    extern char                *optarg;
-    extern int         optind, opterr;
-
-    opterr = 0;
-    if (( prog = rindex( av[ 0 ], '/' )) == NULL ) {
-       prog = av[ 0 ];
-    } else {
-       prog++;
-    }
-#ifdef ultrix
-    openlog( prog, LOG_PID );
-#else /* ultrix */
-    openlog( prog, LOG_PID, LOG_LPR );
-#endif /* ultrix */
-
-    while (( c = getopt( ac, av, "P:C:D:F:L:J:x:y:n:h:w:l:i:c" )) != EOF ) {
-       switch ( c ) {
-       case 'n' :
-           name = optarg;
-           break;
-
-       case 'h' :
-           host = optarg;
-           break;
-
-       case 'w' :
-           width = atoi( optarg );
-#ifdef ZEROWIDTH
-           /*
-            * Some version of lpd pass 0 for the page width.
-            */
-           if ( width == 0 ) {
-               width = 80;
-           }
-#endif /* ZEROWIDTH */
-           break;
-
-       case 'l' :
-           length = atoi( optarg );
-           break;
-
-       case 'i' :
-           indent = atoi( optarg );
-           break;
-
-       case 'c' :      /* Print control chars */
-           literal++;
-           break;
-
-       case 'F' :
-       case 'L' :
-       case 'J' :
-       case 'P' :
-       case 'x' :
-       case 'y' :
-           break;
-       
-#ifdef notdef
-       default :
-           syslog( LOG_ERR, "bad option: %c", c );
-           exit( 2 );
-#endif /* notdef */
-       }
-    }
-    if ( ac - optind > 1 ) {
-       syslog( LOG_ERR, "Too many arguments" );
-       exit( 2 );
-    }
-#ifdef FUCKED
-    if ( index( prog, 'w' )) {
-       waitidle++;
-    }
-    if ( index( prog, 'W' )) {
-       waitidle2++;
-    }
-    if ( index( prog, 'm' )) {
-       multiconn++;
-    }
-#endif /* FUCKED */
-
-    syslog( LOG_INFO, "starting for %s", name ? name : "?" );
-
-restart:
-    if (( inlen = read( 0, inbuf, sizeof( inbuf ))) < 0 ) {
-       syslog( LOG_ERR, "read: %s", strerror(errno) );
-       exit( 1 );
-    }
-    if ( inlen == 0 ) {        /* nothing to be done */
-       syslog( LOG_INFO, "done" );
-       exit( 0 );
-    }
-
-    /*
-     * If we've been given an accounting file, start the accounting
-     * process.
-     */
-    if ( optind < ac ) {
-       /* build arguments */
-       psaargv[ 1 ] = av[ optind ];
-       psaargv[ 2 ] = name;
-       psaargv[ 3 ] = host;
-       if (( c = pexecv( psapath, psaargv )) < 0 ) {
-           syslog( LOG_ERR, "%s: %s", psapath, strerror(errno) );
-           exit( 2 );
-       }
-       children++;
-       syslog( LOG_INFO, "accounting with psa[%d]", c );
-    }
-
-    /*
-     * Check prog's name to decide what programs to execute.
-     */
-    if ( strstr( prog, "pap" ) != NULL ) {
-       if ( optind < ac ) {    /* accounting */
-#ifdef FUCKED
-           if ( multiconn ) {
-               psafileno = getdtablesize();
-               psafileno--;
-               dup2( 1, psafileno );
-
-               if ( waitidle2 ) {
-                   papargv[ 2 ] = "-W";
-                   papargv[ 3 ] = "-c";
-                   papargv[ 4 ] = "-E";
-                   papargv[ 5 ] = _PATH_PAGECOUNT;
-                   papargv[ 6 ] = "-";
-                   papargv[ 7 ] = NULL;
-               } else if ( waitidle ) {
-                   papargv[ 2 ] = "-w";
-                   papargv[ 3 ] = "-c";
-                   papargv[ 4 ] = "-E";
-                   papargv[ 5 ] = _PATH_PAGECOUNT;
-                   papargv[ 6 ] = "-";
-                   papargv[ 7 ] = NULL;
-               } else {
-                   papargv[ 2 ] = "-c";
-                   papargv[ 3 ] = "-E";
-                   papargv[ 4 ] = _PATH_PAGECOUNT;
-                   papargv[ 5 ] = "-";
-                   papargv[ 6 ] = NULL;
-               }
-           } else {
-               /*
-                * This is how it should be done.
-                */
-               papargv[ 2 ] = "-c";
-               papargv[ 3 ] = _PATH_PAGECOUNT;
-               papargv[ 4 ] = "-";
-               papargv[ 5 ] = _PATH_PAGECOUNT;
-               papargv[ 6 ] = NULL;
-           }
-#endif /* FUCKED */
-       } else {
-           papargv[ 2 ] = "-c";
-           papargv[ 3 ] = "-E";
-           papargv[ 4 ] = NULL;
-       }
-
-       if (( c = pexecv( pappath, papargv )) < 0 ) {
-           syslog( LOG_ERR, "%s: %s", pappath, strerror(errno) );
-           exit( 2 );
-       }
-       children++;
-       syslog( LOG_INFO, "sending to pap[%d]", c );
-    }
-
-    /*
-     * Might be a good idea to have both a "forw" and a "rev", so that
-     * reversed documents can be reordered for the printing device.
-     */
-    if ( strstr( prog, "rev" ) != NULL ) {
-       if (( c = pexecv( revpath, revargv )) < 0 ) {
-           syslog( LOG_ERR, "%s: %s", revpath, strerror(errno) );
-           exit( 2 );
-       }
-       syslog( LOG_INFO, "sending to rev[%d]", c );
-       children++;
-    }
-
-    /*
-     * Invoke an external (script) filter to produce PostScript from
-     * non-text input.
-     */
-    if ( *prog != 'i' && *prog != 'o' && *( prog + 1 ) == 'f' ) {
-       filtargv[ 0 ] = filtargv[ 1 ] = prog;
-       if (( c = pexecv( _PATH_PSFILTER, filtargv )) < 0 ) {
-           syslog( LOG_ERR, "%s: %s", _PATH_PSFILTER, strerror(errno) );
-           exit( 2 );
-       }
-       syslog( LOG_INFO, "external filter[%d]", c );
-       children++;
-       rc = copyio();          /* external filter */
-    } else {
-       if ( inlen >= 2 && inbuf[ 0 ] == '%' && inbuf[ 1 ] == '!' ) {
-           syslog( LOG_INFO, "PostScript" );
-           rc = copyio();      /* PostScript */
-       } else if ( inlen >= 2 && inbuf[ 0 ] == '\033' && inbuf[ 1 ] == '%' ) {
-           syslog( LOG_INFO, "PostScript w/PJL" );
-           rc = copyio();      /* PostScript */
-       } else {
-           syslog( LOG_INFO, "straight text" );
-           rc = textps();      /* straight text */
-       }
-    }
-
-#ifdef FUCKED
-    if ( strstr( prog, "pap" ) != NULL && optind < ac && multiconn ) {
-       dup2( psafileno, 1 );
-       close( psafileno );
-       papargv[ 2 ] = "-c";
-       if ( waitidle2 ) {
-           papargv[ 3 ] = "-W";
-           papargv[ 4 ] = _PATH_PAGECOUNT;
-           papargv[ 5 ] = NULL;
-       } else if ( waitidle ) {
-           papargv[ 3 ] = "-w";
-           papargv[ 4 ] = _PATH_PAGECOUNT;
-           papargv[ 5 ] = NULL;
-       } else {
-           papargv[ 3 ] = _PATH_PAGECOUNT;
-           papargv[ 4 ] = NULL;
-       }
-
-       if (( c = pexecv( pappath, papargv )) < 0 ) {
-           syslog( LOG_ERR, "%s: %s", pappath, strerror(errno) );
-           exit( 2 );
-       }
-       children++;
-       syslog( LOG_INFO, "pagecount with pap[%d]", c );
-    }
-#endif /* FUCKED */
-
-    if ( children ) {
-       close( 1 );
-    }
-    while ( children ) {
-       if (( c = wait3( &status, 0, NULL )) < 0 ) {
-           syslog( LOG_ERR, "wait3: %s", strerror(errno) );
-           exit( 1 );
-       }
-       if ( WIFEXITED( status )) {
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(x) ((x).w_status)
-#endif /* WEXITSTATUS */
-           if ( WEXITSTATUS( status ) != 0 ) {
-               syslog( LOG_ERR, "%d died with %d", c, WEXITSTATUS( status ));
-               exit( WEXITSTATUS( status ));
-           } else {
-               syslog( LOG_INFO, "%d done", c );
-               children--;
-           }
-       } else {
-           syslog( LOG_ERR, "%d died badly", c );
-           exit( 1 );
-       }
-    }
-
-    if ( rc == 3 ) {
-       syslog( LOG_INFO, "pausing" );
-       kill( getpid(), SIGSTOP );
-       syslog( LOG_INFO, "restarting" );
-       goto restart;
-    }
-
-    syslog( LOG_INFO, "done" );
-    exit( rc );
-}
-
-int copyio(void)
-{
-    /* implement the FSM needed to do the suspend. Note that
-     * the last characters will be \031\001 so don't worry
-     * Fun things: 1. \031\001 should not be written to output device
-     *  2. The \031 can be last char of one read, \001 first of next
-     *      - we need to write \031 if not followed by \001
-     */
-    struct timeval     tv;
-    fd_set             fdset;
-    int                        ctl = 0;
-
-notdone:
-    do {
-       /*
-        * First, \031 and \001 *must* be the last things in the buffer
-        * (\001 can be the first thing in the next buffer).  There's no
-        * need to scan any of the intervening bytes.  Second, if there's
-        * more input, the escape sequence was bogus, and we should keep
-        * reading.
-        */
-       if ( inlen == 1 ) {
-           if ( ctl == 1 ) {
-               if ( inbuf[ 0 ] == '\001' ) {
-                   ctl = 2;
-                   break;
-               }
-               if ( write( 1, "\031", 1 ) != 1 ) {
-                   syslog( LOG_ERR, "write: %s", strerror(errno) );
-                   return( 1 );
-               }
-               ctl = 0;
-           }
-
-           if ( inbuf[ 0 ] == '\031' ) {
-               ctl = 1;
-           }
-
-       } else {
-           if ( ctl == 1 ) {
-               if ( write( 1, "\031", 1 ) != 1 ) {
-                   syslog( LOG_ERR, "write: %s", strerror(errno) );
-                   return( 1 );
-               }
-           }
-           ctl = 0;
-           if ( inbuf[ inlen - 2 ] == '\031' &&
-                   inbuf[ inlen - 1 ] == '\001' ) {
-               ctl = 2;
-           } else if ( inbuf[ inlen - 1 ] == '\031' ) {
-               ctl = 1;
-           }
-       }
-
-       inlen -= ctl;
-       if (( inlen > 0 ) && ( write( 1, inbuf, inlen ) != inlen )) {
-           syslog( LOG_ERR, "write: %s", strerror(errno) );
-           return( 1 );
-       }
-       if ( ctl == 2 ) {
-           break;
-       }
-    } while (( inlen = read( 0, inbuf, sizeof( inbuf ))) > 0 );
-
-    if ( ctl == 2 ) {
-       tv.tv_sec = 2;
-       tv.tv_usec = 0;
-       FD_ZERO( &fdset );
-       FD_SET( 0, &fdset );
-       if ( select( 1, &fdset, NULL, NULL, &tv ) != 0 ) {
-           if (( inlen = read( 0, inbuf, sizeof( inbuf ))) > 0 ) {
-               goto notdone;
-           }
-       }
-    }
-
-    if ( inlen < 0 ) {
-       syslog( LOG_ERR, "read: %s", strerror(errno) );
-       return( 1 );
-    }
-
-    if ( ctl == 1 ) {
-       if ( write( 1, "\031", 1 ) != 1 ) {
-           syslog( LOG_ERR, "write: %s", strerror(errno) );
-           return( 1 );
-       }
-    } else if ( ctl == 2 ) {
-       return( 3 );
-    }
-    return( 0 );
-}
-
-static char            *font = "Courier";
-static int             point = 11;
-
-static char            pspro[] = "\
-/GSV save def                                          % global VM\n\
-/SP {\n\
-       /SV save def                                    % save vmstate\n\
-       dup /H exch def                                 % save font height\n\
-       exch findfont exch scalefont setfont            % select font\n\
-       ( ) stringwidth pop /W exch def                 % save font width\n\
-       0.5 sub 72 mul /CY exch def                     % save start Y\n\
-       pop 0.5 add 72 mul /CX exch def                 % save start X\n\
-       CX CY moveto                                    % make current point\n\
-} bind def\n\
-/S /show load def\n\
-/NL { CX CY H sub dup /CY exch def moveto } bind def\n\
-/CR { CX CY moveto } bind def\n\
-/B { W neg 0 rmoveto}bind def\n\
-/T { W mul 0 rmoveto}bind def\n\
-/EP { SV restore showpage } bind def\n\
-%%EndProlog\n";
-
-int textps(void)
-{
-    struct papersize   papersize;
-    int                        state = 0, line = 0, col = 0, npages = 0, rc;
-    unsigned int       i;
-    char               *p, *end;
-
-#define elements(x)    (sizeof(x)/sizeof((x)[0]))
-    for ( i = 0; i < elements( papersizes ); i++ ) {
-       if ( width == papersizes[ 0 ].width &&
-               length == papersizes[ 0 ].length ) {
-           papersize = papersizes[ i ];
-           break;
-       }
-    }
-    if ( i >= elements( papersizes )) {
-       papersize = papersizes[ 0 ];            /* default */
-    }
-
-#define ST_AVAIL               (1<<0)
-#define ST_CONTROL             (1<<1)
-#define ST_PAGE                        (1<<2)
-    /*
-     * convert text lines to postscript.
-     * A grungy little state machine. If I was more creative, I could
-     * probably think of a better way of doing this...
-     */
-    do {
-       p = inbuf;
-       end = inbuf + inlen;
-       while ( p < end ) {
-           if (( state & ST_PAGE ) == 0 && *p != '\031' && *p != '\001' ) {
-               if ( npages == 0 ) {
-                   printf( "%%!PS-Adobe-2.0\n%%%%Pages: (atend)\n" );
-                   printf( "%%%%DocumentFonts: %s\n", font );
-                   fflush( stdout );
-
-                   /* output postscript prologue: */
-                   if ( write( 1, pspro, sizeof( pspro ) - 1 ) !=
-                           sizeof( pspro ) - 1 ) {
-                       syslog( LOG_ERR, "write prologue: %s", strerror(errno) );
-                       return( 1 );
-                   }
-                   if ( name && host ) {
-                       printf( "statusdict /jobname (%s@%s) put\n", name,
-                               host );
-                   }
-               }
-
-               printf( "%%%%Page: ? %d\n", ++npages );
-               printf( "%d %f %f /%s %d SP\n", indent,
-                       papersize.win, papersize.lin, font, point );
-               state |= ST_PAGE;
-           }
-           if ( state & ST_CONTROL && *p != '\001' ) {
-               /* It is a very bad thing to toss a job because it contains
-                * unprintable characters.  Instead, we will convert them to
-                * question marks.  This is adapted from a solution described
-                * by Werner Eugster <eugster@giub.unibe.ch> on his ApplePrint
-                * webpage (http://www.giub.unibe.ch/~eugster/appleprint.html).
-                *
-                * Note that this is rather ugly code.  The same change is
-                * applied identically at two different locations in this file.
-                * It would be better someday to combine the two.
-                */
-               if ( !literal ) {
-                       fprintf( stderr,
-                               "unprintable character (0x%x) converted to ?!\n",
-                               (unsigned char)*p );
-                       putchar( '?' ); /* Replace unprintable char with a question mark. */
-               } else {
-                       printf( "\\%o", (unsigned char)031 );
-               }
-               state &= ~ST_CONTROL;
-               col++;
-           }
-
-           switch ( *p ) {
-           case '\n' :         /* end of line */
-               if ( state & ST_AVAIL ) {
-                   printf( ")S\n" );
-                   state &= ~ST_AVAIL;
-               }
-               printf( "NL\n" );
-               line++;
-               col = 0;
-               if ( line >= length ) {
-                   printf( "EP\n" );
-                   state &= ~ST_PAGE;
-                   line = 0;
-               }
-               break;
-
-           case '\r' :         /* carriage return (for overtyping) */
-               if ( state & ST_AVAIL ) {
-                   printf( ")S CR\n" );
-                   state &= ~ST_AVAIL;
-               }
-               col = 0;
-               break;
-
-           case '\f' :         /* form feed */
-               if ( state & ST_AVAIL ) {
-                   printf( ")S\n" );
-                   state &= ~ST_AVAIL;
-               }
-               printf( "EP\n" );
-               state &= ~ST_PAGE;
-               line = 0;
-               col = 0;
-               break;
-
-           case '\b' :         /* backspace */
-               /* show line, back up one character */
-               if ( state & ST_AVAIL ) {
-                   printf( ")S\n" );
-                   state &= ~ST_AVAIL;
-               }
-               printf( "B\n" );
-               col--;
-               break;
-
-           case '\t' :         /* tab */
-               if ( state & ST_AVAIL ) {
-                   printf( ")S\n" );
-                   state &= ~ST_AVAIL;
-               }
-               printf( "%d T\n", 8 - ( col % 8 ));
-               col += 8 - ( col % 8 );
-               break;
-
-           /*
-            * beginning of lpr control sequence
-            */
-           case '\031' :
-               state |= ST_CONTROL;
-               break;
-
-           case '\001' :       /* lpr control sequence */
-               if ( state & ST_CONTROL ) {
-                   rc = 3;
-                   goto out;
-               }
-               /* FALLTHROUGH */
-
-           case '\\' :
-           case ')' :
-           case '(' :
-               if (( state & ST_AVAIL ) == 0 ) {
-                   printf( "(" );
-                   state |= ST_AVAIL;
-               }
-               putchar( '\\' );
-               /* FALLTHROUGH */
-
-           default :
-               if (( state & ST_AVAIL ) == 0 ) {
-                   printf( "(" );
-                   state |= ST_AVAIL;
-               }
-               if ( !isascii( *p ) || !isprint( *p )) {
-                   if ( !literal ) {
-                        fprintf( stderr,
-                           "unprintable character (0x%x) converted to ?!\n",
-                           (unsigned char)*p );
-                       putchar( '?' ); /* Replace unprintable char with a question mark. */
-                   } else {
-                       printf( "\\%o", (unsigned char)*p );
-                   }
-               } else {
-                   putchar( *p );
-               }
-               col++;
-               break;
-           }
-       p++;
-       }
-    } while (( inlen = read( 0, inbuf, sizeof( inbuf ))) > 0 );
-    if ( inlen < 0 ) {
-       syslog( LOG_ERR, "read: %s", strerror(errno) );
-       return( 1 );
-    }
-    rc = 0;
-
-out:
-    if ( state & ST_AVAIL ) {
-       printf( ")S\n" );
-       state &= ~ST_AVAIL;
-    }
-
-    if ( state & ST_PAGE ) {
-       printf( "EP\n" );
-       state &= ~ST_PAGE;
-    }
-
-    if ( npages > 0 ) {
-       printf( "%%%%Trailer\nGSV restore\n%%%%Pages: %d\n%%%%EOF\n", npages );
-       fflush( stdout );
-    }
-
-    return( rc );
-}
-
-/*
- * Interface to pipe and exec, for starting children in pipelines.
- *
- * Manipulates file descriptors 0, 1, and 2, such that the new child
- * is reading from the parent's output.
- */
-int pexecv( char *path, char *argv[])
-{
-    int                fd[ 2 ], c;
-
-    if ( pipe( fd ) < 0 ) {
-       return( -1 );
-    }
-
-    switch ( c = fork()) {
-    case -1 :
-       return( -1 );
-       /* NOTREACHED */
-
-    case 0 :
-       if ( close( fd[ 1 ] ) < 0 ) {
-           return( -1 );
-       }
-       if ( dup2( fd[ 0 ], 0 ) < 0 ) {
-           return( -1 );
-       }
-       if ( close( fd[ 0 ] ) < 0 ) {
-           return( -1 );
-       }
-       execv( path, argv );
-       return( -1 );
-       /* NOTREACHED */
-
-    default :
-       if ( close( fd[ 0 ] ) < 0 ) {
-           return( -1 );
-       }
-       if ( dup2( fd[ 1 ], 1 ) < 0 ) {
-           return( -1 );
-       }
-       if ( close( fd[ 1 ] ) < 0 ) {
-           return( -1 );
-       }
-       return( c );
-    }
-}
index 3155777fe9d202f37548efe7298953e0410a281a..3a02b8359770be9f64fdd0b2cf560fa7831817f4 100644 (file)
@@ -1,7 +1,5 @@
 # Makefile.am for etc/uams/
 
-SUBDIRS = uams_krb4
-
 #
 # conditionally build some modules
 #
index 4c66a8732771f0a1803e285e0d726a8733ca9e64..0f0c8a535329b579bac63659a88b41194f481b59 100644 (file)
@@ -46,7 +46,7 @@ static gcry_mpi_t p, g, Ra;
 static gcry_mpi_t serverNonce;
 static char *K_MD5hash = NULL;
 static int K_hash_len;
-static u_int16_t ID;
+static uint16_t ID;
 
 /* The initialization vectors for CAST128 are fixed by Apple. */
 static unsigned char dhx_c2siv[] = { 'L', 'W', 'a', 'l', 'l', 'a', 'c', 'e' };
@@ -267,7 +267,7 @@ static int dhx2_setup(void *obj, char *ibuf _U_, size_t ibuflen _U_,
 
     /* Session ID first */
     ID = dhxhash(obj);
-    *(u_int16_t *)rbuf = htons(ID);
+    *(uint16_t *)rbuf = htons(ID);
     rbuf += 2;
     *rbuflen += 2;
 
@@ -281,7 +281,7 @@ static int dhx2_setup(void *obj, char *ibuf _U_, size_t ibuflen _U_,
     *rbuflen += 4;
 
     /* len = length of p = PRIMEBITS/8 */
-    *(u_int16_t *)rbuf = htons((u_int16_t) PRIMEBITS/8);
+    *(uint16_t *)rbuf = htons((uint16_t) PRIMEBITS/8);
     rbuf += 2;
     *rbuflen += 2;
 
@@ -365,7 +365,7 @@ static int pam_login_ext(void *obj, char *uname, struct passwd **uam_pwd,
 {
     char *username;
     size_t len, ulen;
-    u_int16_t  temp16;
+    uint16_t  temp16;
 
     *rbuflen = 0;
 
@@ -488,7 +488,7 @@ static int logincont1(void *obj _U_, char *ibuf, size_t ibuflen, char *rbuf, siz
     /* ---- Start building reply packet ---- */
 
     /* Session ID + 1 first */
-    *(u_int16_t *)rbuf = htons(ID+1);
+    *(uint16_t *)rbuf = htons(ID+1);
     rbuf += 2;
     *rbuflen += 2;
 
@@ -714,11 +714,11 @@ static int pam_logincont(void *obj, struct passwd **uam_pwd,
                          char *ibuf, size_t ibuflen,
                          char *rbuf, size_t *rbuflen)
 {
-    u_int16_t retID;
+    uint16_t retID;
     int ret;
 
     /* check for session id */
-    retID = ntohs(*(u_int16_t *)ibuf);
+    retID = ntohs(*(uint16_t *)ibuf);
     if (retID == ID)
         ret = logincont1(obj, ibuf, ibuflen, rbuf, rbuflen);
     else if (retID == ID+1)
index 1392f0a75edfc2d513a3c65365795625cd0c0fb0..8d31b9f845b3502eb4935d38a0df5cf6635cfac2 100644 (file)
 #include <string.h>
 #include <errno.h>
 #include <pwd.h>
-
-#ifdef HAVE_UNISTD_H
+#include <arpa/inet.h>
 #include <unistd.h>
-#endif
 
 #ifdef HAVE_CRYPT_H
 #include <crypt.h>
 #endif
 
-#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
-#endif
-
-#ifdef HAVE_TIME_H
 #include <time.h>
-#endif
 
 #ifdef SHADOWPW
 #include <shadow.h>
@@ -60,7 +53,7 @@ static gcry_mpi_t p, Ra;
 static gcry_mpi_t serverNonce;
 static char *K_MD5hash = NULL;
 static int K_hash_len;
-static u_int16_t ID;
+static uint16_t ID;
 
 /* The initialization vectors for CAST128 are fixed by Apple. */
 static unsigned char dhx_c2siv[] = { 'L', 'W', 'a', 'l', 'l', 'a', 'c', 'e' };
@@ -216,7 +209,7 @@ static int dhx2_setup(void *obj, char *ibuf _U_, size_t ibuflen _U_,
 
     /* Session ID first */
     ID = dhxhash(obj);
-    *(u_int16_t *)rbuf = htons(ID);
+    *(uint16_t *)rbuf = htons(ID);
     rbuf += 2;
     *rbuflen += 2;
 
@@ -230,7 +223,7 @@ static int dhx2_setup(void *obj, char *ibuf _U_, size_t ibuflen _U_,
     *rbuflen += 4;
 
     /* len = length of p = PRIMEBITS/8 */
-    *(u_int16_t *)rbuf = htons((u_int16_t) PRIMEBITS/8);
+    *(uint16_t *)rbuf = htons((uint16_t) PRIMEBITS/8);
     rbuf += 2;
     *rbuflen += 2;
 
@@ -314,7 +307,7 @@ static int passwd_login_ext(void *obj, char *uname, struct passwd **uam_pwd,
 {
     char *username;
     size_t len, ulen;
-    u_int16_t  temp16;
+    uint16_t  temp16;
 
     *rbuflen = 0;
 
@@ -442,7 +435,7 @@ static int logincont1(void *obj _U_, struct passwd **uam_pwd _U_,
     /* ---- Start building reply packet ---- */
 
     /* Session ID + 1 first */
-    *(u_int16_t *)rbuf = htons(ID+1);
+    *(uint16_t *)rbuf = htons(ID+1);
     rbuf += 2;
     *rbuflen += 2;
 
@@ -589,11 +582,11 @@ static int passwd_logincont(void *obj, struct passwd **uam_pwd,
                             char *ibuf, size_t ibuflen,
                             char *rbuf, size_t *rbuflen)
 {
-    u_int16_t retID;
+    uint16_t retID;
     int ret;
 
     /* check for session id */
-    retID = ntohs(*(u_int16_t *)ibuf);
+    retID = ntohs(*(uint16_t *)ibuf);
     if (retID == ID)
         ret = logincont1(obj, uam_pwd, ibuf, ibuflen, rbuf, rbuflen);
     else if (retID == ID+1)
index b3bd931052c54b424cd328579be35f67531b7813..4c7d87c0cbf03fc4e592134ea52046ba382b994b 100644 (file)
@@ -26,7 +26,7 @@
 #ifdef HAVE_PAM_PAM_APPL_H
 #include <pam/pam_appl.h>
 #endif
-
+#include <arpa/inet.h>
 
 #if defined(GNUTLS_DHX)
 #include <gnutls/openssl.h>
 /* the secret key */
 static CAST_KEY castkey;
 static struct passwd *dhxpwd;
-static u_int8_t randbuf[KEYSIZE];
+static uint8_t randbuf[KEYSIZE];
 
 /* diffie-hellman bits */
 static unsigned char msg2_iv[] = "CJalbert";
 static unsigned char msg3_iv[] = "LWallace";
-static const u_int8_t p[] = {0xBA, 0x28, 0x73, 0xDF, 0xB0, 0x60, 0x57, 0xD4,
+static const uint8_t p[] = {0xBA, 0x28, 0x73, 0xDF, 0xB0, 0x60, 0x57, 0xD4,
                             0x3F, 0x20, 0x24, 0x74, 0x4C, 0xEE, 0xE7, 0x5B};
-static const u_int8_t g = 0x07;
+static const uint8_t g = 0x07;
 
 
 /* Static variables used to communicate between the conversation function
@@ -187,7 +187,7 @@ static struct pam_conv PAM_conversation = {
 static int dhx_setup(void *obj, char *ibuf, size_t ibuflen _U_, 
                     char *rbuf, size_t *rbuflen)
 {
-    u_int16_t sessid;
+    uint16_t sessid;
     size_t i;
     BIGNUM *bn, *gbn, *pbn;
     DH *dh;
@@ -375,8 +375,9 @@ static int pam_login_ext(void *obj, char *uname, struct passwd **uam_pwd,
                     char *rbuf, size_t *rbuflen)
 {
     char *username;
-    int len, ulen;
-    u_int16_t  temp16;
+    int len;
+    size_t ulen;
+    uint16_t  temp16;
 
     *rbuflen = 0;
 
@@ -412,7 +413,7 @@ static int pam_logincont(void *obj, struct passwd **uam_pwd,
 {
     const char *hostname;
     BIGNUM *bn1, *bn2, *bn3;
-    u_int16_t sessid;
+    uint16_t sessid;
     int err, PAM_error;
 
     *rbuflen = 0;
@@ -572,7 +573,7 @@ static int pam_changepw(void *obj, char *username,
     char *hostname;
     pam_handle_t *lpamh;
     uid_t uid;
-    u_int16_t sessid;
+    uint16_t sessid;
     int PAM_error;
 
     if (ibuflen < sizeof(sessid)) {
index 465f28972e6b9eec0ceaf0468f41c9582b25bce6..d390f76b4da29d556fb07bdf559849e3610e9362 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: uams_dhx_passwd.c,v 1.29 2010-03-30 12:44:35 franklahm Exp $
- *
  * Copyright (c) 1990,1993 Regents of The University of Michigan.
  * Copyright (c) 1999 Adrian Sun (asun@u.washington.edu) 
  * All Rights Reserved.  See COPYRIGHT.
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #ifdef HAVE_CRYPT_H
 #include <crypt.h>
 #endif /* ! HAVE_CRYPT_H */
-#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
-#endif
-#ifdef HAVE_TIME_H
 #include <time.h>
-#endif
 #include <pwd.h>
+#include <arpa/inet.h>
+
 #ifdef SHADOWPW
 #include <shadow.h>
 #endif /* SHADOWPW */
+
 #if defined(GNUTLS_DHX)
 #include <gnutls/openssl.h>
 #elif defined(OPENSSL_DHX)
@@ -59,7 +54,7 @@
 /* the secret key */
 static CAST_KEY castkey;
 static struct passwd *dhxpwd;
-static u_int8_t randbuf[16];
+static uint8_t randbuf[16];
 
 #ifdef TRU64
 #include <sia.h>
@@ -74,14 +69,14 @@ static int pwd_login(void *obj, char *username, int ulen, struct passwd **uam_pw
                        char *rbuf, size_t *rbuflen)
 {
     unsigned char iv[] = "CJalbert";
-    u_int8_t p[] = {0xBA, 0x28, 0x73, 0xDF, 0xB0, 0x60, 0x57, 0xD4,
+    uint8_t p[] = {0xBA, 0x28, 0x73, 0xDF, 0xB0, 0x60, 0x57, 0xD4,
                    0x3F, 0x20, 0x24, 0x74, 0x4C, 0xEE, 0xE7, 0x5B };
-    u_int8_t g = 0x07;
+    uint8_t g = 0x07;
 #ifdef SHADOWPW
     struct spwd *sp;
 #endif /* SHADOWPW */
     BIGNUM *bn, *gbn, *pbn;
-    u_int16_t sessid;
+    uint16_t sessid;
     size_t i;
     DH *dh;
 
@@ -250,7 +245,7 @@ static int passwd_login_ext(void *obj, char *uname, struct passwd **uam_pwd,
 {
     char       *username;
     size_t     len, ulen;
-    u_int16_t  temp16;
+    uint16_t  temp16;
 
     *rbuflen = 0;
     
@@ -280,7 +275,7 @@ static int passwd_logincont(void *obj, struct passwd **uam_pwd,
 #endif /* SHADOWPW */
     unsigned char iv[] = "LWallace";
     BIGNUM *bn1, *bn2, *bn3;
-    u_int16_t sessid;
+    uint16_t sessid;
     char *p;
     int err = AFPERR_NOTAUTH;
 
index c513bcf752092f7b52130cde6e6cf9796f15b843..f8cfc1af1434c0ad7384456e9340fe5fdd38d379 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: uams_gss.c,v 1.12 2010-03-30 10:25:49 franklahm Exp $
- *
  * Copyright (c) 1990,1993 Regents of The University of Michigan.
  * Copyright (c) 1999 Adrian Sun (asun@u.washington.edu)
  * Copyright (c) 2003 The Reed Institute
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include <stdio.h>
+#include <stdbool.h>
+#include <stdint.h>
 #include <stdlib.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#include <errno.h>
+#include <arpa/inet.h>
+
 #include <atalk/logger.h>
 #include <atalk/afp.h>
 #include <atalk/uam.h>
 #include <atalk/util.h>
+#include <atalk/compat.h>
 
 /* Kerberos includes */
-
-#if HAVE_GSSAPI_H
-#include <gssapi.h>
-#endif
-
-#if HAVE_GSSAPI_GSSAPI_H
+#ifdef HAVE_GSSAPI_GSSAPI_H
 #include <gssapi/gssapi.h>
-#endif
-
-#if HAVE_GSSAPI_GSSAPI_GENERIC_H
-#include <gssapi/gssapi_generic.h>
-#endif
-
-#if HAVE_GSSAPI_GSSAPI_KRB5_H
-#include <gssapi/gssapi_krb5.h>
-#endif
-
-#if HAVE_COM_ERR_H
-#include <com_err.h>
-#endif
-
-/* We work around something I don't entirely understand... */
-/* BF: This is a Heimdal/MIT compatibility fix */
-#ifndef HAVE_GSS_C_NT_HOSTBASED_SERVICE
-#define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
-#endif
+#else
+#include <gssapi.h>
+#endif // HAVE_GSSAPI_GSSAPI_H
 
-#ifdef MIN
-#undef MIN
-#endif
+#define LOG_UAMS(log_level, ...) \
+    LOG(log_level, logtype_uams, __VA_ARGS__)
 
-#define MIN(a, b) ((a > b) ? b : a)
+#define LOG_LOGINCONT(log_level, ...) \
+    LOG_UAMS(log_level, "FPLoginCont: " __VA_ARGS__)
 
-static void log_status( char *s, OM_uint32 major_status,
-                        OM_uint32 minor_status )
+static void log_status(char *s,
+                       OM_uint32 major_status,
+                       OM_uint32 minor_status)
 {
     gss_buffer_desc msg = GSS_C_EMPTY_BUFFER;
     OM_uint32 min_status, maj_status;
@@ -84,19 +47,20 @@ static void log_status( char *s, OM_uint32 major_status,
         maj_status = gss_display_status( &min_status, major_status,
                                          GSS_C_GSS_CODE, GSS_C_NULL_OID,
                                          &maj_ctx, &msg );
-        LOG(log_info, logtype_uams, "uams_gss.c :do_gss_auth: %s %.*s (error %s)", s,
-            (int)msg.length, msg.value, strerror(errno));
+        LOG_UAMS(log_error, "%s %.*s (error %s)",
+                 s, msg.length, msg.value, strerror(errno));
         gss_release_buffer(&min_status, &msg);
 
         if (!maj_ctx)
             break;
     }
+
     while (1) {
         maj_status = gss_display_status( &min_status, minor_status,
-                                         GSS_C_MECH_CODE, GSS_C_NULL_OID, // gss_mech_krb5,
+                                         GSS_C_MECH_CODE, GSS_C_NULL_OID,
                                          &min_ctx, &msg );
-        LOG(log_info, logtype_uams, "uams_gss.c :do_gss_auth: %s %.*s (error %s)", s,
-            (int)msg.length, msg.value, strerror(errno));
+        LOG_UAMS(log_error, "%s %.*s (error %s)",
+                 s, msg.length, msg.value, strerror(errno));
         gss_release_buffer(&min_status, &msg);
 
         if (!min_ctx)
@@ -104,129 +68,66 @@ static void log_status( char *s, OM_uint32 major_status,
     }
 }
 
-
-static void log_ctx_flags( OM_uint32 flags )
+static void log_ctx_flags(OM_uint32 flags)
 {
-#ifdef DEBUG1
     if (flags & GSS_C_DELEG_FLAG)
-        LOG(log_debug, logtype_uams, "uams_gss.c :context flag: GSS_C_DELEG_FLAG" );
+        LOG_LOGINCONT(log_debug, "context flag: GSS_C_DELEG_FLAG");
     if (flags & GSS_C_MUTUAL_FLAG)
-        LOG(log_debug, logtype_uams, "uams_gss.c :context flag: GSS_C_MUTUAL_FLAG" );
+        LOG_LOGINCONT(log_debug, "context flag: GSS_C_MUTUAL_FLAG");
     if (flags & GSS_C_REPLAY_FLAG)
-        LOG(log_debug, logtype_uams, "uams_gss.c :context flag: GSS_C_REPLAY_FLAG" );
+        LOG_LOGINCONT(log_debug, "context flag: GSS_C_REPLAY_FLAG");
     if (flags & GSS_C_SEQUENCE_FLAG)
-        LOG(log_debug, logtype_uams, "uams_gss.c :context flag: GSS_C_SEQUENCE_FLAG" );
+        LOG_LOGINCONT(log_debug, "context flag: GSS_C_SEQUENCE_FLAG");
     if (flags & GSS_C_CONF_FLAG)
-        LOG(log_debug, logtype_uams, "uams_gss.c :context flag: GSS_C_CONF_FLAG" );
+        LOG_LOGINCONT(log_debug, "context flag: GSS_C_CONF_FLAG");
     if (flags & GSS_C_INTEG_FLAG)
-        LOG(log_debug, logtype_uams, "uams_gss.c :context flag: GSS_C_INTEG_FLAG" );
-#endif
-}
-
-static void log_principal(gss_name_t server_name)
-{
-#if 0
-    if (server_name == GSS_C_NO_NAME)
-        return;
-    /* FIXME: must call gss_canonicalize_name before gss_export_name */
-    OM_uint32 major_status = 0, minor_status = 0;
-    gss_buffer_desc exported_name;
-
-    /* Only for debugging purposes, check the gssapi internal representation */
-    major_status = gss_export_name(&minor_status, server_name, &exported_name);
-    LOG(log_debug, logtype_uams, "log_principal: exported server name is %s", (char*) exported_name.value);
-    gss_release_buffer( &minor_status, &exported_name );
-#endif
+        LOG_LOGINCONT(log_debug, "context flag: GSS_C_INTEG_FLAG");
 }
 
-/* get the principal from afpd and import it into server_name */
-static int get_afpd_principal(void *obj, gss_name_t *server_name)
+static void log_service_name(gss_ctx_id_t context)
 {
     OM_uint32 major_status = 0, minor_status = 0;
-    char *fqdn, *service, *principal, *p;
-    size_t fqdnlen=0, servicelen=0;
-    size_t principal_length;
-    gss_buffer_desc s_princ_buffer;
-
-    /* get information from afpd */
-    if (uam_afpserver_option(obj, UAM_OPTION_FQDN, (void*) &fqdn, &fqdnlen) < 0)
-        return 1;
-    LOG(log_debug, logtype_uams, "get_afpd_principal: fqdn: %s", fqdn);
-
-    if (uam_afpserver_option(obj, UAM_OPTION_KRB5SERVICE, (void *)&service, &servicelen) < 0)
-        return 1;
-    LOG(log_debug, logtype_uams, "get_afpd_principal: service: %s", service);
-
-    /* if we don't have all the info, log that and return GSS_C_NO_NAME */
-    if (!service || !servicelen || !fqdn || !fqdnlen) {
-        LOG(log_note, logtype_uams,
-            "get_afpd_principal: could not retrieve information from afpd, using default service principal(s)");
-
-              *server_name = GSS_C_NO_NAME;
-        return 0;
-    }
-
-    /* allocate memory to hold the temporary principal string */
-    principal_length = servicelen + 1 + fqdnlen + 1;
-    if ( NULL == (principal = (char*) malloc( principal_length)) ) {
-        LOG(log_error, logtype_uams,
-            "get_afpd_principal: out of memory allocating %u bytes",
-            principal_length);
-        return 1;
+    gss_name_t service_name;
+    gss_buffer_desc service_name_buffer;
+
+    major_status = gss_inquire_context(&minor_status,
+                                       context,
+                                       NULL,
+                                       &service_name,
+                                       NULL,
+                                       NULL,
+                                       NULL,
+                                       NULL,
+                                       NULL);
+    if (major_status != GSS_S_COMPLETE) {
+        log_status("gss_inquire_context", major_status, minor_status);
+        return;
     }
 
-    /*
-     * Build the principal string.
-     * Format: 'service@fqdn'
-     */
-    strlcpy( principal, service, principal_length);
-    strlcat( principal, "@", principal_length);
-
-    /*
-     * The fqdn we get from afpd may contain a port.
-     * We need to strip the port from fqdn for principal.
-     */
-    if ((p = strchr(fqdn, ':')))
-        *p = '\0';
-
-    strlcat( principal, fqdn, principal_length);
-    if (p)
-        *p = ':';
-    /*
-     * Import our principal into the gssapi internal representation
-     * stored in server_name.
-     */
-    s_princ_buffer.value = principal;
-    s_princ_buffer.length = strlen( principal ) + 1;
+    major_status = gss_display_name(&minor_status,
+                                    service_name,
+                                    &service_name_buffer,
+                                    NULL);
+    if (major_status == GSS_S_COMPLETE) {
+        LOG_LOGINCONT(log_debug,
+                      "service principal is `%s'",
+                      service_name_buffer.value);
 
-    LOG(log_debug, logtype_uams, "get_afpd_principal: importing principal `%s'", principal);
-    major_status = gss_import_name( &minor_status,
-                                    &s_princ_buffer,
-                                    GSS_C_NT_HOSTBASED_SERVICE,
-                                    server_name );
+        gss_release_buffer(&minor_status, &service_name_buffer);
+    } else
+        log_status("gss_display_name", major_status, minor_status);
 
-    /*
-     * Get rid of malloc'ed memmory.
-     * Don't release the s_princ_buffer, we free principal instead.
-     */
-    free(principal);
-
-    if (major_status != GSS_S_COMPLETE) {
-        /* Importing our service principal failed, bail out. */
-        log_status( "import_principal", major_status, minor_status );
-        return 1;
-    }
-    return 0;
+    gss_release_name(&minor_status, &service_name);
 }
 
-
-/* get the username */
-static int get_client_username(char *username, int ulen, gss_name_t *client_name)
+static int get_client_username(char *username,
+                               int ulen,
+                               gss_name_t *client_name)
 {
     OM_uint32 major_status = 0, minor_status = 0;
     gss_buffer_desc client_name_buffer;
     char *p;
-    int namelen, ret=0;
+    int ret = 0;
 
     /*
      * To extract the unix username, use gss_display_name on client_name.
@@ -236,39 +137,42 @@ static int get_client_username(char *username, int ulen, gss_name_t *client_name
      * the username before copying it to afpd's buffer.
      */
 
-    major_status = gss_display_name( &minor_status, *client_name,
-                                     &client_name_buffer, (gss_OID *)NULL );
+    major_status = gss_display_name(&minor_status,
+                                    *client_name,
+                                    &client_name_buffer,
+                                    NULL);
     if (major_status != GSS_S_COMPLETE) {
-        log_status( "display_name", major_status, minor_status );
+        log_status("gss_display_name", major_status, minor_status);
         return 1;
     }
 
-    LOG(log_debug, logtype_uams, "get_client_username: user is `%s'", client_name_buffer.value);
+    LOG_LOGINCONT(log_debug,
+                  "user principal is `%s'",
+                  client_name_buffer.value);
 
     /* chop off realm */
-    p = strchr( client_name_buffer.value, '@' );
+    p = strchr(client_name_buffer.value, '@');
     if (p)
         *p = 0;
     /* FIXME: chop off instance? */
-    p = strchr( client_name_buffer.value, '/' );
+    p = strchr(client_name_buffer.value, '/');
     if (p)
         *p = 0;
 
     /* check if this username fits into afpd's username buffer */
-    namelen = strlen(client_name_buffer.value);
-    if ( namelen >= ulen ) {
+    size_t cnblen = strlen(client_name_buffer.value);
+    if (cnblen >= ulen) {
         /* The username is too long for afpd's buffer, bail out */
-        LOG(log_error, logtype_uams,
-            "get_client_username: username `%s' too long", client_name_buffer.value);
+        LOG_LOGINCONT(log_info,
+                      "username `%s' too long (%d)",
+                      client_name_buffer.value, cnblen);
         ret = 1;
-    }
-    else {
+    } else {
         /* copy stripped username to afpd's buffer */
         strlcpy(username, client_name_buffer.value, ulen);
     }
 
-    /* we're done with client_name_buffer, release it */
-    gss_release_buffer(&minor_status, &client_name_buffer );
+    gss_release_buffer(&minor_status, &client_name_buffer);
 
     return ret;
 }
@@ -276,9 +180,9 @@ static int get_client_username(char *username, int ulen, gss_name_t *client_name
 /* wrap afpd's sessionkey */
 static int wrap_sessionkey(gss_ctx_id_t context, struct session_info *sinfo)
 {
-    OM_uint32 status = 0;
-    int ret=0;
+    OM_uint32 major_status = 0, minor_status = 0;
     gss_buffer_desc sesskey_buff, wrap_buff;
+    int ret = 0;
 
     /*
      * gss_wrap afpd's session_key.
@@ -286,203 +190,175 @@ static int wrap_sessionkey(gss_ctx_id_t context, struct session_info *sinfo)
      * with type 8 (kGetKerberosSessionKey) on FPGetSession.
      * See AFP 3.1 specs, page 77.
      */
-
     sesskey_buff.value = sinfo->sessionkey;
     sesskey_buff.length = sinfo->sessionkey_len;
 
-    /* gss_wrap the session key with the default machanism.
+    /* gss_wrap the session key with the default mechanism.
        Require both confidentiality and integrity services */
-    gss_wrap (&status, context, 1, GSS_C_QOP_DEFAULT, &sesskey_buff, NULL, &wrap_buff);
+    major_status = gss_wrap(&minor_status,
+                            context,
+                            true,
+                            GSS_C_QOP_DEFAULT,
+                            &sesskey_buff,
+                            NULL,
+                            &wrap_buff);
 
-    if ( status != GSS_S_COMPLETE) {
-        LOG(log_error, logtype_uams, "wrap_sessionkey: failed to gss_wrap sessionkey");
-        log_status( "GSS wrap", 0, status );
+    if (major_status != GSS_S_COMPLETE) {
+        log_status("gss_wrap", major_status, minor_status);
         return 1;
     }
 
     /* store the wrapped session key in afpd's session_info struct */
-    if ( NULL == (sinfo->cryptedkey = malloc ( wrap_buff.length )) ) {
-        LOG(log_error, logtype_uams,
-            "wrap_sessionkey: out of memory tyring to allocate %u bytes",
-            wrap_buff.length);
+    if (NULL == (sinfo->cryptedkey = malloc(wrap_buff.length))) {
+        LOG_UAMS(log_error,
+                 "wrap_sessionkey: out of memory tyring to allocate %u bytes",
+                 wrap_buff.length);
         ret = 1;
     } else {
         /* cryptedkey is binary data */
-        memcpy (sinfo->cryptedkey, wrap_buff.value, wrap_buff.length);
+        memcpy(sinfo->cryptedkey, wrap_buff.value, wrap_buff.length);
         sinfo->cryptedkey_len = wrap_buff.length;
     }
 
     /* we're done with buffer, release */
-    gss_release_buffer( &status, &wrap_buff );
+    gss_release_buffer(&minor_status, &wrap_buff);
 
     return ret;
 }
 
-/*-------------*/
-static int acquire_credentials (gss_name_t *server_name, gss_cred_id_t *server_creds)
+static int accept_sec_context(gss_ctx_id_t *context,
+                              gss_buffer_desc *ticket_buffer,
+                              gss_name_t *client_name,
+                              gss_buffer_desc *authenticator_buff)
 {
-    OM_uint32 major_status = 0, minor_status = 0;
-    char *envp;
-
-    if ((envp = getenv("KRB5_KTNAME")))
-        LOG(log_debug, logtype_uams,
-            "acquire credentials: acquiring credentials (uid = %d, keytab = %s)",
-            (int)geteuid(), envp);
-    else
-        LOG(log_debug, logtype_uams,
-            "acquire credentials: acquiring credentials (uid = %d) - $KRB5_KTNAME not found in env",
-            (int)geteuid());
-        
-    /*
-     * Acquire credentials usable for accepting context negotiations.
-     * Credentials are for server_name, have an indefinite lifetime,
-     * have no specific mechanisms, are to be used for accepting context
-     * negotiations and are to be placed in server_creds.
-     * We don't care about the mechanisms or about the time for which they are valid.
-     */
-    major_status = gss_acquire_cred( &minor_status, *server_name,
-                                     GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_ACCEPT,
-                                     server_creds, NULL, NULL );
-
-    if (major_status != GSS_S_COMPLETE) {
-        log_status( "acquire_cred", major_status, minor_status );
-        return 1;
-    }
-
-    return 0;
-}
-
-/*-------------*/
-static int accept_sec_context (gss_ctx_id_t *context, gss_cred_id_t server_creds,
-                               gss_buffer_desc *ticket_buffer, gss_name_t *client_name,
-                               gss_buffer_desc *authenticator_buff)
-{
-    OM_uint32 major_status = 0, minor_status = 0, ret_flags;
+    OM_uint32 major_status = 0, minor_status = 0, flags = 0;
 
     /* Initialize autheticator buffer. */
     authenticator_buff->length = 0;
     authenticator_buff->value = NULL;
 
-    LOG(log_debug, logtype_uams, "accept_context: accepting context (ticketlen: %u)",
-        ticket_buffer->length);
+    LOG_LOGINCONT(log_debug,
+                  "accepting context (ticketlen: %u)",
+                  ticket_buffer->length);
 
     /*
-     * Try to accept the secondary context using the tocken in ticket_buffer.
-     * We don't care about the mechanisms used, nor for the time.
+     * Try to accept the secondary context using the token in ticket_buffer.
+     * We don't care about the principals or mechanisms used, nor for the time.
      * We don't act as a proxy either.
      */
-    major_status = gss_accept_sec_context( &minor_status, context,
-                                           server_creds, ticket_buffer, GSS_C_NO_CHANNEL_BINDINGS,
-                                           client_name, NULL, authenticator_buff,
-                                           &ret_flags, NULL, NULL );
+    major_status = gss_accept_sec_context(&minor_status,
+                                          context,
+                                          GSS_C_NO_CREDENTIAL,
+                                          ticket_buffer,
+                                          GSS_C_NO_CHANNEL_BINDINGS,
+                                          client_name,
+                                          NULL,
+                                          authenticator_buff,
+                                          &flags,
+                                          NULL,
+                                          NULL);
 
     if (major_status != GSS_S_COMPLETE) {
-        log_status( "accept_sec_context", major_status, minor_status );
+        log_status("gss_accept_sec_context", major_status, minor_status);
         return 1;
     }
-    log_ctx_flags( ret_flags );
+
+    log_ctx_flags(flags);
     return 0;
 }
 
-
-/* return 0 on success */
-static int do_gss_auth(void *obj, char *ibuf, int ticket_len,
-                       char *rbuf, int *rbuflen, char *username, int ulen,
+static int do_gss_auth(void *obj,
+                       char *ibuf, size_t ibuflen,
+                       char *rbuf, int *rbuflen,
+                       char *username, size_t ulen,
                        struct session_info *sinfo )
 {
     OM_uint32 status = 0;
-    gss_name_t server_name, client_name;
-    gss_cred_id_t server_creds;
-    gss_ctx_id_t context_handle = GSS_C_NO_CONTEXT;
+    gss_name_t client_name;
+    gss_ctx_id_t context = GSS_C_NO_CONTEXT;
     gss_buffer_desc ticket_buffer, authenticator_buff;
     int ret = 0;
 
-    /* import our principal name from afpd */
-    if (get_afpd_principal(obj, &server_name) != 0) {
-        return 1;
-    }
-    log_principal(server_name);
-
-    /* Now we have to acquire our credentials */
-    if ((ret = acquire_credentials (&server_name, &server_creds)))
-        goto cleanup_vars;
-
     /*
      * Try to accept the secondary context, using the ticket/token the
      * client sent us. Ticket is stored at current ibuf position.
      * Don't try to release ticket_buffer later, it points into ibuf!
      */
-    ticket_buffer.length = ticket_len;
+    ticket_buffer.length = ibuflen;
     ticket_buffer.value = ibuf;
 
-    ret = accept_sec_context (&context_handle, server_creds, &ticket_buffer,
-                              &client_name, &authenticator_buff);
-
-    if (!ret) {
-        /* We succesfully acquired the secondary context, now get the
-           username for afpd and gss_wrap the sessionkey */
-        if ( 0 == (ret = get_client_username(username, ulen, &client_name)) ) {
-            ret = wrap_sessionkey(context_handle, sinfo);
-        }
-
-        if (!ret) {
-            /* FIXME: Is copying the authenticator really necessary?
-               Where is this documented? */
-            u_int16_t auth_len = htons( authenticator_buff.length );
-
-            /* copy the authenticator length into the reply buffer */
-            memcpy( rbuf, &auth_len, sizeof(auth_len) );
-            *rbuflen += sizeof(auth_len);
-            rbuf += sizeof(auth_len);
-
-            /* copy the authenticator value into the reply buffer */
-            memcpy( rbuf, authenticator_buff.value, authenticator_buff.length );
-            *rbuflen += authenticator_buff.length;
-        }
-
-        /* Clean up after ourselves */
-        gss_release_name( &status, &client_name );
-        if ( authenticator_buff.value)
-            gss_release_buffer( &status, &authenticator_buff );
-
-        gss_delete_sec_context( &status, &context_handle, NULL );
-    }
-    gss_release_cred( &status, &server_creds );
+    if ((ret = accept_sec_context(&context,
+                                  &ticket_buffer,
+                                  &client_name,
+                                  &authenticator_buff)))
+        return ret;
+    log_service_name(context);
+
+    /* We succesfully acquired the secondary context, now get the
+       username for afpd and gss_wrap the sessionkey */
+    if ((ret = get_client_username(username, ulen, &client_name)))
+        goto cleanup_client_name;
+
+    if ((ret = wrap_sessionkey(context, sinfo)))
+        goto cleanup_client_name;
+
+    /* Authenticated, construct the reply using:
+     * authenticator length (uint16_t)
+     * authenticator
+     */
+    /* copy the authenticator length into the reply buffer */
+    uint16_t auth_len = htons(authenticator_buff.length);
+    memcpy(rbuf, &auth_len, sizeof(auth_len));
+    *rbuflen += sizeof(auth_len);
+    rbuf += sizeof(auth_len);
 
-cleanup_vars:
-    if (server_name != GSS_C_NO_NAME)
-        gss_release_name( &status, &server_name );
+    /* copy the authenticator value into the reply buffer */
+    memcpy(rbuf, authenticator_buff.value, authenticator_buff.length);
+    *rbuflen += authenticator_buff.length;
+
+cleanup_client_name:
+    gss_release_name(&status, &client_name);
+
+cleanup_context:
+    gss_release_buffer(&status, &authenticator_buff);
+    gss_delete_sec_context(&status, &context, NULL);
 
     return ret;
 }
 
 /* -------------------------- */
-static int gss_login(void *obj, struct passwd **uam_pwd,
+
+/*
+ * For the gss uam, this function only needs to return a two-byte
+ * login-session id. None of the data provided by the client up to this
+ * point is trustworthy as we'll have a signed ticket to parse in logincont.
+ */
+static int gss_login(void *obj,
+                     struct passwd **uam_pwd,
                      char *ibuf, size_t ibuflen,
                      char *rbuf, size_t *rbuflen)
 {
-
-    u_int16_t  temp16;
-
     *rbuflen = 0;
 
     /* The reply contains a two-byte ID value - note
      * that Apple's implementation seems to always return 1 as well
      */
-    temp16 = htons( 1 );
+    uint16_t temp16 = htons(1);
     memcpy(rbuf, &temp16, sizeof(temp16));
     *rbuflen += sizeof(temp16);
+
     return AFPERR_AUTHCONT;
 }
 
-static int gss_logincont(void *obj, struct passwd **uam_pwd,
+static int gss_logincont(void *obj,
+                         struct passwd **uam_pwd,
                          char *ibuf, size_t ibuflen,
                          char *rbuf, size_t *rbuflen)
 {
     struct passwd *pwd = NULL;
-    u_int16_t login_id;
+    uint16_t login_id;
     char *username;
-    u_int16_t ticket_len;
+    uint16_t ticket_len;
     char *p;
     int rblen;
     size_t userlen;
@@ -491,9 +367,10 @@ static int gss_logincont(void *obj, struct passwd **uam_pwd,
     /* Apple's AFP 3.1 documentation specifies that this command
      * takes the following format:
      * pad (byte)
-     * id returned in LoginExt response (u_int16_t)
-     * username (format unspecified) padded, when necessary, to end on an even boundary
-     * ticket length (u_int16_t)
+     * id returned in LoginExt response (uint16_t)
+     * username (format unspecified)
+     *   padded, when necessary, to end on an even boundary
+     * ticket length (uint16_t)
      * ticket
      */
 
@@ -501,49 +378,49 @@ static int gss_logincont(void *obj, struct passwd **uam_pwd,
      * format of this request is as follows:
      * pad (byte) [consumed before login_ext is called]
      * ?? (byte) - always observed to be 0
-     * id returned in LoginExt response (u_int16_t)
+     * id returned in LoginExt response (uint16_t)
      * username, encoding unspecified, null terminated C string,
      *   padded when the terminating null is an even numbered byte.
      *   The packet is formated such that the username begins on an
      *   odd numbered byte. Eg if the username is 3 characters and the
      *   terminating null makes 4, expect to pad the the result.
      *   The encoding of this string is unknown.
-     * ticket length (u_int16_t)
+     * ticket length (uint16_t)
      * ticket
      */
 
     rblen = *rbuflen = 0;
 
     if (ibuflen < 1 +sizeof(login_id)) {
-        LOG(log_info, logtype_uams, "uams_gss.c :LoginCont: received incomplete packet");
+        LOG_LOGINCONT(log_info, "received incomplete packet");
         return AFPERR_PARAM;
     }
     ibuf++, ibuflen--; /* ?? */
 
     /* 2 byte ID from LoginExt -- always '00 01' in this implementation */
-    memcpy( &login_id, ibuf, sizeof(login_id) );
+    memcpy(&login_id, ibuf, sizeof(login_id));
     ibuf += sizeof(login_id), ibuflen -= sizeof(login_id);
-    login_id = ntohs( login_id );
+    login_id = ntohs(login_id);
 
     /* get the username buffer from apfd */
-    if (uam_afpserver_option(obj, UAM_OPTION_USERNAME, (void *) &username, &userlen) < 0)
+    if (uam_afpserver_option(obj, UAM_OPTION_USERNAME, &username, &userlen) < 0)
         return AFPERR_MISC;
 
     /* get the session_info structure from afpd. We need the session key */
-    if (uam_afpserver_option(obj, UAM_OPTION_SESSIONINFO, (void *)&sinfo, NULL) < 0)
+    if (uam_afpserver_option(obj, UAM_OPTION_SESSIONINFO, &sinfo, NULL) < 0)
         return AFPERR_MISC;
 
     if (sinfo->sessionkey == NULL || sinfo->sessionkey_len == 0) {
         /* Should never happen. Most likely way too old afpd version */
-        LOG(log_info, logtype_uams, "internal error: afpd's sessionkey not set");
+        LOG_LOGINCONT(log_error, "internal error: afpd's sessionkey not set");
         return AFPERR_MISC;
     }
 
     /* We skip past the 'username' parameter because all that matters is the ticket */
     p = ibuf;
-    while( *ibuf && ibuflen ) { ibuf++, ibuflen--; }
+    while ( *ibuf && ibuflen ) { ibuf++, ibuflen--; }
     if (ibuflen < 4) {
-        LOG(log_info, logtype_uams, "uams_gss.c :LoginCont: user is %s, no ticket", p);
+        LOG_LOGINCONT(log_info, "user is %s, no ticket", p);
         return AFPERR_PARAM;
     }
 
@@ -551,79 +428,63 @@ static int gss_logincont(void *obj, struct passwd **uam_pwd,
 
     if ((ibuf - p + 1) % 2) ibuf++, ibuflen--; /* deal with potential padding */
 
-    LOG(log_debug, logtype_uams, "uams_gss.c :LoginCont: client thinks user is %s", p);
+    LOG_LOGINCONT(log_debug, "client thinks user is %s", p);
 
     /* get the length of the ticket the client sends us */
     memcpy(&ticket_len, ibuf, sizeof(ticket_len));
     ibuf += sizeof(ticket_len); ibuflen -= sizeof(ticket_len);
-    ticket_len = ntohs( ticket_len );
+    ticket_len = ntohs(ticket_len);
 
     /* a little bounds checking */
     if (ticket_len > ibuflen) {
-        LOG(log_info, logtype_uams,
-            "uams_gss.c :LoginCont: invalid ticket length (%u > %u)", ticket_len, ibuflen);
+        LOG_LOGINCONT(log_info,
+                      "invalid ticket length (%u > %u)",
+                      ticket_len, ibuflen);
         return AFPERR_PARAM;
     }
 
     /* now try to authenticate */
-    if (!do_gss_auth(obj, ibuf, ticket_len, rbuf, &rblen, username, userlen, sinfo)) {
-        /* We use the username we got back from the gssapi client_name.
-           Should we compare this to the username the client sent in the clear?
-           We know the character encoding of the cleartext username (UTF8), what
-           encoding is the gssapi name in? */
-        if((pwd = uam_getname( obj, username, userlen )) == NULL) {
-            LOG(log_info, logtype_uams, "uam_getname() failed for %s", username);
-            return AFPERR_NOTAUTH;
-        }
-        if (uam_checkuser(pwd) < 0) {
-            LOG(log_info, logtype_uams, "%s not a valid user", username);
-            return AFPERR_NOTAUTH;
-        }
-        *rbuflen = rblen;
-        *uam_pwd = pwd;
-        return AFP_OK;
-    } else {
-        LOG(log_info, logtype_uams, "do_gss_auth failed" );
+    if (do_gss_auth(obj, ibuf, ticket_len, rbuf, &rblen, username, userlen, sinfo)) {
+        LOG_LOGINCONT(log_info, "do_gss_auth() failed" );
         *rbuflen = 0;
         return AFPERR_MISC;
     }
-}
-
-/*
- * For the krb5 uam, this function only needs to return a two-byte
- * login-session id. None of the data provided by the client up to this
- * point is trustworthy as we'll have a signed ticket to parse in logincont.
- */
-static int gss_login_ext(void *obj, char *uname, struct passwd **uam_pwd,
-                         char *ibuf, size_t ibuflen,
-                         char *rbuf, size_t *rbuflen)
-{
-    u_int16_t  temp16;
 
-    *rbuflen = 0;
+    /* We use the username we got back from the gssapi client_name.
+       Should we compare this to the username the client sent in the clear?
+       We know the character encoding of the cleartext username (UTF8), what
+       encoding is the gssapi name in? */
+    if ((pwd = uam_getname( obj, username, userlen )) == NULL) {
+        LOG_LOGINCONT(log_info, "uam_getname() failed for %s", username);
+        return AFPERR_NOTAUTH;
+    }
+    if (uam_checkuser(pwd) < 0) {
+        LOG_LOGINCONT(log_info, "`%s'' not a valid user", username);
+        return AFPERR_NOTAUTH;
+    }
 
-    /* The reply contains a two-byte ID value - note
-     * that Apple's implementation seems to always return 1 as well
-     */
-    temp16 = htons( 1 );
-    memcpy(rbuf, &temp16, sizeof(temp16));
-    *rbuflen += sizeof(temp16);
-    return AFPERR_AUTHCONT;
+    *rbuflen = rblen;
+    *uam_pwd = pwd;
+    return AFP_OK;
 }
 
 /* logout */
 static void gss_logout() {
 }
 
-int uam_setup(const char *path)
+static int gss_login_ext(void *obj,
+                         char *uname,
+                         struct passwd **uam_pwd,
+                         char *ibuf, size_t ibuflen,
+                         char *rbuf, size_t *rbuflen)
 {
-    if (uam_register(UAM_SERVER_LOGIN_EXT, path, "Client Krb v2",
-                     gss_login, gss_logincont, gss_logout, gss_login_ext) < 0)
-        if (uam_register(UAM_SERVER_LOGIN, path, "Client Krb v2",
-                         gss_login, gss_logincont, gss_logout) < 0)
-            return -1;
+    return gss_login(obj, uam_pwd, ibuf, ibuflen, rbuf, rbuflen);
+}
 
-    return 0;
+static int uam_setup(const char *path)
+{
+    return uam_register(UAM_SERVER_LOGIN_EXT, path, "Client Krb v2",
+                        gss_login, gss_logincont, gss_logout, gss_login_ext);
 }
 
 static void uam_cleanup(void)
@@ -634,5 +495,6 @@ static void uam_cleanup(void)
 UAM_MODULE_EXPORT struct uam_export uams_gss = {
     UAM_MODULE_SERVER,
     UAM_MODULE_VERSION,
-    uam_setup, uam_cleanup
+    uam_setup,
+    uam_cleanup
 };
index 0b5019e0e7e4d0214cb4db90250553742e138210..00f90ece0972ee01670d5cc1eee55879d6795b35 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <errno.h>
-
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
 #include <pwd.h>
-#include <atalk/logger.h>
 
+#include <atalk/logger.h>
 #include <atalk/afp.h>
 #include <atalk/uam.h>
 #include <atalk/util.h>
+#include <atalk/compat.h>
 
 #ifndef MIN
 #define MIN(a,b) ((a) < (b) ? (a) : (b))
diff --git a/etc/uams/uams_krb4/.gitignore b/etc/uams/uams_krb4/.gitignore
deleted file mode 100644 (file)
index c22a7f2..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-.libs
-.deps
-*.o
-*.so
-*.la
-core
-Makefile.in
-Makefile
-.gitignore
-*.o
diff --git a/etc/uams/uams_krb4/Makefile.am b/etc/uams/uams_krb4/Makefile.am
deleted file mode 100644 (file)
index 219e74b..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-# Makefile.am for etc/uams/uams_krb4/
-
-if USE_KERBEROS
-KERBEROS_MODULE = uams_krb4.la
-else
-KERBEROS_MODULE =
-endif
-
-uams_krb4_la_SOURCES = kuam.c lifetime.c send_to_kdc.c uams_krb4.c
-uams_krb4_la_LDFLAGS = -module -avoid-version
-
-uamsdir = @UAMS_PATH@
-uams_LTLIBRARIES = $(KERBEROS_MODULE)
diff --git a/etc/uams/uams_krb4/kuam.c b/etc/uams/uams_krb4/kuam.c
deleted file mode 100644 (file)
index 3c79064..0000000
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * $Id: kuam.c,v 1.4 2001-06-25 20:13:45 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifdef UAM_AFSKRB
-
-#include <mit-copyright.h>
-#include <krb.h>
-#include <des.h>
-#include <prot.h>
-
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-/* use the bsd time.h struct defs for PC too! */
-#include <sys/time.h>
-#include <sys/types.h>
-
-int     swap_bytes;
-
-/*
- * krb_get_in_tkt() gets a ticket for a given principal to use a given
- * service and stores the returned ticket and session key for future
- * use.
- *
- * The "user", "instance", and "realm" arguments give the identity of
- * the client who will use the ticket.  The "service" and "sinstance"
- * arguments give the identity of the server that the client wishes
- * to use.  (The realm of the server is the same as the Kerberos server
- * to whom the request is sent.)  The "life" argument indicates the
- * desired lifetime of the ticket; the "key_proc" argument is a pointer
- * to the routine used for getting the client's private key to decrypt
- * the reply from Kerberos.  The "decrypt_proc" argument is a pointer
- * to the routine used to decrypt the reply from Kerberos; and "arg"
- * is an argument to be passed on to the "key_proc" routine.
- *
- * If all goes well, krb_get_in_tkt() returns INTK_OK, otherwise it
- * returns an error code:  If an AUTH_MSG_ERR_REPLY packet is returned
- * by Kerberos, then the error code it contains is returned.  Other
- * error codes returned by this routine include INTK_PROT to indicate
- * wrong protocol version, INTK_BADPW to indicate bad password (if
- * decrypted ticket didn't make sense), INTK_ERR if the ticket was for
- * the wrong server or the ticket store couldn't be initialized.
- *
- * The format of the message sent to Kerberos is as follows:
- *
- * Size                        Variable                Field
- * ----                        --------                -----
- *
- * 1 byte              KRB_PROT_VERSION        protocol version number
- * 1 byte              AUTH_MSG_KDC_REQUEST |  message type
- *                     HOST_BYTE_ORDER         local byte order in lsb
- * string              user                    client's name
- * string              instance                client's instance
- * string              realm                   client's realm
- * 4 bytes             tlocal.tv_sec           timestamp in seconds
- * 1 byte              life                    desired lifetime
- * string              service                 service's name
- * string              sinstance               service's instance
- */
-
-kuam_get_in_tkt(user, instance, realm, service, sinstance, life, rpkt )
-    char       *user;
-    char       *instance;
-    char       *realm;
-    char       *service;
-    char       *sinstance;
-    int                life;
-    KTEXT      rpkt;
-{
-    KTEXT_ST pkt_st;
-    KTEXT pkt = &pkt_st;       /* Packet to KDC */
-    KTEXT_ST cip_st;
-    KTEXT cip = &cip_st;       /* Returned Ciphertext */
-    KTEXT_ST tkt_st;
-    KTEXT tkt = &tkt_st;       /* Current ticket */
-    unsigned char *v = pkt->dat; /* Prot vers no */
-    unsigned char *t = (pkt->dat+1); /* Prot msg type */
-    int msg_byte_order;
-    int kerror;
-    struct timeval t_local;
-    u_int32_t rep_err_code;
-
-
-    /* BUILD REQUEST PACKET */
-
-    /* Set up the fixed part of the packet */
-    *v = (unsigned char) KRB_PROT_VERSION;
-    *t = (unsigned char) AUTH_MSG_KDC_REQUEST;
-    *t |= HOST_BYTE_ORDER;
-
-    /* Now for the variable info */
-    (void) strcpy((char *)(pkt->dat+2),user); /* aname */
-    pkt->length = 3 + strlen(user);
-    (void) strcpy((char *)(pkt->dat+pkt->length),
-                 instance);    /* instance */
-    pkt->length += 1 + strlen(instance);
-    (void) strcpy((char *)(pkt->dat+pkt->length),realm); /* realm */
-    pkt->length += 1 + strlen(realm);
-
-    (void) gettimeofday(&t_local,(struct timezone *) 0);
-    /* timestamp */
-    memcpy((pkt->dat+pkt->length), &(t_local.tv_sec), 4);
-    pkt->length += 4;
-
-    *(pkt->dat+(pkt->length)++) = (char) life;
-    (void) strcpy((char *)(pkt->dat+pkt->length),service);
-    pkt->length += 1 + strlen(service);
-    (void) strcpy((char *)(pkt->dat+pkt->length),sinstance);
-    pkt->length += 1 + strlen(sinstance);
-
-    rpkt->length = 0;
-
-    /* SEND THE REQUEST AND RECEIVE THE RETURN PACKET */
-
-    if (kerror = send_to_kdc(pkt, rpkt, realm)) return(kerror);
-
-    /* check packet version of the returned packet */
-    if (pkt_version(rpkt) != KRB_PROT_VERSION)
-        return(INTK_PROT);
-
-    /* Check byte order */
-    msg_byte_order = pkt_msg_type(rpkt) & 1;
-    swap_bytes = 0;
-    if (msg_byte_order != HOST_BYTE_ORDER) {
-        swap_bytes++;
-    }
-
-    switch (pkt_msg_type(rpkt) & ~1) {
-    case AUTH_MSG_KDC_REPLY:
-        break;
-    case AUTH_MSG_ERR_REPLY:
-        memcpy(&rep_err_code,pkt_err_code(rpkt),4);
-        if (swap_bytes) swap_u_long(rep_err_code);
-        return((int)rep_err_code);
-    default:
-        return(INTK_PROT);
-    }
-
-    return( INTK_OK );
-}
-
-kuam_set_in_tkt( user, instance, realm, service, sinstance, ptr)
-    char       *user, *instance, *realm, *service, *sinstance, *ptr;
-{
-    KTEXT_ST           tkt_st;
-    KTEXT              tkt = &tkt_st;
-    struct timeval     t_local;
-    int                        lifetime, kvno, kerror;
-    int32_t            kdc_time;
-    C_Block            ses;
-    char               s_name[ SNAME_SZ ], s_instance[ INST_SZ ];
-    char               rlm[ REALM_SZ ];
-
-    /* extract session key */
-    memcpy(ses, ptr, 8);
-    ptr += 8;
-
-    /* extract server's name */
-    (void) strcpy(s_name,ptr);
-    ptr += strlen(s_name) + 1;
-
-    /* extract server's instance */
-    (void) strcpy(s_instance,ptr);
-    ptr += strlen(s_instance) + 1;
-
-    /* extract server's realm */
-    (void) strcpy(rlm,ptr);
-    ptr += strlen(rlm) + 1;
-
-    /* extract ticket lifetime, server key version, ticket length */
-    /* be sure to avoid sign extension on lifetime! */
-    lifetime = (unsigned char) ptr[0];
-    kvno = (unsigned char) ptr[1];
-    tkt->length = (unsigned char) ptr[2];
-    ptr += 3;
-
-    /* extract ticket itself */
-    memcpy( tkt->dat, ptr, tkt->length);
-    ptr += tkt->length;
-
-    if (strcmp(s_name, service) || strcmp(s_instance, sinstance) ||
-        strcmp(rlm, realm))    /* not what we asked for */
-       return(INTK_ERR);       /* we need a better code here XXX */
-
-    /* check KDC time stamp */
-    memcpy(&kdc_time, ptr, 4); /* Time (coarse) */
-    if (swap_bytes) swap_u_long(kdc_time);
-
-    ptr += 4;
-
-    (void) gettimeofday(&t_local,(struct timezone *) 0);
-    if (abs((int)(t_local.tv_sec - kdc_time)) > CLOCK_SKEW) {
-        return(RD_AP_TIME);            /* XXX should probably be better
-                                          code */
-    }
-
-    /* initialize ticket cache */
-    if (in_tkt(user,instance) != KSUCCESS)
-       return(INTK_ERR);
-
-    /* stash ticket, session key, etc. for future use */
-    if (kerror = save_credentials(s_name, s_instance, rlm, ses,
-                                 lifetime, kvno, tkt, t_local.tv_sec))
-       return(kerror);
-
-    return(INTK_OK);
-}
-
-#endif /* UAM_AFSKRB */
diff --git a/etc/uams/uams_krb4/lifetime.c b/etc/uams/uams_krb4/lifetime.c
deleted file mode 100644 (file)
index 428eac9..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * $Id: lifetime.c,v 1.3 2001-06-25 20:13:45 rufustfirefly Exp $
- *
- * Ticket lifetime.  This defines the table used to lookup lifetime
- * for the fixed part of rande of the one byte lifetime field.  Values
- * less than 0x80 are intrpreted as the number of 5 minute intervals.
- * Values from 0x80 to 0xBF should be looked up in this table.  The
- * value of 0x80 is the same using both methods: 10 and two-thirds
- * hours .  The lifetime of 0xBF is 30 days.  The intervening values
- * of have a fixed ratio of roughly 1.06914.  The value 0xFF is
- * defined to mean a ticket has no expiration time.  This should be
- * used advisedly since individual servers may impose defacto
- * upperbounds on ticket lifetimes.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <netatalk/endian.h>
-
-#define TKTLIFENUMFIXED 64
-#define TKTLIFEMINFIXED 0x80
-#define TKTLIFEMAXFIXED 0xBF
-#define TKTLIFENOEXPIRE 0xFF
-#define MAXTKTLIFETIME (30*24*3600)    /* 30 days */
-#ifndef NEVERDATE
-#define NEVERDATE ((u_int32_t)-1L)
-#endif /* NEVERDATE */
-
-static int tkt_lifetimes[TKTLIFENUMFIXED] = {
-    38400,                             /* 10.67 hours, 0.44 days */ 
-    41055,                             /* 11.40 hours, 0.48 days */ 
-    43894,                             /* 12.19 hours, 0.51 days */ 
-    46929,                             /* 13.04 hours, 0.54 days */ 
-    50174,                             /* 13.94 hours, 0.58 days */ 
-    53643,                             /* 14.90 hours, 0.62 days */ 
-    57352,                             /* 15.93 hours, 0.66 days */ 
-    61318,                             /* 17.03 hours, 0.71 days */ 
-    65558,                             /* 18.21 hours, 0.76 days */ 
-    70091,                             /* 19.47 hours, 0.81 days */ 
-    74937,                             /* 20.82 hours, 0.87 days */ 
-    80119,                             /* 22.26 hours, 0.93 days */ 
-    85658,                             /* 23.79 hours, 0.99 days */ 
-    91581,                             /* 25.44 hours, 1.06 days */ 
-    97914,                             /* 27.20 hours, 1.13 days */ 
-    104684,                            /* 29.08 hours, 1.21 days */ 
-    111922,                            /* 31.09 hours, 1.30 days */ 
-    119661,                            /* 33.24 hours, 1.38 days */ 
-    127935,                            /* 35.54 hours, 1.48 days */ 
-    136781,                            /* 37.99 hours, 1.58 days */ 
-    146239,                            /* 40.62 hours, 1.69 days */ 
-    156350,                            /* 43.43 hours, 1.81 days */ 
-    167161,                            /* 46.43 hours, 1.93 days */ 
-    178720,                            /* 49.64 hours, 2.07 days */ 
-    191077,                            /* 53.08 hours, 2.21 days */ 
-    204289,                            /* 56.75 hours, 2.36 days */ 
-    218415,                            /* 60.67 hours, 2.53 days */ 
-    233517,                            /* 64.87 hours, 2.70 days */ 
-    249664,                            /* 69.35 hours, 2.89 days */ 
-    266926,                            /* 74.15 hours, 3.09 days */ 
-    285383,                            /* 79.27 hours, 3.30 days */ 
-    305116,                            /* 84.75 hours, 3.53 days */ 
-    326213,                            /* 90.61 hours, 3.78 days */ 
-    348769,                            /* 96.88 hours, 4.04 days */ 
-    372885,                            /* 103.58 hours, 4.32 days */ 
-    398668,                            /* 110.74 hours, 4.61 days */ 
-    426234,                            /* 118.40 hours, 4.93 days */ 
-    455705,                            /* 126.58 hours, 5.27 days */ 
-    487215,                            /* 135.34 hours, 5.64 days */ 
-    520904,                            /* 144.70 hours, 6.03 days */ 
-    556921,                            /* 154.70 hours, 6.45 days */ 
-    595430,                            /* 165.40 hours, 6.89 days */ 
-    636601,                            /* 176.83 hours, 7.37 days */ 
-    680618,                            /* 189.06 hours, 7.88 days */ 
-    727680,                            /* 202.13 hours, 8.42 days */ 
-    777995,                            /* 216.11 hours, 9.00 days */ 
-    831789,                            /* 231.05 hours, 9.63 days */ 
-    889303,                            /* 247.03 hours, 10.29 days */ 
-    950794,                            /* 264.11 hours, 11.00 days */ 
-    1016537,                           /* 282.37 hours, 11.77 days */ 
-    1086825,                           /* 301.90 hours, 12.58 days */ 
-    1161973,                           /* 322.77 hours, 13.45 days */ 
-    1242318,                           /* 345.09 hours, 14.38 days */ 
-    1328218,                           /* 368.95 hours, 15.37 days */ 
-    1420057,                           /* 394.46 hours, 16.44 days */ 
-    1518247,                           /* 421.74 hours, 17.57 days */ 
-    1623226,                           /* 450.90 hours, 18.79 days */ 
-    1735464,                           /* 482.07 hours, 20.09 days */ 
-    1855462,                           /* 515.41 hours, 21.48 days */ 
-    1983758,                           /* 551.04 hours, 22.96 days */ 
-    2120925,                           /* 589.15 hours, 24.55 days */ 
-    2267576,                           /* 629.88 hours, 26.25 days */ 
-    2424367,                           /* 673.44 hours, 28.06 days */ 
-    2592000};                          /* 720.00 hours, 30.00 days */ 
-
-/*
- * krb_life_to_time - takes a start time and a Kerberos standard
- * lifetime char and returns the corresponding end time.  There are
- * four simple cases to be handled.  The first is a life of 0xff,
- * meaning no expiration, and results in an end time of 0xffffffff.
- * The second is when life is less than the values covered by the
- * table.  In this case, the end time is the start time plus the
- * number of 5 minute intervals specified by life.  The third case
- * returns start plus the MAXTKTLIFETIME if life is greater than
- * TKTLIFEMAXFIXED.  The last case, uses the life value (minus
- * TKTLIFEMINFIXED) as an index into the table to extract the lifetime
- * in seconds, which is added to start to produce the end time.
- */
-u_int32_t krb_life_to_time(start, life)
-u_int32_t start;
-int life;
-{
-    life = (unsigned char) life;
-    if (life == TKTLIFENOEXPIRE) return NEVERDATE;
-    if (life < TKTLIFEMINFIXED) return start + life*5*60;
-    if (life > TKTLIFEMAXFIXED) return start + MAXTKTLIFETIME;
-    return start + tkt_lifetimes[life - TKTLIFEMINFIXED];
-}
-
-/*
- * krb_time_to_life - takes start and end times for the ticket and
- * returns a Kerberos standard lifetime char, possibily using the
- * tkt_lifetimes table for lifetimes above 127*5 minutes.  First, the
- * special case of (end == NEVERDATE) is handled to mean no
- * expiration.  Then negative lifetimes and those greater than the
- * maximum ticket lifetime are rejected.  Then lifetimes less than the
- * first table entry are handled by rounding the requested lifetime
- * *up* to the next 5 minute interval.  The final step is to search
- * the table for the smallest entry *greater than or equal* to the
- * requested entry.
- */
-int krb_time_to_life(start, end)
-u_int32_t start;
-u_int32_t end;
-{
-    int32_t lifetime;
-    int i;
-
-    if (end == NEVERDATE) return TKTLIFENOEXPIRE;
-    lifetime = end - start;
-    if (lifetime > MAXTKTLIFETIME || lifetime <= 0) return 0;
-    if (lifetime < tkt_lifetimes[0]) return (lifetime + 5*60 - 1)/(5*60);
-    for (i=0; i<TKTLIFENUMFIXED; i++) {
-       if (lifetime <= tkt_lifetimes[i]) {
-           return i+TKTLIFEMINFIXED;
-       }
-    }
-    return 0;
-}
diff --git a/etc/uams/uams_krb4/send_to_kdc.c b/etc/uams/uams_krb4/send_to_kdc.c
deleted file mode 100644 (file)
index d20856f..0000000
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * $Id: send_to_kdc.c,v 1.4 2001-06-25 20:13:45 rufustfirefly Exp $
- * $Author: rufustfirefly $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- *
- * $Source: /home/ralph/netatalk/rsync/netatalk/etc/uams/uams_krb4/send_to_kdc.c,v $
- *
- * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
- *
- * For copying and distribution information, please see the file
- * <mit-copyright.h>.
- */
-
-#ifndef lint
-static char rcsid_send_to_kdc_c[] =
-"$Id: send_to_kdc.c,v 1.4 2001-06-25 20:13:45 rufustfirefly Exp $";
-#endif /* lint */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifdef UAM_AFSKRB
-
-#include <mit-copyright.h>
-
-#include <krb.h>
-#include <prot.h>
-
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#ifdef lint
-#include <sys/uio.h>            /* struct iovec to make lint happy */
-#endif /* lint */
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netdb.h>
-#include <string.h>
-
-#define S_AD_SZ sizeof(struct sockaddr_in)
-
-extern int krb_debug;
-
-extern char *malloc(), *calloc(), *realloc();
-
-int krb_udp_port = 0;
-
-/* CLIENT_KRB_TIMEOUT indicates the time to wait before
- * retrying a server.  It's defined in "krb.h".
- */
-static struct timeval timeout = { CLIENT_KRB_TIMEOUT, 0};
-static char *prog = "send_to_kdc";
-static send_recv();
-
-/*
- * This file contains two routines, send_to_kdc() and send_recv().
- * send_recv() is a static routine used by send_to_kdc().
- */
-
-/*
- * send_to_kdc() sends a message to the Kerberos authentication
- * server(s) in the given realm and returns the reply message.
- * The "pkt" argument points to the message to be sent to Kerberos;
- * the "rpkt" argument will be filled in with Kerberos' reply.
- * The "realm" argument indicates the realm of the Kerberos server(s)
- * to transact with.  If the realm is null, the local realm is used.
- *
- * If more than one Kerberos server is known for a given realm,
- * different servers will be queried until one of them replies.
- * Several attempts (retries) are made for each server before
- * giving up entirely.
- *
- * If an answer was received from a Kerberos host, KSUCCESS is
- * returned.  The following errors can be returned:
- *
- * SKDC_CANT    - can't get local realm
- *              - can't find "kerberos" in /etc/services database
- *              - can't open socket
- *              - can't bind socket
- *              - all ports in use
- *              - couldn't find any Kerberos host
- *
- * SKDC_RETRY   - couldn't get an answer from any Kerberos server,
- *               after several retries
- */
-
-send_to_kdc(pkt,rpkt,realm)
-    KTEXT pkt;
-    KTEXT rpkt;
-    char *realm;
-{
-    int i, f;
-    int no_host; /* was a kerberos host found? */
-    int retry;
-    int n_hosts;
-    int retval;
-    struct sockaddr_in to;
-    struct hostent *host, *hostlist;
-    char *cp;
-    char krbhst[MAX_HSTNM];
-    char lrealm[REALM_SZ];
-
-    /*
-     * If "realm" is non-null, use that, otherwise get the
-     * local realm.
-     */
-    if (realm)
-       (void) strcpy(lrealm, realm);
-    else
-       if (krb_get_lrealm(lrealm,1)) {
-           if (krb_debug)
-               fprintf(stderr, "%s: can't get local realm\n", prog);
-           return(SKDC_CANT);
-       }
-    if (krb_debug)
-        printf("lrealm is %s\n", lrealm);
-    if (krb_udp_port == 0) {
-        register struct servent *sp;
-        if ((sp = getservbyname("kerberos","udp")) == 0) {
-            if (krb_debug)
-                fprintf(stderr, "%s: Can't get kerberos/udp service\n",
-                        prog);
-            return(SKDC_CANT);
-        }
-        krb_udp_port = sp->s_port;
-        if (krb_debug)
-            printf("krb_udp_port is %d\n", krb_udp_port);
-    }
-    memset(&to, 0, S_AD_SZ);
-    hostlist = (struct hostent *) malloc(sizeof(struct hostent));
-    if (!hostlist)
-        return (/*errno */SKDC_CANT);
-    if ((f = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-        if (krb_debug)
-            fprintf(stderr,"%s: Can't open socket\n", prog);
-        return(SKDC_CANT);
-    }
-    /* from now on, exit through rtn label for cleanup */
-
-    no_host = 1;
-    /* get an initial allocation */
-    n_hosts = 0;
-    for (i = 1; krb_get_krbhst(krbhst, lrealm, i) == KSUCCESS; ++i) {
-        if (krb_debug) {
-            printf("Getting host entry for %s...",krbhst);
-            (void) fflush(stdout);
-        }
-        host = gethostbyname(krbhst);
-        if (krb_debug) {
-            printf("%s.\n",
-                   host ? "Got it" : "Didn't get it");
-            (void) fflush(stdout);
-        }
-        if (!host)
-            continue;
-        no_host = 0;    /* found at least one */
-        n_hosts++;
-        /* preserve host network address to check later
-         * (would be better to preserve *all* addresses,
-         * take care of that later)
-         */
-        hostlist = (struct hostent *)
-            realloc((char *)hostlist,
-                    (unsigned)
-                    sizeof(struct hostent)*(n_hosts+1));
-        if (!hostlist)
-            return /*errno */SKDC_CANT;
-        memcpy(&hostlist[n_hosts-1], host, sizeof(struct hostent));
-        host = &hostlist[n_hosts-1];
-        cp = malloc((unsigned)host->h_length);
-        if (!cp) {
-            retval = /*errno */SKDC_CANT;
-            goto rtn;
-        }
-        memcpy(cp, host->h_addr, host->h_length);
-/* At least Sun OS version 3.2 (or worse) and Ultrix version 2.2
-   (or worse) only return one name ... */
-#if !(defined(ULTRIX022) || (defined(SunOS) && SunOS < 40))
-        host->h_addr_list = (char **)malloc(sizeof(char *));
-        if (!host->h_addr_list) {
-            retval = /*errno */SKDC_CANT;
-            goto rtn;
-        }
-#endif /* ULTRIX022 || SunOS */
-        host->h_addr = cp;
-        memset(&hostlist[n_hosts], 0, sizeof(struct hostent));
-        to.sin_family = host->h_addrtype;
-        memcpy(&to.sin_addr, host->h_addr, host->h_length);
-        to.sin_port = krb_udp_port;
-        if (send_recv(pkt, rpkt, f, &to, hostlist)) {
-            retval = KSUCCESS;
-            goto rtn;
-        }
-        if (krb_debug) {
-            printf("Timeout, error, or wrong descriptor\n");
-            (void) fflush(stdout);
-        }
-    }
-    if (no_host) {
-       if (krb_debug)
-           fprintf(stderr, "%s: can't find any Kerberos host.\n",
-                   prog);
-        retval = SKDC_CANT;
-        goto rtn;
-    }
-    /* retry each host in sequence */
-    for (retry = 0; retry < CLIENT_KRB_RETRY; ++retry) {
-        for (host = hostlist; host->h_name != (char *)NULL; host++) {
-            to.sin_family = host->h_addrtype;
-            memcpy(&to.sin_addr, host->h_addr, host->h_length);
-            if (send_recv(pkt, rpkt, f, &to, hostlist)) {
-                retval = KSUCCESS;
-                goto rtn;
-            }
-        }
-    }
-    retval = SKDC_RETRY;
-rtn:
-    (void) close(f);
-    if (hostlist) {
-        register struct hostent *hp;
-        for (hp = hostlist; hp->h_name; hp++)
-#if !(defined(ULTRIX022) || (defined(SunOS) && SunOS < 40))
-            if (hp->h_addr_list) {
-#endif /* ULTRIX022 || SunOS */
-                if (hp->h_addr)
-                    free(hp->h_addr);
-#if !(defined(ULTRIX022) || (defined(SunOS) && SunOS < 40))
-                free((char *)hp->h_addr_list);
-            }
-#endif /* ULTRIX022 || SunOS */
-        free((char *)hostlist);
-    }
-    return(retval);
-}
-
-/*
- * try to send out and receive message.
- * return 1 on success, 0 on failure
- */
-
-static send_recv(pkt,rpkt,f,_to,addrs)
-    KTEXT pkt;
-    KTEXT rpkt;
-    int f;
-    struct sockaddr_in *_to;
-    struct hostent *addrs;
-{
-    fd_set readfds;
-    register struct hostent *hp;
-    struct sockaddr_in from;
-    int sin_size, rc;
-    int numsent;
-
-    if (krb_debug) {
-        if (_to->sin_family == AF_INET)
-            printf("Sending message to %s...",
-                   inet_ntoa(_to->sin_addr));
-        else
-            printf("Sending message...");
-        (void) fflush(stdout);
-    }
-    if ((numsent = sendto(f,(char *)(pkt->dat), pkt->length, 0, 
-                         (struct sockaddr *)_to,
-                          S_AD_SZ)) != pkt->length) {
-        if (krb_debug)
-            printf("sent only %d/%d\n",numsent, pkt->length);
-        return 0;
-    }
-    if (krb_debug) {
-        printf("Sent\nWaiting for reply...");
-        (void) fflush(stdout);
-    }
-    FD_ZERO(&readfds);
-    FD_SET(f, &readfds);
-    errno = 0;
-    /* select - either recv is ready, or timeout */
-    /* see if timeout or error or wrong descriptor */
-    if (select(f + 1, &readfds, (fd_set *)0, (fd_set *)0, &timeout) < 1
-        || !FD_ISSET(f, &readfds)) {
-        if (krb_debug) {
-            fprintf(stderr, "select failed: readfds=%x",
-                    readfds);
-            perror("");
-        }
-        return 0;
-    }
-    sin_size = sizeof(from);
-    if (( rc = recvfrom(f, (char *)(rpkt->dat), sizeof(rpkt->dat), 0,
-                (struct sockaddr *)&from, &sin_size)) < 0) {
-        if (krb_debug)
-            perror("recvfrom");
-        return 0;
-    }
-    rpkt->length = rc;
-    if (krb_debug) {
-        printf("received packet from %s\n", inet_ntoa(from.sin_addr));
-        fflush(stdout);
-    }
-    for (hp = addrs; hp->h_name != (char *)NULL; hp++) {
-        if (!memcmp(hp->h_addr, (char *)&from.sin_addr.s_addr,
-                  hp->h_length)) {
-            if (krb_debug) {
-                printf("Received it\n");
-                (void) fflush(stdout);
-            }
-            return 1;
-        }
-        if (krb_debug)
-            fprintf(stderr,
-                    "packet not from %x\n",
-                    hp->h_addr);
-    }
-    if (krb_debug)
-        fprintf(stderr, "%s: received packet from wrong host! (%x)\n",
-                "send_to_kdc(send_rcv)", from.sin_addr.s_addr);
-    return 0;
-}
-
-#endif /* UAM_AFSKRB */
diff --git a/etc/uams/uams_krb4/uams_krb4.c b/etc/uams/uams_krb4/uams_krb4.c
deleted file mode 100644 (file)
index ff7c2c0..0000000
+++ /dev/null
@@ -1,799 +0,0 @@
-/*
- * $Id: uams_krb4.c,v 1.10 2009-10-15 11:39:48 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#if defined( KRB ) || defined( UAM_AFSKRB )
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/stat.h>
-#include <sys/socket.h>
-#include <limits.h>
-
-/* STDC check */
-#if STDC_HEADERS
-#include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#include <ctype.h>
-#include <pwd.h>
-#include <atalk/logger.h>
-#include <netinet/in.h>
-#include <des.h>
-#include <krb.h>
-#if 0
-#include <prot.h>
-#endif /* 0 */
-
-#include <netatalk/endian.h>
-#include <atalk/afp.h>
-#include <atalk/compat.h>
-#include <atalk/util.h>
-#include <atalk/uam.h>
-
-static C_Block                 seskey;
-static Key_schedule            seskeysched;
-
-static char            realm[ REALM_SZ ];
-
-#ifdef UAM_AFSKRB
-static int             validseskey = 0;
-static int             logged = 0;
-static char            *tktfile;
-static char            instance[ INST_SZ ], name[ ANAME_SZ ];
-#endif /* UAM_AFSKRB */
-
-#ifdef AFS
-#include <afs/stds.h>
-#include <rx/rxkad.h>
-#include <afs/afs.h>
-#include <afs/venus.h>
-#include <afs/afsint.h>
-
-char *ka_LocalCell();
-
-struct ClearToken {
-    int32_t AuthHandle;
-    char HandShakeKey[8];
-    int32_t ViceId;
-    int32_t BeginTimestamp;
-    int32_t EndTimestamp;
-};
-#endif /* AFS */
-
-
-#ifdef KRB
-
-static void lcase( p )
-    char       *p;
-{
-    for (; *p; p++ ) {
-       if ( isupper( *p )) {
-           *p = tolower( *p );
-       }
-    }
-    return;
-}
-
-static void ucase( p )
-    char       *p;
-{
-    for (; *p; p++ ) {
-       if ( islower( *p )) {
-           *p = toupper( *p );
-       }
-    }
-    return;
-}
-
-#define KRB4CMD_HELO   1
-#define KRB4RPL_REALM  2
-#define KRB4WRT_SESS   3
-#define KRB4RPL_DONE   4
-#define KRB4RPL_PRINC  5
-#define KRB4WRT_TOKEN  6
-#define KRB4WRT_SKIP   7
-#define KRB4RPL_DONEMUT        8
-#define KRB4CMD_SESS   9
-#define KRB4CMD_TOKEN  10
-#define KRB4CMD_SKIP   11
-
-static int krb4_login(void *obj, struct passwd **uam_pwd,
-                     char *ibuf, size_t ibuflen,
-                     char *rbuf, size_t *rbuflen )
-{
-    char               *p;
-    char               *username;
-    struct passwd      *pwd;
-    u_int16_t          len;
-    KTEXT_ST           tkt;
-    static AUTH_DAT    ad;
-    int                        rc, proto;
-    size_t             ulen;
-    char               inst[ 40 ], princ[ 40 ];
-
-    if (uam_afpserver_option(obj, UAM_OPTION_USERNAME, &username, &ulen) < 0)
-      return AFPERR_MISC;
-
-    if (uam_afpserver_option(obj, UAM_OPTION_PROTOCOL, &proto, NULL) < 0)
-      return AFPERR_MISC;
-
-    switch( *ibuf ) {
-       case KRB4CMD_SESS:
-           LOG(log_info, logtype_default, "krb4_login: KRB4CMD_SESS" );
-           ++ibuf;
-           p = ibuf;
-           memcpy( &len, p, sizeof( u_int16_t ));
-           tkt.length = ntohs( len );
-           p += sizeof( u_int16_t );
-
-           if ( tkt.length <= 0 || tkt.length > MAX_KTXT_LEN ) {
-               *rbuflen = 0;
-               LOG(log_info, logtype_default, "krb4_login: tkt.length = %d", tkt.length );
-               return( AFPERR_BADUAM );
-           }
-
-           memcpy( tkt.dat, p, tkt.length );
-           p += tkt.length;
-
-           strcpy( inst, "*" );
-
-           switch( proto ) {
-               case AFPPROTO_ASP:
-                   strcpy( princ, "afpserver" );
-                   break;
-               case AFPPROTO_DSI:
-                   strcpy( princ, "rcmd" );
-                   break;
-           }
-
-           if( (rc = krb_rd_req( &tkt, princ, inst, 0, &ad, "" )) 
-               != RD_AP_OK ) {
-               LOG(log_error, logtype_default, 
-                       "krb4_login: krb_rd_req(): %s", krb_err_txt[ rc ] );
-               *rbuflen = 0;
-               return( AFPERR_BADUAM );
-           }
-
-           LOG(log_info, logtype_default, "krb4_login: %s.%s@%s", ad.pname, ad.pinst, 
-               ad.prealm );
-           strcpy( realm, ad.prealm );
-           memcpy( seskey, ad.session, sizeof( C_Block ) );
-           key_sched( (C_Block *)seskey, seskeysched );
-
-           strncpy( username, ad.pname, ulen );
-
-           p = rbuf;
-
-#ifdef AFS
-           *p = KRB4RPL_DONE;  /* XXX */
-           *rbuflen = 1;
-
-           if (( pwd = uam_getname( obj, ad.pname, strlen(ad.pname) )) == NULL ) {
-               return AFPERR_PARAM;
-           }
-/*
-           if (uam_checkuser( pwd ) < 0) {
-               return AFPERR_NOTAUTH;
-           }
-*/
-           *uam_pwd = pwd;
-           return( AFP_OK ); /* Should this be AFPERR_AUTHCONT? */
-#else /* AFS */
-           /* get principals */
-           *p++ = KRB4RPL_PRINC;
-           len = strlen( realm );
-           *p++ = len + 1;
-           *p++ = '@';
-           strcpy( p, realm );
-           p += len + 1;
-           break;
-#endif /* AFS */
-       case KRB4CMD_HELO:
-           p = rbuf;
-           if (krb_get_lrealm( realm, 1 ) != KSUCCESS ) {
-               LOG(log_error, logtype_default, "krb4_login: can't get local realm!" );
-               return( AFPERR_NOTAUTH );
-           }
-           *p++ = KRB4RPL_REALM;
-           *p++ = 1;
-           len = strlen( realm );
-           *p++ = len;
-           strcpy( p, realm );
-           p += len + 1;
-           break;
-
-       default:
-           *rbuflen = 0;
-           LOG(log_info, logtype_default, "krb4_login: bad command %d", *ibuf );
-           return( AFPERR_NOTAUTH );
-    }
-
-#ifdef AFS
-    if ( setpag() < 0 ) {
-       *rbuflen = 0;
-       LOG(log_error, logtype_default, "krb_login: setpag: %s", strerror(errno) );
-       return( AFPERR_BADUAM );
-    }
-#endif /*AFS*/
-
-    *rbuflen = p - rbuf;
-    return( AFPERR_AUTHCONT );
-}
-
-static int krb4_action( void *v1, void *v2, const int i )
-{
-       return i;
-}
-
-/*
-   I have a hunch that problems might arise on platforms 
-   with non-16bit short's and non-32bit int's
-*/
-static int krb4_logincont(void *obj, struct passwd **uam_pwd,
-                         char *ibuf, size_t ibuflen,
-                         char *rbuf, size_t *rbuflen)
-{
-    static struct passwd       *pwd;
-    KTEXT_ST           tkt;
-    static AUTH_DAT    ad;
-    int                        rc;
-    u_int16_t          len;
-    char               *p, *username, *servername;
-    CREDENTIALS                cr;
-#ifdef AFS
-    struct ViceIoctl   vi;
-    struct ClearToken  ct;
-#endif /* AFS */
-    char               buf[ 1024 ];
-    int                        aint, ulen, snlen;
-
-    if (uam_afpserver_option(obj, UAM_OPTION_USERNAME, &username, &ulen) < 0)
-      return AFPERR_MISC;
-
-    if (uam_afpserver_option(obj, UAM_OPTION_HOSTNAME, &servername, &snlen) < 0)
-      return AFPERR_MISC;
-
-    ibuf++;
-    switch ( rc = *ibuf++ ) {
-       case KRB4CMD_TOKEN :
-#ifdef AFS
-           p = buf;
-           memcpy( &len, ibuf, sizeof( u_int16_t ) );
-           ibuf += sizeof( len );
-           len = ntohs( len );
-           aint = len;
-           memcpy( p, &aint, sizeof( int ) );
-           p += sizeof( int );
-           memcpy( p, ibuf, len );
-           pcbc_encrypt( (C_Block *)p, (C_Block *)p, len, seskeysched,
-               seskey, DECRYPT );
-           p += len;
-           ibuf += len;
-
-           memcpy( &len, ibuf, sizeof( u_int16_t ) );
-           ibuf += sizeof( u_int16_t ) );
-           len = ntohs( len );
-
-           if ( len != sizeof( struct ClearToken ) ) {
-               LOG(log_error, logtype_default, "krb4_logincont: token too short" );
-               *rbuflen = 0;
-               return( AFPERR_BADUAM );
-           }
-           memcpy( &ct, ibuf, len );
-
-           pcbc_encrypt( (C_Block *)&ct, (C_Block *)&ct, len, 
-               seskeysched, seskey, DECRYPT );
-
-           aint = sizeof( struct ClearToken );
-           memcpy( p, &aint, sizeof( int ) );
-           p += sizeof( int );
-           memcpy( p, &ct, sizeof( struct ClearToken ) );
-           p += sizeof( struct ClearToken );
-
-           aint = 0;
-           memcpy( p, &aint, sizeof( int ) );
-           p += sizeof( int );
-
-           lcase( realm );
-           strcpy( p, realm );
-           p += strlen( realm ) + 1;
-
-           vi.in = buf;
-           vi.in_size = p - buf;
-           vi.out = buf;
-           vi.out_size = sizeof( buf );
-
-           if ( pioctl( 0, VIOCSETTOK, &vi, 0 ) < 0 ) {
-               LOG(log_error, logtype_default, "krb4_logincont: pioctl: %s", strerror(errno) );
-               *rbuflen = 0;
-               return( AFPERR_BADUAM );
-           }
-           /* FALL THROUGH */
-
-       case KRB4CMD_SKIP:
-           p = rbuf;
-           *p = KRB4RPL_DONE;  /* XXX */
-           *rbuflen = 1;
-
-           if (( pwd = uam_getname( obj, username, strlen(username) ) ) == NULL ) {
-               return( AFPERR_NOTAUTH );
-           }
-/*
-           if (uam_checkuser(pwd) < 0) {
-               return AFPERR_NOTAUTH;
-           }
-*/
-           *uam_pwd = pwd;
-           return( AFP_OK );
-#endif /* AFS */
-       default:
-           /* read in the rest */
-           if (uam_afp_read(obj, rbuf, rbuflen, krb4_action) < 0)
-               return AFPERR_PARAM;
-
-           p = rbuf;
-           switch ( rc = *p++ ) {
-               case KRB4WRT_SESS :
-                   memcpy( &len, p, sizeof( len ));
-                   tkt.length = ntohs( len );
-                   p += sizeof( short );
-
-                   if ( tkt.length <= 0 || tkt.length > MAX_KTXT_LEN ) {
-                       return( AFPERR_BADUAM );
-                   }
-                   memcpy( tkt.dat, p, tkt.length );
-                   p += tkt.length;
-
-                   if (( rc = krb_rd_req( &tkt, "afpserver", servername, 
-                       0, &ad, "" )) != RD_AP_OK ) {
-                       LOG(log_error, logtype_default, "krb4_logincont: krb_rd_req(): %s", krb_err_txt[ rc ] );
-                       return( AFPERR_BADUAM );
-                   }
-
-                   LOG(log_info, logtype_default, "krb4_login: %s.%s@%s", ad.pname, 
-                       ad.pinst, ad.prealm );
-                   memcpy(realm, ad.prealm, sizeof(realm));
-                   memcpy(seskey, ad.session, sizeof( C_Block ));
-                   key_sched((C_Block *) seskey, seskeysched );
-
-                   strncpy(username, ad.pname, ulen);
-
-                   p = rbuf;
-#ifndef AFS
-                   *p = KRB4RPL_DONE;  /* XXX */
-                   *rbuflen = 1;
-
-                   if (( pwd = uam_getname( obj, ad.pname, strlen(ad.pname) )) 
-                       == NULL ) {
-                       return( AFPERR_PARAM );
-                   }
-                   *uam_pwd = pwd;
-                   return AFP_OK;
-#else /* ! AFS */
-                   /* get principals */
-                   *p++ = KRB4RPL_PRINC;
-                   len = strlen( realm );
-                   *p++ = len + 1;
-                   *p++ = '@';
-                   strcpy( p, realm );
-                   p += len + 1;
-                   *rbuflen = p - rbuf;
-                   return( AFPERR_AUTHCONT );
-
-               case KRB4WRT_TOKEN :
-                   memcpy( &len, p, sizeof( len ));
-                   len = ntohs( len );
-                   p += sizeof( len );
-                   memcpy( &cr, p, len );
-
-                   pcbc_encrypt((C_Block *)&cr, (C_Block *)&cr, len, 
-                       seskeysched, seskey, DES_DECRYPT );
-
-                   p = buf;
-                   cr.ticket_st.length = ntohl( cr.ticket_st.length );
-                   memcpy( p, &cr.ticket_st.length, sizeof( int ));
-                   p += sizeof( int );
-                   memcpy( p, cr.ticket_st.dat, cr.ticket_st.length );
-                   p += cr.ticket_st.length;
-
-                   ct.AuthHandle = ntohl( cr.kvno );
-                   memcpy( ct.HandShakeKey, cr.session, sizeof( cr.session ));
-                   ct.ViceId = 0;
-                   ct.BeginTimestamp = ntohl( cr.issue_date );
-                   ct.EndTimestamp = krb_life_to_time( ntohl( cr.issue_date ),
-                   ntohl( cr.lifetime ));
-
-                   aint = sizeof( struct ClearToken );
-                   memcpy( p, &aint, sizeof( int ));
-                   p += sizeof( int );
-                   memcpy( p, &ct, sizeof( struct ClearToken ));
-                   p += sizeof( struct ClearToken );
-
-                   aint = 0;
-                   memcpy( p, &aint, sizeof( int ));
-                   p += sizeof( int );
-
-                   lcase( realm );
-                   strcpy( p, realm );
-                   p += strlen( realm ) + 1;
-
-                   vi.in = buf;
-                   vi.in_size = p - buf;
-                   vi.out = buf;
-                   vi.out_size = sizeof( buf );
-                   if ( pioctl( 0, VIOCSETTOK, &vi, 0 ) < 0 ) {
-                       LOG(log_error, logtype_default, "krb4_logincont: pioctl: %s", strerror(errno) );
-                       return( AFPERR_BADUAM );
-                   }
-                   /* FALL THROUGH */
-
-               case KRB4WRT_SKIP :
-                   p = rbuf;
-                   *p = KRB4RPL_DONE;  /* XXX */
-                   *rbuflen = 1;
-
-                   if (( pwd = uam_getname( obj, ad.pname, strlen(ad.pname) )) 
-                       == NULL ) {
-                       return( AFPERR_PARAM );
-                   }
-                   *uam_pwd = pwd;
-                   return AFP_OK;
-#endif /*AFS*/
-
-               default:
-                   LOG(log_info, logtype_default, "krb4_logincont: bad command %d", rc );
-                   *rbuflen = 0;
-                   return( AFPERR_NOTAUTH );
-                   break;
-           }
-           break;
-    }
-}
-
-#endif /* KRB */
-
-
-#ifdef AFS
-#include <rx/rxkad.h>
-#include <afs/afsint.h>
-
-char *ka_LocalCell();
-
-static void
-addrealm(realm,cells)
-    char *realm;
-       char ***cells;
-{
-    char **ptr;
-       int temp;
-
-       ptr= *cells;
-
-    for(;*ptr != 0 ;ptr++)
-        if(!strcmp(realm,*ptr))
-            return;
-
-       temp=ptr- *cells;
-       *cells=(char**)realloc(*cells,((2+temp)*sizeof(char*)));
-       ptr= *cells+temp;
-
-    *ptr=(char*)malloc(strlen(realm)+1);
-    strcpy(*ptr++,realm);
-       *ptr=0;
-    return;
-}
-
-static int kcheckuser(pwd,passwd)
-       struct passwd *pwd;
-       char *passwd;
-{
-       int32_t code;
-       char *instance="";
-       char realm[MAXKTCREALMLEN];
-       char lorealm[MAXKTCREALMLEN];
-       char *cell;
-       Date lifetime=MAXKTCTICKETLIFETIME;
-       int rval;
-       char **cells=(char **)malloc(sizeof(char*));
-       char *temp;
-       int rc,cellNum;
-       struct ktc_principal serviceName;
-
-       *cells=0;
-
-       code = ka_Init(0);
-
-       {
-               char *temp,*temp1;
-               temp=(char*)malloc(strlen(pwd->pw_dir)+1);
-               strcpy(temp,pwd->pw_dir);
-               temp1=temp;
-               temp=strtok(temp,"/");
-               temp=strtok('\0',"/");
-               ka_CellToRealm(temp,realm,0);
-               addrealm(realm,&cells);
-               free(temp1);
-       }
-
-       setpag();
-       authenticate(cells,pwd->pw_name,passwd);
-       cellNum=0;
-       rc=ktc_ListTokens(cellNum,&cellNum,&serviceName);
-       if(rc)
-               rval=1;
-       else{
-               rval=0;
-       }
-
-       return(rval);
-}
-
-static void authenticate(cells,name,passwd)
-       char **cells;
-       char *name;
-       char *passwd;
-{
-       char **ptr=cells;
-       char *errorstring;
-
-       while(*ptr){
-           ka_UserAuthenticate(name,/*instance*/"",/*cell*/*ptr++,
-                   passwd,/*setpag*/0,&errorstring);
-       }
-}
-#endif /* AFS */
-
-#if defined( UAM_AFSKRB ) && defined( AFS )
-static int afskrb_login(void *obj, struct passwd *uam_pwd,
-                       char *ibuf, size_t ibuflen, 
-                       char *rbuf, size_t *rbuflen )
-{
-    KTEXT_ST   authent, rpkt;
-    CREDENTIALS        cr;
-    char       *p, *q, *username, servername;
-    int                len, rc, whoserealm, ulen, snlen;
-    short      slen;
-
-    *rbuflen = 0;
-    if (uam_afpserver_option(obj, UAM_OPTION_USERNAME, &username, &ulen) < 0)
-      return AFPERR_MISC;
-
-    if (uam_afpserver_option(obj, UAM_OPTION_HOSTNAME, &servername, &snlen ) < 0)
-      return AFPERR_MISC;
-    
-    len = (unsigned char) *ibuf++;
-    ibuf[ len ] = '\0';
-    if (( p = strchr( ibuf, '@' )) != NULL ) {
-       *p++ = '\0';
-       strcpy( realm, p );
-       ucase( realm );
-       whoserealm = 0;
-    } else {
-       if ( krb_get_lrealm( realm, 1 ) != KSUCCESS ) {
-           return AFPERR_BADUAM;
-       }
-       whoserealm = 1;
-    }
-    if (( p = strchr( ibuf, '.' )) != NULL ) {
-       *p++ = '\0';
-       strcpy( instance, p );
-    } else {
-       *instance = '\0';
-    }
-    strcpy( name, ibuf );
-    /*
-     * We don't have the session key, yet. Get one.
-     */
-    p = rbuf;
-    if ( validseskey == 0 ) {
-       if ( setpag() < 0 ) {
-           LOG(log_error, logtype_default, "krb_login: setpag: %s", strerror(errno) );
-           return AFPERR_BADUAM;
-       }
-       krb_set_tkt_string(( tktfile = mktemp( _PATH_AFPTKT )));
-       if (( rc =  krb_get_svc_in_tkt( "afpserver", servername, realm,
-               TICKET_GRANTING_TICKET, realm, 255, KEYFILE )) != INTK_OK ) {
-           LOG(log_error, logtype_default, "krb_login: can't get ticket-granting-ticket" );
-           return (( whoserealm ) ? AFPERR_BADUAM : AFPERR_PARAM );
-       }
-       if ( krb_mk_req( &authent, name, instance, realm, 0 ) != KSUCCESS ) {
-           return ( AFPERR_PARAM );
-       }
-       if ( krb_get_cred( name, instance, realm, &cr ) != KSUCCESS ) {
-           return ( AFPERR_BADUAM );
-       }
-
-       if ( unlink( tktfile ) < 0 ) {
-           LOG(log_error, logtype_default, "krb_login: unlink %s: %s", tktfile, strerror(errno) );
-           return ( AFPERR_BADUAM );
-       }
-
-       memcpy( seskey, cr.session, sizeof( C_Block ));
-       key_sched((C_Block *) seskey, seskeysched );
-       validseskey = 1;
-       strncpy(username, name, ulen);
-
-       memcpy( p, authent.dat, authent.length );
-       p += authent.length;
-    }
-
-    if ( kuam_get_in_tkt( name, instance, realm, TICKET_GRANTING_TICKET,
-           realm, 255, &rpkt ) != INTK_OK ) {
-       return ( AFPERR_PARAM );
-    }
-
-
-    q = (char *)rpkt.dat;
-    *p++ = *q++;
-    *p++ = *q++;
-    while ( *q++ )
-       ;
-    while ( *q++ )
-       ;
-    while ( *q++ )
-       ;
-    q += 10;
-
-    len = strlen( realm );
-    strcpy( p, realm );
-    p += len + 1;
-    memcpy( &slen, q, sizeof( short ));
-    memcpy( p, &slen, sizeof( short ));
-    p += sizeof( short );
-    q += sizeof( short );
-    memcpy( p, q, slen );
-    p += slen;
-
-    *rbuflen = p - rbuf;
-    return( AFPERR_AUTHCONT );
-}
-
-static int afskrb_logincont(void *obj, struct passwd *uam_pwd,
-                           char *ibuf, size_t ibuflen, 
-                           char *rbuf, size_t *rbuflen )
-{
-    CREDENTIALS                cr;
-    struct ViceIoctl   vi;
-    struct ClearToken  ct;
-    struct passwd      *pwd;
-    char               buf[ 1024 ], *p;
-    int                        aint;
-    short              clen;
-
-    *rbuflen = 0;
-    if (uam_afpserver_option(obj, UAM_OPTION_USERNAME, &username, NULL) < 0)
-      return AFPERR_MISC;
-    
-    ibuf += 2;
-    memcpy( &clen, ibuf, sizeof( short ));
-    clen = ntohs( clen );
-    ibuf += sizeof( short );
-
-    pcbc_encrypt((C_Block *)ibuf, (C_Block *)ibuf,
-           clen, seskeysched, seskey, DES_DECRYPT );
-    if ( kuam_set_in_tkt( name, instance, realm, TICKET_GRANTING_TICKET,
-           realm, ibuf ) != INTK_OK ) {
-       return ( AFPERR_PARAM );
-    }
-
-    if ( get_ad_tkt( "afs", "", realm, 255 ) != KSUCCESS ) {
-       return ( AFPERR_PARAM );
-    }
-    if ( krb_get_cred( "afs", "", realm, &cr ) != KSUCCESS ) {
-       return ( AFPERR_PARAM );
-    }
-
-    p = buf;
-    memcpy( p, &cr.ticket_st.length, sizeof( int ));
-    p += sizeof( int );
-    memcpy( p, cr.ticket_st.dat, cr.ticket_st.length );
-    p += cr.ticket_st.length;
-
-    ct.AuthHandle = cr.kvno;
-    memcpy( ct.HandShakeKey, cr.session, sizeof( cr.session ));
-    ct.ViceId = 0;
-    ct.BeginTimestamp = cr.issue_date;
-    /* ct.EndTimestamp = cr.issue_date + ( cr.lifetime * 5 * 60 ); */
-    ct.EndTimestamp = krb_life_to_time( cr.issue_date, cr.lifetime );
-
-    aint = sizeof( struct ClearToken );
-    memcpy( p, &aint, sizeof( int ));
-    p += sizeof( int );
-    memcpy( p, &ct, sizeof( struct ClearToken ));
-    p += sizeof( struct ClearToken );
-
-    aint = 0;
-    memcpy( p, &aint, sizeof( int ));
-    p += sizeof( int );
-
-    lcase( realm );
-    strcpy( p, realm );
-    p += strlen( realm ) + 1;
-
-    vi.in = buf;
-    vi.in_size = p - buf;
-    vi.out = buf;
-    vi.out_size = sizeof( buf );
-    if ( pioctl( 0, VIOCSETTOK, &vi, 0 ) < 0 ) {
-       LOG(log_error, logtype_default, "krb_logincont: pioctl: %s", strerror(errno) );
-       return ( AFPERR_BADUAM );
-    }
-
-    if ( unlink( tktfile ) < 0 ) {
-       LOG(log_error, logtype_default, "krb_logincont: %s: %s", tktfile, strerror(errno) );
-       return ( AFPERR_BADUAM );
-    }
-
-    if (( pwd = uam_getname( obj, username, strlen(username) )) == NULL ) {
-       return ( AFPERR_PARAM );
-    }
-
-    if ( logged == 0 ) {
-       logged = 1;
-       LOG(log_info, logtype_default, "authenticated %s.%s@%s", name, instance, realm );
-       *uam_pwd = pwd;
-       return AFP_OK;
-    }
-    LOG(log_info, logtype_default, "re-authenticated %s.%s@%s", name, instance, realm );
-    return( AFP_OK );
-}
-#endif /* UAM_AFSKRB AFS */
-
-static int uam_setup(const char *path)
-{
-#ifdef KRB
-   uam_register(UAM_SERVER_LOGIN, path, "Kerberos IV", krb4_login, 
-               krb4_logincont, NULL);
-   /* uam_afpserver_action(); */
-#endif /* KRB */
-#ifdef UAM_AFSKRB
-   uam_register(UAM_SERVER_LOGIN, path, "AFS Kerberos", afskrb_login, 
-               afskrb_logincont, NULL);
-   /* uam_afpserver_action(); */
-#endif /* UAM_AFSKRB */
-   return 0;
-}
-
-static void uam_cleanup(void)
-{
-#ifdef KRB
-   /* uam_afpserver_action(); */
-   uam_unregister(UAM_SERVER_LOGIN, "Kerberos IV");
-#endif
-#ifdef UAM_AFSKRB
-   /* uam_afpserver_action(); */
-   uam_unregister(UAM_SERVER_LOGIN, "AFS Kerberos");
-#endif
-}
-
-UAM_MODULE_EXPORT struct uam_export uams_krb4 = {
-  UAM_MODULE_SERVER,
-  UAM_MODULE_VERSION,
-  uam_setup, uam_cleanup
-};
-
-#endif /* KRB or UAM_AFSKRB */
-
index 46ce0d51a43d50d020b5737bb5797f9db2364cc4..6f15ac0a30c660bbdec3939e66b0059e06643f5f 100644 (file)
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif /* HAVE_UNISTD_H */
-
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#include <atalk/logger.h>
-
 #ifdef HAVE_SECURITY_PAM_APPL_H
 #include <security/pam_appl.h>
 #endif
 #ifdef HAVE_PAM_PAM_APPL_H
 #include <pam/pam_appl.h>
 #endif
+#include <arpa/inet.h>
 
 #include <atalk/afp.h>
 #include <atalk/uam.h>
 #include <atalk/util.h>
+#include <atalk/logger.h>
+#include <atalk/compat.h>
 
 #define PASSWDLEN 8
 
@@ -253,7 +239,7 @@ static int pam_login_ext(void *obj, char *uname, struct passwd **uam_pwd,
 {
     char *username; 
     size_t  len, ulen;
-    u_int16_t  temp16;
+    uint16_t  temp16;
 
     *rbuflen = 0;
 
index 36d7a387b7ef03ca209cb9e786aeb512ec065585..bec45a360813bd502affc3a9ac5eed8902f6fae3 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: uams_passwd.c,v 1.31 2010-03-30 12:44:35 franklahm Exp $
- *
  * Copyright (c) 1990,1993 Regents of The University of Michigan.
  * Copyright (c) 1999 Adrian Sun (asun@u.washington.edu) 
  * All Rights Reserved.  See COPYRIGHT.
 #include <sys/types.h>
 #include <stdio.h>
 #include <stdlib.h>
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #ifdef HAVE_CRYPT_H
 #include <crypt.h>
 #endif /* ! HAVE_CRYPT_H */
 #include <pwd.h>
-#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
-#endif
-#ifdef HAVE_TIME_H
 #include <time.h>
-#endif
 #ifdef SHADOWPW
 #include <shadow.h>
 #endif /* SHADOWPW */
+#include <arpa/inet.h>
 
 #include <atalk/afp.h>
 #include <atalk/logger.h>
 #include <atalk/uam.h>
 #include <atalk/util.h>
+#include <atalk/compat.h>
 
 #define PASSWDLEN 8
 
@@ -198,7 +179,7 @@ static int passwd_login_ext(void *obj, char *uname, struct passwd **uam_pwd,
 {
     char       *username;
     size_t     len, ulen;
-    u_int16_t  temp16;
+    uint16_t  temp16;
 
     *rbuflen = 0;
 
index ec6d4095e17db4eea8caf3342e06d9a3cf0e0e4d..9b9c1d801dd57d53c543d8cdc1e11fb555f18f05 100644 (file)
@@ -53,7 +53,7 @@
 /* the secret key */
 static struct passwd *pgppwd;
 static CAST_KEY castkey;
-static u_int8_t randbuf[16];
+static uint8_t randbuf[16];
 
 /* pgp passwd */
 static int pgp_login(void *obj, struct passwd **uam_pwd,
@@ -109,7 +109,7 @@ static int pgp_logincont(void *obj, struct passwd **uam_pwd,
 {
        unsigned char iv[] = "RJscorat";
     BIGNUM *bn1, *bn2, *bn3;
-    u_int16_t sessid;
+    uint16_t sessid;
     char *p;
 
     *rbuflen = 0;
index 3d3a5bb9b72afc9bf267a03bb3682d9288f28d1f..301fdd0ff4cb69d48fe7e1f81d7572a954c7dfea 100644 (file)
 
 #include <stdio.h>
 #include <stdlib.h>
-
-/* STDC check */
-#if STDC_HEADERS
 #include <string.h>
-#else /* STDC_HEADERS */
-#ifndef HAVE_STRCHR
-#define strchr index
-#define strrchr index
-#endif /* HAVE_STRCHR */
-char *strchr (), *strrchr ();
-#ifndef HAVE_MEMCPY
-#define memcpy(d,s,n) bcopy ((s), (d), (n))
-#define memmove(d,s,n) bcopy ((s), (d), (n))
-#endif /* ! HAVE_MEMCPY */
-#endif /* STDC_HEADERS */
-
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <ctype.h>
 #include <pwd.h>
 #include <sys/stat.h>
 #include <sys/param.h>
+#include <arpa/inet.h>
 
 #include <atalk/logger.h>
-
-#include <netatalk/endian.h>
-
 #include <atalk/afp.h>
 #include <atalk/uam.h>
 
@@ -58,7 +37,7 @@ char *strchr (), *strrchr ();
 static C_Block         seskey;
 static Key_schedule    seskeysched;
 static struct passwd   *randpwd;
-static u_int8_t         randbuf[8];
+static uint8_t         randbuf[8];
 
 /* hash to a 16-bit number. this will generate completely harmless 
  * warnings on 64-bit machines. */
@@ -144,7 +123,7 @@ static int afppasswd(const struct passwd *pwd,
                     unsigned char *passwd, int len, 
                     const int set)
 {
-  u_int8_t key[DES_KEY_SZ*2];
+  uint8_t key[DES_KEY_SZ*2];
   char buf[MAXPATHLEN + 1], *p;
   Key_schedule schedule;
   FILE *fp;
@@ -305,7 +284,7 @@ static int rand_login(void *obj, char *username, int ulen, struct passwd **uam_p
 {
 
   char *passwdfile;
-  u_int16_t sessid;
+  uint16_t sessid;
   size_t len;
   int err;
  
@@ -350,7 +329,7 @@ static int randnum_logincont(void *obj, struct passwd **uam_pwd,
                             char *ibuf, size_t ibuflen _U_, 
                             char *rbuf _U_, size_t *rbuflen)
 {
-  u_int16_t sessid;
+  uint16_t sessid;
 
   *rbuflen = 0;
 
@@ -389,7 +368,7 @@ static int rand2num_logincont(void *obj, struct passwd **uam_pwd,
                              char *ibuf, size_t ibuflen _U_, 
                              char *rbuf, size_t *rbuflen)
 {
-  u_int16_t sessid;
+  uint16_t sessid;
   unsigned int i;
 
   *rbuflen = 0;
@@ -532,7 +511,7 @@ static int randnum_login_ext(void *obj, char *uname, struct passwd **uam_pwd,
 {
     char       *username;
     size_t     len, ulen;
-    u_int16_t  temp16;
+    uint16_t  temp16;
 
     *rbuflen = 0;
 
index 895a5e778b39b68094b7bf7771c67cf63c08dec9..4ee8385436cbec5213219bccb5d72809e7b024c4 100644 (file)
@@ -1,4 +1,4 @@
 Makefile
 Makefile.in
-.gitignore
 *.o
+lockrpc.gen.h
\ No newline at end of file
index 3c1feda3c8dd05e272f84ff377078460e48b8c8f..f1cf185970a59a2471838ab9b9248232842a429f 100644 (file)
@@ -1,11 +1,43 @@
 # Makefile.am for include/atalk/
 
 atalkincludedir = $(includedir)/atalk
+
 atalkinclude_HEADERS = \
-       adouble.h vfs.h aep.h afp.h asp.h atp.h \
-       cnid.h compat.h ddp.h dsi.h ldapconfig.h list.h logger.h \
-       nbp.h netddp.h pap.h paths.h queue.h rtmp.h server_child.h \
-       server_ipc.h tdb.h uam.h unicode.h util.h uuid.h volinfo.h \
-       zip.h ea.h acl.h unix.h directory.h hash.h volume.h
+       adouble.h \
+       afp.h \
+       vfs.h \
+       cnid.h \
+       logger.h \
+       netatalk_conf.h \
+       paths.h \
+       unicode.h \
+       util.h \
+       ea.h \
+       acl.h \
+       unix.h \
+       volume.h
 
-noinst_HEADERS = cnid_dbd_private.h cnid_private.h bstradd.h bstrlib.h errchk.h ftw.h globals.h fce_api.h standards.h
+noinst_HEADERS = \
+       directory.h \
+       hash.h \
+       uuid.h \
+       queue.h \
+       server_child.h \
+       server_ipc.h \
+       tdb.h \
+       uam.h \
+       cnid_dbd_private.h \
+       cnid_private.h \
+       bstradd.h \
+       bstrlib.h \
+       errchk.h \
+       ftw.h \
+       compat.h \
+       dsi.h \
+       ldapconfig.h \
+       list.h \
+       globals.h \
+       fce_api.h \
+       standards.h \
+       iniparser.h \
+       dictionary.h
index 78a35b02909ecd932bbf86d00cb5d908402e9426..a551d162585bf7074e399f740987ef4ddc1e4087 100644 (file)
@@ -1,5 +1,4 @@
 /*
- * $Id: adouble.h,v 1.55 2010-03-30 12:55:26 franklahm Exp $
  * Copyright (c) 1990,1991 Regents of The University of Michigan.
  * All Rights Reserved.
  *
 
 #include <atalk/standards.h>
 
+#include <inttypes.h>
 #include <sys/types.h>
 #include <sys/stat.h>
-
-#ifdef HAVE_UNISTD_H
-#undef __USE_MISC
-#define __USE_MISC
 #include <unistd.h>
-#endif
-
-#include <sys/cdefs.h>
-
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif
 
 #include <sys/mman.h>
 
-#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
-#endif
-#include <netatalk/endian.h>
 
-/* version info */
-#define AD_VERSION1     0x00010000
-#define SFM_VERSION     AD_VERSION1
+#include <atalk/bstrlib.h>
 
+/* version info */
 #define AD_VERSION2     0x00020000
 #define AD_VERSION2_OSX 0x00020001
-/*
-  #define AD_VERSION1_ADS 0x00010002
-*/
-#define AD_VERSION1_SFM 0x00010003
-#define AD_VERSION      AD_VERSION2
+#define AD_VERSION_EA   0x00020002
+
+/* default */
+#define AD_VERSION      AD_VERSION_EA
 
 /*
  * AppleDouble entry IDs.
  */
 #define ADEID_DFORK         1
 #define ADEID_RFORK         2
-#define ADEID_NAME          3 /* Note: starting with Netatalk 2.1 we do NOT alway set the name */
+#define ADEID_NAME          3
 #define ADEID_COMMENT       4
 #define ADEID_ICONBW        5
 #define ADEID_ICONCOL       6
 #define ADEID_AFPFILEI      14 /* where the rest of the FILEI info goes */
 #define ADEID_DID           15
 
-#if AD_VERSION == AD_VERSION1
-#define ADEID_MAX           16
-#else
 /* netatalk private note fileid reused DID */
 #define ADEID_PRIVDEV       16
 #define ADEID_PRIVINO       17
 #define ADEID_PRIVSYN       18 /* in synch with database */
 #define ADEID_PRIVID        19
-#define ADEID_SFMRESERVE1   20
-#define ADEID_SFMRESERVE2   21
+#define ADEID_MAX           (ADEID_PRIVID + 1)
 
+/* These are the real ids for these entries, as stored in the adouble file */
 #define AD_DEV              0x80444556
 #define AD_INO              0x80494E4F
 #define AD_SYN              0x8053594E
 #define AD_ID               0x8053567E
-#define ADEID_MAX           22
-#endif
 
 /* magic */
 #define AD_APPLESINGLE_MAGIC 0x00051600
 #define AD_APPLEDOUBLE_MAGIC 0x00051607
 #define AD_MAGIC             AD_APPLEDOUBLE_MAGIC
-#define SFM_MAGIC            0x00504641
 
 /* sizes of relevant entry bits */
 #define ADEDLEN_MAGIC       4
 #define ADEDLEN_VERSION     4
 #define ADEDLEN_FILLER      16
 #define ADEDLEN_NENTRIES    2
-
-/* 26 */
-#define AD_HEADER_LEN       (ADEDLEN_MAGIC + ADEDLEN_VERSION + \
-                             ADEDLEN_FILLER + ADEDLEN_NENTRIES)
+#define AD_HEADER_LEN       (ADEDLEN_MAGIC + ADEDLEN_VERSION + ADEDLEN_FILLER + ADEDLEN_NENTRIES) /* 26 */
 #define AD_ENTRY_LEN        12  /* size of a single entry header */
 
-/* v1 field widths */
-#define ADEDLEN_NAME        255
-#define ADEDLEN_COMMENT     200
-#define ADEDLEN_FILEI       16
-#define ADEDLEN_FINDERI     32
-
-/* v2 field widths */
+/* field widths */
+#define ADEDLEN_NAME            255
+#define ADEDLEN_COMMENT         200
+#define ADEDLEN_FILEI           16
+#define ADEDLEN_FINDERI         32
 #define ADEDLEN_FILEDATESI      16
 #define ADEDLEN_SHORTNAME       12 /* length up to 8.3 */
 #define ADEDLEN_AFPFILEI        4
 #define ADEDLEN_PRIVSYN         8
 #define ADEDLEN_PRIVID          4
 
-#define ADEID_NUM_V1            5
 #define ADEID_NUM_V2            13
+#define ADEID_NUM_EA            8
+#define ADEID_NUM_OSX           2
 
-// #define ADEID_NUM_SFM        5
-/* sizeof SFM meta data */
-#define AD_SFM_LEN 60
+#define AD_DATASZ2 (AD_HEADER_LEN + ADEDLEN_NAME + ADEDLEN_COMMENT + ADEDLEN_FILEI + \
+                    ADEDLEN_FINDERI + ADEDLEN_DID + ADEDLEN_AFPFILEI + ADEDLEN_SHORTNAME + \
+                    ADEDLEN_PRODOSFILEI + ADEDLEN_PRIVDEV + ADEDLEN_PRIVINO + \
+                    ADEDLEN_PRIVSYN + ADEDLEN_PRIVID + (ADEID_NUM_V2 * AD_ENTRY_LEN))
+#if AD_DATASZ2 != 741
+#error bad size for AD_DATASZ2
+#endif
 
-/* 589 */
-#define AD_DATASZ1      (AD_HEADER_LEN + ADEDLEN_NAME + ADEDLEN_COMMENT + ADEDLEN_FILEI + ADEDLEN_FINDERI + \
-                         (ADEID_NUM_V1 * AD_ENTRY_LEN))
+#define AD_DATASZ_EA (AD_HEADER_LEN + (ADEID_NUM_EA * AD_ENTRY_LEN) + \
+                      ADEDLEN_FINDERI + ADEDLEN_COMMENT + ADEDLEN_FILEDATESI + ADEDLEN_AFPFILEI + \
+                      ADEDLEN_PRIVDEV + ADEDLEN_PRIVINO + ADEDLEN_PRIVSYN + ADEDLEN_PRIVID)
 
-#if AD_DATASZ1 != 589
-#error bad size for AD_DATASZ1
+#if AD_DATASZ_EA != 402
+#error bad size for AD_DATASZ_EA
 #endif
 
-#define AD_NEWSZ2       (ADEDLEN_DID + ADEDLEN_AFPFILEI + ADEDLEN_SHORTNAME + ADEDLEN_PRODOSFILEI \
-                         + ADEDLEN_PRIVDEV + ADEDLEN_PRIVINO + ADEDLEN_PRIVSYN + ADEDLEN_PRIVID)
+#define AD_DATASZ_OSX (AD_HEADER_LEN + (ADEID_NUM_OSX * AD_ENTRY_LEN) + ADEDLEN_FINDERI)
 
-/* 725 */
-#define AD_DATASZ2      (AD_DATASZ1 + AD_NEWSZ2 + ((ADEID_NUM_V2 - ADEID_NUM_V1) * AD_ENTRY_LEN))
-
-#if AD_DATASZ2 != 741
-#error bad size for AD_DATASZ2
+#if AD_DATASZ_OSX != 82
+#error bad size for AD_DATASZ_OSX
 #endif
 
 #define AD_DATASZ_MAX   1024
-#if AD_VERSION == AD_VERSION1
-#define AD_DATASZ   AD_DATASZ1 /* hold enough for the entries */
-#elif AD_VERSION == AD_VERSION2
+
+#if AD_VERSION == AD_VERSION2
 #define AD_DATASZ   AD_DATASZ2
+#elif AD_VERSION == AD_VERSION_EA
+#define AD_DATASZ   AD_DATASZ_EA
 #endif
 
-/*
- * some legacy defines from netatalk-990130
- * (to keep from breaking certain packages)
- *
- */
+/* fallback for ad:ea on filesystems without fds for EAs, like old adouble:osx */
+#define ADEDOFF_FINDERI_OSX  (AD_HEADER_LEN + ADEID_NUM_OSX*AD_ENTRY_LEN)
+#define ADEDOFF_RFORK_OSX    (ADEDOFF_FINDERI_OSX + ADEDLEN_FINDERI)
 
-#define ADEDOFF_RFORK   589
-#define ADEDOFF_NAME    86
-#define ADEDOFF_COMMENT 341
-#define ADEDOFF_FINDERI 557
-#ifndef ADEDOFF_FILEI
-#define ADEDOFF_FILEI   541
-#endif
+/* special fd value used to indicate an open fork file is a (not open) symlink */
+#define AD_SYMLINK -2
 
-typedef u_int32_t cnid_t;
-
-/*
- * The header of the AppleDouble Header File looks like this:
- *
- *  NAME            SIZE
- *  ====            ====
- *  Magic           4
- *  Version         4
- *  Home File System    16  (this becomes filler in ad v2)
- *  Number of Entries   2
- *  Entry Descriptors for each entry:
- *      Entry ID    4
- *      Offset      4
- *      Length      4
- */
+typedef uint32_t cnid_t;
 
 struct ad_entry {
-    off_t   ade_off;
+    off_t     ade_off;
     ssize_t   ade_len;
 };
 
@@ -218,81 +172,82 @@ typedef struct adf_lock_t {
 } adf_lock_t;
 
 struct ad_fd {
-    int          adf_fd;        /* -1: invalid, -2: symlink */
-
-#ifndef HAVE_PREAD
-    off_t        adf_off;
-#endif
-
+    int          adf_fd;        /* -1: invalid, AD_SYMLINK: symlink */
     char         *adf_syml;
     int          adf_flags;
-    int          adf_excl;
     adf_lock_t   *adf_lock;
     int          adf_refcount, adf_lockcount, adf_lockmax;
 };
 
 /* some header protection */
 #define AD_INITED  0xad494e54  /* ad"INT" */
-struct adouble_fops;
+#define AD_CLOSED  0xadc10ced
 
-struct adouble {
-    u_int32_t           ad_magic;
-    u_int32_t           ad_version;
-    char                ad_filler[ 16 ];
-    struct ad_entry     ad_eid[ ADEID_MAX ];
-    struct ad_fd        ad_data_fork, ad_resource_fork, ad_metadata_fork;
-    struct ad_fd        *ad_md; /* either ad_resource or ad_metadata */
-
-    int                 ad_flags;    /* This really stores version info too (AD_VERSION*) */
-    int                 ad_adflags;  /* ad_open flags adflags like ADFLAGS_DIR */
-    unsigned int        ad_inited;
-    int                 ad_options;
-    int                 ad_fileordir;
-    int                 ad_refcount; /* used in afpd/ofork.c */
-    off_t               ad_rlen;     /* ressource fork len with AFP 3.0
-                                        the header parameter size is too small.
-                                     */
-    char                *ad_m_name;   /* mac name for open fork */
-    int                 ad_m_namelen;
-    struct adouble_fops *ad_ops;
-    u_int16_t       ad_open_forks;      /* open forks (by others) */
-
-#ifdef USE_MMAPPED_HEADERS
-    char                *ad_data;
-#else
-    char        ad_data[AD_DATASZ_MAX];
-#endif
-};
+struct adouble;
 
 struct adouble_fops {
-    char *(*ad_path)(const char *, int);
-    int  (*ad_mkrf)(char *);
+    const char *(*ad_path)(const char *, int);
+    int  (*ad_mkrf)(const char *);
     int  (*ad_rebuild_header)(struct adouble *);
-    int  (*ad_check_header)(struct adouble *, struct stat *);
-    int  (*ad_header_read)(struct adouble *, struct stat *);
-    int  (*ad_header_upgrade)(struct adouble *, char *);
+    int  (*ad_header_read)(const char *, struct adouble *, const struct stat *);
+    int  (*ad_header_upgrade)(struct adouble *, const char *);
+};
+
+struct adouble {
+    uint32_t            ad_magic;         /* Official adouble magic                   */
+    uint32_t            ad_version;       /* Official adouble version number          */
+    char                ad_filler[16];
+    struct ad_entry     ad_eid[ADEID_MAX];
+
+    struct ad_fd        ad_data_fork;     /* the data fork                            */
+
+    struct ad_fd        ad_metadata_fork; /* adouble:v2 -> unused                     *
+                                           * adouble:ea -> fd unused, only flags used */
+
+    struct ad_fd        ad_resource_fork; /* adouble:v2 -> the adouble file           *
+                                           * adouble:ea -> the EA fd                  */
+
+    struct ad_fd        *ad_rfp;          /* adouble:v2 -> ad_resource_fork           *
+                                           * adouble:ea -> ad_resource_fork           */
+
+    struct ad_fd        *ad_mdp;          /* adouble:v2 -> ad_resource_fork           *
+                                           * adouble:ea -> ad_metadata_fork           */
+
+    int                 ad_vers;          /* Our adouble version info (AD_VERSION*)   */
+    int                 ad_adflags;       /* ad_open flags adflags like ADFLAGS_DIR   */
+    uint32_t            ad_inited;
+    int                 ad_options;
+    int                 ad_refcount;       /* multiple forks may open one adouble     */
+    off_t               ad_rlen;           /* ressource fork len with AFP 3.0         *
+                                            * the header parameter size is too small. */
+    char                *ad_name;          /* name in server encoding (usually UTF8)  */
+    struct adouble_fops *ad_ops;
+    uint16_t            ad_open_forks;     /* open forks (by others)                  */
+    char                ad_data[AD_DATASZ_MAX];
 };
 
 #define ADFLAGS_DF        (1<<0)
-#define ADFLAGS_HF        (1<<1)
-#define ADFLAGS_DIR       (1<<2)
-/*
-#define ADFLAGS_NOADOUBLE (1<<3)
-*/
-#define ADFLAGS_V1COMPAT  (1<<4)
-#define ADFLAGS_NOHF      (1<<5)  /* not an error if no ressource fork */
-#define ADFLAGS_RDONLY    (1<<6)  /* don't try readwrite */
-#define ADFLAGS_OPENFORKS (1<<7)  /* check for open fork in ad_metadata function */
-#define ADFLAGS_RF        (1<<8)
-#define ADFLAGS_MD        ADFLAGS_HF /* (1<<9) */
-#define ADFLAGS_CREATE    (1<<9)
-
-/* adouble v2 cnid cache */
+#define ADFLAGS_RF        (1<<1)
+#define ADFLAGS_HF        (1<<2)
+#define ADFLAGS_DIR       (1<<3)
+#define ADFLAGS_NOHF      (1<<4)  /* not an error if no metadata fork */
+#define ADFLAGS_NORF      (1<<5)  /* not an error if no ressource fork */
+#define ADFLAGS_CHECK_OF  (1<<6)  /* check for open forks from us and other afpd's */
+#define ADFLAGS_SETSHRMD  (1<<7)  /* setting share mode must be done with excl fcnt lock,
+                                     which implies that the file must be openend rw.
+                                     If it can't be opened rw (eg EPERM or EROFS) it will
+                                     be opened ro and the fcntl locks will be shared, that
+                                     at least prevent other users who have rw access to the
+                                     file from placing excl locks. */
+#define ADFLAGS_RDWR      (1<<8)  /* open read/write */
+#define ADFLAGS_RDONLY    (1<<9)  /* open read only */
+#define ADFLAGS_CREATE    (1<<10)  /* create file, open called with O_CREAT */
+#define ADFLAGS_EXCL      (1<<11)  /* exclusive open, open called with O_EXCL */
+#define ADFLAGS_TRUNC     (1<<12) /* truncate, open called with O_TRUNC */
+
 #define ADVOL_NODEV      (1 << 0)
-#define ADVOL_CACHE      (1 << 1)
 #define ADVOL_UNIXPRIV   (1 << 2) /* adouble unix priv */
 #define ADVOL_INVDOTS    (1 << 3) /* dot files (.DS_Store) are invisible) */
-#define ADVOL_NOADOUBLE  (1 << 4)
 
 /* lock flags */
 #define ADLOCK_CLR      (0)
@@ -303,39 +258,28 @@ struct adouble_fops {
 #define ADLOCK_FILELOCK (1<<3)
 
 /* we use this so that we can use the same mechanism for both byte
- * locks and file synchronization locks. i do this by co-opting either
- * first bits on 32-bit machines or shifting above the last bit on
- * 64-bit machines. this only matters for the data fork. */
-#if defined(TRY_64BITOFF_T) && (~0UL > 0xFFFFFFFFU)
-/* synchronization locks */
-#define AD_FILELOCK_BASE (0x80000000)
-#else
+ * locks and file synchronization locks. */
 #if _FILE_OFFSET_BITS == 64
-#define AD_FILELOCK_BASE (0x7FFFFFFFFFFFFFFFULL - 9)
+#define AD_FILELOCK_BASE (UINT64_C(0x7FFFFFFFFFFFFFFF) - 9)
 #else
-#define AD_FILELOCK_BASE (0x7FFFFFFF -9)
-#endif
+#define AD_FILELOCK_BASE (UINT32_C(0x7FFFFFFF) - 9)
 #endif
 
-/* FIXME:
- * AD_FILELOCK_BASE case
- */
-#if _FILE_OFFSET_BITS == 64
-#define BYTELOCK_MAX (0x7FFFFFFFFFFFFFFFULL)
-#else
-/* Tru64 is an always-64-bit OS; version 4.0 does not set _FILE_OFFSET_BITS */
-#if defined(TRU64)
-#define BYTELOCK_MAX (0x7FFFFFFFFFFFFFFFULL)
-#else
-#define BYTELOCK_MAX (0x7FFFFFFFU)
-#endif
-#endif
+#define BYTELOCK_MAX (AD_FILELOCK_BASE - 1)
 
+/* datafork and rsrcfork sharemode locks */
 #define AD_FILELOCK_OPEN_WR        (AD_FILELOCK_BASE + 0)
 #define AD_FILELOCK_OPEN_RD        (AD_FILELOCK_BASE + 1)
-#define AD_FILELOCK_DENY_WR        (AD_FILELOCK_BASE + 2)
-#define AD_FILELOCK_DENY_RD        (AD_FILELOCK_BASE + 3)
-#define AD_FILELOCK_OPEN_NONE      (AD_FILELOCK_BASE + 4)
+#define AD_FILELOCK_RSRC_OPEN_WR   (AD_FILELOCK_BASE + 2)
+#define AD_FILELOCK_RSRC_OPEN_RD   (AD_FILELOCK_BASE + 3)
+
+#define AD_FILELOCK_DENY_WR        (AD_FILELOCK_BASE + 4)
+#define AD_FILELOCK_DENY_RD        (AD_FILELOCK_BASE + 5)
+#define AD_FILELOCK_RSRC_DENY_WR   (AD_FILELOCK_BASE + 6)
+#define AD_FILELOCK_RSRC_DENY_RD   (AD_FILELOCK_BASE + 7)
+
+#define AD_FILELOCK_OPEN_NONE      (AD_FILELOCK_BASE + 8)
+#define AD_FILELOCK_RSRC_OPEN_NONE (AD_FILELOCK_BASE + 9)
 
 /* time stuff. we overload the bits a little.  */
 #define AD_DATE_CREATE         0
@@ -404,159 +348,102 @@ struct adouble_fops {
 #define AD_AFPFILEI_BLANKACCESS (1 << 2) /* blank access permissions */
 
 #define ad_data_fileno(ad)  ((ad)->ad_data_fork.adf_fd)
-#define ad_reso_fileno(ad)  ((ad)->ad_resource_fork.adf_fd)
-#define ad_meta_fileno(ad)  ((ad)->ad_md->adf_fd)
+#define ad_reso_fileno(ad)  ((ad)->ad_rfp->adf_fd)
+#define ad_meta_fileno(ad)  ((ad)->ad_mdp->adf_fd)
+
+/* -1: not open, AD_SYMLINK (-2): it's a symlink */
+#define AD_DATA_OPEN(ad) ((ad)->ad_data_fork.adf_fd >= 0)
+#define AD_META_OPEN(ad) ((ad)->ad_mdp->adf_fd >= 0)
+#define AD_RSRC_OPEN(ad) ((ad)->ad_rfp->adf_fd >= 0)
 
 #define ad_getversion(ad)   ((ad)->ad_version)
 
 #define ad_getentrylen(ad,eid)     ((ad)->ad_eid[(eid)].ade_len)
 #define ad_setentrylen(ad,eid,len) ((ad)->ad_eid[(eid)].ade_len = (len))
-#define ad_getentryoff(ad,eid)     ((ad)->ad_eid[(eid)].ade_off)
+#define ad_setentryoff(ad,eid,off) ((ad)->ad_eid[(eid)].ade_off = (off))
 #define ad_entry(ad,eid)           ((caddr_t)(ad)->ad_data + (ad)->ad_eid[(eid)].ade_off)
 
-#define ad_get_HF_flags(ad) ((ad)->ad_resource_fork.adf_flags)
-#define ad_get_MD_flags(ad) ((ad)->ad_md->adf_flags)
+#define ad_get_RF_flags(ad) ((ad)->ad_rfp->adf_flags)
+#define ad_get_MD_flags(ad) ((ad)->ad_mdp->adf_flags)
+
+/* Refcounting open forks using one struct adouble */
+#define ad_ref(ad)   (ad)->ad_refcount++
+#define ad_unref(ad) --((ad)->ad_refcount)
 
 /* ad_flush.c */
-extern int ad_rebuild_adouble_header (struct adouble *);
-extern int ad_rebuild_sfm_header (struct adouble *);
+extern int ad_rebuild_adouble_header_v2(struct adouble *);
+extern int ad_rebuild_adouble_header_ea(struct adouble *);
 extern int ad_copy_header (struct adouble *, struct adouble *);
 extern int ad_flush (struct adouble *);
 extern int ad_close (struct adouble *, int);
+extern int fsetrsrcea(struct adouble *ad, int fd, const char *eaname, const void *value, size_t size, int flags);
 
 /* ad_lock.c */
-extern int ad_fcntl_lock    (struct adouble *, const u_int32_t /*eid*/,
-                                 const int /*type*/, const off_t /*offset*/,
-                                 const off_t /*len*/, const int /*user*/);
-extern void ad_fcntl_unlock (struct adouble *, const int /*user*/);
-extern int ad_fcntl_tmplock (struct adouble *, const u_int32_t /*eid*/,
-                                 const int /*type*/, const off_t /*offset*/,
-                                 const off_t /*len*/, const int /*user*/);
-extern int ad_testlock      (struct adouble * /*adp*/, int /*eid*/, off_t /*off*/);
-
-extern u_int16_t ad_openforks (struct adouble * /*adp*/, u_int16_t);
-extern int ad_excl_lock     (struct adouble * /*adp*/, const u_int32_t /*eid*/);
-
-#define ad_lock ad_fcntl_lock
-#define ad_tmplock ad_fcntl_tmplock
-#define ad_unlock ad_fcntl_unlock
+extern int ad_testlock      (struct adouble *adp, int eid, off_t off);
+extern uint16_t ad_openforks(struct adouble *adp, uint16_t);
+extern int ad_lock(struct adouble *, uint32_t eid, int type, off_t off, off_t len, int fork);
+extern void ad_unlock(struct adouble *, int fork, int unlckbrl);
+extern int ad_tmplock(struct adouble *, uint32_t eid, int type, off_t off, off_t len, int fork);
 
 /* ad_open.c */
+extern off_t ad_getentryoff(const struct adouble *ad, int eid);
+extern const char *adflags2logstr(int adflags);
 extern int ad_setfuid     (const uid_t );
 extern uid_t ad_getfuid   (void );
 extern char *ad_dir       (const char *);
-extern char *ad_path      (const char *, int);
-extern char *ad_path_osx  (const char *, int);
-extern char *ad_path_ads  (const char *, int);
-extern char *ad_path_sfm  (const char *, int);
-extern int ad_mode        (const char *, int);
-extern int ad_mkdir       (const char *, int);
-extern void ad_init       (struct adouble *, int, int );
-extern int ad_open        (const char *, int, int, int, struct adouble *);
-extern int ad_openat      (int dirfd, const char *, int, int, int, struct adouble *);
-extern int ad_refresh     (struct adouble *);
+extern const char *ad_path      (const char *, int);
+extern const char *ad_path_ea   (const char *, int);
+extern const char *ad_path_osx  (const char *path, int adflags);
+extern int ad_mode        (const char *, mode_t);
+extern int ad_mkdir       (const char *, mode_t);
+struct vol;
+extern void ad_init       (struct adouble *, const struct vol * restrict);
+extern void ad_init_old   (struct adouble *ad, int flags, int options);
+extern int ad_open        (struct adouble *ad, const char *path, int adflags, ...);
+extern int ad_openat      (struct adouble *, int dirfd, const char *path, int adflags, ...);
+extern int ad_refresh     (const char *path, struct adouble *);
 extern int ad_stat        (const char *, struct stat *);
 extern int ad_metadata    (const char *, int, struct adouble *);
 extern int ad_metadataat  (int, const char *, int, struct adouble *);
+extern mode_t ad_hf_mode(mode_t mode);
+extern int ad_valid_header_osx(const char *path);
 
-#define ad_open_metadata(name, flags, mode, adp)\
-   ad_open(name, ADFLAGS_MD|(flags), O_RDWR |(mode), 0666, (adp))
-
-#define ad_close_metadata(adp) ad_close( (adp), ADFLAGS_MD)
-
-/* build a resource fork mode from the data fork mode:
- * remove X mode and extend header to RW if R or W (W if R for locking),
- */
-static inline mode_t ad_hf_mode (mode_t mode)
-{
-    mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
-    /* fnctl lock need write access */
-    if ((mode & S_IRUSR))
-        mode |= S_IWUSR;
-    if ((mode & S_IRGRP))
-        mode |= S_IWGRP;
-    if ((mode & S_IROTH))
-        mode |= S_IWOTH;
-
-    /* if write mode set add read mode */
-    if ((mode & S_IWUSR))
-        mode |= S_IRUSR;
-    if ((mode & S_IWGRP))
-        mode |= S_IRGRP;
-    if ((mode & S_IWOTH))
-        mode |= S_IROTH;
-
-    return mode;
-}
-
-/* ad_ea.c */
-ssize_t sys_getxattr (const char *path, const char *name, void *value, size_t size);
-ssize_t sys_lgetxattr (const char *path, const char *name, void *value, size_t size);
-ssize_t sys_fgetxattr (int filedes, const char *name, void *value, size_t size);
-ssize_t sys_listxattr (const char *path, char *list, size_t size);
-ssize_t sys_llistxattr (const char *path, char *list, size_t size);
-ssize_t sys_flistxattr (int filedes, char *list, size_t size);
-int sys_removexattr (const char *path, const char *name);
-int sys_lremovexattr (const char *path, const char *name);
-int sys_fremovexattr (int filedes, const char *name);
-int sys_setxattr (const char *path, const char *name, const void *value, size_t size, int flags);
-int sys_lsetxattr (const char *path, const char *name, const void *value, size_t size, int flags);
-int sys_fsetxattr (int filedes, const char *name, const void *value, size_t size, int flags);
-int sys_copyxattr (const char *src, const char *dst);
+/* ad_conv.c */
+extern int ad_convert(const char *path, const struct stat *sp, const struct vol *vol, const char **newpath);
 
 /* ad_read.c/ad_write.c */
 extern int     sys_ftruncate(int fd, off_t length);
-
-extern ssize_t ad_read (struct adouble *, const u_int32_t,
-                            const off_t, char *, const size_t);
-extern ssize_t ad_pread (struct ad_fd *, void *, size_t, off_t);
-extern ssize_t ad_write (struct adouble *, const u_int32_t, off_t,
-                             const int, const char *, const size_t);
-extern ssize_t adf_pread  (struct ad_fd *, void *, size_t, off_t);
-extern ssize_t adf_pwrite (struct ad_fd *, const void *, size_t, off_t);
-extern int     ad_dtruncate (struct adouble *, const off_t);
-extern int     ad_rtruncate (struct adouble *, const off_t);
+extern ssize_t ad_read(struct adouble *, uint32_t, off_t, char *, size_t);
+extern ssize_t ad_pread(struct ad_fd *, void *, size_t, off_t);
+extern ssize_t ad_write(struct adouble *, uint32_t, off_t, int, const char *, size_t);
+extern ssize_t adf_pread(struct ad_fd *, void *, size_t, off_t);
+extern ssize_t adf_pwrite(struct ad_fd *, const void *, size_t, off_t);
+extern int     ad_dtruncate(struct adouble *, off_t);
+extern int     ad_rtruncate(struct adouble *, off_t);
+extern int     copy_fork(int eid, struct adouble *add, struct adouble *ads);
 
 /* ad_size.c */
-extern off_t ad_size (const struct adouble *, const u_int32_t );
+extern off_t ad_size (const struct adouble *, uint32_t );
 
 /* ad_mmap.c */
-extern void *ad_mmapread (struct adouble *, const u_int32_t,
-                              const off_t, const size_t);
-extern void *ad_mmapwrite (struct adouble *, const u_int32_t,
-                               const off_t, const int, const size_t);
+extern void *ad_mmapread(struct adouble *, uint32_t, off_t, size_t);
+extern void *ad_mmapwrite(struct adouble *, uint32_t, off_t, int, size_t);
 #define ad_munmap(buf, len)  (munmap((buf), (len)))
 
 /* ad_date.c */
-extern int ad_setdate (struct adouble *, unsigned int, u_int32_t);
-extern int ad_getdate (const struct adouble *, unsigned int, u_int32_t *);
+extern int ad_setdate(struct adouble *, unsigned int, uint32_t);
+extern int ad_getdate(const struct adouble *, unsigned int, uint32_t *);
 
 /* ad_attr.c */
-extern int       ad_setattr (const struct adouble *, const u_int16_t);
-extern int       ad_getattr (const struct adouble *, u_int16_t *);
-
-/* Note: starting with Netatalk 2.1 we do NOT alway set the name */
-extern int       ad_setname (struct adouble *, const char *);
-
-#if AD_VERSION == AD_VERSION2
-extern int       ad_setid (struct adouble *, const dev_t dev,const ino_t ino, const u_int32_t, const u_int32_t, const void *);
-extern u_int32_t ad_getid (struct adouble *, const dev_t, const ino_t, const cnid_t, const void *);
-extern u_int32_t ad_forcegetid (struct adouble *adp);
-#else
-#define ad_setid(a, b, c)
-#endif
+extern int       ad_setattr(const struct adouble *, const uint16_t);
+extern int       ad_getattr(const struct adouble *, uint16_t *);
+extern int       ad_setname(struct adouble *, const char *);
+extern int       ad_setid(struct adouble *, dev_t dev, ino_t ino, uint32_t, uint32_t, const void *);
+extern uint32_t  ad_getid(struct adouble *, dev_t, ino_t, cnid_t, const void *);
+extern uint32_t  ad_forcegetid(struct adouble *adp);
 
 #ifdef WITH_SENDFILE
-extern int ad_readfile_init(const struct adouble *ad, 
-                                      const int eid, off_t *off,
-                                      const int end);
+extern int ad_readfile_init(const struct adouble *ad, int eid, off_t *off, int end);
 #endif
 
-#if 0
-#ifdef HAVE_SENDFILE_WRITE
-extern ssize_t ad_writefile (struct adouble *, const int,
-                                 const int, off_t, const int, const size_t);
-#endif /* HAVE_SENDFILE_WRITE */
-#endif /* 0 */
-
 #endif /* _ATALK_ADOUBLE_H */
diff --git a/include/atalk/aep.h b/include/atalk/aep.h
deleted file mode 100644 (file)
index 11176ab..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef _ATALK_AEP_H
-#define _ATALK_AEP_H 1
-
-#ifndef NO_DDP
-
-#define AEPOP_REQUEST  1
-#define AEPOP_REPLY    2
-
-#endif  /* NO_DDP */
-#endif
index 303e705047f58fa5b7b88a799222034dcb282670..76315aa41acd661b4e7b8b6c8dc454496ce6b38c 100644 (file)
 #ifndef _ATALK_AFP_H
 #define _ATALK_AFP_H 1
 
+#include <stdint.h>
 #include <sys/types.h>
-#include <netatalk/endian.h>
 
-typedef u_int16_t AFPUserBytes;
+typedef uint16_t AFPUserBytes;
 
 /* protocols */
 #define AFPPROTO_ASP           1
 #define AFPPROTO_DSI           2
 
-/* actual transports. the DSI ones (tcp right now) need to be
- * kept in sync w/ <atalk/dsi.h>. 
- * convention: AFPTRANS_* = (1 << DSI_*) 
- */
-#define AFPTRANS_NONE          0
-#define AFPTRANS_DDP          (1 << 0)
-#define AFPTRANS_TCP          (1 << 1)
-#define AFPTRANS_ALL          (AFPTRANS_DDP | AFPTRANS_TCP)
-
 /* server flags */
 #define AFPSRVRINFO_COPY         (1<<0)  /* supports copyfile */
 #define AFPSRVRINFO_PASSWD       (1<<1)  /* supports change password */
diff --git a/include/atalk/asp.h b/include/atalk/asp.h
deleted file mode 100644 (file)
index 3c7252d..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef _ATALK_ASP_H
-#define _ATALK_ASP_H 1
-
-#ifndef NO_DDP
-
-#include <sys/types.h>
-#include <sys/cdefs.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/afp.h>
-#include <atalk/server_child.h>
-
-#define ASP_HDRSIZ        4
-#define ASP_CMDSIZ        578
-
-#define ASP_MAXPACKETS    8
-#define ASP_CMDMAXSIZ     (ASP_CMDSIZ + ASP_HDRSIZ)
-#define ASP_DATASIZ       (ASP_CMDSIZ*ASP_MAXPACKETS)
-#define ASP_DATAMAXSIZ    ((ASP_CMDSIZ + ASP_HDRSIZ)*ASP_MAXPACKETS)
-
-typedef struct ASP {
-    ATP                        asp_atp;
-    struct sockaddr_at asp_sat;
-    u_int8_t           asp_wss;
-    u_int8_t            asp_sid;
-    union {
-       struct {
-           char                        *as_status;
-           int                         as_slen;
-       }                       asu_status;
-       u_int16_t               asu_seq;
-    }                  asp_u;
-#define asp_status     asp_u.asu_status.as_status
-#define asp_slen       asp_u.asu_status.as_slen
-#define asp_seq                asp_u.asu_seq
-    int                        asp_flags;
-    char               child, inited, *commands;
-    char                cmdbuf[ASP_CMDMAXSIZ];
-    char                data[ASP_DATAMAXSIZ];  
-    size_t             cmdlen, datalen;
-    off_t              read_count, write_count;
-} *ASP;
-
-#define ASPFL_SLS      1
-#define ASPFL_SSS      2
-
-#define ASPFUNC_CLOSE  1
-#define ASPFUNC_CMD    2
-#define ASPFUNC_STAT   3
-#define ASPFUNC_OPEN   4
-#define ASPFUNC_TICKLE 5
-#define ASPFUNC_WRITE  6
-#define ASPFUNC_WRTCONT        7
-#define ASPFUNC_ATTN   8
-
-#define ASPERR_OK      0x0000
-#define ASPERR_BADVERS 0xfbd6
-#define ASPERR_BUFSMALL        0xfbd5
-#define ASPERR_NOSESS  0xfbd4
-#define ASPERR_NOSERV  0xfbd3
-#define ASPERR_PARM    0xfbd2
-#define ASPERR_SERVBUSY        0xfbd1
-#define ASPERR_SESSCLOS        0xfbd0
-#define ASPERR_SIZERR  0xfbcf
-#define ASPERR_TOOMANY 0xfbce
-#define ASPERR_NOACK   0xfbcd
-
-extern ASP asp_init         (ATP);
-extern void asp_setstatus   (ASP, char *, const int);
-extern ASP asp_getsession   (ASP, server_child *, const int);
-extern int asp_close        (ASP);
-extern int asp_shutdown     (ASP);
-extern int asp_attention    (ASP, AFPUserBytes);
-extern int asp_getrequest   (ASP);
-extern int asp_cmdreply     (ASP, int);
-extern int asp_wrtcont      (ASP, char *, size_t *);
-#define asp_wrtreply(a,b)   asp_cmdreply((a), (b))
-extern void asp_kill        (int);
-extern int asp_tickle      (ASP, const u_int8_t, struct sockaddr_at *);
-extern void asp_stop_tickle (void);
-
-#endif  /* NO_DDP */
-#endif
diff --git a/include/atalk/atp.h b/include/atalk/atp.h
deleted file mode 100644 (file)
index 9618e75..0000000
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * $Id: atp.h,v 1.5 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef _ATALK_ATP_H
-#define _ATALK_ATP_H 1
-
-#ifndef NO_DDP
-#include <sys/cdefs.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-
-/* ATP packet format
-
- |----------------|
- | link header    |
- |      ...       |
- |----------------|
- | DDP header     |
- |      ...       |
- |   type = 3     |
- |----------------|
- | control info   | --> bits 7,6: function code
- |----------------|            5: XO bit
- | bitmap/seq no. |            4: EOM bit
- |----------------|            3: STS bit
- | TID (MSB)      |        2,1,0: release timer code (ignored under phase I)
- |----------------|
- | TID (LSB)      |
- |----------------|
- | user bytes (4) |
- |----------------|
- | data (0-578)   |
- |      ...       |
- |----------------|
-*/
-struct atphdr {
-    u_int8_t   atphd_ctrlinfo; /* control information */
-    u_int8_t   atphd_bitmap;   /* bitmap or sequence number */
-    u_int16_t  atphd_tid;      /* transaction id. */
-};
-
-/* ATP protocol parameters
-*/
-#define ATP_MAXDATA    (578+4)         /* maximum ATP data size */
-#define ATP_BUFSIZ     587             /* maximum packet size */
-#define ATP_HDRSIZE    5               /* includes DDP type field */
-
-#define ATP_TRELMASK   0x07            /* mask all but TREL */
-#define ATP_RELTIME    30              /* base release timer (in secs) */
-
-#define ATP_TREL30     0x0             /* release time codes */
-#define ATP_TREL1M     0x1             /* these are passed in flags of */
-#define ATP_TREL2M     0x2             /* atp_sreq call, and set in the */
-#define ATP_TREL4M     0x3             /* packet control info. */
-#define ATP_TREL8M     0x4
-
-#define ATP_TRIES_INFINITE     -1      /* for atp_sreq, etc */
-
-struct atpxobuf {
-    u_int16_t          atpxo_tid;
-    struct timeval     atpxo_tv;
-    int                        atpxo_reltime;
-    struct atpbuf      *atpxo_packet[8];
-};
-
-struct atpbuf {
-    struct atpbuf      *atpbuf_next;           /* next buffer in chain */
-    size_t             atpbuf_dlen;            /* data length <= ATP_BUFSIZ */
-    struct sockaddr_at atpbuf_addr;            /* net address sent/recvd */
-    union {
-       char            atpbuf_data[ ATP_BUFSIZ ];      /* the data */
-       struct atpxobuf atpbuf_xo;                      /* for XO requests */
-    } atpbuf_info;
-};
-
-struct atp_handle {
-    int                        atph_socket;            /* ddp socket */
-    struct sockaddr_at atph_saddr;             /* address */
-    u_int16_t          atph_tid;               /* last tid used */
-    u_int16_t          atph_rtid;              /* last received (rreq) */
-    u_int8_t           atph_rxo;               /* XO flag from last rreq */
-    int                        atph_rreltime;          /* release time (secs) */
-    struct atpbuf      *atph_sent;             /* packets we send (XO) */
-    struct atpbuf      *atph_queue;            /* queue of pending packets */
-    int                        atph_reqtries;          /* retry count for request */
-    int                        atph_reqto;             /* retry timeout for request */
-    int                        atph_rrespcount;        /* expected # of responses */
-    u_int8_t           atph_rbitmap;           /* bitmap for request */
-    struct atpbuf      *atph_reqpkt;           /* last request packet */
-    struct timeval     atph_reqtv;             /* when we last sent request */
-    struct atpbuf      *atph_resppkt[8];       /* response to request */
-};
-
-typedef struct atp_handle *ATP;
-
-#define atp_sockaddr( h )      (&(h)->atph_saddr)
-#define atp_fileno(x)          ((x)->atph_socket)
-
-struct sreq_st {
-    char           *atpd_data;         /* request data */
-    int                    atpd_dlen;
-    int                    atpd_tries;         /* max. retry count */
-    int                    atpd_to;            /* retry interval */
-};
-
-struct rres_st {
-    struct iovec    *atpd_iov;         /* for response */
-    int                    atpd_iovcnt;
-};
-
-struct rreq_st {
-    char           *atpd_data;         /* request data */
-    int                    atpd_dlen;
-};
-
-struct sres_st {
-    struct iovec    *atpd_iov;         /* for response */
-    int                    atpd_iovcnt;
-};
-
-struct atp_block {
-    struct sockaddr_at *atp_saddr;             /* from/to address */
-    union {
-       struct sreq_st  sreqdata;
-#define atp_sreqdata   atp_data.sreqdata.atpd_data
-#define atp_sreqdlen   atp_data.sreqdata.atpd_dlen
-#define atp_sreqtries  atp_data.sreqdata.atpd_tries
-#define atp_sreqto     atp_data.sreqdata.atpd_to
-
-       struct rres_st  rresdata;
-#define atp_rresiov    atp_data.rresdata.atpd_iov
-#define atp_rresiovcnt atp_data.rresdata.atpd_iovcnt
-
-       struct rreq_st  rreqdata;
-#define atp_rreqdata   atp_data.rreqdata.atpd_data
-#define atp_rreqdlen   atp_data.rreqdata.atpd_dlen
-
-       struct sres_st  sresdata;
-#define atp_sresiov    atp_data.sresdata.atpd_iov
-#define atp_sresiovcnt atp_data.sresdata.atpd_iovcnt
-    } atp_data;
-    u_int8_t           atp_bitmap;     /* response buffer bitmap */
-};
-
-
-/* flags for ATP options (and control byte)
-*/
-#define ATP_STS                (1<<3)          /* Send Transaction Status */
-#define ATP_EOM                (1<<4)          /* End Of Message */
-#define ATP_XO         (1<<5)          /* eXactly Once mode */
-
-/* function codes
-*/
-#define ATP_FUNCMASK   (3<<6)          /* mask all but function */
-
-#define ATP_TREQ       (1<<6)          /* Trans. REQuest */
-#define ATP_TRESP      (2<<6)          /* Trans. RESPonse */
-#define ATP_TREL       (3<<6)          /* Trans. RELease */
-
-extern ATP             atp_open  (u_int8_t, 
-                                      const struct at_addr *);
-extern int             atp_close (ATP);
-extern int             atp_sreq  (ATP, struct atp_block *, int, 
-                                      u_int8_t);
-extern int             atp_rresp (ATP, struct atp_block *);
-extern int             atp_rsel  (ATP, struct sockaddr_at *, int);
-extern int             atp_rreq  (ATP, struct atp_block *);
-extern int             atp_sresp (ATP, struct atp_block *);
-
-#endif  /* NO_DDP */
-#endif
index d7df70e1d164ddd82c5c61f44f9e07996500607a..2d3aa062b8b601c4ac016e4aa59d5d672e8e05c6 100644 (file)
  * This is instance of CNID database object.
  */
 struct _cnid_db {
-    u_int32_t flags;             /* Flags describing some CNID backend aspects. */
+    uint32_t flags;             /* Flags describing some CNID backend aspects. */
     char *volpath;               /* Volume path this particular CNID db refers to. */
     void *_private;              /* back-end speficic data */
 
-    cnid_t (*cnid_add)         (struct _cnid_db *cdb, const struct stat *st, const cnid_t did,
-                                char *name, const size_t, cnid_t hint);
+    cnid_t (*cnid_add)         (struct _cnid_db *cdb, const struct stat *st, cnid_t did,
+                                const char *name, size_t, cnid_t hint);
     int    (*cnid_delete)      (struct _cnid_db *cdb, cnid_t id);
-    cnid_t (*cnid_get)         (struct _cnid_db *cdb, const cnid_t did, char *name, const  size_t);
-    cnid_t (*cnid_lookup)      (struct _cnid_db *cdb, const struct stat *st, const cnid_t did,
-                                char *name, const size_t);
+    cnid_t (*cnid_get)         (struct _cnid_db *cdb, cnid_t did, const char *name, size_t);
+    cnid_t (*cnid_lookup)      (struct _cnid_db *cdb, const struct stat *st, cnid_t did,
+                                const char *name, size_t);
     cnid_t (*cnid_nextid)      (struct _cnid_db *cdb);
     char * (*cnid_resolve)     (struct _cnid_db *cdb, cnid_t *id, void *buffer, size_t len);
-    int    (*cnid_update)      (struct _cnid_db *cdb, const cnid_t id, const struct stat *st,
-                                const cnid_t did, char *name, const size_t len);
+    int    (*cnid_update)      (struct _cnid_db *cdb, cnid_t id, const struct stat *st,
+                                cnid_t did, const char *name, size_t len);
     void   (*cnid_close)       (struct _cnid_db *cdb);
     int    (*cnid_getstamp)    (struct _cnid_db *cdb, void *buffer, const size_t len);
-    cnid_t (*cnid_rebuild_add) (struct _cnid_db *, const struct stat *, const cnid_t,
-                                char *, const size_t, cnid_t);
-    int    (*cnid_find)        (struct _cnid_db *cdb, char *name, size_t namelen,
+    cnid_t (*cnid_rebuild_add) (struct _cnid_db *, const struct stat *, cnid_t,
+                                const char *, size_t, cnid_t);
+    int    (*cnid_find)        (struct _cnid_db *cdb, const char *name, size_t namelen,
                                 void *buffer, size_t buflen);
 };
 typedef struct _cnid_db cnid_db;
@@ -91,7 +91,7 @@ struct _cnid_module {
     char *name;
     struct list_head db_list;   /* CNID modules are also stored on a bidirectional list. */
     struct _cnid_db *(*cnid_open)(struct cnid_open_args *args);
-    u_int32_t flags;            /* Flags describing some CNID backend aspects. */
+    uint32_t flags;            /* Flags describing some CNID backend aspects. */
 
 };
 typedef struct _cnid_module cnid_module;
index 36dee3d8264890402fa6cc7b0f7d233c08efa706..d7484e42088d7c69ab71326f96d71c1d093bea86 100644 (file)
@@ -43,7 +43,7 @@ struct cnid_dbd_rqst {
     ino_t   ino;
     uint32_t type;
     cnid_t  did;
-    char    *name;
+    const char *name;
     size_t  namelen;
 };
 
@@ -56,7 +56,7 @@ struct cnid_dbd_rply {
 };
 
 typedef struct CNID_private {
-    u_int32_t magic;
+    uint32_t magic;
     char      db_dir[MAXPATHLEN + 1]; /* Database directory without /.AppleDB appended */
     char      *cnidserver;
     char      *cnidport;
index 429955349f74c9ca2572357c68851f5f359c1167..1c217c4ca752d4e34fc5a552c06ff16e9c2514ba 100644 (file)
@@ -6,91 +6,24 @@
  * are checks for EINTR everywhere. 
  */
 
-#include <sys/cdefs.h>
 #include <signal.h>
 
-#ifdef __svr4__
-/*
- * SunOS 5 (solaris) has SA_RESTART, but no SA_INTERRUPT.
- */
-#ifndef SA_INTERRUPT
-#define SA_INTERRUPT   0
-#endif
-
-#include <sys/types.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-extern int flock (int, int);
-extern int inet_aton (const char *, struct in_addr *);
-#else /* __svr4__ */
-
-#ifdef sun
-/*
- * SunOS 4 has SA_INTERRUPT, but no SA_RESTART.
- */
-#ifndef SA_RESTART
-#define SA_RESTART     0
-#endif
-#endif /* sun */
-
-#endif /* __svr4__ */
-
-#ifdef linux
-/*
- * Linux has SA_RESTART, but no SA_INTERRUPT.  Note that the documentation
- * seems to be wrong on several counts.  First, SA_ONESHOT is not the default,
- * and second, SA_RESTART does what you'd expect (the same as svr4) and has
- * nothing to do with SA_ONESHOT.
- */
-#ifndef SA_INTERRUPT
-#define SA_INTERRUPT   0
-#endif /* SA_INTERRUPT */
-#endif /* linux */
-
-#ifdef ultrix 
-#include <sys/types.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-/*
- * Here's the really confusing one...  Under Ultrix, sigaction() works just
- * like sigvec(), except that SV_INTERRUPT is always set.  Hence, there is
- * no SA_INTERRUPT flag.  Unfortunately, there's also no SA_RESTART, so
- * there's no way to suppress the interrupt.  Sigh.
- */
-#ifndef SA_INTERRUPT
-#define SA_INTERRUPT   0
-#endif
-#ifndef SA_RESTART
-#define SA_RESTART     0
-#endif
-
-extern char *strdup (const char *);
-extern int inet_aton (const char *, struct in_addr *);
-#endif /* ultrix */
-
-#ifdef BSD4_4
-#ifndef SA_INTERRUPT
-#define SA_INTERRUPT   0
-#endif
-#endif /* BSD4_4 */
+#include "config.h"
 
 #if defined(ultrix) || defined(_IBMR2) || defined(NEED_GETUSERSHELL)
 extern char *getusershell (void);
 #endif
 
 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
-#include <stdio.h>
-#include <stdarg.h>
-#endif
-
-#ifndef HAVE_SNPRINTF
+# include <stdio.h>
+# include <stdarg.h>
+# ifndef HAVE_SNPRINTF
 int snprintf (char *str,size_t count,const char *fmt,...);
-#endif
+# endif
 
-#ifndef HAVE_VSNPRINTF
+# ifndef HAVE_VSNPRINTF
 int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
+# endif
 #endif
 
 /* OpenBSD */
@@ -103,3 +36,25 @@ extern int pselect(int, fd_set * restrict, fd_set * restrict,
                    fd_set * restrict, const struct timespec * restrict,
                    const sigset_t * restrict);
 #endif
+
+#ifndef HAVE_FLOCK
+extern int flock (int, int);
+#endif
+
+#ifndef HAVE_INET_ATON
+struct in_addr;
+extern int inet_aton(const char *, struct in_addr *);
+#endif
+
+#ifndef HAVE_STRNLEN
+extern size_t strnlen(const char *s, size_t n);
+#endif
+
+#ifndef HAVE_STRLCPY
+extern size_t strlcpy (char *, const char *, size_t);
+#endif
+#ifndef HAVE_STRLCAT
+extern size_t strlcat (char *, const char *, size_t);
+#endif
+
diff --git a/include/atalk/ddp.h b/include/atalk/ddp.h
deleted file mode 100644 (file)
index f4ecd55..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef _ATALK_DDP_H
-#define _ATALK_DDP_H 1
-
-#ifndef NO_DDP
-
-#define DDPTYPE_RTMPRD 1
-#define DDPTYPE_NBP    2
-#define DDPTYPE_ATP    3
-#define DDPTYPE_AEP    4
-#define DDPTYPE_RTMPR  5
-#define DDPTYPE_ZIP    6
-#define DDPTYPE_ADSP   7
-
-#endif /* NO_DDP */
-#endif
diff --git a/include/atalk/dictionary.h b/include/atalk/dictionary.h
new file mode 100644 (file)
index 0000000..7a91052
--- /dev/null
@@ -0,0 +1,71 @@
+
+/*-------------------------------------------------------------------------*/
+/**
+   @file    dictionary.h
+   @author  N. Devillard
+   @date    Sep 2007
+   @version $Revision: 1.12 $
+   @brief   Implements a dictionary for string variables.
+
+   This module implements a simple dictionary object, i.e. a list
+   of string/string associations. This object is useful to store e.g.
+   informations retrieved from a configuration file (ini files).
+*/
+/*--------------------------------------------------------------------------*/
+
+/*
+       $Id: dictionary.h,v 1.12 2007-11-23 21:37:00 ndevilla Exp $
+       $Author: ndevilla $
+       $Date: 2007-11-23 21:37:00 $
+       $Revision: 1.12 $
+*/
+
+#ifndef _DICTIONARY_H_
+#define _DICTIONARY_H_
+
+/*---------------------------------------------------------------------------
+                                                               Includes
+ ---------------------------------------------------------------------------*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+/*---------------------------------------------------------------------------
+                                                               New types
+ ---------------------------------------------------------------------------*/
+
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Dictionary object
+
+  This object contains a list of string/string associations. Each
+  association is identified by a unique string key. Looking up values
+  in the dictionary is speeded up by the use of a (hopefully collision-free)
+  hash function.
+ */
+/*-------------------------------------------------------------------------*/
+typedef struct _dictionary_ {
+       int                             n ;             /** Number of entries in dictionary */
+       int                             size ;  /** Storage size */
+       char        **  val ;   /** List of string values */
+       char        **  key ;   /** List of string keys */
+       unsigned         *      hash ;  /** List of hash values for keys */
+} dictionary ;
+
+
+/*---------------------------------------------------------------------------
+                                                       Function prototypes
+ ---------------------------------------------------------------------------*/
+
+unsigned   dictionary_hash  (char * key);
+dictionary *dictionary_new  (int size);
+void       dictionary_del   (dictionary * vd);
+const char *dictionary_get  (const dictionary * d, const char *section, const char * key, const char * def);
+int        dictionary_set   (dictionary * vd, char *section, char * key, char * val);
+void       dictionary_unset (dictionary * d, char *section, char * key);
+void       dictionary_dump  (dictionary * d, FILE * out);
+
+#endif
index 801db32643b714a7af010fcee807ff1265b503f7..a2759aa18ca1cb455d73b0c1c6c3479a3c941882 100644 (file)
 #ifndef ATALK_DIRECTORY_H
 #define ATALK_DIRECTORY_H 1
 
-#include <sys/cdefs.h>
 #include <sys/types.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 #include <dirent.h>
 #include <stdint.h>
 
 #include <atalk/cnid.h>
 #include <atalk/bstrlib.h>
 #include <atalk/queue.h>
+#include <atalk/unicode.h>
 
 /* setgid directories */
 #ifndef DIRBITS
index eded2b8f5ad7d5e97980970694f1bf51381d6de8..bd8cc8b4e50ec700970fb05bcefa5f6267810cbe 100644 (file)
  * All rights reserved.
  */
 
-#ifndef _ATALK_DSI_H 
+#ifndef _ATALK_DSI_H
 #define _ATALK_DSI_H
 
-#include <sys/cdefs.h>
 #include <sys/types.h>
 #include <sys/time.h>
-#include <signal.h>
 #include <sys/socket.h>
+#include <signal.h>
+#include <arpa/inet.h>
 #include <netinet/in.h>
 
 #include <atalk/afp.h>
 #include <atalk/server_child.h>
 #include <atalk/globals.h>
-#include <netatalk/endian.h>
-
 
 /* What a DSI packet looks like:
- 0                               32
- |-------------------------------|
- |flags  |command| requestID     |
- |-------------------------------|
- |error code/enclosed data offset|
- |-------------------------------|
- |total data length              |
- |-------------------------------|
- |reserved field                 |
- |-------------------------------|
-
- CONVENTION: anything with a dsi_ prefix is kept in network byte order.
  0                               32
  |-------------------------------|
  |flags  |command| requestID     |
  |-------------------------------|
  |error code/enclosed data offset|
  |-------------------------------|
  |total data length              |
  |-------------------------------|
  |reserved field                 |
  |-------------------------------|
+
  CONVENTION: anything with a dsi_ prefix is kept in network byte order.
 */
 
-/* these need to be kept in sync w/ AFPTRANS_* in <atalk/afp.h>. 
+/* these need to be kept in sync w/ AFPTRANS_* in <atalk/afp.h>.
  * convention: AFPTRANS_* = (1 << DSI_*) */
 typedef enum {
-  DSI_MIN = 1,
-  DSI_TCPIP = 1,
-  DSI_MAX = 1
+    DSI_MIN = 1,
+    DSI_TCPIP = 1,
+    DSI_MAX = 1
 } dsi_proto;
 
 #define DSI_BLOCKSIZ 16
 struct dsi_block {
-  u_int8_t dsi_flags;       /* packet type: request or reply */
-  u_int8_t dsi_command;     /* command */
-  u_int16_t dsi_requestID;  /* request ID */
-  u_int32_t dsi_code;       /* error code or data offset */
-  u_int32_t dsi_len;        /* total data length */
-  u_int32_t dsi_reserved;   /* reserved field */
+    uint8_t dsi_flags;       /* packet type: request or reply */
+    uint8_t dsi_command;     /* command */
+    uint16_t dsi_requestID;  /* request ID */
+    uint32_t dsi_code;       /* error code or data offset */
+    uint32_t dsi_len;        /* total data length */
+    uint32_t dsi_reserved;   /* reserved field */
 };
 
-#define DSI_CMDSIZ        8192 
+#define DSI_CMDSIZ        8192
 #define DSI_DATASIZ       8192
 
 /* child and parent processes might interpret a couple of these
  * differently. */
 typedef struct DSI {
-  AFPObj *AFPobj;
-  dsi_proto protocol;
-  struct dsi_block header;
-  struct sockaddr_storage server, client;
-  struct itimerval timer;
-  int      tickle;        /* tickle count */
-  int     in_write;      /* in the middle of writing multiple packets,
-                             signal handlers can't write to the socket */
-  int      msg_request;   /* pending message to the client */
-  int      down_request;  /* pending SIGUSR1 down in 5 mn */
-
-  u_int32_t attn_quantum, datasize, server_quantum;
-  u_int16_t serverID, clientID;
-  char      *status;
-  u_int8_t  commands[DSI_CMDSIZ], data[DSI_DATASIZ];
-  size_t statuslen;
-  size_t datalen, cmdlen;
-  off_t  read_count, write_count;
-  uint32_t flags;             /* DSI flags like DSI_SLEEPING, DSI_DISCONNECTED */
-  const char *program; 
-  int socket, serversock;
-
-  /* protocol specific open/close, send/receive
-   * send/receive fill in the header and use dsi->commands.
-   * write/read just write/read data */
-  pid_t  (*proto_open)(struct DSI *);
-  void   (*proto_close)(struct DSI *);
-
-  /* url registered with slpd */
-#ifdef USE_SRVLOC
-  char srvloc_url[512];
-#endif 
+    struct DSI *next;             /* multiple listening addresses */
+    AFPObj   *AFPobj;
+    int      statuslen;
+    char     status[1400];
+    char     *signature;
+    struct dsi_block        header;
+    struct sockaddr_storage server, client;
+    struct itimerval        timer;
+    int      tickle;            /* tickle count */
+    int      in_write;          /* in the middle of writing multiple packets,
+                                   signal handlers can't write to the socket */
+    int      msg_request;       /* pending message to the client */
+    int      down_request;      /* pending SIGUSR1 down in 5 mn */
+
+    uint32_t attn_quantum, datasize, server_quantum;
+    uint16_t serverID, clientID;
+    uint8_t  commands[DSI_CMDSIZ], data[DSI_DATASIZ];
+    size_t   datalen, cmdlen;
+    off_t    read_count, write_count;
+    uint32_t flags;             /* DSI flags like DSI_SLEEPING, DSI_DISCONNECTED */
+    int      socket;            /* AFP session socket */
+    int      serversock;        /* listening socket */
+
+    /* DSI readahead buffer used for buffered reads in dsi_peek */
+    size_t   dsireadbuf;        /* size of the DSI readahead buffer used in dsi_peek() */
+    char     *buffer;           /* buffer start */
+    char     *start;            /* current buffer head */
+    char     *eof;              /* end of currently used buffer */
+    char     *end;
 
 #ifdef USE_ZEROCONF
-  char *bonjourname;      /* server name as UTF8 maxlen MAXINSTANCENAMELEN */
-  int zeroconf_registered;
+    char *bonjourname;      /* server name as UTF8 maxlen MAXINSTANCENAMELEN */
+    int zeroconf_registered;
 #endif
 
-  /* DSI readahead buffer used for buffered reads in dsi_peek */
-  size_t dsireadbuf; /* size of the DSI readahead buffer used in dsi_peek() */
-  char *buffer;
-  char *start;
-  char *eof;
-  char *end;
+    /* protocol specific open/close, send/receive
+     * send/receive fill in the header and use dsi->commands.
+     * write/read just write/read data */
+    pid_t  (*proto_open)(struct DSI *);
+    void   (*proto_close)(struct DSI *);
 } DSI;
-  
+
 /* DSI flags */
 #define DSIFL_REQUEST    0x00
 #define DSIFL_REPLY      0x01
@@ -125,17 +119,17 @@ typedef struct DSI {
 #define DSIFUNC_MAX     8       /* largest command */
 
 /* DSI Error codes: most of these aren't used. */
-#define DSIERR_OK      0x0000
-#define DSIERR_BADVERS 0xfbd6
-#define DSIERR_BUFSMALL        0xfbd5
-#define DSIERR_NOSESS  0xfbd4
-#define DSIERR_NOSERV  0xfbd3
-#define DSIERR_PARM    0xfbd2
-#define DSIERR_SERVBUSY        0xfbd1
-#define DSIERR_SESSCLOS        0xfbd0
-#define DSIERR_SIZERR  0xfbcf
-#define DSIERR_TOOMANY 0xfbce
-#define DSIERR_NOACK   0xfbcd
+#define DSIERR_OK   0x0000
+#define DSIERR_BADVERS  0xfbd6
+#define DSIERR_BUFSMALL 0xfbd5
+#define DSIERR_NOSESS   0xfbd4
+#define DSIERR_NOSERV   0xfbd3
+#define DSIERR_PARM 0xfbd2
+#define DSIERR_SERVBUSY 0xfbd1
+#define DSIERR_SESSCLOS 0xfbd0
+#define DSIERR_SIZERR   0xfbcf
+#define DSIERR_TOOMANY  0xfbce
+#define DSIERR_NOACK    0xfbcd
 
 /* server and client quanta */
 #define DSI_DEFQUANT        2           /* default attention quantum size */
@@ -162,15 +156,12 @@ typedef struct DSI {
 #endif
 
 /* basic initialization: dsi_init.c */
-extern DSI *dsi_init (const dsi_proto /*protocol*/,
-                         const char * /*program*/, 
-                         const char * /*host*/, const char * /*address*/,
-                         const char * /*port*/, const int /*proxy*/,
-                         const u_int32_t /* server quantum */);
+extern DSI *dsi_init(AFPObj *obj, const char *hostname, const char *address, const char *port);
 extern void dsi_setstatus (DSI *, char *, const size_t);
+extern int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address, const char *port);
 
 /* in dsi_getsess.c */
-extern afp_child_t *dsi_getsession (DSI *, server_child *, const int);
+extern int dsi_getsession (DSI *, server_child *, const int, afp_child_t **);
 extern void dsi_kill (int);
 
 
@@ -183,6 +174,8 @@ extern void dsi_getstatus (DSI *);
 extern void dsi_close (DSI *);
 
 #define DSI_NOWAIT 1
+#define DSI_MSG_MORE 2
+
 /* low-level stream commands -- in dsi_stream.c */
 extern ssize_t dsi_stream_write (DSI *, void *, const size_t, const int mode);
 extern size_t dsi_stream_read (DSI *, void *, const size_t);
@@ -191,7 +184,7 @@ extern int dsi_stream_receive (DSI *);
 extern int dsi_disconnect(DSI *dsi);
 
 #ifdef WITH_SENDFILE
-extern ssize_t dsi_stream_read_file(DSI *, int, off_t off, const size_t len);
+extern ssize_t dsi_stream_read_file(DSI *, int, off_t off, const size_t len, const int err);
 #endif
 
 /* client writes -- dsi_write.c */
@@ -202,15 +195,15 @@ extern void   dsi_writeflush (DSI *);
 
 /* client reads -- dsi_read.c */
 extern ssize_t dsi_readinit (DSI *, void *, const size_t, const size_t,
-                                const int);
+                             const int);
 extern ssize_t dsi_read (DSI *, void *, const size_t);
 extern void dsi_readdone (DSI *);
 
 /* some useful macros */
 #define dsi_serverID(x)   ((x)->serverID++)
-#define dsi_send(x)       do { \
-    (x)->header.dsi_len = htonl((x)->cmdlen); \
-    dsi_stream_send((x), (x)->commands, (x)->cmdlen); \
-} while (0)
+#define dsi_send(x)       do {                              \
+        (x)->header.dsi_len = htonl((x)->cmdlen);           \
+        dsi_stream_send((x), (x)->commands, (x)->cmdlen);   \
+    } while (0)
 
 #endif /* atalk/dsi.h */
index c0165a1a257f210999055d8a271bc81dadf9e2a8..228970373a54567e6e35eec6935034938c5dffaf 100644 (file)
@@ -1,5 +1,4 @@
 /*
-   $Id: ea.h,v 1.11 2010-03-12 15:16:49 franklahm Exp $
    Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
 
    This program is free software; you can redistribute it and/or modify
 #include <config.h>
 #endif
 
+#if HAVE_ATTR_XATTR_H
+#include <attr/xattr.h>
+#elif HAVE_SYS_XATTR_H
+#include <sys/xattr.h>
+#endif
+
+#ifdef HAVE_SYS_EA_H
+#include <sys/ea.h>
+#endif
+
+#ifdef HAVE_SYS_EXTATTR_H
+#include <sys/extattr.h>
+#endif
+
 #ifdef HAVE_SOLARIS_ACLS
 #include <sys/acl.h>
 #endif
 
+#ifndef ENOATTR
+#define ENOATTR ENODATA
+#endif
+
 #include <atalk/vfs.h>
 
 /*
@@ -56,6 +73,28 @@ enum {
 #define XATTR_REPLACE 0x2       /* set value, fail if attr does not exist */
 #endif
 
+/* Names for our Extended Attributes adouble data */
+#define AD_EA_META "org.netatalk.Metadata"
+#define AD_EA_RESO "org.netatalk.ResourceFork"
+#define NOT_NETATALK_EA(a) (strcmp((a), AD_EA_META) != 0) && (strcmp((a), AD_EA_RESO) != 0)
+
+/****************************************************************************************
+ * Wrappers for native EA functions taken from Samba
+ ****************************************************************************************/
+ssize_t sys_getxattr (const char *path, const char *name, void *value, size_t size);
+ssize_t sys_lgetxattr (const char *path, const char *name, void *value, size_t size);
+ssize_t sys_fgetxattr (int filedes, const char *name, void *value, size_t size);
+ssize_t sys_listxattr (const char *path, char *list, size_t size);
+ssize_t sys_llistxattr (const char *path, char *list, size_t size);
+ssize_t sys_flistxattr (int filedes, char *list, size_t size);
+int sys_removexattr (const char *path, const char *name);
+int sys_lremovexattr (const char *path, const char *name);
+int sys_fremovexattr (int filedes, const char *name);
+int sys_setxattr (const char *path, const char *name, const void *value, size_t size, int flags);
+int sys_lsetxattr (const char *path, const char *name, const void *value, size_t size, int flags);
+int sys_fsetxattr (int filedes, const char *name, const void *value, size_t size, int flags);
+int sys_copyxattr (const char *src, const char *dst);
+int sys_getxattrfd(int fd, const char *uname, int oflag, ...);
 
 /****************************************************************************************
  * Stuff for our implementation of storing EAs in files in .AppleDouble dirs
index 78e530a8e95227eac265a01e27dcdedbc7081216..094065b9d5a7d6a799680eba3f2eac91c197e65a 100644 (file)
 #define EC_INIT int ret = 0
 #define EC_STATUS(a) ret = (a)
 #define EC_FAIL do { ret = -1; goto cleanup; } while (0)
+#define EC_FAIL_LOG(a, ...)                     \
+    do {               \
+        LOG(log_error, logtype_default, a, __VA_ARGS__);   \
+        ret = -1;      \
+        goto cleanup;  \
+    } while (0)
 #define EC_CLEANUP cleanup
 #define EC_EXIT return ret
 
index 9175afe90be69dffbc8bffd14e721762c45031a0..aebb56adffcdafdb9463b712afa9fe91685186e0 100755 (executable)
@@ -54,7 +54,7 @@ int fce_register_file_modification( struct ofork *ofork );
 int fce_register_tm_size(const char *vol, size_t used);
 
 int fce_add_udp_socket(const char *target );  // IP or IP:Port
-int fce_set_coalesce( char *coalesce_opt ); // all|delete|create
+int fce_set_coalesce(const char *coalesce_opt ); // all|delete|create
 int fce_set_events(const char *events);     /* fmod,fdel,ddel,fcre,dcre,tmsz (default is all except tmsz) */
 
 #define FCE_DEFAULT_PORT 12250
index 68e68a32f3f403f6dea131dde173883a1dae9d90..28d928b418a2264d51103628db3a82cb38a2bfd3 100644 (file)
@@ -7,7 +7,6 @@
 #define AFPD_GLOBALS_H 1
 
 #include <sys/param.h>
-#include <sys/cdefs.h>
 
 #ifdef ADMIN_GRP
 #include <grp.h>
 #include <netdb.h>  /* this isn't header-protected under ultrix */
 #endif /* HAVE_NETDB_H */
 
-#include <netatalk/at.h>
 #include <atalk/afp.h>
 #include <atalk/compat.h>
 #include <atalk/unicode.h>
 #include <atalk/uam.h>
+#include <atalk/iniparser.h>
 
 /* #define DOSFILELEN 12 */             /* Type1, DOS-compat*/
 #define MACFILELEN 31                   /* Type2, HFS-compat */
 
 #define MAXUSERLEN 256
 
+#define DEFAULT_MAX_DIRCACHE_SIZE 8192
+
 #define OPTION_DEBUG         (1 << 0)
-#define OPTION_USERVOLFIRST  (1 << 1)
-#define OPTION_NOUSERVOL     (1 << 2)
-#define OPTION_PROXY         (1 << 3)
-#define OPTION_CUSTOMICON    (1 << 4)
-#define OPTION_NOSLP         (1 << 5)
+#define OPTION_CLOSEVOL      (1 << 1)
+#define OPTION_SERVERNOTIF   (1 << 2)
+#define OPTION_NOSENDFILE    (1 << 3)
+/* #define OPTION_CUSTOMICON    (1 << 4) */
+#define OPTION_AFP_READ_LOCK (1 << 5) /* whether to do AFP spec conforming read locks (default: no) */
 #define OPTION_ANNOUNCESSH   (1 << 6)
 #define OPTION_UUID          (1 << 7)
 #define OPTION_ACL2MACCESS   (1 << 8)
 #define OPTION_NOZEROCONF    (1 << 9)
 #define OPTION_KEEPSESSIONS  (1 << 10) /* preserve sessions across master afpd restart with SIGQUIT */
+#define OPTION_SHARE_RESERV  (1 << 11) /* whether to use Solaris fcntl F_SHARE locks */
+
+#define PASSWD_NONE     0
+#define PASSWD_SET     (1 << 0)
+#define PASSWD_NOSAVE  (1 << 1)
+#define PASSWD_ALL     (PASSWD_SET | PASSWD_NOSAVE)
+
+#define IS_AFP_SESSION(obj) ((obj)->dsi && (obj)->dsi->serversock == -1)
+
+/**********************************************************************************************
+ * Ini config sections
+ **********************************************************************************************/
 
-#ifdef FORCE_UIDGID
-/* set up a structure for this */
-typedef struct uidgidset_t {
-    uid_t uid;
-    gid_t gid;
-} uidgidset;
-#endif /* FORCE_UIDGID */
+#define INISEC_GLOBAL "Global"
+#define INISEC_HOMES  "Homes"
+
+struct DSI;
+#define AFPOBJ_TMPSIZ (MAXPATHLEN)
 
-/* a couple of these options could get stuck in unions to save
- * space. */
 struct afp_volume_name {
     time_t     mtime;
-    char       *name;
-    char       *full_name;
     int        loaded;
 };
 
 struct afp_options {
-    int connections, transports, tickleval, timeout, server_notif, flags, dircachesize;
+    int connections;            /* Maximum number of possible AFP connections */
+    int tickleval;
+    int timeout;
+    int flags;
+    int dircachesize;
     int sleep;                  /* Maximum time allowed to sleep (in tickles) */
     int disconnected;           /* Maximum time in disconnected state (in tickles) */
     int fce_fmodwait;           /* number of seconds FCE file mod events are put on hold */
     unsigned int tcp_sndbuf, tcp_rcvbuf;
-    unsigned char passwdbits, passwdminlen, loginmaxfail;
-    u_int32_t server_quantum;
+    unsigned char passwdbits, passwdminlen;
+    uint32_t server_quantum;
     int dsireadbuf; /* scale factor for sizefof(dsi->buffer) = server_quantum * dsireadbuf */
-    char hostname[MAXHOSTNAMELEN + 1], *server, *ipaddr, *port, *configfile;
-#ifndef NO_DDP
-    struct at_addr ddpaddr;
-#endif
+    char *hostname;
+    char *listen, *port;
+    char *Cnid_srv, *Cnid_port;
+    char *configfile;
     char *uampath, *fqdn;
-    char *pidfile;
     char *sigconffile;
     char *uuidconf;
-    struct afp_volume_name defaultvol, systemvol, uservol;
-    int  closevol;
-
     char *guest, *loginmesg, *keyfile, *passwdfile;
     char *uamlist;
-    char *authprintdir;
     char *signatureopt;
     unsigned char signature[16];
     char *k5service, *k5realm, *k5keytab;
-    char *unixcodepage,*maccodepage;
+    char *unixcodepage, *maccodepage, *volcodepage;
     charset_t maccharset, unixcharset; 
     mode_t umask;
     mode_t save_mask;
@@ -96,37 +102,37 @@ struct afp_options {
     gid_t admingid;
 #endif /* ADMIN_GRP */
     int    volnamelen;
-
     /* default value for winbind authentication */
     char *ntdomain, *ntseparator;
     char *logconfig;
-
+    char *logfile;
     char *mimicmodel;
     char *adminauthuser;
+    struct afp_volume_name volfile;
 };
 
-#define AFPOBJ_TMPSIZ (MAXPATHLEN)
-typedef struct _AFPObj {
-    int proto;
-    unsigned long servernum;
-    void *handle;               /* either (DSI *) or (ASP *) */
-    void *config; 
+typedef struct AFPObj {
+    const char *cmdlineconfigfile;
+    int cmdlineflags;
+    const void *signature;
+    struct DSI *dsi;
     struct afp_options options;
-    char *Obj, *Type, *Zone;
+    dictionary *iniconfig;
     char username[MAXUSERLEN];
-    void (*logout)(void), (*exit)(int);
-    int (*reply)(void *, int);
-    int (*attention)(void *, AFPUserBytes);
     /* to prevent confusion, only use these in afp_* calls */
     char oldtmp[AFPOBJ_TMPSIZ + 1], newtmp[AFPOBJ_TMPSIZ + 1];
     void *uam_cookie; /* cookie for uams */
     struct session_info  sinfo;
     uid_t uid;         /* client running user id */
     int ipc_fd; /* anonymous PF_UNIX socket for IPC with afpd parent */
-#ifdef FORCE_UIDGID
-    int                 force_uid;
-    uidgidset          uidgid;
-#endif
+    gid_t *groups;
+    int ngroups;
+    int afp_version;
+    /* Functions */
+    void (*logout)(void);
+    void (*exit)(int);
+    int (*reply)(void *, int);
+    int (*attention)(void *, AFPUserBytes);
 } AFPObj;
 
 /* typedef for AFP functions handlers */
@@ -145,10 +151,8 @@ extern const char         *Cnid_port;
 
 extern int  get_afp_errno   (const int param);
 extern void afp_options_init (struct afp_options *);
-extern int afp_options_parse (int, char **, struct afp_options *);
-extern int afp_options_parseline (char *, struct afp_options *);
-extern void afp_options_free (struct afp_options *,
-                                      const struct afp_options *);
+extern void afp_options_parse_cmdline(AFPObj *obj, int ac, char **av);
+extern void afp_options_free(struct afp_options *);
 extern void setmessage (const char *);
 extern void readmessage (AFPObj *);
 
@@ -163,9 +167,6 @@ extern const char *AfpErr2name(int err);
 /* directory.c */
 extern struct dir rootParent;
 
-#ifndef NO_DDP
-extern void afp_over_asp (AFPObj *);
-#endif /* NO_DDP */
 extern void afp_over_dsi (AFPObj *);
 
 #endif /* globals.h */
diff --git a/include/atalk/iniparser.h b/include/atalk/iniparser.h
new file mode 100644 (file)
index 0000000..0eefa4c
--- /dev/null
@@ -0,0 +1,52 @@
+
+/*-------------------------------------------------------------------------*/
+/**
+   @file    iniparser.h
+   @author  N. Devillard
+   @date    Sep 2007
+   @version 3.0
+   @brief   Parser for ini files.
+*/
+/*--------------------------------------------------------------------------*/
+
+/*
+       $Id: iniparser.h,v 1.26 2011-03-02 20:15:13 ndevilla Exp $
+       $Revision: 1.26 $
+*/
+
+#ifndef _INIPARSER_H_
+#define _INIPARSER_H_
+
+/*---------------------------------------------------------------------------
+                                                               Includes
+ ---------------------------------------------------------------------------*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/*
+ * The following #include is necessary on many Unixes but not Linux.
+ * It is not needed for Windows platforms.
+ * Uncomment it if needed.
+ */
+/* #include <unistd.h> */
+
+#include "dictionary.h"
+
+int        iniparser_getnsec(const dictionary * d);
+const char *iniparser_getsecname(const dictionary * d, int n);
+void       iniparser_dump_ini(const dictionary * d, FILE * f);
+void       iniparser_dump(const dictionary * d, FILE * f);
+const char *iniparser_getstring(const dictionary * d, const char *section, const char * key, const char * def);
+char       *iniparser_getstrdup(const dictionary * d, const char *section, const char * key, const char * def);
+int        iniparser_getint(const dictionary * d, const char *section, const char * key, int notfound);
+double     iniparser_getdouble(const dictionary * d, const char *section, const char * key, double notfound);
+int        iniparser_getboolean(const dictionary * d, const char *section, const char * key, int notfound);
+int        iniparser_set(dictionary * ini, char *section, char * key, char * val);
+void       iniparser_unset(dictionary * ini, char *section, char * key);
+int        iniparser_find_entry(const dictionary * ini, const char * entry) ;
+dictionary *iniparser_load(const char * ininame);
+void       iniparser_freedict(dictionary * d);
+
+#endif
index f170f036d01c8deebd591f6cf4bec44295b42b2d..90a1c95b6eddb3a450d9e6f272f7277a78f17f4f 100644 (file)
@@ -3,8 +3,10 @@
 #ifndef LDAPCONFIG_H
 #define LDAPCONFIG_H
 
+#include <atalk/iniparser.h>
+
 /* One function does the whole job */
-extern int acl_ldap_readconfig(char *name);
+extern int acl_ldap_readconfig(dictionary *iniconfig);
 
 /* These are the prefvalues */
 extern char *ldap_server;
@@ -20,7 +22,7 @@ extern char *ldap_group_attr;
 extern char *ldap_uid_attr;
 
 struct ldap_pref {
-    void *pref;
+    const void *pref;
     char *name;
     int strorint;     /* string to just store in char * or convert to int ? */
     int intfromarray; /* convert to int, but use string to int mapping array pref_array[] */
@@ -28,7 +30,7 @@ struct ldap_pref {
 };
 
 struct pref_array {
-    char *pref;         /* name of pref from ldap_prefs[] to which this value corresponds */
+    const char *pref;         /* name of pref from ldap_prefs[] to which this value corresponds */
     char *valuestring;  /* config string */
     int  value;         /* corresponding value */
 };
index 0c6e7d8536a85d2c3ee2ae219c44c2f8d909163e..cf67bcad6f5260d8b1e0d42b3812e77a9b492521 100644 (file)
@@ -159,28 +159,7 @@ extern UAM_MODULE_EXPORT logtype_conf_t type_configs[logtype_end_of_list_marker]
     Global function decarations
    ========================================================================= */
 
-/*  */
-void log_init(void);
-
-/* Setup the level and type of log that will be logged for file loggging */
-void log_setup(const char *filename, enum loglevels loglevel, enum logtypes logtype);
-
-/* Setup the level and type of log that will be logged to syslog. */
-void syslog_setup(int loglevel, enum logtypes logtype, 
-                 int display_options, int facility);
-
-/* This gets called e.g. from afpd.conf parsing code with a string like: */
-/* "default log_maxdebug /var/log/afpd.log" */
-void setuplog(const char *logstr);
-
-/* This gets called e.g. from afpd.conf parsing code with a string like: */
-/* "default dummyname" */
-void unsetuplog(const char *logstr);
-
-/* finish up and close the logs */
-void log_close(void);
-
-/* This function sets up the ProcessName */
+void setuplog(const char *loglevel, const char *logfile);
 void set_processname(const char *processname);
 
 /* LOG macro func no.1: log the message to file */
@@ -193,9 +172,6 @@ UAM_MODULE_EXPORT  void make_log_entry(enum loglevels loglevel, enum logtypes lo
  * We choose the verbose form in favor of the obfuscated ones, its easier
  * to parse for human beings and facilitates expanding the macro for
  * inline checks for debug levels.
- *
- * How to properly enclose multistatement macros:
- * http://en.wikipedia.org/wiki/C_macro#Multiple_statements
  */
 
 #define LOG_MAX log_info
diff --git a/include/atalk/nbp.h b/include/atalk/nbp.h
deleted file mode 100644 (file)
index 45bae00..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef _ATALK_NBP_H
-#define _ATALK_NBP_H 1
-
-#ifndef NO_DDP
-
-#define NBP_UNRGSTR_4ARGS 1
-#define ATP_OPEN_2ARGS 1
-
-#include <sys/cdefs.h>
-#include <sys/types.h>
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-
-struct nbphdr {
-#if BYTE_ORDER == BIG_ENDIAN
-    unsigned   nh_op : 4,
-               nh_cnt : 4,
-#else /* BYTE_ORDER != BIG_ENDIAN */
-    unsigned   nh_cnt : 4,
-               nh_op : 4,
-#endif /* BYTE_ORDER */
-               nh_id : 8;
-};
-
-#define SZ_NBPHDR      2
-
-struct nbptuple {
-    u_int16_t   nt_net;
-    u_int8_t    nt_node;
-    u_int8_t    nt_port;
-    u_int8_t    nt_enum;
-};
-#define SZ_NBPTUPLE    5
-
-#define NBPSTRLEN      32
-/*
- * Name Binding Protocol Network Visible Entity
- */
-struct nbpnve {
-    struct sockaddr_at nn_sat;
-    u_char             nn_objlen;
-    char               nn_obj[ NBPSTRLEN ];
-    u_char             nn_typelen;
-    char               nn_type[ NBPSTRLEN ];
-    u_char             nn_zonelen;
-    char               nn_zone[ NBPSTRLEN ];
-};
-
-/*
- * Note that NBPOP_ERROR is not standard. As Apple adds more NBPOPs,
- * we need to check for collisions with our extra values.  */
-#define NBPOP_BRRQ      0x1
-#define NBPOP_LKUP      0x2
-#define NBPOP_LKUPREPLY         0x3
-#define NBPOP_FWD       0x4
-#define NBPOP_RGSTR     0x7
-#define NBPOP_UNRGSTR   0x8
-#define NBPOP_CONFIRM    0x9
-#define NBPOP_OK        0xa  /* NBPOP_STATUS_REPLY */
-#define NBPOP_CLOSE_NOTE 0xb
-
-#define NBPOP_ERROR     0xf
-
-#define NBPMATCH_NOGLOB        (1<<1)
-#define NBPMATCH_NOZONE        (1<<2)
-
-extern int nbp_name (const char *, char **, char **, char **);
-extern int nbp_lookup (const char *, const char *, const char *,
-                          struct nbpnve *, const int, 
-                          const struct at_addr *);
-extern int nbp_rgstr (struct sockaddr_at *, 
-                         const char *, const char *, const char *);
-extern int nbp_unrgstr (const char *, const char *, const char *,
-                           const struct at_addr *);
-
-#endif  /* NO_DDP */
-#endif
diff --git a/include/atalk/netatalk_conf.h b/include/atalk/netatalk_conf.h
new file mode 100644 (file)
index 0000000..33459b3
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+   Copyright (c) 2012 Frank Lahm <franklahm@gmail.com>
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+ */
+
+#ifndef AFP_CONFIG_H
+#define AFP_CONFIG_H
+
+#include <stdint.h>
+
+#include <atalk/globals.h>
+#include <atalk/volume.h>
+
+extern int        afp_config_parse(AFPObj *obj, char *processname);
+
+extern int        load_charset(struct vol *vol);
+extern int        load_volumes(AFPObj *obj, void (*delvol_fn)(const AFPObj *obj, struct vol *));
+extern void       unload_volumes(AFPObj *obj);
+extern struct vol *getvolumes(void);
+extern struct vol *getvolbyvid(const uint16_t);
+extern struct vol *getvolbypath(AFPObj *obj, const char *path);
+extern struct vol *getvolbyname(const char *name);
+extern void       volume_free(struct vol *vol);
+extern void       volume_unlink(struct vol *volume);
+#endif
diff --git a/include/atalk/netddp.h b/include/atalk/netddp.h
deleted file mode 100644 (file)
index e6bccd4..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * $Id: netddp.h,v 1.4 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
- * All Rights Reserved. See COPYRIGHT.
- *
- * this provides a generic interface to the ddp layer. with this, we
- * should be able to interact with any appletalk stack that allows
- * direct access to the ddp layer. right now, only os x server's ddp
- * layer and the generic socket based interfaces are understood.  
- */
-
-#ifndef _ATALK_NETDDP_H
-#define _ATALK_NETDDP_H 1
-
-#ifndef NO_DDP
-
-#include <sys/types.h>
-#include <sys/cdefs.h>
-#include <sys/socket.h>
-#include <netatalk/at.h>
-
-extern int netddp_open   (struct sockaddr_at *, struct sockaddr_at *);
-
-#if !defined(NO_DDP) && defined(MACOSX_SERVER)
-extern int netddp_sendto (int, void *, size_t, unsigned int, 
-                          const struct sockaddr *, unsigned int);
-extern int netddp_recvfrom (int, void *, int, unsigned int, 
-                            struct sockaddr *, unsigned int *);
-#define netddp_close(a)  ddp_close(a)
-#else
-#include <unistd.h>
-#include <sys/types.h>
-
-#define netddp_close(a)  close(a)
-#define netddp_sendto    sendto
-#define netddp_recvfrom  recvfrom
-#endif
-
-#endif  /* NO_DDP */
-#endif /* netddp.h */
-
diff --git a/include/atalk/pap.h b/include/atalk/pap.h
deleted file mode 100644 (file)
index 3d40082..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef _ATALK_PAP_H
-#define _ATALK_PAP_H 1
-
-#ifndef NO_DDP
-
-#define PAP_OPEN       1
-#define PAP_OPENREPLY  2
-#define PAP_READ       3
-#define PAP_DATA       4
-#define PAP_TICKLE     5
-#define PAP_CLOSE      6
-#define PAP_CLOSEREPLY 7
-#define PAP_SENDSTATUS 8
-#define PAP_STATUS     9
-
-#define PAP_MAXDATA    512
-#define PAP_MAXQUANTUM 8
-
-#endif  /* NO_DDP */
-#endif
index 98eb44b06864523836bfbef244da7687b2c8686e..1aab969094f0c22cb48b328abfa249ccdc3a4a89 100644 (file)
 #  endif
 #endif
 
-/*
- * papd paths
- */
-#define _PATH_PAPDPRINTCAP     "/etc/printcap"
-#ifdef ultrix
-#define _PATH_PAPDSPOOLDIR     "/usr/spool/lpd"
-#else /* !ultrix */
-#define _PATH_PAPDSPOOLDIR     "/var/spool/lpd"
-#endif /* ultrix */
-#ifdef BSD4_4
-#define _PATH_DEVPRINTER       "/var/run/printer"
-#else /* !BSD4_4 */
-#define _PATH_DEVPRINTER       "/dev/printer"
-#endif /* BSD4_4 */
 
 /*
- * atalkd paths
- */
-#define _PATH_ATALKDEBUG       "/tmp/atalkd.debug"
-#define _PATH_ATALKDTMP                "atalkd.tmp"
-#if defined (FHS_COMPATIBILITY) || defined (__NetBSD__) || defined (__OpenBSD__)
-#  define _PATH_ATALKDLOCK     ATALKPATHCAT(_PATH_LOCKDIR,"atalkd.pid")
-#else
-#  define _PATH_ATALKDLOCK     ATALKPATHCAT(_PATH_LOCKDIR,"atalkd")
-#endif
-
-/*
- * psorder paths
- */
-#define _PATH_TMPPAGEORDER     "/tmp/psorderXXXXXX"
-#if defined (FHS_COMPATIBILITY) || defined (__NetBSD__) || defined (__OpenBSD__)
-#  define _PATH_PAPDLOCK       ATALKPATHCAT(_PATH_LOCKDIR,"papd.pid")
-#else
-#  define _PATH_PAPDLOCK       ATALKPATHCAT(_PATH_LOCKDIR,"papd")
-#endif
-
-/*
- * afpd paths
+ * netatalk paths
  */
 #define _PATH_AFPTKT           "/tmp/AFPtktXXXXXX"
 #define _PATH_AFP_IPC       ATALKPATHCAT(_PATH_LOCKDIR,"afpd_ipc")
 #if defined (FHS_COMPATIBILITY) || defined (__NetBSD__) || defined (__OpenBSD__)
-#  define _PATH_AFPDLOCK       ATALKPATHCAT(_PATH_LOCKDIR,"afpd.pid")
-#else
-#  define _PATH_AFPDLOCK       ATALKPATHCAT(_PATH_LOCKDIR,"afpd")
-#endif
-
-/*
- * cnid_metad paths
- */
-#if defined (FHS_COMPATIBILITY) || defined (__NetBSD__) || defined (__OpenBSD__)
-#  define _PATH_CNID_METAD_LOCK        ATALKPATHCAT(_PATH_LOCKDIR,"cnid_metad.pid")
+#  define _PATH_NETATALK_LOCK  ATALKPATHCAT(_PATH_LOCKDIR,"netatalk.pid")
 #else
-#  define _PATH_CNID_METAD_LOCK        ATALKPATHCAT(_PATH_LOCKDIR,"cnid_metad")
+#  define _PATH_NETATALK_LOCK  ATALKPATHCAT(_PATH_LOCKDIR,"netatalk")
 #endif
 
 #endif /* atalk/paths.h */
+
diff --git a/include/atalk/rpc.h b/include/atalk/rpc.h
new file mode 100644 (file)
index 0000000..00a385d
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2011 Frank Lahm
+ * All Rights Reserved.  See COPYRIGHT.
+ */
+
+#ifndef ATALK_RPC_H
+#define ATALK_RPC_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <sys/types.h>
+#include <inttypes.h>
+
+#include <atalk/lockrpc.gen.h>
+
+#include "event2/event.h"
+#include "event2/http.h"
+#include "event2/rpc.h"
+
+struct adouble;
+extern int rpc_init(const char *addr, unsigned short port);
+extern int rpc_lock(struct adouble *, uint32_t eid, int type, off_t off, off_t len, int user);
+extern void rpc_unlock(struct adouble *, int user);
+extern int rpc_tmplock(struct adouble *, uint32_t eid, int type, off_t off, off_t len, int user);
+
+#endif  /* ATALK_RPC_H */
diff --git a/include/atalk/rtmp.h b/include/atalk/rtmp.h
deleted file mode 100644 (file)
index 474bd5a..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef _ATALK_RTMP_H
-#define _ATALK_RTMP_H 1
-
-#ifndef NO_DDP
-
-#include <netatalk/endian.h>
-
-#define RTMPROP_REQUEST        1
-
-struct rtmpent {
-    u_int16_t   re_net;
-    u_int8_t    re_hops;
-};
-
-#define RTMPHOPS_MAX   15
-#define RTMPHOPS_POISON        31
-
-struct rtmprdhdr {
-    u_int16_t   rrdh_snet;
-    u_int8_t    rrdh_idlen;
-    u_int8_t    rrdh_id;
-};
-
-#endif  /* NO_DDP */
-#endif
index 5ee8314f3dd44c40992e788c7009a69ba20f782d..ad41bceccec2441f95ee4907547e1b93d39ce4ba 100644 (file)
@@ -6,9 +6,8 @@
 #ifndef _ATALK_SERVER_CHILD_H
 #define _ATALK_SERVER_CHILD_H 1
 
-#include <sys/cdefs.h>
 #include <sys/types.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 
 /* useful stuff for child processes. most of this is hidden in 
  * server_child.c to ease changes in implementation */
@@ -36,8 +35,6 @@ typedef struct server_child_data {
   struct server_child_data **prevp, *next;
 } afp_child_t;
 
-extern int parent_or_child;
-
 /* server_child.c */
 extern server_child *server_child_alloc (const int, const int);
 extern afp_child_t *server_child_add (server_child *, int, pid_t, int ipc_fd);
@@ -46,7 +43,7 @@ extern void server_child_free (server_child *);
 
 extern void server_child_kill (server_child *, const int, const int);
 extern void server_child_kill_one_by_id (server_child *children, const int forkid, const pid_t pid, const uid_t,
-                                               const u_int32_t len, char *id, u_int32_t boottime);
+                                               const uint32_t len, char *id, uint32_t boottime);
 extern int  server_child_transfer_session(server_child *children, int forkid, pid_t, uid_t, int, uint16_t);
 extern void server_child_setup (server_child *, const int, void (*)(const pid_t));
 extern void server_child_handler (server_child *);
index 6f3b1ff7562786e90a7f4715d1a8349206f32710..789649a1a6ded108932ddd9d90f52b0be10a4b14 100644 (file)
@@ -3,33 +3,40 @@
 
 /* 
    Unix SMB/CIFS implementation.
-   Samba database functions
-   Copyright (C) Andrew Tridgell 1999
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell 1999-2004
    
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
-   (at your option) any later version.
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
    
-   This program is distributed in the hope that it will be useful,
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU 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., 675 Mass Ave, Cambridge, MA 02139, USA.
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifdef  __cplusplus
 extern "C" {
 #endif
 
+#include <sys/types.h>
+#include <signal.h>
 
 /* flags to tdb_store() */
-#define TDB_REPLACE 1
-#define TDB_INSERT 2
-#define TDB_MODIFY 3
+#define TDB_REPLACE 1          /* Unused */
+#define TDB_INSERT 2           /* Don't overwrite an existing entry */
+#define TDB_MODIFY 3           /* Don't create an existing entry    */
 
 /* flags for tdb_open() */
 #define TDB_DEFAULT 0 /* just a readability place holder */
@@ -39,101 +46,127 @@ extern "C" {
 #define TDB_NOMMAP   8 /* don't use mmap */
 #define TDB_CONVERT 16 /* convert endian (internal use) */
 #define TDB_BIGENDIAN 32 /* header is big-endian (internal use) */
-
-#define TDB_ERRCODE(code, ret) ((tdb->ecode = (code)), ret)
+#define TDB_NOSYNC   64 /* don't use synchronous transactions */
+#define TDB_SEQNUM   128 /* maintain a sequence number */
+#define TDB_VOLATILE   256 /* Activate the per-hashchain freelist, default 5 */
+#define TDB_ALLOW_NESTING 512 /* Allow transactions to nest */
+#define TDB_DISALLOW_NESTING 1024 /* Disallow transactions to nest */
 
 /* error codes */
 enum TDB_ERROR {TDB_SUCCESS=0, TDB_ERR_CORRUPT, TDB_ERR_IO, TDB_ERR_LOCK, 
-               TDB_ERR_OOM, TDB_ERR_EXISTS, TDB_ERR_NOEXIST, TDB_ERR_NOLOCK, TDB_ERR_LOCK_TIMEOUT };
+               TDB_ERR_OOM, TDB_ERR_EXISTS, TDB_ERR_NOLOCK, TDB_ERR_LOCK_TIMEOUT,
+               TDB_ERR_NOEXIST, TDB_ERR_EINVAL, TDB_ERR_RDONLY,
+               TDB_ERR_NESTING};
 
-#ifndef u32
-#define u32 unsigned
-#endif
+/* debugging uses one of the following levels */
+enum tdb_debug_level {TDB_DEBUG_FATAL = 0, TDB_DEBUG_ERROR, 
+                     TDB_DEBUG_WARNING, TDB_DEBUG_TRACE};
 
-typedef struct {
-       char *dptr;
+typedef struct TDB_DATA {
+       unsigned char *dptr;
        size_t dsize;
 } TDB_DATA;
 
-typedef u32 tdb_len;
-typedef u32 tdb_off;
+#ifndef PRINTF_ATTRIBUTE
+#if (__GNUC__ >= 3)
+/** Use gcc attribute to check printf fns.  a1 is the 1-based index of
+ * the parameter containing the format, and a2 the index of the first
+ * argument. Note that some gcc 2.x versions don't handle this
+ * properly **/
+#define PRINTF_ATTRIBUTE(a1, a2) __attribute__ ((format (__printf__, a1, a2)))
+#else
+#define PRINTF_ATTRIBUTE(a1, a2)
+#endif
+#endif
 
-/* this is stored at the front of every database */
-struct tdb_header {
-       char magic_food[32]; /* for /etc/magic */
-       u32 version; /* version of the code */
-       u32 hash_size; /* number of hash entries */
-       tdb_off rwlocks;
-       tdb_off reserved[31];
-};
+/* this is the context structure that is returned from a db open */
+typedef struct tdb_context TDB_CONTEXT;
 
-struct tdb_lock_type {
-       u32 count;
-       u32 ltype;
-};
+typedef int (*tdb_traverse_func)(struct tdb_context *, TDB_DATA, TDB_DATA, void *);
+typedef void (*tdb_log_func)(struct tdb_context *, enum tdb_debug_level, const char *, ...) PRINTF_ATTRIBUTE(3, 4);
+typedef unsigned int (*tdb_hash_func)(TDB_DATA *key);
 
-struct tdb_traverse_lock {
-       struct tdb_traverse_lock *next;
-       u32 off;
-       u32 hash;
+struct tdb_logging_context {
+        tdb_log_func log_fn;
+        void *log_private;
 };
 
-/* this is the context structure that is returned from a db open */
-typedef struct tdb_context {
-       char *name; /* the name of the database */
-       void *map_ptr; /* where it is currently mapped */
-       int fd; /* open file descriptor for the database */
-       tdb_len map_size; /* how much space has been mapped */
-       int read_only; /* opened read-only */
-       struct tdb_lock_type *locked; /* array of chain locks */
-       enum TDB_ERROR ecode; /* error code for last tdb error */
-       struct tdb_header header; /* a cached copy of the header */
-       u32 flags; /* the flags passed to tdb_open */
-       u32 *lockedkeys; /* array of locked keys: first is #keys */
-       struct tdb_traverse_lock travlocks; /* current traversal locks */
-       struct tdb_context *next; /* all tdbs to avoid multiple opens */
-       dev_t device;   /* uniquely identifies this tdb */
-       ino_t inode;    /* uniquely identifies this tdb */
-       void (*log_fn)(struct tdb_context *tdb, int level, const char *, ...); /* logging function */
-       int open_flags; /* flags used in the open - needed by reopen */
-} TDB_CONTEXT;
-
-typedef int (*tdb_traverse_func)(TDB_CONTEXT *, TDB_DATA, TDB_DATA, void *);
-typedef void (*tdb_log_func)(TDB_CONTEXT *, int , const char *, ...);
-
-TDB_CONTEXT *tdb_open(const char *name, int hash_size, int tdb_flags,
+struct tdb_context *tdb_open(const char *name, int hash_size, int tdb_flags,
                      int open_flags, mode_t mode);
-TDB_CONTEXT *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
+struct tdb_context *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
                         int open_flags, mode_t mode,
-                        tdb_log_func log_fn);
-
-int tdb_reopen(TDB_CONTEXT *tdb);
-int tdb_reopen_all(void);
-void tdb_logging_function(TDB_CONTEXT *tdb, tdb_log_func);
-enum TDB_ERROR tdb_error(TDB_CONTEXT *tdb);
-const char *tdb_errorstr(TDB_CONTEXT *tdb);
-TDB_DATA tdb_fetch(TDB_CONTEXT *tdb, TDB_DATA key);
-int tdb_delete(TDB_CONTEXT *tdb, TDB_DATA key);
-int tdb_store(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf, int flag);
-int tdb_append(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA new_dbuf);
-int tdb_close(TDB_CONTEXT *tdb);
-TDB_DATA tdb_firstkey(TDB_CONTEXT *tdb);
-TDB_DATA tdb_nextkey(TDB_CONTEXT *tdb, TDB_DATA key);
-int tdb_traverse(TDB_CONTEXT *tdb, tdb_traverse_func fn, void *state);
-int tdb_exists(TDB_CONTEXT *tdb, TDB_DATA key);
-int tdb_lockkeys(TDB_CONTEXT *tdb, u32 number, TDB_DATA keys[]);
-void tdb_unlockkeys(TDB_CONTEXT *tdb);
-int tdb_lockall(TDB_CONTEXT *tdb);
-void tdb_unlockall(TDB_CONTEXT *tdb);
+                        const struct tdb_logging_context *log_ctx,
+                        tdb_hash_func hash_fn);
+void tdb_set_max_dead(struct tdb_context *tdb, int max_dead);
+
+int tdb_reopen(struct tdb_context *tdb);
+int tdb_reopen_all(int parent_longlived);
+void tdb_set_logging_function(struct tdb_context *tdb, const struct tdb_logging_context *log_ctx);
+enum TDB_ERROR tdb_error(struct tdb_context *tdb);
+const char *tdb_errorstr(struct tdb_context *tdb);
+TDB_DATA tdb_fetch(struct tdb_context *tdb, TDB_DATA key);
+int tdb_parse_record(struct tdb_context *tdb, TDB_DATA key,
+                    int (*parser)(TDB_DATA key, TDB_DATA data,
+                                  void *private_data),
+                    void *private_data);
+int tdb_delete(struct tdb_context *tdb, TDB_DATA key);
+int tdb_store(struct tdb_context *tdb, TDB_DATA key, TDB_DATA dbuf, int flag);
+int tdb_append(struct tdb_context *tdb, TDB_DATA key, TDB_DATA new_dbuf);
+int tdb_close(struct tdb_context *tdb);
+TDB_DATA tdb_firstkey(struct tdb_context *tdb);
+TDB_DATA tdb_nextkey(struct tdb_context *tdb, TDB_DATA key);
+int tdb_traverse(struct tdb_context *tdb, tdb_traverse_func fn, void *);
+int tdb_traverse_read(struct tdb_context *tdb, tdb_traverse_func fn, void *);
+int tdb_exists(struct tdb_context *tdb, TDB_DATA key);
+int tdb_lockall(struct tdb_context *tdb);
+int tdb_lockall_nonblock(struct tdb_context *tdb);
+int tdb_unlockall(struct tdb_context *tdb);
+int tdb_lockall_read(struct tdb_context *tdb);
+int tdb_lockall_read_nonblock(struct tdb_context *tdb);
+int tdb_unlockall_read(struct tdb_context *tdb);
+int tdb_lockall_mark(struct tdb_context *tdb);
+int tdb_lockall_unmark(struct tdb_context *tdb);
+const char *tdb_name(struct tdb_context *tdb);
+int tdb_fd(struct tdb_context *tdb);
+tdb_log_func tdb_log_fn(struct tdb_context *tdb);
+void *tdb_get_logging_private(struct tdb_context *tdb);
+int tdb_transaction_start(struct tdb_context *tdb);
+int tdb_transaction_prepare_commit(struct tdb_context *tdb);
+int tdb_transaction_commit(struct tdb_context *tdb);
+int tdb_transaction_cancel(struct tdb_context *tdb);
+int tdb_transaction_recover(struct tdb_context *tdb);
+int tdb_get_seqnum(struct tdb_context *tdb);
+int tdb_hash_size(struct tdb_context *tdb);
+size_t tdb_map_size(struct tdb_context *tdb);
+int tdb_get_flags(struct tdb_context *tdb);
+void tdb_add_flags(struct tdb_context *tdb, unsigned flag);
+void tdb_remove_flags(struct tdb_context *tdb, unsigned flag);
+void tdb_enable_seqnum(struct tdb_context *tdb);
+void tdb_increment_seqnum_nonblock(struct tdb_context *tdb);
+int tdb_check(struct tdb_context *tdb,
+             int (*check) (TDB_DATA key, TDB_DATA data, void *private_data),
+             void *private_data);
 
 /* Low level locking functions: use with care */
-void tdb_set_lock_alarm(sig_atomic_t *palarm);
-int tdb_chainlock(TDB_CONTEXT *tdb, TDB_DATA key);
-int tdb_chainunlock(TDB_CONTEXT *tdb, TDB_DATA key);
+int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key);
+int tdb_chainlock_nonblock(struct tdb_context *tdb, TDB_DATA key);
+int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key);
+int tdb_chainlock_read(struct tdb_context *tdb, TDB_DATA key);
+int tdb_chainunlock_read(struct tdb_context *tdb, TDB_DATA key);
+int tdb_chainlock_mark(struct tdb_context *tdb, TDB_DATA key);
+int tdb_chainlock_unmark(struct tdb_context *tdb, TDB_DATA key);
+
+void tdb_setalarm_sigptr(struct tdb_context *tdb, volatile sig_atomic_t *sigptr);
+
+/* wipe and repack */
+int tdb_wipe_all(struct tdb_context *tdb);
+int tdb_repack(struct tdb_context *tdb);
 
 /* Debug functions. Not used in production. */
-void tdb_dump_all(TDB_CONTEXT *tdb);
-int tdb_printfreelist(TDB_CONTEXT *tdb);
+void tdb_dump_all(struct tdb_context *tdb);
+int tdb_printfreelist(struct tdb_context *tdb);
+int tdb_validate_freelist(struct tdb_context *tdb, int *pnum_entries);
+int tdb_freelist_size(struct tdb_context *tdb);
 
 extern TDB_DATA tdb_null;
 
index ba62783aa657aad332875986cbb6854897993c9f..dcb32e99d2e726b7feaaf67c0799e9454f35de59 100644 (file)
@@ -5,7 +5,6 @@
 #ifndef UAM_H
 #define UAM_H 1
 
-#include <sys/cdefs.h>
 #include <pwd.h>
 #include <stdarg.h>
 
@@ -40,7 +39,6 @@
 #define UAM_OPTION_RANDNUM      (1 << 4) /* request a random number */
 #define UAM_OPTION_HOSTNAME     (1 << 5) /* get host name */
 #define UAM_OPTION_COOKIE       (1 << 6) /* cookie handle */
-#define UAM_OPTION_PROTOCOL    (1 << 7) /* DSI or ASP */
 #define UAM_OPTION_CLIENTNAME   (1 << 8) /* get client IP address */
 #define UAM_OPTION_KRB5SERVICE  (1 << 9) /* service name for krb5 principal */
 #define UAM_OPTION_MACCHARSET   (1 << 10) /* mac charset handle */
@@ -53,7 +51,6 @@
  * get back the corresponding option. not all of these are implemented. */
 #define UAM_PASSWD_FILENAME     (1 << 0)
 #define UAM_PASSWD_MINLENGTH    (1 << 1)
-#define UAM_PASSWD_MAXFAIL      (1 << 2) /* not implemented yet. */
 #define UAM_PASSWD_EXPIRETIME   (1 << 3) /* not implemented yet. */
 
 /* max lenght of username  */
index 325b7ac2bf911275095a0939ce21109f33a953b1..9b05cd362131629b51cb98f45373e19d284eb036 100644 (file)
@@ -1,12 +1,11 @@
 #ifndef _ATALK_UNICODE_H
 #define _ATALK_UNICODE_H 1
 
-#include <sys/cdefs.h>
-#include <netatalk/endian.h>
 #include <errno.h>
+#include <stdint.h>
 #include <sys/param.h>
 
-#define ucs2_t u_int16_t
+#define ucs2_t uint16_t
 
 #ifndef MIN
 #define MIN(a,b)     ((a)<(b)?(a):(b))
@@ -80,7 +79,7 @@ struct charset_functions {
                    char **outbuf, size_t *outbytesleft);
     size_t (*push)(void *, char **inbuf, size_t *inbytesleft,
                    char **outbuf, size_t *outbytesleft);
-    u_int32_t flags;
+    uint32_t flags;
     const char *iname;
     struct charset_functions *prev, *next;
 };
@@ -94,9 +93,9 @@ extern int atalk_register_charset (struct charset_functions *);
 
 /* from utf16_case.c */
 extern ucs2_t    toupper_w  (ucs2_t);
-extern u_int32_t toupper_sp (u_int32_t);
+extern uint32_t  toupper_sp (uint32_t);
 extern ucs2_t    tolower_w  (ucs2_t);
-extern u_int32_t tolower_sp (u_int32_t);
+extern uint32_t  tolower_sp (uint32_t);
 
 /* from util_unistr.c */
 extern int      strupper_w (ucs2_t *);
@@ -124,6 +123,7 @@ extern size_t   utf8_charlen ( char* );
 extern size_t   utf8_strlen_validate ( char *);
 
 /* from charcnv.c */
+extern int      set_charset_name(charset_t, const char *);
 extern void     init_iconv (void);
 extern size_t   convert_string (charset_t, charset_t, void const *, size_t, void *, size_t);
 extern size_t   convert_string_allocate (charset_t, charset_t, void const *, size_t, char **);
@@ -140,7 +140,7 @@ extern size_t   ucs2_to_charset_allocate (charset_t, char **dest, const ucs2_t *
 extern size_t   utf8_to_charset_allocate (charset_t, char **dest, const char *src);
 extern size_t   ucs2_to_charset (charset_t, const ucs2_t *src, char *dest, size_t);
 
-extern size_t   convert_charset (charset_t, charset_t, charset_t, const char *, size_t, char *, size_t, u_int16_t *);
+extern size_t   convert_charset (charset_t, charset_t, charset_t, const char *, size_t, char *, size_t, uint16_t *);
 
 extern size_t   charset_precompose ( charset_t, char *, size_t, char *, size_t);
 extern size_t   charset_decompose  ( charset_t, char *, size_t, char *, size_t);
index f6d191ca6000d21f1613cad1a3fd6afb47083786..24c1f7c5686e8d4063e655412d7e86f653b6e476 100644 (file)
@@ -1,5 +1,4 @@
 /*
-   $Id: unix.h,v 1.3 2010-03-12 15:16:49 franklahm Exp $
    Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
 
    This program is free software; you can redistribute it and/or modify
@@ -23,6 +22,9 @@
 #include <sys/types.h>
 #include <dirent.h>
 
+#define NETATALK_DIOSZ_STACK 65536
+#define NETATALK_DIOSZ_HEAP  (1024*1024)
+
 /* vfs/unix.c */
 extern int netatalk_unlink(const char *name);
 extern int netatalk_unlinkat(int dirfd, const char *name);
@@ -36,7 +38,13 @@ extern int netatalk_rmdir_all_errors(int dirfd, const char *name);
 
 extern int setfilmode(const char *, mode_t, struct stat *, mode_t);
 extern int dir_rx_set(mode_t mode);
-extern int stickydirmode(const char *name, const mode_t mode, const int dropbox, const mode_t v_umask);
 extern int unix_rename(int sfd, const char *oldpath, int dfd, const char *newpath);
 extern int copy_file(int sfd, const char *src, const char *dst, mode_t mode);
+extern int copy_file_fd(int sfd, int dfd);
+extern int copy_ea(const char *ea, int sfd, const char *src, const char *dst, mode_t mode);
+
+extern void become_root(void);
+extern void unbecome_root(void);
+extern int gmem(gid_t gid, int ngroups, gid_t *groups);
+
 #endif  /* ATALK_UNIX_H */
index 3a6dd24498bb85e7e66c84800f4edb633ca26aeb..c5b23ee6f9eaeca3687c0a884d6b5a0c5c614c63 100644 (file)
 #ifndef _ATALK_UTIL_H
 #define _ATALK_UTIL_H 1
 
-#include <sys/cdefs.h>
 #include <sys/types.h>
-#ifdef HAVE_UNISTD_H
+#include <sys/socket.h>
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <poll.h>
-#include <netatalk/at.h>
 
 #include <atalk/unicode.h>
 #include <atalk/bstrlib.h>
 #define AFP_ASSERT(b)
 #endif /* NDEBUG */
 
+#ifndef MIN
+#define MIN(a, b)  ((a) < (b) ? (a) : (b))
+#endif
+
+#ifndef MAX
+#define MAX(a, b)  ((a) > (b) ? (a) : (b))
+#endif
+
 #define STRCMP(a,b,c) (strcmp(a,c) b 0)
+#define ZERO_STRUCT(a) memset(&(a), 0, sizeof(a))
+#define ZERO_STRUCTP(a) memset((a), 0, sizeof(a))
 #ifndef MAX
 #define MAX(a,b) ((a) > (b) ? a : b)
 #endif
 #define MIN(a,b) ((a) < (b) ? a : b)
 #endif
 
-#if BYTE_ORDER == BIG_ENDIAN
+#ifdef WORDS_BIGENDIAN
 #define hton64(x)       (x)
 #define ntoh64(x)       (x)
-#else /* BYTE_ORDER == BIG_ENDIAN */
+#else
 #define hton64(x)       ((uint64_t) (htonl(((x) >> 32) & 0xffffffffLL)) | \
                          (uint64_t) ((htonl(x) & 0xffffffffLL) << 32))
 #define ntoh64(x)       (hton64(x))
-#endif /* BYTE_ORDER == BIG_ENDIAN */
+#endif
 
 #ifdef WITH_SENDFILE
 extern ssize_t sys_sendfile (int __out_fd, int __in_fd, off_t *__offset,size_t __count);
@@ -74,9 +81,6 @@ extern void freeifacelist(char **);
 
 #define diatolower(x)     _dialowermap[(unsigned char) (x)]
 #define diatoupper(x)     _diacasemap[(unsigned char) (x)]
-#ifndef NO_DDP
-extern int atalk_aton     (char *, struct at_addr *);
-#endif
 extern void bprint        (char *, int);
 extern int strdiacasecmp  (const char *, const char *);
 extern int strndiacasecmp (const char *, const char *, size_t);
@@ -87,19 +91,6 @@ extern void fault_setup        (void (*fn)(void *));
 extern void netatalk_panic(const char *why);
 #define server_unlock(x)  (unlink(x))
 
-/* strlcpy and strlcat are used by pam modules */
-#ifndef UAM_MODULE_EXPORT
-#define UAM_MODULE_EXPORT 
-#endif
-
-#ifndef HAVE_STRLCPY
-UAM_MODULE_EXPORT size_t strlcpy (char *, const char *, size_t);
-#endif
-#ifndef HAVE_STRLCAT
-UAM_MODULE_EXPORT size_t strlcat (char *, const char *, size_t);
-#endif
-
 #ifndef HAVE_DLFCN_H
 extern void *mod_open    (const char *);
 extern void *mod_symbol  (void *, const char *);
@@ -190,6 +181,7 @@ extern char *stripped_slashes_basename(char *p);
 extern int lchdir(const char *dir);
 extern void randombytes(void *buf, int n);
 extern int daemonize(int nochdir, int noclose);
+extern int run_cmd(const char *cmd, char **cmd_argv);
 
 /******************************************************************
  * cnid.c
index 024ac7a0535895a38f6841f2f9cfaeebf383eb00..4c9b3c95f8ff0225b503da0ae7bf3aeaa6d8e3ac 100644 (file)
@@ -17,7 +17,7 @@
 
 #define UUID_BINSIZE 16
 
-typedef unsigned char *uuidp_t;
+typedef const unsigned char *uuidp_t;
 typedef unsigned char atalk_uuid_t[UUID_BINSIZE];
 
 typedef enum {UUID_USER   = 1,
@@ -31,11 +31,11 @@ extern char *uuidtype[];
  * Interface
  ********************************************************/
 
-extern int getuuidfromname( const char *name, uuidtype_t type, uuidp_t uuid);
-extern int getnamefromuuid( const uuidp_t uuidp, char **name, uuidtype_t *type);
-
+extern int getuuidfromname( const char *name, uuidtype_t type, unsigned char *uuid);
+extern int getnamefromuuid( const unsigned char *uuid, char **name, uuidtype_t *type);
 extern void localuuid_from_id(unsigned char *buf, uuidtype_t type, unsigned int id);
-extern const char *uuid_bin2string(unsigned char *uuid);
-extern void uuid_string2bin( const char *uuidstring, uuidp_t uuid);
+extern const char *uuid_bin2string(const unsigned char *uuid);
+extern void uuid_string2bin( const char *uuidstring, unsigned char *uuid);
 extern void uuidcache_dump(void);
+
 #endif /* AFP_UUID_H */
diff --git a/include/atalk/volinfo.h b/include/atalk/volinfo.h
deleted file mode 100644 (file)
index 0f3a402..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-#ifndef _ATALK_VOLINFO_H
-#define _ATALK_VOLINFO_H 1
-
-#include <atalk/unicode.h>
-#include <atalk/volume.h>
-
-/* volinfo for shell utilities */
-#define VOLINFODIR  ".AppleDesktop"
-#define VOLINFOFILE ".volinfo"
-
-typedef struct {
-    const u_int32_t option;
-    const char      *name;
-} vol_opt_name_t;
-
-struct volinfo {
-    int                 retaincount;
-    int                 malloced;
-
-    char                *v_name;
-    char                *v_path;
-    int                 v_flags;
-    int                 v_casefold;
-    char                *v_cnidscheme;
-    char                *v_dbpath;
-    char                *v_volcodepage;
-    charset_t           v_volcharset;
-    char                *v_maccodepage;
-    charset_t           v_maccharset;
-    int                 v_adouble;  /* default adouble format */
-    int                 v_ad_options;
-    int                 v_vfs_ea;
-    char                *(*ad_path)(const char *, int);
-    char                *v_dbd_host;
-    char                *v_dbd_port;
-};
-
-struct volinfo *allocvolinfo(char *path);
-extern int loadvolinfo(char *path, struct volinfo *vol);
-extern void retainvolinfo(struct volinfo *vol);
-extern int closevolinfo(struct volinfo *vol);
-extern int savevolinfo(const struct vol *vol, const char *Cnid_srv, const char *Cnid_port);
-extern int vol_load_charsets(struct volinfo *vol);
-
-#endif
index af2b411c625ca6b07f8203798d5ccbcd12d36c10..7a27c644daa864297d939dc6fa50f96549e69cc7 100644 (file)
@@ -7,14 +7,13 @@
 #define ATALK_VOLUME_H 1
 
 #include <stdint.h>
-#include <sys/cdefs.h>
 #include <sys/types.h>
-// #include <netatalk/endian.h>
 
 #include <atalk/unicode.h>
 #include <atalk/cnid.h>
 #include <atalk/hash.h>
 #include <atalk/vfs.h>
+#include <atalk/globals.h>
 
 #define AFPVOL_U8MNAMELEN   255 /* AFP3 sepc */
 #define AFPVOL_MACNAMELEN    27 /* AFP2 spec */
@@ -23,7 +22,8 @@ typedef uint64_t VolSpace;
 
 struct vol {
     struct vol      *v_next;
-    u_int16_t       v_vid;
+    AFPObj          *v_obj;
+    uint16_t        v_vid;
     int             v_flags;
     char            *v_path;
     struct dir      *v_root;
@@ -31,20 +31,19 @@ struct vol {
 
     charset_t       v_volcharset;
     charset_t       v_maccharset;
-    u_int16_t       v_mtou_flags;    /* flags for convert_charset in mtoupath */
-    u_int16_t       v_utom_flags;
+    uint16_t        v_mtou_flags;    /* flags for convert_charset in mtoupath */
+    uint16_t        v_utom_flags;
     long            v_kTextEncoding; /* mac charset encoding in network order
                                       * FIXME: should be a u_int32_t ? */
     size_t          max_filename;
     char            *v_veto;
     int             v_adouble;    /* adouble format: v1, v2, sfm ... */
     int             v_ad_options; /* adouble option NODEV, NOCACHE, etc.. */
-    char            *(*ad_path)(const char *, int);
+    const char      *(*ad_path)(const char *, int);
     struct _cnid_db *v_cdb;
     char            v_stamp[ADEDLEN_PRIVSYN];
     VolSpace        v_limitsize; /* Size limit, if any, in MiB */
     mode_t          v_umask;
-    mode_t          v_perm;  /* default permission value OR with requested perm*/
     mode_t          v_dperm; /* default directories permission value OR with requested perm*/
     mode_t          v_fperm; /* default files permission value OR with requested perm*/
     ucs2_t          *v_u8mname;     /* converted to utf8-mac in ucs2 */
@@ -70,7 +69,8 @@ struct vol {
     
     /* only when opening/closing volumes or in error */
     int             v_casefold;
-    char            *v_localname;   /* as defined in AppleVolumes.default */
+    char            *v_configname;   /* as defined in afpc.conf */
+    char            *v_localname;    /* as defined in afp.conf but with vars expanded */
     char            *v_volcodepage;
     char            *v_maccodepage;
     char            *v_password;
@@ -78,8 +78,10 @@ struct vol {
     char            *v_dbpath;
     char            *v_cnidserver;
     char            *v_cnidport;
+#if 0
     int             v_hide;       /* new volume wait until old volume is closed */
     int             v_new;        /* volume deleted but there's a new one with the same name */
+#endif
     int             v_deleted;    /* volume open but deleted in new config file */
     char            *v_root_preexec;
     char            *v_preexec;
@@ -88,40 +90,29 @@ struct vol {
     int             v_root_preexec_close;
     int             v_preexec_close;
     char            *v_uuid;    /* For TimeMachine zeroconf record */
-#ifdef FORCE_UIDGID
-    char            *v_forceuid;
-    char            *v_forcegid;
-#endif
 #ifdef __svr4__
     int         v_qfd;
 #endif /*__svr4__*/
 };
 
-#define AFPVOL_OPEN (1<<0)
+/* load_volumes() flags */
+#define LV_ALL (1 << 0)
 
+/* volume flags */
+#define AFPVOL_OPEN (1<<0)
 /* flags  for AFS and quota 0xxx0 */
 #define AFPVOL_GVSMASK  (7<<2)
-#define AFPVOL_NONE (0<<2)
+#define AFPVOL_NONE     (0<<2)
 #define AFPVOL_AFSGVS   (1<<2)
-#define AFPVOL_USTATFS  (2<<2)
-#define AFPVOL_UQUOTA   (4<<2)
+#define AFPVOL_USTATFS  (1<<3)
+#define AFPVOL_UQUOTA   (1<<4)
 
 /*
   Flags that alter volume behaviour.
   Keep in sync with libatalk/util/volinfo.c
 */
-#define AFPVOL_A2VOL     (1 << 5)   /* prodos volume */
-#define AFPVOL_CRLF      (1 << 6)   /* cr/lf translation */
-#define AFPVOL_NOADOUBLE (1 << 7)   /* don't create .AppleDouble by default */
+#define AFPVOL_NOV2TOEACONV (1 << 5) /* no adouble:v2 to adouble:ea conversion */
 #define AFPVOL_RO        (1 << 8)   /* read-only volume */
-#define AFPVOL_MSWINDOWS (1 << 9)   /* deal with ms-windows yuckiness.
-                                       this is going away. */
-#define AFPVOL_NOHEX     (1 << 10)  /* don't do :hex translation */
-#define AFPVOL_USEDOTS   (1 << 11)  /* use real dots */
-#define AFPVOL_LIMITSIZE (1 << 12)  /* limit size for older macs */
-#define AFPVOL_MAPASCII  (1 << 13)  /* map the ascii range as well */
-#define AFPVOL_DROPBOX   (1 << 14)  /* dropkludge dropbox support */
-#define AFPVOL_NOFILEID  (1 << 15)  /* don't advertise createid resolveid and deleteid calls */
 #define AFPVOL_NOSTAT    (1 << 16)  /* advertise the volume even if we can't stat() it
                                      * maybe because it will be mounted later in preexec */
 #define AFPVOL_UNIX_PRIV (1 << 17)  /* support unix privileges */
@@ -129,11 +120,8 @@ struct vol {
                                      * help if device number is notconsistent across reboot
                                      * NOTE symlink to a different device will return an ACCESS error
                                      */
-#define AFPVOL_CASEINSEN (1 << 19)  /* volume is case insensitive */
 #define AFPVOL_EILSEQ    (1 << 20)  /* encode illegal sequence 'asis' UCS2, ex "\217-", which is not
                                        a valid SHIFT-JIS char, is encoded  as U\217 -*/
-
-#define AFPVOL_CACHE     (1 << 21)   /* Use adouble v2 CNID caching. Default: yes */
 #define AFPVOL_INV_DOTS  (1 << 22)   /* dots files are invisible */
 #define AFPVOL_TM        (1 << 23)   /* Supports TimeMachine */
 #define AFPVOL_ACLS      (1 << 24)   /* Volume supports ACLS */
@@ -160,10 +148,6 @@ struct vol {
 #define AFPVOL_UUPPERMLOWER    (AFPVOL_MTOUUPPER | AFPVOL_UTOMLOWER)
 #define AFPVOL_ULOWERMUPPER    (AFPVOL_MTOULOWER | AFPVOL_UTOMUPPER)
 
-#define MSWINDOWS_BADCHARS ":\t\\/<>*?|\""
-
-int wincheck(const struct vol *vol, const char *path);
-
 #define AFPVOLSIG_FLAT          0x0001 /* flat fs */
 #define AFPVOLSIG_FIX           0x0002 /* fixed ids */
 #define AFPVOLSIG_VAR           0x0003 /* variable ids */
@@ -196,11 +180,10 @@ int wincheck(const struct vol *vol, const char *path);
 #define VOLPBIT_XBTOTAL 10
 #define VOLPBIT_BSIZE   11        /* block size */
 
-#define utf8_encoding() (afp_version >= 30)
+#define utf8_encoding(obj) ((obj)->afp_version >= 30)
 
-#define vol_noadouble(vol) (((vol)->v_flags & AFPVOL_NOADOUBLE) ? 1 : 0)
 #define vol_nodev(vol) (((vol)->v_flags & AFPVOL_NODEV) ? 1 : 0)
-#define vol_unix_priv(vol) (afp_version >= 30 && ((vol)->v_flags & AFPVOL_UNIX_PRIV))
+#define vol_unix_priv(vol) ((vol)->v_obj->afp_version >= 30 && ((vol)->v_flags & AFPVOL_UNIX_PRIV))
 #define vol_inv_dots(vol) (((vol)->v_flags & AFPVOL_INV_DOTS) ? 1 : 0)
 
 
diff --git a/include/atalk/zip.h b/include/atalk/zip.h
deleted file mode 100644 (file)
index 42a7d64..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-
-#ifndef _ATALK_ZIP_H
-#define _ATALK_ZIP_H 1
-
-#ifndef NO_DDP
-
-#include <netatalk/endian.h>
-
-struct ziphdr {
-    u_int8_t    zh_op;
-    u_int8_t    zh_cnt;
-#define zh_count       zh_cnt
-#define zh_zero                zh_cnt
-#define zh_flags       zh_cnt
-};
-
-struct zipreplent {
-    u_int16_t   zre_net;
-    u_int8_t    zre_zonelen;
-};
-
-#define ZIPOP_QUERY    1
-#define ZIPOP_REPLY    2
-#define ZIPOP_TAKEDOWN 3       /* XXX */
-#define ZIPOP_BRINGUP  4       /* XXX */
-#define ZIPOP_GNI      5
-#define ZIPOP_GNIREPLY 6
-#define ZIPOP_NOTIFY   7
-#define ZIPOP_EREPLY   8
-#define ZIPOP_GETMYZONE        7
-#define ZIPOP_GETZONELIST 8
-#define ZIPOP_GETLOCALZONES 9
-
-#define ZIPGNI_INVALID 0x80
-#define ZIPGNI_ONEZONE 0x20
-
-#endif  /* NO_DDP */
-#endif
index a9c43764e33bcf320f9e60c52f684ba80640536f..33a5b662a8d4d689fd366a470abd24c71c971487 100644 (file)
@@ -4,5 +4,5 @@ Makefile.in
 *.la
 .deps
 .libs
-.gitignore
 dummy.o
+libatalk.abi.tmp
index a241d94cd7c43e88c8ce78511d266e523c3621da..03c7cf57990c100fcaabf6b970b04c6954ee21b5 100644 (file)
@@ -1,46 +1,88 @@
-
 # Makefile.am for libatalk/
 
-SUBDIRS = acl adouble bstring compat cnid dsi tdb util unicode vfs
+# This is the version info for the libatalk binary API.  It has three
+# numbers:
+#
+#   Current  -- the number of the binary API that we're implementing
+#   Revision -- which iteration of the implementation of the binary
+#               API are we supplying?
+#   Age      -- How many previous binary API versions do we also
+#               support?
+#
+# To increment a VERSION_INFO (current:revision:age):
+#    If the ABI didn't change, but any library code changed:
+#        current:revision+1:age
+#    If the ABI changed, but it's backward-compatible:
+#        current+1:0:age+1
+#    If the ABI changed and it isn't backward-compatible:
+#        current+1:0:0
+#
+
+VERSION_INFO = 1:0:0
+
+# History:          VERSION_INFO
+#
+#   3.0.0-alpha1    0:0:0
+#   3.0.0-alpha2    0:0:0
+#   3.0.0-alpha3    0:0:0
+#   3.0.0-beta1     0:0:0
+#   3.0.0-beta2     1:0:0
+
+SUBDIRS = acl adouble bstring compat cnid dsi iniparser tdb util unicode vfs
 
 lib_LTLIBRARIES = libatalk.la
 
 libatalk_la_SOURCES = dummy.c
 
 libatalk_la_LIBADD  = \
+       @WRAP_LIBS@ @ACL_LIBS@ \
        acl/libacl.la \
        adouble/libadouble.la   \
        bstring/libbstring.la \
+       cnid/libcnid.la \
        compat/libcompat.la     \
        dsi/libdsi.la           \
-       util/libutil.la         \
+       iniparser/libiniparser.la \
        tdb/libtdb.la       \
        unicode/libunicode.la \
+       util/libutil.la         \
        vfs/libvfs.la
 
 libatalk_la_DEPENDENCIES = \
        acl/libacl.la \
        adouble/libadouble.la   \
        bstring/libbstring.la \
+       cnid/libcnid.la \
        compat/libcompat.la     \
        dsi/libdsi.la           \
-       util/libutil.la         \
+       iniparser/libiniparser.la \
        tdb/libtdb.la       \
        unicode/libunicode.la \
+       util/libutil.la         \
        vfs/libvfs.la
 
-libatalk_la_LDFLAGS = -static
-
-if USE_APPLETALK
-SUBDIRS +=  asp atp nbp netddp
-libatalk_la_LIBADD += \
-       asp/libasp.la           \
-       atp/libatp.la           \
-       nbp/libnbp.la           \
-       netddp/libnetddp.la
-libatalk_la_DEPENDENCIES += \
-       asp/libasp.la           \
-       atp/libatp.la           \
-       nbp/libnbp.la           \
-       netddp/libnetddp.la
+libatalk_la_LDFLAGS = -version-info $(VERSION_INFO)
+
+if DEVELOPER
+all-local: .libs/libatalk.so
+       @$(top_srcdir)/abigen.sh .libs/libatalk.so > libatalk.abi.tmp
+       @if [ ! -f libatalk-$(NETATALK_VERSION).abi ] ; then \
+               cp libatalk.abi.tmp libatalk-$(NETATALK_VERSION).abi ; \
+               echo "**********************************************************************************************************" ; \
+               echo "                                created ABI file libatalk-$(NETATALK_VERSION).abi" ; \
+               echo "    check https://sourceforge.net/apps/mediawiki/netatalk/index.php?title=Developer_Infos#ABI_checking" ; \
+               echo "**********************************************************************************************************" ; \
+               exit 1 ; \
+       fi
+       @diff -u libatalk-$(NETATALK_VERSION).abi libatalk.abi.tmp || ( \
+               echo '**********************************************************************************************************' && \
+               echo '***                                     libatalk ABI changed                                           ***' && \
+               echo '*** check https://sourceforge.net/apps/mediawiki/netatalk/index.php?title=Developer_Infos#ABI_checking ***' && \
+               echo '**********************************************************************************************************' && \
+               exit 1 )
+
 endif
+
+EXTRA_DIST = \
+       libatalk-3.0beta1.abi \
+       libatalk-3.0beta2.abi
index e7f9753aca68a1400cd41dd409dc5744e8478463..0e75ee9ee420ff98c151043d533ab13c2f1150be 100644 (file)
@@ -4,10 +4,14 @@ noinst_HEADERS = aclldap.h cache.h
 
 noinst_LTLIBRARIES = libacl.la
 libacl_la_SOURCES = cache.c unix.c uuid.c
+libacl_la_CFLAGS =
 libacl_la_LDFLAGS =
+libacl_la_LIBADD  =
 
 if HAVE_LDAP
 libacl_la_SOURCES += ldap.c ldap_config.c
-libacl_la_LDFLAGS += -lldap
+libacl_la_CFLAGS  += @LDAP_CFLAGS@
+libacl_la_LIBADD  += @LDAP_LIBS@
+libacl_la_LDFLAGS += @LDAP_LDFLAGS@
 endif
 
index 9fe8405ff72a3e9b9e749cbbeb8b97ce5e559d8f..bc9806d9d323f1e58af3c44e0c94c79b62ad1037 100644 (file)
 typedef struct cacheduser {
     unsigned long uid;      /* for future use */
     uuidtype_t type;
-    uuidp_t uuid;
+    unsigned char *uuid;
     char *name;
     time_t creationtime;
     struct cacheduser *prev;
     struct cacheduser *next;
 } cacheduser_t;
 
-cacheduser_t *namecache[256];   /* indexed by hash of name */
-cacheduser_t *uuidcache[256];   /* indexed by hash of uuid */
+static cacheduser_t *namecache[256];   /* indexed by hash of name */
+static cacheduser_t *uuidcache[256];   /* indexed by hash of uuid */
 
 /********************************************************
  * helper function
@@ -127,7 +127,7 @@ static unsigned char hashuuid(uuidp_t uuid) {
 int add_cachebyname( const char *inname, const uuidp_t inuuid, const uuidtype_t type, const unsigned long uid _U_) {
     int ret = 0;
     char *name = NULL;
-    uuidp_t uuid = NULL;
+    unsigned char *uuid = NULL;
     cacheduser_t *cacheduser = NULL;
     unsigned char hash;
 
@@ -200,7 +200,7 @@ cleanup:
  * @returns       0 on sucess, entry found
  *                -1 no entry found
  */
-int search_cachebyname(const char *name, uuidtype_t *type, uuidp_t uuid) {
+int search_cachebyname( const char *name, uuidtype_t *type, unsigned char *uuid) {
     int ret;
     unsigned char hash;
     cacheduser_t *entry;
@@ -299,7 +299,7 @@ int search_cachebyuuid( uuidp_t uuidp, char **name, uuidtype_t *type) {
 int add_cachebyuuid( uuidp_t inuuid, const char *inname, uuidtype_t type, const unsigned long uid _U_) {
     int ret = 0;
     char *name = NULL;
-    uuidp_t uuid = NULL;
+    unsigned char *uuid = NULL;
     cacheduser_t *cacheduser = NULL;
     cacheduser_t *entry;
     unsigned char hash;
index 252d7da2681742cda7772c43eb793f76204853ab..11731a26c69d5bdeb683be1667a8c2c6bd351e03 100644 (file)
@@ -32,7 +32,7 @@
  * Interface
  ********************************************************/
 
-extern int search_cachebyname( const char *name, uuidtype_t *type, uuidp_t uuid);
+extern int search_cachebyname( const char *name, uuidtype_t *type, unsigned char *uuid);
 extern int add_cachebyname( const char *inname, const uuidp_t inuuid, const uuidtype_t type, const unsigned long uid);
 extern int search_cachebyuuid( uuidp_t uuidp, char **name, uuidtype_t *type);
 extern int add_cachebyuuid( uuidp_t inuuid, const char *inname, uuidtype_t type, const unsigned long uid);
index 122abb5ba1b433ec17a5770bde0864d94419f581..062bab72acbb5d487bc9cfec403b4dd21f9808cd 100644 (file)
@@ -55,32 +55,32 @@ char *ldap_group_attr;
 char *ldap_uid_attr;
 
 struct ldap_pref ldap_prefs[] = {
-    {&ldap_server,     "ldap_server",      0, 0, -1},
-    {&ldap_auth_method,"ldap_auth_method", 1, 1, -1},
-    {&ldap_auth_dn,    "ldap_auth_dn",     0, 0,  0},
-    {&ldap_auth_pw,    "ldap_auth_pw",     0, 0,  0},
-    {&ldap_userbase,   "ldap_userbase",    0, 0, -1},
-    {&ldap_userscope,  "ldap_userscope",   1 ,1, -1},
-    {&ldap_groupbase,  "ldap_groupbase",   0, 0, -1},
-    {&ldap_groupscope, "ldap_groupscope",  1 ,1, -1},
-    {&ldap_uuid_attr,  "ldap_uuid_attr",   0, 0, -1},
-    {&ldap_uuid_string,"ldap_uuid_string", 0, 0,  0},
-    {&ldap_name_attr,  "ldap_name_attr",   0, 0, -1},
-    {&ldap_group_attr, "ldap_group_attr",  0, 0, -1},
-    {&ldap_uid_attr,   "ldap_uid_attr",    0, 0,  0},
+    {&ldap_server,     "ldap server",      0, 0, -1},
+    {&ldap_auth_method,"ldap auth method", 1, 1, -1},
+    {&ldap_auth_dn,    "ldap auth dn",     0, 0,  0},
+    {&ldap_auth_pw,    "ldap auth pw",     0, 0,  0},
+    {&ldap_userbase,   "ldap userbase",    0, 0, -1},
+    {&ldap_userscope,  "ldap userscope",   1 ,1, -1},
+    {&ldap_groupbase,  "ldap groupbase",   0, 0, -1},
+    {&ldap_groupscope, "ldap groupscope",  1 ,1, -1},
+    {&ldap_uuid_attr,  "ldap uuid attr",   0, 0, -1},
+    {&ldap_uuid_string,"ldap uuid string", 0, 0,  0},
+    {&ldap_name_attr,  "ldap name attr",   0, 0, -1},
+    {&ldap_group_attr, "ldap group attr",  0, 0, -1},
+    {&ldap_uid_attr,   "ldap uid attr",    0, 0,  0},
     {NULL,             NULL,               0, 0, -1}
 };
 
 struct pref_array prefs_array[] = {
-    {"ldap_auth_method", "none",   LDAP_AUTH_NONE},
-    {"ldap_auth_method", "simple", LDAP_AUTH_SIMPLE},
-    {"ldap_auth_method", "sasl",   LDAP_AUTH_SASL},
-    {"ldap_userscope",   "base",   LDAP_SCOPE_BASE},
-    {"ldap_userscope",   "one",    LDAP_SCOPE_ONELEVEL},
-    {"ldap_userscope",   "sub",    LDAP_SCOPE_SUBTREE},
-    {"ldap_groupscope",  "base",   LDAP_SCOPE_BASE},
-    {"ldap_groupscope",  "one",    LDAP_SCOPE_ONELEVEL},
-    {"ldap_groupscope",  "sub",    LDAP_SCOPE_SUBTREE},
+    {"ldap auth method", "none",   LDAP_AUTH_NONE},
+    {"ldap auth method", "simple", LDAP_AUTH_SIMPLE},
+    {"ldap auth method", "sasl",   LDAP_AUTH_SASL},
+    {"ldap userscope",   "base",   LDAP_SCOPE_BASE},
+    {"ldap userscope",   "one",    LDAP_SCOPE_ONELEVEL},
+    {"ldap userscope",   "sub",    LDAP_SCOPE_SUBTREE},
+    {"ldap groupscope",  "base",   LDAP_SCOPE_BASE},
+    {"ldap groupscope",  "one",    LDAP_SCOPE_ONELEVEL},
+    {"ldap groupscope",  "sub",    LDAP_SCOPE_SUBTREE},
     {NULL,               NULL,     0}
 };
 
index e0440a6b770514d72543fb0edfffcc1192c02bb2..bd9d414b85758ce8439863100e9752f33b0785af 100644 (file)
 #include <ctype.h>
 #include <ldap.h>
 
+#include <atalk/globals.h>
 #include <atalk/ldapconfig.h>
 #include <atalk/logger.h>
+#include <atalk/iniparser.h>
 
-#define LINESIZE 1024
-
-/* Parse one line. Return result in pref and val */
-static int getpref(char *buf, char **R_pref, char **R_val)
-{
-    char *p, *pref, *val;
-
-    /* a little pre-processing to get rid of spaces and end-of-lines */
-    p = buf;
-    while (p && isspace(*p))
-        p++;
-    if (!p || (*p == '\0'))
-        return -1;
-
-    if ((val = strchr(p, '=')) == NULL)
-        return -1;
-    while ((*val == '=') || (*val == ' '))
-        val++;
-    if ((val = strtok(val, " \n")) == NULL)
-        return -1;
-    if ((pref = strtok(p, " =")) == NULL)
-        return -1;
-    if ((val = strdup(val)) == NULL)
-        return -1;
-
-    *R_pref = pref;
-    *R_val = val;
-    return 0;
-}
-
-/* Parse the afp_ldap.conf file */
-int acl_ldap_readconfig(char *name)
+int acl_ldap_readconfig(dictionary *iniconfig)
 {
     int i, j;
-    FILE *f;
-    char buf[LINESIZE];
-    char *pref, *val;
+    const char *val;
 
-    f = fopen(name,"r");
-    if (!f) {
-        perror("fopen");
-        return -1;
+    i = 0;
+    /* now see if its a correct pref */
+    for (i = 0; ldap_prefs[i].name != NULL; i++) {
+        if ((val = iniparser_getstring(iniconfig, INISEC_GLOBAL, ldap_prefs[i].name, NULL))) {
+            /* check if we have pre-defined values */
+            if (ldap_prefs[i].intfromarray == 0) {
+                /* no, its just a string */
+                ldap_prefs[i].valid = 0;
+                if (ldap_prefs[i].strorint)
+                    /* store as int */
+                    *((int *)(ldap_prefs[i].pref)) = atoi(val);
+                else
+                    /* store string as string */
+                    *((const char **)(ldap_prefs[i].pref)) = strdup(val);
+            } else {
+                /* ok, we have string to int mapping for this pref
+                   eg. "none", "simple", "sasl" map to 0, 128, 129 */
+                for (j = 0; prefs_array[j].pref != NULL; j++) {
+                    if ((strcmp(prefs_array[j].pref, ldap_prefs[i].name) == 0)
+                        && (strcmp(prefs_array[j].valuestring, val) == 0)) {
+                        ldap_prefs[i].valid = 0;
+                        *((int *)(ldap_prefs[i].pref)) = prefs_array[j].value;
+                        break;
+                    }
+                }
+            }
+        }
     }
 
-    while (!feof(f)) {
-        /* read a line from file */
-        if (!fgets(buf, LINESIZE, f) || buf[0] == '#')
-            continue;
-
-        /* parse and return pref and value */
-        if ((getpref(buf, &pref, &val)) != 0)
-            continue;
-
-        i = 0;
-        /* now see if its a correct pref */
-        while(ldap_prefs[i].pref != NULL) {
-            if ((strcmp(ldap_prefs[i].name, pref)) == 0) {
-                /* ok, found a valid pref */
-
-                /* check if we have pre-defined values */
-                if (0 == ldap_prefs[i].intfromarray) {
-                    /* no, its just a string */
-                    ldap_prefs[i].valid = 0;
-                    if (0 == ldap_prefs[i].strorint)
-                        /* store string as string */
-                        *((char **)(ldap_prefs[i].pref)) = val;
-                    else
-                        /* store as int */
-                        *((int *)(ldap_prefs[i].pref)) = atoi(val);
-                } else {
-                    /* ok, we have string to int mapping for this pref
-                       eg. "none", "simple", "sasl" map to 0, 128, 129 */
-                    j = 0;
-                    while(prefs_array[j].pref != NULL) {
-                        if (((strcmp(prefs_array[j].pref, pref)) == 0) &&
-                            ((strcmp(prefs_array[j].valuestring, val)) == 0)) {
-                            ldap_prefs[i].valid = 0;
-                            *((int *)(ldap_prefs[i].pref)) = prefs_array[j].value;
-                        }
-                        j++;
-                    } /* while j*/
-                } /* if else 0 == ldap_prefs*/
-                break;
-            } /* if strcmp */
-            i++;
-        } /* while i */
-        if (ldap_prefs[i].pref == NULL)
-            LOG(log_error, logtype_afpd,"afp_ldap.conf: Unknown option: \"%s\"", pref);
-    }  /*  EOF */
-
     /* check if the config is sane and complete */
     i = 0;
     ldap_config_valid = 1;
 
     while(ldap_prefs[i].pref != NULL) {
         if ( ldap_prefs[i].valid != 0) {
-            LOG(log_debug, logtype_afpd,"afp_ldap.conf: Missing option: \"%s\"", ldap_prefs[i].name);
+            LOG(log_debug, logtype_afpd,"LDAP: Missing option: \"%s\"", ldap_prefs[i].name);
             ldap_config_valid = 0;
             break;
         }
@@ -133,16 +79,15 @@ int acl_ldap_readconfig(char *name)
 
     if (ldap_config_valid) {
         if (ldap_auth_method == LDAP_AUTH_NONE)
-            LOG(log_debug, logtype_afpd,"afp_ldap.conf: Using anonymous bind.");
+            LOG(log_debug, logtype_afpd,"LDAP: Using anonymous bind.");
         else if (ldap_auth_method == LDAP_AUTH_SIMPLE)
-            LOG(log_debug, logtype_afpd,"afp_ldap.conf: Using simple bind.");
+            LOG(log_debug, logtype_afpd,"LDAP: Using simple bind.");
         else {
             ldap_config_valid = 0;
-            LOG(log_error, logtype_afpd,"afp_ldap.conf: SASL not yet supported.");
+            LOG(log_error, logtype_afpd,"LDAP: SASL not yet supported.");
         }
     } else
-        LOG(log_info, logtype_afpd,"afp_ldap.conf: not used");
-    fclose(f);
+        LOG(log_info, logtype_afpd,"LDAP: not used");
     return 0;
 }
 #endif /* HAVE_LDAP */
index 9bad9c94ea277ec4d1a7be192ab539aa6c71977d..6284935173d87c7cced42ce80419977cc1df40f8 100644 (file)
@@ -33,6 +33,7 @@
 #include <atalk/afp.h>
 #include <atalk/util.h>
 #include <atalk/acl.h>
+#include <atalk/unix.h>
 
 #ifdef HAVE_SOLARIS_ACLS
 
@@ -47,7 +48,7 @@ int get_nfsv4_acl(const char *name, ace_t **retAces)
     *retAces = NULL;
     /* Only call acl() for regular files and directories, otherwise just return 0 */
     if (lstat(name, &st) != 0) {
-        LOG(log_warning, logtype_afpd, "get_nfsv4_acl(\"%s/%s\"): %s", getcwdpath(), name, strerror(errno));
+        LOG(log_debug, logtype_afpd, "get_nfsv4_acl(\"%s/%s\"): %s", getcwdpath(), name, strerror(errno));
         return -1;
     }
 
@@ -234,8 +235,16 @@ int nfsv4_chmod(char *name, mode_t mode)
     if (chmod(name, mode) != 0) /* (3) */
         goto exit;
 
-    if ((nnaces = get_nfsv4_acl(name, &nacl)) == -1) /* (4) */
-        goto exit;
+    if ((nnaces = get_nfsv4_acl(name, &nacl)) == -1) {/* (4) */
+        if (errno != EACCES)
+            goto exit;
+        become_root();
+        nnaces = get_nfsv4_acl(name, &nacl);
+        unbecome_root();
+        if (nnaces == -1)
+            goto exit;
+    }
+
     if ((nnaces = strip_nontrivial_aces(&nacl, nnaces)) == -1) /* (5) */
         goto exit;
 
@@ -243,8 +252,17 @@ int nfsv4_chmod(char *name, mode_t mode)
         goto exit;
 
     if ((ret = acl(name, ACE_SETACL, noaces + nnaces, cacl)) != 0) {
-        LOG(log_error, logtype_afpd, "nfsv4_chmod: error setting acl: %s", strerror(errno));
-        goto exit;
+        if (errno != EACCES) {
+            LOG(log_error, logtype_afpd, "nfsv4_chmod: error setting acl: %s", strerror(errno));
+            goto exit;
+        }
+        become_root();
+        ret = acl(name, ACE_SETACL, noaces + nnaces, cacl);
+        unbecome_root();
+        if (ret != 0) {
+            LOG(log_error, logtype_afpd, "nfsv4_chmod: error setting acl: %s", strerror(errno));
+            goto exit;
+        }
     }
 
 exit:
@@ -252,7 +270,7 @@ exit:
     if (nacl) free(nacl);
     if (cacl) free(cacl);
 
-    LOG(log_debug, logtype_afpd, "nfsv4_chmod(\"%s/%s\", %04o): result: %u",
+    LOG(log_debug, logtype_afpd, "nfsv4_chmod(\"%s/%s\", %04o): result: %d",
         getcwdpath(), name, mode, ret);
 
     return ret;
@@ -284,7 +302,8 @@ int posix_chmod(const char *name, mode_t mode) {
     acl_t acl;
     u_char not_found = (SEARCH_GROUP_OBJ|SEARCH_MASK); /* used as flags */
 
-    LOG(log_maxdebug, logtype_afpd, "posix_chmod: %s mode: 0x%08x", name, mode);
+    LOG(log_maxdebug, logtype_afpd, "posix_chmod(\"%s\", mode: %04o) BEGIN",
+        fullpathname(name), mode);
 
     /* Call chmod() first because there might be some special bits to be set which
      * aren't related to access control.
@@ -374,7 +393,8 @@ cleanup:
         acl_free(acl);
     }
 done:
-    LOG(log_maxdebug, logtype_afpd, "posix_chmod: %d", ret);
+    LOG(log_maxdebug, logtype_afpd, "posix_chmod(\"%s\", mode: %04o): END: %d",
+        fullpathname(name), mode, ret);
     return ret;
 }
 
index 1ab48a7e391d8ed9331290fae89a3aae63dcc5e3..7d6e7d620cf6ad0aaf554c814c9b0774e0ccc3d4 100644 (file)
@@ -24,6 +24,7 @@
 #include <sys/types.h>
 #include <pwd.h>
 #include <grp.h>
+#include <arpa/inet.h>
 
 #include <atalk/logger.h>
 #include <atalk/afp.h>
@@ -72,7 +73,7 @@ void localuuid_from_id(unsigned char *buf, uuidtype_t type, unsigned int id)
  * convert ascii string that can include dashes to binary uuid.
  * caller must provide a buffer.
  */
-void uuid_string2bin( const char *uuidstring, uuidp_t uuid) {
+void uuid_string2bin( const char *uuidstring, unsigned char *uuid) {
     int nibble = 1;
     int i = 0;
     unsigned char c, val = 0;
@@ -106,7 +107,7 @@ void uuid_string2bin( const char *uuidstring, uuidp_t uuid) {
  * Use defined or default ascii mask for dash placement
  * Returns pointer to static buffer.
  */
-const char *uuid_bin2string(unsigned char *uuid) {
+const char *uuid_bin2string(const unsigned char *uuid) {
     static char uuidstring[64];
     const char *uuidmask;
     int i = 0;
@@ -143,7 +144,7 @@ const char *uuid_bin2string(unsigned char *uuid) {
  *   uuid: pointer to uuid_t storage that the caller must provide
  * returns 0 on success !=0 on errror
  */
-int getuuidfromname( const char *name, uuidtype_t type, uuidp_t uuid) {
+int getuuidfromname( const char *name, uuidtype_t type, unsigned char *uuid) {
     int ret = 0;
     uuidtype_t mytype = type;
     char nulluuid[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0};
index 8a242c2a87679e775aa3773c3d335f02ad6d49f6..49144a2aa62831042f33efff428316378d724b60 100644 (file)
@@ -2,7 +2,17 @@
 
 noinst_LTLIBRARIES = libadouble.la
 
-libadouble_la_SOURCES = ad_open.c ad_flush.c ad_read.c ad_write.c ad_size.c \
-       ad_mmap.c ad_lock.c ad_date.c ad_attr.c ad_sendfile.c
+libadouble_la_SOURCES = \
+       ad_attr.c \
+       ad_conv.c \
+       ad_date.c \
+       ad_flush.c \
+       ad_lock.c \
+       ad_mmap.c \
+       ad_open.c \
+       ad_read.c \
+       ad_sendfile.c \
+       ad_size.c \
+       ad_write.c
 
-noinst_HEADERS = ad_private.h
+noinst_HEADERS = ad_lock.h
index 123560b5683b3e4af2729ce02631f238c48ffe4a..e5fe323fd7814249cf21b412695a85f02739f3ae 100644 (file)
@@ -3,7 +3,9 @@
 #endif /* HAVE_CONFIG_H */
 
 #include <string.h>
+#include <arpa/inet.h>
 #include <atalk/adouble.h>
+#include <atalk/logger.h>
 
 #define FILEIOFF_ATTR 14
 #define AFPFILEIOFF_ATTR 2
    retrieved from the FinderFlags. This fixes Bug #2802236:
    <https://sourceforge.net/tracker/?func=detail&aid=2802236&group_id=8642&atid=108642>
  */
-int ad_getattr(const struct adouble *ad, u_int16_t *attr)
+int ad_getattr(const struct adouble *ad, uint16_t *attr)
 {
-    u_int16_t fflags;
+    uint16_t fflags;
     *attr = 0;
 
-    if (ad->ad_version == AD_VERSION1) {
-        if (ad_getentryoff(ad, ADEID_FILEI)) {
-            memcpy(attr, ad_entry(ad, ADEID_FILEI) + FILEIOFF_ATTR,
-                   sizeof(u_int16_t));
-        }
-    }
-#if AD_VERSION == AD_VERSION2
-    else if (ad->ad_version == AD_VERSION2) {
-        if (ad_getentryoff(ad, ADEID_AFPFILEI)) {
-            memcpy(attr, ad_entry(ad, ADEID_AFPFILEI) + AFPFILEIOFF_ATTR, 2);
-
-            /* Now get opaque flags from FinderInfo */
-            memcpy(&fflags, ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, 2);
-            if (fflags & htons(FINDERINFO_INVISIBLE))
-                *attr |= htons(ATTRBIT_INVISIBLE);
+    if (ad_getentryoff(ad, ADEID_AFPFILEI)) {
+        memcpy(attr, ad_entry(ad, ADEID_AFPFILEI) + AFPFILEIOFF_ATTR, 2);
+
+        /* Now get opaque flags from FinderInfo */
+        memcpy(&fflags, ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, 2);
+        if (fflags & htons(FINDERINFO_INVISIBLE))
+            *attr |= htons(ATTRBIT_INVISIBLE);
+        else
+            *attr &= htons(~ATTRBIT_INVISIBLE);
+        /*
+         * This one is tricky, I actually got it wrong the first time:
+         * for directories bit 1<<1 is ATTRBIT_EXPFLDR and is NOT opaque !
+         */
+        if ( ! (ad->ad_adflags & ADFLAGS_DIR)) {
+            if (fflags & htons(FINDERINFO_ISHARED))
+                *attr |= htons(ATTRBIT_MULTIUSER);
             else
-                *attr &= htons(~ATTRBIT_INVISIBLE);
- /*
-   This one is tricky, I actually got it wrong the first time:
-   for directories bit 1<<1 is ATTRBIT_EXPFLDR and is NOT opaque !
- */
-            if ( ! (ad->ad_adflags & ADFLAGS_DIR)) {
-                if (fflags & htons(FINDERINFO_ISHARED))
-                    *attr |= htons(ATTRBIT_MULTIUSER);
-                else
-                    *attr &= htons(~ATTRBIT_MULTIUSER);
-            }
+                *attr &= htons(~ATTRBIT_MULTIUSER);
         }
     }
-#endif
-    else
-        return -1;
 
     *attr |= htons(ad->ad_open_forks);
 
@@ -58,49 +48,37 @@ int ad_getattr(const struct adouble *ad, u_int16_t *attr)
 }
 
 /* ----------------- */
-int ad_setattr(const struct adouble *ad, const u_int16_t attribute)
+int ad_setattr(const struct adouble *ad, const uint16_t attribute)
 {
     uint16_t fflags;
 
     /* we don't save open forks indicator */
-    u_int16_t attr = attribute & ~htons(ATTRBIT_DOPEN | ATTRBIT_ROPEN);
+    uint16_t attr = attribute & ~htons(ATTRBIT_DOPEN | ATTRBIT_ROPEN);
 
     /* Proactively (10.4 does indeed try to set ATTRBIT_MULTIUSER (=ATTRBIT_EXPFLDR)
        for dirs with SetFile -a M <dir> ) disable all flags not defined for dirs. */
     if (ad->ad_adflags & ADFLAGS_DIR)
         attr &= ~(ATTRBIT_MULTIUSER | ATTRBIT_NOWRITE | ATTRBIT_NOCOPY);
 
-    if (ad->ad_version == AD_VERSION1) {
-        if (ad_getentryoff(ad, ADEID_FILEI)) {
-            memcpy(ad_entry(ad, ADEID_FILEI) + FILEIOFF_ATTR, &attr,
-                   sizeof(attr));
-        }
-    }
-#if AD_VERSION == AD_VERSION2
-    else if (ad->ad_version == AD_VERSION2) {
-        if (ad_getentryoff(ad, ADEID_AFPFILEI) && ad_getentryoff(ad, ADEID_FINDERI)) {
-            memcpy(ad_entry(ad, ADEID_AFPFILEI) + AFPFILEIOFF_ATTR, &attr, sizeof(attr));
+    if (ad_getentryoff(ad, ADEID_AFPFILEI) && ad_getentryoff(ad, ADEID_FINDERI)) {
+        memcpy(ad_entry(ad, ADEID_AFPFILEI) + AFPFILEIOFF_ATTR, &attr, sizeof(attr));
             
-            /* Now set opaque flags in FinderInfo too */
-            memcpy(&fflags, ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, 2);
-            if (attr & htons(ATTRBIT_INVISIBLE))
-                fflags |= htons(FINDERINFO_INVISIBLE);
-            else
-                fflags &= htons(~FINDERINFO_INVISIBLE);
-
-            /* See above comment in ad_getattr() */
-            if (attr & htons(ATTRBIT_MULTIUSER)) {
-                if ( ! (ad->ad_adflags & ADFLAGS_DIR) )
-                    fflags |= htons(FINDERINFO_ISHARED);
-            } else
-                    fflags &= htons(~FINDERINFO_ISHARED);
-
-            memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &fflags, 2);
-        }
+        /* Now set opaque flags in FinderInfo too */
+        memcpy(&fflags, ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, 2);
+        if (attr & htons(ATTRBIT_INVISIBLE))
+            fflags |= htons(FINDERINFO_INVISIBLE);
+        else
+            fflags &= htons(~FINDERINFO_INVISIBLE);
+
+        /* See above comment in ad_getattr() */
+        if (attr & htons(ATTRBIT_MULTIUSER)) {
+            if ( ! (ad->ad_adflags & ADFLAGS_DIR) )
+                fflags |= htons(FINDERINFO_ISHARED);
+        } else
+            fflags &= htons(~FINDERINFO_ISHARED);
+
+        memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &fflags, 2);
     }
-#endif
-    else
-        return -1;
 
     return 0;
 }
@@ -109,81 +87,80 @@ int ad_setattr(const struct adouble *ad, const u_int16_t attribute)
  * save file/folder ID in AppleDoubleV2 netatalk private parameters
  * return 1 if resource fork has been modified
  */
-#if AD_VERSION == AD_VERSION2
-int ad_setid (struct adouble *adp, const dev_t dev, const ino_t ino , const u_int32_t id, const cnid_t did, const void *stamp)
+int ad_setid (struct adouble *adp, const dev_t dev, const ino_t ino , const uint32_t id, const cnid_t did, const void *stamp)
 {
-    if ((adp->ad_flags == AD_VERSION2) && (adp->ad_options & ADVOL_CACHE)) {
-
-        /* ad_getid depends on this to detect presence of ALL entries */
-        ad_setentrylen( adp, ADEID_PRIVID, sizeof(id));
-        memcpy(ad_entry( adp, ADEID_PRIVID ), &id, sizeof(id));
+    uint32_t tmp;
+
+    ad_setentrylen( adp, ADEID_PRIVID, sizeof(id));
+    tmp = id;
+    if (adp->ad_vers == AD_VERSION_EA)
+        tmp = htonl(tmp);
+    memcpy(ad_entry( adp, ADEID_PRIVID ), &tmp, sizeof(tmp));
+
+    ad_setentrylen( adp, ADEID_PRIVDEV, sizeof(dev_t));
+    if ((adp->ad_options & ADVOL_NODEV)) {
+        memset(ad_entry( adp, ADEID_PRIVDEV ), 0, sizeof(dev_t));
+    } else {
+        memcpy(ad_entry( adp, ADEID_PRIVDEV ), &dev, sizeof(dev_t));
+    }
 
-        ad_setentrylen( adp, ADEID_PRIVDEV, sizeof(dev_t));
-        if ((adp->ad_options & ADVOL_NODEV)) {
-            memset(ad_entry( adp, ADEID_PRIVDEV ), 0, sizeof(dev_t));
-        } else {
-            memcpy(ad_entry( adp, ADEID_PRIVDEV ), &dev, sizeof(dev_t));
-        }
+    ad_setentrylen( adp, ADEID_PRIVINO, sizeof(ino_t));
+    memcpy(ad_entry( adp, ADEID_PRIVINO ), &ino, sizeof(ino_t));
 
-        ad_setentrylen( adp, ADEID_PRIVINO, sizeof(ino_t));
-        memcpy(ad_entry( adp, ADEID_PRIVINO ), &ino, sizeof(ino_t));
+    ad_setentrylen( adp, ADEID_DID, sizeof(did));
+    memcpy(ad_entry( adp, ADEID_DID ), &did, sizeof(did));
 
-        ad_setentrylen( adp, ADEID_DID, sizeof(did));
-        memcpy(ad_entry( adp, ADEID_DID ), &did, sizeof(did));
+    ad_setentrylen( adp, ADEID_PRIVSYN, ADEDLEN_PRIVSYN);
+    memcpy(ad_entry( adp, ADEID_PRIVSYN ), stamp, ADEDLEN_PRIVSYN);
 
-        ad_setentrylen( adp, ADEID_PRIVSYN, ADEDLEN_PRIVSYN);
-        memcpy(ad_entry( adp, ADEID_PRIVSYN ), stamp, ADEDLEN_PRIVSYN);
-        return 1;
-    }
-    return 0;
+    return 1;
 }
 
 /* ----------------------------- */
-u_int32_t ad_getid (struct adouble *adp, const dev_t st_dev, const ino_t st_ino , const cnid_t did, const void *stamp)
+uint32_t ad_getid (struct adouble *adp, const dev_t st_dev, const ino_t st_ino , const cnid_t did, const void *stamp)
 {
-    u_int32_t aint = 0;
+    uint32_t aint = 0;
     dev_t  dev;
     ino_t  ino;
     cnid_t a_did;
     char   temp[ADEDLEN_PRIVSYN];
 
-    /* look in AD v2 header
-     * note inode and device are opaques and not in network order
-     * only use the ID if adouble is writable for us.
-     */
-    if (adp
-        && (adp->ad_options & ADVOL_CACHE)
-        && (adp->ad_md->adf_flags & O_RDWR )
-        && (sizeof(dev_t) == ad_getentrylen(adp, ADEID_PRIVDEV)) /* One check to ensure ALL values are there */
-        ) {
-        memcpy(&dev, ad_entry(adp, ADEID_PRIVDEV), sizeof(dev_t));
-        memcpy(&ino, ad_entry(adp, ADEID_PRIVINO), sizeof(ino_t));
-        memcpy(temp, ad_entry(adp, ADEID_PRIVSYN), sizeof(temp));
-        memcpy(&a_did, ad_entry(adp, ADEID_DID), sizeof(cnid_t));
-
-        if ( ((adp->ad_options & ADVOL_NODEV) || dev == st_dev)
-             && ino == st_ino
-             && (!did || a_did == did)
-             && (memcmp(stamp, temp, sizeof(temp)) == 0) ) {
-            memcpy(&aint, ad_entry(adp, ADEID_PRIVID), sizeof(aint));
-            return aint;
+    if (adp) {
+        if (sizeof(dev_t) == ad_getentrylen(adp, ADEID_PRIVDEV)) {
+            memcpy(&dev, ad_entry(adp, ADEID_PRIVDEV), sizeof(dev_t));
+            memcpy(&ino, ad_entry(adp, ADEID_PRIVINO), sizeof(ino_t));
+            memcpy(temp, ad_entry(adp, ADEID_PRIVSYN), sizeof(temp));
+            memcpy(&a_did, ad_entry(adp, ADEID_DID), sizeof(cnid_t));
+
+            if (((adp->ad_options & ADVOL_NODEV) || (dev == st_dev))
+                && ino == st_ino
+                && (!did || a_did == did)
+                && (memcmp(stamp, temp, sizeof(temp)) == 0) ) {
+                memcpy(&aint, ad_entry(adp, ADEID_PRIVID), sizeof(aint));
+                if (adp->ad_vers == AD_VERSION2)
+                    return aint;
+                else
+                    return ntohl(aint);
+            }
         }
     }
     return 0;
 }
 
 /* ----------------------------- */
-u_int32_t ad_forcegetid (struct adouble *adp)
+uint32_t ad_forcegetid (struct adouble *adp)
 {
-    u_int32_t aint = 0;
+    uint32_t aint = 0;
 
-    if (adp && (adp->ad_options & ADVOL_CACHE)) {
+    if (adp) {
         memcpy(&aint, ad_entry(adp, ADEID_PRIVID), sizeof(aint));
-        return aint;
+        if (adp->ad_vers == AD_VERSION2)
+            return aint;
+        else
+            return ntohl(aint);
     }
     return 0;
 }
-#endif
 
 /* -----------------
  * set resource fork filename attribute.
diff --git a/libatalk/adouble/ad_conv.c b/libatalk/adouble/ad_conv.c
new file mode 100644 (file)
index 0000000..eaac8db
--- /dev/null
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2012 Frank Lahm
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ */
+
+/*!
+ * @file
+ * Part of Netatalk's AppleDouble implementatation
+ * @sa include/atalk/adouble.h
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <errno.h>
+#include <sys/param.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <arpa/inet.h>
+
+#include <atalk/logger.h>
+#include <atalk/adouble.h>
+#include <atalk/util.h>
+#include <atalk/unix.h>
+#include <atalk/ea.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
+#include <atalk/compat.h>
+#include <atalk/errchk.h>
+#include <atalk/volume.h>
+
+#include "ad_lock.h"
+
+static char emptyfilad[32] = {0,0,0,0,0,0,0,0,
+                              0,0,0,0,0,0,0,0,
+                              0,0,0,0,0,0,0,0,
+                              0,0,0,0,0,0,0,0};
+
+static char emptydirad[32] = {0,0,0,0,0,0,0,0,
+                              0,0,0,0,0,0,1,0,
+                              0,0,0,0,0,0,0,0,
+                              0,0,0,0,0,0,0,0};
+
+static int ad_conv_v22ea_hf(const char *path, const struct stat *sp, const struct vol *vol)
+{
+    EC_INIT;
+    struct adouble adv2;
+    struct adouble adea;
+    const char *adpath;
+    int adflags;
+    uint32_t ctime, mtime, afpinfo = 0;
+    char *emptyad;
+
+    LOG(log_debug, logtype_default,"ad_conv_v22ea_hf(\"%s\"): BEGIN", fullpathname(path));
+
+    ad_init(&adea, vol);
+    ad_init_old(&adv2, AD_VERSION2, adea.ad_options);
+    adflags = S_ISDIR(sp->st_mode) ? ADFLAGS_DIR : 0;
+
+    /* Open and lock adouble:v2 file */
+    EC_ZERO( ad_open(&adv2, path, adflags | ADFLAGS_HF | ADFLAGS_RDWR) );
+
+    EC_NEG1_LOG( ad_tmplock(&adv2, ADEID_RFORK, ADLOCK_WR | ADLOCK_FILELOCK, 0, 0, 0) );
+    EC_NEG1_LOG( adv2.ad_ops->ad_header_read(path, &adv2, sp) );
+
+    /* Check if it's a non-empty header */
+    if (S_ISREG(sp->st_mode))
+        emptyad = &emptyfilad[0];
+    else
+        emptyad = &emptydirad[0];
+
+    if (ad_getentrylen(&adv2, ADEID_COMMENT) != 0)
+        goto copy;
+    if (ad_getentryoff(&adv2, ADEID_FINDERI)
+        && (ad_getentrylen(&adv2, ADEID_FINDERI) == ADEDLEN_FINDERI)
+        && (memcmp(ad_entry(&adv2, ADEID_FINDERI), emptyad, ADEDLEN_FINDERI) != 0))
+        goto copy;
+    if (ad_getentryoff(&adv2, ADEID_FILEDATESI)) {
+        EC_ZERO_LOG( ad_getdate(&adv2, AD_DATE_CREATE | AD_DATE_UNIX, &ctime) );
+        EC_ZERO_LOG( ad_getdate(&adv2, AD_DATE_MODIFY | AD_DATE_UNIX, &mtime) );
+        if ((ctime != mtime) || (mtime != sp->st_mtime))
+            goto copy;
+    }
+    if (ad_getentryoff(&adv2, ADEID_AFPFILEI)) {
+        if (memcmp(ad_entry(&adv2, ADEID_AFPFILEI), &afpinfo, ADEDLEN_AFPFILEI) != 0)
+            goto copy;
+    }
+
+    LOG(log_debug, logtype_default,"ad_conv_v22ea_hf(\"%s\"): default adouble", fullpathname(path), ret);
+    goto EC_CLEANUP;
+
+copy:
+    /* Create a adouble:ea meta EA */
+    LOG(log_debug, logtype_default,"ad_conv_v22ea_hf(\"%s\"): copying adouble", fullpathname(path), ret);
+    EC_ZERO_LOGSTR( ad_open(&adea, path, adflags | ADFLAGS_HF | ADFLAGS_RDWR | ADFLAGS_CREATE),
+                    "ad_conv_v22ea_hf(\"%s\"): error creating metadata EA: %s",
+                    fullpathname(path), strerror(errno));
+    EC_ZERO_LOG( ad_copy_header(&adea, &adv2) );
+    ad_flush(&adea);
+
+EC_CLEANUP:
+    EC_ZERO_LOG( ad_close(&adv2, ADFLAGS_HF | ADFLAGS_SETSHRMD) );
+    EC_ZERO_LOG( ad_close(&adea, ADFLAGS_HF | ADFLAGS_SETSHRMD) );
+    LOG(log_debug, logtype_default,"ad_conv_v22ea_hf(\"%s\"): END: %d", fullpathname(path), ret);
+    EC_EXIT;
+}
+
+static int ad_conv_v22ea_rf(const char *path, const struct stat *sp, const struct vol *vol)
+{
+    EC_INIT;
+    struct adouble adv2;
+    struct adouble adea;
+
+    LOG(log_debug, logtype_default,"ad_conv_v22ea_rf(\"%s\"): BEGIN", fullpathname(path));
+
+    if (S_ISDIR(sp->st_mode))
+        return 0;
+
+    ad_init(&adea, vol);
+    ad_init_old(&adv2, AD_VERSION2, adea.ad_options);
+
+    /* Open and lock adouble:v2 file */
+    EC_ZERO( ad_open(&adv2, path, ADFLAGS_HF | ADFLAGS_RF | ADFLAGS_RDWR) );
+
+    if (adv2.ad_rlen > 0) {
+        EC_NEG1_LOG( ad_tmplock(&adv2, ADEID_RFORK, ADLOCK_WR | ADLOCK_FILELOCK, 0, 0, 0) );
+
+        /* Create a adouble:ea resource fork */
+        EC_ZERO_LOG( ad_open(&adea, path, ADFLAGS_HF | ADFLAGS_RF | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) );
+
+        EC_ZERO_LOG( copy_fork(ADEID_RFORK, &adea, &adv2) );
+        adea.ad_rlen = adv2.ad_rlen;
+        ad_flush(&adea);
+    }
+
+EC_CLEANUP:
+    EC_ZERO_LOG( ad_close(&adv2, ADFLAGS_HF | ADFLAGS_RF) );
+    EC_ZERO_LOG( ad_close(&adea, ADFLAGS_HF | ADFLAGS_RF) );
+    LOG(log_debug, logtype_default,"ad_conv_v22ea_rf(\"%s\"): END: %d", fullpathname(path), ret);
+    EC_EXIT;
+}
+
+static int ad_conv_v22ea(const char *path, const struct stat *sp, const struct vol *vol)
+{
+    EC_INIT;
+    const char *adpath;
+    int adflags = S_ISDIR(sp->st_mode) ? ADFLAGS_DIR : 0;
+
+    become_root();
+
+    EC_ZERO( ad_conv_v22ea_hf(path, sp, vol) );
+    EC_ZERO( ad_conv_v22ea_rf(path, sp, vol) );
+
+    EC_NULL( adpath = ad_path(path, adflags) );
+    LOG(log_debug, logtype_default,"ad_conv_v22ea_hf(\"%s\"): deleting adouble:v2 file: \"%s\"",
+        path, fullpathname(adpath));
+
+    unlink(adpath);
+
+EC_CLEANUP:
+    if (errno == ENOENT)
+        EC_STATUS(0);
+
+    unbecome_root();
+
+    EC_EXIT;
+}
+
+/*!
+ * Remove hexencoded dots and slashes (":2e" and ":2f")
+ */
+static int ad_conv_dehex(const char *path, const struct stat *sp, const struct vol *vol, const char **newpathp)
+{
+    EC_INIT;
+    static char buf[MAXPATHLEN];
+    const char *adpath, *p;
+    int adflags = S_ISDIR(sp->st_mode) ? ADFLAGS_DIR : 0;
+    bstring newpath = NULL;
+
+    LOG(log_debug, logtype_default,"ad_conv_dehex(\"%s\"): BEGIN", fullpathname(path));
+
+    *newpathp = NULL;
+
+    if ((p = strchr(path, ':')) == NULL)
+        goto EC_CLEANUP;
+
+    EC_NULL( newpath = bfromcstr(path) );
+
+    EC_ZERO( bfindreplace(newpath, bfromcstr(":2e"), bfromcstr("."), 0) );
+    EC_ZERO( bfindreplace(newpath, bfromcstr(":2f"), bfromcstr(":"), 0) );
+    
+    become_root();
+    if (adflags != ADFLAGS_DIR)
+        rename(vol->ad_path(path, 0), vol->ad_path(bdata(newpath), 0));
+    rename(path, bdata(newpath));
+    unbecome_root();
+
+    strlcpy(buf, bdata(newpath), sizeof(buf));
+    *newpathp = buf;
+
+EC_CLEANUP:
+    if (newpath)
+        bdestroy(newpath);
+    EC_EXIT;
+}
+
+/*!
+ * AppleDouble and encoding conversion on the fly
+ *
+ * @param path      (r) path to file or directory
+ * @param sp        (r) stat(path)
+ * @param vol       (r) volume handle
+ * @param newpath   (w) if encoding changed, new name. Can be NULL.
+ *
+ * @returns         -1 on internal error, otherwise 0. newpath is NULL if no character conversion was done,
+ *                  otherwise newpath points to a static string with the converted name
+ */
+int ad_convert(const char *path, const struct stat *sp, const struct vol *vol, const char **newpath)
+{
+    EC_INIT;
+    const char *p;
+
+    LOG(log_debug, logtype_default,"ad_convert(\"%s\"): BEGIN", fullpathname(path));
+
+    if (newpath)
+        *newpath = NULL;
+
+    if ((vol->v_adouble == AD_VERSION_EA) && !(vol->v_flags & AFPVOL_NOV2TOEACONV))
+        EC_ZERO( ad_conv_v22ea(path, sp, vol) );
+
+    if (vol->v_adouble == AD_VERSION_EA) {
+        EC_ZERO( ad_conv_dehex(path, sp, vol, &p) );
+        if (p && newpath)
+            *newpath = p;
+    }
+
+EC_CLEANUP:
+    LOG(log_debug, logtype_default,"ad_convert(\"%s\"): END: %d", fullpathname(path), ret);
+    EC_EXIT;
+}
+
index 132c4f1ae7935b151b68ce34d269f3b91cd68616..304642d55f178b6e33d2ce2c9e1785457d933b18 100644 (file)
@@ -3,65 +3,42 @@
 #endif /* HAVE_CONFIG_H */
 
 #include <string.h>
+#include <arpa/inet.h>
 #include <atalk/adouble.h>
 
-int ad_setdate(struct adouble *ad, 
-              unsigned int dateoff, u_int32_t date)
+int ad_setdate(struct adouble *ad,
+               unsigned int dateoff, uint32_t date)
 {
-  int xlate = (dateoff & AD_DATE_UNIX);
+    int xlate = (dateoff & AD_DATE_UNIX);
 
-  dateoff &= AD_DATE_MASK;
-  if (xlate)
-    date = AD_DATE_FROM_UNIX(date);
+    dateoff &= AD_DATE_MASK;
+    if (xlate)
+        date = AD_DATE_FROM_UNIX(date);
 
-  if (ad->ad_version == AD_VERSION1) {
-
-    if (!ad_getentryoff(ad, ADEID_FILEI))
-        return -1;
-
-    if (dateoff > AD_DATE_BACKUP)
-      return -1;
-    memcpy(ad_entry(ad, ADEID_FILEI) + dateoff, &date, sizeof(date));
-
-  } else if (ad->ad_version == AD_VERSION2) {
     if (!ad_getentryoff(ad, ADEID_FILEDATESI))
         return -1;
-        
+
     if (dateoff > AD_DATE_ACCESS)
         return -1;
     memcpy(ad_entry(ad, ADEID_FILEDATESI) + dateoff, &date, sizeof(date));
 
-  } else 
-    return -1;
-
-  return 0;
+    return 0;
 }
 
 int ad_getdate(const struct adouble *ad,
-              unsigned int dateoff, u_int32_t *date) 
+               unsigned int dateoff, uint32_t *date)
 {
-  int xlate = (dateoff & AD_DATE_UNIX);
-
-  dateoff &= AD_DATE_MASK;
-  if (ad->ad_version == AD_VERSION1) {
-    if (dateoff > AD_DATE_BACKUP)
-      return -1;
-    if (!ad_getentryoff(ad, ADEID_FILEI))
-        return -1;
-    memcpy(date, ad_entry(ad, ADEID_FILEI) + dateoff, sizeof(u_int32_t));
+    int xlate = (dateoff & AD_DATE_UNIX);
 
-  } else if (ad->ad_version == AD_VERSION2) {
+    dateoff &= AD_DATE_MASK;
     if (!ad_getentryoff(ad, ADEID_FILEDATESI))
         return -1;
 
     if (dateoff > AD_DATE_ACCESS)
-      return -1;
-    memcpy(date, ad_entry(ad, ADEID_FILEDATESI) + dateoff, sizeof(u_int32_t));
-
-  } else 
-    return -1;
+        return -1;
+    memcpy(date, ad_entry(ad, ADEID_FILEDATESI) + dateoff, sizeof(uint32_t));
 
-  if (xlate)
-    *date = AD_DATE_TO_UNIX(*date);
-  return 0;
+    if (xlate)
+        *date = AD_DATE_TO_UNIX(*date);
+    return 0;
 }
index 1f4d8b331b4bb92eafcb3a15c4d20dffe28aa6de..eaf904cac77ab597d57e89ee0699a68d8788db01 100644 (file)
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 1990,1991 Regents of The University of Michigan.
+ * Copyright (c) 2010      Frank Lahm
  * All Rights Reserved.
  *
  * Permission to use, copy, modify, and distribute this software and
 #endif /* HAVE_CONFIG_H */
 
 #include <string.h>
-#include <atalk/adouble.h>
-
 #include <stdio.h>
 #include <stdlib.h>
 #include <errno.h>
+#include <arpa/inet.h>
 
-#include "ad_private.h"
-#if AD_VERSION == AD_VERSION1
-
-#define EID_DISK(a) (a)
+#include <atalk/adouble.h>
+#include <atalk/ea.h>
+#include <atalk/logger.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
+#include <atalk/errchk.h>
+#include <atalk/util.h>
 
-#else
+#include "ad_lock.h"
 
-static const u_int32_t set_eid[] = {
+static const uint32_t set_eid[] = {
     0,1,2,3,4,5,6,7,8,
     9,10,11,12,13,14,15,
     AD_DEV, AD_INO, AD_SYN, AD_ID
 };
 
 #define EID_DISK(a) (set_eid[a])
-#endif
 
-/* rebuild the adouble header
- * XXX should be in a separate file ?
+/*
+ * Prepare ad->ad_data buffer from struct adouble for writing on disk
  */
-int  ad_rebuild_adouble_header(struct adouble *ad)
+int ad_rebuild_adouble_header_v2(struct adouble *ad)
 {
-    u_int32_t       eid;
-    u_int32_t       temp;
-
-    u_int16_t       nent;
+    uint32_t       eid;
+    uint32_t       temp;
+    uint16_t       nent;
     char        *buf, *nentp;
+    int             len;
+
+    LOG(log_debug, logtype_default, "ad_rebuild_adouble_header_v2");
 
-    /*
-     * Rebuild any header information that might have changed.
-     */
     buf = ad->ad_data;
 
     temp = htonl( ad->ad_magic );
@@ -72,15 +73,13 @@ int  ad_rebuild_adouble_header(struct adouble *ad)
     memcpy(buf, &temp, sizeof( temp ));
     buf += sizeof( temp );
 
-    memcpy(buf, ad->ad_filler, sizeof( ad->ad_filler ));
     buf += sizeof( ad->ad_filler );
 
     nentp = buf;
     buf += sizeof( nent );
     for ( eid = 0, nent = 0; eid < ADEID_MAX; eid++ ) {
-        if ( ad->ad_eid[ eid ].ade_off == 0 ) {
+        if (ad->ad_eid[ eid ].ade_off == 0)
             continue;
-        }
         temp = htonl( EID_DISK(eid) );
         memcpy(buf, &temp, sizeof( temp ));
         buf += sizeof( temp );
@@ -96,9 +95,116 @@ int  ad_rebuild_adouble_header(struct adouble *ad)
     }
     nent = htons( nent );
     memcpy(nentp, &nent, sizeof( nent ));
+
     return ad_getentryoff(ad, ADEID_RFORK);
 }
 
+int ad_rebuild_adouble_header_ea(struct adouble *ad)
+{
+    uint32_t       eid;
+    uint32_t       temp;
+    uint16_t       nent;
+    char        *buf, *nentp;
+    int             len;
+
+    LOG(log_debug, logtype_default, "ad_rebuild_adouble_header_ea");
+
+    buf = ad->ad_data;
+
+    temp = htonl( ad->ad_magic );
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    temp = htonl( ad->ad_version );
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    buf += sizeof( ad->ad_filler );
+
+    nentp = buf;
+    buf += sizeof( nent );
+    for ( eid = 0, nent = 0; eid < ADEID_MAX; eid++ ) {
+        if ((ad->ad_eid[ eid ].ade_off == 0) || (eid == ADEID_RFORK))
+            continue;
+        temp = htonl( EID_DISK(eid) );
+        memcpy(buf, &temp, sizeof( temp ));
+        buf += sizeof( temp );
+
+        temp = htonl( ad->ad_eid[ eid ].ade_off );
+        memcpy(buf, &temp, sizeof( temp ));
+        buf += sizeof( temp );
+
+        temp = htonl( ad->ad_eid[ eid ].ade_len );
+        memcpy(buf, &temp, sizeof( temp ));
+        buf += sizeof( temp );
+        nent++;
+    }
+    nent = htons( nent );
+    memcpy(nentp, &nent, sizeof( nent ));
+
+    return AD_DATASZ_EA;
+}
+
+/*!
+ * Prepare adbuf buffer from struct adouble for writing on disk
+ */
+static int ad_rebuild_adouble_header_osx(struct adouble *ad, char *adbuf)
+{
+    uint32_t       temp;
+    uint16_t       nent;
+    char           *buf;
+    int            len;
+
+    LOG(log_debug, logtype_default, "ad_rebuild_adouble_header_osx");
+
+    buf = &adbuf[0];
+
+    temp = htonl( ad->ad_magic );
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    temp = htonl( ad->ad_version );
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    memset(buf, 0, sizeof(ad->ad_filler));
+    buf += sizeof( ad->ad_filler );
+
+    nent = htons(ADEID_NUM_OSX);
+    memcpy(buf, &nent, sizeof( nent ));
+    buf += sizeof( nent );
+
+    /* FinderInfo */
+    temp = htonl(EID_DISK(ADEID_FINDERI));
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    temp = htonl(ADEDOFF_FINDERI_OSX);
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    temp = htonl(ADEDLEN_FINDERI);
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    memcpy(adbuf + ADEDOFF_FINDERI_OSX, ad_entry(ad, ADEID_FINDERI), ADEDLEN_FINDERI);
+
+    /* rfork */
+    temp = htonl( EID_DISK(ADEID_RFORK) );
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    temp = htonl(ADEDOFF_RFORK_OSX);
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    temp = htonl( ad->ad_rlen);
+    memcpy(buf, &temp, sizeof( temp ));
+    buf += sizeof( temp );
+
+    return AD_DATASZ_OSX;
+}
+
 /* -------------------
  * XXX copy only header with same size or comment
  * doesn't work well for adouble with different version.
@@ -106,139 +212,235 @@ int  ad_rebuild_adouble_header(struct adouble *ad)
  */
 int ad_copy_header(struct adouble *add, struct adouble *ads)
 {
-    u_int32_t       eid;
-    u_int32_t       len;
+    uint32_t       eid;
+    uint32_t       len;
 
     for ( eid = 0; eid < ADEID_MAX; eid++ ) {
-        if ( ads->ad_eid[ eid ].ade_off == 0 ) {
+        if ( ads->ad_eid[ eid ].ade_off == 0 || add->ad_eid[ eid ].ade_off == 0 )
             continue;
-        }
-
-        if ( add->ad_eid[ eid ].ade_off == 0 ) {
-            continue;
-        }
 
         len = ads->ad_eid[ eid ].ade_len;
-        if (!len) {
+        if (!len || len != add->ad_eid[ eid ].ade_len)
             continue;
-        }
 
-        if (eid != ADEID_COMMENT && add->ad_eid[ eid ].ade_len != len ) {
+        switch (eid) {
+        case ADEID_COMMENT:
+        case ADEID_PRIVDEV:
+        case ADEID_PRIVINO:
+        case ADEID_PRIVSYN:
+        case ADEID_PRIVID:
             continue;
+        default:
+            ad_setentrylen( add, eid, len );
+            memcpy( ad_entry( add, eid ), ad_entry( ads, eid ), len );
         }
-
-        ad_setentrylen( add, eid, len );
-        memcpy( ad_entry( add, eid ), ad_entry( ads, eid ), len );
     }
     add->ad_rlen = ads->ad_rlen;
+
+    if ((ads->ad_vers == AD_VERSION2) && (add->ad_vers = AD_VERSION_EA)
+        || (ads->ad_vers == AD_VERSION_EA) && (add->ad_vers = AD_VERSION2)) {
+        cnid_t id;
+        memcpy(&id, ad_entry(add, ADEID_PRIVID), sizeof(cnid_t));
+        id = htonl(id);
+        memcpy(ad_entry(add, ADEID_PRIVID), &id, sizeof(cnid_t));
+    }
     return 0;
 }
 
-/* ------------------- */
-int  ad_rebuild_sfm_header(struct adouble *ad)
+static int ad_flush_hf(struct adouble *ad)
 {
-    u_int32_t       temp;
-
-    u_int16_t       attr;
-    char        *buf;
-
-    /*
-     * Rebuild any header information that might have changed.
-     */
-    buf = ad->ad_data;
-    /* FIXME */
-/*    temp = htonl( ad->ad_magic ); */
-    temp = ad->ad_magic;
-    memcpy(buf, &temp, sizeof( temp ));
-
-/*    temp = htonl( ad->ad_version ); */
-    temp = ad->ad_version;
-    memcpy(buf +4, &temp, sizeof( temp ));
+    EC_INIT;
+    int len;
+    int cwd = -1;
+
+    LOG(log_debug, logtype_default, "ad_flush_hf(%s)", adflags2logstr(ad->ad_adflags));
+
+    struct ad_fd *adf;
+
+    switch (ad->ad_vers) {
+    case AD_VERSION2:
+        adf = ad->ad_mdp;
+        break;
+    case AD_VERSION_EA:
+        adf = &ad->ad_data_fork;
+        break;
+    default:
+        LOG(log_error, logtype_afpd, "ad_flush: unexpected adouble version");
+        return -1;
+    }
 
-    /* need to save attrib */
-    if (!ad_getattr(ad, &attr)) {
-        attr &= ~htons(ATTRBIT_DOPEN | ATTRBIT_ROPEN);
+    if ((adf->adf_flags & O_RDWR)
+        || ((ad->ad_adflags & ADFLAGS_DIR) && (ad->ad_adflags & ADFLAGS_RDWR))) {
+        if (ad_getentryoff(ad, ADEID_RFORK)) {
+            if (ad->ad_rlen > 0xffffffff)
+                ad_setentrylen(ad, ADEID_RFORK, 0xffffffff);
+            else
+                ad_setentrylen(ad, ADEID_RFORK, ad->ad_rlen);
+        }
+        len = ad->ad_ops->ad_rebuild_header(ad);
 
-        memcpy(buf +48 +4, &attr, sizeof(attr));
+        switch (ad->ad_vers) {
+        case AD_VERSION2:
+            if (adf_pwrite(ad->ad_mdp, ad->ad_data, len, 0) != len) {
+                if (errno == 0)
+                    errno = EIO;
+                return( -1 );
+            }
+            break;
+        case AD_VERSION_EA:
+            if (AD_META_OPEN(ad)) {
+                if (ad->ad_adflags & ADFLAGS_DIR) {
+                    EC_NEG1_LOG( cwd = open(".", O_RDONLY) );
+                    EC_NEG1_LOG( fchdir(ad_data_fileno(ad)) );
+                    EC_ZERO_LOG( sys_lsetxattr(".", AD_EA_META, ad->ad_data, AD_DATASZ_EA, 0) );
+                    EC_NEG1_LOG( fchdir(cwd) );
+                    EC_NEG1_LOG( close(cwd) );
+                    cwd = -1;
+                } else {
+                    EC_ZERO_LOG( sys_fsetxattr(ad_data_fileno(ad), AD_EA_META, ad->ad_data, AD_DATASZ_EA, 0) );
+                }
+            }
+            break;
+        default:
+            LOG(log_error, logtype_afpd, "ad_flush: unexpected adouble version");
+            return -1;
+        }
+    }
 
+EC_CLEANUP:
+    if (cwd != -1) {
+        if (fchdir(cwd) != 0) {
+            AFP_PANIC("ad_flush: cant fchdir");
+        }
+        close(cwd);
     }
-    return AD_SFM_LEN;
+    EC_EXIT;
 }
 
-
-int ad_flush( struct adouble *ad)
+/* Flush resofork adouble file if any (currently adouble:ea and #ifndef HAVE_EAFD eg Linux) */
+static int ad_flush_rf(struct adouble *ad)
 {
-    int len;
+    ssize_t len;
+    char    adbuf[AD_DATASZ_OSX];
 
-    if (( ad->ad_md->adf_flags & O_RDWR )) {
-        /* sync our header */
-        if (ad->ad_rlen > 0xffffffff) {
-            ad_setentrylen(ad, ADEID_RFORK, 0xffffffff);
-        }
-        else {
-            ad_setentrylen(ad, ADEID_RFORK, ad->ad_rlen);
+#ifdef HAVE_EAFD
+    return 0;
+#endif
+    if (ad->ad_vers != AD_VERSION_EA)
+        return 0;
+
+    LOG(log_debug, logtype_default, "ad_flush_rf(%s)", adflags2logstr(ad->ad_adflags));
+
+    if ((ad->ad_rfp->adf_flags & O_RDWR)) {
+        if (ad_getentryoff(ad, ADEID_RFORK)) {
+            if (ad->ad_rlen > 0xffffffff)
+                ad_setentrylen(ad, ADEID_RFORK, 0xffffffff);
+            else
+                ad_setentrylen(ad, ADEID_RFORK, ad->ad_rlen);
         }
-        len = ad->ad_ops->ad_rebuild_header(ad);
+        len = ad_rebuild_adouble_header_osx(ad, &adbuf[0]);
 
-        if (adf_pwrite(ad->ad_md, ad->ad_data, len, 0) != len) {
-            if ( errno == 0 ) {
+        if (adf_pwrite(ad->ad_rfp, adbuf, len, 0) != len) {
+            if (errno == 0)
                 errno = EIO;
-            }
-            return( -1 );
+            return -1;
         }
     }
-
-    return( 0 );
+    return 0;
 }
 
-/* use refcounts so that we don't have to re-establish fcntl locks. */
-int ad_close( struct adouble *ad, int adflags)
+int ad_flush(struct adouble *ad)
 {
-    int         err = 0;
+    EC_INIT;
 
-    if ((adflags & ADFLAGS_DF)
-        && (ad_data_fileno(ad) >= 0 || ad_data_fileno(ad) == -2) /* -2 means symlink */
-        && --ad->ad_data_fork.adf_refcount == 0) {
-        if (ad->ad_data_fork.adf_syml != NULL) {
-            free(ad->ad_data_fork.adf_syml);
-            ad->ad_data_fork.adf_syml = 0;
-        } else {
-            if ( close( ad_data_fileno(ad) ) < 0 )
-                err = -1;
-        }
-        ad_data_fileno(ad) = -1;
-        adf_lock_free(&ad->ad_data_fork);
+    LOG(log_debug, logtype_default, "ad_flush(%s)", adflags2logstr(ad->ad_adflags));
+
+    if (AD_META_OPEN(ad)) {
+        EC_ZERO( ad_flush_hf(ad) );
     }
 
-    if (!( adflags & ADFLAGS_HF )) {
-        return err;
+    if (AD_RSRC_OPEN(ad)) {
+        EC_ZERO( ad_flush_rf(ad) );
     }
 
-    /* meta /resource fork */
+EC_CLEANUP:
+    EC_EXIT;
+}
 
-    if ( ad_meta_fileno(ad) != -1 && !(--ad->ad_md->adf_refcount)) {
-        if ( close( ad_meta_fileno(ad) ) < 0 ) {
-            err = -1;
-        }
-        ad_meta_fileno(ad) = -1;
-        adf_lock_free(ad->ad_md);
+static int ad_data_closefd(struct adouble *ad)
+{
+    int ret = 0;
+
+    if (ad_data_fileno(ad) == AD_SYMLINK) {
+        free(ad->ad_data_fork.adf_syml);
+        ad->ad_data_fork.adf_syml = NULL;
+    } else {
+        if (close(ad_data_fileno(ad)) < 0)
+            ret = -1;
     }
+    ad_data_fileno(ad) = -1;
+    return ret;
+}
+
+/*!
+ * Close a struct adouble freeing all resources
+ */
+int ad_close(struct adouble *ad, int adflags)
+{
+    int err = 0;
 
-    if (ad->ad_flags != AD_VERSION1_SFM) {
+    if (ad == NULL)
         return err;
+
+    LOG(log_debug, logtype_default,
+        "ad_close(%s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        adflags2logstr(adflags),
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
+
+    if (adflags & (ADFLAGS_SETSHRMD | ADFLAGS_CHECK_OF)) {
+        /* sharemode locks are stored in the data fork, adouble:v2 needs this extra handling */
+        adflags |= ADFLAGS_DF;
     }
 
-    if ((adflags & ADFLAGS_DIR)) {
-        return err;
+    if ((ad->ad_vers == AD_VERSION2) && (adflags & ADFLAGS_RF))
+        adflags |= ADFLAGS_HF;
+
+    if ((adflags & ADFLAGS_DF)
+        && (ad_data_fileno(ad) >= 0 || ad_data_fileno(ad) == AD_SYMLINK)
+        && --ad->ad_data_fork.adf_refcount == 0) {
+        if (ad_data_closefd(ad) < 0)
+            err = -1;
+        adf_lock_free(&ad->ad_data_fork);
     }
 
-    if ( ad_reso_fileno(ad) != -1 && !(--ad->ad_resource_fork.adf_refcount)) {
-        if ( close( ad_reso_fileno(ad) ) < 0 ) {
+    if ((adflags & ADFLAGS_HF)
+        && (ad_meta_fileno(ad) != -1) && !(--ad->ad_mdp->adf_refcount)) {
+        if (close( ad_meta_fileno(ad)) < 0)
             err = -1;
+        ad_meta_fileno(ad) = -1;
+        if (ad->ad_vers == AD_VERSION2)
+            adf_lock_free(ad->ad_mdp);
+    }
+
+    if ((adflags & ADFLAGS_RF) && (ad->ad_vers == AD_VERSION_EA)) {
+        if ((ad_reso_fileno(ad) != -1)
+            && !(--ad->ad_rfp->adf_refcount)) {
+            if (close(ad->ad_rfp->adf_fd) < 0)
+                err = -1;
+            ad->ad_rlen = 0;
+            ad_reso_fileno(ad) = -1;
+            adf_lock_free(ad->ad_rfp);
         }
-        ad_reso_fileno(ad) = -1;
-        adf_lock_free(&ad->ad_resource_fork);
     }
 
+    LOG(log_debug, logtype_default,
+        "ad_close(%s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        adflags2logstr(adflags), err,
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
+
     return err;
 }
index e2139e5850b7ed4eacd1dd09dd5f88ce37d31cc5..92f0ab89224501331c5a010dd323196ced0258b3 100644 (file)
@@ -2,11 +2,9 @@
  * Copyright (c) 1998,1999 Adrian Sun (asun@zoology.washington.edu)
  * All Rights Reserved. See COPYRIGHT for more information.
  *
- * Byte-range locks. This uses either whole-file flocks to fake byte
- * locks or fcntl-based actual byte locks. Because fcntl locks are
+ * Because fcntl locks are
  * process-oriented, we need to keep around a list of file descriptors
- * that refer to the same file. Currently, this doesn't serialize access 
- * to the locks. as a result, there's the potential for race conditions. 
+ * that refer to the same file.
  *
  * TODO: fix the race when reading/writing.
  *       keep a pool of both locks and reference counters around so that
@@ -20,6 +18,9 @@
 
 #include <atalk/adouble.h>
 #include <atalk/logger.h>
+#include <atalk/compat.h>
+#include <atalk/errchk.h>
+#include <atalk/util.h>
 
 #include <stdio.h>
 #include <stdlib.h>
 
 #include <string.h>
 
-#include "ad_private.h"
+#include "ad_lock.h"
 
-/* translate between ADLOCK styles and specific locking mechanisms */
-#define XLATE_FLOCK(type) ((type) == ADLOCK_RD ? LOCK_SH : \
-((type) == ADLOCK_WR ? LOCK_EX : \
- ((type) == ADLOCK_CLR ? LOCK_UN : -1)))
-
-#ifdef DISABLE_LOCKING
-#define fcntl(a, b, c ) (0)
-#endif
+static const char *shmdstrfromoff(off_t off)
+{
+    switch (off) {
+    case AD_FILELOCK_OPEN_WR:
+        return "OPEN_WR_DATA";
+    case AD_FILELOCK_OPEN_RD:
+        return "OPEN_RD_DATA";
+    case AD_FILELOCK_RSRC_OPEN_WR:
+        return "OPEN_WR_RSRC";
+    case AD_FILELOCK_RSRC_OPEN_RD:
+        return "OPEN_RD_RSRC";
+    case AD_FILELOCK_DENY_WR:
+        return "DENY_WR_DATA";
+    case AD_FILELOCK_DENY_RD:
+        return "DENY_RD_DATA";
+    case AD_FILELOCK_RSRC_DENY_WR:
+        return "DENY_WR_RSRC";
+    case AD_FILELOCK_RSRC_DENY_RD:
+        return "DENY_RD_RSRC";
+    case AD_FILELOCK_OPEN_NONE:
+        return "OPEN_NONE_DATA";
+    case AD_FILELOCK_RSRC_OPEN_NONE:
+        return "OPEN_NONE_RSRC";
+    default:
+        return "-";
+    }
+}
 
 /* ----------------------- */
 static int set_lock(int fd, int cmd,  struct flock *lock)
 {
-  if (fd == -2) {
-      /* We assign fd = -2 for symlinks -> do nothing */
-      if (cmd == F_GETLK)
-           lock->l_type = F_UNLCK;
-      return 0;
-  }
-  return fcntl(fd, cmd, lock);
+    EC_INIT;
+
+    LOG(log_debug, logtype_default, "set_lock(fd: %d, %s, %s, off: %jd (%s), len: %jd): BEGIN",
+        fd, cmd == F_SETLK ? "F_SETLK" : "F_GETLK",
+        lock->l_type == F_RDLCK ? "F_RDLCK" : lock->l_type == F_WRLCK ? "F_WRLCK" : "F_UNLCK",
+        (intmax_t)lock->l_start,
+        shmdstrfromoff(lock->l_start),
+        (intmax_t)lock->l_len);
+
+    if (fd == AD_SYMLINK) {
+        if (cmd == F_GETLK)
+            lock->l_type = F_UNLCK;
+        return 0;
+    }
+
+    EC_NEG1( fcntl(fd, cmd, lock) );
+
+EC_CLEANUP:
+    EC_EXIT;
 }
 
 /* ----------------------- */
@@ -68,9 +100,9 @@ static int XLATE_FCNTL_LOCK(int type)
 /* ----------------------- */
 static int OVERLAP(off_t a, off_t alen, off_t b, off_t blen) 
 {
- return (!alen && a <= b) || 
-       (!blen && b <= a) || 
-       ( (a + alen > b) && (b + blen > a) );
   return (!alen && a <= b) || 
+        (!blen && b <= a) || 
+        ( (a + alen > b) && (b + blen > a) );
 }
 
 /* allocation for lock regions. we allocate aggressively and shrink
@@ -85,10 +117,8 @@ static void adf_freelock(struct ad_fd *ad, const int i)
 
     if (--(*lock->refcount) < 1) {
        free(lock->refcount); 
-       if (!ad->adf_excl) {
-           lock->lock.l_type = F_UNLCK;
-           set_lock(ad->adf_fd, F_SETLK, &lock->lock); /* unlock */
-       }
+    lock->lock.l_type = F_UNLCK;
+    set_lock(ad->adf_fd, F_SETLK, &lock->lock); /* unlock */
     }
 
     ad->adf_lockcount--;
@@ -117,50 +147,50 @@ static void adf_freelock(struct ad_fd *ad, const int i)
 
 
 /* this needs to deal with the following cases:
- * 1) fork is the only user of the lock 
- * 2) fork shares a read lock with another open fork
+ * 1) free all UNIX byterange lock from any fork
+ * 2) free all locks of the requested fork
  *
  * i converted to using arrays of locks. everytime a lock
  * gets removed, we shift all of the locks down.
  */
-static void adf_unlock(struct ad_fd *ad, const int fork)
+static void adf_unlock(struct adouble *ad, struct ad_fd *adf, const int fork, int unlckbrl)
 {
-    adf_lock_t *lock = ad->adf_lock;
+    adf_lock_t *lock = adf->adf_lock;
     int i;
 
-    for (i = 0; i < ad->adf_lockcount; i++) {
-      
-      if (lock[i].user == fork) {
-       /* we're really going to delete this lock. note: read locks
-           are the only ones that allow refcounts > 1 */
-        adf_freelock(ad, i);
-        i--; /* we shifted things down, so we need to backtrack */
-        /* unlikely but realloc may have change adf_lock */
-        lock = ad->adf_lock;       
-      }
+    for (i = 0; i < adf->adf_lockcount; i++) {
+        if ((unlckbrl && lock[i].lock.l_start < AD_FILELOCK_BASE)
+            || lock[i].user == fork) {
+            /* we're really going to delete this lock. note: read locks
+               are the only ones that allow refcounts > 1 */
+            adf_freelock(adf, i);
+            /* we shifted things down, so we need to backtrack */
+            i--; 
+            /* unlikely but realloc may have change adf_lock */
+            lock = adf->adf_lock;       
+        }
     }
 }
 
 /* relock any byte lock that overlaps off/len. unlock everything
  * else. */
-static void adf_relockrange(struct ad_fd *ad, int fd,
-                                      const off_t off, const off_t len)
+static void adf_relockrange(struct ad_fd *ad, int fd, off_t off, off_t len)
 {
     adf_lock_t *lock = ad->adf_lock;
     int i;
     
-    if (!ad->adf_excl) for (i = 0; i < ad->adf_lockcount; i++) {
-      if (OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) 
-       set_lock(fd, F_SETLK, &lock[i].lock);
+    for (i = 0; i < ad->adf_lockcount; i++) {
+        if (OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) 
+            set_lock(fd, F_SETLK, &lock[i].lock);
     }
 }
 
 
 /* find a byte lock that overlaps off/len for a particular open fork */
 static int adf_findlock(struct ad_fd *ad,
-                                  const int fork, const int type,
-                                  const off_t off,
-                                  const off_t len)
+                        const int fork, const int type,
+                        const off_t off,
+                        const off_t len)
 {
   adf_lock_t *lock = ad->adf_lock;
   int i;
@@ -173,28 +203,30 @@ static int adf_findlock(struct ad_fd *ad,
       return i;
     }
   }
-
   return -1;
 }
 
 
 /* search other fork lock lists */
 static int adf_findxlock(struct ad_fd *ad, 
-                                    const int fork, const int type,
-                                    const off_t off,
-                                    const off_t len)
+                         const int fork, const int type,
+                         const off_t off,
+                         const off_t len)
 {
-  adf_lock_t *lock = ad->adf_lock;
-  int i;
+    adf_lock_t *lock = ad->adf_lock;
+    int i;
   
-  for (i = 0; i < ad->adf_lockcount; i++) {
-    if ((((type & ADLOCK_RD) && (lock[i].lock.l_type == F_RDLCK)) ||
-        ((type & ADLOCK_WR) && (lock[i].lock.l_type == F_WRLCK))) &&
-       (lock[i].user != fork) && 
-       OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) 
-           return i;
-  } 
-  return -1;
+    for (i = 0; i < ad->adf_lockcount; i++) {
+        if ((((type & ADLOCK_RD) && (lock[i].lock.l_type == F_RDLCK))
+             ||
+             ((type & ADLOCK_WR) && (lock[i].lock.l_type == F_WRLCK)))
+            &&
+            (lock[i].user != fork)
+            && 
+            OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) 
+            return i;
+    } 
+    return -1;
 }
 
 /* okay, this needs to do the following:
@@ -209,436 +241,421 @@ static int adf_findxlock(struct ad_fd *ad,
  *       2) if the header file doesn't exist, we stick the locks
  *          in the locations specified by AD_FILELOCK_RD/WR.
  */
-#define LOCK_DATA_WR (0)
-#define LOCK_DATA_RD (1)
-#define LOCK_RSRC_WR (2)
-#define LOCK_RSRC_RD (3)
-
-#define LOCK_RSRC_DRD (4)
-#define LOCK_RSRC_DWR (5)
-#define LOCK_DATA_DRD (6)
-#define LOCK_DATA_DWR (7)
-
-#define LOCK_RSRC_NONE (8)
-#define LOCK_DATA_NONE (9)
 
 /* -------------- 
-       translate a data fork lock to an offset
+       translate a resource fork lock to an offset
 */
-
-static off_t df2off(off_t off)
+static off_t rf2off(off_t off)
 {
     off_t start = off;
        if (off == AD_FILELOCK_OPEN_WR)
-               start = LOCK_DATA_WR;
+               start = AD_FILELOCK_RSRC_OPEN_WR;
        else if (off == AD_FILELOCK_OPEN_RD)
-               start = LOCK_DATA_RD;
+               start = AD_FILELOCK_RSRC_OPEN_RD;
     else if (off == AD_FILELOCK_DENY_RD)
-               start = LOCK_DATA_DRD;
+               start = AD_FILELOCK_RSRC_DENY_RD;
        else if (off == AD_FILELOCK_DENY_WR)
-               start = LOCK_DATA_DWR;
+               start = AD_FILELOCK_RSRC_DENY_WR;
        else if (off == AD_FILELOCK_OPEN_NONE)
-               start = LOCK_DATA_NONE;
+               start = AD_FILELOCK_RSRC_OPEN_NONE;
        return start;
 }
 
-/* -------------- 
-       translate a resource fork lock to an offset
-*/
-
-static off_t hf2off(off_t off)
+/*!
+ * Test a lock
+ *
+ * (1) Test against our own locks array
+ * (2) Test fcntl lock, locks from other processes
+ *
+ * @param adf     (r) handle
+ * @param off     (r) offset
+ * @param len     (r) lenght
+ *
+ * @returns           1 if there's an existing lock, 0 if there's no lock,
+ *                    -1 in case any error occured
+ */
+static int testlock(const struct ad_fd *adf, off_t off, off_t len)
 {
-    off_t start = off;
-       if (off == AD_FILELOCK_OPEN_WR)
-               start = LOCK_RSRC_WR;
-       else if (off == AD_FILELOCK_OPEN_RD)
-               start = LOCK_RSRC_RD;
-    else if (off == AD_FILELOCK_DENY_RD)
-               start = LOCK_RSRC_DRD;
-       else if (off == AD_FILELOCK_DENY_WR)
-               start = LOCK_RSRC_DWR;
-       else if (off == AD_FILELOCK_OPEN_NONE)
-               start = LOCK_RSRC_NONE;
-       return start;
+    struct flock lock;
+    adf_lock_t *plock;
+    int i;
+
+    lock.l_start = off;
+
+    plock = adf->adf_lock;
+    lock.l_whence = SEEK_SET;
+    lock.l_len = len;
+
+    /* (1) Do we have a lock ? */
+    for (i = 0; i < adf->adf_lockcount; i++) {
+        if (OVERLAP(lock.l_start, 1, plock[i].lock.l_start, plock[i].lock.l_len)) 
+            return 1;
+    }
+
+    /* (2) Does another process have a lock? */
+    lock.l_type = (adf->adf_flags & O_RDWR) ? F_WRLCK : F_RDLCK;
+
+    if (set_lock(adf->adf_fd, F_GETLK, &lock) < 0) {
+        /* is that kind of error possible ?*/
+        return (errno == EACCES || errno == EAGAIN) ? 1 : -1;
+    }
+  
+    if (lock.l_type == F_UNLCK) {
+        return 0;
+    }
+    return 1;
 }
 
-/* ------------------ */
-int ad_fcntl_lock(struct adouble *ad, const u_int32_t eid, const int locktype,
-                 const off_t off, const off_t len, const int fork)
+#define LTYPE2STRBUFSIZ 128
+static const char *locktypetostr(int type)
 {
-  struct flock lock;
-  struct ad_fd *adf;
-  adf_lock_t *adflock;
-  int oldlock;
-  int i;
-  int type;  
-
-  lock.l_start = off;
-  type = locktype;
-  if (eid == ADEID_DFORK) {
-    adf = &ad->ad_data_fork;
-    if ((type & ADLOCK_FILELOCK)) {
-        if (ad_meta_fileno(ad) != -1) { /* META */
-            adf = ad->ad_md;
-            lock.l_start = df2off(off);
-        }
+    int first = 1;
+    static char buf[LTYPE2STRBUFSIZ];
+
+    buf[0] = 0;
+
+    if (type == 0) {
+        strlcat(buf, "CLR", LTYPE2STRBUFSIZ);
+        first = 0;
+        return buf;
     }
-  } else { /* rfork */
-    if (ad_meta_fileno(ad) == -1 || ad_reso_fileno(ad) == -1) {
-        /* there's no meta data. return a lock error 
-         * otherwise if a second process is able to create it
-         * locks are a mess.
-         */
-        errno = EACCES;
-        return -1;
+    if (type & ADLOCK_RD) {
+        if (!first)
+            strlcat(buf, "|", LTYPE2STRBUFSIZ);
+        strlcat(buf, "RD", LTYPE2STRBUFSIZ);
+        first = 0;
     }
-    if (type & ADLOCK_FILELOCK) {
-      adf = ad->ad_md;                 /* either resource or meta data (set in ad_open) */
-      lock.l_start = hf2off(off);
+    if (type & ADLOCK_WR) {
+        if (!first)
+            strlcat(buf, "|", LTYPE2STRBUFSIZ);
+        strlcat(buf, "WR", LTYPE2STRBUFSIZ);
+        first = 0;
     }
-    else {
-      /* we really want the resource fork it's a byte lock */
-      adf = &ad->ad_resource_fork;
-      lock.l_start += ad_getentryoff(ad, eid);
+    if (type & ADLOCK_UPGRADE) {
+        if (!first)
+            strlcat(buf, "|", LTYPE2STRBUFSIZ);
+        strlcat(buf, "UPG", LTYPE2STRBUFSIZ);
+        first = 0;
+    }
+    if (type & ADLOCK_FILELOCK) {
+        if (!first)
+            strlcat(buf, "|", LTYPE2STRBUFSIZ);
+        strlcat(buf, "FILELOCK", LTYPE2STRBUFSIZ);
+        first = 0;
     }
-  }
-  /* NOTE: we can't write lock a read-only file. on those, we just
-    * make sure that we have a read lock set. that way, we at least prevent
-    * someone else from really setting a deny read/write on the file. 
-    */
-  if (!(adf->adf_flags & O_RDWR) && (type & ADLOCK_WR)) {
-      type = (type & ~ADLOCK_WR) | ADLOCK_RD;
-  }
-  
-  lock.l_type = XLATE_FCNTL_LOCK(type & ADLOCK_MASK);
-  lock.l_whence = SEEK_SET;
-  lock.l_len = len;
 
-  /* byte_lock(len=-1) lock whole file */
-  if (len == BYTELOCK_MAX) {
-      lock.l_len -= lock.l_start; /* otherwise  EOVERFLOW error */
-  }
+    return buf;
+}
 
-  /* see if it's locked by another fork. 
-   * NOTE: this guarantees that any existing locks must be at most
-   * read locks. we use ADLOCK_WR/RD because F_RD/WRLCK aren't
-   * guaranteed to be ORable. */
-  if (adf_findxlock(adf, fork, ADLOCK_WR | 
-                   ((type & ADLOCK_WR) ? ADLOCK_RD : 0), 
-                   lock.l_start, lock.l_len) > -1) {
-    errno = EACCES;
-    return -1;
-  }
-  
-  /* look for any existing lock that we may have */
-  i = adf_findlock(adf, fork, ADLOCK_RD | ADLOCK_WR, lock.l_start, lock.l_len);
-  adflock = (i < 0) ? NULL : adf->adf_lock + i;
-
-  /* here's what we check for:
-     1) we're trying to re-lock a lock, but we didn't specify an update.
-     2) we're trying to free only part of a lock. 
-     3) we're trying to free a non-existent lock. */
-  if ( (!adflock && (lock.l_type == F_UNLCK))
-       ||
-       (adflock
-        && !(type & ADLOCK_UPGRADE)
-        && ((lock.l_type != F_UNLCK)
-            || (adflock->lock.l_start != lock.l_start)
-            || (adflock->lock.l_len != lock.l_len) ))
-      ) {
-      errno = EINVAL;
-      return -1;
-  }
+/******************************************************************************
+ * Public functions
+ ******************************************************************************/
 
+int ad_lock(struct adouble *ad, uint32_t eid, int locktype, off_t off, off_t len, int fork)
+{
+    struct flock lock;
+    struct ad_fd *adf;
+    adf_lock_t *adflock;
+    int oldlock;
+    int i;
+    int type;  
+    int ret = 0, fcntl_lock_err = 0;
+
+    LOG(log_debug, logtype_default, "ad_lock(%s, %s, off: %jd (%s), len: %jd): BEGIN",
+        eid == ADEID_DFORK ? "data" : "reso",
+        locktypetostr(locktype),
+        (intmax_t)off,
+        shmdstrfromoff(off),
+        (intmax_t)len);
+
+    if ((locktype & ADLOCK_FILELOCK) && (len != 1))
+        AFP_PANIC("lock API error");
+
+    type = locktype;
+
+    if (eid == ADEID_DFORK) {
+        adf = &ad->ad_data_fork;
+        lock.l_start = off;
+    } else { /* rfork */
+        if (type & ADLOCK_FILELOCK) {
+            adf = &ad->ad_data_fork;
+            lock.l_start = rf2off(off);
+        } else {
+            adf = ad->ad_rfp;
+            lock.l_start = off + ad_getentryoff(ad, ADEID_RFORK);
+        }
+    }
 
-  /* now, update our list of locks */
-  /* clear the lock */
-  if (lock.l_type == F_UNLCK) { 
-    adf_freelock(adf, i);
-    return 0;
-  }
+    /* NOTE: we can't write lock a read-only file. on those, we just
+     * make sure that we have a read lock set. that way, we at least prevent
+     * someone else from really setting a deny read/write on the file. 
+     */
+    if (!(adf->adf_flags & O_RDWR) && (type & ADLOCK_WR)) {
+        type = (type & ~ADLOCK_WR) | ADLOCK_RD;
+    }
+  
+    lock.l_type = XLATE_FCNTL_LOCK(type & ADLOCK_MASK);
+    lock.l_whence = SEEK_SET;
+    lock.l_len = len;
 
-  /* attempt to lock the file. */
-  if (!adf->adf_excl && set_lock(adf->adf_fd, F_SETLK, &lock) < 0) 
-    return -1;
+    /* byte_lock(len=-1) lock whole file */
+    if (len == BYTELOCK_MAX) {
+        lock.l_len -= lock.l_start; /* otherwise  EOVERFLOW error */
+    }
 
-  /* we upgraded this lock. */
-  if (adflock && (type & ADLOCK_UPGRADE)) {
-    memcpy(&adflock->lock, &lock, sizeof(lock));
-    return 0;
-  } 
-
-  /* it wasn't an upgrade */
-  oldlock = -1;
-  if (lock.l_type == F_RDLCK) {
-    oldlock = adf_findxlock(adf, fork, ADLOCK_RD, lock.l_start, lock.l_len);
-  } 
-    
-  /* no more space. this will also happen if lockmax == lockcount == 0 */
-  if (adf->adf_lockmax == adf->adf_lockcount) { 
-    adf_lock_t *tmp = (adf_lock_t *) 
-           realloc(adf->adf_lock, sizeof(adf_lock_t)*
-                   (adf->adf_lockmax + ARRAY_BLOCK_SIZE));
-    if (!tmp)
-      goto fcntl_lock_err;
-    adf->adf_lock = tmp;
-    adf->adf_lockmax += ARRAY_BLOCK_SIZE;
-  } 
-  adflock = adf->adf_lock + adf->adf_lockcount;
-
-  /* fill in fields */
-  memcpy(&adflock->lock, &lock, sizeof(lock));
-  adflock->user = fork;
-  if (oldlock > -1) {
-    adflock->refcount = (adf->adf_lock + oldlock)->refcount;
-  } else if ((adflock->refcount = calloc(1, sizeof(int))) == NULL) {
-    goto fcntl_lock_err;
-  }
+    /* see if it's locked by another fork. 
+     * NOTE: this guarantees that any existing locks must be at most
+     * read locks. we use ADLOCK_WR/RD because F_RD/WRLCK aren't
+     * guaranteed to be ORable. */
+    if (adf_findxlock(adf, fork, ADLOCK_WR | 
+                      ((type & ADLOCK_WR) ? ADLOCK_RD : 0), 
+                      lock.l_start, lock.l_len) > -1) {
+        errno = EACCES;
+        ret = -1;
+        goto exit;
+    }
   
-  (*adflock->refcount)++;
-  adf->adf_lockcount++;
-  return 0;
-
-fcntl_lock_err:
-  lock.l_type = F_UNLCK;
-  if (!adf->adf_excl) set_lock(adf->adf_fd, F_SETLK, &lock);
-  return -1;
-}
+    /* look for any existing lock that we may have */
+    i = adf_findlock(adf, fork, ADLOCK_RD | ADLOCK_WR, lock.l_start, lock.l_len);
+    adflock = (i < 0) ? NULL : adf->adf_lock + i;
+
+    /* here's what we check for:
+       1) we're trying to re-lock a lock, but we didn't specify an update.
+       2) we're trying to free only part of a lock. 
+       3) we're trying to free a non-existent lock. */
+    if ( (!adflock && (lock.l_type == F_UNLCK))
+         ||
+         (adflock
+          && !(type & ADLOCK_UPGRADE)
+          && ((lock.l_type != F_UNLCK)
+              || (adflock->lock.l_start != lock.l_start)
+              || (adflock->lock.l_len != lock.l_len) ))
+        ) {
+        errno = EINVAL;
+        ret = -1;
+        goto exit;
+    }
 
-/* -------------------------
-   we are using lock as tristate variable
-   
-   we have a lock ==> 1
-   no             ==> 0
-   error          ==> -1
-      
-*/
-static int testlock(struct ad_fd *adf, off_t off, off_t len)
-{
-  struct flock lock;
-  adf_lock_t *plock;
-  int i;
 
-  lock.l_start = off;
+    /* now, update our list of locks */
+    /* clear the lock */
+    if (lock.l_type == F_UNLCK) { 
+        adf_freelock(adf, i);
+        goto exit;
+    }
 
-  plock = adf->adf_lock;
-  lock.l_whence = SEEK_SET;
-  lock.l_len = len;
+    /* attempt to lock the file. */
+    if (set_lock(adf->adf_fd, F_SETLK, &lock) < 0) {
+        ret = -1;
+        goto exit;
+    }
 
-  /* Do we have a lock? */
-  for (i = 0; i < adf->adf_lockcount; i++) {
-    if (OVERLAP(lock.l_start, 1, plock[i].lock.l_start, plock[i].lock.l_len)) 
-        return 1;   /* */
-  }
-  /* Does another process have a lock? 
-  */
-  lock.l_type = (adf->adf_flags & O_RDWR) ?F_WRLCK : F_RDLCK;
+    /* we upgraded this lock. */
+    if (adflock && (type & ADLOCK_UPGRADE)) {
+        memcpy(&adflock->lock, &lock, sizeof(lock));
+        goto exit;
+    } 
+
+    /* it wasn't an upgrade */
+    oldlock = -1;
+    if (lock.l_type == F_RDLCK) {
+        oldlock = adf_findxlock(adf, fork, ADLOCK_RD, lock.l_start, lock.l_len);
+    } 
+    
+    /* no more space. this will also happen if lockmax == lockcount == 0 */
+    if (adf->adf_lockmax == adf->adf_lockcount) { 
+        adf_lock_t *tmp = (adf_lock_t *) 
+            realloc(adf->adf_lock, sizeof(adf_lock_t)*
+                    (adf->adf_lockmax + ARRAY_BLOCK_SIZE));
+        if (!tmp) {
+            ret = fcntl_lock_err = -1;
+            goto exit;
+        }
+        adf->adf_lock = tmp;
+        adf->adf_lockmax += ARRAY_BLOCK_SIZE;
+    } 
+    adflock = adf->adf_lock + adf->adf_lockcount;
 
-  if (set_lock(adf->adf_fd, F_GETLK, &lock) < 0) {
-      /* is that kind of error possible ?*/
-      return (errno == EACCES || errno == EAGAIN)?1:-1;
-  }
+    /* fill in fields */
+    memcpy(&adflock->lock, &lock, sizeof(lock));
+    adflock->user = fork;
+    if (oldlock > -1) {
+        adflock->refcount = (adf->adf_lock + oldlock)->refcount;
+    } else if ((adflock->refcount = calloc(1, sizeof(int))) == NULL) {
+        ret = fcntl_lock_err = 1;
+        goto exit;
+    }
   
-  if (lock.l_type == F_UNLCK) {
-      return 0;
-  }
-  return 1;
+    (*adflock->refcount)++;
+    adf->adf_lockcount++;
+
+exit:
+    if (ret != 0) {
+        if (fcntl_lock_err != 0) {
+            lock.l_type = F_UNLCK;
+            set_lock(adf->adf_fd, F_SETLK, &lock);
+        }
+    }
+    LOG(log_debug, logtype_default, "ad_lock: END: %d", ret);
+    return ret;
 }
 
-/* --------------- */
-int ad_testlock(struct adouble *ad, int eid, const off_t off)
+int ad_tmplock(struct adouble *ad, uint32_t eid, int locktype, off_t off, off_t len, int fork)
 {
-  struct ad_fd *adf;
-  off_t      lock_offset;
-
-  lock_offset = off;
-  if (eid == ADEID_DFORK) {
-    adf = &ad->ad_data_fork;
-    if (ad_meta_fileno(ad) != -1) {
-       adf = ad->ad_md;
-       lock_offset = df2off(off);
-    }
-  } 
-  else { /* rfork */
-    if (ad_meta_fileno(ad) == -1) {
-        /* there's no resource fork. return no lock */
-        return 0;
+    struct flock lock;
+    struct ad_fd *adf;
+    int err;
+    int type;  
+
+    LOG(log_debug, logtype_default, "ad_tmplock(%s, %s, off: %jd (%s), len: %jd): BEGIN",
+        eid == ADEID_DFORK ? "data" : "reso",
+        locktypetostr(locktype),
+        (intmax_t)off,
+        shmdstrfromoff(off),
+        (intmax_t)len);
+
+    lock.l_start = off;
+    type = locktype;
+
+    if (eid == ADEID_DFORK) {
+        adf = &ad->ad_data_fork;
+    } else {
+        adf = &ad->ad_resource_fork;
+        if (adf->adf_fd == -1) {
+            /* there's no resource fork. return success */
+            err = 0;
+            goto exit;
+        }
+        /* if ADLOCK_FILELOCK we want a lock from offset 0
+         * it's used when deleting a file:
+         * in open we put read locks on meta datas
+         * in delete a write locks on the whole file
+         * so if the file is open by somebody else it fails
+         */
+        if (!(type & ADLOCK_FILELOCK))
+            lock.l_start += ad_getentryoff(ad, eid);
     }
-    adf = ad->ad_md;
-    lock_offset = hf2off(off);
-  }
-  return testlock(adf, lock_offset, 1);
+
+    if (!(adf->adf_flags & O_RDWR) && (type & ADLOCK_WR)) {
+        type = (type & ~ADLOCK_WR) | ADLOCK_RD;
+    }
+  
+    lock.l_type = XLATE_FCNTL_LOCK(type & ADLOCK_MASK);
+    lock.l_whence = SEEK_SET;
+    lock.l_len = len;
+
+    /* see if it's locked by another fork. */
+    if (fork && adf_findxlock(adf, fork,
+                              ADLOCK_WR | ((type & ADLOCK_WR) ? ADLOCK_RD : 0), 
+                              lock.l_start, lock.l_len) > -1) {
+        errno = EACCES;
+        err = -1;
+        goto exit;
+    }
+
+    /* okay, we might have ranges byte-locked. we need to make sure that
+     * we restore the appropriate ranges once we're done. so, we check
+     * for overlap on an unlock and relock. 
+     * XXX: in the future, all the byte locks will be sorted and contiguous.
+     *      we just want to upgrade all the locks and then downgrade them
+     *      here. */
+    err = set_lock(adf->adf_fd, F_SETLK, &lock);
+    if (!err && (lock.l_type == F_UNLCK))
+        adf_relockrange(adf, adf->adf_fd, lock.l_start, len);
+
+exit:
+    LOG(log_debug, logtype_default, "ad_tmplock: END: %d", err);
+    return err;
 }
 
-/* -------------------------
-   return if a file is open by another process.
-   Optimized for the common case:
-   - there's no locks held by another process (clients)
-   - or we already know the answer and don't need to test.
-*/
-u_int16_t ad_openforks(struct adouble *ad, u_int16_t attrbits)
+/* --------------------- */
+void ad_unlock(struct adouble *ad, const int fork, int unlckbrl)
 {
-  u_int16_t ret = 0;
-  struct ad_fd *adf;
-  off_t off;
-
-  if (!(attrbits & (ATTRBIT_DOPEN | ATTRBIT_ROPEN))) {
-      off_t len;
-      /* XXX know the locks layout: 
-         AD_FILELOCK_OPEN_WR is first 
-         and use it for merging requests
-      */
-      if (ad_meta_fileno(ad) != -1) {
-          /* there's a resource fork test the four bytes for
-           * data RW/RD and fork RW/RD locks in one request
-          */
-         adf = ad->ad_md;
-         off = LOCK_DATA_WR;
-         len = 4;
-      }
-      else {
-          /* no resource fork, only data RD/RW may exist */
-          adf = &ad->ad_data_fork;
-          off = AD_FILELOCK_OPEN_WR;
-          len = 2;
-      }
-      if (!testlock(adf, off, len))
-          return ret;
-  }
-  /* either there's a lock or we already know one 
-     fork is open
-  */
-  if (!(attrbits & ATTRBIT_DOPEN)) {
-      if (ad_meta_fileno(ad) != -1) {
-         adf = ad->ad_md;
-         off = LOCK_DATA_WR;
-      }
-      else {
-          adf = &ad->ad_data_fork;
-          off = AD_FILELOCK_OPEN_WR;
-      }
-      ret = testlock(adf, off, 2) > 0? ATTRBIT_DOPEN : 0;
-  }
+    LOG(log_debug, logtype_default, "ad_unlock(unlckbrl: %d): BEGIN", unlckbrl);
 
-  if (!(attrbits & ATTRBIT_ROPEN)) {
-      if (ad_meta_fileno(ad) != -1) {
-         adf = ad->ad_md;
-          off = LOCK_RSRC_WR;
-          ret |= testlock(adf, off, 2) > 0? ATTRBIT_ROPEN : 0;
-      }
-  }
+    if (ad_data_fileno(ad) != -1) {
+        adf_unlock(ad, &ad->ad_data_fork, fork, unlckbrl);
+    }
+    if (ad_reso_fileno(ad) != -1) {
+        adf_unlock(ad, &ad->ad_resource_fork, fork, unlckbrl);
+    }
 
-  return ret;
+    LOG(log_debug, logtype_default, "ad_unlock: END");
 }
 
-/* -------------------------
-*/
-int ad_fcntl_tmplock(struct adouble *ad, const u_int32_t eid, const int locktype,
-                    const off_t off, const off_t len, const int fork)
+/*!
+ * Test for a share mode lock
+ *
+ * @param ad      (rw) handle
+ * @param eid     (r)  datafork or ressource fork
+ * @param off     (r)  sharemode lock to test
+ *
+ * @returns           1 if there's an existing lock, 0 if there's no lock,
+ *                    -1 in case any error occured
+ */
+int ad_testlock(struct adouble *ad, int eid, const off_t off)
 {
-  struct flock lock;
-  struct ad_fd *adf;
-  int err;
-  int type;  
-
-  lock.l_start = off;
-  type = locktype;
-  if (eid == ADEID_DFORK) {
-    adf = &ad->ad_data_fork;
-  } else {
-    /* FIXME META */
-    adf = &ad->ad_resource_fork;
-    if (adf->adf_fd == -1) {
-        /* there's no resource fork. return success */
-        return 0;
+    int ret = 0;
+    off_t lock_offset;
+
+    LOG(log_debug, logtype_default, "ad_testlock(%s, off: %jd (%s): BEGIN",
+        eid == ADEID_DFORK ? "data" : "reso",
+        (intmax_t)off,
+        shmdstrfromoff(off));
+
+    if (eid == ADEID_DFORK) {
+        lock_offset = off;
+    } else { /* rfork */
+        lock_offset = rf2off(off);
     }
-    /* if ADLOCK_FILELOCK we want a lock from offset 0
-     * it's used when deleting a file:
-     * in open we put read locks on meta datas
-     * in delete a write locks on the whole file
-     * so if the file is open by somebody else it fails
-    */
-    if (!(type & ADLOCK_FILELOCK))
-        lock.l_start += ad_getentryoff(ad, eid);
-  }
-
-  if (!(adf->adf_flags & O_RDWR) && (type & ADLOCK_WR)) {
-      type = (type & ~ADLOCK_WR) | ADLOCK_RD;
-  }
-  
-  lock.l_type = XLATE_FCNTL_LOCK(type & ADLOCK_MASK);
-  lock.l_whence = SEEK_SET;
-  lock.l_len = len;
-
-  /* see if it's locked by another fork. */
-  if (fork && adf_findxlock(adf, fork, ADLOCK_WR | 
-                   ((type & ADLOCK_WR) ? ADLOCK_RD : 0), 
-                   lock.l_start, lock.l_len) > -1) {
-    errno = EACCES;
-    return -1;
-  }
 
-  /* okay, we might have ranges byte-locked. we need to make sure that
-   * we restore the appropriate ranges once we're done. so, we check
-   * for overlap on an unlock and relock. 
-   * XXX: in the future, all the byte locks will be sorted and contiguous.
-   *      we just want to upgrade all the locks and then downgrade them
-   *      here. */
-  if (!adf->adf_excl) {
-       err = set_lock(adf->adf_fd, F_SETLK, &lock);
-  }
-  else {
-      err = 0;
-  }
-  if (!err && (lock.l_type == F_UNLCK))
-    adf_relockrange(adf, adf->adf_fd, lock.l_start, len);
+    ret = testlock(&ad->ad_data_fork, lock_offset, 1);
 
-  return err;
+    LOG(log_debug, logtype_default, "ad_testlock: END: %d", ret);
+    return ret;
 }
 
-/* -------------------------
-   the fork is opened in Read Write, Deny Read, Deny Write mode
-   lock the whole file once   
-*/
-int ad_excl_lock(struct adouble *ad, const u_int32_t eid)
+/*!
+ * Return if a file is open by another process.
+ *
+ * Optimized for the common case:
+ * - there's no locks held by another process (clients)
+ * - or we already know the answer and don't need to test (attrbits)
+ *
+ * @param ad          (rw) handle
+ * @param attrbits    (r)  forks opened by us
+ * @returns                bitflags ATTRBIT_DOPEN | ATTRBIT_ROPEN if
+ *                         other process has fork of file opened 
+ */
+uint16_t ad_openforks(struct adouble *ad, uint16_t attrbits)
 {
-  struct ad_fd *adf;
-  struct flock lock;
-  int    err;
-  
-  lock.l_start = 0;
-  lock.l_type = F_WRLCK;
-  lock.l_whence = SEEK_SET;
-  lock.l_len = 0;
-
-  if (eid == ADEID_DFORK) {
-    adf = &ad->ad_data_fork;
-  } else {
-    adf = &ad->ad_resource_fork;
-    lock.l_start = ad_getentryoff(ad, eid);
-  }
-  
-  err = set_lock(adf->adf_fd, F_SETLK, &lock);
-  if (!err)
-      adf->adf_excl = 1;
-  return err;
-}
+    uint16_t ret = 0;
+    struct ad_fd *adf;
+    off_t off;
+    off_t len;
 
-/* --------------------- */
-void ad_fcntl_unlock(struct adouble *ad, const int fork)
-{
-  if (ad_data_fileno(ad) != -1) {
-    adf_unlock(&ad->ad_data_fork, fork);
-  }
-  if (ad_reso_fileno(ad) != -1) {
-    adf_unlock(&ad->ad_resource_fork, fork);
-  }
+    if (ad_data_fileno(ad) == -1)
+        return 0;
 
-  if (ad->ad_flags != AD_VERSION1_SFM) {
-    return;
-  }
-  if (ad_meta_fileno(ad) != -1) {
-    adf_unlock(&ad->ad_metadata_fork, fork);
-  }
+    if (!(attrbits & (ATTRBIT_DOPEN | ATTRBIT_ROPEN))) {
+        /* Test all 4 locks at once */
+        off = AD_FILELOCK_OPEN_WR;
+        len = 4;
+        if (testlock(&ad->ad_data_fork, off, len) == 0)
+            return 0;
+    }
+
+    /* either there's a lock or we already know one fork is open */
+
+    if (!(attrbits & ATTRBIT_DOPEN)) {
+        off = AD_FILELOCK_OPEN_WR;
+        ret = testlock(&ad->ad_data_fork, off, 2) > 0 ? ATTRBIT_DOPEN : 0;
+    }
+
+    if (!(attrbits & ATTRBIT_ROPEN)) {
+        off = AD_FILELOCK_RSRC_OPEN_WR;
+        ret |= testlock(&ad->ad_data_fork, off, 2) > 0? ATTRBIT_ROPEN : 0;
+    }
 
+    return ret;
 }
diff --git a/libatalk/adouble/ad_lock.h b/libatalk/adouble/ad_lock.h
new file mode 100644 (file)
index 0000000..2d15da9
--- /dev/null
@@ -0,0 +1,29 @@
+#ifndef LIBATALK_ADOUBLE_AD_PRIVATE_H
+#define LIBATALK_ADOUBLE_AD_PRIVATE_H 1
+
+#include <atalk/adouble.h>
+
+/* this is so that we can keep lists of fds referencing the same file
+ * around. that way, we can honor locks created by the same process
+ * with the same file. */
+
+#define adf_lock_init(a) do {   \
+        (a)->adf_lockmax = 0;   \
+        (a)->adf_lockcount = 0; \
+        (a)->adf_lock = NULL;   \
+    } while (0)
+
+#define adf_lock_free(a) do {                                 \
+        int i;                                                \
+        if (!(a)->adf_lock)                                   \
+            break;                                            \
+        for (i = 0; i < (a)->adf_lockcount; i++) {            \
+            adf_lock_t *lock = (a)->adf_lock + i;             \
+            if (--(*lock->refcount) < 1)                      \
+                free(lock->refcount);                         \
+        }                                                     \
+        free((a)->adf_lock);                                  \
+        adf_lock_init(a);                                     \
+    } while (0)
+
+#endif /* libatalk/adouble/ad_private.h */
index 2cb5c05937f2f6d69470996bea5994eaaf069e2b..a93ab5a502dfa64a7f826160457b4fa61d93b304 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: ad_mmap.c,v 1.6 2008-12-03 18:35:44 didg Exp $
- *
  * ad_mmap provides interfaces to memory mapped files. as this is the
  * case, we don't have to deal w/ temporary buffers such as
  * ad_data. the ad_mmap routines are designed to not interact w/ the
@@ -17,7 +15,7 @@
 #include <atalk/adouble.h>
 #include <string.h>
 
-#include "ad_private.h"
+#include "ad_lock.h"
 
 static void *ad_mmap(const size_t length, const int prot,
                                const int flags, const int fd, 
index 7adb4abda262c7261a8197463d36f9369a2a7426..c02121ac0d1be8271e6c406418e9e4f9e8525cdc 100644 (file)
@@ -1,6 +1,8 @@
 /*
  * Copyright (c) 1999 Adrian Sun (asun@u.washington.edu)
  * Copyright (c) 1990,1991 Regents of The University of Michigan.
+ * Copyright (c) 2010 Frank Lahm
+ *
  * All Rights Reserved.
  *
  * Permission to use, copy, modify, and distribute this software and
@@ -26,8 +28,6 @@
 /*!
  * @file
  * Part of Netatalk's AppleDouble implementatation
- * @note We don't use inlines because a good compiler should be
- *       able to optimize all the static funcs below.
  * @sa include/atalk/adouble.h
  */
 
 #endif /* HAVE_CONFIG_H */
 
 #include <errno.h>
-
-#include <atalk/adouble.h>
 #include <sys/param.h>
-#include <atalk/logger.h>
-
-#include <atalk/util.h>
-#include <string.h>
-
-#include "ad_private.h"
 #include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <arpa/inet.h>
 
-#ifndef MAX
-#define MAX(a, b)  ((a) < (b) ? (b) : (a))
-#endif /* ! MAX */
+#include <atalk/logger.h>
+#include <atalk/adouble.h>
+#include <atalk/util.h>
+#include <atalk/unix.h>
+#include <atalk/ea.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
+#include <atalk/compat.h>
+#include <atalk/errchk.h>
+#include <atalk/volume.h>
 
-/*
- * AppleDouble entry default offsets.
- * The layout looks like this:
- *
- * this is the v1 layout:
- *     255         200         16          32          N
- *  |  NAME |    COMMENT    | FILEI |    FINDERI    | RFORK |
- *
- * we need to change it to look like this:
- *
- * v2 layout:
- * field       length (in bytes)
- * NAME        255
- * COMMENT     200
- * FILEDATESI  16     replaces FILEI
- * FINDERI     32
- * DID          4     new
- * AFPFILEI     4     new
- * SHORTNAME   12     8.3 new
- * RFORK        N
- *
- * so, all we need to do is replace FILEI with FILEDATESI, move RFORK,
- * and add in the new fields.
- *
- * NOTE: the HFS module will need similar modifications to interact with
- * afpd correctly.
- */
+#include "ad_lock.h"
 
 #define ADEDOFF_MAGIC        (0)
 #define ADEDOFF_VERSION      (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
 /* initial lengths of some of the fields */
 #define ADEDLEN_INIT     0
 
-/* make sure we don't redefine ADEDOFF_FILEI */
-#ifdef ADEDOFF_FILEI
-#undef ADEDOFF_FILEI
-#endif /* ADEDOFF_FILEI */
-
-#define ADEDOFF_NAME_V1      (AD_HEADER_LEN + ADEID_NUM_V1*AD_ENTRY_LEN)
-#define ADEDOFF_COMMENT_V1   (ADEDOFF_NAME_V1 + ADEDLEN_NAME)
-#define ADEDOFF_FILEI        (ADEDOFF_COMMENT_V1 + ADEDLEN_COMMENT)
-#define ADEDOFF_FINDERI_V1   (ADEDOFF_FILEI + ADEDLEN_FILEI)
-#define ADEDOFF_RFORK_V1     (ADEDOFF_FINDERI_V1 + ADEDLEN_FINDERI)
-
 /* i stick things in a slightly different order than their eid order in
  * case i ever want to separate RootInfo behaviour from the rest of the
  * stuff. */
+
+/* ad:v2 */
 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
-#define ADEDOFF_DID      (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
+#define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
 #define ADEDOFF_PRIVINO      (ADEDOFF_PRIVDEV + ADEDLEN_PRIVDEV)
 #define ADEDOFF_PRIVSYN      (ADEDOFF_PRIVINO + ADEDLEN_PRIVINO)
 #define ADEDOFF_PRIVID       (ADEDOFF_PRIVSYN + ADEDLEN_PRIVSYN)
-
 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRIVID + ADEDLEN_PRIVID)
 
-#define ADEID_NUM_OSX        2
-#define ADEDOFF_FINDERI_OSX  (AD_HEADER_LEN + ADEID_NUM_OSX*AD_ENTRY_LEN)
-#define ADEDOFF_RFORK_OSX    (ADEDOFF_FINDERI_OSX + ADEDLEN_FINDERI)
-
-/* we keep local copies of a bunch of stuff so that we can initialize things
- * correctly. */
+/* ad:ea */
+#define ADEDOFF_FINDERI_EA    (AD_HEADER_LEN + ADEID_NUM_EA * AD_ENTRY_LEN)
+#define ADEDOFF_COMMENT_EA    (ADEDOFF_FINDERI_EA    + ADEDLEN_FINDERI)
+#define ADEDOFF_FILEDATESI_EA (ADEDOFF_COMMENT_EA    + ADEDLEN_COMMENT)
+#define ADEDOFF_AFPFILEI_EA   (ADEDOFF_FILEDATESI_EA + ADEDLEN_FILEDATESI)
+#define ADEDOFF_PRIVDEV_EA    (ADEDOFF_AFPFILEI_EA   + ADEDLEN_AFPFILEI)
+#define ADEDOFF_PRIVINO_EA    (ADEDOFF_PRIVDEV_EA    + ADEDLEN_PRIVDEV)
+#define ADEDOFF_PRIVSYN_EA    (ADEDOFF_PRIVINO_EA    + ADEDLEN_PRIVINO)
+#define ADEDOFF_PRIVID_EA     (ADEDOFF_PRIVSYN_EA    + ADEDLEN_PRIVSYN)
 
 /* this is to prevent changing timezones from causing problems with
-   localtime volumes. the screw-up is 30 years. we use a delta of 5
-   years.  */
+   localtime volumes. the screw-up is 30 years. we use a delta of 5 years */
 #define TIMEWARP_DELTA 157680000
 
-
 struct entry {
-    u_int32_t id, offset, len;
+    uint32_t id, offset, len;
 };
 
-static const struct entry entry_order1[ADEID_NUM_V1 +1] = {
-    {ADEID_NAME,    ADEDOFF_NAME_V1,    ADEDLEN_INIT},      /* 3 */
-    {ADEID_COMMENT, ADEDOFF_COMMENT_V1, ADEDLEN_INIT},      /* 4 */
-    {ADEID_FILEI,   ADEDOFF_FILEI,      ADEDLEN_FILEI},     /* 7 */
-    {ADEID_FINDERI, ADEDOFF_FINDERI_V1, ADEDLEN_FINDERI},   /* 9 */
-    {ADEID_RFORK,   ADEDOFF_RFORK_V1,   ADEDLEN_INIT},      /* 2 */
-    {0, 0, 0}
-};
+/* --------------------------- */
+static uid_t default_uid = -1;
 
-#if AD_VERSION == AD_VERSION1
-#define DISK_EID(ad, a) (a)
+/* Forward declarations */
+static int ad_mkrf(const char *path);
+static int ad_header_read(const char *path, struct adouble *ad, const struct stat *hst);
+static int ad_header_upgrade(struct adouble *ad, const char *name);
 
-#else /* AD_VERSION == AD_VERSION2 */
+static int ad_mkrf_ea(const char *path);
+static int ad_header_read_ea(const char *path, struct adouble *ad, const struct stat *hst);
+static int ad_header_upgrade_ea(struct adouble *ad, const char *name);
+static int ad_reso_size(const char *path, int adflags, struct adouble *ad);
+static int ad_mkrf_osx(const char *path);
 
-static u_int32_t get_eid(struct adouble *ad, u_int32_t eid)
-{
-    if (eid <= 15)
-        return eid;
-    if (ad->ad_version == AD_VERSION1)
-        return 0;
-    if (eid == AD_DEV)
-        return ADEID_PRIVDEV;
-    if (eid == AD_INO)
-        return ADEID_PRIVINO;
-    if (eid == AD_SYN)
-        return ADEID_PRIVSYN;
-    if (eid == AD_ID)
-        return ADEID_PRIVID;
 
-    return 0;
-}
+static struct adouble_fops ad_adouble = {
+    &ad_path,
+    &ad_mkrf,
+    &ad_rebuild_adouble_header_v2,
+    &ad_header_read,
+    &ad_header_upgrade,
+};
 
-#define DISK_EID(ad, a) get_eid(ad, a)
+static struct adouble_fops ad_adouble_ea = {
+#ifdef HAVE_EAFD
+    &ad_path_ea,
+    &ad_mkrf_ea,
+#else
+    &ad_path_osx,
+    &ad_mkrf_osx,
+#endif
+    &ad_rebuild_adouble_header_ea,
+    &ad_header_read_ea,
+    &ad_header_upgrade_ea,
+};
 
-static const struct entry entry_order2[ADEID_NUM_V2 +1] = {
-    {ADEID_NAME, ADEDOFF_NAME_V2, ADEDLEN_INIT},
-    {ADEID_COMMENT, ADEDOFF_COMMENT_V2, ADEDLEN_INIT},
-    {ADEID_FILEDATESI, ADEDOFF_FILEDATESI, ADEDLEN_FILEDATESI},
-    {ADEID_FINDERI, ADEDOFF_FINDERI_V2, ADEDLEN_FINDERI},
-    {ADEID_DID, ADEDOFF_DID, ADEDLEN_DID},
-    {ADEID_AFPFILEI, ADEDOFF_AFPFILEI, ADEDLEN_AFPFILEI},
-    {ADEID_SHORTNAME, ADEDOFF_SHORTNAME, ADEDLEN_INIT},
+static const struct entry entry_order2[ADEID_NUM_V2 + 1] = {
+    {ADEID_NAME,        ADEDOFF_NAME_V2,     ADEDLEN_INIT},
+    {ADEID_COMMENT,     ADEDOFF_COMMENT_V2,  ADEDLEN_INIT},
+    {ADEID_FILEDATESI,  ADEDOFF_FILEDATESI,  ADEDLEN_FILEDATESI},
+    {ADEID_FINDERI,     ADEDOFF_FINDERI_V2,  ADEDLEN_FINDERI},
+    {ADEID_DID,         ADEDOFF_DID,         ADEDLEN_DID},
+    {ADEID_AFPFILEI,    ADEDOFF_AFPFILEI,    ADEDLEN_AFPFILEI},
+    {ADEID_SHORTNAME,   ADEDOFF_SHORTNAME,   ADEDLEN_INIT},
     {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
-    {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV, ADEDLEN_INIT},
-    {ADEID_PRIVINO,     ADEDOFF_PRIVINO, ADEDLEN_INIT},
-    {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN, ADEDLEN_INIT},
-    {ADEID_PRIVID,     ADEDOFF_PRIVID, ADEDLEN_INIT},
-    {ADEID_RFORK, ADEDOFF_RFORK_V2, ADEDLEN_INIT},
+    {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV,     ADEDLEN_INIT},
+    {ADEID_PRIVINO,     ADEDOFF_PRIVINO,     ADEDLEN_INIT},
+    {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN,     ADEDLEN_INIT},
+    {ADEID_PRIVID,      ADEDOFF_PRIVID,      ADEDLEN_INIT},
+    {ADEID_RFORK,       ADEDOFF_RFORK_V2,    ADEDLEN_INIT},
+    {0, 0, 0}
+};
 
+/* Using Extended Attributes */
+static const struct entry entry_order_ea[ADEID_NUM_EA + 1] = {
+    {ADEID_FINDERI,    ADEDOFF_FINDERI_EA,    ADEDLEN_FINDERI},
+    {ADEID_COMMENT,    ADEDOFF_COMMENT_EA,    ADEDLEN_INIT},
+    {ADEID_FILEDATESI, ADEDOFF_FILEDATESI_EA, ADEDLEN_FILEDATESI},
+    {ADEID_AFPFILEI,   ADEDOFF_AFPFILEI_EA,   ADEDLEN_AFPFILEI},
+    {ADEID_PRIVDEV,    ADEDOFF_PRIVDEV_EA,    ADEDLEN_INIT},
+    {ADEID_PRIVINO,    ADEDOFF_PRIVINO_EA,    ADEDLEN_INIT},
+    {ADEID_PRIVSYN,    ADEDOFF_PRIVSYN_EA,    ADEDLEN_INIT},
+    {ADEID_PRIVID,     ADEDOFF_PRIVID_EA,     ADEDLEN_INIT},
     {0, 0, 0}
 };
 
-/* OS X adouble finder info and resource fork only
- */
+/* fallback for EAs */
 static const struct entry entry_order_osx[ADEID_NUM_OSX +1] = {
     {ADEID_FINDERI, ADEDOFF_FINDERI_OSX, ADEDLEN_FINDERI},
     {ADEID_RFORK, ADEDOFF_RFORK_OSX, ADEDLEN_INIT},
-
     {0, 0, 0}
 };
 
-#define ADEID_NUM_SFM 3
-static const struct entry entry_order_sfm[ADEID_NUM_SFM +1] = {
-    {ADEID_FINDERI,     16,         ADEDLEN_FINDERI},   /* 9 */
-    {ADEID_SFMRESERVE2, 16+32,      6},                 /* 21 */
-    {ADEID_FILEI,       60,         ADEDLEN_FILEI},     /* 7 */
-
-    {0, 0, 0}
-};
+#define ADFLAGS2LOGSTRBUFSIZ 128
+const char *adflags2logstr(int adflags)
+{
+    int first = 1;
+    static char buf[ADFLAGS2LOGSTRBUFSIZ];
+
+    buf[0] = 0;
+
+    if (adflags & ADFLAGS_DF) {
+        strlcat(buf, "DF", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_RF) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "RF", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_NORF) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "NORF", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_HF) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "HF", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_NOHF) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "NOHF", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_DIR) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "DIR", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_CHECK_OF) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "OF", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_SETSHRMD) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "SHRMD", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_RDWR) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_RDWR", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_RDONLY) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_RDONLY", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_CREATE) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_CREAT", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_EXCL) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_EXCL", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (adflags & ADFLAGS_TRUNC) {
+        if (!first)
+            strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_TRUNC", ADFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+
+    return buf;
+}
 
-#endif /* AD_VERSION == AD_VERSION2 */
+#define OPENFLAGS2LOGSTRBUFSIZ 128
+const char *openflags2logstr(int oflags)
+{
+    int first = 1;
+    static char buf[OPENFLAGS2LOGSTRBUFSIZ];
+
+    buf[0] = 0;
+
+    if ((oflags & O_RDONLY) || (oflags == O_RDONLY)) {
+        strlcat(buf, "O_RDONLY", OPENFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (oflags & O_RDWR) {
+        if (!first)
+            strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_RDWR", OPENFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (oflags & O_CREAT) {
+        if (!first)
+            strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_CREAT", OPENFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (oflags & O_TRUNC) {
+        if (!first)
+            strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_TRUNC", OPENFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    if (oflags & O_EXCL) {
+        if (!first)
+            strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
+        strlcat(buf, "O_EXCL", OPENFLAGS2LOGSTRBUFSIZ);
+        first = 0;
+    }
+    return buf;
+}    
+
+static uint32_t get_eid(uint32_t eid)
+{
+    if (eid <= 15)
+        return eid;
+    if (eid == AD_DEV)
+        return ADEID_PRIVDEV;
+    if (eid == AD_INO)
+        return ADEID_PRIVINO;
+    if (eid == AD_SYN)
+        return ADEID_PRIVSYN;
+    if (eid == AD_ID)
+        return ADEID_PRIVID;
 
-#if AD_VERSION == AD_VERSION2
+    return 0;
+}
 
-/* update a version 2 adouble resource fork with our private entries */
-static int ad_update(struct adouble *ad, const char *path)
+/* ----------------------------------- */
+static int new_ad_header(struct adouble *ad, const char *path, struct stat *stp, int adflags)
 {
-    struct stat st;
-    u_int16_t nentries = 0;
-    off_t     off, shiftdata=0;
     const struct entry  *eid;
-    static off_t entry_len[ADEID_MAX];
-    static char  databuf[ADEID_MAX][256], *buf;
-    int fd;
-    int ret = -1;
-
-    /* check to see if we should convert this header. */
-    if (!path || ad->ad_flags != AD_VERSION2)
-        return 0;
-
-    LOG(log_maxdebug, logtype_default, "ad_update: checking whether '%s' needs an upgrade.", path);
-
-    if (!(ad->ad_md->adf_flags & O_RDWR)) {
-        /* we were unable to open the file read write the last time */
-        return 0;
-    }
-
-    if (ad->ad_eid[ADEID_RFORK].ade_off) {
-        shiftdata = ADEDOFF_RFORK_V2 -ad->ad_eid[ADEID_RFORK].ade_off;
-    }
-
-    memcpy(&nentries, ad->ad_data + ADEDOFF_NENTRIES, sizeof( nentries ));
-    nentries = ntohs( nentries );
-
-    if ( shiftdata == 0 && nentries == ADEID_NUM_V2)
-        return 0;
-
-    memset(entry_len, 0, sizeof(entry_len));
-    memset(databuf, 0, sizeof(databuf));
-
-    /* bail if we can't get a lock */
-    if (ad_tmplock(ad, ADEID_RFORK, ADLOCK_WR, 0, 0, 0) < 0)
-        goto bail_err;
-
-    fd = ad->ad_md->adf_fd;
-
-    if (fstat(fd, &st)) {
-        goto bail_lock;
-    }
-
-    if (st.st_size > 0x7fffffff) {
-        LOG(log_debug, logtype_default, "ad_update: file '%s' too big for update.", path);
-        errno = EIO;
-        goto bail_lock;
-    }
-
-    off = ad->ad_eid[ADEID_RFORK].ade_off;
-    if (off > st.st_size) {
-        LOG(log_error, logtype_default, "ad_update: invalid resource fork offset. (off: %u)", off);
-        errno = EIO;
-        goto bail_lock;
-    }
-
-    if (ad->ad_eid[ADEID_RFORK].ade_len > st.st_size - off) {
-        LOG(log_error, logtype_default, "ad_update: invalid resource fork length. (rfork len: %u)", ad->ad_eid[ADEID_RFORK].ade_len);
-        errno = EIO;
-        goto bail_lock;
-    }
+    uint16_t            ashort;
+    struct stat         st;
 
-    if ((void *) (buf = (char *)
-                  mmap(NULL, st.st_size + shiftdata,
-                       PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) ==
-        MAP_FAILED) {
-        goto bail_lock;
-    }
+    LOG(log_debug, logtype_default, "new_ad_header(\"%s\")", path);
 
-    /* last place for failure. */
-    if (sys_ftruncate(fd, st.st_size + shiftdata) < 0) {
-        munmap(buf, st.st_size + shiftdata);
-        goto bail_lock;
+    if (stp == NULL) {
+        stp = &st;
+        if (lstat(path, &st) != 0)
+            return -1;
     }
 
-    /* move the RFORK. this assumes that the RFORK is at the end */
-    if (off) {
-        memmove(buf + ADEDOFF_RFORK_V2, buf + off, ad->ad_eid[ADEID_RFORK].ade_len);
+    ad->ad_magic = AD_MAGIC;
+    ad->ad_version = ad->ad_vers & 0x0f0000;
+    if (!ad->ad_version) {
+        ad->ad_version = AD_VERSION;
     }
 
-    munmap(buf, st.st_size + shiftdata);
-
-    /* now, fix up our copy of the header */
-    memset(ad->ad_filler, 0, sizeof(ad->ad_filler));
+    memset(ad->ad_data, 0, sizeof(ad->ad_data));
 
-    /* save the header entries */
-    eid = entry_order2;
-    while (eid->id) {
-        if( ad->ad_eid[eid->id].ade_off != 0) {
-            if ( eid->id > 2 && ad->ad_eid[eid->id].ade_len < 256)
-                memcpy( databuf[eid->id], ad->ad_data +ad->ad_eid[eid->id].ade_off, ad->ad_eid[eid->id].ade_len);
-            entry_len[eid->id] = ad->ad_eid[eid->id].ade_len;
-        }
-        eid++;
+    if (ad->ad_vers == AD_VERSION2)
+        eid = entry_order2;
+    else if (ad->ad_vers == AD_VERSION_EA)
+        eid = entry_order_ea;
+    else if (ad->ad_vers == AD_VERSION2_OSX)
+        eid = entry_order_osx;
+    else {
+        return -1;
     }
 
-    memset(ad->ad_data + AD_HEADER_LEN, 0, AD_DATASZ - AD_HEADER_LEN);
-
-    /* copy the saved entries to the new header */
-    eid = entry_order2;
     while (eid->id) {
-        if ( eid->id > 2 && entry_len[eid->id] > 0) {
-            memcpy(ad->ad_data+eid->offset, databuf[eid->id], entry_len[eid->id]);
-        }
         ad->ad_eid[eid->id].ade_off = eid->offset;
-        ad->ad_eid[eid->id].ade_len = entry_len[eid->id];
+        ad->ad_eid[eid->id].ade_len = eid->len;
         eid++;
     }
 
-    /* rebuild the header and cleanup */
-    LOG(log_debug, logtype_default, "updated AD2 header %s", path);
-    ad_flush(ad );
-    ret = 0;
-
-bail_lock:
-    ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
-bail_err:
-    return ret;
-}
-
-/* ------------------------------------------
-   FIXME work only if < 2GB
-*/
-static int ad_convert(struct adouble *ad, const char *path)
-{
-    struct stat st;
-    u_int16_t attr;
-    char *buf;
-    int fd, off;
-    int ret = -1;
-    /* use resource fork offset from file */
-    int shiftdata;
-    int toV2;
-    int toV1;
-
-    if (!path) {
-        return 0;
-    }
-
-    if (!(ad->ad_md->adf_flags & ( O_RDWR))) {
-        /* we were unable to open the file read write the last time */
-        return 0;
-    }
-
-    /* check to see if we should convert this header. */
-    toV2 = ad->ad_version == AD_VERSION1 && ad->ad_flags == AD_VERSION2;
-    toV1 = ad->ad_version == AD_VERSION2 && ad->ad_flags == AD_VERSION1;
-
-    if (!toV2 && !toV1)
-        return 0;
-
-    /* convert from v1 to v2. what does this mean?
-     *  1) change FILEI into FILEDATESI
-     *  2) create space for SHORTNAME, AFPFILEI, DID, and PRODOSI
-     *  3) move FILEI attributes into AFPFILEI
-     *  4) initialize ACCESS field of FILEDATESI.
-     *  5) move the resource fork
-     */
-
-    /* bail if we can't get a lock */
-    if (ad_tmplock(ad, ADEID_RFORK, ADLOCK_WR, 0, 0, 0) < 0)
-        goto bail_err;
-
-    /* we reuse fd from the resource fork */
-    fd = ad->ad_md->adf_fd;
-
-    if (ad->ad_eid[ADEID_RFORK].ade_off) {
-        shiftdata = ADEDOFF_RFORK_V2 -ad->ad_eid[ADEID_RFORK].ade_off;
-    }
-    else {
-        shiftdata = ADEDOFF_RFORK_V2 -ADEDOFF_RFORK_V1; /* 136 */
-    }
-
-    if (fstat(fd, &st)) {
-        goto bail_lock;
-    }
-
-    if (st.st_size > 0x7fffffff -shiftdata) {
-        LOG(log_debug, logtype_default, "ad_v1tov2: file too big.");
-        errno = EIO;
-        goto bail_lock;
-    }
+    /* put something sane in the directory finderinfo */
+    if (ad->ad_vers != AD_VERSION2_OSX) {
+        if ((adflags & ADFLAGS_DIR)) {
+            /* set default view */
+            ashort = htons(FINDERINFO_CLOSEDVIEW);
+            memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
+        } else {
+            /* set default creator/type fields */
+            memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
+            memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
+        }
 
-    off = ad->ad_eid[ADEID_RFORK].ade_off;
+        /* make things invisible */
+        if ((ad->ad_options & ADVOL_INVDOTS)
+            && (*path == '.')
+            && !((adflags & ADFLAGS_DIR) && (path[1] == 0))
+            ) {
+            ashort = htons(ATTRBIT_INVISIBLE);
+            ad_setattr(ad, ashort);
+            ashort = htons(FINDERINFO_INVISIBLE);
+            memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
+        }
 
-    if (off > st.st_size) {
-        LOG(log_error, logtype_default, "ad_v1tov2: invalid resource fork offset. (off: %u)", off);
-        errno = EIO;
-        goto bail_lock;
+        /* put something sane in the date fields */
+        ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, stp->st_mtime);
+        ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, stp->st_mtime);
+        ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, stp->st_mtime);
+        ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
     }
-
-    if (ad->ad_eid[ADEID_RFORK].ade_len > st.st_size - off) {
-        LOG(log_error, logtype_default, "ad_v1tov2: invalid resource fork length. (rfork len: %u)", ad->ad_eid[ADEID_RFORK].ade_len);
-        errno = EIO;
-        goto bail_lock;
-    }
-
-    if ((void *) (buf = (char *)
-                  mmap(NULL, st.st_size + shiftdata,
-                       PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) ==
-        MAP_FAILED) {
-        goto bail_lock;
-    }
-
-    /* last place for failure. */
-
-    if (sys_ftruncate(fd, st.st_size + shiftdata) < 0) {
-        goto bail_lock;
-    }
-
-    /* move the RFORK. this assumes that the RFORK is at the end */
-    if (off) {
-        memmove(buf + ADEDOFF_RFORK_V2, buf + off, ad->ad_eid[ADEID_RFORK].ade_len);
-    }
-
-    munmap(buf, st.st_size + shiftdata);
-
-    /* now, fix up our copy of the header */
-    memset(ad->ad_filler, 0, sizeof(ad->ad_filler));
-
-    /* replace FILEI with FILEDATESI */
-    ad_getattr(ad, &attr);
-    ad->ad_eid[ADEID_FILEDATESI].ade_off = ADEDOFF_FILEDATESI;
-    ad->ad_eid[ADEID_FILEDATESI].ade_len = ADEDLEN_FILEDATESI;
-    ad->ad_eid[ADEID_FILEI].ade_off = 0;
-    ad->ad_eid[ADEID_FILEI].ade_len = 0;
-
-    /* add in the new entries */
-    ad->ad_eid[ADEID_DID].ade_off = ADEDOFF_DID;
-    ad->ad_eid[ADEID_DID].ade_len = ADEDLEN_DID;
-    ad->ad_eid[ADEID_AFPFILEI].ade_off = ADEDOFF_AFPFILEI;
-    ad->ad_eid[ADEID_AFPFILEI].ade_len = ADEDLEN_AFPFILEI;
-    ad->ad_eid[ADEID_SHORTNAME].ade_off = ADEDOFF_SHORTNAME;
-    ad->ad_eid[ADEID_SHORTNAME].ade_len = ADEDLEN_INIT;
-    ad->ad_eid[ADEID_PRODOSFILEI].ade_off = ADEDOFF_PRODOSFILEI;
-    ad->ad_eid[ADEID_PRODOSFILEI].ade_len = ADEDLEN_PRODOSFILEI;
-
-    ad->ad_eid[ADEID_PRIVDEV].ade_off = ADEDOFF_PRIVDEV;
-    ad->ad_eid[ADEID_PRIVDEV].ade_len = ADEDLEN_INIT;
-    ad->ad_eid[ADEID_PRIVINO].ade_off = ADEDOFF_PRIVINO;
-    ad->ad_eid[ADEID_PRIVINO].ade_len = ADEDLEN_INIT;
-    ad->ad_eid[ADEID_PRIVSYN].ade_off = ADEDOFF_PRIVSYN;
-    ad->ad_eid[ADEID_PRIVSYN].ade_len = ADEDLEN_INIT;
-    ad->ad_eid[ADEID_PRIVID].ade_off  = ADEDOFF_PRIVID;
-    ad->ad_eid[ADEID_PRIVID].ade_len =  ADEDLEN_INIT;
-
-    /* shift the old entries (NAME, COMMENT, FINDERI, RFORK) */
-    ad->ad_eid[ADEID_NAME].ade_off = ADEDOFF_NAME_V2;
-    ad->ad_eid[ADEID_COMMENT].ade_off = ADEDOFF_COMMENT_V2;
-    ad->ad_eid[ADEID_FINDERI].ade_off = ADEDOFF_FINDERI_V2;
-    ad->ad_eid[ADEID_RFORK].ade_off = ADEDOFF_RFORK_V2;
-
-    /* switch to dest version */
-    ad->ad_version = (toV2)?AD_VERSION2:AD_VERSION1;
-
-    /* move our data buffer to make space for the new entries. */
-    memmove(ad->ad_data + ADEDOFF_NAME_V2, ad->ad_data + ADEDOFF_NAME_V1,
-            ADEDOFF_RFORK_V1 - ADEDOFF_NAME_V1);
-
-    /* now, fill in the space with appropriate stuff. we're
-       operating as a v2 file now. */
-    ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
-    memset(ad_entry(ad, ADEID_DID), 0, ADEDLEN_DID);
-    memset(ad_entry(ad, ADEID_AFPFILEI), 0, ADEDLEN_AFPFILEI);
-    ad_setattr(ad, attr);
-    memset(ad_entry(ad, ADEID_SHORTNAME), 0, ADEDLEN_SHORTNAME);
-    memset(ad_entry(ad, ADEID_PRODOSFILEI), 0, ADEDLEN_PRODOSFILEI);
-
-    /* rebuild the header and cleanup */
-    ad_flush(ad );
-    ret = 0;
-
-bail_lock:
-    ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
-bail_err:
-    return ret;
+    return 0;
 }
-#endif /* AD_VERSION == AD_VERSION2 */
 
 /* -------------------------------------
    read in the entries
 */
-static void parse_entries(struct adouble *ad, char *buf,
-                          u_int16_t nentries)
+static void parse_entries(struct adouble *ad, char *buf, uint16_t nentries)
 {
-    u_int32_t   eid, len, off;
-    int         warning = 0;
+    uint32_t   eid, len, off;
+    int        warning = 0;
 
     /* now, read in the entry bits */
     for (; nentries > 0; nentries-- ) {
         memcpy(&eid, buf, sizeof( eid ));
-        eid = DISK_EID(ad, ntohl( eid ));
+        eid = get_eid(ntohl(eid));
         buf += sizeof( eid );
         memcpy(&off, buf, sizeof( off ));
         off = ntohl( off );
@@ -510,19 +407,19 @@ static void parse_entries(struct adouble *ad, char *buf,
         len = ntohl( len );
         buf += sizeof( len );
 
-        if (eid && eid < ADEID_MAX && off < sizeof(ad->ad_data) &&
-            (off +len <= sizeof(ad->ad_data) || eid == ADEID_RFORK)) {
+        if (eid
+            && eid < ADEID_MAX
+            && off < sizeof(ad->ad_data)
+            && (off + len <= sizeof(ad->ad_data) || eid == ADEID_RFORK)) {
             ad->ad_eid[ eid ].ade_off = off;
             ad->ad_eid[ eid ].ade_len = len;
         } else if (!warning) {
             warning = 1;
-            LOG(log_debug, logtype_default, "ad_refresh: nentries %hd  eid %d",
-                nentries, eid );
+            LOG(log_warning, logtype_default, "parse_entries: bogus eid: %d", eid);
         }
     }
 }
 
-
 /* this reads enough of the header so that we can figure out all of
  * the entry lengths and offsets. once that's done, we just read/mmap
  * the rest of the header in.
@@ -530,17 +427,16 @@ static void parse_entries(struct adouble *ad, char *buf,
  * NOTE: we're assuming that the resource fork is kept at the end of
  *       the file. also, mmapping won't work for the hfs fs until it
  *       understands how to mmap header files. */
-static int ad_header_read(struct adouble *ad, struct stat *hst)
+static int ad_header_read(const char *path _U_, struct adouble *ad, const struct stat *hst)
 {
     char                *buf = ad->ad_data;
-    u_int16_t           nentries;
+    uint16_t            nentries;
     int                 len;
     ssize_t             header_len;
-    static int          warning = 0;
     struct stat         st;
 
     /* read the header */
-    if ((header_len = adf_pread( ad->ad_md, buf, sizeof(ad->ad_data), 0)) < 0) {
+    if ((header_len = adf_pread( ad->ad_mdp, buf, AD_DATASZ2, 0)) < 0) {
         return -1;
     }
     if (header_len < AD_HEADER_LEN) {
@@ -550,42 +446,15 @@ static int ad_header_read(struct adouble *ad, struct stat *hst)
 
     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
+    ad->ad_magic = ntohl( ad->ad_magic );
+    ad->ad_version = ntohl( ad->ad_version );
 
-    /* tag broken v1 headers. just assume they're all right.
-     * we detect two cases: null magic/version
-     *                      byte swapped magic/version
-     * XXX: in the future, you'll need the v1compat flag.
-     * (ad->ad_flags & ADFLAGS_V1COMPAT) */
-    if (!ad->ad_magic && !ad->ad_version) {
-        if (!warning) {
-            LOG(log_debug, logtype_default, "notice: fixing up null v1 magic/version.");
-            warning++;
-        }
-        ad->ad_magic = AD_MAGIC;
-        ad->ad_version = AD_VERSION1;
-
-    } else if (ad->ad_magic == AD_MAGIC && ad->ad_version == AD_VERSION1) {
-        if (!warning) {
-            LOG(log_debug, logtype_default, "notice: fixing up byte-swapped v1 magic/version.");
-            warning++;
-        }
-
-    } else {
-        ad->ad_magic = ntohl( ad->ad_magic );
-        ad->ad_version = ntohl( ad->ad_version );
-    }
-
-    if ((ad->ad_magic != AD_MAGIC) || ((ad->ad_version != AD_VERSION1)
-#if AD_VERSION == AD_VERSION2
-                                       && (ad->ad_version != AD_VERSION2)
-#endif /* AD_VERSION == AD_VERSION2 */
-            )) {
-        LOG(log_debug, logtype_default, "ad_open: can't parse AppleDouble header.");
+    if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
+        LOG(log_error, logtype_default, "ad_open: can't parse AppleDouble header.");
         errno = EIO;
         return -1;
     }
 
-    memcpy(ad->ad_filler, buf + ADEDOFF_FILLER, sizeof( ad->ad_filler ));
     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
     nentries = ntohs( nentries );
 
@@ -598,7 +467,7 @@ static int ad_header_read(struct adouble *ad, struct stat *hst)
 
     buf += AD_HEADER_LEN;
     if (len > header_len - AD_HEADER_LEN) {
-        LOG(log_debug, logtype_default, "ad_header_read: can't read entry info.");
+        LOG(log_error, logtype_default, "ad_header_read: can't read entry info.");
         errno = EIO;
         return -1;
     }
@@ -610,218 +479,871 @@ static int ad_header_read(struct adouble *ad, struct stat *hst)
     if (!ad_getentryoff(ad, ADEID_RFORK)
         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
         ) {
-        LOG(log_debug, logtype_default, "ad_header_read: problem with rfork entry offset.");
+        LOG(log_error, logtype_default, "ad_header_read: problem with rfork entry offset.");
         errno = EIO;
         return -1;
     }
 
     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
-        LOG(log_debug, logtype_default, "ad_header_read: can't read in entries.");
+        LOG(log_error, logtype_default, "ad_header_read: can't read in entries.");
         errno = EIO;
         return -1;
     }
 
     if (hst == NULL) {
         hst = &st;
-        if (fstat(ad->ad_md->adf_fd, &st) < 0) {
+        if (fstat(ad->ad_mdp->adf_fd, &st) < 0) {
             return 1; /* fail silently */
         }
     }
+
     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
 
-    /* fix up broken dates */
-    if (ad->ad_version == AD_VERSION1) {
-        u_int32_t aint;
-
-        /* check to see if the ad date is wrong. just see if we have
-         * a modification date in the future. */
-        if (((ad_getdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, &aint)) == 0) &&
-            (aint > TIMEWARP_DELTA + hst->st_mtime)) {
-            ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, aint - AD_DATE_DELTA);
-            ad_getdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, &aint);
-            ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, aint - AD_DATE_DELTA);
-            ad_getdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, &aint);
-            ad_setdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, aint - AD_DATE_DELTA);
-        }
+    return 0;
+}
+
+/* error here means it's not ad ._ adouble:osx file and thus we return 1 */
+int ad_valid_header_osx(const char *path)
+{
+    EC_INIT;
+    int fd = -1;
+    struct adouble      adosx;
+    char                *buf = &adosx.ad_data[0];
+    ssize_t             header_len;
+
+    LOG(log_debug, logtype_afpd, "ad_valid_header_osx(\"%s\"): BEGIN", fullpathname(path));
+
+    EC_NEG1( fd = open(path, O_RDONLY) );
+
+    /* read the header */
+    EC_NEG1( header_len = read(fd, buf, AD_DATASZ_OSX) );
+
+    if (header_len < AD_HEADER_LEN)
+        EC_FAIL;
+
+    memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
+    memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
+    adosx.ad_magic = ntohl(adosx.ad_magic);
+    adosx.ad_version = ntohl(adosx.ad_version);
+
+    if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
+        LOG(log_error, logtype_afpd, "ad_valid_header_osx: not an adouble:ox file");
+        EC_FAIL;
     }
 
+EC_CLEANUP:
+    LOG(log_debug, logtype_afpd, "ad_valid_header_osx(\"%s\"): END: %d", fullpathname(path), ret);
+    if (fd != -1)
+        close(fd);
+    if (ret != 0)
+        return 1;
     return 0;
 }
 
-/* ---------------------------
-   SFM structure
-*/
-#if 0
-typedef struct {
-    byte    afpi_Signature[4];      /* Must be 0x00504641 */
-    byte    afpi_Version[4];        /* Must be 0x00010000 */
-    byte    afpi_Reserved1[4];
-    byte    afpi_BackupTime[4];     /* Backup time for the file/dir */
-    byte    finderinfo[32];         /* Finder info */
-    byte    afpi_ProDosInfo[6];     /* ProDos Info */
-    byte    afpi_Reserved2[6];
-} sfm_info;
-#endif
-
-static int ad_header_sfm_read(struct adouble *ad, struct stat *hst)
+/* Read an ._ file, only uses the resofork, finderinfo is taken from EA */
+static int ad_header_read_osx(const char *path _U_, struct adouble *ad, const struct stat *hst)
 {
-    char                *buf = ad->ad_data;
-    const struct entry  *eid;
+    EC_INIT;
+    struct adouble      adosx;
+    char                *buf = &adosx.ad_data[0];
+    uint16_t            nentries;
+    int                 len;
     ssize_t             header_len;
     struct stat         st;
 
+    memset(buf, 0, sizeof(adosx.ad_data));
+
     /* read the header */
-    if ((header_len = adf_pread( ad->ad_md, buf, sizeof(ad->ad_data), 0)) < 0) {
+    EC_NEG1( header_len = adf_pread(ad->ad_rfp, buf, AD_DATASZ_OSX, 0) );
+
+    if (header_len < AD_HEADER_LEN) {
+        errno = EIO;
         return -1;
     }
-    if (header_len != AD_SFM_LEN) {
+
+    memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
+    memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
+    adosx.ad_magic = ntohl(adosx.ad_magic);
+    adosx.ad_version = ntohl(adosx.ad_version);
+
+    if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
+        LOG(log_error, logtype_afpd, "ad_header_read_osx: can't parse AppleDouble header");
         errno = EIO;
         return -1;
     }
 
-    memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
-    memcpy(&ad->ad_version, buf + 4, sizeof( ad->ad_version ));
-
-    /* FIXME in the great Microsoft tradition they aren't in network order */
-#if 0
-    if (ad->ad_magic == SFM_MAGIC && ad->ad_version == AD_VERSION1) {
-        static int          warning = 0;
-        if (!warning) {
-            LOG(log_debug, logtype_default, "notice: fixing up byte-swapped v1 magic/version.");
-            warning++;
-        }
+    memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
+    nentries = ntohs(nentries);
+    len = nentries * AD_ENTRY_LEN;
 
-    } else {
-        ad->ad_magic = ntohl( ad->ad_magic );
-        ad->ad_version = ntohl( ad->ad_version );
+    if (len + AD_HEADER_LEN > sizeof(adosx.ad_data))
+        len = sizeof(adosx.ad_data) - AD_HEADER_LEN;
+
+    buf += AD_HEADER_LEN;
+    if (len > header_len - AD_HEADER_LEN) {
+        LOG(log_error, logtype_afpd, "ad_header_read_osx: can't read entry info.");
+        errno = EIO;
+        return -1;
     }
-#endif
-    if ((ad->ad_magic != SFM_MAGIC) || ((ad->ad_version != AD_VERSION1) )) {
+
+    nentries = len / AD_ENTRY_LEN;
+    parse_entries(&adosx, buf, nentries);
+
+    if (ad_getentryoff(&adosx, ADEID_RFORK) == 0
+        || ad_getentryoff(&adosx, ADEID_RFORK) > sizeof(ad->ad_data)
+        || ad_getentryoff(&adosx, ADEID_RFORK) > header_len
+        ) {
+        LOG(log_error, logtype_afpd, "ad_header_read_osx: problem with rfork entry offset.");
         errno = EIO;
-        LOG(log_debug, logtype_default, "ad_header_sfm_read: can't parse AppleDouble header.");
         return -1;
     }
 
-    /* reinit adouble table */
-    eid = entry_order_sfm;
-    while (eid->id) {
-        ad->ad_eid[eid->id].ade_off = eid->offset;
-        ad->ad_eid[eid->id].ade_len = eid->len;
-        eid++;
+    if (hst == NULL) {
+        hst = &st;
+        EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
     }
 
-    /* steal some prodos for attribute */
-    {
+    ad_setentryoff(ad, ADEID_RFORK, ad_getentryoff(&adosx, ADEID_RFORK));
+    ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
+
+EC_CLEANUP:
+    EC_EXIT;
+}
+
+static int ad_header_read_ea(const char *path, struct adouble *ad, const struct stat *hst _U_)
+{
+    uint16_t nentries;
+    int      len;
+    ssize_t  header_len;
+    char     *buf = ad->ad_data;
 
-        u_int16_t attribute;
-        memcpy(&attribute, buf + 48 +4, sizeof(attribute));
-        ad_setattr(ad, attribute );
+    if (ad_meta_fileno(ad) != -1)
+        header_len = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_META, ad->ad_data, AD_DATASZ_EA);
+    else
+        header_len = sys_lgetxattr(path, AD_EA_META, ad->ad_data, AD_DATASZ_EA);
+     if (header_len < 1) {
+        LOG(log_debug, logtype_default, "ad_header_read_ea: %s", strerror(errno));
+        return -1;
     }
 
-    if (ad->ad_resource_fork.adf_fd != -1) {
-        /* we have a resource fork use it rather than the metadata */
-        if (fstat(ad->ad_resource_fork.adf_fd, &st) < 0) {
-            /* XXX set to zero ?
-               ad->ad_rlen =  0;
-            */
-            return 1;
-        }
-        ad->ad_rlen = st.st_size;
-        hst = &st;
+    if (header_len < AD_HEADER_LEN) {
+        LOG(log_error, logtype_default, "ad_header_read_ea: bogus AppleDouble header.");
+        errno = EIO;
+        return -1;
     }
-    else if (hst == NULL) {
-        hst = &st;
-        if (fstat(ad->ad_md->adf_fd, &st) < 0) {
-            return 1; /* fail silently */
-        }
+
+    memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
+    memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
+
+    ad->ad_magic = ntohl( ad->ad_magic );
+    ad->ad_version = ntohl( ad->ad_version );
+
+    if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
+        LOG(log_error, logtype_default, "ad_header_read_ea: wrong magic or version");
+        errno = EIO;
+        return -1;
     }
 
-    /* fix up broken dates */
-    if (ad->ad_version == AD_VERSION1) {
-        u_int32_t aint;
+    memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
+    nentries = ntohs( nentries );
 
-        /* check to see if the ad date is wrong. just see if we have
-         * a modification date in the future. */
-        if (((ad_getdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, &aint)) == 0) &&
-            (aint > TIMEWARP_DELTA + hst->st_mtime)) {
-            ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, aint - AD_DATE_DELTA);
-            ad_getdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, &aint);
-            ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, aint - AD_DATE_DELTA);
-            ad_getdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, &aint);
-            ad_setdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, aint - AD_DATE_DELTA);
-        }
+    /* Protect against bogus nentries */
+    len = nentries * AD_ENTRY_LEN;
+    if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
+        len = sizeof(ad->ad_data) - AD_HEADER_LEN;
+    if (len > header_len - AD_HEADER_LEN) {
+        LOG(log_error, logtype_default, "ad_header_read_ea: can't read entry info.");
+        errno = EIO;
+        return -1;
     }
+    nentries = len / AD_ENTRY_LEN;
+
+    /* Now parse entries */
+    parse_entries(ad, buf + AD_HEADER_LEN, nentries);
 
     return 0;
 }
 
-/* ---------------------------------------
- * Put the .AppleDouble where it needs to be:
- *
- *      /   a/.AppleDouble/b
- *  a/b
- *      \   b/.AppleDouble/.Parent
+/*!
+ * Takes a path to an AppleDouble file and creates the parrent .AppleDouble directory
  *
- * FIXME: should do something for pathname > MAXPATHLEN
+ * Example:
+ * path: "/path/.AppleDouble/file"
+ * => mkdir("/path/.AppleDouble/") (in ad_mkdir())
  */
-char *
-ad_path( const char *path, int adflags)
+static int ad_mkrf(const char *path)
 {
-    static char pathbuf[ MAXPATHLEN + 1];
-    const char *slash;
-    size_t  l ;
+    char *slash;
+    /*
+     * Probably .AppleDouble doesn't exist, try to mkdir it.
+     */
+    if (NULL == ( slash = strrchr( path, '/' )) ) {
+        return -1;
+    }
+    *slash = '\0';
+    errno = 0;
+    if ( ad_mkdir( path, 0777 ) < 0 ) {
+        return -1;
+    }
+    *slash = '/';
+    return 0;
+}
 
-    if ( adflags & ADFLAGS_DIR ) {
-        l = strlcpy( pathbuf, path, sizeof(pathbuf));
+static int ad_mkrf_ea(const char *path _U_)
+{
+    AFP_PANIC("ad_mkrf_ea: dont use");
+    return 0;
+}
 
-        if ( l && l < MAXPATHLEN) {
-            pathbuf[l++] = '/';
+static int ad_mkrf_osx(const char *path _U_)
+{
+    return 0;
+}
+
+/* ----------------
+   if we are root change path user/ group
+   It can be a native function for BSD cf. FAQ.Q10
+   path:  pathname to chown
+   stbuf: parent directory inode
+
+   use fstat and fchown or lchown with linux?
+*/
+#define EMULATE_SUIDDIR
+
+static int ad_chown(const char *path, struct stat *stbuf)
+{
+    int ret = 0;
+#ifdef EMULATE_SUIDDIR
+    uid_t id;
+
+    if (default_uid != (uid_t)-1) {
+        /* we are root (admin) */
+        id = (default_uid)?default_uid:stbuf->st_uid;
+        ret = lchown( path, id, stbuf->st_gid );
+    }
+#endif
+    return ret;
+}
+
+#define DEFMASK 07700   /* be conservative */
+
+/* ----------------
+   return access right and inode of path parent directory
+*/
+static int ad_mode_st(const char *path, mode_t *mode, struct stat *stbuf)
+{
+    if (*mode == 0) {
+        return -1;
+    }
+    if (ad_stat(path, stbuf) != 0) {
+        *mode &= DEFMASK;
+        return -1;
+    }
+    *mode &= stbuf->st_mode;
+    return 0;
+}
+
+/* --------------------------- */
+static int ad_header_upgrade(struct adouble *ad _U_, const char *name _U_)
+{
+    return 0;
+}
+
+static int ad_header_upgrade_ea(struct adouble *ad _U_, const char *name _U_)
+{
+    AFP_PANIC("ad_header_upgrade_ea: dont use");
+    return 0;
+}
+
+/*!
+ * Error handling for adouble header(=metadata) file open error
+ *
+ * We're called because opening ADFLAGS_HF caused an error.
+ * 1. In case ad_open is called with ADFLAGS_NOHF the error is suppressed.
+ * 2. If ad_open was called with ADFLAGS_DF we may have opened the datafork and thus
+ *    ought to close it before returning with an error condition.
+ */
+static int ad_error(struct adouble *ad, int adflags)
+{
+    int err = errno;
+    if (adflags & ADFLAGS_NOHF) { /* 1 */
+        return 0;
+    }
+    if (adflags & (ADFLAGS_DF | ADFLAGS_SETSHRMD | ADFLAGS_CHECK_OF)) { /* 2 */
+        ad_close( ad, ADFLAGS_DF );
+        err = errno;
+    }
+    return -1 ;
+}
+
+/*!
+ * Map ADFLAGS to open() flags
+ *
+ * @param adfile   (r) the file you really want to open: ADFLAGS_DF or ADFLAGS_HF
+ * @param adflags  (r) flags from ad_open(..., adflags, ...)
+ * @returns            mapped flags suitable for calling open()
+ */
+static int ad2openflags(const struct adouble *ad, int adfile, int adflags)
+{
+    int oflags = 0;
+
+    if (adflags & ADFLAGS_RDWR)
+        oflags |= O_RDWR;
+    if (adflags & ADFLAGS_RDONLY) {
+        if (((adfile == ADFLAGS_DF || adfile == ADFLAGS_RF) && (adflags & ADFLAGS_SETSHRMD))
+            /* need rw access for locks */
+            || ((adfile == ADFLAGS_HF) && (ad->ad_vers == AD_VERSION2)))
+            /* need rw access for adouble file for the case:
+             1) openfork(data+meta:O_RDONLY), 2) openfork(reso(=meta):O_RDWR) */
+            oflags |= O_RDWR;
+        else
+            oflags |= O_RDONLY;
+    }
+    if (adflags & ADFLAGS_CREATE)
+        oflags |= O_CREAT;
+    if (adflags & ADFLAGS_EXCL)
+        oflags |= O_EXCL;
+    if (adflags & ADFLAGS_TRUNC)
+        oflags |= O_TRUNC;
+
+    return oflags;
+}
+
+static int ad_open_df(const char *path, int adflags, mode_t mode, struct adouble *ad)
+{
+    EC_INIT;
+    struct stat st_dir;
+    int         oflags;
+    mode_t      admode;
+    int         st_invalid = -1;
+    ssize_t     lsz;
+
+    LOG(log_debug, logtype_default,
+        "ad_open_df(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        fullpathname(path), adflags2logstr(adflags),
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
+
+    if (ad_data_fileno(ad) != -1) {
+        /* the file is already open, but we want write access: */
+        if ((adflags & ADFLAGS_RDWR)
+            /* and it was denied the first time: */
+            && (ad->ad_data_fork.adf_flags & O_RDONLY)) {
+                errno = EACCES;
+                return -1;
+            }
+        /* it's not new anymore */
+        ad->ad_data_fork.adf_flags &= ~( O_TRUNC | O_CREAT );
+        ad->ad_data_fork.adf_refcount++;
+        goto EC_CLEANUP;
+    }
+
+    oflags = O_NOFOLLOW | ad2openflags(ad, ADFLAGS_DF, adflags);
+
+    admode = mode;
+    if ((adflags & ADFLAGS_CREATE)) {
+        st_invalid = ad_mode_st(path, &admode, &st_dir);
+        if ((ad->ad_options & ADVOL_UNIXPRIV))
+            admode = mode;
+    }
+
+    ad->ad_data_fork.adf_fd = open(path, oflags, admode);
+
+    if (ad->ad_data_fork.adf_fd == -1) {
+        switch (errno) {
+        case EACCES:
+        case EPERM:
+        case EROFS:
+            if ((adflags & ADFLAGS_SETSHRMD) && (adflags & ADFLAGS_RDONLY)) {
+                oflags &= ~O_RDWR;
+                oflags |= O_RDONLY;
+                EC_NEG1( ad->ad_data_fork.adf_fd = open(path, oflags, admode) );
+                break;
+            }
+            return -1;
+        case OPEN_NOFOLLOW_ERRNO:
+            ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
+            if ((lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN)) <= 0) {
+                free(ad->ad_data_fork.adf_syml);
+                EC_FAIL;
+            }
+            ad->ad_data_fork.adf_syml[lsz] = 0;
+            ad->ad_data_fork.adf_fd = AD_SYMLINK;
+            break;
+        default:
+            EC_FAIL;
         }
-        strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
+    }
+
+    if (!st_invalid)
+        ad_chown(path, &st_dir); /* just created, set owner if admin (root) */
+
+    ad->ad_data_fork.adf_flags = oflags;
+    adf_lock_init(&ad->ad_data_fork);
+    ad->ad_data_fork.adf_refcount++;
+
+EC_CLEANUP:
+    LOG(log_debug, logtype_default,
+        "ad_open_df(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        fullpathname(path), adflags2logstr(adflags), ret,
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
+    EC_EXIT;
+}
+
+static int ad_open_hf_v2(const char *path, int adflags, mode_t mode, struct adouble *ad)
+{
+    EC_INIT;
+    struct stat st_dir;
+    struct stat st_meta;
+    struct stat *pst = NULL;
+    const char  *ad_p;
+    int         oflags, nocreatflags, opened = 0;
+    mode_t      admode;
+    int         st_invalid = -1;
+
+    LOG(log_debug, logtype_default,
+        "ad_open_hf_v2(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        fullpathname(path), adflags2logstr(adflags),
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
+
+    if (ad_meta_fileno(ad) != -1) {
+        /* the file is already open, but we want write access: */
+        if ((adflags & ADFLAGS_RDWR) &&
+            /* and it was already denied: */
+            (ad->ad_mdp->adf_flags & O_RDONLY)) {
+            errno = EACCES;
+            EC_FAIL;
+        }
+        ad_refresh(path, ad);
+        /* it's not new anymore */
+        ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
+        ad->ad_mdp->adf_refcount++;
+        goto EC_CLEANUP;
+    }
+
+    ad_p = ad->ad_ops->ad_path(path, adflags);
+    oflags = O_NOFOLLOW | ad2openflags(ad, ADFLAGS_HF, adflags);
+    LOG(log_debug, logtype_default,"ad_open_hf_v2(\"%s\"): open flags: %s",
+        fullpathname(path), openflags2logstr(oflags));
+    nocreatflags = oflags & ~(O_CREAT | O_EXCL);
+
+    ad_meta_fileno(ad) = open(ad_p, nocreatflags);
+
+    if (ad_meta_fileno(ad) != -1) {
+        ad->ad_mdp->adf_flags = nocreatflags;
     } else {
-        if (NULL != ( slash = strrchr( path, '/' )) ) {
-            slash++;
-            l = slash - path;
-            /* XXX we must return NULL here and test in the caller */
-            if (l > MAXPATHLEN)
-                l = MAXPATHLEN;
-            memcpy( pathbuf, path, l);
-        } else {
-            l = 0;
-            slash = path;
+        switch (errno) {
+        case EACCES:
+        case EPERM:
+        case EROFS:
+            if ((adflags & ADFLAGS_RDONLY) && (adflags & ADFLAGS_SETSHRMD)) {
+                nocreatflags &= ~O_RDWR;
+                nocreatflags |= O_RDONLY;
+                EC_NEG1( ad_meta_fileno(ad) = open(ad_p, nocreatflags) );
+                ad->ad_mdp->adf_flags = nocreatflags;
+                break;
+            }
+            EC_FAIL;
+        case ENOENT:
+            if (!(oflags & O_CREAT))
+                EC_FAIL;
+            /*
+             * We're expecting to create a new adouble header file here
+             */
+            LOG(log_debug, logtype_default, "ad_open(\"%s\"): creating adouble file",
+                fullpathname(path));
+            admode = mode;
+            errno = 0;
+            st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
+            if ((ad->ad_options & ADVOL_UNIXPRIV))
+                admode = mode;
+            admode = ad_hf_mode(admode);
+            if (errno == ENOENT) {
+                EC_NEG1_LOG( ad->ad_ops->ad_mkrf(ad_p) );
+                admode = mode;
+                st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
+                if ((ad->ad_options & ADVOL_UNIXPRIV))
+                    admode = mode;
+                admode = ad_hf_mode(admode);
+            }
+
+            /* retry with O_CREAT */
+            EC_NEG1( ad_meta_fileno(ad) = open(ad_p, oflags, admode) );
+            ad->ad_mdp->adf_flags = oflags;
+            /* just created, set owner if admin owner (root) */
+            if (!st_invalid)
+                ad_chown(ad_p, &st_dir);
+            break;
+        default:
+            EC_FAIL;
         }
-        l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
-        strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
     }
 
-    return( pathbuf );
+    /* Now we've got a new opened fd, we need to check that in the error case */
+    opened = 1;
+
+    if (!(ad->ad_mdp->adf_flags & O_CREAT)) {
+        /* check for 0 length files, treat them as new. */
+        if (fstat(ad->ad_mdp->adf_fd, &st_meta) == 0) {
+            if (st_meta.st_size == 0)
+                ad->ad_mdp->adf_flags |= O_TRUNC;
+            else
+                /* we have valid data in st_meta stat structure, reused it in ad_header_read */
+                pst = &st_meta;
+        }
+    }
+
+    adf_lock_init(ad->ad_mdp);
+    ad->ad_mdp->adf_refcount = 1;
+
+    if ((ad->ad_mdp->adf_flags & ( O_TRUNC | O_CREAT ))) {
+        /* This is a new adouble header file, create it */
+        EC_NEG1_LOG( new_ad_header(ad, path, pst, adflags) );
+        ad_flush(ad);
+    } else {
+        /* Read the adouble header in and parse it.*/
+        EC_NEG1_LOG( ad->ad_ops->ad_header_read(path, ad, pst) );
+    }
+
+EC_CLEANUP:
+    if (ret != 0 && opened && ad_meta_fileno(ad) != -1) {
+        close(ad_meta_fileno(ad));
+        ad_meta_fileno(ad) = -1;
+        ad->ad_mdp->adf_refcount = 0;
+    }
+    LOG(log_debug, logtype_default,
+        "ad_open_hf_v2(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        fullpathname(path), adflags2logstr(adflags), ret,
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
+    EC_EXIT;
 }
 
-/* -------------------- */
-static int ad_mkrf(char *path)
+static int ad_open_hf_ea(const char *path, int adflags, int mode, struct adouble *ad)
+{
+    EC_INIT;
+    ssize_t rforklen;
+    int oflags;
+    int opened = 0;
+
+    LOG(log_debug, logtype_default,
+        "ad_open_hf_ea(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        fullpathname(path), adflags2logstr(adflags),
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
+
+    oflags = O_NOFOLLOW | (ad2openflags(ad, ADFLAGS_DF, adflags) & ~(O_CREAT | O_TRUNC));
+
+    if (ad_meta_fileno(ad) == AD_SYMLINK)
+        /* symlink */
+        EC_EXIT;
+
+    if (ad_meta_fileno(ad) != -1) {
+        /* the file is already open, but we want write access: */
+        if ((oflags & O_RDWR) &&
+            /* and it was already denied: */
+            (ad->ad_mdp->adf_flags & O_RDONLY)) {
+            LOG(log_error, logtype_default, "ad_open_hf_ea(%s): rw request for ro file: %s",
+                fullpathname(path), strerror(errno));
+            errno = EACCES;
+            EC_FAIL;
+        }
+        /* it's not new anymore */
+        ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
+    } else {
+        if (oflags & O_RDWR) {
+            /* Fo a RDONLY adouble we just use sys_lgetxattr instead if sys_fgetxattr */
+            if (adflags & ADFLAGS_DIR)
+                /* For directories we open the directory RDONYL so we can later fchdir()  */
+                oflags = (oflags & ~O_RDWR) | O_RDONLY;
+            LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): opening base file for meta adouble EA", path);
+            EC_NEG1(ad_meta_fileno(ad) = open(path, oflags));
+            opened = 1;
+            ad->ad_mdp->adf_flags = oflags;
+        }
+    }
+
+    /* Read the adouble header in and parse it.*/
+    if (ad->ad_ops->ad_header_read(path, ad, NULL) != 0) {
+        if (!(adflags & ADFLAGS_CREATE)) {
+            LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): can't read metadata EA", path);
+            errno = ENOENT;
+            EC_FAIL;
+        }
+
+        LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): creating metadata EA", path);
+
+        /* It doesnt exist, EPERM or another error */
+        if (!(errno == ENOATTR || errno == ENOENT)) {
+            LOG(log_error, logtype_default, "ad_open_hf_ea: unexpected: %s", strerror(errno));
+            EC_FAIL;
+        }
+
+        /* Create one */
+        EC_NEG1_LOG(new_ad_header(ad, path, NULL, adflags));
+        ad->ad_mdp->adf_flags |= O_CREAT; /* mark as just created */
+        ad_flush(ad);
+        LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): created metadata EA", path);
+    }
+
+    if (ad_meta_fileno(ad) != -1)
+        ad->ad_mdp->adf_refcount++;
+    (void)ad_reso_size(path, adflags, ad);
+
+EC_CLEANUP:
+    if (ret != 0 && opened && ad_meta_fileno(ad) != -1) {
+        close(ad_meta_fileno(ad));
+        ad_meta_fileno(ad) = -1;
+        ad->ad_mdp->adf_refcount = 0;
+    }
+    LOG(log_debug, logtype_default,
+        "ad_open_hf_ea(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        fullpathname(path), adflags2logstr(adflags), ret,
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
+        
+    EC_EXIT;
+}
+
+static int ad_open_hf(const char *path, int adflags, int mode, struct adouble *ad)
+{
+    int ret = 0;
+
+    memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
+    ad->ad_rlen = 0;
+
+    switch (ad->ad_vers) {
+    case AD_VERSION2:
+        ret = ad_open_hf_v2(path, adflags, mode, ad);
+        break;
+    case AD_VERSION_EA:
+        ret = ad_open_hf_ea(path, adflags, mode, ad);
+        break;
+    default:
+        ret = -1;
+        break;
+    }
+
+    if (ret != 0)
+        ret = ad_error(ad, adflags);
+
+    return ret;
+}
+
+/*!
+ * Get resofork length for adouble:ea
+ */
+static int ad_reso_size(const char *path, int adflags, struct adouble *ad)
+{
+    EC_INIT;
+    struct stat st;
+
+    if (adflags & ADFLAGS_DIR) {
+        ad->ad_rlen = 0;
+        goto EC_CLEANUP;
+    }
+
+    LOG(log_debug, logtype_default, "ad_reso_size(\"%s\"): BEGIN", path);
+
+#ifdef HAVE_EAFD
+    ssize_t easz;
+
+    if (ad_reso_fileno(ad) != -1) {
+        EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
+        ad->ad_rlen = st.st_size;
+    } else if (ad_meta_fileno(ad) != -1) {
+        EC_NEG1( (ad->ad_rlen = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_RESO, NULL, 0)) );
+    } else {
+        EC_NEG1( (ad->ad_rlen = sys_lgetxattr(path, AD_EA_RESO, NULL, 0)) );
+    }
+
+#else
+    const char *rfpath;
+    EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags));
+    EC_ZERO( lstat(rfpath, &st));
+    if (st.st_size > ADEDOFF_RFORK_OSX)
+        ad->ad_rlen = st.st_size - ADEDOFF_RFORK_OSX;
+    else
+        ad->ad_rlen = 0;
+#endif
+
+    LOG(log_debug, logtype_default, "ad_reso_size(\"%s\"): size: %zd", path, ad->ad_rlen);
+
+EC_CLEANUP:
+    if (ret != 0)
+        ad->ad_rlen = 0;
+    EC_EXIT;
+}
+
+static int ad_open_rf_v2(const char *path, int adflags, int mode, struct adouble *ad)
 {
-    char *slash;
     /*
-     * Probably .AppleDouble doesn't exist, try to mkdir it.
+     * ad_open_hf_v2() does the work, but if it failed and adflags are ADFLAGS_NOHF | ADFLAGS_RF
+     * ad_open_hf_v2() didn't give an error, but we're supposed to return a reso fork fd
      */
-    if (NULL == ( slash = strrchr( path, '/' )) ) {
+    if (!AD_RSRC_OPEN(ad) && !(adflags & ADFLAGS_NORF))
         return -1;
+    return 0;
+}
+
+static int ad_open_rf_ea(const char *path, int adflags, int mode, struct adouble *ad)
+{
+    EC_INIT;
+    int oflags;
+    int opened = 0;
+    int closeflags = adflags & (ADFLAGS_DF | ADFLAGS_HF);
+    ssize_t rlen;
+#ifndef HAVE_EAFD
+    const char *rfpath;
+    struct stat st;
+#endif
+
+    LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): BEGIN", fullpathname(path));
+
+    oflags = O_NOFOLLOW | (ad2openflags(ad, ADFLAGS_RF, adflags) & ~O_CREAT);
+
+    if (ad_reso_fileno(ad) != -1) {
+        /* the file is already open, but we want write access: */
+        if ((oflags & O_RDWR)
+            /* and it was already denied: */
+            && (ad->ad_rfp->adf_flags & O_RDONLY)) {
+            errno = EACCES;
+            EC_FAIL;
+        }
+        ad->ad_rfp->adf_flags &= ~( O_TRUNC | O_CREAT );
+        ad->ad_rfp->adf_refcount++;
+        EC_NEG1_LOG( ad_reso_size(path, adflags, ad));
+        goto EC_CLEANUP;
     }
-    *slash = '\0';
-    errno = 0;
-    if ( ad_mkdir( path, 0777 ) < 0 ) {
-        return -1;
+#ifdef HAVE_EAFD
+    if (ad_meta_fileno(ad) < 0)
+        EC_FAIL;
+    if ((ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad), AD_EA_RESO, oflags)) == -1) {
+        if (!(adflags & ADFLAGS_CREATE)) {
+            errno = ENOENT;
+            EC_FAIL;
+        }
+        oflags |= O_CREAT;
+        EC_NEG1_LOG( ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad),
+                                                         AD_EA_RESO, oflags, 0666) ); 
     }
-    *slash = '/';
-    return 0;
+#else
+    EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags) );
+    if ((ad_reso_fileno(ad) = open(rfpath, oflags)) == -1) {
+        if (!(adflags & ADFLAGS_CREATE))
+            EC_FAIL;
+        oflags |= O_CREAT;
+        EC_NEG1_LOG( ad_reso_fileno(ad) = open(rfpath, oflags, mode) );
+        LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork: \"%s\"",
+            path, rfpath);
+    }
+#endif
+    opened = 1;
+    ad->ad_rfp->adf_refcount = 1;
+    ad->ad_rfp->adf_flags = oflags;
+
+#ifndef HAVE_EAFD
+    EC_ZERO_LOG( fstat(ad_reso_fileno(ad), &st) );
+    if (ad->ad_rfp->adf_flags & O_CREAT) {
+        /* This is a new adouble header file, create it */
+        LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork, initializing: \"%s\"",
+            path, rfpath);
+        LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork, flushing: \"%s\"",
+            path, rfpath);
+        ad_flush(ad);
+    } else {
+        /* Read the adouble header */
+        LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): reading adouble rfork: \"%s\"",
+            path, rfpath);
+        EC_NEG1_LOG( ad_header_read_osx(NULL, ad, &st) );
+    }
+#endif
+
+    (void)ad_reso_size(path, adflags, ad);
+
+EC_CLEANUP:
+    if (ret != 0) {
+        if (opened && (ad_reso_fileno(ad) != -1)) {
+            close(ad_reso_fileno(ad));
+            ad_reso_fileno(ad) = -1;
+            ad->ad_rfp->adf_refcount = 0;
+        }
+        if (adflags & ADFLAGS_NORF) {
+            ret = 0;
+        } else {
+            int err = errno;
+            (void)ad_close(ad, closeflags);
+            errno = err;
+        }
+        ad->ad_rlen = 0;
+    }
+
+    LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): END: %d", fullpathname(path), ret);
+
+    EC_EXIT;
 }
 
-/* ---------------------------------------
- * Put the resource fork where it needs to be:
- * ._name
+/*!
+ * Open ressource fork
  */
-char *
-ad_path_osx(const char *path, int adflags _U_)
+static int ad_open_rf(const char *path, int adflags, int mode, struct adouble *ad)
+{
+    int ret = 0;
+
+    switch (ad->ad_vers) {
+    case AD_VERSION2:
+        ret = ad_open_rf_v2(path, adflags, mode, ad);
+        break;
+    case AD_VERSION_EA:
+        ret = ad_open_rf_ea(path, adflags, mode, ad);
+        break;
+    default:
+        ret = -1;
+        break;
+    }
+
+    return ret;
+}
+
+/***********************************************************************************
+ * API functions
+ ********************************************************************************* */
+
+off_t ad_getentryoff(const struct adouble *ad, int eid)
+{
+    if (ad->ad_vers == AD_VERSION2)
+        return ad->ad_eid[eid].ade_off;
+
+    switch (eid) {
+    case ADEID_DFORK:
+        return 0;
+    case ADEID_RFORK:
+#ifdef HAVE_EAFD
+        return 0;
+#else
+        return ADEDOFF_RFORK_OSX;
+#endif
+    default:
+        return ad->ad_eid[eid].ade_off;
+    }
+    /* deadc0de */
+    AFP_PANIC("What am I doing here?");
+}
+
+const char *ad_path_ea( const char *path, int adflags _U_)
+{
+    return path;
+}
+
+const char *ad_path_osx(const char *path, int adflags _U_)
 {
     static char pathbuf[ MAXPATHLEN + 1];
     char    c, *slash, buf[MAXPATHLEN + 1];
@@ -846,101 +1368,54 @@ ad_path_osx(const char *path, int adflags _U_)
     strlcat( pathbuf, slash, MAXPATHLEN +1);
     return pathbuf;
 }
-/* -------------------- */
-static int ad_mkrf_osx(char *path _U_)
-{
-    return 0;
-}
 
-/* ---------------------------------------
+/*
  * Put the .AppleDouble where it needs to be:
  *
- *      /   a/.AppleDouble/b/AFP_AfpInfo
+ *      /   a/.AppleDouble/b
  *  a/b
- *      \   b/.AppleDouble/.Parent/AFP_AfpInfo
+ *      \   b/.AppleDouble/.Parent
  *
+ * FIXME: should do something for pathname > MAXPATHLEN
  */
-char *
-ad_path_sfm( const char *path, int adflags)
+const char *ad_path( const char *path, int adflags)
 {
     static char pathbuf[ MAXPATHLEN + 1];
-    char    c, *slash, buf[MAXPATHLEN + 1];
-    size_t      l;
+    const char *slash;
+    size_t  ;
 
-    l = strlcpy(buf, path, MAXPATHLEN +1);
     if ( adflags & ADFLAGS_DIR ) {
-        strcpy( pathbuf, buf);
-        if ( *buf != '\0' && l < MAXPATHLEN) {
+        l = strlcpy( pathbuf, path, sizeof(pathbuf));
+
+        if ( l && l < MAXPATHLEN) {
             pathbuf[l++] = '/';
-            pathbuf[l] = 0;
         }
-        slash = ".Parent";
+        strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
     } else {
-        if (NULL != ( slash = strrchr( buf, '/' )) ) {
-            c = *++slash;
-            *slash = '\0';
-            strcpy( pathbuf, buf);
-            *slash = c;
+        if (NULL != ( slash = strrchr( path, '/' )) ) {
+            slash++;
+            l = slash - path;
+            /* XXX we must return NULL here and test in the caller */
+            if (l > MAXPATHLEN)
+                l = MAXPATHLEN;
+            memcpy( pathbuf, path, l);
         } else {
-            pathbuf[ 0 ] = '\0';
-            slash = buf;
+            l = 0;
+            slash = path;
         }
+        l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
+        strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
     }
-    strlcat( pathbuf, ".AppleDouble/", MAXPATHLEN +1);
-    strlcat( pathbuf, slash, MAXPATHLEN +1);
 
-    if ((adflags == ADFLAGS_RF)) {
-        strlcat( pathbuf, "/AFP_Resource", MAXPATHLEN +1);
-    }
-    else {
-        strlcat( pathbuf, "/AFP_AfpInfo", MAXPATHLEN +1);
-    }
     return( pathbuf );
 }
 
-/* -------------------- */
-static int ad_mkrf_sfm(char *path)
-{
-    char *slash;
-    /*
-     * Probably .AppleDouble doesn't exist, try to mkdir it.
-     */
-    if (NULL == ( slash = strrchr( path, '/' )) ) {
-        return -1;
-    }
-    *slash = 0;
-    errno = 0;
-    if ( ad_mkdir( path, 0777 ) < 0 ) {
-        if ( errno == ENOENT ) {
-            char *slash1;
-
-            if (NULL == ( slash1 = strrchr( path, '/' )) )
-                return -1;
-            errno = 0;
-            *slash1 = 0;
-            if ( ad_mkdir( path, 0777 ) < 0 )
-                return -1;
-            *slash1 = '/';
-            if ( ad_mkdir( path, 0777 ) < 0 )
-                return -1;
-        }
-        else
-            return -1;
-    }
-    *slash = '/';
-    return 0;
-}
-
 /* -------------------------
  * Support inherited protection modes for AppleDouble files.  The supplied
  * mode is ANDed with the parent directory's mask value in lieu of "umask",
  * and that value is returned.
  */
-
-#define DEFMASK 07700   /* be conservative */
-
-char
-*ad_dir(const char *path)
+char *ad_dir(const char *path)
 {
     static char     modebuf[ MAXPATHLEN + 1];
     char        *slash;
@@ -987,82 +1462,35 @@ use_cur:
     return modebuf;
 }
 
-/* ---------------- */
-static uid_t default_uid = -1;
-
 int ad_setfuid(const uid_t id)
 {
     default_uid = id;
     return 0;
 }
 
-/* ---------------- */
-uid_t ad_getfuid(void)
-{
-    return default_uid;
-}
-
-/* ----------------
-   return inode of path parent directory
-*/
-int ad_stat(const char *path, struct stat *stbuf)
-{
-    char                *p;
-
-    p = ad_dir(path);
-    if (!p) {
-        return -1;
-    }
-//FIXME!
-    return lstat( p, stbuf );
-}
-
-/* ----------------
-   if we are root change path user/ group
-   It can be a native function for BSD cf. FAQ.Q10
-   path:  pathname to chown
-   stbuf: parent directory inode
-
-   use fstat and fchown or lchown with linux?
-*/
-#define EMULATE_SUIDDIR
-
-static int ad_chown(const char *path, struct stat *stbuf)
-{
-    int ret = 0;
-#ifdef EMULATE_SUIDDIR
-    uid_t id;
-
-    if (default_uid != (uid_t)-1) {
-        /* we are root (admin) */
-        id = (default_uid)?default_uid:stbuf->st_uid;
-        ret = lchown( path, id, stbuf->st_gid );
-    }
-#endif
-    return ret;
-}
-
+/* ---------------- */
+uid_t ad_getfuid(void)
+{
+    return default_uid;
+}
+
 /* ----------------
-   return access right and inode of path parent directory
+   stat path parent directory
 */
-static int ad_mode_st(const char *path, int *mode, struct stat *stbuf)
+int ad_stat(const char *path, struct stat *stbuf)
 {
-    if (*mode == 0) {
-        return -1;
-    }
-    if (ad_stat(path, stbuf) != 0) {
-        *mode &= DEFMASK;
+    char *p;
+
+    p = ad_dir(path);
+    if (!p)
         return -1;
-    }
-    *mode &= stbuf->st_mode;
-    return 0;
+    return lstat( p, stbuf );
 }
 
 /* ----------------
    return access right of path parent directory
 */
-int
-ad_mode( const char *path, int mode)
+int ad_mode( const char *path, mode_t mode)
 {
     struct stat     stbuf;
     ad_mode_st(path, &mode, &stbuf);
@@ -1072,8 +1500,7 @@ ad_mode( const char *path, int mode)
 /*
  * Use mkdir() with mode bits taken from ad_mode().
  */
-int
-ad_mkdir( const char *path, int mode)
+int ad_mkdir( const char *path, mode_t mode)
 {
     int ret;
     int st_invalid;
@@ -1091,436 +1518,158 @@ ad_mkdir( const char *path, int mode)
     return ret;
 }
 
-/* ----------------- */
-static int ad_error(struct adouble *ad, int adflags)
+static void ad_init_func(struct adouble *ad)
 {
-    int err = errno;
-    if ((adflags & ADFLAGS_NOHF)) {
-        /* FIXME double check : set header offset ?*/
-        return 0;
-    }
-    if ((adflags & ADFLAGS_DF)) {
-        ad_close( ad, ADFLAGS_DF );
-        err = errno;
+    switch (ad->ad_vers) {
+    case AD_VERSION2:
+        ad->ad_ops = &ad_adouble;
+        ad->ad_rfp = &ad->ad_resource_fork;
+        ad->ad_mdp = &ad->ad_resource_fork;
+        break;
+    case AD_VERSION_EA:
+        ad->ad_ops = &ad_adouble_ea;
+        ad->ad_rfp = &ad->ad_resource_fork;
+        ad->ad_mdp = &ad->ad_data_fork;
+        break;
+    default:
+        AFP_PANIC("ad_init: unknown AD version");
     }
-    return -1 ;
-}
-
-static int new_rfork(const char *path, struct adouble *ad, int adflags);
-
-#ifdef  HAVE_PREAD
-#define AD_SET(a)
-#else
-#define AD_SET(a) a = 0
-#endif
 
-/* --------------------------- */
-static int ad_check_size(struct adouble *ad _U_, struct stat *st)
-{
-    if (st->st_size > 0 && st->st_size < AD_DATASZ1)
-        return 1;
-    return 0;
-}
-
-/* --------------------------- */
-static int ad_check_size_sfm(struct adouble *ad _U_, struct stat *st)
-{
-    if (st->st_size > 0 && st->st_size < AD_SFM_LEN)
-        return 1;
-    return 0;
-}
 
-/* --------------------------- */
-static int ad_header_upgrade(struct adouble *ad, char *name)
-{
-#if AD_VERSION == AD_VERSION2
-    int ret;
-    if ( (ret = ad_convert(ad, name)) < 0 || (ret = ad_update(ad, name) < 0)) {
-        return ret;
-    }
-#endif
-    return 0;
+    ad_data_fileno(ad) = -1;
+    ad_reso_fileno(ad) = -1;
+    ad_meta_fileno(ad) = -1;
+    ad->ad_refcount = 1;
+    return;
 }
 
-/* --------------------------- */
-static int ad_header_upgrade_none(struct adouble *ad _U_, char *name _U_)
+void ad_init_old(struct adouble *ad, int flags, int options)
 {
-    return 0;
+    memset(ad, 0, sizeof(struct adouble));
+    ad->ad_vers = flags;
+    ad->ad_options = options;
+    ad_init_func(ad);
 }
 
-/* --------------------------- */
-static struct adouble_fops ad_osx = {
-    &ad_path_osx,
-    &ad_mkrf_osx,
-    &ad_rebuild_adouble_header,
-    &ad_check_size,
-
-    &ad_header_read,
-    &ad_header_upgrade,
-};
-
-static struct adouble_fops ad_sfm = {
-    &ad_path_sfm,
-    &ad_mkrf_sfm,
-    &ad_rebuild_sfm_header,
-    &ad_check_size_sfm,
-
-    &ad_header_sfm_read,
-    &ad_header_upgrade_none,
-};
-
-static struct adouble_fops ad_adouble = {
-    &ad_path,
-    &ad_mkrf,
-    &ad_rebuild_adouble_header,
-    &ad_check_size,
-
-    &ad_header_read,
-    &ad_header_upgrade,
-};
-
-
-void ad_init(struct adouble *ad, int flags, int options)
+void ad_init(struct adouble *ad, const struct vol * restrict vol)
 {
-    ad->ad_inited = 0;
-    ad->ad_flags = flags;
-    if (flags == AD_VERSION2_OSX) {
-        ad->ad_ops = &ad_osx;
-        ad->ad_md = &ad->ad_resource_fork;
-    }
-    else if (flags == AD_VERSION1_SFM) {
-        ad->ad_ops = &ad_sfm;
-        ad->ad_md = &ad->ad_metadata_fork;
-    }
-    else {
-        ad->ad_ops = &ad_adouble;
-        ad->ad_md = &ad->ad_resource_fork;
-    }
-    ad->ad_options = options;
-
-    ad_data_fileno(ad) = -1;
-    ad_reso_fileno(ad) = -1;
-    ad_meta_fileno(ad) = -1;
-    /* following can be read even if there's no
-     * meda data.
-     */
-    memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
-    ad->ad_rlen = 0;
+    memset(ad, 0, sizeof(struct adouble));
+    ad->ad_vers = vol->v_adouble;
+    ad->ad_options = vol->v_ad_options;
+    ad_init_func(ad);
 }
 
 /*!
  * Open data-, metadata(header)- or ressource fork
  *
+ * ad_open(struct adouble *ad, const char *path, int adflags, int flags)
+ * ad_open(struct adouble *ad, const char *path, int adflags, int flags, mode_t mode)
+ *
  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
  * @code
  *      struct adoube ad;
  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
  * @endcode
  *
- * @param path    Path to file or directory
+ * Open a files data fork, metadata fork or ressource fork.
  *
- * @param adflags ADFLAGS_DF: open data file/fork\n
- *                ADFLAGS_HF: open header (metadata) file\n
- *                ADFLAGS_RF: open ressource fork *** FIXME: not used ?! *** \n
- *                ADFLAGS_CREATE: indicate creation\n
- *                ADFLAGS_NOHF: it's not an error if header file couldn't be created\n
- *                ADFLAGS_DIR: if path is a directory you MUST or ADFLAGS_DIR to adflags\n
- *                ADFLAGS_NOADOUBLE: dont create adouble files if not necessary\n
- *                ADFLAGS_RDONLY: open read only\n
- *                ADFLAGS_OPENFORKS: check for open forks from other processes\n
- *                ADFLAGS_MD: alias for ADFLAGS_HF\n
- *                ADFLAGS_V1COMPAT: obsolete
+ * @param ad        (rw) pointer to struct adouble
+ * @param path      (r)  Path to file or directory
+ * @param adflags   (r)  Flags specifying which fork to open, can be or'd:
+ *                         ADFLAGS_DF:        open data fork
+ *                         ADFLAGS_RF:        open ressource fork
+ *                         ADFLAGS_HF:        open header (metadata) file
+ *                         ADFLAGS_NOHF:      it's not an error if header file couldn't be opened
+ *                         ADFLAGS_NORF:      it's not an error if reso fork couldn't be opened
+ *                         ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags
  *
- * @param oflags  flags passed through to open syscall: \n
- *                O_RDONLY: *** FIXME *** \n
- *                O_RDWR: *** FIXME *** \n
- *                O_CREAT: create fork\n
- *                O_EXCL: fail if exists with O_CREAT
+ *                       Access mode for the forks:
+ *                         ADFLAGS_RDONLY:    open read only
+ *                         ADFLAGS_RDWR:      open read write
  *
- * @param mode    passed to open with O_CREAT
+ *                       Creation flags:
+ *                         ADFLAGS_CREATE:    create if not existing
+ *                         ADFLAGS_TRUNC:     truncate
  *
- * @param ad      pointer to struct adouble
+ *                       Special flags:
+ *                         ADFLAGS_CHECK_OF:  check for open forks from us and other afpd's
+ *                         ADFLAGS_SETSHRMD:  this adouble struct will be used to set sharemode locks.
+ *                                            This basically results in the files being opened RW instead of RDONLY.
+ * @param mode      (r)  mode used with O_CREATE
  *
- * @returns 0 on success
+ * The open mode flags (rw vs ro) have to take into account all the following requirements:
+ * - we remember open fds for files because me must avoid a single close releasing fcntl locks for other
+ *   fds of the same file
  *
- * @note It's not possible to open the header file O_RDONLY -- the read
- *       will fail and return an error. this refcounts things now.\n
- *       metadata(ressource)-fork only gets created with O_CREAT.
+ * @returns 0 on success, any other value indicates an error
  */
-int ad_open( const char *path, int adflags, int oflags, int mode, struct adouble  *ad)
+int ad_open(struct adouble *ad, const char *path, int adflags, ...)
 {
-    struct stat         st_dir;
-    struct stat         st_meta;
-    struct stat         *pst = NULL;
-    char        *ad_p;
-    int         hoflags, admode;
-    int                 st_invalid = -1;
-    int                 open_df = 0;
-
-    if (ad->ad_inited != AD_INITED) {
-        ad->ad_inited = AD_INITED;
-        ad->ad_refcount = 1;
-        ad->ad_open_forks = 0;
-        ad->ad_adflags = adflags;
-        ad->ad_resource_fork.adf_refcount = 0;
-        ad->ad_data_fork.adf_refcount = 0;
-        ad->ad_data_fork.adf_syml=0;
-    }
-    else {
-        ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
-        /* XXX not true if we have a meta data fork ? */
-        if ((ad->ad_resource_fork.adf_refcount > ad->ad_data_fork.adf_refcount))
-            ad->ad_open_forks |= ATTRBIT_ROPEN;
-    }
-
-    if ((adflags & ADFLAGS_DF)) {
-        if (ad_data_fileno(ad) == -1) {
-            hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
-            admode = mode;
-            if ((oflags & O_CREAT)) {
-                st_invalid = ad_mode_st(path, &admode, &st_dir);
-                if ((ad->ad_options & ADVOL_UNIXPRIV)) {
-                    admode = mode;
-                }
-            }
-                
-            ad->ad_data_fork.adf_fd =open( path, hoflags | O_NOFOLLOW, admode );
-            
-            if (ad->ad_data_fork.adf_fd == -1) {
-                if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
-                    hoflags = oflags;
-                    ad->ad_data_fork.adf_fd = open( path, hoflags | O_NOFOLLOW, admode );
-                }
-                if (ad->ad_data_fork.adf_fd == -1 && errno == OPEN_NOFOLLOW_ERRNO) {
-                    int lsz;
-
-                    ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
-                    lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN);
-                    if (lsz <= 0) {
-                        free(ad->ad_data_fork.adf_syml);
-                        return -1;
-                    }
-                    ad->ad_data_fork.adf_syml[lsz] = 0;
-                    ad->ad_data_fork.adf_fd = -2; /* -2 means its a symlink */
-                }
-            }
-
-            if ( ad->ad_data_fork.adf_fd == -1 )
-                return -1;
-
-            AD_SET(ad->ad_data_fork.adf_off);
-            ad->ad_data_fork.adf_flags = hoflags;
-            if (!st_invalid) {
-                /* just created, set owner if admin (root) */
-                ad_chown(path, &st_dir);
-            }
-            adf_lock_init(&ad->ad_data_fork);
-        }
-        else {
-            /* the file is already open... but */
-            if ((oflags & ( O_RDWR | O_WRONLY)) &&             /* we want write access */
-                !(ad->ad_data_fork.adf_flags & ( O_RDWR | O_WRONLY))) /* and it was denied the first time */
-            {
-                errno = EACCES;
-                return -1;
-            }
-            /* FIXME
-             * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
-             * already open. Should we check for it? ie
-             * O_EXCL --> error
-             * O_TRUNC --> truncate the fork.
-             * idem for ressource fork.
-             */
-        }
-        open_df = ADFLAGS_DF;
-        ad->ad_data_fork.adf_refcount++;
-    }
+    EC_INIT;
+    va_list args;
+    mode_t mode = 0;
 
-    if (!(adflags & ADFLAGS_HF))
-        return 0;
-
-    /* ****************************************** */
-
-    if (ad_meta_fileno(ad) != -1) { /* the file is already open */
-        if ((oflags & ( O_RDWR | O_WRONLY)) &&
-            !(ad->ad_md->adf_flags & ( O_RDWR | O_WRONLY))) {
-            if (open_df) {
-                /* don't call with ADFLAGS_HF because we didn't open ressource fork */
-                ad_close( ad, open_df );
-            }
-            errno = EACCES;
-            return -1;
-        }
-        ad_refresh(ad);
-        /* it's not new anymore */
-        ad->ad_md->adf_flags &= ~( O_TRUNC | O_CREAT );
-        ad->ad_md->adf_refcount++;
-        goto sfm;
-    }
+    LOG(log_debug, logtype_default,
+        "ad_open(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        fullpathname(path), adflags2logstr(adflags),
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
 
-    memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
-    ad->ad_rlen = 0;
-    ad_p = ad->ad_ops->ad_path( path, adflags );
+    if (adflags & ADFLAGS_CHECK_OF)
+        /* Checking for open forks requires sharemode lock support (ie RDWR instead of RDONLY) */
+        adflags |= ADFLAGS_SETSHRMD;
 
-    hoflags = oflags & ~(O_CREAT | O_EXCL);
-    if (!(adflags & ADFLAGS_RDONLY)) {
-        hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
-    }
-    ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
-    if (ad->ad_md->adf_fd < 0 ) {
-        if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
-            hoflags = oflags & ~(O_CREAT | O_EXCL);
-            ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
-        }
-    }
+    if (adflags & ADFLAGS_SETSHRMD)
+        /* sharemode locks are stored in the data fork */
+        adflags |= ADFLAGS_DF;
 
-    if ( ad->ad_md->adf_fd < 0 ) {
-        if (errno == ENOENT && (oflags & O_CREAT) ) {
-            /*
-             * We're expecting to create a new adouble header file,
-             * here.
-             * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
-             */
-            LOG(log_debug, logtype_default, "ad_open(\"%s\"): {cwd: \"%s\"} creating adouble file",
-                ad_p, getcwdpath());
-            admode = mode;
-            errno = 0;
-            st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
-            if ((ad->ad_options & ADVOL_UNIXPRIV)) {
-                admode = mode;
-            }
-            admode = ad_hf_mode(admode);
-            if ((errno == ENOENT) && (ad->ad_flags != AD_VERSION2_OSX)) {
-                if (ad->ad_ops->ad_mkrf( ad_p) < 0) {
-                    return ad_error(ad, adflags);
-                }
-                admode = mode;
-                st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
-                if ((ad->ad_options & ADVOL_UNIXPRIV)) {
-                    admode = mode;
-                }
-                admode = ad_hf_mode(admode);
-            }
-            /* retry with O_CREAT */
-            ad->ad_md->adf_fd = open( ad_p, oflags,admode );
-            if ( ad->ad_md->adf_fd < 0 ) {
-                return ad_error(ad, adflags);
-            }
-            ad->ad_md->adf_flags = oflags;
-            /* just created, set owner if admin owner (root) */
-            if (!st_invalid) {
-                ad_chown(ad_p, &st_dir);
-            }
-        }
-        else {
-            return ad_error(ad, adflags);
-        }
-    } else {
-        ad->ad_md->adf_flags = hoflags;
-        if (fstat(ad->ad_md->adf_fd, &st_meta) == 0 && st_meta.st_size == 0) {
-            /* for 0 length files, treat them as new. */
-            ad->ad_md->adf_flags |= O_TRUNC;
-        } 
-        else {
-            /* we have valid data in st_meta stat structure, reused it
-               in ad_header_read
-            */
-            pst = &st_meta;
-        }
+    if (ad->ad_vers == AD_VERSION2) {
+        if (adflags & ADFLAGS_RF)
+            adflags |= ADFLAGS_HF;
+        if (adflags & ADFLAGS_NORF)
+            adflags |= ADFLAGS_NOHF;
     }
-    AD_SET(ad->ad_md->adf_off);
 
-    ad->ad_md->adf_refcount = 1;
-    adf_lock_init(ad->ad_md);
-    if ((ad->ad_md->adf_flags & ( O_TRUNC | O_CREAT ))) {
-        /*
-         * This is a new adouble header file. Initialize the structure,
-         * instead of reading it.
-         */
-        if (new_rfork(path, ad, adflags) < 0) {
-            int err = errno;
-            /* the file is already deleted, perm, whatever, so return an error*/
-            ad_close(ad, adflags);
-            errno = err;
-            return -1;
-        }
-        ad_flush(ad);
+    if (ad->ad_inited != AD_INITED) {
+        ad->ad_adflags = adflags;
+        ad->ad_inited = AD_INITED;
     } else {
-        /* Read the adouble header in and parse it.*/
-        if (ad->ad_ops->ad_header_read( ad , pst) < 0
-            || ad->ad_ops->ad_header_upgrade(ad, ad_p) < 0)
-        {
-            int err = errno;
-
-            ad_close( ad, adflags );
-            errno = err;
-            return -1;
-        }
+        ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
+        if (ad->ad_resource_fork.adf_refcount > 0)
+            ad->ad_open_forks |= ATTRBIT_ROPEN;
     }
 
-    /* ****************************************** */
-    /* open the resource fork if SFM */
-sfm:
-    if (ad->ad_flags != AD_VERSION1_SFM) {
-        return 0;
-    }
+    va_start(args, adflags);
+    if (adflags & ADFLAGS_CREATE)
+        mode = va_arg(args, mode_t);
+    va_end(args);
 
-    if ((adflags & ADFLAGS_DIR)) {
-        /* no resource fork for directories / volumes XXX it's false! */
-        return 0;
+    if (adflags & ADFLAGS_DF) {
+        EC_ZERO( ad_open_df(path, adflags, mode, ad) );
     }
 
-    /* untrue yet but ad_close will decremente it*/
-    ad->ad_resource_fork.adf_refcount++;
-
-    if (ad_reso_fileno(ad) != -1) { /* the file is already open */
-        if ((oflags & ( O_RDWR | O_WRONLY)) &&
-            !(ad->ad_resource_fork.adf_flags & ( O_RDWR | O_WRONLY))) {
-
-            ad_close( ad, open_df | ADFLAGS_HF);
-            errno = EACCES;
-            return -1;
-        }
-        return 0;
+    if (adflags & ADFLAGS_HF) {
+        EC_ZERO( ad_open_hf(path, adflags, mode, ad) );
     }
 
-    ad_p = ad->ad_ops->ad_path( path, ADFLAGS_RF );
-
-    admode = mode;
-    st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
-
-    if ((ad->ad_options & ADVOL_UNIXPRIV)) {
-        admode = mode;
+    if (adflags & ADFLAGS_RF) {
+        EC_ZERO( ad_open_rf(path, adflags, mode, ad) );
     }
 
-    hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
-    ad->ad_resource_fork.adf_fd = open( ad_p, hoflags, admode );
-
-    if (ad->ad_resource_fork.adf_fd < 0 ) {
-        if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
-            hoflags = oflags;
-            ad->ad_resource_fork.adf_fd =open( ad_p, hoflags, admode );
-        }
+    if (adflags & ADFLAGS_CHECK_OF) {
+        ad->ad_open_forks |= ad_openforks(ad, ad->ad_open_forks);
     }
 
-    if ( ad->ad_resource_fork.adf_fd < 0) {
-        int err = errno;
+EC_CLEANUP:
+    LOG(log_debug, logtype_default,
+        "ad_open(\"%s\"): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
+        fullpathname(path), ret,
+        ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
+        ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
+        ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
 
-        ad_close( ad, adflags );
-        errno = err;
-        return -1;
-    }
-    adf_lock_init(&ad->ad_resource_fork);
-    AD_SET(ad->ad_resource_fork.adf_off);
-    ad->ad_resource_fork.adf_flags = hoflags;
-    if ((oflags & O_CREAT) && !st_invalid) {
-        /* just created, set owner if admin (root) */
-        ad_chown(ad_p, &st_dir);
-    }
-    else if (!fstat(ad->ad_resource_fork.adf_fd, &st_meta)) {
-        ad->ad_rlen = st_meta.st_size;
-    }
-    return 0 ;
+    EC_EXIT;
 }
 
 /*!
@@ -1530,29 +1679,19 @@ sfm:
  *
  * @param name  name of file/dir
  * @param flags ADFLAGS_DIR: name is a directory \n
- *              ADFLAGS_CREATE: force creation of header file, but only as user, not as root\n
- *              ADFLAGS_OPENFORKS: test if name is open by another afpd process
+ *              ADFLAGS_CHECK_OF: test if name is open by us or another afpd process
  *
  * @param adp   pointer to struct adouble
- *
- * @note caller MUST pass ADFLAGS_DIR for directories. Whether ADFLAGS_CREATE really creates
- *       a adouble file depends on various other volume options, eg. ADVOL_CACHE
  */
 int ad_metadata(const char *name, int flags, struct adouble *adp)
 {
     uid_t uid;
-    int   ret, err, dir;
-    int   create = O_RDONLY;
+    int   ret, err, oflags;
 
-    dir = flags & ADFLAGS_DIR;
+    /* Sanitize flags */
+    oflags = (flags & (ADFLAGS_CHECK_OF | ADFLAGS_DIR)) | ADFLAGS_HF | ADFLAGS_RDONLY;    
 
-    /* Check if we shall call ad_open with O_CREAT */
-    if ( (adp->ad_options & ADVOL_CACHE)
-         && ! (adp->ad_options & ADVOL_NOADOUBLE)
-         && (flags & ADFLAGS_CREATE) ) {
-        create = O_CREAT | O_RDWR;
-    }
-    if ((ret = ad_open(name, ADFLAGS_HF | dir, create, 0666, adp)) < 0 && errno == EACCES) {
+    if ((ret = ad_open(adp, name, oflags)) < 0 && errno == EACCES) {
         uid = geteuid();
         if (seteuid(0)) {
             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
@@ -1560,7 +1699,7 @@ int ad_metadata(const char *name, int flags, struct adouble *adp)
             return -1;
         }
         /* we are root open read only */
-        ret = ad_open(name, ADFLAGS_HF|ADFLAGS_RDONLY| dir, O_RDONLY, 0, adp);
+        ret = ad_open(adp, name, oflags);
         err = errno;
         if ( seteuid(uid) < 0) {
             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
@@ -1569,15 +1708,6 @@ int ad_metadata(const char *name, int flags, struct adouble *adp)
         errno = err;
     }
 
-    if (!ret && (ADFLAGS_OPENFORKS & flags)) {
-        /*
-          we need to check if the file is open by another process.
-          it's slow so we only do it if we have to:
-          - it's requested.
-          - we don't already have the answer!
-        */
-        adp->ad_open_forks |= ad_openforks(adp, adp->ad_open_forks);
-    }
     return ret;
 }
 
@@ -1602,6 +1732,7 @@ int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
     }
 
     if (dirfd != -1) {
+
         if (fchdir(cwdfd) != 0) {
             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
             exit(EXITERR_SYS);
@@ -1616,118 +1747,108 @@ exit:
 
 }
 
-/* ----------------------------------- */
-static int new_rfork(const char *path, struct adouble *ad, int adflags)
+int ad_refresh(const char *path, struct adouble *ad)
 {
-    const struct entry  *eid;
-    u_int16_t           ashort;
-    struct stat         st;
-
-    ad->ad_magic = AD_MAGIC;
-    ad->ad_version = ad->ad_flags & 0x0f0000;
-    if (!ad->ad_version) {
-        ad->ad_version = AD_VERSION;
-    }
-
-    memset(ad->ad_filler, 0, sizeof( ad->ad_filler ));
-    memset(ad->ad_data, 0, sizeof(ad->ad_data));
+    switch (ad->ad_vers) {
+    case AD_VERSION2:
+        if (ad_meta_fileno(ad) == -1)
+            return -1;
+        return ad->ad_ops->ad_header_read(NULL, ad, NULL);
+        break;
+    case AD_VERSION_EA:
+#ifdef HAVE_EAFD
+        if (AD_META_OPEN(ad)) {
+            if (ad_data_fileno(ad) == -1)
+                return -1;
+            // TODO: read meta EA
+        }
 
-#if AD_VERSION == AD_VERSION2
-    if (ad->ad_flags == AD_VERSION2)
-        eid = entry_order2;
-    else if (ad->ad_flags == AD_VERSION2_OSX)
-        eid = entry_order_osx;
-    else  if (ad->ad_flags == AD_VERSION1_SFM) {
-        ad->ad_magic = SFM_MAGIC;
-        eid = entry_order_sfm;
-    }
-    else
+        if (AD_RSRC_OPEN(ad)) {
+            if (ad_reso_fileno(ad) == -1)
+                return -1;
+            struct stat st;
+            if (fstat(ad_reso_fileno(ad), &st) == -1)
+                return -1;
+            ad->ad_rlen = st.st_size;
+        }
+#else
+        if (AD_META_OPEN(ad)) {
+            if (ad_data_fileno(ad) == -1)
+                return -1;
+            // TODO: read meta EA
+        }
+        if (AD_RSRC_OPEN(ad)) {
+            if (ad_reso_fileno(ad) == -1)
+                return -1;
+            if (ad_header_read_osx(path, ad, NULL) < 0)
+                return -1;
+        }
 #endif
-        eid = entry_order1;
-
-    while (eid->id) {
-        ad->ad_eid[eid->id].ade_off = eid->offset;
-        ad->ad_eid[eid->id].ade_len = eid->len;
-        eid++;
-    }
-
-    /* put something sane in the directory finderinfo */
-    if ((adflags & ADFLAGS_DIR)) {
-        /* set default view */
-        ashort = htons(FINDERINFO_CLOSEDVIEW);
-        memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF,
-               &ashort, sizeof(ashort));
-    } else {
-        /* set default creator/type fields */
-        memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
-        memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
-    }
-
-    /* make things invisible */
-    if ((ad->ad_options & ADVOL_INVDOTS) && !(adflags & ADFLAGS_CREATE) &&
-        (*path == '.') && strcmp(path, ".") && strcmp(path, ".."))
-    {
-        ashort = htons(ATTRBIT_INVISIBLE);
-        ad_setattr(ad, ashort);
-        ashort = htons(FINDERINFO_INVISIBLE);
-        memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
-    }
-
-    if (lstat(path, &st) < 0) {
+        return ad->ad_ops->ad_header_read(path, ad, NULL);
+        break;
+    default:
         return -1;
+        break;
     }
 
-    /* put something sane in the date fields */
-    ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
-    ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
-    ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
-    ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
-    return 0;
-}
-
-/* to do this with mmap, we need the hfs fs to understand how to mmap
-   header files. */
-int ad_refresh(struct adouble *ad)
-{
-
-    if (ad_meta_fileno(ad) < 0)
-        return -1;
-
-    return ad->ad_ops->ad_header_read(ad, NULL);
 }
 
-int ad_openat(int dirfd,  /* dir fd openat like */
+int ad_openat(struct adouble  *ad,
+              int dirfd,  /* dir fd openat like */
               const char *path,
-              int adflags,
-              int oflags,
-              int mode,
-              struct adouble  *ad)
+              int adflags, ...)
 {
-    int ret = 0;
+    EC_INIT;
     int cwdfd = -1;
+    va_list args;
+    mode_t mode;
 
     if (dirfd != -1) {
-        if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
-            ret = -1;
-            goto exit;
-        }
+        if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0))
+            EC_FAIL;
     }
 
-    if (ad_open(path, adflags, oflags, mode, ad) < 0) {
-        ret = -1;
-        goto exit;
-    }
+    va_start(args, adflags);
+    if (adflags & ADFLAGS_CREATE)
+        mode = va_arg(args, mode_t);
+    va_end(args);
+
+    EC_NEG1( ad_open(ad, path, adflags, mode) );
 
     if (dirfd != -1) {
         if (fchdir(cwdfd) != 0) {
-            LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
-            exit(EXITERR_SYS);
+            AFP_PANIC("ad_openat: cant chdir back");
         }
     }
 
-exit:
+EC_CLEANUP:
     if (cwdfd != -1)
         close(cwdfd);
 
     return ret;
 }
+
+/* build a resource fork mode from the data fork mode:
+ * remove X mode and extend header to RW if R or W (W if R for locking),
+ */
+mode_t ad_hf_mode(mode_t mode)
+{
+    mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
+    /* fnctl lock need write access */
+    if ((mode & S_IRUSR))
+        mode |= S_IWUSR;
+    if ((mode & S_IRGRP))
+        mode |= S_IWGRP;
+    if ((mode & S_IROTH))
+        mode |= S_IWOTH;
+
+    /* if write mode set add read mode */
+    if ((mode & S_IWUSR))
+        mode |= S_IRUSR;
+    if ((mode & S_IWGRP))
+        mode |= S_IRGRP;
+    if ((mode & S_IWOTH))
+        mode |= S_IROTH;
+
+    return mode;
+}
diff --git a/libatalk/adouble/ad_private.h b/libatalk/adouble/ad_private.h
deleted file mode 100644 (file)
index 82a11aa..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * $Id: ad_private.h,v 1.6 2008-12-03 18:35:44 didg Exp $
- */
-
-#ifndef LIBATALK_ADOUBLE_AD_PRIVATE_H
-#define LIBATALK_ADOUBLE_AD_PRIVATE_H 1
-
-#include <atalk/adouble.h>
-
-#ifndef MAP_FAILED
-#define MAP_FAILED ((void *) -1)
-#endif /* ! MAP_FAILED */
-
-/* this is so that we can keep lists of fds referencing the same file
- * around. that way, we can honor locks created by the same process
- * with the same file. */
-
-#define adf_lock_init(a) do { \
-       (a)->adf_lockmax = (a)->adf_lockcount = 0; \
-       (a)->adf_excl = 0;(a)->adf_lock = NULL; \
-} while (0)
-
-#define adf_lock_free(a) do { \
-    int i;\
-       if (!(a)->adf_lock) \
-               break; \
-        for (i = 0; i < (a)->adf_lockcount; i++) {\
-            adf_lock_t *lock = (a)->adf_lock + i;\
-            if (--(*lock->refcount) < 1)free(lock->refcount); \
-        }\
-       free((a)->adf_lock); \
-       adf_lock_init(a); \
-} while (0)
-
-#endif /* libatalk/adouble/ad_private.h */
index 17c2361faa99a775fef26c000bfb1ff82a8b2675..ed7c0cb4da2b182b93a7c203e615403751682bb0 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: ad_read.c,v 1.10 2010-02-10 14:05:37 franklahm Exp $
- *
  * Copyright (c) 1990,1991 Regents of The University of Michigan.
  * All Rights Reserved.
  *
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include <atalk/adouble.h>
 #include <string.h>
 #include <sys/param.h>
+#include <errno.h>
+#include <stdlib.h>
 
-#ifndef MIN
-#define MIN(a,b)    ((a)<(b)?(a):(b))
-#endif /* ! MIN */
+#include <atalk/adouble.h>
+#include <atalk/ea.h>
+#include <atalk/logger.h>
+#include <atalk/util.h>
 
 ssize_t adf_pread(struct ad_fd *ad_fd, void *buf, size_t count, off_t offset)
 {
@@ -59,9 +59,11 @@ ssize_t adf_pread(struct ad_fd *ad_fd, void *buf, size_t count, off_t offset)
 /* XXX: locks have to be checked before each stream of consecutive
  *      ad_reads to prevent a denial in the middle from causing
  *      problems. */
-ssize_t ad_read( struct adouble *ad, const u_int32_t eid, off_t off, char *buf, const size_t buflen)
+ssize_t ad_read( struct adouble *ad, const uint32_t eid, off_t off, char *buf, const size_t buflen)
 {
     ssize_t     cc;
+    ssize_t     rlen;
+    off_t r_off = 0;
 
     /* We're either reading the data fork (and thus the data file)
      * or we're reading anything else (and thus the header file). */
@@ -77,32 +79,22 @@ ssize_t ad_read( struct adouble *ad, const u_int32_t eid, off_t off, char *buf,
             cc = adf_pread(&ad->ad_data_fork, buf, buflen, off);
         }
     } else {
-        off_t r_off;
-
-        if ( ad_reso_fileno( ad ) == -1 ) {
+        if (! AD_RSRC_OPEN(ad))
             /* resource fork is not open ( cf etc/afp/fork.c) */
             return 0;
+
+        if (ad->ad_vers == AD_VERSION_EA) {
+#ifdef HAVE_EAFD
+            r_off = off;
+#else
+            r_off = off + ADEDOFF_RFORK_OSX;
+#endif
+        } else {
+            r_off = ad_getentryoff(ad, eid) + off;
         }
-        r_off = ad_getentryoff(ad, eid) + off;
 
-        if (( cc = adf_pread( &ad->ad_resource_fork, buf, buflen, r_off )) < 0 ) {
+        if (( cc = adf_pread( &ad->ad_resource_fork, buf, buflen, r_off )) < 0 )
             return( -1 );
-        }
-        /*
-         * We've just read in bytes from the disk that we read earlier
-         * into ad_data. If we're going to write this buffer out later,
-         * we need to update ad_data.
-         * FIXME : always false?
-         */
-        if (r_off < ad_getentryoff(ad, ADEID_RFORK)) {
-            if ( ad->ad_resource_fork.adf_flags & O_RDWR ) {
-                memcpy(buf, ad->ad_data + r_off,
-                       MIN(sizeof( ad->ad_data ) - r_off, cc));
-            } else {
-                memcpy(ad->ad_data + r_off, buf,
-                       MIN(sizeof( ad->ad_data ) - r_off, cc));
-            }
-        }
     }
 
     return( cc );
index 0e7b27835e69bc3f6dd3de803a07c091f3be2a46..3cb28e7802c935db16ab4acf80645db577b43816 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: ad_sendfile.c,v 1.11 2010-01-21 14:14:49 didg Exp $
- *
  * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
  * All rights reserved. See COPYRIGHT.
  *
 #endif /* HAVE_CONFIG_H */
 
 #ifdef WITH_SENDFILE
-
-#include <atalk/adouble.h>
-
 #include <stdio.h>
-
 #include <sys/socket.h>
 #include <sys/uio.h>
-
 #include <errno.h>  
 
+#include <atalk/adouble.h>
 #include <atalk/logger.h>
-#include "ad_private.h"
+
+#include "ad_lock.h"
 
 #if defined(SENDFILE_FLAVOR_LINUX)
 #include <sys/sendfile.h>
index 0b45babdb954f6342721e4ba7093ea598590e6d8..337ff6ed3d5f07075ff286dfa58964488c9158f4 100644 (file)
@@ -15,7 +15,7 @@
 #include <atalk/logger.h>
 #include <atalk/adouble.h>
 
-off_t ad_size(const struct adouble *ad, const u_int32_t eid)
+off_t ad_size(const struct adouble *ad, const uint32_t eid)
 {
   if (eid == ADEID_DFORK) {
     struct stat st;
index 3031f6390ffa6dc485ba49dc10c55feebd849516..bfed9b400f27f8fd577310bc4052a76e2e6a5017 100644 (file)
@@ -7,16 +7,18 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include <atalk/adouble.h>
-
+#include <stdlib.h>
 #include <string.h>
 #include <sys/param.h>
 #include <errno.h>
 
-
-#ifndef MIN
-#define MIN(a,b)       ((a)<(b)?(a):(b))
-#endif /* ! MIN */
+#include <atalk/adouble.h>
+#include <atalk/ea.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
+#include <atalk/logger.h>
+#include <atalk/util.h>
+#include <atalk/errchk.h>
 
 /* XXX: locking has to be checked before each stream of consecutive
  *      ad_writes to prevent a lock in the middle from causing problems. 
@@ -45,48 +47,56 @@ ssize_t adf_pwrite(struct ad_fd *ad_fd, const void *buf, size_t count, off_t off
 }
 
 /* end is always 0 */
-ssize_t ad_write(struct adouble *ad, const u_int32_t eid, off_t off, const int end, const char *buf, const size_t buflen)
+ssize_t ad_write(struct adouble *ad, uint32_t eid, off_t off, int end, const char *buf, size_t buflen)
 {
+    EC_INIT;
     struct stat                st;
     ssize_t            cc;
+    size_t roundup;
+    off_t    r_off;
 
-    if (ad_data_fileno(ad) == -2) {
-        /* It's a symlink */
+    if (ad_data_fileno(ad) == AD_SYMLINK) {
         errno = EACCES;
         return -1;
     }
+
+    LOG(log_debug, logtype_default, "ad_write: off: %ju, size: %zu, eabuflen: %zu",
+        (uintmax_t)off, buflen, ad->ad_rlen);
     
     if ( eid == ADEID_DFORK ) {
-       if ( end ) {
-           if ( fstat( ad_data_fileno(ad), &st ) < 0 ) {
-               return( -1 );
-           }
-           off = st.st_size - off;
-       }
-       cc = adf_pwrite(&ad->ad_data_fork, buf, buflen, off);
+        if ( end ) {
+            if ( fstat( ad_data_fileno(ad), &st ) < 0 ) {
+                return( -1 );
+            }
+            off = st.st_size - off;
+        }
+        cc = adf_pwrite(&ad->ad_data_fork, buf, buflen, off);
     } else if ( eid == ADEID_RFORK ) {
-        off_t    r_off;
-
-       if ( end ) {
-           if ( fstat( ad_data_fileno(ad), &st ) < 0 ) {
-               return( -1 );
-           }
-           off = st.st_size - off -ad_getentryoff(ad, eid);
-       }
-       r_off = ad_getentryoff(ad, eid) + off;
-       cc = adf_pwrite(&ad->ad_resource_fork, buf, buflen, r_off);
-
-       /* sync up our internal buffer  FIXME always false? */
-       if (r_off < ad_getentryoff(ad, ADEID_RFORK)) {
-           memcpy(ad->ad_data + r_off, buf, MIN(sizeof(ad->ad_data) -r_off, cc));
+        if (end) {
+            if (fstat( ad_reso_fileno(ad), &st ) < 0)
+                return(-1);
+            off = st.st_size - off - ad_getentryoff(ad, eid);
         }
-        if ( ad->ad_rlen < off + cc ) {
-             ad->ad_rlen = off + cc;
+        if (ad->ad_vers == AD_VERSION_EA) {
+#ifdef HAVE_EAFD
+            r_off = off;
+#else
+            r_off = ADEDOFF_RFORK_OSX + off;
+#endif
+        } else {
+            r_off = ad_getentryoff(ad, eid) + off;
         }
-    }
-    else {
+        cc = adf_pwrite(&ad->ad_resource_fork, buf, buflen, r_off);
+
+        if ( ad->ad_rlen < off + cc )
+            ad->ad_rlen = off + cc;
+    } else {
         return -1; /* we don't know how to write if it's not a ressource or data fork */
     }
+
+EC_CLEANUP:
+    if (ret != 0)
+        return ret;
     return( cc );
 }
 
@@ -151,19 +161,121 @@ char            c = 0;
 /* ------------------------ */
 int ad_rtruncate( struct adouble *ad, const off_t size)
 {
-    if ( sys_ftruncate( ad_reso_fileno(ad),
-           size + ad->ad_eid[ ADEID_RFORK ].ade_off ) < 0 ) {
-       return -1;
-    }
-    ad->ad_rlen = size;    
+    EC_INIT;
 
-    return 0;
+#ifndef HAVE_EAFD
+    if (ad->ad_vers == AD_VERSION_EA && size == 0)
+        EC_NEG1( unlink(ad->ad_ops->ad_path(ad->ad_name, 0)) );
+    else
+#endif
+        EC_NEG1( sys_ftruncate(ad_reso_fileno(ad), size + ad->ad_eid[ ADEID_RFORK ].ade_off) );
+
+EC_CLEANUP:
+    if (ret == 0)
+        ad->ad_rlen = size;    
+    else
+        LOG(log_error, logtype_default, "ad_rtruncate(\"%s\"): %s",
+            fullpathname(ad->ad_name), strerror(errno));
+    EC_EXIT;
 }
 
 int ad_dtruncate(struct adouble *ad, const off_t size)
 {
     if (sys_ftruncate(ad_data_fileno(ad), size) < 0) {
-      return -1;
+        LOG(log_error, logtype_default, "sys_ftruncate(fd: %d): %s",
+            ad_data_fileno(ad), strerror(errno));
+        return -1;
+    }
+
+    return 0;
+}
+
+/* ----------------------- */
+static int copy_all(const int dfd, const void *buf,
+                               size_t buflen)
+{
+    ssize_t cc;
+
+    while (buflen > 0) {
+        if ((cc = write(dfd, buf, buflen)) < 0) {
+            switch (errno) {
+            case EINTR:
+                continue;
+            default:
+                return -1;
+            }
+        }
+        buflen -= cc;
     }
+
     return 0;
 }
+
+/* -------------------------- 
+ * copy only the fork data stream
+*/
+int copy_fork(int eid, struct adouble *add, struct adouble *ads)
+{
+    ssize_t cc;
+    int     err = 0;
+    char    filebuf[8192];
+    int     sfd, dfd;
+
+    if (eid == ADEID_DFORK) {
+        sfd = ad_data_fileno(ads);
+        dfd = ad_data_fileno(add);
+    }
+    else {
+        sfd = ad_reso_fileno(ads);
+        dfd = ad_reso_fileno(add);
+    }        
+
+    if ((off_t)-1 == lseek(sfd, ad_getentryoff(ads, eid), SEEK_SET))
+       return -1;
+
+    if ((off_t)-1 == lseek(dfd, ad_getentryoff(add, eid), SEEK_SET))
+       return -1;
+       
+#if 0 /* ifdef SENDFILE_FLAVOR_LINUX */
+    /* doesn't work With 2.6 FIXME, only check for EBADFD ? */
+    off_t   offset = 0;
+    size_t  size;
+    struct stat         st;
+    #define BUF 128*1024*1024
+
+    if (fstat(sfd, &st) == 0) {
+        
+        while (1) {
+            if ( offset >= st.st_size) {
+               return 0;
+            }
+            size = (st.st_size -offset > BUF)?BUF:st.st_size -offset;
+            if ((cc = sys_sendfile(dfd, sfd, &offset, size)) < 0) {
+                switch (errno) {
+                case ENOSYS:
+                case EINVAL:  /* there's no guarantee that all fs support sendfile */
+                    goto no_sendfile;
+                default:
+                    return -1;
+                }
+            }
+        }
+    }
+    no_sendfile:
+    lseek(sfd, offset, SEEK_SET);
+#endif 
+
+    while (1) {
+        if ((cc = read(sfd, filebuf, sizeof(filebuf))) < 0) {
+            if (errno == EINTR)
+                continue;
+            err = -1;
+            break;
+        }
+
+        if (!cc || ((err = copy_all(dfd, filebuf, cc)) < 0)) {
+            break;
+        }
+    }
+    return err;
+}
diff --git a/libatalk/asp/.gitignore b/libatalk/asp/.gitignore
deleted file mode 100644 (file)
index 2ff33a9..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Makefile
-Makefile.in
-*.lo
-*.la
-.deps
-.libs
-.gitignore
-asp_attn.o asp_close.o asp_cmdreply.o asp_getreq.o asp_getsess.o asp_init.o asp_shutdown.o asp_tickle.o asp_write.o
diff --git a/libatalk/asp/Makefile.am b/libatalk/asp/Makefile.am
deleted file mode 100644 (file)
index ae83084..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-# Makefile.am for libatalk/asp/
-
-AM_CFLAGS = -I$(top_srcdir)
-
-noinst_LTLIBRARIES = libasp.la
-
-libasp_la_SOURCES = asp_attn.c asp_close.c asp_cmdreply.c asp_getreq.c asp_getsess.c asp_init.c asp_write.c asp_shutdown.c asp_tickle.c 
-
-noinst_HEADERS = asp_child.h
diff --git a/libatalk/asp/asp_attn.c b/libatalk/asp/asp_attn.c
deleted file mode 100644 (file)
index 1c2a8fa..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * $Id: asp_attn.c,v 1.7 2002-12-04 10:59:37 didg Exp $
- * Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu)
- * All rights reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <string.h>
-#include <atalk/logger.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <sys/socket.h>
-
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-#include <atalk/afp.h>
-
-/* attentions can get sent at any time. as a consequence, we don't
- * want to touch anything that might be used elsewhere. */
-int asp_attention(ASP asp, AFPUserBytes flags)
-{
-    char cmds[ASP_HDRSIZ], data[ASP_HDRSIZ];
-    struct sockaddr_at  sat;
-    struct atp_block   atpb;
-    struct iovec       iov[ 1 ];
-
-    cmds[0] = ASPFUNC_ATTN;
-    cmds[1] = asp->asp_sid;
-    flags = htons(flags);
-    memcpy(cmds + 2, &flags, sizeof(flags));
-
-    sat = asp->asp_sat;
-    sat.sat_port = asp->asp_wss;
-    atpb.atp_saddr = &sat;
-    atpb.atp_sreqdata = cmds;
-    atpb.atp_sreqdlen = sizeof(cmds);
-    atpb.atp_sreqto = 2;
-    atpb.atp_sreqtries = 5;
-
-    if ( atp_sreq( asp->asp_atp, &atpb, 1, 0 ) < 0 ) {
-       LOG(log_error, logtype_default, "atp_sreq: %s", strerror(errno) );
-       return 0;
-    }
-
-    iov[ 0 ].iov_base = data;
-    iov[ 0 ].iov_len = sizeof( data );
-    atpb.atp_rresiov = iov;
-    atpb.atp_rresiovcnt = sizeof( iov )/sizeof( iov[ 0 ] );
-    if ( atp_rresp( asp->asp_atp, &atpb ) < 0 ) {
-       LOG(log_error, logtype_default, "atp_rresp: %s", strerror(errno) );
-       return 0;
-    }
-
-    return 1;
-}
diff --git a/libatalk/asp/asp_child.h b/libatalk/asp/asp_child.h
deleted file mode 100644 (file)
index 081cd6f..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * $Id: asp_child.h,v 1.2 2001-06-29 14:14:46 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef _ASP_CHILD_H
-#define _ASP_CHILD_H 1
-
-struct asp_child {
-    int                        ac_pid;
-    int                        ac_state;
-    struct sockaddr_at ac_sat;
-};
-
-#define ACSTATE_DEAD   0
-#define ACSTATE_OK     1
-#define ACSTATE_BAD    7
-
-#endif /* _ASP_CHILD_H */
diff --git a/libatalk/asp/asp_close.c b/libatalk/asp/asp_close.c
deleted file mode 100644 (file)
index 6187825..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * $Id: asp_close.c,v 1.5 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/socket.h>
-
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-
-int asp_close(ASP asp)
-{
-    struct atp_block   atpb;
-    struct iovec       iov[ 1 ];
-    int err = 0;
-
-    memset(asp->commands, 0, sizeof(u_int32_t));
-
-    atpb.atp_saddr = &asp->asp_sat;
-    iov[ 0 ].iov_base = asp->commands;
-    iov[ 0 ].iov_len = sizeof(u_int32_t);
-    atpb.atp_sresiov = iov;
-    atpb.atp_sresiovcnt = 1;
-
-    if (atp_sresp( asp->asp_atp, &atpb ) < 0)
-      err = -1;
-
-    if (atp_close( asp->asp_atp ) < 0)
-      err = -1;
-
-    free( asp );
-    return err;
-}
diff --git a/libatalk/asp/asp_cmdreply.c b/libatalk/asp/asp_cmdreply.c
deleted file mode 100644 (file)
index f3a3fd1..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * $Id: asp_cmdreply.c,v 1.5 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <sys/socket.h>
-
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-
-#if defined(BSD) || defined(BSD4_3)
-#define memmove(a, b, n)   bcopy((b), (a), (n))
-#endif /* BSD || BSD4_3 */
-
-int asp_cmdreply(ASP asp, int result)
-{
-    struct iovec       iov[ ASP_MAXPACKETS ];
-    struct atp_block   atpb;
-    int                        iovcnt, buflen;
-    char                *buf;
-
-    /* unpack data into a format that atp likes. it needs to get
-     * 4-byte headers prepended before each ASP_CMDSIZ chunk. */
-    buf = (char *) asp->data;
-    buflen = asp->datalen;
-    asp->write_count += buflen;
-    result = htonl(result);
-
-    iovcnt = 0;
-    do {
-       iov[ iovcnt ].iov_base = buf;
-       memmove(buf + ASP_HDRSIZ, buf, buflen);
-
-       if ( iovcnt == 0 ) {
-           memcpy( iov[ iovcnt ].iov_base, &result, ASP_HDRSIZ );
-       } else {
-           memset( iov[ iovcnt ].iov_base, 0, ASP_HDRSIZ );
-       }
-
-       if ( buflen > ASP_CMDSIZ ) {
-         buf += ASP_CMDMAXSIZ;
-         buflen -= ASP_CMDSIZ;
-         iov[ iovcnt ].iov_len = ASP_CMDMAXSIZ;
-       } else {
-         iov[ iovcnt ].iov_len = buflen + ASP_HDRSIZ;
-         buflen = 0;
-       }
-       iovcnt++;
-    } while ( buflen > 0 );
-
-    atpb.atp_saddr = &asp->asp_sat;
-    atpb.atp_sresiov = iov;
-    atpb.atp_sresiovcnt = iovcnt;
-    if ( atp_sresp( asp->asp_atp, &atpb ) < 0 ) {
-       return( -1 );
-    }
-    asp->asp_seq++;
-
-    return( 0 );
-}
diff --git a/libatalk/asp/asp_getreq.c b/libatalk/asp/asp_getreq.c
deleted file mode 100644 (file)
index 211c55d..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * $Id: asp_getreq.c,v 1.3 2001-06-29 14:14:46 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- *
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-
-int asp_getrequest(ASP asp)
-{
-    struct atp_block   atpb;
-    u_int16_t          seq;
-
-    asp->asp_sat.sat_port = ATADDR_ANYPORT;
-    atpb.atp_saddr = &asp->asp_sat;
-    atpb.atp_rreqdata = asp->cmdbuf;
-    atpb.atp_rreqdlen = sizeof(asp->cmdbuf);
-
-    if ( atp_rreq( asp->asp_atp, &atpb ) < 0 ) {
-       return( -1 );
-    }
-
-    asp->cmdlen = atpb.atp_rreqdlen - 4;
-    asp->read_count += asp->cmdlen;
-    memcpy( &seq, asp->cmdbuf + 2, sizeof(seq));
-    seq = ntohs( seq );
-
-    if ((asp->cmdbuf[0] != ASPFUNC_CLOSE) && (seq != asp->asp_seq)) {
-       return( -2 );
-    }
-    if ( asp->cmdbuf[1] != asp->asp_sid ) {
-       return( -3 );
-    }
-
-    return( asp->cmdbuf[0] ); /* the command */
-}
diff --git a/libatalk/asp/asp_getsess.c b/libatalk/asp/asp_getsess.c
deleted file mode 100644 (file)
index 5a1d585..0000000
+++ /dev/null
@@ -1,349 +0,0 @@
-/*
- * $Id: asp_getsess.c,v 1.9 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1996 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <signal.h>
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/socket.h>
-#include <sys/param.h>
-#ifdef HAVE_SYS_WAIT_H
-#include <sys/wait.h>
-#endif /* HAVE_SYS_WAIT_H */
-
-#include <netatalk/at.h>
-#include <atalk/logger.h>
-#include <atalk/compat.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-#include <atalk/server_child.h>
-
-#include "asp_child.h"
-
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
-#endif /* ! WEXITSTATUS */
-#ifndef WIFEXITED
-#define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
-#endif /* ! WIFEXITED */
-
-#ifndef MIN
-#define MIN(a,b)     ((a)<(b)?(a):(b))
-#endif /* ! MIN */
-
-static ASP server_asp;
-static struct server_child *children = NULL;
-static struct asp_child    **asp_ac = NULL;
-
-/* send tickles and check tickle status of connections
- * thoughts on using a hashed list:
- * + child_cleanup, finding slots 
- * - tickle_handler, freeing, tickles 
- * if setup for a large number of connections,
- * + space: if actual connections < potential
- * - space: actual connections ~ potential
- */
-static void tickle_handler(int sig _U_)
-{
-  int sid;
-  
-  /* check status */
-  for (sid = 0; sid < children->nsessions; sid++) {
-    if (asp_ac[sid] == NULL || asp_ac[sid]->ac_state == ACSTATE_DEAD) 
-      continue;
-    
-    if (++asp_ac[sid]->ac_state >= ACSTATE_BAD) {
-      /* kill. if already dead, just continue */
-      if (kill( asp_ac[ sid ]->ac_pid, SIGTERM) == 0)
-       LOG(log_info, logtype_default, "asp_alrm: %d timed out",
-               asp_ac[ sid ]->ac_pid );
-
-      asp_ac[ sid ]->ac_state = ACSTATE_DEAD;
-      continue;
-    }
-
-    /* send off a tickle */
-    asp_tickle(server_asp, sid, &asp_ac[sid]->ac_sat);
-  }
-}
-
-static void child_cleanup(const pid_t pid)
-{
-  int i;
-
-  for (i = 0; i < children->nsessions; i++)
-    if (asp_ac[i] && (asp_ac[i]->ac_pid == pid)) {
-      asp_ac[i]->ac_state = ACSTATE_DEAD;
-      break;
-    }
-}
-
-
-/* kill children */
-void asp_kill(int sig)
-{
-  if (children) 
-    server_child_kill(children, CHILD_ASPFORK, sig);
-}
-
-void asp_stop_tickle(void)
-{
-    if (server_asp && server_asp->inited) {
-       static const struct itimerval timer = {{0, 0}, {0, 0}};
-       
-       setitimer(ITIMER_REAL, &timer, NULL);
-    }
-}
-
-/*
- * This call handles open, tickle, and getstatus requests. On a
- * successful open, it forks a child process. 
- * It returns an ASP to the child and parent and NULL if there is
- * an error.
- */
-static void set_asp_ac(int sid, struct asp_child *tmp);
-
-ASP asp_getsession(ASP asp, server_child *server_children, 
-                  const int tickleval)
-{
-    struct sigaction    action;
-    struct itimerval    timer;
-    struct sockaddr_at  sat;
-    struct atp_block    atpb;
-    ATP                 atp;
-    struct iovec        iov[ 8 ];
-    pid_t               pid;
-    int                 i, iovcnt, sid;
-    u_int16_t           asperr;
-    char                *buf;
-    int                 buflen;
-
-    if (!asp->inited) {
-      if (!(children = server_children))
-       return NULL;
-
-      /* only calloc once */
-      if (!asp_ac && (asp_ac = (struct asp_child **) 
-          calloc(server_children->nsessions, sizeof(struct asp_child *)))
-          == NULL)
-       return NULL;
-
-      server_asp = asp;
-
-      /* install cleanup pointer */
-      server_child_setup(children, CHILD_ASPFORK, child_cleanup);
-
-      /* install tickle handler 
-       * we are the parent process
-       */
-      memset(&action, 0, sizeof(action));
-      action.sa_handler = tickle_handler;
-      sigemptyset(&action.sa_mask);
-      sigaddset(&action.sa_mask, SIGHUP);
-      sigaddset(&action.sa_mask, SIGTERM);
-      sigaddset(&action.sa_mask, SIGCHLD);
-      action.sa_flags = SA_RESTART;
-
-      timer.it_interval.tv_sec = timer.it_value.tv_sec = tickleval;
-      timer.it_interval.tv_usec = timer.it_value.tv_usec = 0;
-      if ((sigaction(SIGALRM, &action, NULL) < 0) ||
-         (setitimer(ITIMER_REAL, &timer, NULL) < 0)) {
-       free(asp_ac);
-       server_asp = NULL;
-       asp_ac = NULL;
-       return NULL;
-      }
-
-      asp->inited = 1;
-    }
-                   
-    memset( &sat, 0, sizeof( struct sockaddr_at ));
-#ifdef BSD4_4
-    sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    sat.sat_family = AF_APPLETALK;
-    sat.sat_addr.s_net = ATADDR_ANYNET;
-    sat.sat_addr.s_node = ATADDR_ANYNODE;
-    sat.sat_port = ATADDR_ANYPORT;
-    atpb.atp_saddr = &sat;
-    atpb.atp_rreqdata = asp->cmdbuf;
-    atpb.atp_rreqdlen = sizeof( asp->cmdbuf );
-    while ( atp_rreq( asp->asp_atp, &atpb ) < 0 ) {
-      if ( errno == EINTR || errno == EAGAIN ) {
-       continue;
-      }
-      return( NULL );
-    }
-    
-    switch ( asp->cmdbuf[ 0 ] ) {
-    case ASPFUNC_TICKLE:
-      sid = asp->cmdbuf[1];
-      if ((asp_ac[sid] != NULL) && (asp_ac[sid]->ac_state != ACSTATE_DEAD))
-       asp_ac[sid]->ac_state = ACSTATE_OK;
-      break;
-
-    case ASPFUNC_STAT :
-#ifdef EBUG
-      printf( "asp stat\n" );
-#endif /* EBUG */
-      if ( asp->asp_slen > 0 ) {
-        i = 0;
-        while(atpb.atp_bitmap) {
-            i++;
-            atpb.atp_bitmap >>= 1;
-        }
-
-       /* asp->data is big enough ... */
-        memcpy( asp->data, asp->asp_status, MIN(asp->asp_slen, i*ASP_CMDSIZ));
-       
-        buflen = MIN(asp->asp_slen, i*ASP_CMDSIZ);
-        buf = asp->data;
-        iovcnt = 0;
-
-        /* If status information is too big to fit into the available
-         * ASP packets, we simply send as much as we can.
-         * Older client versions will most likely not be able to use
-         * the additional information anyway, like directory services
-         * or UTF8 server name. A very long fqdn could be a problem,
-         * we could end up with an invalid address list.
-         */
-        do {
-            iov[ iovcnt ].iov_base = buf;
-            memmove(buf + ASP_HDRSIZ, buf, buflen);
-            memset( iov[ iovcnt ].iov_base, 0, ASP_HDRSIZ );
-
-           if ( buflen > ASP_CMDSIZ ) {
-                buf += ASP_CMDMAXSIZ;
-                buflen -= ASP_CMDSIZ;
-                iov[ iovcnt ].iov_len = ASP_CMDMAXSIZ;
-            } else {
-                iov[ iovcnt ].iov_len = buflen + ASP_HDRSIZ;
-                buflen = 0;
-            }
-            iovcnt++;
-        } while ( iovcnt < i && buflen > 0 );
-
-        atpb.atp_sresiovcnt = iovcnt;
-        atpb.atp_sresiov = iov;
-        atp_sresp( asp->asp_atp, &atpb );
-      }
-      break;
-
-    case ASPFUNC_OPEN :
-      if (children->count < children->nsessions) {
-      struct asp_child    *asp_ac_tmp;
-
-       /* find a slot */
-       for (sid = 0; sid < children->nsessions; sid++) {
-         if (asp_ac[sid] == NULL)
-           break;
-
-         if (asp_ac[sid]->ac_state == ACSTATE_DEAD) {
-           free(asp_ac[sid]);
-           asp_ac[sid] = NULL;
-           break;
-         }
-       }
-
-       if ((atp = atp_open(ATADDR_ANYPORT, 
-                           &(atp_sockaddr(asp->asp_atp)->sat_addr))) == NULL) 
-         return NULL;
-
-    int dummy[2];
-       switch ((pid = fork())) {
-       case 0 : /* child */
-         server_reset_signal();
-         /* free/close some things */
-         for (i = 0; i < children->nsessions; i++ ) {
-           if ( asp_ac[i] != NULL )
-             free( asp_ac[i] );
-         }
-         free(asp_ac);
-         
-         server_child_free(children);
-         children = NULL;
-         atp_close(asp->asp_atp);
-
-         asp->child = 1;
-         asp->asp_atp = atp;
-         asp->asp_sat = sat;
-         asp->asp_wss = asp->cmdbuf[1];
-         asp->asp_seq = 0;
-         asp->asp_sid = sid;
-         asp->asp_flags = ASPFL_SSS;
-         return asp;
-         
-       case -1 : /* error */
-         asp->cmdbuf[ 0 ] = 0;
-         asp->cmdbuf[ 1 ] = 0;
-         asperr = ASPERR_SERVBUSY;
-         break;
-         
-       default : /* parent process */
-         /* we need atomic setting or pb with tickle_handler */ 
-      if (server_child_add(children, CHILD_ASPFORK, pid, dummy)) {
-           if ((asp_ac_tmp = malloc(sizeof(struct asp_child))) == NULL) {
-            kill(pid, SIGQUIT); 
-            break;
-        }
-        asp_ac_tmp->ac_pid = pid;
-        asp_ac_tmp->ac_state = ACSTATE_OK;
-        asp_ac_tmp->ac_sat = sat;
-        asp_ac_tmp->ac_sat.sat_port = asp->cmdbuf[1];
-           
-        asp->cmdbuf[0] = atp_sockaddr(atp)->sat_port;
-        asp->cmdbuf[1] = sid;
-        set_asp_ac(sid, asp_ac_tmp);
-        asperr = ASPERR_OK;
-        break;
-      } else {
-           kill(pid, SIGQUIT); 
-           break;
-      }
-         atp_close(atp);
-         break;
-       }
-       
-      } else {
-       asp->cmdbuf[0] = asp->cmdbuf[1] = 0;
-       asperr = ASPERR_SERVBUSY;
-      }
-
-      memcpy( asp->cmdbuf + 2, &asperr, sizeof(asperr));
-      iov[ 0 ].iov_base = asp->cmdbuf;
-      iov[ 0 ].iov_len = 4;
-      atpb.atp_sresiov = iov;
-      atpb.atp_sresiovcnt = 1;
-      atp_sresp( asp->asp_atp, &atpb );
-      break;
-
-    default:
-      LOG(log_info, logtype_default, "ASPUnknown %d", asp->cmdbuf[0]);
-      break;
-    }
-
-    return asp;
-}
-
-/* with fn defined after use, assume it's not optimized by the compiler */
-static void set_asp_ac(int sid, struct asp_child *tmp)
-{
-    asp_ac[sid] = tmp;
-}
diff --git a/libatalk/asp/asp_init.c b/libatalk/asp/asp_init.c
deleted file mode 100644 (file)
index 06e77f0..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * $Id: asp_init.c,v 1.4 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/socket.h>
-#include <sys/param.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-ASP asp_init(ATP atp)
-{
-    ASP                asp;
-
-    if (( asp = (struct ASP *)calloc(1, sizeof( struct ASP ))) == NULL ) {
-       return( NULL );
-    }
-
-    asp->asp_atp = atp;
-#ifdef BSD4_4
-    asp->asp_sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    asp->asp_sat.sat_family = AF_APPLETALK;
-    asp->asp_sat.sat_addr.s_net = ATADDR_ANYNET;
-    asp->asp_sat.sat_addr.s_node = ATADDR_ANYNODE;
-    asp->asp_sat.sat_port = ATADDR_ANYPORT;
-    asp->asp_status = NULL;
-    asp->asp_slen = 0;
-    asp->asp_sid = 0;
-    asp->asp_flags = ASPFL_SLS;
-    asp->cmdlen = asp->datalen = 0;
-    asp->read_count = asp->write_count = 0;
-    asp->commands = asp->cmdbuf + 4;
-
-    return( asp );
-}
-
-void asp_setstatus(ASP asp, char *status, const int slen)
-{
-    asp->asp_status = status;
-    asp->asp_slen = slen;
-}
diff --git a/libatalk/asp/asp_shutdown.c b/libatalk/asp/asp_shutdown.c
deleted file mode 100644 (file)
index 1f77e1f..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * $Id: asp_shutdown.c,v 1.4 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1996 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-
-int asp_shutdown(ASP asp)
-{
-    struct atp_block   atpb;
-    struct iovec       iov;
-    char               *p;
-    u_int16_t          seq;
-    u_int8_t           oport;
-
-
-    p = asp->commands;
-    *p++ = ASPFUNC_CLOSE;
-    *p++ = asp->asp_sid;
-    seq = 0;
-    memcpy( p, &seq, sizeof(seq));
-    p += sizeof(seq);
-
-    oport = asp->asp_sat.sat_port;
-    atpb.atp_saddr = &asp->asp_sat;
-    atpb.atp_saddr->sat_port = asp->asp_wss;
-    atpb.atp_sreqdata = asp->commands;
-    atpb.atp_sreqdlen = p - asp->commands;
-    atpb.atp_sreqto = 2;
-    atpb.atp_sreqtries = 5;
-
-    if ( atp_sreq( asp->asp_atp, &atpb, 1, ATP_XO ) < 0 ) {
-       asp->asp_sat.sat_port = oport;
-       return( -1 );
-    }
-
-    iov.iov_base = asp->commands;
-    iov.iov_len = ASP_CMDSIZ;
-    atpb.atp_rresiov = &iov;
-    atpb.atp_rresiovcnt = 1;
-
-    if ( atp_rresp( asp->asp_atp, &atpb ) < 0 ) {
-       asp->asp_sat.sat_port = oport;
-       return( -1 );
-    }
-    asp->asp_sat.sat_port = oport;
-
-    return( 0 );
-}
diff --git a/libatalk/asp/asp_tickle.c b/libatalk/asp/asp_tickle.c
deleted file mode 100644 (file)
index c6f3752..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * $Id: asp_tickle.c,v 1.7 2002-12-04 10:59:37 didg Exp $
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <atalk/logger.h>
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif /* HAVE_SYS_TYPES_H */
-#include <errno.h>
-
-#include <sys/socket.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-
-/* send off a tickle */
-int asp_tickle(ASP asp, const u_int8_t sid, struct sockaddr_at *sat)
-{
-  struct atp_block atpb;
-  char buf[ASP_HDRSIZ];
-
-  buf[ 0 ] = ASPFUNC_TICKLE;
-  buf[ 1 ] = sid;
-  buf[ 2 ] = buf[ 3 ] = 0;
-
-  atpb.atp_saddr = sat;
-  atpb.atp_sreqdata = buf;
-  atpb.atp_sreqdlen = sizeof(buf);
-  atpb.atp_sreqto = 0;
-  atpb.atp_sreqtries = 1;
-  if ( atp_sreq( asp->asp_atp, &atpb, 0, 0 ) < 0 ) {
-    LOG(log_error, logtype_default, "atp_sreq: %s", strerror(errno) );
-    return 0;
-  }
-  return 1;
-}
diff --git a/libatalk/asp/asp_write.c b/libatalk/asp/asp_write.c
deleted file mode 100644 (file)
index 2819e31..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * $Id: asp_write.c,v 1.4 2009-10-22 12:35:39 franklahm Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/asp.h>
-
-#if defined(BSD) || defined(BSD4_3)
-#define memmove(a, b, n)   bcopy((b), (a), (n))
-#endif /* BSD || BSD4_3 */
-
-int asp_wrtcont(ASP asp, char *buf, size_t *buflen)
-{
-    struct iovec       iov[ ASP_MAXPACKETS ];
-    struct atp_block   atpb;
-    char               *p;
-    int                        iovcnt = ASP_MAXPACKETS;
-    u_int16_t          blen, seq;
-    u_int8_t           oport;
-
-    p = buf;
-    *p++ = ASPFUNC_WRTCONT;
-    *p++ = asp->asp_sid;
-    seq = htons( asp->asp_seq );
-    memcpy( p, &seq, sizeof(seq));
-    p += sizeof(seq);
-    blen = htons(*buflen);
-    memcpy( p, &blen, sizeof(blen));
-    p += sizeof(blen);
-
-    for ( iovcnt = 0; iovcnt < ASP_MAXPACKETS; iovcnt++ ) {
-        iov[iovcnt].iov_base = buf + iovcnt*ASP_CMDMAXSIZ;
-       iov[ iovcnt ].iov_len = ASP_CMDMAXSIZ;
-    }
-
-    oport = asp->asp_sat.sat_port;
-    atpb.atp_saddr = &asp->asp_sat;
-    atpb.atp_saddr->sat_port = asp->asp_wss;
-    atpb.atp_sreqdata = buf;
-    atpb.atp_sreqdlen = p - buf;
-    atpb.atp_sreqto = 2;
-    atpb.atp_sreqtries = 5;
-
-    if ( atp_sreq( asp->asp_atp, &atpb, iovcnt, ATP_XO ) < 0 ) {
-       asp->asp_sat.sat_port = oport;
-       return( -1 );
-    }
-    asp->write_count += atpb.atp_sreqdlen;
-
-    atpb.atp_rresiov = iov;
-    atpb.atp_rresiovcnt = iovcnt;
-    if ( atp_rresp( asp->asp_atp, &atpb ) < 0 ) {
-       asp->asp_sat.sat_port = oport;
-       return( -1 );
-    }
-
-    asp->asp_sat.sat_port = oport;
-
-    /* get rid of the 4-byte headers */
-    p = buf;
-    for ( iovcnt = 0; iovcnt < atpb.atp_rresiovcnt; iovcnt++ ) {
-       memmove(p, (char *) iov[ iovcnt ].iov_base + ASP_HDRSIZ, 
-               iov[ iovcnt ].iov_len - ASP_HDRSIZ );
-       p += ( iov[ iovcnt ].iov_len - ASP_HDRSIZ );
-    }
-
-    *buflen = p - buf;
-    asp->read_count += *buflen;
-    return 0;
-}
diff --git a/libatalk/atp/.gitignore b/libatalk/atp/.gitignore
deleted file mode 100644 (file)
index d6c38da..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Makefile
-Makefile.in
-*.lo
-*.la
-.deps
-.libs
-.gitignore
-atp_bufs.o atp_close.o atp_open.o atp_packet.o atp_rreq.o atp_rresp.o atp_rsel.o atp_sreq.o atp_sresp.o
diff --git a/libatalk/atp/Makefile.am b/libatalk/atp/Makefile.am
deleted file mode 100644 (file)
index fe553b0..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-# Makefile.am for libatalk/atp/
-
-noinst_LTLIBRARIES = libatp.la
-
-libatp_la_SOURCES = atp_bufs.c atp_close.c atp_open.c atp_packet.c atp_rreq.c atp_rresp.c atp_rsel.c atp_sreq.c atp_sresp.c 
-
-noinst_HEADERS = atp_internals.h
diff --git a/libatalk/atp/atp_bufs.c b/libatalk/atp/atp_bufs.c
deleted file mode 100644 (file)
index 9c899e2..0000000
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * $Id: atp_bufs.c,v 1.5 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-/* 
- * Our own memory maintenance for atp
-*/
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/socket.h>
-
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include "atp_internals.h"
-
-#define                        N_MORE_BUFS             10
-
-static struct atpbuf   *free_list = NULL;      /* free buffers */
-
-#ifdef EBUG
-static int             numbufs = 0;
-#endif /* EBUG */
-
-/* only call this when the free_list is empty...
- * N_MORE_BUFS must be >= one
-*/
-static int more_bufs(void)
-{
-    int                        i;
-    char               *mem;
-    struct atpbuf      *bp;
-
-    /* get the whole chunk in one malloc call
-    */
-    if (( mem = malloc( N_MORE_BUFS * sizeof( struct atpbuf ))) == NULL ) {
-       errno = ENOBUFS;
-       return -1;
-    }
-    /* now split into separate bufs
-    */
-    bp = free_list = (struct atpbuf *) mem;
-    for ( i = 1; i < N_MORE_BUFS; ++i ) {
-       bp->atpbuf_next = (struct atpbuf *) ( mem += sizeof( struct atpbuf ));
-       bp = bp->atpbuf_next;
-    }
-    bp->atpbuf_next = NULL;
-
-    return 0;
-}
-
-
-#ifdef EBUG
-void atp_print_bufuse(ATP ah, char *s)
-{
-    struct atpbuf      *bp;
-    int                        i, sentcount, incount, respcount;
-
-    sentcount = 0;
-    for ( bp = ah->atph_sent; bp != NULL; bp = bp->atpbuf_next ) {
-       ++sentcount;
-       for ( i = 0; i < 8; ++i ) {
-           if ( bp->atpbuf_info.atpbuf_xo.atpxo_packet[ i ] != NULL ) {
-               ++sentcount;
-           }
-       }
-    }
-
-    if ( ah->atph_reqpkt != NULL ) {
-       ++sentcount;
-    }
-
-
-    incount = 0;
-    for ( bp = ah->atph_queue; bp != NULL; bp = bp->atpbuf_next, ++incount );
-
-    respcount = 0;
-    for ( i = 0; i < 8; ++i ) {
-        if ( ah->atph_resppkt[ i ] != NULL ) {
-           ++respcount;
-       }
-    }
-
-    printf( "<%d> %s: bufs total %d  sent %d  incoming %d  req %d  resp %d\n",
-       getpid(), s, numbufs, sentcount, incount,
-       ( ah->atph_reqpkt != NULL ) ? 1: 0, respcount );
-}
-#endif /* EBUG */
-
-
-struct atpbuf *atp_alloc_buf(void)
-{
-    struct atpbuf *bp;
-
-    if ( free_list == NULL && more_bufs() ) return NULL;
-
-    bp = free_list;
-    free_list = free_list->atpbuf_next;
-#ifdef EBUG
-    ++numbufs;
-#endif /* EBUG */
-    return bp;
-}
-
-
-int atp_free_buf(struct atpbuf *bp)
-{
-    if ( bp == NULL ) {
-       return -1;
-    }
-    bp->atpbuf_next = free_list;
-    free_list = bp;
-#ifdef EBUG
-    --numbufs;
-#endif /* EBUG */
-    return 0;
-}
-
-
diff --git a/libatalk/atp/atp_close.c b/libatalk/atp/atp_close.c
deleted file mode 100644 (file)
index 4d31b5f..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * $Id: atp_close.c,v 1.5 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1997 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/socket.h>
-
-#include <netatalk/at.h>
-#include <atalk/netddp.h>
-#include <atalk/atp.h>
-#include "atp_internals.h"
-#ifdef EBUG
-#include <stdio.h>
-#endif /* EBUG */
-
-int atp_close(ATP ah)
-{
-    struct atpbuf      *cq;
-    int                        i;
-
-    /* remove from list of open atp sockets & discard queued data
-    */
-#ifdef EBUG
-    print_bufuse( ah, "atp_close");
-#endif /* EBUG */
-
-    while ( ah->atph_queue != NULL ) {
-       cq = ah->atph_queue;
-       ah->atph_queue = cq->atpbuf_next;
-       atp_free_buf( cq );
-    }
-
-    while ( ah->atph_sent != NULL ) {
-       cq = ah->atph_sent;
-       for ( i = 0; i < 8; ++i ) {
-           if ( cq->atpbuf_info.atpbuf_xo.atpxo_packet[ i ] != NULL ) {
-               atp_free_buf( cq->atpbuf_info.atpbuf_xo.atpxo_packet[ i ] );
-           }
-       }
-       ah->atph_sent = cq->atpbuf_next;
-       atp_free_buf( cq );
-    }
-
-    if ( ah->atph_reqpkt != NULL ) {
-       atp_free_buf( ah->atph_reqpkt );
-       ah->atph_reqpkt = NULL;
-    }
-
-    for ( i = 0; i < 8; ++i ) {
-       if ( ah->atph_resppkt[ i ] != NULL ) {
-           atp_free_buf( ah->atph_resppkt[ i ] );
-           ah->atph_resppkt[ i ] = NULL;
-       }
-    }
-
-#ifdef EBUG
-    print_bufuse( ah, "atp_close end");
-#endif /* EBUG */
-
-    i = ah->atph_socket;
-    atp_free_buf( (struct atpbuf *) ah );
-
-    if (netddp_close(i) < 0)
-      return -1;
-
-    return 0;
-}
diff --git a/libatalk/atp/atp_internals.h b/libatalk/atp/atp_internals.h
deleted file mode 100644 (file)
index 51d3b8b..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * $Id: atp_internals.h,v 1.4 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef ATP_INTERNALS_H
-#define ATP_INTERNALS_H 1
-
-#include <sys/types.h>
-#include <sys/cdefs.h>
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <atalk/atp.h>
-
-/*
- * masks for matching incoming packets
- */
-#define ATP_FUNCANY    ATP_TREQ | ATP_TRESP | ATP_TREL
-#define ATP_TIDANY     0xffff
-
-/* in atp_bufs.c */
-extern struct atpbuf *atp_alloc_buf (void);
-extern void atp_print_bufuse        (ATP, char *);
-extern int atp_free_buf             (struct atpbuf *);
-
-/* in atp_packet.c */
-extern int at_addr_eq               (struct sockaddr_at *, 
-                                        struct sockaddr_at *);
-extern void atp_build_req_packet    (struct atpbuf *, u_int16_t, 
-                                        u_int8_t, struct atp_block *);
-extern void atp_build_resp_packet   (struct atpbuf *, u_int16_t,
-                                        u_int8_t, struct atp_block *,
-                                        u_int8_t);
-extern int atp_recv_atp             (ATP, struct sockaddr_at *, 
-                                        u_int8_t *, u_int16_t, char *,
-                                        int);
-#ifdef EBUG
-extern void atp_print_addr          (char *, struct sockaddr_at *);
-#endif /* EBUG */
-
-#endif /* ATP_INTERNALS_H */
diff --git a/libatalk/atp/atp_open.c b/libatalk/atp/atp_open.c
deleted file mode 100644 (file)
index 1690752..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * $Id: atp_open.c,v 1.5 2001-08-15 02:17:57 srittau Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-
-#include <atalk/netddp.h>
-#include <atalk/ddp.h>
-#include <atalk/atp.h>
-
-#include "atp_internals.h"
-
-ATP atp_open(u_int8_t port, const struct at_addr *saddr)
-{
-    struct sockaddr_at  addr;
-    int                        s;
-    ATP                        atp;
-    struct timeval     tv;
-    int                        pid;
-
-#ifdef DEBUG
-    printf( "<%d> atp_open\n", getpid());
-#endif /* DEBUG */
-
-    memset(&addr, 0, sizeof(addr));
-    addr.sat_port = port;
-    if (saddr) 
-      memcpy(&addr.sat_addr, saddr, sizeof(struct at_addr));
-    if ((s = netddp_open(&addr, NULL)) < 0)
-        return NULL;
-
-    if (( atp = (ATP) atp_alloc_buf()) == NULL ) {
-        netddp_close(s);
-       return NULL;
-    }
-
-    /* initialize the atp handle */
-    memset(atp, 0, sizeof( struct atp_handle ));
-    memcpy(&atp->atph_saddr, &addr, sizeof(addr));
-
-    atp->atph_socket = s;
-    atp->atph_reqto = -1;
-    gettimeofday( &tv, (struct timezone *) 0 );
-    pid = getpid();
-    atp->atph_tid = tv.tv_sec ^ ((( pid << 8 ) & 0xff00 ) | ( pid >> 8 ));
-
-#ifdef EBUG
-srandom( tv.tv_sec );
-#endif /* EBUG */
-
-    return atp;
-}
diff --git a/libatalk/atp/atp_packet.c b/libatalk/atp/atp_packet.c
deleted file mode 100644 (file)
index a7fae01..0000000
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * $Id: atp_packet.c,v 1.6 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/param.h>
-#include <netinet/in.h>
-
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-
-#include <atalk/netddp.h>
-#include <atalk/ddp.h>
-#include <atalk/atp.h>
-#include <atalk/util.h>
-
-#include "atp_internals.h"
-
-/* FIXME/SOCKLEN_T: socklen_t is a unix98 feature. */
-#ifndef SOCKLEN_T
-#define SOCKLEN_T unsigned int
-#endif /* ! SOCKLEN_T */
-
-#ifdef EBUG
-#include <stdio.h>
-
-static void print_func(u_int8_t ctrlinfo)
-{
-    switch ( ctrlinfo & ATP_FUNCMASK ) {
-    case ATP_TREQ:
-       printf( "TREQ" );
-       break;
-    case ATP_TRESP:
-       printf( "TRESP" );
-       break;
-    case ATP_TREL:
-       printf( "ANY/TREL" );
-       break;
-    case ATP_TIDANY:
-       printf( "*" );
-       break;
-    default:
-       printf( "%x", ctrlinfo & ATP_FUNCMASK );
-    }
-}
-
-static void dump_packet(char *buf, int len)
-{
-    int                i;
-
-    for ( i = 0; i < len; ++i ) {
-       printf( "%x-%c ", buf[i], buf[i] );
-    }
-    putchar( '\n' );
-}
-
-void atp_print_addr(char *s, struct sockaddr_at *saddr)
-{
-    printf( "%s ", s );
-    saddr->sat_family == AF_APPLETALK ? printf( "at." ) :
-      printf( "%d.", saddr->sat_family );
-    saddr->sat_addr.s_net == ATADDR_ANYNET ? printf( "*." ) :
-      printf( "%d.", ntohs( saddr->sat_addr.s_net ));
-    saddr->sat_addr.s_node == ATADDR_ANYNODE ? printf( "*." ) :
-      printf( "%d.", saddr->sat_addr.s_node );
-    saddr->sat_port == ATADDR_ANYPORT ? printf( "*" ) :
-      printf( "%d", saddr->sat_port );
-}
-#endif /* EBUG */
-
-
-void atp_build_req_packet( struct atpbuf *pktbuf,
-                          u_int16_t tid,
-                          u_int8_t ctrl,
-                          struct atp_block *atpb )
-{
-    struct atphdr      hdr;
-
-    /* fill in the packet fields
-    */
-    hdr.atphd_ctrlinfo = ctrl;
-    hdr.atphd_bitmap = atpb->atp_bitmap;
-    hdr.atphd_tid = htons( tid );
-    *(pktbuf->atpbuf_info.atpbuf_data) = DDPTYPE_ATP;
-    memcpy(pktbuf->atpbuf_info.atpbuf_data + 1, &hdr, sizeof( struct atphdr ));
-    memcpy(pktbuf->atpbuf_info.atpbuf_data + ATP_HDRSIZE, 
-          atpb->atp_sreqdata, atpb->atp_sreqdlen ); 
-
-    /* set length
-    */
-    pktbuf->atpbuf_dlen = ATP_HDRSIZE + (size_t) atpb->atp_sreqdlen;
-}
-
-void atp_build_resp_packet( struct atpbuf *pktbuf,
-                           u_int16_t tid,
-                           u_int8_t ctrl,
-                           struct atp_block *atpb,
-                           u_int8_t seqnum )
-{
-    struct atphdr      hdr;
-
-    /* fill in the packet fields */
-    *(pktbuf->atpbuf_info.atpbuf_data) = DDPTYPE_ATP;
-    hdr.atphd_ctrlinfo = ctrl;
-    hdr.atphd_bitmap = seqnum;
-    hdr.atphd_tid = htons( tid );
-    memcpy(pktbuf->atpbuf_info.atpbuf_data + 1, &hdr, 
-          sizeof( struct atphdr ));
-    memcpy(pktbuf->atpbuf_info.atpbuf_data + ATP_HDRSIZE,
-         atpb->atp_sresiov[ seqnum ].iov_base,
-         atpb->atp_sresiov[ seqnum ].iov_len ); 
-
-    /* set length
-    */
-    pktbuf->atpbuf_dlen = ATP_HDRSIZE + (size_t) atpb->atp_sresiov[ seqnum ].iov_len;
-}
-
-
-int
-atp_recv_atp( ATP ah,
-             struct sockaddr_at *fromaddr,
-             u_int8_t *func,
-             u_int16_t tid,
-             char *rbuf,
-             int wait )
-{
-/* 
-  Receive a packet from address fromaddr of the correct function type
-  and with the correct tid.  fromaddr = AT_ANY... and function == ATP_TYPEANY
-  and tid == ATP_TIDANY can be used to wildcard match.
-  
-  recv_atp returns the length of the packet received (or -1 if error)
-  The function code for the packet received is returned in *func (ATP_TREQ or
-    ATP_TRESP).
-*/
-    struct atpbuf      *pq, *cq;
-    struct atphdr      ahdr;
-    u_int16_t          rfunc;
-    u_int16_t          rtid;
-    int                        i;
-    int                        dlen = -1;
-    int                        recvlen;
-    struct sockaddr_at faddr;
-    SOCKLEN_T          faddrlen;
-    struct atpbuf      *inbuf;
-
-    tid = htons( tid );
-
-    /* first check the queue
-    */
-#ifdef EBUG
-    atp_print_bufuse( ah, "recv_atp checking queue" );
-#endif /* EBUG */
-    for ( pq = NULL, cq = ah->atph_queue; cq != NULL;
-      pq = cq, cq = cq->atpbuf_next ) {
-       memcpy(&ahdr, cq->atpbuf_info.atpbuf_data + 1, 
-              sizeof( struct atphdr ));
-       rfunc = ahdr.atphd_ctrlinfo & ATP_FUNCMASK;
-#ifdef EBUG
-       printf( "<%d> checking", getpid());
-       printf( " tid=%hu func=", ntohs( ahdr.atphd_tid ));
-       print_func( rfunc );
-       atp_print_addr( " from", &cq->atpbuf_addr );
-       putchar( '\n' );
-#endif /* EBUG */
-       if ((( tid & ahdr.atphd_tid ) == ahdr.atphd_tid ) &&
-           (( *func & rfunc ) == rfunc )
-           && at_addr_eq( fromaddr, &cq->atpbuf_addr )) {
-           break;
-       }
-    }
-    if ( cq != NULL ) {
-       /* we found one in the queue -- copy to rbuf
-       */
-       dlen = (int) cq->atpbuf_dlen;
-       *func = rfunc;
-       memcpy( fromaddr, &cq->atpbuf_addr, sizeof( struct sockaddr_at ));
-       memcpy( rbuf, cq->atpbuf_info.atpbuf_data, cq->atpbuf_dlen );
-
-       /* remove packet from queue and free buffer
-       */
-       if ( pq == NULL ) {
-           ah->atph_queue = NULL;
-       } else {
-           pq->atpbuf_next = cq->atpbuf_next;
-       }
-       atp_free_buf( cq );
-       return( dlen );
-    }
-
-    /* we need to get it the net -- call on ddp to receive a packet
-    */
-#ifdef EBUG
-    printf( "<%d>", getpid());
-    atp_print_addr( " waiting on address", &ah->atph_saddr );
-    printf( "\nfor tid=%hu func=", ntohs( tid ));
-    print_func( *func );
-    atp_print_addr( " from", fromaddr );
-    putchar( '\n' );
-#endif /* EBUG */
-
-    do {
-#ifdef EBUG
-    fflush( stdout );
-#endif /* EBUG */
-       faddrlen = sizeof( struct sockaddr_at );
-       memset( &faddr, 0, sizeof( struct sockaddr_at ));
-
-       if (( recvlen = netddp_recvfrom( ah->atph_socket, rbuf, 
-                                        ATP_BUFSIZ, 0,
-                                        (struct sockaddr *) &faddr,
-                                        &faddrlen )) < 0 ) {
-           return -1;
-       }
-       memcpy( &ahdr, rbuf + 1, sizeof( struct atphdr ));
-       if ( recvlen >= ATP_HDRSIZE && *rbuf == DDPTYPE_ATP) {
-           /* this is a valid ATP packet -- check for a match */
-           rfunc = ahdr.atphd_ctrlinfo & ATP_FUNCMASK;
-           rtid = ahdr.atphd_tid;
-#ifdef EBUG
-           printf( "<%d> got tid=%hu func=", getpid(), ntohs( rtid ));
-           print_func( rfunc );
-           atp_print_addr( " from", &faddr );
-           putchar( '\n' );
-           bprint( rbuf, recvlen );
-#endif /* EBUG */
-           if ( rfunc == ATP_TREL ) {
-               /* remove response from sent list */
-               for ( pq = NULL, cq = ah->atph_sent; cq != NULL;
-                 pq = cq, cq = cq->atpbuf_next ) {
-                   if ( at_addr_eq( &faddr, &cq->atpbuf_addr ) &&
-                     cq->atpbuf_info.atpbuf_xo.atpxo_tid == ntohs( rtid )) 
-                       break;
-               }
-               if ( cq != NULL ) {
-#ifdef EBUG
-       printf( "<%d> releasing transaction %hu\n", getpid(), ntohs( rtid ));
-#endif /* EBUG */
-                   if ( pq == NULL ) {
-                       ah->atph_sent = cq->atpbuf_next;
-                   } else {
-                       pq->atpbuf_next = cq->atpbuf_next;
-                   }
-                   for ( i = 0; i < 8; ++i ) {
-                       if ( cq->atpbuf_info.atpbuf_xo.atpxo_packet[ i ]
-                                   != NULL ) {
-                           atp_free_buf ( cq->atpbuf_info.atpbuf_xo.atpxo_packet[ i ] );
-                       }
-                   }
-                   atp_free_buf( cq );
-               }
-
-           } else if ((( tid & rtid ) == rtid ) &&
-                   (( *func & rfunc ) == rfunc ) &&
-                   at_addr_eq( fromaddr, &faddr )) { /* got what we wanted */
-               *func = rfunc;
-               dlen = recvlen;
-               memcpy( fromaddr, &faddr, sizeof( struct sockaddr_at ));
-
-           } else {
-               /* add packet to incoming queue */
-#ifdef EBUG
-       printf( "<%d> queuing incoming...\n", getpid() );
-#endif /* EBUG */
-               if (( inbuf = atp_alloc_buf()) == NULL ) {
-                   return -1;
-               }
-               memcpy( &inbuf->atpbuf_addr, &faddr, 
-                       sizeof( struct sockaddr_at ));
-               inbuf->atpbuf_next = ah->atph_queue;
-               inbuf->atpbuf_dlen = (size_t) recvlen;
-               memcpy( inbuf->atpbuf_info.atpbuf_data, rbuf, recvlen );
-           }
-       }
-       if ( !wait && dlen < 0 ) {
-           return( 0 );
-       }
-
-    } while ( dlen < 0 );
-
-    return( dlen );
-}
-
-
-int at_addr_eq( 
-    struct sockaddr_at *paddr,         /* primary address */
-    struct sockaddr_at *saddr)         /* secondary address */
-{
-/* compare two atalk addresses -- only check the non-zero fields
-    of paddr against saddr.
-   return zero if not equal, non-zero if equal
-*/
-    return (( paddr->sat_port == ATADDR_ANYPORT || paddr->sat_port == saddr->sat_port )
-       &&  ( paddr->sat_addr.s_net == ATADDR_ANYNET ||
-             paddr->sat_addr.s_net == saddr->sat_addr.s_net )
-       &&  ( paddr->sat_addr.s_node == ATADDR_ANYNODE ||
-             paddr->sat_addr.s_node == saddr->sat_addr.s_node ));
-}
-
diff --git a/libatalk/atp/atp_rreq.c b/libatalk/atp/atp_rreq.c
deleted file mode 100644 (file)
index 6736dbd..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * $Id: atp_rreq.c,v 1.4 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <errno.h>
-
-#include <netinet/in.h>
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <atalk/atp.h>
-
-#include "atp_internals.h"
-
-
-/* wait for a tranasaction service request
-*/
-int atp_rreq(
-    ATP                        ah,             /* open atp handle */
-    struct atp_block   *atpb)          /* parameter block */
-{
-    struct atpbuf      *req_buf;       /* for receiving request packet */
-    struct atphdr      req_hdr;        /* request header overlay */
-    struct sockaddr_at faddr;          /* sender's address */
-    int                        recvlen;        /* length of received packet */
-    u_int16_t          tid;
-    int                        rc;
-    u_int8_t           func;
-
-#ifdef EBUG
-    atp_print_bufuse( ah, "atp_rreq" );
-#endif /* EBUG */
-
-    while (( rc = atp_rsel( ah, atpb->atp_saddr, ATP_TREQ )) == 0 ) {
-       ;
-    }
-
-    if ( rc != ATP_TREQ ) {
-#ifdef EBUG
-       printf( "<%d> atp_rreq: atp_rsel returns err %d\n", getpid(), rc );
-#endif /* EBUG */
-       return( rc );
-    }
-
-    /* allocate a buffer for receiving request
-    */
-    if (( req_buf = atp_alloc_buf()) == NULL ) {
-       return -1;
-    }
-
-    memcpy( &faddr, atpb->atp_saddr, sizeof( struct sockaddr_at ));
-    func = ATP_TREQ;
-    if (( recvlen = atp_recv_atp( ah, &faddr, &func, ATP_TIDANY,
-         req_buf->atpbuf_info.atpbuf_data, 1 )) < 0 ) {
-       atp_free_buf( req_buf );
-       return -1;
-    }
-
-    memcpy( &req_hdr, req_buf->atpbuf_info.atpbuf_data + 1, 
-           sizeof( struct atphdr ));
-    tid = ntohs( req_hdr.atphd_tid );
-
-    ah->atph_rtid = tid;
-    if (( ah->atph_rxo = req_hdr.atphd_ctrlinfo & ATP_XO ) != 0 ) {
-       ah->atph_rreltime = ATP_RELTIME *
-               ( 1 << ( req_hdr.atphd_ctrlinfo & ATP_TRELMASK ));
-    }
-
-    memcpy( atpb->atp_saddr, &faddr, sizeof( struct sockaddr_at ));
-
-    if ( recvlen - ATP_HDRSIZE > atpb->atp_rreqdlen ) {
-       atp_free_buf( req_buf );
-       errno = EMSGSIZE;
-       return -1;
-    }
-
-    atpb->atp_rreqdlen = recvlen - ATP_HDRSIZE;
-    memcpy( atpb->atp_rreqdata, 
-           req_buf->atpbuf_info.atpbuf_data + ATP_HDRSIZE,
-           recvlen - ATP_HDRSIZE );
-    atpb->atp_bitmap = req_hdr.atphd_bitmap;
-    atp_free_buf( req_buf );
-    return( 0 );
-}
diff --git a/libatalk/atp/atp_rresp.c b/libatalk/atp/atp_rresp.c
deleted file mode 100644 (file)
index ac0a146..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * $Id: atp_rresp.c,v 1.6 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <errno.h>
-#include <sys/uio.h>
-#include <sys/socket.h>
-
-#include <netatalk/at.h>
-#include <atalk/atp.h>
-#include <atalk/util.h>
-
-#ifdef EBUG
-#include <stdio.h>
-#endif /* EBUG */
-
-#include "atp_internals.h"
-
-int
-atp_rresp(
-    ATP                        ah,             /* open atp handle */
-    struct atp_block   *atpb)          /* parameter block */
-{
-    int                i, rc;
-    size_t     len;
-
-#ifdef EBUG
-    atp_print_bufuse( ah, "atp_rresp" );
-#endif /* EBUG */
-    /* check parameters
-    */
-    if ( atpb->atp_rresiovcnt <= 0 || atpb->atp_rresiovcnt > 8 ) {
-       errno = EINVAL;
-       return( -1 );
-    }
-
-    while (( rc = atp_rsel( ah, atpb->atp_saddr, ATP_TRESP )) == 0 ) {
-       ;
-    }
-
-    if ( rc != ATP_TRESP ) {
-       return( rc );
-    }
-
-    for ( i = 0; i < 8; ++i ) {
-       if ( ah->atph_resppkt[ i ] == NULL ) {
-           break;
-       }
-       len = ah->atph_resppkt[ i ]->atpbuf_dlen - ATP_HDRSIZE;
-       if ( i > atpb->atp_rresiovcnt - 1 ||
-               len > atpb->atp_rresiov[ i ].iov_len ) {
-           errno = EMSGSIZE;
-           return( -1 );
-       }
-#ifdef EBUG
-       fprintf( stderr, "atp_rresp copying %ld bytes packet %d\n",
-               len, i );
-       bprint( (char *)ah->atph_resppkt[ i ]->atpbuf_info.atpbuf_data,
-               len + ATP_HDRSIZE );
-#endif /* EBUG */
-       memcpy(atpb->atp_rresiov[ i ].iov_base,
-              ah->atph_resppkt[ i ]->atpbuf_info.atpbuf_data + ATP_HDRSIZE,
-              len );
-       atpb->atp_rresiov[ i ].iov_len = len;
-       atp_free_buf( ah->atph_resppkt[ i ] );
-       ah->atph_resppkt[ i ] = NULL;
-    }
-    atpb->atp_rresiovcnt = i;
-
-    return( 0 );
-}
diff --git a/libatalk/atp/atp_rsel.c b/libatalk/atp/atp_rsel.c
deleted file mode 100644 (file)
index bc6ec56..0000000
+++ /dev/null
@@ -1,360 +0,0 @@
-/*
- * $Id: atp_rsel.c,v 1.6 2009-10-14 01:38:28 didg Exp $
- *
- * Copyright (c) 1990,1997 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <signal.h>
-#include <errno.h>
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-
-#include <atalk/netddp.h>
-#include <atalk/compat.h>
-#include <atalk/atp.h>
-#include <atalk/util.h>
-
-#include "atp_internals.h"
-
-#ifdef DROP_ATPTREL
-static int     release_count = 0;
-#endif /* DROP_ATPTREL */
-
-
-static int
-resend_request(ATP ah)
-{
-    /*
-     * update bitmap and send request packet
-     */
-    struct atphdr      req_hdr;
-
-#ifdef EBUG
-    printf( "\n<%d> resend_request: resending %ld byte request packet",
-           getpid(), ah->atph_reqpkt->atpbuf_dlen );
-    atp_print_addr( " to", &ah->atph_reqpkt->atpbuf_addr );
-    putchar( '\n' );
-    bprint( ah->atph_reqpkt->atpbuf_info.atpbuf_data,
-           ah->atph_reqpkt->atpbuf_dlen );
-#endif /* EBUG */
-
-    memcpy( &req_hdr, ah->atph_reqpkt->atpbuf_info.atpbuf_data + 1, 
-       sizeof( struct atphdr ));
-    req_hdr.atphd_bitmap = ah->atph_rbitmap;
-    memcpy( ah->atph_reqpkt->atpbuf_info.atpbuf_data + 1, &req_hdr, 
-           sizeof( struct atphdr ));
-
-    gettimeofday( &ah->atph_reqtv, (struct timezone *)0 );
-    if ( netddp_sendto( ah->atph_socket,
-           ah->atph_reqpkt->atpbuf_info.atpbuf_data,
-           ah->atph_reqpkt->atpbuf_dlen, 0,
-           (struct sockaddr *) &ah->atph_reqpkt->atpbuf_addr,
-           sizeof( struct sockaddr_at )) != ah->atph_reqpkt->atpbuf_dlen ) {
-       return( -1 );
-    }
-
-    if ( ah->atph_reqtries > 0 ) {
-       --(ah->atph_reqtries);
-    }
-
-    return( 0 );
-}
-
-int
-atp_rsel( 
-    ATP                        ah,             /* open atp handle */
-    struct sockaddr_at *faddr,         /* address to receive from */
-    int                        func)           /* which function(s) to wait for;
-                                          0 means request or response */
-{
-    struct atpbuf      *abuf, *pb, *cb;
-    struct atphdr      req_hdr, resp_hdr;
-    fd_set             fds;
-    int                        i, recvlen, requesting, mask, c;
-    u_int8_t           rfunc;
-    u_int16_t          tid;
-    struct timeval     tv;
-    struct sockaddr_at saddr;
-
-#ifdef EBUG
-    atp_print_bufuse( ah, "atp_rsel at top" );
-#endif /* EBUG */
-    if ( func == 0 ) {
-       func = ATP_FUNCANY;
-    }
-
-    requesting = ( func & ATP_TRESP ) && ah->atph_rrespcount > 0 &&
-       ( ah->atph_reqtries > 0 || ah->atph_reqtries == ATP_TRIES_INFINITE );
-
-    if ( requesting && ah->atph_rbitmap == 0 ) {
-       /*
-        * we already have a complete atp response; just return
-        */
-       return( ATP_TRESP );
-    }
-
-    if (( abuf = atp_alloc_buf()) == NULL ) {
-       return( -1 );
-    }
-
-    if ( requesting ) {
-#ifdef EBUG
-       printf( "<%d> atp_rsel: request pending\n", getpid());
-#endif /* EBUG */
-       gettimeofday( &tv, (struct timezone *)0 );
-       if ( tv.tv_sec - ah->atph_reqtv.tv_sec > ah->atph_reqto ) {
-           if ( resend_request( ah ) < 0 ) {
-               atp_free_buf( abuf );
-               return( -1 );
-           }
-       }
-    }
-
-    for ( ;; ) {
-       rfunc = func;
-       if ( requesting ) {
-           FD_ZERO( &fds );
-           FD_SET( ah->atph_socket, &fds );
-           tv.tv_sec = ah->atph_reqto;
-           tv.tv_usec = 0;
-           if (( c = select( ah->atph_socket + 1, &fds, NULL, NULL,
-                   &tv )) < 0 ) {
-               atp_free_buf( abuf );
-               return( -1 );
-           }
-           if ( c == 0 || FD_ISSET( ah->atph_socket, &fds ) == 0 ) {
-               recvlen = -1;
-               errno = EINTR;
-               goto timeout;
-           }
-       }
-       memcpy( &saddr, faddr, sizeof( struct sockaddr_at ));
-#ifdef EBUG
-       printf( "<%d> atp_rsel calling recv_atp,", getpid());
-       atp_print_addr( " accepting from: ", &saddr );
-       putchar( '\n' );
-#endif /* EBUG */
-       if (( recvlen = atp_recv_atp( ah, &saddr, &rfunc, ATP_TIDANY,
-               abuf->atpbuf_info.atpbuf_data, 0 )) >= 0 ) {
-           break;      /* we received something */
-       }
-
-timeout :
-       if ( !requesting || errno != EINTR ) {
-           break;      /* error */
-       }
-           
-       if ( ah->atph_reqtries <= 0 &&
-               ah->atph_reqtries != ATP_TRIES_INFINITE ) {
-           errno = ETIMEDOUT;
-           break;
-       }
-       
-       if ( resend_request( ah ) < 0 ) {
-           break;      /* error */
-       }
-    }
-
-    if ( recvlen <= 0 ) {      /* error */
-       atp_free_buf( abuf );
-       return( recvlen );
-    }
-
-#ifdef EBUG
-    printf( "<%d> atp_rsel: rcvd %d bytes", getpid(), recvlen );
-    atp_print_addr( " from: ", &saddr );
-    putchar( '\n' );
-    bprint( abuf->atpbuf_info.atpbuf_data, recvlen );
-#endif /* EBUG */
-
-    abuf->atpbuf_dlen = (size_t) recvlen;
-    memcpy( &resp_hdr, abuf->atpbuf_info.atpbuf_data + 1,
-           sizeof( struct atphdr ));
-
-    if ( rfunc == ATP_TREQ ) {
-       /*
-        * we got a request: check to see if it is a duplicate (XO)
-        * while we are at it, we expire old XO responses from sent list
-        */
-       memcpy( &req_hdr, abuf->atpbuf_info.atpbuf_data + 1, 
-               sizeof( struct atphdr ));
-       tid = ntohs( req_hdr.atphd_tid );
-       gettimeofday( &tv, (struct timezone *)0 );
-       for ( pb = NULL, cb = ah->atph_sent; cb != NULL;
-               pb = cb, cb = cb->atpbuf_next ) {
-#ifdef EBUG
-           printf( "<%d>", getpid());
-           atp_print_addr( " examining", &cb->atpbuf_addr );
-           printf( " %hu", cb->atpbuf_info.atpbuf_xo.atpxo_tid );
-           atp_print_addr( " (looking for", &saddr );
-           printf( " %hu)\n", tid );
-#endif /* EBUG */
-           if ( tv.tv_sec - cb->atpbuf_info.atpbuf_xo.atpxo_tv.tv_sec
-                   > cb->atpbuf_info.atpbuf_xo.atpxo_reltime ) {
-               /* discard expired response */
-#ifdef EBUG
-               printf( "<%d> expiring tid %hu\n", getpid(),
-                       cb->atpbuf_info.atpbuf_xo.atpxo_tid );
-#endif /* EBUG */
-               if ( pb == NULL ) {
-                   ah->atph_sent = cb->atpbuf_next;
-               } else {
-                   pb->atpbuf_next = cb->atpbuf_next;
-               }
-
-               for ( i = 0; i < 8; ++i ) {
-                   if ( cb->atpbuf_info.atpbuf_xo.atpxo_packet[ i ]
-                           != NULL ) {
-                       atp_free_buf( cb->atpbuf_info.atpbuf_xo.atpxo_packet[ i ] );
-                   }
-               }
-               atp_free_buf( cb );
-
-               if (( cb = pb ) == NULL )
-                   break;
-
-           } else if ( at_addr_eq( &saddr, &cb->atpbuf_addr )) {
-               if ( cb->atpbuf_info.atpbuf_xo.atpxo_tid == tid ) {
-                   break;
-               }
-           }
-       }
-
-       if ( cb != NULL ) {
-#ifdef EBUG
-           printf( "<%d> duplicate request -- re-sending XO resp\n",
-                   getpid());
-#endif /* EBUG */
-           /* matches an old response -- just re-send and reset expire */
-           cb->atpbuf_info.atpbuf_xo.atpxo_tv = tv;
-           for ( i = 0; i < 8; ++i ) {
-               if ( cb->atpbuf_info.atpbuf_xo.atpxo_packet[i] != NULL &&
-                       req_hdr.atphd_bitmap & ( 1 << i )) {
-                   netddp_sendto( ah->atph_socket,
-                           cb->atpbuf_info.atpbuf_xo.atpxo_packet[i]->atpbuf_info.atpbuf_data,
-                           cb->atpbuf_info.atpbuf_xo.atpxo_packet[i]->atpbuf_dlen,
-                           0, (struct sockaddr *) &saddr, sizeof( struct sockaddr_at));
-               }
-           }
-       }
-
-       if ( cb == NULL ) {
-           /* new request -- queue it and return */
-           memcpy( &abuf->atpbuf_addr, &saddr, sizeof( struct sockaddr_at ));
-           memcpy( faddr, &saddr, sizeof( struct sockaddr_at ));
-           abuf->atpbuf_next = ah->atph_queue;
-           ah->atph_queue = abuf;
-           return( ATP_TREQ );
-       } else {
-           atp_free_buf( abuf );
-           return( 0 );
-       }
-    }
-
-    /*
-     * we got a response: update bitmap
-     */
-    memcpy( &req_hdr, ah->atph_reqpkt->atpbuf_info.atpbuf_data + 1, 
-           sizeof( struct atphdr ));
-    if ( requesting && ah->atph_rbitmap & ( 1<<resp_hdr.atphd_bitmap )
-               && req_hdr.atphd_tid == resp_hdr.atphd_tid ) {
-       ah->atph_rbitmap &= ~( 1<<resp_hdr.atphd_bitmap );
-
-       if ( ah->atph_resppkt[ resp_hdr.atphd_bitmap ] != NULL ) {
-           atp_free_buf( ah->atph_resppkt[ resp_hdr.atphd_bitmap ] );
-       }
-       ah->atph_resppkt[ resp_hdr.atphd_bitmap ] = abuf;
-
-       /* if End Of Message, clear all higher bitmap bits
-       */
-       if ( resp_hdr.atphd_ctrlinfo & ATP_EOM ) {
-#ifdef EBUG
-           printf( "<%d> EOM -- seq num %d  current bitmap %d\n",
-               getpid(), resp_hdr.atphd_bitmap, ah->atph_rbitmap );
-#endif /* EBUG */
-           mask = 1 << resp_hdr.atphd_bitmap;
-           ah->atph_rbitmap &= ( mask | (mask-1) );
-       }
-
-       /* if Send Trans. Status, send updated request
-       */
-       if ( resp_hdr.atphd_ctrlinfo & ATP_STS ) {
-#ifdef EBUG
-           puts( "STS" );
-#endif /* EBUG */
-           req_hdr.atphd_bitmap = ah->atph_rbitmap;
-           memcpy(ah->atph_reqpkt->atpbuf_info.atpbuf_data + 1,
-                  &req_hdr, sizeof( struct atphdr ));
-           if ( netddp_sendto( ah->atph_socket,
-                   ah->atph_reqpkt->atpbuf_info.atpbuf_data,
-                   ah->atph_reqpkt->atpbuf_dlen, 0,
-                   (struct sockaddr *) &ah->atph_reqpkt->atpbuf_addr,
-                   sizeof( struct sockaddr_at )) !=
-                   ah->atph_reqpkt->atpbuf_dlen ) {
-               atp_free_buf( abuf );
-               return( -1 );
-           }
-       }
-    } else {
-       /*
-        * we are not expecting this response -- toss it
-        */
-       atp_free_buf( abuf );
-#ifdef EBUG
-       printf( "atp_rsel: ignoring resp bm=%x tid=%d (expected %x/%d)\n",
-               resp_hdr.atphd_bitmap, ntohs( resp_hdr.atphd_tid ),
-               ah->atph_rbitmap, ah->atph_tid );
-#endif /* EBUG */
-    }
-
-    if ( !ah->atph_rbitmap && ( req_hdr.atphd_ctrlinfo & ATP_XO )) {
-       /*
-        * successful completion - send release
-        * the release consists of DDP type byte + ATP header + 4 user bytes
-        */
-       req_hdr.atphd_ctrlinfo = ATP_TREL;
-       memcpy( ah->atph_reqpkt->atpbuf_info.atpbuf_data + 1, &req_hdr, 
-           sizeof( struct atphdr ));
-       memset( ah->atph_reqpkt->atpbuf_info.atpbuf_data + ATP_HDRSIZE, 0, 4 );
-       ah->atph_reqpkt->atpbuf_dlen = sizeof( struct atphdr ) + ATP_HDRSIZE;
-#ifdef EBUG
-       printf( "<%d> sending TREL", getpid() );
-       bprint( ah->atph_reqpkt->atpbuf_info.atpbuf_data,
-               ah->atph_reqpkt->atpbuf_dlen );
-#endif /* EBUG */
-#ifdef DROP_ATPTREL
-       if (( ++release_count % 10 ) != 0 ) {
-#endif /* DROP_ATPTREL */
-       netddp_sendto( ah->atph_socket, 
-                      ah->atph_reqpkt->atpbuf_info.atpbuf_data,
-                      ah->atph_reqpkt->atpbuf_dlen, 0,
-                      (struct sockaddr *) &ah->atph_reqpkt->atpbuf_addr,
-                      sizeof( struct sockaddr_at));
-#ifdef DROP_ATPTREL
-       }
-#endif /* DROP_ATPTREL */
-    }
-
-    if ( ah->atph_rbitmap != 0 ) {
-       if ( ah->atph_reqtries > 0
-               || ah->atph_reqtries == ATP_TRIES_INFINITE ) {
-           return( 0 );
-       } else {
-           errno = ETIMEDOUT;
-           return( -1 );
-       }
-    }
-
-    memcpy( faddr, &saddr, sizeof( struct sockaddr_at ));
-    return( ATP_TRESP );
-}
diff --git a/libatalk/atp/atp_sreq.c b/libatalk/atp/atp_sreq.c
deleted file mode 100644 (file)
index a34f347..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * $Id: atp_sreq.c,v 1.5 2002-01-17 06:08:55 srittau Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/time.h>
-#include <errno.h>
-#include <sys/uio.h>
-#include <signal.h>
-
-#include <netinet/in.h>
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-
-#include <atalk/netddp.h>
-#include <atalk/atp.h>
-#include <atalk/util.h>
-
-#include "atp_internals.h"
-
-/*
- * ah:        open atp handle
- * atpb:      parameter block
- * respcount: buffers available for response
- * flags:     ATP_XO, ATP_TREL
- */
-int
-atp_sreq( ATP ah, struct atp_block *atpb, int respcount, u_int8_t flags )
-{
-    struct atpbuf      *req_buf;
-    int                        i;
-
-#ifdef EBUG
-    atp_print_bufuse( ah, "atp_sreq" );
-#endif /* EBUG */
-
-    /* check parameters
-    */
-    if ( atpb->atp_sreqdlen < 4 || atpb->atp_sreqdlen > ATP_MAXDATA
-           || ( respcount < 0 ) || ( respcount > 8 )
-           || ( atpb->atp_sreqto < 0 ) || (( atpb->atp_sreqtries < 1 )
-           && ( atpb->atp_sreqtries != ATP_TRIES_INFINITE ))) {
-       errno = EINVAL;
-       return -1;
-    }
-    /* clean up any packet fragments left from last request
-    */
-    for ( i = 0; i < 8; ++i ) {
-       if ( ah->atph_resppkt[ i ] != NULL ) {
-           atp_free_buf( ah->atph_resppkt[ i ] );
-           ah->atph_resppkt[ i ] = NULL;
-       }
-    }
-
-    /* generate bitmap, tid and ctrlinfo
-    */
-    atpb->atp_bitmap = ( 1 << respcount ) - 1;
-
-    /* allocate a new buffer and build request packet
-    */
-    if (( req_buf = atp_alloc_buf()) == NULL ) {
-       return( -1 );
-    }
-    atp_build_req_packet( req_buf, ah->atph_tid++, flags | ATP_TREQ, atpb );
-    memcpy( &req_buf->atpbuf_addr, atpb->atp_saddr,
-           sizeof( struct sockaddr_at ));
-
-    /* send the initial request
-    */
-#ifdef EBUG
-    printf( "\n<%d> atp_sreq: sending a %ld byte packet ", getpid(),
-           req_buf->atpbuf_dlen );
-    atp_print_addr( " to", atpb->atp_saddr );
-    putchar( '\n' );
-    bprint( req_buf->atpbuf_info.atpbuf_data, req_buf->atpbuf_dlen );
-#endif /* EBUG */
-
-    gettimeofday( &ah->atph_reqtv, (struct timezone *)0 );
-#ifdef DROPPACKETS
-if (( random() % 3 ) != 2 ) {
-#endif /* DROPPACKETS */
-    if ( netddp_sendto( ah->atph_socket, req_buf->atpbuf_info.atpbuf_data,
-           req_buf->atpbuf_dlen, 0, (struct sockaddr *) atpb->atp_saddr,
-           sizeof( struct sockaddr_at )) != req_buf->atpbuf_dlen ) {
-       atp_free_buf( req_buf );
-       return( -1 );
-    }
-#ifdef DROPPACKETS
-} else printf( "<%d> atp_sreq: dropped request\n", getpid() );
-#endif /* DROPPACKETS */
-
-    if ( atpb->atp_sreqto != 0 ) {
-       if ( ah->atph_reqpkt != NULL ) {
-           atp_free_buf( ah->atph_reqpkt );
-       }
-       ah->atph_reqto = atpb->atp_sreqto;
-       if ( atpb->atp_sreqtries == ATP_TRIES_INFINITE ) {
-           ah->atph_reqtries = ATP_TRIES_INFINITE;
-       } else {
-           /* we already sent one */
-           ah->atph_reqtries = atpb->atp_sreqtries - 1;
-       }
-       ah->atph_reqpkt = req_buf;
-       ah->atph_rbitmap = ( 1 << respcount ) - 1;
-       ah->atph_rrespcount = respcount;
-    } else {
-       atp_free_buf( req_buf );
-       ah->atph_rrespcount = 0;
-    }
-
-    return( 0 );
-}
diff --git a/libatalk/atp/atp_sresp.c b/libatalk/atp/atp_sresp.c
deleted file mode 100644 (file)
index 781760b..0000000
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * $Id: atp_sresp.c,v 1.6 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <errno.h>
-#include <sys/uio.h>
-#include <sys/time.h>
-#include <sys/socket.h>
-
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-
-#include <atalk/netddp.h>
-#include <atalk/atp.h>
-#include <atalk/util.h>
-
-#include "atp_internals.h"
-
-/* send a transaction response
-*/
-int atp_sresp(
-    ATP                        ah,             /* open atp handle */
-    struct atp_block   *atpb)          /* parameter block */
-{
-    int                        i;
-    u_int8_t           ctrlinfo;
-    struct atpbuf      *resp_buf;
-    struct atpbuf      *save_buf; /* uninitialized, OK 310105 */
-
-#ifdef EBUG
-    atp_print_bufuse( ah, "atp_sresp" );
-#endif /* EBUG */
-
-    /* check parameters
-    */
-    for ( i = atpb->atp_sresiovcnt - 1; i >= 0; --i ) {
-       if ( atpb->atp_sresiov[ i ].iov_len > ATP_MAXDATA ) 
-           break;
-    }
-    if ( i >= 0 || atpb->atp_sresiovcnt < 1 || atpb->atp_sresiovcnt > 8 ) {
-       errno = EINVAL;
-       return -1;
-    }
-
-    /* allocate a new buffer for reponse packet construction
-    */
-    if (( resp_buf = atp_alloc_buf()) == NULL ) {
-       return -1;
-    }
-
-    /* send all the response packets
-     * also need to attach list to ah for dup. detection (if XO)
-    */
-#ifdef EBUG
-    printf( "<%d> preparing to send %s response tid=%hu ", getpid(),
-           ah->atph_rxo ? "XO" : "", ah->atph_rtid );
-    atp_print_addr( " to", atpb->atp_saddr );
-    putchar( '\n' );
-#endif /* EBUG */
-    if ( ah->atph_rxo ) {
-       if (( save_buf = atp_alloc_buf()) == NULL ) {
-           return -1;
-       }
-       for ( i = 0; i < 8;
-               save_buf->atpbuf_info.atpbuf_xo.atpxo_packet[ i++ ] = NULL );
-    }
-    for ( i = 0; i < atpb->atp_sresiovcnt; ++i ) {
-       ctrlinfo = ATP_TRESP;
-#ifdef STS_RESPONSES
-       ctrlinfo |= ATP_STS;
-#endif /* STS_RESPONSES */
-       if ( i == atpb->atp_sresiovcnt-1 ) {
-           ctrlinfo |= ATP_EOM;
-       }
-       atp_build_resp_packet( resp_buf, ah->atph_rtid, ctrlinfo, atpb, i );
-
-       if ( ah->atph_rxo ) {
-           save_buf->atpbuf_info.atpbuf_xo.atpxo_packet[i] = resp_buf;
-       }
-#ifdef DROPPACKETS
-if (( random() % 3 ) != 2 ) {
-#endif /* DROPPACKETS */
-#ifdef EBUG
-printf( "<%d> sending packet tid=%hu serial no.=%d\n", getpid(),
-  ah->atph_rtid, i );
-bprint( resp_buf->atpbuf_info.atpbuf_data, resp_buf->atpbuf_dlen );
-#endif /* EBUG */
-       if ( netddp_sendto( ah->atph_socket, resp_buf->atpbuf_info.atpbuf_data,
-         resp_buf->atpbuf_dlen, 0, (struct sockaddr *) atpb->atp_saddr,
-         sizeof( struct sockaddr_at )) != resp_buf->atpbuf_dlen ) {
-           if ( ah->atph_rxo ) {
-               for ( ; i >= 0; --i ) {
-                   atp_free_buf( save_buf->atpbuf_info.atpbuf_xo.atpxo_packet[ i ] );
-               }
-               atp_free_buf( save_buf );
-           }
-           return -1;
-       }
-#ifdef DROPPACKETS
-} else printf( "<%d> atp_sresp: dropped serial no. %d\n", getpid(),  i );
-#endif /* DROPPACKETS */
-       /* allocate a buffer for next packet (if XO mode)
-       */
-       if ( ah->atph_rxo && ( resp_buf = atp_alloc_buf()) == NULL ) {
-           return -1;
-       }
-    }
-    atp_free_buf( resp_buf );
-    if ( ah->atph_rxo ) {
-       /* record timestamp, tid, release time, and destination address
-       */
-       gettimeofday( &save_buf->atpbuf_info.atpbuf_xo.atpxo_tv,
-               (struct timezone *) 0 );
-       save_buf->atpbuf_info.atpbuf_xo.atpxo_tid = ah->atph_rtid;
-       save_buf->atpbuf_info.atpbuf_xo.atpxo_reltime = ah->atph_rreltime;
-       memcpy( &save_buf->atpbuf_addr, atpb->atp_saddr, 
-               sizeof( struct sockaddr_at ));
-
-       /* add to list of packets we have sent
-       */
-       save_buf->atpbuf_next = ah->atph_sent;
-       ah->atph_sent = save_buf;
-#ifdef EBUG
-printf( "<%d> saved XO response\n", getpid());
-#endif /* EBUG */
-    }
-    return 0;
-}
index 97649a7cb2b589f289a6aa7ea0062670b0b65de7..d6b17278abd378865158d88cfaa9bd2f5c3ff6aa 100644 (file)
@@ -6,12 +6,10 @@
 #ifndef _ATALK_CNID_CDB__H
 #define _ATALK_CNID_CDB__H 1
 
-#include <sys/cdefs.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <string.h>
 
-#include <netatalk/endian.h>
 #include <atalk/cnid.h>
 
 /* cnid_open.c */
@@ -22,19 +20,19 @@ extern struct _cnid_db *cnid_cdb_open (struct cnid_open_args *args);
 extern void cnid_cdb_close (struct _cnid_db *);
 
 /* cnid_add.c */
-extern cnid_t cnid_cdb_add (struct _cnid_db *, const struct stat *, const cnid_t,
-                           char *, const size_t, cnid_t);
+extern cnid_t cnid_cdb_add (struct _cnid_db *, const struct stat *, cnid_t,
+                            const char *, size_t, cnid_t);
 extern int cnid_cdb_getstamp (struct _cnid_db *, void *, const size_t );
 
 /* cnid_get.c */
-extern cnid_t cnid_cdb_get (struct _cnid_db *, const cnid_t, char *, const size_t); 
+extern cnid_t cnid_cdb_get (struct _cnid_db *, cnid_t, const char *, size_t); 
 extern char *cnid_cdb_resolve (struct _cnid_db *, cnid_t *, void *, size_t ); 
-extern cnid_t cnid_cdb_lookup (struct _cnid_db *, const struct stat *, const cnid_t,
-                              char *, const size_t);
+extern cnid_t cnid_cdb_lookup (struct _cnid_db *, const struct stat *, cnid_t,
+                               const char *, size_t);
 
 /* cnid_update.c */
-extern int cnid_cdb_update (struct _cnid_db *, const cnid_t, const struct stat *,
-                           const cnid_t, char *, size_t);
+extern int cnid_cdb_update (struct _cnid_db *, cnid_t, const struct stat *,
+                            cnid_t, const char *, size_t);
 
 /* cnid_delete.c */
 extern int cnid_cdb_delete (struct _cnid_db *, const cnid_t);
@@ -46,7 +44,7 @@ extern int cnid_cdb_lock   (void *);
 extern int cnid_cdb_unlock (void *);
 
 extern cnid_t cnid_cdb_rebuild_add (struct _cnid_db *, const struct stat *,
-                const cnid_t, char *, const size_t, cnid_t);
+                                    cnid_t, const char *, size_t, cnid_t);
 
 
 #endif /* include/atalk/cnid_cdb.h */
index 418f68cd647cf1fabf777963ef95b71a96537ad5..a1e69a76ac5446a37afde531b208c9cbdc1a46bf 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: cnid_cdb_add.c,v 1.8 2009-11-20 17:22:11 didg Exp $
- *
  * Copyright (c) 1999. Adrian Sun (asun@zoology.washington.edu)
  * All Rights Reserved. See COPYRIGHT.
  *
 #endif /* HAVE_CONFIG_H */
 
 #ifdef CNID_BACKEND_CDB
+#include <arpa/inet.h>
 #include "cnid_cdb_private.h"
 
-extern int cnid_cdb_update(struct _cnid_db *cdb, const cnid_t id, const struct stat *st,
-                const cnid_t did, char *name, const size_t len);
-
+extern int cnid_cdb_update(struct _cnid_db *cdb, cnid_t id, const struct stat *st,
+                           cnid_t did, const char *name, size_t len);
 
 #define tid    NULL
 
@@ -168,8 +166,7 @@ cleanup:
 
 /* ------------------------ */
 cnid_t cnid_cdb_add(struct _cnid_db *cdb, const struct stat *st,
-                const cnid_t did, char *name, const size_t len,
-                cnid_t hint)
+                    cnid_t did, const char *name, size_t len, cnid_t hint)
 {
     CNID_private *db;
     DBT key, data;
index e95033737544619d8b2a720ff8590884673ce891..1d14640af1fb68c77b2e9903a07385a36e47b619 100644 (file)
@@ -12,6 +12,7 @@
 #endif /* HAVE_CONFIG_H */
 
 #ifdef CNID_BACKEND_CDB
+#include <arpa/inet.h>
 #include "cnid_cdb_private.h"
 
 #define tid    NULL
index 5ae4ea02f0ef29fd6de9971f7e19967f83b111fa..d4e090550eab6f85e3de0aa6671f7aa7d6006453 100644 (file)
@@ -1,7 +1,3 @@
-/*
- * $Id: cnid_cdb_get.c,v 1.5 2009-10-29 13:38:16 didg Exp $
- */
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
@@ -10,8 +6,7 @@
 #include "cnid_cdb_private.h"
 
 /* Return CNID for a given did/name. */
-cnid_t cnid_cdb_get(struct _cnid_db *cdb, const cnid_t did, char *name,
-                const size_t len)
+cnid_t cnid_cdb_get(struct _cnid_db *cdb, cnid_t did, const char *name, size_t len)
 {
     char start[CNID_DID_LEN + MAXPATHLEN + 1], *buf;
     CNID_private *db;
index 07de091067fb3b561925e4003f5f2d3831d353b1..7b2f933c5182b4e1c4d4974f5a46c3bd7aa695ac 100644 (file)
@@ -1,7 +1,3 @@
-/*
- * $Id: cnid_cdb_lookup.c,v 1.6 2009-11-20 17:22:11 didg Exp $
- */
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
@@ -14,8 +10,8 @@
 
 /* This returns the CNID corresponding to a particular file.  It will
  * also fix up the various databases if there's a problem. */
-cnid_t cnid_cdb_lookup(struct _cnid_db *cdb, const struct stat *st, const cnid_t did,
-                   char *name, const size_t len)
+cnid_t cnid_cdb_lookup(struct _cnid_db *cdb, const struct stat *st, cnid_t did,
+                       const char *name, size_t len)
 {
     unsigned char *buf;
     CNID_private *db;
index 10ecc78d8c34efaf51365820954b1ff5d06c0f6a..056420dad099f1123a6e514f98630055d285fa3a 100644 (file)
 
 static char *old_dbfiles[] = {"cnid.db", NULL};
 
-/* -----------------------
- * bandaid for LanTest performance pb. for now not used, cf. ifdef 0 below
-*/
-static int my_yield(void)
-{
-    struct timeval t;
-    int ret;
-
-    t.tv_sec = 0;
-    t.tv_usec = 1000;
-    ret = select(0, NULL, NULL, NULL, &t);
-    return 0;
-}
-
 /* --------------- */
 static int didname(DB *dbp _U_, const DBT *pkey _U_, const DBT *pdata, DBT *skey)
 {
@@ -368,7 +354,6 @@ struct _cnid_db *cnid_cdb_open(struct cnid_open_args *args)
         }
     }
 
-    db_env_set_func_yield(my_yield);
     return cdb;
 
   fail_appinit:
index 1373f5cb01d4f273b46e60d5c95e8922edbfbbc9..ff28be84c9d399e309837bb0257fcf792d67a22c 100644 (file)
@@ -1,7 +1,3 @@
-/*
- * $Id: cnid_cdb_private.h,v 1.7 2009-11-20 17:22:11 didg Exp $
- */
-
 #ifndef LIBATALK_CDB_PRIVATE_H
 #define LIBATALK_CDB_PRIVATE_H 1
 
@@ -9,26 +5,17 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include <netatalk/endian.h>
-
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <sys/param.h>
 #include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
-#endif /* HAVE_SYS_TIME_H */
-#ifdef HAVE_TIME_H
 #include <time.h>
-#endif
-#include <sys/cdefs.h>
+#include <arpa/inet.h>
+
 #include <db.h>
 
 #include <atalk/logger.h>
index 351f31536073982a4b3f08be5e1b40f61fec8f21..be2db1023692be7e7d966b76e23d1773b37ee1a0 100644 (file)
@@ -73,10 +73,8 @@ cleanup:
     return CNID_INVALID;
 }
 
-/* ------------------------ */
 cnid_t cnid_cdb_rebuild_add(struct _cnid_db *cdb, const struct stat *st,
-                const cnid_t did, char *name, const size_t len, 
-               cnid_t hint)
+                            cnid_t did, const char *name, size_t len, cnid_t hint)
 {
     CNID_private *db;
     DBT key, data;
index f1a4a30dc48b24f6bedbbca48d7d034f81d57615..f7676c840054516c10be062dae3e874719b7e23e 100644 (file)
@@ -1,7 +1,3 @@
-/*
- * $Id: cnid_cdb_update.c,v 1.4 2009-11-20 17:22:11 didg Exp $
- */
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
@@ -14,9 +10,8 @@
 /* cnid_update: takes the given cnid and updates the metadata.  To
  * handle the did/name data, there are a bunch of functions to get
  * and set the various fields. */
-int cnid_cdb_update(struct _cnid_db *cdb, const cnid_t id, const struct stat *st,
-                const cnid_t did, char *name, const size_t len
-                /*, const char *info, const int infolen*/)
+int cnid_cdb_update(struct _cnid_db *cdb, cnid_t id, const struct stat *st,
+                    cnid_t did, const char *name, size_t len)
 {
     unsigned char *buf;
     CNID_private *db;
index 8bb6373ee373e91acd57912a71414b3eebaafc30..0a977e6ae8a5f4f469b48b7b037e1811d370ba76 100644 (file)
@@ -29,6 +29,7 @@
 #include <atalk/list.h>
 #include <atalk/logger.h>
 #include <atalk/util.h>
+#include <atalk/compat.h>
 
 /* List of all registered modules. */
 static struct list_head modules = ATALK_LIST_HEAD_INIT(modules);
@@ -161,7 +162,7 @@ struct _cnid_db *cnid_open(const char *volpath, mode_t mask, char *type, int fla
 }
 
 /* ------------------- */
-static void block_signal( u_int32_t flags)
+static void block_signal(uint32_t flags)
 {
     if ((flags & CNID_FLAG_BLOCK)) {
         pthread_sigmask(SIG_BLOCK, &sigblockset, NULL);
@@ -169,7 +170,7 @@ static void block_signal( u_int32_t flags)
 }
 
 /* ------------------- */
-static void unblock_signal(u_int32_t flags)
+static void unblock_signal(uint32_t flags)
 {
     if ((flags & CNID_FLAG_BLOCK)) {
         pthread_sigmask(SIG_UNBLOCK, &sigblockset, NULL);
@@ -199,7 +200,7 @@ static cnid_t valide(cnid_t id)
 /* Closes CNID database. Currently it's just a wrapper around db->cnid_close(). */
 void cnid_close(struct _cnid_db *db)
 {
-u_int32_t flags;
+    uint32_t flags;
 
     if (NULL == db) {
         LOG(log_error, logtype_afpd, "Error: cnid_close called with NULL argument !");
index ded82431fae704beeaa06f352f61f36b05500cff..32be8f475408fc644d21d010dc9e76091678d9e4 100644 (file)
 #ifdef CNID_BACKEND_DBD
 
 #include <stdlib.h>
-#ifdef HAVE_SYS_STAT_H
 #include <sys/stat.h>
-#endif /* HAVE_SYS_STAT_H */
-#ifdef HAVE_SYS_UIO_H
 #include <sys/uio.h>
-#endif /* HAVE_SYS_UIO_H */
-#ifdef HAVE_STRINGS_H
-#include <strings.h>
-#endif
 #include <sys/time.h>
 #include <sys/un.h>
 #include <sys/socket.h>
@@ -33,8 +26,8 @@
 #include <errno.h>
 #include <netdb.h>
 #include <time.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/logger.h>
 #include <atalk/adouble.h>
 #include <atalk/cnid.h>
@@ -275,7 +268,7 @@ static int send_packet(CNID_private *db, struct cnid_dbd_rqst *rqst)
     vecs = 1;
 
     if (rqst->namelen) {
-        iov[1].iov_base = rqst->name;
+        iov[1].iov_base = (char *)rqst->name;
         iov[1].iov_len  = rqst->namelen;
         towrite += rqst->namelen;
         vecs++;
@@ -540,8 +533,7 @@ void cnid_dbd_close(struct _cnid_db *cdb)
 
 /* ---------------------- */
 cnid_t cnid_dbd_add(struct _cnid_db *cdb, const struct stat *st,
-                    const cnid_t did, char *name, const size_t len,
-                    cnid_t hint)
+                    cnid_t did, const char *name, size_t len, cnid_t hint)
 {
     CNID_private *db;
     struct cnid_dbd_rqst rqst;
@@ -605,7 +597,7 @@ cnid_t cnid_dbd_add(struct _cnid_db *cdb, const struct stat *st,
 }
 
 /* ---------------------- */
-cnid_t cnid_dbd_get(struct _cnid_db *cdb, const cnid_t did, char *name, const size_t len)
+cnid_t cnid_dbd_get(struct _cnid_db *cdb, cnid_t did, const char *name, size_t len)
 {
     CNID_private *db;
     struct cnid_dbd_rqst rqst;
@@ -731,8 +723,8 @@ int cnid_dbd_getstamp(struct _cnid_db *cdb, void *buffer, const size_t len)
 }
 
 /* ---------------------- */
-cnid_t cnid_dbd_lookup(struct _cnid_db *cdb, const struct stat *st, const cnid_t did,
-                       char *name, const size_t len)
+cnid_t cnid_dbd_lookup(struct _cnid_db *cdb, const struct stat *st, cnid_t did,
+                       const char *name, size_t len)
 {
     CNID_private *db;
     struct cnid_dbd_rqst rqst;
@@ -793,7 +785,7 @@ cnid_t cnid_dbd_lookup(struct _cnid_db *cdb, const struct stat *st, const cnid_t
 }
 
 /* ---------------------- */
-int cnid_dbd_find(struct _cnid_db *cdb, char *name, size_t namelen, void *buffer, size_t buflen)
+int cnid_dbd_find(struct _cnid_db *cdb, const char *name, size_t namelen, void *buffer, size_t buflen)
 {
     CNID_private *db;
     struct cnid_dbd_rqst rqst;
@@ -848,8 +840,8 @@ int cnid_dbd_find(struct _cnid_db *cdb, char *name, size_t namelen, void *buffer
 }
 
 /* ---------------------- */
-int cnid_dbd_update(struct _cnid_db *cdb, const cnid_t id, const struct stat *st,
-                    const cnid_t did, char *name, const size_t len)
+int cnid_dbd_update(struct _cnid_db *cdb, cnid_t id, const struct stat *st,
+                    cnid_t did, const char *name, size_t len)
 {
     CNID_private *db;
     struct cnid_dbd_rqst rqst;
@@ -903,8 +895,7 @@ int cnid_dbd_update(struct _cnid_db *cdb, const cnid_t id, const struct stat *st
 
 /* ---------------------- */
 cnid_t cnid_dbd_rebuild_add(struct _cnid_db *cdb, const struct stat *st,
-                            const cnid_t did, char *name, const size_t len,
-                            cnid_t hint)
+                            cnid_t did, const char *name, size_t len, cnid_t hint)
 {
     CNID_private *db;
     struct cnid_dbd_rqst rqst;
index 1f645908358b442633beae7e730e9789be690975..fdba4c042a62591e3e771ed449ad7de6588986ca 100644 (file)
@@ -8,31 +8,30 @@
 #ifndef _ATALK_CNID_DBD__H
 #define _ATALK_CNID_DBD__H 1
 
-#include <sys/cdefs.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <string.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/cnid.h>
 
 extern struct _cnid_module cnid_dbd_module;
 extern struct _cnid_db *cnid_dbd_open (struct cnid_open_args *args);
 extern void   cnid_dbd_close      (struct _cnid_db *);
-extern cnid_t cnid_dbd_add        (struct _cnid_db *, const struct stat *, const cnid_t,
-                                   char *, const size_t, cnid_t);
-extern cnid_t cnid_dbd_get        (struct _cnid_db *, const cnid_t, char *, const size_t); 
+extern cnid_t cnid_dbd_add        (struct _cnid_db *, const struct stat *, cnid_t,
+                                   const char *, size_t, cnid_t);
+extern cnid_t cnid_dbd_get        (struct _cnid_db *, cnid_t, const char *, size_t); 
 extern char  *cnid_dbd_resolve    (struct _cnid_db *, cnid_t *, void *, size_t ); 
 extern int    cnid_dbd_getstamp   (struct _cnid_db *, void *, const size_t ); 
-extern cnid_t cnid_dbd_lookup     (struct _cnid_db *, const struct stat *, const cnid_t,
-                                   char *, const size_t);
-extern int    cnid_dbd_find       (struct _cnid_db *cdb, char *name, size_t namelen,
+extern cnid_t cnid_dbd_lookup     (struct _cnid_db *, const struct stat *, cnid_t,
+                                   const char *, size_t);
+extern int    cnid_dbd_find       (struct _cnid_db *cdb, const char *name, size_t namelen,
                                    void *buffer, size_t buflen);
-extern int    cnid_dbd_update     (struct _cnid_db *, const cnid_t, const struct stat *,
-                                   const cnid_t, char *, size_t);
+extern int    cnid_dbd_update     (struct _cnid_db *, cnid_t, const struct stat *,
+                                   cnid_t, const char *, size_t);
 extern int    cnid_dbd_delete     (struct _cnid_db *, const cnid_t);
 extern cnid_t cnid_dbd_rebuild_add(struct _cnid_db *, const struct stat *,
-                                   const cnid_t, char *, const size_t, cnid_t);
+                                   cnid_t, const char *, size_t, cnid_t);
 
 /* FIXME: These functions could be static in cnid_dbd.c */
 
index 5502fb60f94c49836b9de1cd62005ebdeec7f841..5903d03fe449da281238818e9501c57e812cf9f1 100644 (file)
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
+#include <arpa/inet.h>
 
 /* ------------------------ */
 cnid_t cnid_last_add(struct _cnid_db *cdb, const struct stat *st,
-                     const cnid_t did _U_, char *name _U_, const size_t len _U_, cnid_t hint _U_)
+                     cnid_t did _U_, const char *name _U_, size_t len _U_, cnid_t hint _U_)
 {
 
     /* FIXME: it relies on fact, that this is never called twice for the same file/dir. */
@@ -86,9 +87,8 @@ int cnid_last_delete(struct _cnid_db *cdb _U_, const cnid_t id _U_)
 }
 
 
-
 /* Return CNID for a given did/name. */
-cnid_t cnid_last_get(struct _cnid_db *cdb _U_, const cnid_t did _U_, char *name _U_, const size_t len _U_)
+cnid_t cnid_last_get(struct _cnid_db *cdb _U_, cnid_t did _U_, const char *name _U_, size_t len _U_)
 {
     /* FIXME: it relies on fact, that this is never called twice for the same file/dir. */
     /* Propably we should look through DID tree. */
@@ -96,10 +96,9 @@ cnid_t cnid_last_get(struct _cnid_db *cdb _U_, const cnid_t did _U_, char *name
 }
 
 
-
 /* */
-cnid_t cnid_last_lookup(struct _cnid_db *cdb _U_, const struct stat *st _U_, const cnid_t did _U_, 
-    char *name _U_, const size_t len _U_)
+cnid_t cnid_last_lookup(struct _cnid_db *cdb _U_, const struct stat *st _U_, cnid_t did _U_, 
+                        const char *name _U_, size_t len _U_)
 {
     /* FIXME: this function doesn't work in [last] scheme ! */
     /* Should be never called or CNID should be somewhat refactored again. */
@@ -175,8 +174,8 @@ char *cnid_last_resolve(struct _cnid_db *cdb _U_, cnid_t * id _U_, void *buffer
 }
 
 
-int cnid_last_update(struct _cnid_db *cdb _U_, const cnid_t id _U_, const struct stat *st _U_,
-                     const cnid_t did  _U_, char *name  _U_, const size_t len _U_)
+int cnid_last_update(struct _cnid_db *cdb _U_, cnid_t id _U_, const struct stat *st _U_,
+                     cnid_t did  _U_, const char *name  _U_, size_t len _U_)
 {
     return 0;
 }
index fdcf32a5cc524fc74e4abba68670d4ef792b20a4..7fce6e7268d04462cd7506d5bc4b8981c4ca48d5 100644 (file)
@@ -1,4 +1,3 @@
-
 /* 
  * interface for database access to cnids. i do it this way to abstract
  * things a bit in case we want to change the underlying implementation.
@@ -7,12 +6,10 @@
 #ifndef _ATALK_CNID_LAST__H
 #define _ATALK_CNID_LAST__H 1
 
-#include <sys/cdefs.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <string.h>
 
-#include <netatalk/endian.h>
 #include <atalk/cnid.h>
 
 struct _cnid_last_private {
@@ -22,13 +19,13 @@ struct _cnid_last_private {
 extern struct _cnid_module cnid_last_module;
 extern struct _cnid_db *cnid_last_open (struct cnid_open_args *args);
 extern void cnid_last_close (struct _cnid_db *);
-extern cnid_t cnid_last_add (struct _cnid_db *, const struct stat *, const cnid_t,
-                                 char *, const size_t, cnid_t);
-extern cnid_t cnid_last_get (struct _cnid_db *, const cnid_t, char *, const size_t);
+extern cnid_t cnid_last_add (struct _cnid_db *, const struct stat *, cnid_t,
+                             const char *, size_t, cnid_t);
+extern cnid_t cnid_last_get (struct _cnid_db *, cnid_t, const char *, size_t);
 extern char *cnid_last_resolve (struct _cnid_db *, cnid_t *, void *, size_t);
-extern cnid_t cnid_last_lookup (struct _cnid_db *, const struct stat *, const cnid_t, char *, const size_t);
-extern int cnid_last_update (struct _cnid_db *, const cnid_t, const struct stat *,
-                                 const cnid_t, char *, size_t);
-extern int cnid_last_delete (struct _cnid_db *, const cnid_t);
+extern cnid_t cnid_last_lookup (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t);
+extern int cnid_last_update (struct _cnid_db *, cnid_t, const struct stat *,
+                             cnid_t, const char *, size_t);
+extern int cnid_last_delete (struct _cnid_db *, cnid_t);
 
 #endif /* include/atalk/cnid_last.h */
index 1f7a08e6336dfb2ad6274dbac77c165c0e9fd11d..64cc214b65902fb13aa439339ab28e52f2444dca 100644 (file)
@@ -6,14 +6,12 @@
 #ifndef _ATALK_CNID_TDB__H
 #define _ATALK_CNID_TDB__H 1
 
-#include <sys/cdefs.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <string.h>
-
 #include <sys/param.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/cnid.h>
 #include <atalk/cnid_private.h>
 #define STANDALONE 1
@@ -53,17 +51,17 @@ extern struct _cnid_db *cnid_tdb_open (struct cnid_open_args *args);
 extern void cnid_tdb_close (struct _cnid_db *);
 
 /* cnid_add.c */
-extern cnid_t cnid_tdb_add (struct _cnid_db *, const struct stat *, const cnid_t,
-                                 char *, const size_t, cnid_t);
+extern cnid_t cnid_tdb_add (struct _cnid_db *, const struct stat *, cnid_t,
+                            const char *, size_t, cnid_t);
 
 /* cnid_get.c */
-extern cnid_t cnid_tdb_get (struct _cnid_db *, const cnid_t, char *, const size_t);
+extern cnid_t cnid_tdb_get (struct _cnid_db *, cnid_t, const char *, size_t);
 extern char *cnid_tdb_resolve (struct _cnid_db *, cnid_t *, void *, size_t);
-extern cnid_t cnid_tdb_lookup (struct _cnid_db *, const struct stat *, const cnid_t, char *, const size_t);
+extern cnid_t cnid_tdb_lookup (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t);
 
 /* cnid_update.c */
-extern int cnid_tdb_update (struct _cnid_db *, const cnid_t, const struct stat *,
-                                 const cnid_t, char *, size_t);
+extern int cnid_tdb_update (struct _cnid_db *, cnid_t, const struct stat *,
+                            cnid_t, const char *, size_t);
 
 /* cnid_delete.c */
 extern int cnid_tdb_delete (struct _cnid_db *, const cnid_t);
@@ -72,6 +70,6 @@ extern int cnid_tdb_delete (struct _cnid_db *, const cnid_t);
 extern cnid_t cnid_tdb_nextid (struct _cnid_db *);
 
 /* construct db_cnid data. NOTE: this is not re-entrant.  */
-extern unsigned char *make_tdb_data(u_int32_t flags, const struct stat *st, const cnid_t did, const char *name, const size_t len);
+extern unsigned char *make_tdb_data(uint32_t flags, const struct stat *st, const cnid_t did, const char *name, const size_t len);
 
 #endif /* include/atalk/cnid_tdb.h */
index 5758300c2e528c6b8a513b086fb8a4fb4a43e1e9..fcb43fa2f6488d5d725a79ee43cec230571e96a3 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: cnid_tdb_add.c,v 1.4 2009-11-20 17:37:14 didg Exp $
- *
  * Copyright (c) 1999. Adrian Sun (asun@zoology.washington.edu)
  * All Rights Reserved. See COPYRIGHT.
  *
@@ -40,12 +38,12 @@ static void make_devino_data(unsigned char *buf, dev_t dev, ino_t ino)
     buf[CNID_DEV_LEN + CNID_INO_LEN - 8] = ino;    
 }
 
-unsigned char *make_tdb_data(u_int32_t flags, const struct stat *st,const cnid_t did,
+unsigned char *make_tdb_data(uint32_t flags, const struct stat *st,const cnid_t did,
                      const char *name, const size_t len)
 {
     static unsigned char start[CNID_HEADER_LEN + MAXPATHLEN + 1];
     unsigned char *buf = start  +CNID_LEN;
-    u_int32_t i;
+    uint32_t i;
 
     if (len > MAXPATHLEN)
         return NULL;
@@ -154,7 +152,7 @@ cleanup:
 
 /* ------------------------ */
 cnid_t cnid_tdb_add(struct _cnid_db *cdb, const struct stat *st,
-                     const cnid_t did, char *name, const size_t len, cnid_t hint)
+                    cnid_t did, const char *name, size_t len, cnid_t hint)
 {
     const struct stat *lstp;
     cnid_t id;
index 019eea5287567c7a024f2f038f0a7c6f0f4de360..8321d04e868eb20469c061bd08c0057c7dacc7ae 100644 (file)
@@ -1,7 +1,3 @@
-/*
- * $Id: cnid_tdb_get.c,v 1.4 2009-11-20 17:37:14 didg Exp $
- */
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif
@@ -11,7 +7,7 @@
 #include "cnid_tdb.h"
 
 /* Return CNID for a given did/name. */
-cnid_t cnid_tdb_get(struct _cnid_db *cdb, const cnid_t did, char *name, const size_t len)
+cnid_t cnid_tdb_get(struct _cnid_db *cdb, cnid_t did, const char *name, size_t len)
 {
     char start[CNID_DID_LEN + MAXPATHLEN + 1], *buf;
     struct _cnid_tdb_private *db;
index ba47e36837f197c42f6b302f0a22ed78ca68e77c..f095cd54b9c989e186e66360177b0c4bc4f8110a 100644 (file)
@@ -1,7 +1,3 @@
-/*
- * $Id: cnid_tdb_lookup.c,v 1.6 2009-11-21 11:12:49 didg Exp $
- */
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif
@@ -11,7 +7,7 @@
 #include "cnid_tdb.h"
 #include <atalk/logger.h>
 
-cnid_t cnid_tdb_lookup(struct _cnid_db *cdb, const struct stat *st, const cnid_t did, char *name, const size_t len)
+cnid_t cnid_tdb_lookup(struct _cnid_db *cdb, const struct stat *st, cnid_t did, const char *name, size_t len)
 {
     char *buf;
     struct _cnid_tdb_private *db;
@@ -19,9 +15,9 @@ cnid_t cnid_tdb_lookup(struct _cnid_db *cdb, const struct stat *st, const cnid_t
     int devino = 1, didname = 1;
     char dev[CNID_DEV_LEN];
     char ino[CNID_INO_LEN];  
-    u_int32_t type_devino  = (unsigned)-1;
-    u_int32_t type_didname = (unsigned)-1;
-    u_int32_t type;
+    uint32_t type_devino  = (unsigned)-1;
+    uint32_t type_didname = (unsigned)-1;
+    uint32_t type;
     int update = 0;
     cnid_t id_devino = 0, id_didname = 0,id = 0;
 
index d658b94ae25f785399da7175bd3cc67a5f206d69..d02ef0bcc054caa1da65ab3ccfa5f6c5885a8b5a 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: cnid_tdb_open.c,v 1.8 2010-03-31 09:47:32 franklahm Exp $
- *
  * Copyright (c) 1999. Adrian Sun (asun@zoology.washington.edu)
  * All Rights Reserved. See COPYRIGHT.
  *
@@ -131,7 +129,7 @@ struct _cnid_db *cnid_tdb_open(struct cnid_open_args *args)
 
     data = tdb_fetch(db->tdb_didname, key);
     if (!data.dptr) {
-        u_int32_t version = htonl(DBVERSION);
+        uint32_t version = htonl(DBVERSION);
 
         data.dptr = (char *)&version;
         data.dsize = sizeof(version);
index 8c4d35e379dd535b7085719df8c6eb783c719d1e..d367334e06126c8f903fe8bea20d1a0d7efea0b1 100644 (file)
@@ -1,7 +1,3 @@
-/*
- * $Id: cnid_tdb_update.c,v 1.6 2009-11-21 11:12:49 didg Exp $
- */
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif
@@ -11,9 +7,8 @@
 #include "cnid_tdb.h"
 #include <atalk/logger.h>
 
-int cnid_tdb_update(struct _cnid_db *cdb, const cnid_t id, const struct stat *st,
-                     const cnid_t did, char *name, const size_t len
-                     /*, const char *info, const int infolen */ )
+int cnid_tdb_update(struct _cnid_db *cdb, cnid_t id, const struct stat *st,
+                    cnid_t did, const char *name, size_t len)
 {
     struct _cnid_tdb_private *db;
     TDB_DATA key, data, altdata;
index 6540debf33a7eabc8f0816346a1d609e74b0fc4a..810a6c64044fb4b8006f69e9fe043adc2becaf12 100644 (file)
@@ -6,10 +6,6 @@ libcompat_la_SOURCES = \
        misc.c \
        mktemp.c        \
        getusershell.c  \
-       strcasecmp.c    \
-       strstr.c        \
-       strdup.c        \
-       inet_aton.c     \
        rquota_xdr.c    \
-       pselect.c       \
-       snprintf.c
+       pselect.c               \
+       strlcpy.c
index aa167222594dc4f087300a4a289fb3bbf7042642..5811531520ddcf860da59a6d76dae346d0e8a191 100644 (file)
@@ -2,6 +2,8 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
+#include <atalk/compat.h>
+
 #if !defined HAVE_DIRFD && defined SOLARIS
 #include <dirent.h>
 int dirfd(DIR *dir)
@@ -9,3 +11,17 @@ int dirfd(DIR *dir)
     return dir->d_fd;
 }
 #endif
+
+#ifndef HAVE_STRNLEN
+size_t strnlen(const char *s, size_t max)
+{
+    size_t len;
+  
+    for (len = 0; len < max; len++) {
+        if (s[len] == '\0') {
+            break;
+        }
+    }
+    return len;  
+}
+#endif
index d72eaa7dbdb450158dbc39b896f6c3cae9bc67f3..03dd3bb601f1d6cb849d43736c5017aa461a649d 100644 (file)
 #include <rpc/rpc.h>
 #include <rpcsvc/rquota.h>
 
+#ifndef u_int
+#define u_int unsigned
+#endif
+
 bool_t
 xdr_getquota_args(xdrs, objp)
        XDR *xdrs;
diff --git a/libatalk/compat/snprintf.c b/libatalk/compat/snprintf.c
deleted file mode 100644 (file)
index eea7729..0000000
+++ /dev/null
@@ -1,1132 +0,0 @@
-/**************************************************************************
- * Copyright 1994-2000 Patrick Powell, San Diego, CA <papowell@astart.com>
- * 
- * Modified for Netatalk 2002/02/12 Burkhard Schmidt <bs@cpfs.mpg.de>
- **************************************************************************/
-
-/*
-   Overview:
-
-   plp_snprintf( char *buffer, int len, const char *format,...)
-   plp_unsafe_snprintf( char *buffer, int len, const char *format,...)
-     its horribly unsafe companion that does NOT protect you from
-     the printing of evil control characters,  but may be necessary
-     See the man page documentation below
-   
-   This version of snprintf was developed originally for printing
-   on a motley collection of specialized hardware that had NO IO
-   library.  Due to contractual restrictions,  a clean room implementation
-   of the printf() code had to be developed.
-   
-   The method chosen for printf was to be as paranoid as possible,
-   as these platforms had NO memory protection,  and very small
-   address spaces.  This made it possible to try to print
-   very long strings, i.e. - all of memory, very easily.  To guard
-   against this,  all printing was done via a buffer, generous enough
-   to hold strings,  but small enough to protect against overruns,
-   etc.
-   
-   Strangely enough,  this proved to be of immense importance when
-   SPRINTFing to a buffer on a stack...  The rest,  of course,  is
-   well known,  as buffer overruns in the stack are a common way to
-   do horrible things to operating systems, security, etc etc.
-   
-   This version of snprintf is VERY limited by modern standards.
-
-   Revision History:
-   First Released Version - 1994.  This version had NO comments.
-   First Released Version - 1994.  This version had NO comments.
-   Second Major Released Version - Tue May 23 10:43:44 PDT 2000
-    Configuration and other items changed.  Read this doc.
-    Treat this as a new version.
-   
-   COPYRIGHT AND TERMS OF USE:
-   
-   You may use, copy, distribute, or otherwise incorporate this software
-   and documentation into any product or other item,  provided that
-   the copyright in the documentation and source code as well as the
-   source code generated constant strings in the object, executable
-   or other code remain in place and are present in executable modules
-   or objects.
-   
-   You may modify this code as appropriate to your usage; however the
-   modified version must be identified by changing the various source
-   and object code identification strings as is appropriately noted
-   in the source code.
-   
-   The next include line is expected to work in conjunction with the
-   GNU CONFIGURE utility.  You  should define the following macros
-   appropriately:
-   
-   HAVE_STDARG_H - if the <stdargs.h> include file is available
-   HAVE_VARARG_H - if the <varargs.h> include file is available
-   
-   HAVE_STRERROR - if the strerror() routine is available.
-     If it is not available, then examine the lines containing
-     the tests below.  You may need to fiddle with HAVE_SYS_NERR
-   HAVE_SYS_ERRLIST
-   HAVE_DECL_SYS_ERRLIST
-   HAVE_SYS_NERR
-   HAVE_DECL_SYS_NERR
-   
-   HAVE_QUAD_T      - if the quad_t type is defined
-   HAVE_LONG_LONG   - if the long long type is defined
-   HAVE_LONG_DOUBLE - if the long double type is defined
-   
-     If you are using the GNU configure (autoconf) facility, add the
-     following line to the configure.in file, to force checking for the
-     quad_t and long long  data types:
-
-
-       AC_CHECK_FUNCS(strerror);
-       AC_CACHE_CHECK(for errno,
-       ac_cv_errno,
-       [
-       AC_TRY_LINK(,[extern int errno; return (errno);],
-               ac_cv_errno=yes, ac_cv_errno=no)
-       ])
-       if test "$ac_cv_errno" = yes; then
-               AC_DEFINE(HAVE_ERRNO)
-               AC_CACHE_CHECK(for errno declaration,
-               ac_cv_decl_errno,
-               [
-               AC_TRY_COMPILE([
-               #include <stdio.h>
-               #ifdef HAVE_STDLIB_H
-               #include <stdlib.h>
-               #endif
-               #ifdef HAVE_UNISTD_H
-               #include <unistd.h>
-               #endif
-               #ifdef HAVE_ERRNO_H
-               #include <errno.h>
-               ],[return(sys_nerr);],
-                       ac_cv_decl_errno=yes, ac_cv_decl_errno=no)
-               ])
-               if test "$ac_cv_decl_errno" = yes; then
-                       AC_DEFINE(HAVE_DECL_ERRNO)
-               fi;
-       fi
-
-       AC_CACHE_CHECK(for sys_nerr,
-       ac_cv_sys_nerr,
-       [
-       AC_TRY_LINK(,[extern int sys_nerr; return (sys_nerr);],
-               ac_cv_sys_nerr=yes, ac_cv_sys_nerr=no)
-       ])
-       if test "$ac_cv_sys_nerr" = yes; then
-               AC_DEFINE(HAVE_SYS_NERR)
-               AC_CACHE_CHECK(for sys_nerr declaration,
-               ac_cv_decl_sys_nerr,
-               [
-               AC_TRY_COMPILE([
-               #include <stdio.h>
-               #ifdef HAVE_STDLIB_H
-               #include <stdlib.h>
-               #endif
-               #ifdef HAVE_UNISTD_H
-               #include <unistd.h>
-               #endif],[return(sys_nerr);],
-               ac_cv_decl_sys_nerr_def=yes, ac_cv_decl_sys_nerr_def=no)
-               ])
-               if test "$ac_cv_decl_sys_nerr" = yes; then
-                       AC_DEFINE(HAVE_DECL_SYS_NERR)
-               fi
-       fi
-
-
-       AC_CACHE_CHECK(for sys_errlist array,
-       ac_cv_sys_errlist,
-       [AC_TRY_LINK(,[extern char *sys_errlist[];
-               sys_errlist[0];],
-               ac_cv_sys_errlist=yes, ac_cv_sys_errlist=no)
-       ])
-       if test "$ac_cv_sys_errlist" = yes; then
-               AC_DEFINE(HAVE_SYS_ERRLIST)
-               AC_CACHE_CHECK(for sys_errlist declaration,
-               ac_cv_sys_errlist_def,
-               [AC_TRY_COMPILE([
-               #include <stdio.h>
-               #include <errno.h>
-               #ifdef HAVE_STDLIB_H
-               #include <stdlib.h>
-               #endif
-               #ifdef HAVE_UNISTD_H
-               #include <unistd.h>
-               #endif],[char *s = sys_errlist[0]; return(*s);],
-               ac_cv_decl_sys_errlist=yes, ac_cv_decl_sys_errlist=no)
-               ])
-               if test "$ac_cv_decl_sys_errlist" = yes; then
-                       AC_DEFINE(HAVE_DECL_SYS_ERRLIST)
-               fi
-       fi
-
-
-
-       AC_CACHE_CHECK(checking for long long,
-       ac_cv_long_long,
-       [
-       AC_TRY_COMPILE([
-       #include <stdio.h>
-       #include <sys/types.h>
-       ], [printf("%d",sizeof(long long));],
-       ac_cv_long_long=yes, ac_cv_long_long=no)
-       ])
-       if test $ac_cv_long_long = yes; then
-         AC_DEFINE(HAVE_LONG_LONG)
-       fi
-
-       AC_CACHE_CHECK(checking for long double,
-       ac_cv_long_double,
-       [
-       AC_TRY_COMPILE([
-       #include <stdio.h>
-       #include <sys/types.h>
-       ], [printf("%d",sizeof(long double));],
-       ac_cv_long_double=yes, ac_cv_long_double=no)
-       ])
-       if test $ac_cv_long_double = yes; then
-         AC_DEFINE(HAVE_LONG_DOUBLE)
-       fi
-
-       AC_CACHE_CHECK(checking for quad_t,
-       ac_cv_quad_t,
-       [
-       AC_TRY_COMPILE([
-       #include <stdio.h>
-       #include <sys/types.h>
-       ], [printf("%d",sizeof(quad_t));],
-       ac_cv_quad_t=yes, ac_cv_quad_t=no)
-       ])
-       if test $ac_cv_quad_t = yes; then
-         AC_DEFINE(HAVE_QUAD_T)
-       fi
-
-
-
-NAME
-     plp_snprintf, plp_vsnprintf - formatted output conversion
-
-SYNOPSIS
-     #include <stdio.h>
-     #include <stdarg.h>
-
-     int
-     plp_snprintf(const char *format, size_t size, va_list ap);
-     int
-     plp_unsafe_snprintf(const char *format, size_t size, va_list ap);
-
-     AKA snprintf and unsafe_snprintf in the documentation below
-
-     int
-     vsnprintf(char *str, size_t size, const char *format, va_list ap);
-     int
-     unsafe_vsnprintf(char *str, size_t size, const char *format, va_list ap);
-
-     AKA vsnprintf and unsafe_vsnprintf in the documentation below
-
-     (Multithreaded Safe)
-
-DESCRIPTION
-     The printf() family of functions produces output according to
-     a format as described below.  Snprintf(), and vsnprintf()
-     write to the character string str. These functions write the
-     output under the control of a format string that specifies
-     how subsequent arguments (or arguments accessed via the
-     variable-length argument facilities of stdarg(3))  are converted
-     for output.  These functions return the number of characters
-     printed (not including the trailing `\0' used to end output
-     to strings).  Snprintf() and vsnprintf() will write at most
-     size-1 of the characters printed into the output string (the
-     size'th character then gets the terminating `\0'); if the
-     return value is greater than or equal to the size argument,
-     the string was too short and some of the printed characters
-     were discarded.  The size or str may be given as zero to find
-     out how many characters are needed; in this case, the str
-     argument is ignored.
-
-     By default, the snprintf function will not format control
-     characters (except new line and tab) in strings.  This is a
-     safety feature that has proven to be extremely critical when
-     using snprintf for secure applications and when debugging.
-     If you MUST have control characters formatted or printed,
-     then use the unsafe_snprintf() and unsafe_vsnprintf() and on
-     your own head be the consequences.  You have been warned.
-
-     There is one exception to the comments above, and that is
-     the "%c" (character) format.  It brutally assumes that the
-     user will have performed the necessary 'isprint()' or other
-     checks and uses the integer value as a character.
-
-     The format string is composed of zero or more directives:
-     ordinary characters (not %), which are copied unchanged to
-     the output stream; and conversion specifications, each
-     of which results in fetching zero or more subsequent arguments.
-     Each conversion specification is introduced by the character
-     %. The arguments must correspond properly (after type promotion)
-     with the conversion specifier.  After the %, the following
-     appear in sequence:
-
-     o   Zero or more of the following flags:
-
-          -   A zero `0' character specifying zero padding.  For
-            all conversions except n, the converted value is padded
-            on the left with zeros rather than blanks.  If a
-            precision is given with a numeric conversion (d, i,
-            o, u, i, x, and X), the `0' flag is ignored.
-
-       -   A negative field width flag `-' indicates the converted
-            value is to be left adjusted on the field boundary.  Except
-            for n conversions, the converted value is padded on
-            the right with blanks, rather than on the left with
-            blanks or zeros.  A `-' overrides a `0' if both are
-            given.
-
-          -   A space, specifying that a blank should be left before
-            a positive number produced by a signed conversion (d, e, E, f,
-            g, G, or i).
-
-          -   A `+' character specifying that a sign always be placed
-            before a number produced by a signed conversion.  A `+' overrides
-            a space if both are used.
-
-     o   An optional decimal digit string specifying a minimum
-                field width.  If the converted value has fewer
-                characters than the field width, it will be padded
-                with spaces on the left (or right, if the
-                left-adjustment flag has been given) to fill out
-                the field width.
-
-     o   An optional precision, in the form of a period `.' followed
-                by an optional digit string.  If the digit string
-                is omitted, the precision is taken as zero.  This
-                gives the minimum number of digits to appear for
-                d, i, o, u, x, and X conversions, the number of
-                digits to appear after the decimal-point for e,
-                E, and f conversions, the maximum number of
-                significant digits for g and G conversions, or
-                the maximum number of characters to be printed
-                from a string for s conversions.
-
-     o   The optional character h, specifying that a following d,
-                i, o, u, x, or X conversion corresponds to a short
-                int or unsigned short int argument, or that a
-                following n conversion corresponds to a pointer
-                to a short int argument.
-
-     o   The optional character l (ell) specifying that a following
-                d, i, o, u, x, or X conversion applies to a pointer
-                to a long int or unsigned long int argument, or
-                that a following n conversion corresponds to a
-                pointer to a long int argument.
-
-     o   The optional character q, specifying that a following d,
-                i, o, u, x, or X conversion corresponds to a quad_t
-                or u_quad_t argument, or that a following n
-                conversion corresponds to a quad_t argument.
-         This value is always printed in HEX notation.  Tough.
-         quad_t's are an OS system implementation, and should
-         not be allowed.
-
-     o   The character L specifying that a following e, E, f, g,
-                or G conversion corresponds to a long double
-                argument.
-
-     o   A character that specifies the type of conversion to be applied.
-
-
-     A field width or precision, or both, may be indicated by an asterisk `*'
-     instead of a digit string.  In this case, an int argument supplies the
-     field width or precision.  A negative field width is treated as a left
-     adjustment flag followed by a positive field width; a negative precision
-     is treated as though it were missing.
-
-     The conversion specifiers and their meanings are:
-
-     diouxX  The int (or appropriate variant) argument is converted to signed
-                        decimal (d and i), unsigned octal (o), unsigned decimal
-                        (u), or unsigned hexadecimal (x and X) notation.  The
-                        letters abcdef are used for x conversions; the letters
-                        ABCDEF are used for X conversions.  The precision, if
-                        any, gives the minimum number of digits that must
-                        appear; if the converted value requires fewer digits,
-                        it is padded on the left with zeros.
-
-     eE      The double argument is rounded and converted in the style
-             [-]d.ddde+-dd where there is one digit before the decimal-point
-                        character and the number of digits after it is equal
-                        to the precision; if the precision is missing, it is
-                        taken as 6; if the precision is zero, no decimal-point
-                        character appears.  An E conversion uses the letter
-                        E (rather than e) to introduce the exponent.
-                        The exponent always contains at least two digits; if
-                        the value is zero, the exponent is 00.
-
-     f       The double argument is rounded and converted to decimal notation
-             in the style [-]ddd.ddd, where the number of digits after the
-             decimal-point character is equal to the precision specification.
-             If the precision is missing, it is taken as 6; if the precision
-             is explicitly zero, no decimal-point character appears.  If a
-             decimal point appears, at least one digit appears before it.
-
-     g       The double argument is converted in style f or e (or
-                        E for G conversions).  The precision specifies the
-                        number of significant digits.  If the precision is
-                        missing, 6 digits are given; if the precision is zero,
-                        it is treated as 1.  Style e is used if the exponent
-                        from its conversion is less than -4 or greater than
-                        or equal to the precision.  Trailing zeros are removed
-                        from the fractional part of the result; a decimal
-                        point appears only if it is followed by at least one
-                        digit.
-
-     c       The int argument is converted to an unsigned char,
-             and the resulting character is written.
-
-     s       The ``char *'' argument is expected to be a pointer to an array
-                        of character type (pointer to a string).  Characters
-                        from the array are written up to (but not including)
-                        a terminating NUL character; if a precision is
-                        specified, no more than the number specified are
-                        written.  If a precision is given, no null character
-                        need be present; if the precision is not specified,
-                        or is greater than the size of the array, the array
-                        must contain a terminating NUL character.
-
-     %       A `%' is written. No argument is converted. The complete
-             conversion specification is `%%'.
-
-     In no case does a non-existent or small field width cause truncation of a
-     field; if the result of a conversion is wider than the field width, the
-     field is expanded to contain the conversion result.
-
-EXAMPLES
-     To print a date and time in the form `Sunday, July 3, 10:02', where
-     weekday and month are pointers to strings:
-
-           #include <stdio.h>
-           fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
-                   weekday, month, day, hour, min);
-
-     To print pi to five decimal places:
-
-           #include <math.h>
-           #include <stdio.h>
-           fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
-
-     To allocate a 128 byte string and print into it:
-
-           #include <stdio.h>
-           #include <stdlib.h>
-           #include <stdarg.h>
-           char *newfmt(const char *fmt, ...)
-           {
-                           char *p;
-                           va_list ap;
-                           if ((p = malloc(128)) == NULL)
-                                   return (NULL);
-                           va_start(ap, fmt);
-                           (void) vsnprintf(p, 128, fmt, ap);
-                           va_end(ap);
-                           return (p);
-           }
-
-SEE ALSO
-     printf(1),  scanf(3)
-
-STANDARDS
-     Turkey C Standardization and wimpy POSIX folks did not define
-     snprintf or vsnprintf().
-
-BUGS
-     The conversion formats %D, %O, and %U are not standard and are provided
-     only for backward compatibility.  The effect of padding the %p format
-     with zeros (either by the `0' flag or by specifying a precision), and the
-     benign effect (i.e., none) of the `#' flag on %n and %p conversions, as
-     well as other nonsensical combinations such as %Ld, are not standard;
-     such combinations should be avoided.
-
-     The typedef names quad_t and u_quad_t are infelicitous.
-
-*/
-
-
-#include "config.h"
-
-#if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
-
-#include <sys/types.h>
-#include <ctype.h>
-#include <stdlib.h>
-#if defined(HAVE_STRING_H)
-# include <string.h>
-#endif
-#if defined(HAVE_STRINGS_H)
-# include <strings.h>
-#endif
-#include <stdio.h>
-
-/*
- * For testing, define these values
- */
-#if 0
-#define HAVE_STDARG_H 1
-#define TEST 1
-#define HAVE_QUAD_T 1
-#endif
-
-/**** ENDINCLUDE ****/
-
-/*************************************************
- * KEEP THIS STRING - MODIFY AT THE END WITH YOUR REVISIONS
- * i.e. - the LOCAL REVISIONS part is for your use
- *************************************************/
- static char *const _id = "plp_snprintf V98.12.21 Copyright Patrick Powell 1988-2000 "
- "$Id: snprintf.c,v 1.2 2008-11-14 10:29:08 didg Exp $"
- " LOCAL REVISIONS: Modified for Netatalk 2002/02/12 Burkhard Schmidt";
-
-/* varargs declarations: */
-
-# undef HAVE_STDARGS    /* let's hope that works everywhere (mj) */
-# undef VA_LOCAL_DECL
-# undef VA_START
-# undef VA_SHIFT
-# undef VA_END
-
-#if defined(HAVE_STDARG_H)
-# include <stdarg.h>
-# define HAVE_STDARGS    /* let's hope that works everywhere (mj) */
-# define VA_LOCAL_DECL   va_list ap;
-# define VA_START(f)     va_start(ap, f)
-# define VA_SHIFT(v,t) ;       /* no-op for ANSI */
-# define VA_END          va_end(ap)
-#else
-# if defined(HAVE_VARARGS_H)
-#  include <varargs.h>
-#  undef HAVE_STDARGS
-#  define VA_LOCAL_DECL   va_list ap;
-#  define VA_START(f)     va_start(ap)         /* f is ignored! */
-#  define VA_SHIFT(v,t)        v = va_arg(ap,t)
-#  define VA_END               va_end(ap)
-# else
-XX ** NO VARARGS ** XX
-# endif
-#endif
-
-union value {
-#if defined(HAVE_QUAD_T)
-       quad_t qvalue;
-#endif
-#if defined(HAVE_LONG_LONG)
-       long long value;
-#else
-       long value;
-#endif
-       double dvalue;
-};
-
-#undef CVAL 
-#define CVAL(s) (*((unsigned char *)s))
-
-extern int errno;
- static char * plp_Errormsg ( int err, char *buffer );
- static void dopr( int visible_control, char **buffer, int *left,
-       const char *format, va_list args );
- static void fmtstr( int visible_control, char **buffer, int *left,
-       char *value, int ljust, int len, int zpad, int precision );
- static void fmtnum(  char **buffer, int *left,
-       union value *value, int base, int dosign,
-       int ljust, int len, int zpad, int precision );
-#if defined(HAVE_QUAD_T)
- static void fmtquad(  char **buffer, int *left,
-       union value *value, int base, int dosign,
-       int ljust, int len, int zpad, int precision );
-#endif
- static void fmtdouble( char **bufer, int *left,
-       int fmt, double value,
-       int ljust, int len, int zpad, int precision );
- static void dostr(  char **buffer, int *left, char *str );
- static void dopr_outch(  char **buffer, int *left, int c );
-
-int plp_vsnprintf(char *str, size_t count, const char *fmt, va_list args)
-{
-       int left;
-       char *buffer;
-       if( count < 0 ) count = 0;
-       left = count;
-       if( count == 0 ) str = 0;
-       buffer = str;
-       dopr( 1, &buffer, &left, fmt, args );
-       /* fprintf(stderr,"str 0x%x, buffer 0x%x, count %d, left %d\n",
-               (int)str, (int)buffer, count, left ); */
-       if( str && count > 0 ){
-               if( left > 0 ){
-                       str[count-left] = 0;
-               } else {
-                       str[count-1] = 0;
-               }
-       }
-       return(count - left);
-}
-
-int plp_unsafe_vsnprintf(char *str, size_t count, const char *fmt, va_list args)
-{
-       int left;
-       char *buffer;
-       if( count < 0 ) count = 0;
-       left = count;
-       if( count == 0 ) str = 0;
-       buffer = str;
-       dopr( 0, &buffer, &left, fmt, args );
-       /* fprintf(stderr,"str 0x%x, buffer 0x%x, count %d, left %d\n",
-               (int)str, (int)buffer, count, left ); */
-       if( str && count > 0 ){
-               if( left > 0 ){
-                       str[count-left] = 0;
-               } else {
-                       str[count-1] = 0;
-               }
-       }
-       return(count - left);
-}
-
-/* VARARGS3 */
-#ifdef HAVE_STDARGS
-int plp_snprintf (char *str,size_t count,const char *fmt,...)
-#else
-int plp_snprintf (va_alist) va_dcl
-#endif
-{
-#ifndef HAVE_STDARGS
-    char *str;
-       size_t count;
-    char *fmt;
-#endif
-       int n = 0;
-    VA_LOCAL_DECL
-
-    VA_START (fmt);
-    VA_SHIFT (str, char *);
-    VA_SHIFT (count, size_t );
-    VA_SHIFT (fmt, char *);
-    n = plp_vsnprintf ( str, count, fmt, ap);
-    VA_END;
-       return( n );
-}
-
-
-/* VARARGS3 */
-#ifdef HAVE_STDARGS
-int plp_unsafe_snprintf (char *str,size_t count,const char *fmt,...)
-#else
-int plp_unsafe_snprintf (va_alist) va_dcl
-#endif
-{
-#ifndef HAVE_STDARGS
-    char *str;
-       size_t count;
-    char *fmt;
-#endif
-       int n = 0;
-    VA_LOCAL_DECL
-
-    VA_START (fmt);
-    VA_SHIFT (str, char *);
-    VA_SHIFT (count, size_t );
-    VA_SHIFT (fmt, char *);
-    n = plp_unsafe_vsnprintf ( str, count, fmt, ap);
-    VA_END;
-       return( n );
-}
- static void dopr( int visible_control, char **buffer, int *left, const char *format, va_list args )
-{
-       int ch;
-       union value value;
-       int longflag = 0;
-       int quadflag = 0;
-       char *strvalue;
-       int ljust;
-       int len;
-       int zpad;
-       int precision;
-       int set_precision;
-       double dval;
-       int err = errno;
-       int base = 0;
-       int signed_val = 0;
-
-       while( (ch = *format++) ){
-               switch( ch ){
-               case '%':
-                       longflag = quadflag =
-                       ljust = len = zpad = base = signed_val = 0;
-                       precision = -1; set_precision = 0;
-               nextch: 
-                       ch = *format++;
-                       switch( ch ){
-                       case 0:
-                               dostr( buffer, left, "**end of format**" );
-                               return;
-                       case '-': ljust = 1; goto nextch;
-                       case '.': set_precision = 1; precision = 0; goto nextch;
-                       case '*': len = va_arg( args, int ); goto nextch;
-                       case '0': /* set zero padding if len not set */
-                               if(len==0 && set_precision == 0 ) zpad = '0';
-                       case '1': case '2': case '3':
-                       case '4': case '5': case '6':
-                       case '7': case '8': case '9':
-                               if( set_precision ){
-                                       precision = precision*10 + ch - '0';
-                               } else {
-                                       len = len*10 + ch - '0';
-                               }
-                               goto nextch;
-                       case 'l': ++longflag; goto nextch;
-                       case 'q':
-#if !defined( HAVE_QUAD_T )
-                                       dostr( buffer, left, "*no quad_t support *");
-                                       return;
-#endif
-                                       quadflag = 1;
-                                       goto nextch;
-                       case 'u': case 'U':
-                               if( base == 0 ){ base = 10; signed_val = 0; }
-                       case 'o': case 'O':
-                               if( base == 0 ){ base = 8; signed_val = 0; }
-                       case 'd': case 'D':
-                               if( base == 0 ){ base = 10; signed_val = 1; }
-                       case 'x':
-                               if( base == 0 ){ base = 16; signed_val = 0; }
-                       case 'X':
-                               if( base == 0 ){ base = -16; signed_val = 0; }
-#if defined( HAVE_QUAD_T )
-                               if( quadflag ){
-                                       value.qvalue = va_arg( args, quad_t );
-                                       fmtquad( buffer, left,  &value,base,signed_val, ljust, len, zpad, precision );
-                                       break;
-                               } else
-#endif
-                               if( longflag > 1 ){
-#if defined(HAVE_LONG_LONG)
-                                       if( signed_val ){
-                                       value.value = va_arg( args, long long );
-                                       } else {
-                                       value.value = va_arg( args, unsigned long long );
-                                       }
-#else
-                                       if( signed_val ){
-                                       value.value = va_arg( args, long );
-                                       } else {
-                                       value.value = va_arg( args, unsigned long );
-                                       }
-#endif
-                               } else if( longflag ){
-                                       if( signed_val ){
-                                               value.value = va_arg( args, long );
-                                       } else {
-                                               value.value = va_arg( args, unsigned long );
-                                       }
-                               } else {
-                                       if( signed_val ){
-                                               value.value = va_arg( args, int );
-                                       } else {
-                                               value.value = va_arg( args, unsigned int );
-                                       }
-                               }
-                               fmtnum( buffer, left,  &value,base,signed_val, ljust, len, zpad, precision ); break;
-                       case 's':
-                               strvalue = va_arg( args, char *);
-                               fmtstr( visible_control, buffer, left, strvalue,ljust,len, zpad, precision );
-                               break;
-                       case 'c':
-                               ch = va_arg( args, int );
-                               { char b[2];
-                                       b[0] = ch;
-                                       b[1] = 0;
-                                       fmtstr( 0, buffer, left, b,ljust,len, zpad, precision );
-                               }
-                               break;
-                       case 'f': case 'g': case 'e':
-                               dval = va_arg( args, double );
-                               fmtdouble( buffer, left, ch, dval,ljust,len, zpad, precision ); break;
-                       case 'm':
-                               { char shortbuffer[32];
-                               fmtstr( visible_control, buffer, left,
-                                       plp_Errormsg(err, shortbuffer),ljust,len, zpad, precision );
-                               }
-                               break;
-                       case '%': dopr_outch( buffer, left, ch ); continue;
-                       default:
-                               dostr(  buffer, left, "???????" );
-                       }
-                       longflag = 0;
-                       break;
-               default:
-                       dopr_outch( buffer, left, ch );
-                       break;
-               }
-       }
-}
-
-/*
- * Format '%[-]len[.precision]s'
- * -   = left justify (ljust)
- * len = minimum length
- * precision = numbers of chars in string to use
- */
- static void
-fmtstr( int visible_control, char **buffer, int *left,
-        char *value, int ljust, int len, int zpad, int precision )
-{
-       int padlen, strlenv, i, c;      /* amount to pad */
-
-       if( value == 0 ){
-               value = "<NULL>";
-       }
-       /* cheap strlen so you do not have library call */
-       for( strlenv = i = 0; (c=CVAL(value+i)); ++i ){
-               if( visible_control && iscntrl( c ) && c != '\t' && c != '\n' ){
-                       ++strlenv;
-               }
-               ++strlenv;
-       }
-       if( precision > 0 && strlenv > precision ){
-               strlenv = precision;
-       }
-       padlen = len - strlenv;
-       if( padlen < 0 ) padlen = 0;
-       if( ljust ) padlen = -padlen;
-       while( padlen > 0 ) {
-               dopr_outch( buffer, left, ' ' );
-               --padlen;
-       }
-       /* output characters */
-       for( i = 0; i < strlenv && (c = CVAL(value+i)); ++i ){
-               if( visible_control && iscntrl( c ) && c != '\t' && c != '\n' ){
-                       dopr_outch(buffer, left, '^');
-                       c = ('@' | (c & 0x1F));
-               }
-               dopr_outch(buffer, left, c);
-       }
-       while( padlen < 0 ) {
-               dopr_outch( buffer, left, ' ' );
-               ++padlen;
-       }
-}
-
- static void
-fmtnum( char **buffer, int *left,
-       union value *value, int base, int dosign, int ljust,
-       int len, int zpad, int precision )
-{
-       int signvalue = 0;
-#if defined(HAVE_LONG_LONG)
-       unsigned long long uvalue;
-#else
-       unsigned long uvalue;
-#endif
-       char convert[sizeof( union value) * 8 + 16];
-       int place = 0;
-       int padlen = 0; /* amount to pad */
-       int caps = 0;
-
-       /* fprintf(stderr,"value 0x%x, base %d, dosign %d, ljust %d, len %d, zpad %d\n",
-               value, base, dosign, ljust, len, zpad );/ **/
-       uvalue = value->value;
-       if( dosign ){
-               if( value->value < 0 ) {
-                       signvalue = '-';
-                       uvalue = -value->value; 
-               }
-       }
-       if( base < 0 ){
-               caps = 1;
-               base = -base;
-       }
-       do{
-               convert[place++] =
-                       (caps? "0123456789ABCDEF":"0123456789abcdef")
-                        [uvalue % (unsigned)base  ];
-               uvalue = (uvalue / (unsigned)base );
-       }while(uvalue);
-       convert[place] = 0;
-       padlen = len - place;
-       if( padlen < 0 ) padlen = 0;
-       if( ljust ) padlen = -padlen;
-       /* fprintf( stderr, "str '%s', place %d, sign %c, padlen %d\n",
-               convert,place,signvalue,padlen); / **/
-       if( zpad && padlen > 0 ){
-               if( signvalue ){
-                       dopr_outch( buffer, left, signvalue );
-                       --padlen;
-                       signvalue = 0;
-               }
-               while( padlen > 0 ){
-                       dopr_outch( buffer, left, zpad );
-                       --padlen;
-               }
-       }
-       while( padlen > 0 ) {
-               dopr_outch( buffer, left, ' ' );
-               --padlen;
-       }
-       if( signvalue ) dopr_outch( buffer, left, signvalue );
-       while( place > 0 ) dopr_outch( buffer, left, convert[--place] );
-       while( padlen < 0 ){
-               dopr_outch( buffer, left, ' ' );
-               ++padlen;
-       }
-}
-
-#if defined(HAVE_QUAD_T)
-
- static void
-fmtquad( char **buffer, int *left,
-       union value *value, int base, int dosign, int ljust,
-       int len, int zpad, int precision )
-{
-       int signvalue = 0;
-       int place = 0;
-       int padlen = 0; /* amount to pad */
-       int caps = 0;
-       int i, c;
-       union {
-               quad_t qvalue;
-               unsigned char qconvert[sizeof(quad_t)];
-       } vvalue;
-       char convert[2*sizeof(quad_t)+1];
-
-       /* fprintf(stderr,"value 0x%x, base %d, dosign %d, ljust %d, len %d, zpad %d\n",
-               value, base, dosign, ljust, len, zpad );/ **/
-       vvalue.qvalue = value->qvalue;
-
-       if( base < 0 ){
-               caps = 1;
-       }
-
-       for( i = 0; i < sizeof(quad_t); ++i ){
-               c = vvalue.qconvert[i];
-               convert[2*i] = 
-                       (caps? "0123456789ABCDEF":"0123456789abcdef")[ (c >> 4) & 0xF];
-               convert[2*i+1] = 
-                       (caps? "0123456789ABCDEF":"0123456789abcdef")[ c  & 0xF];
-       }
-       convert[2*i] = 0;
-
-       place = strlen(convert);
-       padlen = len - place;
-       if( padlen < 0 ) padlen = 0;
-       if( ljust ) padlen = -padlen;
-       /* fprintf( stderr, "str '%s', place %d, sign %c, padlen %d\n",
-               convert,place,signvalue,padlen); / **/
-       if( zpad && padlen > 0 ){
-               if( signvalue ){
-                       dopr_outch( buffer, left, signvalue );
-                       --padlen;
-                       signvalue = 0;
-               }
-               while( padlen > 0 ){
-                       dopr_outch( buffer, left, zpad );
-                       --padlen;
-               }
-       }
-       while( padlen > 0 ) {
-               dopr_outch( buffer, left, ' ' );
-               --padlen;
-       }
-       if( signvalue ) dopr_outch( buffer, left, signvalue );
-       while( place > 0 ) dopr_outch( buffer, left, convert[--place] );
-       while( padlen < 0 ){
-               dopr_outch( buffer, left, ' ' );
-               ++padlen;
-       }
-}
-
-#endif
-
- static void mystrcat(char *dest, char *src )
-{
-       if( dest && src ){
-               dest += strlen(dest);
-               strcpy(dest,src);
-       }
-}
-
- static void
-fmtdouble( char **buffer, int *left,
-       int fmt, double value, int ljust, int len, int zpad, int precision )
-{
-       char convert[sizeof( union value) * 8 + 16];
-       char formatstr[128];
-
-       /* fprintf(stderr,"len %d, precision %d\n", len, precision ); */
-       if( len > (sizeof(convert) - 20) ){
-               len = sizeof(convert) - 20;
-       }
-       if( precision >= 0 && precision > sizeof(convert) - 20 ){
-               precision = sizeof(convert) - 20;
-       }
-       if( precision >= 0 && precision > len ) precision = len;
-       strcpy( formatstr, "%" );
-       if( ljust ) mystrcat(formatstr, "-" );
-       if( zpad ) mystrcat(formatstr, "0" );
-       if( len ){
-               sprintf( formatstr+strlen(formatstr), "%d", len );
-       }
-       if( precision >= 0 ){
-               sprintf( formatstr+strlen(formatstr), ".%d", precision );
-       }
-       sprintf( formatstr+strlen(formatstr), "%c", fmt );
-       /* this is easier than trying to do the portable dtostr */
-       /* fprintf(stderr,"format string '%s'\n", formatstr); */
-       sprintf( convert, formatstr, value );
-       dostr( buffer, left, convert );
-}
-
- static void dostr( char **buffer, int *left, char *str  )
-{
-       if(str)while(*str) dopr_outch( buffer, left, *str++ );
-}
-
- static void dopr_outch( char **buffer, int *left, int c )
-{
-       if( *left > 0 ){
-               *(*buffer)++ = c;
-       }
-       *left -= 1;
-}
-
-
-/****************************************************************************
- * static char *plp_errormsg( int err )
- *  returns a printable form of the
- *  errormessage corresponding to the valie of err.
- *  This is the poor man's version of sperror(), not available on all systems
- *  Patrick Powell Tue Apr 11 08:05:05 PDT 1995
- ****************************************************************************/
-/****************************************************************************/
-
-#if !defined(HAVE_STRERROR)
-# undef  num_errors
-# if defined(HAVE_SYS_ERRLIST)
-#  if !defined(HAVE_DECL_SYS_ERRLIST)
-     extern const char *const sys_errlist[];
-#  endif
-#  if defined(HAVE_SYS_NERR)
-#   if !defined(HAVE_DECL_SYS_NERR)
-      extern int sys_nerr;
-#   endif
-#   define num_errors    (sys_nerr)
-#  endif
-# endif
-# if !defined(num_errors)
-#   define num_errors   (-1)            /* always use "errno=%d" */
-# endif
-#endif
-
- static char * plp_Errormsg ( int err, char *buffer /* int maxlen = 32 */)
-{
-    char *cp;
-
-#if defined(HAVE_STRERROR)
-       cp = (void *)strerror(err);
-#else
-# if defined(HAVE_SYS_ERRLIST)
-    if (err >= 0 && err < num_errors) {
-               cp = (void *)sys_errlist[err];
-    } else
-# endif
-       {
-               (void) sprintf (buffer, "errno=%d", err);
-               cp = buffer;
-    }
-#endif
-    return (cp);
-}
-
-#if defined(TEST)
-#include <stdio.h>
-int main( void )
-{
-       char buffer[128];
-       char *t;
-       char *test1 = "01234";
-       int n;
-       errno = 1;
-       buffer[0] = 0;
-       n = plp_snprintf( buffer, 0, (t="test")); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t="errno '%s'")); printf( "[%d] %s = '%s'\n", n, t, buffer, strerror(errno) );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%s"), test1 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%12s"), test1 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%-12s"), test1 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%12.2s"), test1 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%-12.2s"), test1 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%g"), 1.25 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%g"), 1.2345 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%12g"), 1.25 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%12.1g"), 1.25 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%12.2g"), 1.25 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%12.3g"), 1.25 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%0*d"), 6, 1 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-#if defined(HAVE_LONG_LONG)
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%llx"), 1, 2, 3, 4 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%llx"), (long long)1, (long long)2 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%qx"), 1, 2, 3, 4 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%qx"), (quad_t)1, (quad_t)2 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-#endif
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "0%x, 0%x"), (char *)(0x01234567), (char *)0, 0, 0, 0); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "0%x, 0%x"), (char *)(0x01234567), (char *)0x89ABCDEF, 0, 0, 0); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "0%x, 0%x"), t, 0, 0, 0, 0); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%f"), 1.25 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%f"), 1.2345 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%12f"), 1.25 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%12.2f"), 1.25 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%f"), 1.0 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%.0f"), 1.0 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%0.0f"), 1.0 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%1.0f"), 1.0 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%1.5f"), 1.0 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       n = plp_snprintf( buffer, sizeof(buffer), (t = "%5.5f"), 1.0 ); printf( "[%d] %s = '%s'\n", n, t, buffer );
-       return(0);
-}
-#endif
-
-#endif /* !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF) */
-
-#ifndef HAVE_VSNPRINTF
-int vsnprintf(char *str, size_t count, const char *fmt, va_list args)
-{
-    int n;
-    
-    n = plp_vsnprintf(str, count, fmt, args);
-    
-    return(n);
-}
-#endif /* ! HAVE_VSNPRINTF */
-
-#ifndef HAVE_SNPRINTF
-#ifdef HAVE_STDARGS
-int snprintf (char *str,size_t count,const char *fmt,...)
-#else
-int snprintf (va_alist) va_dcl
-#endif
-{
-#ifndef HAVE_STDARGS
-    char *str;
-       size_t count;
-    char *fmt;
-#endif
-       int n = 0;
-    VA_LOCAL_DECL
-
-    VA_START (fmt);
-    VA_SHIFT (str, char *);
-    VA_SHIFT (count, size_t );
-    VA_SHIFT (fmt, char *);
-    n = plp_vsnprintf ( str, count, fmt, ap);
-    VA_END;
-       return( n );
-}
-#endif /* ! HAVE_VNSPRINTF */
diff --git a/libatalk/compat/strcasecmp.c b/libatalk/compat/strcasecmp.c
deleted file mode 100644 (file)
index bc8cb57..0000000
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * $Id: strcasecmp.c,v 1.4 2003-02-17 01:51:08 srittau Exp $
- *
- * Copyright (c) 1987 Regents of the University of California.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms are permitted
- * provided that: (1) source distributions retain this entire copyright
- * notice and comment, and (2) distributions including binaries display
- * the following acknowledgement:  ``This product includes software
- * developed by the University of California, Berkeley and its contributors''
- * in the documentation or other materials provided with the distribution
- * and in all advertising materials mentioning features or use of this
- * software. 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-# if defined( ibm032 )
-
-#include <sys/types.h>
-#include <string.h>
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static const char sccsid[] = "@(#)strcasecmp.c 5.9 (Berkeley) 6/1/90";
-#endif /* LIBC_SCCS and not lint */
-
-/*
- * 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 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(s1, s2)
-       char *s1, *s2;
-{
-       register u_char *cm = charmap,
-                       *us1 = (u_char *)s1,
-                       *us2 = (u_char *)s2;
-
-       while (cm[*us1] == cm[*us2++])
-               if (*us1++ == '\0')
-                       return (0);
-       return (cm[*us1] - cm[*--us2]);
-}
-
-int
-strncasecmp(s1, s2, n)
-       char *s1, *s2;
-       register size_t n;
-{
-       if (n != 0) {
-               register u_char *cm = charmap,
-                               *us1 = (u_char *)s1,
-                               *us2 = (u_char *)s2;
-
-               do {
-                       if (cm[*us1] != cm[*us2++])
-                               return (cm[*us1] - cm[*--us2]);
-                       if (*us1++ == '\0')
-                               break;
-               } while (--n != 0);
-       }
-       return (0);
-}
-
-# endif /* ibm032 */
diff --git a/libatalk/compat/strdup.c b/libatalk/compat/strdup.c
deleted file mode 100644 (file)
index 9537a85..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * $Id: strdup.c,v 1.4 2003-02-17 01:51:08 srittau Exp $
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#ifdef ultrix
-char *strdup(const char *string)
-{
-  char *new;
-  
-  if (new = (char *) malloc(strlen(string) + 1))
-    strcpy(new, string);
-
-  return new;
-}
-#endif /* ultrix */
diff --git a/libatalk/compat/strlcpy.c b/libatalk/compat/strlcpy.c
new file mode 100644 (file)
index 0000000..314b039
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+   Copy from samba lib/replace.c
+
+   Unix SMB/CIFS implementation.
+   replacement routines for broken systems
+   Copyright (C) Andrew Tridgell 1992-1998
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+   strlcpy strlcat functions.
+*/
+                          
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <atalk/util.h>
+#include <string.h>
+
+#ifndef HAVE_STRLCPY
+/* like strncpy but does not 0 fill the buffer and always null
+   terminates. bufsize is the size of the destination buffer */
+ size_t strlcpy(char *d, const char *s, size_t bufsize)
+{
+        size_t len = strlen(s);
+        size_t ret = len;
+
+        if (bufsize <= 0) 
+               return 0;
+
+        if (len >= bufsize) 
+               len = bufsize-1;
+
+        memcpy(d, s, len);
+        d[len] = 0;
+        return ret;
+}
+#endif
+#ifndef HAVE_STRLCAT
+/* like strncat but does not 0 fill the buffer and always null
+   terminates. bufsize is the length of the buffer, which should
+   be one more than the maximum resulting string length */
+ size_t strlcat(char *d, const char *s, size_t bufsize)
+{
+        size_t len1 = strlen(d);
+        size_t len2 = strlen(s);
+        size_t ret = len1 + len2;
+
+       if (len1 >= bufsize) {
+               return 0;
+       } 
+        if (len1+len2 >= bufsize) {
+                len2 = bufsize - (len1+1);
+        }
+        if (len2 > 0) {
+                memcpy(d+len1, s, len2);
+                d[len1+len2] = 0;
+        }
+        return ret;
+}
+#endif
diff --git a/libatalk/compat/strstr.c b/libatalk/compat/strstr.c
deleted file mode 100644 (file)
index ae555b4..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * $Id: strstr.c,v 1.4 2003-02-17 01:51:08 srittau Exp $
- *
- * 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.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)strstr.c   5.2 (Berkeley) 1/26/91";
-#endif /* LIBC_SCCS and not lint */
-
-# if defined(ibm032) || (defined(sun) && defined(i386))
-#ifdef sun
-#define const
-#endif /* sun */
-
-#include <sys/types.h>
-#include <string.h>
-
-/*
- * Find the first occurrence of find in s.
- */
-char *
-strstr(s, find)
-       register const char *s, *find;
-{
-       register char c, sc;
-       register size_t len;
-
-       if ((c = *find++) != 0) {
-               len = strlen(find);
-               do {
-                       do {
-                               if ((sc = *s++) == 0)
-                                       return (0);
-                       } while (sc != c);
-               } while (strncmp(s, find, len) != 0);
-               s--;
-       }
-       return ((char *)s);
-}
-# endif /* ibm03 sun i386 */
index d64cbed69f8babe20481577e9e13905219195877..34fa76e544e2bd7e462dfeb72ca579fe419db37c 100644 (file)
@@ -7,5 +7,3 @@ LIBS = @LIBS@
 noinst_LTLIBRARIES = libdsi.la
 
 libdsi_la_SOURCES = dsi_attn.c dsi_close.c dsi_cmdreply.c dsi_getsess.c dsi_getstat.c dsi_init.c dsi_opensess.c dsi_read.c dsi_tcp.c dsi_tickle.c dsi_write.c dsi_stream.c
-
-noinst_HEADERS = dsi_private.h
index 9aef79b53534aeabd9598c622c001b7b8f4904bc..5a60c24d5c25d30d223b820b3edf496c89009740 100644 (file)
 #include <string.h>
 #include <signal.h>
 #include <sys/types.h>
+#include <arpa/inet.h>
 
 #include <atalk/dsi.h>
 #include <atalk/afp.h>
-#include <netatalk/endian.h>
 
 #ifndef MIN
 #define MIN(a,b) ((a) < (b) ? (a) : (b))
@@ -31,8 +31,8 @@ int dsi_attention(DSI *dsi, AFPUserBytes flags)
 {
   /* header + AFPUserBytes */
   char block[DSI_BLOCKSIZ + sizeof(AFPUserBytes)];
-  u_int32_t len, nlen;
-  u_int16_t id;
+  uint32_t len, nlen;
+  uint16_t id;
 
   if (dsi->flags & DSI_SLEEPING)
       return 1;
index 6362182ba49fe6d259dd67277eb8cc0f7df6b7e3..80bee3fe702a79cfbd18bd7a7ac4bd8539295aaf 100644 (file)
@@ -11,8 +11,9 @@
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <arpa/inet.h>
+
 #include <atalk/dsi.h>
-#include <netatalk/endian.h>
 
 void dsi_close(DSI *dsi)
 {
index 0d7e5f025a7936847046d6dc06a7938ebe6dc847..5b0d627de2c788e7356ffeb50219163d6007cb3c 100644 (file)
@@ -8,9 +8,10 @@
 #endif /* HAVE_CONFIG_H */
 
 #include <stdio.h>
+#include <arpa/inet.h>
+
 #include <atalk/dsi.h>
 #include <atalk/logger.h>
-#include <netatalk/endian.h>
 
 /* this assumes that the reply follows right after the command, saving
  * on a couple assignments. specifically, command, requestID, and
index bcc32da23c04e3d7e677c6e459099beba2637f06..001279cd74ae6ad717eef7fe01a7880a77b3dfab 100644 (file)
 #include <sys/types.h>
 #include <sys/socket.h>
 
-/* POSIX.1 sys/wait.h check */
 #include <sys/types.h>
-#ifdef HAVE_SYS_WAIT_H
 #include <sys/wait.h>
-#endif /* HAVE_SYS_WAIT_H */
-#ifndef WEXITSTATUS
-#define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
-#endif /* ! WEXITSTATUS */
-#ifndef WIFEXITED
-#define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
-#endif /* ! WIFEXITED */
-
 #include <sys/time.h>
 #include <atalk/logger.h>
 #include <atalk/util.h>
 #include <atalk/dsi.h>
 #include <atalk/server_child.h>
 
-/* hand off the command. return child connection to the main program */
-afp_child_t *dsi_getsession(DSI *dsi, server_child *serv_children, int tickleval)
+/*!
+ * Start a DSI session, fork an afpd process
+ *
+ * @param childp    (w) after fork: parent return pointer to child, child returns NULL
+ * @returns             0 on sucess, any other value denotes failure
+ */
+int dsi_getsession(DSI *dsi, server_child *serv_children, int tickleval, afp_child_t **childp)
 {
   pid_t pid;
   unsigned int ipc_fds[2];  
@@ -46,19 +41,19 @@ afp_child_t *dsi_getsession(DSI *dsi, server_child *serv_children, int tickleval
 
   if (socketpair(PF_UNIX, SOCK_STREAM, 0, ipc_fds) < 0) {
       LOG(log_error, logtype_dsi, "dsi_getsess: %s", strerror(errno));
-      exit( EXITERR_CLNT );
+      return -1;
   }
 
   if (setnonblock(ipc_fds[0], 1) != 0 || setnonblock(ipc_fds[1], 1) != 0) {
       LOG(log_error, logtype_dsi, "dsi_getsess: setnonblock: %s", strerror(errno));
-      exit(EXITERR_CLNT);
+      return -1;
   }
 
   switch (pid = dsi->proto_open(dsi)) { /* in libatalk/dsi/dsi_tcp.c */
   case -1:
     /* if we fail, just return. it might work later */
     LOG(log_error, logtype_dsi, "dsi_getsess: %s", strerror(errno));
-    return NULL;
+    return -1;
 
   case 0: /* child. mostly handled below. */
     break;
@@ -77,7 +72,8 @@ afp_child_t *dsi_getsession(DSI *dsi, server_child *serv_children, int tickleval
       kill(pid, SIGKILL);
     }
     dsi->proto_close(dsi);
-    return child;
+    *childp = child;
+    return 0;
   }
   
   /* child: check number of open connections. this is one off the
@@ -95,6 +91,7 @@ afp_child_t *dsi_getsession(DSI *dsi, server_child *serv_children, int tickleval
   dsi->AFPobj->ipc_fd = ipc_fds[1];
   close(ipc_fds[0]);
   close(dsi->serversock);
+  dsi->serversock = -1;
   server_child_free(serv_children); 
 
   switch (dsi->header.dsi_command) {
@@ -126,7 +123,8 @@ afp_child_t *dsi_getsession(DSI *dsi, server_child *serv_children, int tickleval
     dsi->timer.it_interval.tv_usec = dsi->timer.it_value.tv_usec = 0;
     signal(SIGPIPE, SIG_IGN); /* we catch these ourselves */
     dsi_opensession(dsi);
-    return NULL;
+    *childp = NULL;
+    return 0;
 
   default: /* just close */
     LOG(log_info, logtype_dsi, "DSIUnknown %d", dsi->header.dsi_command);
index 33e89fad3eda10c948fa29e5b6a06b5baa5c0df0..aec872ab0c15f1aaea351ddeb9febe44860e9f9a 100644 (file)
@@ -11,9 +11,9 @@
 
 #include <stdio.h>
 #include <string.h>
+#include <arpa/inet.h>
 
 #include <atalk/dsi.h>
-#include <netatalk/endian.h>
 
 /* return the status and then delete the connection. most of the
  * fields are already set. */
index 547eed997ff815c6379c3423a60a22d2e62a43a3..824d31f36d255d407192bd6a9eaec98be63fda80 100644 (file)
@@ -1,7 +1,5 @@
 /*
- * $Id: dsi_init.c,v 1.10 2009-11-05 14:38:08 franklahm Exp $
- *
- * Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu)
+ * Copyright (c) 2012, Frank Lahm <franklahm@googlemail.com>
  * All rights reserved. See COPYRIGHT.
  */
 
 #include <stdlib.h>
 #include <signal.h>
 #include <atalk/dsi.h>
-#include "dsi_private.h"
 
-DSI *dsi_init(const dsi_proto protocol, const char *program, 
-             const char *hostname, const char *address,
-             const char *port, const int proxy, const u_int32_t quantum)
+DSI *dsi_init(AFPObj *obj, const char *hostname, const char *address, const char *port)
 {
     DSI                *dsi;
 
-    if ((dsi = (DSI *) calloc(1, sizeof(DSI))) == NULL) {
-      return( NULL );
-    }
-    dsi->attn_quantum = DSI_DEFQUANT; /* default quantum size */
-    dsi->server_quantum = quantum; /* default server quantum */
-    dsi->program = program;
+    if ((dsi = (DSI *)calloc(1, sizeof(DSI))) == NULL)
+        return NULL;
 
-    switch (protocol) {
-      /* currently the only transport protocol that exists for dsi */
-    case DSI_TCPIP: 
-      if (!dsi_tcp_init(dsi, hostname, address, port, proxy)) {
-       free(dsi);
-       dsi = NULL;
-      }
-      break;
+    dsi->attn_quantum = DSI_DEFQUANT;
+    dsi->server_quantum = obj->options.server_quantum;
+    dsi->dsireadbuf = obj->options.dsireadbuf;
 
-    default: /* unknown protocol */
-      free(dsi);
-      dsi = NULL;
-      break;
+    /* currently the only transport protocol that exists for dsi */
+    if (dsi_tcp_init(dsi, hostname, address, port) != 0) {
+        free(dsi);
+        dsi = NULL;
     }
 
     return dsi;
 }
-
-void dsi_setstatus(DSI *dsi, char *status, const size_t slen)
-{
-    dsi->status = status;
-    dsi->statuslen = slen;
-}
index 2d7fd23b84c947789f060dfe7b89b3e3ab41f398..d01e64c42fb017c2b6ec94eab1283ff8d7ef22d6 100644 (file)
 
 static void dsi_init_buffer(DSI *dsi)
 {
-    size_t quantum = dsi->server_quantum ? dsi->server_quantum : DSI_SERVQUANT_DEF;
-
     /* default is 12 * 300k = 3,6 MB (Apr 2011) */
-    if ((dsi->buffer = malloc(dsi->dsireadbuf * quantum)) == NULL) {
+    if ((dsi->buffer = malloc(dsi->dsireadbuf * dsi->server_quantum)) == NULL) {
         LOG(log_error, logtype_dsi, "dsi_init_buffer: OOM");
         AFP_PANIC("OOM in dsi_init_buffer");
     }
     dsi->start = dsi->buffer;
     dsi->eof = dsi->buffer;
-    dsi->end = dsi->buffer + (dsi->dsireadbuf * quantum);
+    dsi->end = dsi->buffer + (dsi->dsireadbuf * dsi->server_quantum);
 }
 
 /* OpenSession. set up the connection */
 void dsi_opensession(DSI *dsi)
 {
-  u_int32_t i = 0; /* this serves double duty. it must be 4-bytes long */
+  uint32_t i = 0; /* this serves double duty. it must be 4-bytes long */
   int offs;
 
   dsi_init_buffer(dsi);
diff --git a/libatalk/dsi/dsi_private.h b/libatalk/dsi/dsi_private.h
deleted file mode 100644 (file)
index 8872f8f..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * $Id: dsi_private.h,v 1.4 2009-11-05 14:38:08 franklahm Exp $
- *
- * Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu)
- * All rights reserved. See COPYRIGHT.
- */
-
-#ifndef _DSI_PRIVATE_H
-#define _DSI_PRIVATE_H 1
-
-/* this header handles interactions between protocol-specific code and
- * dsi initialization. only dsi_init.c and dsi_<proto>.c should
- * include it.
- */
-
-#include <sys/cdefs.h>
-#include <sys/types.h>
-#include <netatalk/endian.h>
-
-extern int dsi_tcp_init (DSI *, const char * /*host*/, 
-                            const char * /*address*/,
-                            const char * /*port*/,
-                            const int /*proxy*/);
-
-#endif /* _DSI_PRIVATE_H */
index 12971511022f00835b61b922871b36bb75fa5789..a0cbd872c2851a7ef2ba14021a52138f4a03d7ad 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: dsi_read.c,v 1.7 2009-10-25 06:13:11 didg Exp $
- *
  * Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu)
  * All rights reserved. See COPYRIGHT.
  */
 
 #include <stdio.h>
 #include <string.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <signal.h>
 #include <sys/types.h>
 #include <sys/time.h>
-#ifdef HAVE_SYS_FILIO_H
-#include <sys/filio.h>
-#endif
 
 #include <atalk/dsi.h>
 #include <atalk/util.h>
@@ -30,8 +23,7 @@
  * it will send off the header plus whatever is in its command
  * buffer. it returns the amount of stuff still to be read
  * (constrained by the buffer size). */
-ssize_t dsi_readinit(DSI *dsi, void *buf, const size_t buflen,
-                     const size_t size, const int err)
+ssize_t dsi_readinit(DSI *dsi, void *buf, const size_t buflen, const size_t size, const int err)
 {
     LOG(log_maxdebug, logtype_dsi, "dsi_readinit: sending %zd bytes from buffer, total size: %zd",
         buflen, size);
index ab1339184b48b1394a89415c481f2689ad0d83c9..97eb8ad717e96b17c493df472a2254be318a0c15 100644 (file)
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 1998 Adrian Sun (asun@zoology.washington.edu)
+ * Copyright (c) 2010,2011,2012 Frank Lahm <franklahm@googlemail.com>
  * All rights reserved. See COPYRIGHT.
  *
  * this file provides the following functions:
 
 #include <stdio.h>
 #include <stdlib.h>
-
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif
-
 #include <string.h>
 #include <errno.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/uio.h>
 
+#ifdef HAVE_SENDFILEV
+#include <sys/sendfile.h>
+#endif
+
 #include <atalk/logger.h>
 #include <atalk/dsi.h>
-#include <netatalk/endian.h>
 #include <atalk/util.h>
 
-#define min(a,b)  ((a) < (b) ? (a) : (b))
-
 #ifndef MSG_MORE
 #define MSG_MORE 0x8000
 #endif
 #define MSG_DONTWAIT 0x40
 #endif
 
+/* Pack a DSI header in wire format */
+static void dsi_header_pack_reply(const DSI *dsi, char *buf)
+{
+    buf[0] = dsi->header.dsi_flags;
+    buf[1] = dsi->header.dsi_command;
+    memcpy(buf + 2, &dsi->header.dsi_requestID, sizeof(dsi->header.dsi_requestID));           
+    memcpy(buf + 4, &dsi->header.dsi_code, sizeof(dsi->header.dsi_code));
+    memcpy(buf + 8, &dsi->header.dsi_len, sizeof(dsi->header.dsi_len));
+    memcpy(buf + 12, &dsi->header.dsi_reserved, sizeof(dsi->header.dsi_reserved));
+}
+
 /*
  * afpd is sleeping too much while trying to send something.
  * May be there's no reader or the reader is also sleeping in write,
@@ -128,7 +137,7 @@ static int dsi_peek(DSI *dsi)
 /* 
  * Return all bytes up to count from dsi->buffer if there are any buffered there
  */
-static size_t from_buf(DSI *dsi, u_int8_t *buf, size_t count)
+static size_t from_buf(DSI *dsi, uint8_t *buf, size_t count)
 {
     size_t nbe = 0;
 
@@ -141,7 +150,7 @@ static size_t from_buf(DSI *dsi, u_int8_t *buf, size_t count)
     nbe = dsi->eof - dsi->start;
 
     if (nbe > 0) {
-        nbe = min((size_t)nbe, count);
+        nbe = MIN((size_t)nbe, count);
         memcpy(buf, dsi->start, nbe);
         dsi->start += nbe;
 
@@ -163,7 +172,7 @@ static size_t from_buf(DSI *dsi, u_int8_t *buf, size_t count)
  *    Note: this may return fewer bytes then requested in count !!
  * 3. If the buffer was empty, read from the socket.
  */
-static ssize_t buf_read(DSI *dsi, u_int8_t *buf, size_t count)
+static ssize_t buf_read(DSI *dsi, uint8_t *buf, size_t count)
 {
     ssize_t len;
 
@@ -187,7 +196,7 @@ static ssize_t buf_read(DSI *dsi, u_int8_t *buf, size_t count)
  * Get "length" bytes from buffer and/or socket. In order to avoid frequent small reads
  * this tries to read larger chunks (8192 bytes) into a buffer.
  */
-static size_t dsi_buffered_stream_read(DSI *dsi, u_int8_t *data, const size_t length)
+static size_t dsi_buffered_stream_read(DSI *dsi, uint8_t *data, const size_t length)
 {
   size_t len;
   size_t buflen;
@@ -201,7 +210,7 @@ static size_t dsi_buffered_stream_read(DSI *dsi, u_int8_t *data, const size_t le
   }
 
   /* fill the buffer with 8192 bytes or until buffer is full */
-  buflen = min(8192, dsi->end - dsi->eof);
+  buflen = MIN(8192, dsi->end - dsi->eof);
   if (buflen > 0) {
       ssize_t ret;
       ret = read(dsi->socket, dsi->eof, buflen);
@@ -264,7 +273,7 @@ ssize_t dsi_stream_write(DSI *dsi, void *data, const size_t length, int mode)
 {
   size_t written;
   ssize_t len;
-  unsigned int flags = 0;
+  unsigned int flags;
 
   dsi->in_write++;
   written = 0;
@@ -274,8 +283,13 @@ ssize_t dsi_stream_write(DSI *dsi, void *data, const size_t length, int mode)
   if (dsi->flags & DSI_DISCONNECTED)
       return -1;
 
+  if (mode & DSI_MSG_MORE)
+      flags = MSG_MORE;
+  else
+      flags = 0;
+
   while (written < length) {
-      len = send(dsi->socket, (u_int8_t *) data + written, length - written, flags);
+      len = send(dsi->socket, (uint8_t *) data + written, length - written, flags);
       if (len >= 0) {
           written += len;
           continue;
@@ -315,72 +329,116 @@ exit:
   return written;
 }
 
-
 /* ---------------------------------
 */
 #ifdef WITH_SENDFILE
-ssize_t dsi_stream_read_file(DSI *dsi, int fromfd, off_t offset, const size_t length)
+ssize_t dsi_stream_read_file(DSI *dsi, const int fromfd, off_t offset, const size_t length, const int err)
 {
-  int ret = 0;
-  size_t written;
-  ssize_t len;
-  off_t pos = offset;
+    int ret = 0;
+    size_t written = 0;
+    size_t total = length;
+    ssize_t len;
+    off_t pos = offset;
+    char block[DSI_BLOCKSIZ];
+#ifdef HAVE_SENDFILEV
+    int sfvcnt;
+    struct sendfilevec vec[2];
+    ssize_t nwritten;
+#endif
 
-  LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file(send %zd bytes): START", length);
+    LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file(off: %jd, len: %zu)", (intmax_t)offset, length);
 
-  if (dsi->flags & DSI_DISCONNECTED)
-      return -1;
+    if (dsi->flags & DSI_DISCONNECTED)
+        return -1;
 
-  dsi->in_write++;
-  written = 0;
+    dsi->in_write++;
+
+    dsi->flags |= DSI_NOREPLY;
+    dsi->header.dsi_flags = DSIFL_REPLY;
+    dsi->header.dsi_len = htonl(length);
+    dsi->header.dsi_code = htonl(err);
+    dsi_header_pack_reply(dsi, block);
+
+#ifdef HAVE_SENDFILEV
+    total += DSI_BLOCKSIZ;
+    sfvcnt = 2;
+    vec[0].sfv_fd = SFV_FD_SELF;
+    vec[0].sfv_flag = 0;
+    vec[0].sfv_off = block;
+    vec[0].sfv_len = DSI_BLOCKSIZ;
+    vec[1].sfv_fd = fromfd;
+    vec[1].sfv_flag = 0;
+    vec[1].sfv_off = offset;
+    vec[1].sfv_len = length;
+#else
+    dsi_stream_write(dsi, block, sizeof(block), DSI_MSG_MORE);
+#endif
 
-  while (written < length) {
-    len = sys_sendfile(dsi->socket, fromfd, &pos, length - written);
-        
-    if (len < 0) {
-      if (errno == EINTR)
-          continue;
-      if (errno == EINVAL || errno == ENOSYS) {
-          ret = -1;
-          goto exit;
-      }          
-      if (errno == EAGAIN || errno == EWOULDBLOCK) {
-#if defined(SOLARIS) || defined(FREEBSD)
-          if (pos > offset) {
-              /* we actually have sent sth., adjust counters and keep trying */
-              len = pos - offset;
-              written += len;
-              offset = pos;
-          }
+    while (written < total) {
+#ifdef HAVE_SENDFILEV
+        nwritten = 0;
+        len = sendfilev(dsi->socket, vec, sfvcnt, &nwritten);
+#else
+        len = sys_sendfile(dsi->socket, fromfd, &pos, total - written);
 #endif
-          if (dsi_peek(dsi)) {
-              /* can't go back to blocking mode, exit, the next read
-                 will return with an error and afpd will die.
-              */
-              break;
-          }
-          continue;
-      }
-      LOG(log_error, logtype_dsi, "dsi_stream_read_file: %s", strerror(errno));
-      break;
-    }
-    else if (!len) {
-        /* afpd is going to exit */
-          ret = -1;
-          goto exit;
-    }
-    else 
-        written += len;
-  }
+        if (len < 0) {
+            switch (errno) {
+            case EINTR:
+            case EAGAIN:
+                len = 0;
+#ifdef HAVE_SENDFILEV
+                len = (size_t)nwritten;
+#else
+#if defined(SOLARIS) || defined(FREEBSD)
+                if (pos > offset) {
+                    /* we actually have sent sth., adjust counters and keep trying */
+                    len = pos - offset;
+                    offset = pos;
+                }
+#endif /* defined(SOLARIS) || defined(FREEBSD) */
+#endif /* HAVE_SENDFILEV */
 
-  dsi->write_count += written;
+                if (dsi_peek(dsi)) {
+                    ret = -1;
+                    goto exit;
+                }
+                break;
+            default:
+                LOG(log_error, logtype_dsi, "dsi_stream_read_file: %s", strerror(errno));
+                ret = -1;
+                goto exit;
+            }
+        } else if (len == 0) {
+            /* afpd is going to exit */
+            ret = -1;
+            goto exit;
+        }
+#ifdef HAVE_SENDFILEV
+        if (sfvcnt == 2 && len >= vec[0].sfv_len) {
+            vec[1].sfv_off += len - vec[0].sfv_len;
+            vec[1].sfv_len -= len - vec[0].sfv_len;
+
+            vec[0] = vec[1];
+            sfvcnt = 1;
+        } else {
+            vec[0].sfv_off += len;
+            vec[0].sfv_len -= len;
+        }
+#endif  /* HAVE_SENDFILEV */
+        LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file: wrote: %zd", len);
+        written += len;
+    }
+#ifdef HAVE_SENDFILEV
+    written -= DSI_BLOCKSIZ;
+#endif
+    dsi->write_count += written;
 
 exit:
-  dsi->in_write--;
-  LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file: sent: %zd", written);
-  if (ret != 0)
-      return -1;
-  return written;
+    dsi->in_write--;
+    LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file: written: %zd", written);
+    if (ret != 0)
+        return -1;
+    return written;
 }
 #endif
 
@@ -403,7 +461,7 @@ size_t dsi_stream_read(DSI *dsi, void *data, const size_t length)
 
   stored = 0;
   while (stored < length) {
-      len = buf_read(dsi, (u_int8_t *) data + stored, length - stored);
+      len = buf_read(dsi, (uint8_t *) data + stored, length - stored);
       if (len == -1 && (errno == EINTR || errno == EAGAIN)) {
           LOG(log_maxdebug, logtype_dsi, "dsi_stream_read: select read loop");
           continue;
@@ -448,14 +506,7 @@ int dsi_stream_send(DSI *dsi, void *buf, size_t length)
   if (dsi->flags & DSI_DISCONNECTED)
       return 0;
 
-  block[0] = dsi->header.dsi_flags;
-  block[1] = dsi->header.dsi_command;
-  memcpy(block + 2, &dsi->header.dsi_requestID, 
-        sizeof(dsi->header.dsi_requestID));
-  memcpy(block + 4, &dsi->header.dsi_code, sizeof(dsi->header.dsi_code));
-  memcpy(block + 8, &dsi->header.dsi_len, sizeof(dsi->header.dsi_len));
-  memcpy(block + 12, &dsi->header.dsi_reserved,
-        sizeof(dsi->header.dsi_reserved));
+  dsi_header_pack_reply(dsi, block);
 
   if (!length) { /* just write the header */
       LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): DSI header, no data", sizeof(block));
@@ -527,7 +578,7 @@ int dsi_stream_receive(DSI *dsi)
       return 0;
 
   /* read in the header */
-  if (dsi_buffered_stream_read(dsi, (u_int8_t *)block, sizeof(block)) != sizeof(block)) 
+  if (dsi_buffered_stream_read(dsi, (uint8_t *)block, sizeof(block)) != sizeof(block)) 
     return 0;
 
   dsi->header.dsi_flags = block[0];
@@ -543,7 +594,7 @@ int dsi_stream_receive(DSI *dsi)
   dsi->clientID = ntohs(dsi->header.dsi_requestID);
   
   /* make sure we don't over-write our buffers. */
-  dsi->cmdlen = min(ntohl(dsi->header.dsi_len), DSI_CMDSIZ);
+  dsi->cmdlen = MIN(ntohl(dsi->header.dsi_len), DSI_CMDSIZ);
   if (dsi_stream_read(dsi, dsi->commands, dsi->cmdlen) != dsi->cmdlen) 
     return 0;
 
index 3aa900ff20e5270a4495974d5bb1969298e01275..2c16323e2d607884e60ceff2dc6371b3f0a92a7b 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * $Id: dsi_tcp.c,v 1.25 2009-12-08 22:34:37 didg Exp $
- *
  * Copyright (c) 1997, 1998 Adrian Sun (asun@zoology.washington.edu)
  * All rights reserved. See COPYRIGHT.
  *
@@ -15,9 +13,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <errno.h>
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #include <sys/types.h>
 #include <sys/time.h>
 #include <sys/socket.h>
-
-#ifdef HAVE_STDINT_H
 #include <stdint.h>
-#endif /* HAVE_STDINT_H */
 
 #include <sys/ioctl.h>
 #ifdef TRU64
@@ -56,8 +49,7 @@ int deny_severity = log_warning;
 #include <atalk/dsi.h>
 #include <atalk/compat.h>
 #include <atalk/util.h>
-#include <netatalk/endian.h>
-#include "dsi_private.h"
+#include <atalk/errchk.h>
 
 #define min(a,b)  ((a) < (b) ? (a) : (b))
 
@@ -104,7 +96,7 @@ static int dsi_tcp_open(DSI *dsi)
 #ifdef TCPWRAP
     {
         struct request_info req;
-        request_init(&req, RQ_DAEMON, dsi->program, RQ_FILE, dsi->socket, NULL);
+        request_init(&req, RQ_DAEMON, "afpd", RQ_FILE, dsi->socket, NULL);
         fromhost(&req);
         if (!hosts_access(&req)) {
             LOG(deny_severity, logtype_dsi, "refused connect from %s", eval_client(&req));
@@ -122,12 +114,9 @@ static int dsi_tcp_open(DSI *dsi)
     if (0 == (pid = fork()) ) { /* child */
         static struct itimerval timer = {{0, 0}, {DSI_TCPTIMEOUT, 0}};
         struct sigaction newact, oldact;
-        u_int8_t block[DSI_BLOCKSIZ];
+        uint8_t block[DSI_BLOCKSIZ];
         size_t stored;
 
-        /* Immediateyl mark globally that we're a child now */
-        parent_or_child = 1;
-
         /* reset signals */
         server_reset_signal();
 
@@ -258,9 +247,10 @@ static void guess_interface(DSI *dsi, const char *hostname, const char *port)
             getip_string((struct sockaddr *)&dsi->server), port, ifr.ifr_name);
         goto iflist_done;
     }
-    LOG(log_info, logtype_dsi, "dsi_tcp (Chooser will not select afp/tcp) "
-        "Check to make sure %s is in /etc/hosts and the correct domain is in "
-        "/etc/resolv.conf: %s", hostname, strerror(errno));
+
+    LOG(log_note, logtype_dsi, "dsi_tcp: couldn't find network interface with IP address to advertice, "
+        "check to make sure \"%s\" is in /etc/hosts or can be resolved with DNS, or "
+        "add a netinterface that is not a loopback or point-2-point type", hostname);
 
 iflist_done:
     close(fd);
@@ -273,14 +263,24 @@ iflist_done:
 #endif
 
 /* this needs to accept passed in addresses */
-int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address,
-                 const char *port, const int proxy)
+int dsi_tcp_init(DSI *dsi, const char *hostname, const char *inaddress, const char *inport)
 {
-    int                ret;
-    int                flag;
+    EC_INIT;
+    int                flag, err;
+    char               *a = NULL, *b;
+    const char         *address;
+    const char         *port;
     struct addrinfo    hints, *servinfo, *p;
 
-    dsi->protocol = DSI_TCPIP;
+    /* Check whether address is of the from IP:PORT and split */
+    address = inaddress;
+    port = inport;
+    if (address && strchr(address, ':')) {
+        EC_NULL_LOG( address = a = strdup(address) );
+        b = strchr(a, ':');
+        *b = 0;
+        port = b + 1;
+    }
 
     /* Prepare hint for getaddrinfo */
     memset(&hints, 0, sizeof hints);
@@ -301,67 +301,62 @@ int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address,
         hints.ai_family = AF_UNSPEC;
 #endif
     }
-    if ((ret = getaddrinfo(address ? address : NULL, port ? port : "548", &hints, &servinfo)) != 0) {
+    if ((ret = getaddrinfo(address ? address : NULL, port, &hints, &servinfo)) != 0) {
         LOG(log_error, logtype_dsi, "dsi_tcp_init: getaddrinfo: %s\n", gai_strerror(ret));
-        return 0;
+        EC_FAIL;
     }
 
-    /* create a socket */
-    if (proxy)
-        dsi->serversock = -1;
-    else {
-        /* loop through all the results and bind to the first we can */
-        for (p = servinfo; p != NULL; p = p->ai_next) {
-            if ((dsi->serversock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
-                LOG(log_info, logtype_dsi, "dsi_tcp_init: socket: %s", strerror(errno));
-                continue;
-            }
+    /* loop through all the results and bind to the first we can */
+    for (p = servinfo; p != NULL; p = p->ai_next) {
+        if ((dsi->serversock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
+            LOG(log_info, logtype_dsi, "dsi_tcp_init: socket: %s", strerror(errno));
+            continue;
+        }
 
-            /*
-             * Set some socket options:
-             * SO_REUSEADDR deals w/ quick close/opens
-             * TCP_NODELAY diables Nagle
-             */
+        /*
+         * Set some socket options:
+         * SO_REUSEADDR deals w/ quick close/opens
+         * TCP_NODELAY diables Nagle
+         */
 #ifdef SO_REUSEADDR
-            flag = 1;
-            setsockopt(dsi->serversock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
+        flag = 1;
+        setsockopt(dsi->serversock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
 #endif
 #if defined(FREEBSD) && defined(IPV6_BINDV6ONLY)
-            int on = 0;
-            setsockopt(dsi->serversock, IPPROTO_IPV6, IPV6_BINDV6ONLY, (char *)&on, sizeof (on));
+        int on = 0;
+        setsockopt(dsi->serversock, IPPROTO_IPV6, IPV6_BINDV6ONLY, (char *)&on, sizeof (on));
 #endif
 
 #ifndef SOL_TCP
 #define SOL_TCP IPPROTO_TCP
 #endif
-            flag = 1;
-            setsockopt(dsi->serversock, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
-            
-            if (bind(dsi->serversock, p->ai_addr, p->ai_addrlen) == -1) {
-                close(dsi->serversock);
-                LOG(log_info, logtype_dsi, "dsi_tcp_init: bind: %s\n", strerror(errno));
-                continue;
-            }
-
-            if (listen(dsi->serversock, DSI_TCPMAXPEND) < 0) {
-                close(dsi->serversock);
-                LOG(log_info, logtype_dsi, "dsi_tcp_init: listen: %s\n", strerror(errno));
-                continue;
-            }
+        flag = 1;
+        setsockopt(dsi->serversock, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
             
-            break;
+        if (bind(dsi->serversock, p->ai_addr, p->ai_addrlen) == -1) {
+            close(dsi->serversock);
+            LOG(log_info, logtype_dsi, "dsi_tcp_init: bind: %s\n", strerror(errno));
+            continue;
         }
 
-        if (p == NULL)  {
-            LOG(log_error, logtype_dsi, "dsi_tcp_init: no suitable network config for TCP socket");
-            freeaddrinfo(servinfo);
-            return 0;
+        if (listen(dsi->serversock, DSI_TCPMAXPEND) < 0) {
+            close(dsi->serversock);
+            LOG(log_info, logtype_dsi, "dsi_tcp_init: listen: %s\n", strerror(errno));
+            continue;
         }
+            
+        break;
+    }
 
-        /* Copy struct sockaddr to struct sockaddr_storage */
-        memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
+    if (p == NULL)  {
+        LOG(log_error, logtype_dsi, "dsi_tcp_init: no suitable network config for TCP socket");
         freeaddrinfo(servinfo);
-    } /* if (proxy) */
+        EC_FAIL;
+    }
+
+    /* Copy struct sockaddr to struct sockaddr_storage */
+    memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
+    freeaddrinfo(servinfo);
 
     /* Point protocol specific functions to tcp versions */
     dsi->proto_open = dsi_tcp_open;
@@ -371,7 +366,7 @@ int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address,
 
     if (address) {
         /* address is a parameter, use it 'as is' */
-        return 1;
+        goto EC_CLEANUP;
     }
 
     /* Prepare hint for getaddrinfo */
@@ -379,8 +374,8 @@ int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address,
     hints.ai_family = AF_UNSPEC;
     hints.ai_socktype = SOCK_STREAM;
 
-    if ((ret = getaddrinfo(hostname, port ? port : "548", &hints, &servinfo)) != 0) {
-        LOG(log_info, logtype_dsi, "dsi_tcp_init: getaddrinfo '%s': %s\n", hostname, gai_strerror(ret));
+    if ((err = getaddrinfo(hostname, port, &hints, &servinfo)) != 0) {
+        LOG(log_info, logtype_dsi, "dsi_tcp_init: getaddrinfo '%s': %s\n", hostname, gai_strerror(err));
         goto interfaces;
     }
 
@@ -401,13 +396,17 @@ int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address,
         /* Store found address in dsi->server */
         memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
         freeaddrinfo(servinfo);
-        return 1;
+        goto EC_CLEANUP;
     }
     LOG(log_info, logtype_dsi, "dsi_tcp: hostname '%s' resolves to loopback address", hostname);
     freeaddrinfo(servinfo);
 
 interfaces:
     guess_interface(dsi, hostname, port ? port : "548");
-    return 1;
+
+EC_CLEANUP:
+    if (a)
+        free(a);
+    EC_EXIT;
 }
 
index 2a996539a968ba0201c8c19d1f62e9a53a8f7c25..40d0c0ad4cb43376dc0421c4b8fd504708fc15e2 100644 (file)
 #include <signal.h>
 
 #include <atalk/dsi.h>
-#include <netatalk/endian.h>
 
 /* server generated tickles. as this is only called by the tickle handler,
  * we don't need to block signals. */
 int dsi_tickle(DSI *dsi)
 {
   char block[DSI_BLOCKSIZ];
-  u_int16_t id;
+  uint16_t id;
   
   if ((dsi->flags & DSI_SLEEPING) || dsi->in_write)
       return 1;
index 79d03caf9491175267e75cd6be1edd55869c9064..13a723470153895766530e65235d3a2b00c6070d 100644 (file)
 
 /* this streams writes */
 #include <stdio.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <sys/time.h>
-#ifdef HAVE_FCNTL_H
 #include <fcntl.h>
-#endif /* HAVE_FCNTL_H */
 #include <string.h>
 
 #include <atalk/dsi.h>
-#include <netatalk/endian.h>
-
-#ifndef MIN
-#define MIN(a,b)     ((a) < (b) ? (a) : (b))
-#endif /* ! MIN */
+#include <atalk/util.h>
+#include <atalk/logger.h>
 
 /* initialize relevant things for dsi_write. this returns the amount
  * of data in the data buffer. the interface has been reworked to allow
@@ -42,17 +35,21 @@ size_t dsi_writeinit(DSI *dsi, void *buf, const size_t buflen _U_)
    * data */
   header = ntohl(dsi->header.dsi_code);
   dsi->datasize = header ? ntohl(dsi->header.dsi_len) - header : 0;
+
   if (dsi->datasize > 0) {
-    len = MIN(sizeof(dsi->commands) - header, dsi->datasize);
-    
-    /* write last part of command buffer into buf */
-    memcpy(buf, dsi->commands + header, len);
-    
-    /* recalculate remaining data */
-    dsi->datasize -= len;
+      len = MIN(sizeof(dsi->commands) - header, dsi->datasize);
+
+      /* write last part of command buffer into buf */
+      memcpy(buf, dsi->commands + header, len);
+
+      /* recalculate remaining data */
+      dsi->datasize -= len;
   } else
     len = 0;
 
+  LOG(log_maxdebug, logtype_dsi, "dsi_writeinit: len: %ju, remaining DSI datasize: %jd",
+      (intmax_t)len, (intmax_t)dsi->datasize);
+
   return len;
 }
 
@@ -63,10 +60,14 @@ size_t dsi_write(DSI *dsi, void *buf, const size_t buflen)
 {
   size_t length;
 
-  if (((length = MIN(buflen, dsi->datasize)) > 0) &&
-      ((length = dsi_stream_read(dsi, buf, length)) > 0)) {
-    dsi->datasize -= length;
-    return length;
+  LOG(log_maxdebug, logtype_dsi, "dsi_write: remaining DSI datasize: %jd", (intmax_t)dsi->datasize);
+
+  if ((length = MIN(buflen, dsi->datasize)) > 0) {
+      if ((length = dsi_stream_read(dsi, buf, length)) > 0) {
+          LOG(log_maxdebug, logtype_dsi, "dsi_write: received: %ju", (intmax_t)length);
+          dsi->datasize -= length;
+          return length;
+      }
   }
   return 0;
 }
diff --git a/libatalk/iniparser/Makefile.am b/libatalk/iniparser/Makefile.am
new file mode 100644 (file)
index 0000000..a0789af
--- /dev/null
@@ -0,0 +1,7 @@
+# Makefile.am for libatalk/iniparser/
+
+noinst_LTLIBRARIES = libiniparser.la
+
+libiniparser_la_SOURCES = \
+       dictionary.c \
+       iniparser.c
diff --git a/libatalk/iniparser/dictionary.c b/libatalk/iniparser/dictionary.c
new file mode 100644 (file)
index 0000000..b44796b
--- /dev/null
@@ -0,0 +1,376 @@
+/*-------------------------------------------------------------------------*/
+/**
+   @file       dictionary.c
+   @author     N. Devillard
+   @date       Sep 2007
+   @version    $Revision: 1.27 $
+   @brief      Implements a dictionary for string variables.
+
+   This module implements a simple dictionary object, i.e. a list
+   of string/string associations. This object is useful to store e.g.
+   informations retrieved from a configuration file (ini files).
+*/
+/*--------------------------------------------------------------------------*/
+
+/*
+       $Id: dictionary.c,v 1.27 2007-11-23 21:39:18 ndevilla Exp $
+       $Revision: 1.27 $
+*/
+/*---------------------------------------------------------------------------
+                                                               Includes
+ ---------------------------------------------------------------------------*/
+#include <atalk/dictionary.h>
+#include <atalk/compat.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+/** Maximum value size for integers and doubles. */
+#define MAXVALSZ       1024
+
+/** Minimal allocated number of entries in a dictionary */
+#define DICTMINSZ      128
+
+/** Invalid key token */
+#define DICT_INVALID_KEY    ((char*)-1)
+
+/*---------------------------------------------------------------------------
+                                                       Private functions
+ ---------------------------------------------------------------------------*/
+
+#define MAXKEYSIZE 1024
+static char *makekey(const char *section, const char *entry)
+{
+    static char buf[MAXKEYSIZE];
+
+    strlcpy(buf, section, MAXKEYSIZE);
+    if (entry) {
+        strlcat(buf, ":", MAXKEYSIZE);
+        strlcat(buf, entry, MAXKEYSIZE);
+    }
+
+    return buf;
+}
+
+/* Doubles the allocated size associated to a pointer */
+/* 'size' is the current allocated size. */
+static void * mem_double(void * ptr, int size)
+{
+    void * newptr ;
+    newptr = calloc(2*size, 1);
+    if (newptr==NULL) {
+        return NULL ;
+    }
+    memcpy(newptr, ptr, size);
+    free(ptr);
+    return newptr ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Duplicate a string
+  @param    s String to duplicate
+  @return   Pointer to a newly allocated string, to be freed with free()
+
+  This is a replacement for strdup(). This implementation is provided
+  for systems that do not have it.
+ */
+/*--------------------------------------------------------------------------*/
+static char * xstrdup(char * s)
+{
+    char * t ;
+    if (!s)
+        return NULL ;
+    t = malloc(strlen(s)+1) ;
+    if (t) {
+        strcpy(t,s);
+    }
+    return t ;
+}
+
+/*---------------------------------------------------------------------------
+                                                       Function codes
+ ---------------------------------------------------------------------------*/
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Compute the hash key for a string.
+  @param       key             Character string to use for key.
+  @return      1 unsigned int on at least 32 bits.
+
+  This hash function has been taken from an Article in Dr Dobbs Journal.
+  This is normally a collision-free function, distributing keys evenly.
+  The key is stored anyway in the struct so that collision can be avoided
+  by comparing the key itself in last resort.
+ */
+/*--------------------------------------------------------------------------*/
+unsigned dictionary_hash(char * key)
+{
+       int                     len ;
+       unsigned        hash ;
+       int                     i ;
+
+       len = strlen(key);
+       for (hash=0, i=0 ; i<len ; i++) {
+               hash += (unsigned)key[i] ;
+               hash += (hash<<10);
+               hash ^= (hash>>6) ;
+       }
+       hash += (hash <<3);
+       hash ^= (hash >>11);
+       hash += (hash <<15);
+       return hash ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Create a new dictionary object.
+  @param       size    Optional initial size of the dictionary.
+  @return      1 newly allocated dictionary objet.
+
+  This function allocates a new dictionary object of given size and returns
+  it. If you do not know in advance (roughly) the number of entries in the
+  dictionary, give size=0.
+ */
+/*--------------------------------------------------------------------------*/
+dictionary * dictionary_new(int size)
+{
+       dictionary      *       d ;
+
+       /* If no size was specified, allocate space for DICTMINSZ */
+       if (size<DICTMINSZ) size=DICTMINSZ ;
+
+       if (!(d = (dictionary *)calloc(1, sizeof(dictionary)))) {
+               return NULL;
+       }
+       d->size = size ;
+       d->val  = (char **)calloc(size, sizeof(char*));
+       d->key  = (char **)calloc(size, sizeof(char*));
+       d->hash = (unsigned int *)calloc(size, sizeof(unsigned));
+       return d ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Delete a dictionary object
+  @param       d       dictionary object to deallocate.
+  @return      void
+
+  Deallocate a dictionary object and all memory associated to it.
+ */
+/*--------------------------------------------------------------------------*/
+void dictionary_del(dictionary * d)
+{
+       int             i ;
+
+       if (d==NULL) return ;
+       for (i=0 ; i<d->size ; i++) {
+               if (d->key[i]!=NULL)
+                       free(d->key[i]);
+               if (d->val[i]!=NULL)
+                       free(d->val[i]);
+       }
+       free(d->val);
+       free(d->key);
+       free(d->hash);
+       free(d);
+       return ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Get a value from a dictionary.
+  @param       d               dictionary object to search.
+  @param       key             Key to look for in the dictionary.
+  @param    def     Default value to return if key not found.
+  @return      1 pointer to internally allocated character string.
+
+  This function locates a key in a dictionary and returns a pointer to its
+  value, or the passed 'def' pointer if no such key can be found in
+  dictionary. The returned character pointer points to data internal to the
+  dictionary object, you should not try to free it or modify it.
+ */
+/*--------------------------------------------------------------------------*/
+const char * dictionary_get(const dictionary * d, const char *section, const char * key, const char * def)
+{
+       unsigned        hash ;
+       int                     i ;
+
+       hash = dictionary_hash(makekey(section, key));
+       for (i=0 ; i<d->size ; i++) {
+        if (d->key[i]==NULL)
+            continue ;
+        /* Compare hash */
+               if (hash==d->hash[i]) {
+            /* Compare string, to avoid hash collisions */
+            if (!strcmp(makekey(section, key), d->key[i])) {
+                               return d->val[i] ;
+                       }
+               }
+       }
+       return def ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Set a value in a dictionary.
+  @param    d       dictionary object to modify.
+  @param    key     Key to modify or add.
+  @param    val     Value to add.
+  @return   int     0 if Ok, anything else otherwise
+
+  If the given key is found in the dictionary, the associated value is
+  replaced by the provided one. If the key cannot be found in the
+  dictionary, it is added to it.
+
+  It is Ok to provide a NULL value for val, but NULL values for the dictionary
+  or the key are considered as errors: the function will return immediately
+  in such a case.
+
+  Notice that if you dictionary_set a variable to NULL, a call to
+  dictionary_get will return a NULL value: the variable will be found, and
+  its value (NULL) is returned. In other words, setting the variable
+  content to NULL is equivalent to deleting the variable from the
+  dictionary. It is not possible (in this implementation) to have a key in
+  the dictionary without value.
+
+  This function returns non-zero in case of failure.
+ */
+/*--------------------------------------------------------------------------*/
+int dictionary_set(dictionary * d, char *section, char * key, char * val)
+{
+       int                     i ;
+       unsigned        hash ;
+
+       if (d==NULL || section==NULL) return -1 ;
+       
+       /* Compute hash for this key */
+       hash = dictionary_hash(makekey(section, key));
+       /* Find if value is already in dictionary */
+       if (d->n>0) {
+               for (i=0 ; i<d->size ; i++) {
+            if (d->key[i]==NULL)
+                continue ;
+                       if (hash==d->hash[i]) { /* Same hash value */
+                               if (!strcmp(makekey(section, key), d->key[i])) {         /* Same key */
+                                       /* Found a value: modify and return */
+                                       if (d->val[i]!=NULL)
+                                               free(d->val[i]);
+                    d->val[i] = val ? xstrdup(val) : NULL ;
+                    /* Value has been modified: return */
+                                       return 0 ;
+                               }
+                       }
+               }
+       }
+       /* Add a new value */
+       /* See if dictionary needs to grow */
+       if (d->n==d->size) {
+
+               /* Reached maximum size: reallocate dictionary */
+               d->val  = (char **)mem_double(d->val,  d->size * sizeof(char*)) ;
+               d->key  = (char **)mem_double(d->key,  d->size * sizeof(char*)) ;
+               d->hash = (unsigned int *)mem_double(d->hash, d->size * sizeof(unsigned)) ;
+        if ((d->val==NULL) || (d->key==NULL) || (d->hash==NULL)) {
+            /* Cannot grow dictionary */
+            return -1 ;
+        }
+               /* Double size */
+               d->size *= 2 ;
+       }
+
+    /* Insert key in the first empty slot */
+    for (i=0 ; i<d->size ; i++) {
+        if (d->key[i]==NULL) {
+            /* Add key here */
+            break ;
+        }
+    }
+       /* Copy key */
+       d->key[i]  = xstrdup(makekey(section, key));
+    d->val[i]  = val ? xstrdup(val) : NULL ;
+       d->hash[i] = hash;
+       d->n ++ ;
+       return 0 ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Delete a key in a dictionary
+  @param       d               dictionary object to modify.
+  @param       key             Key to remove.
+  @return   void
+
+  This function deletes a key in a dictionary. Nothing is done if the
+  key cannot be found.
+ */
+/*--------------------------------------------------------------------------*/
+void dictionary_unset(dictionary * d, char *section, char * key)
+{
+       unsigned        hash ;
+       int                     i ;
+
+       if (key == NULL) {
+               return;
+       }
+
+       hash = dictionary_hash(makekey(section, key));
+       for (i=0 ; i<d->size ; i++) {
+        if (d->key[i]==NULL)
+            continue ;
+        /* Compare hash */
+               if (hash==d->hash[i]) {
+            /* Compare string, to avoid hash collisions */
+            if (!strcmp(makekey(section, key), d->key[i])) {
+                /* Found key */
+                break ;
+                       }
+               }
+       }
+    if (i>=d->size)
+        /* Key not found */
+        return ;
+
+    free(d->key[i]);
+    d->key[i] = NULL ;
+    if (d->val[i]!=NULL) {
+        free(d->val[i]);
+        d->val[i] = NULL ;
+    }
+    d->hash[i] = 0 ;
+    d->n -- ;
+    return ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Dump a dictionary to an opened file pointer.
+  @param       d       Dictionary to dump
+  @param       f       Opened file pointer.
+  @return      void
+
+  Dumps a dictionary onto an opened file pointer. Key pairs are printed out
+  as @c [Key]=[Value], one per line. It is Ok to provide stdout or stderr as
+  output file pointers.
+ */
+/*--------------------------------------------------------------------------*/
+void dictionary_dump(dictionary * d, FILE * out)
+{
+       int             i ;
+
+       if (d==NULL || out==NULL) return ;
+       if (d->n<1) {
+               fprintf(out, "empty dictionary\n");
+               return ;
+       }
+       for (i=0 ; i<d->size ; i++) {
+        if (d->key[i]) {
+            fprintf(out, "%20s\t[%s]\n",
+                    d->key[i],
+                    d->val[i] ? d->val[i] : "UNDEF");
+        }
+       }
+       return ;
+}
diff --git a/libatalk/iniparser/iniparser.c b/libatalk/iniparser/iniparser.c
new file mode 100644 (file)
index 0000000..8e58de6
--- /dev/null
@@ -0,0 +1,653 @@
+
+/*-------------------------------------------------------------------------*/
+/**
+   @file    iniparser.c
+   @author  N. Devillard
+   @date    Sep 2007
+   @version 3.0
+   @brief   Parser for ini files.
+*/
+
+/*---------------------------- Includes ------------------------------------*/
+#include <ctype.h>
+
+#include <atalk/iniparser.h>
+#include <atalk/logger.h>
+
+/*---------------------------- Defines -------------------------------------*/
+#define ASCIILINESZ         (1024)
+#define INI_INVALID_KEY     ((char*)-1)
+
+/*---------------------------------------------------------------------------
+                        Private to this module
+ ---------------------------------------------------------------------------*/
+/**
+ * This enum stores the status for each parsed line (internal use only).
+ */
+typedef enum _line_status_ {
+    LINE_UNPROCESSED,
+    LINE_ERROR,
+    LINE_EMPTY,
+    LINE_COMMENT,
+    LINE_SECTION,
+    LINE_VALUE
+} line_status ;
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Remove blanks at the beginning and the end of a string.
+  @param       s       String to parse.
+  @return      ptr to statically allocated string.
+
+  This function returns a pointer to a statically allocated string,
+  which is identical to the input string, except that all blank
+  characters at the end and the beg. of the string have been removed.
+  Do not free or modify the returned string! Since the returned string
+  is statically allocated, it will be modified at each function call
+  (not re-entrant).
+ */
+/*--------------------------------------------------------------------------*/
+static char * strstrip(char * s)
+{
+    static char l[ASCIILINESZ+1];
+       char * last ;
+       
+    if (s==NULL) return NULL ;
+    
+       while (isspace((int)*s) && *s) s++;
+       memset(l, 0, ASCIILINESZ+1);
+       strcpy(l, s);
+       last = l + strlen(l);
+       while (last > l) {
+               if (!isspace((int)*(last-1)))
+                       break ;
+               last -- ;
+       }
+       *last = (char)0;
+       return (char*)l ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Get number of sections in a dictionary
+  @param    d   Dictionary to examine
+  @return   int Number of sections found in dictionary
+
+  This function returns the number of sections found in a dictionary.
+  The test to recognize sections is done on the string stored in the
+  dictionary: a section name is given as "section" whereas a key is
+  stored as "section:key", thus the test looks for entries that do not
+  contain a colon.
+
+  This clearly fails in the case a section name contains a colon, but
+  this should simply be avoided.
+
+  This function returns -1 in case of error.
+ */
+/*--------------------------------------------------------------------------*/
+int iniparser_getnsec(const dictionary * d)
+{
+    int i ;
+    int nsec ;
+
+    if (d==NULL) return -1 ;
+    nsec=0 ;
+    for (i=0 ; i<d->size ; i++) {
+        if (d->key[i]==NULL)
+            continue ;
+        if (strchr(d->key[i], ':')==NULL) {
+            nsec ++ ;
+        }
+    }
+    return nsec ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Get name for section n in a dictionary.
+  @param    d   Dictionary to examine
+  @param    n   Section number (from 0 to nsec-1).
+  @return   Pointer to char string
+
+  This function locates the n-th section in a dictionary and returns
+  its name as a pointer to a string statically allocated inside the
+  dictionary. Do not free or modify the returned string!
+
+  This function returns NULL in case of error.
+ */
+/*--------------------------------------------------------------------------*/
+const char * iniparser_getsecname(const dictionary * d, int n)
+{
+    int i ;
+    int foundsec ;
+
+    if (d==NULL || n<0) return NULL ;
+    foundsec=0 ;
+    for (i=0 ; i<d->size ; i++) {
+        if (d->key[i]==NULL)
+            continue ;
+        if (strchr(d->key[i], ':')==NULL) {
+            foundsec++ ;
+            if (foundsec>n)
+                break ;
+        }
+    }
+    if (foundsec<=n) {
+        return NULL ;
+    }
+    return d->key[i] ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Dump a dictionary to an opened file pointer.
+  @param    d   Dictionary to dump.
+  @param    f   Opened file pointer to dump to.
+  @return   void
+
+  This function prints out the contents of a dictionary, one element by
+  line, onto the provided file pointer. It is OK to specify @c stderr
+  or @c stdout as output files. This function is meant for debugging
+  purposes mostly.
+ */
+/*--------------------------------------------------------------------------*/
+void iniparser_dump(const dictionary * d, FILE * f)
+{
+    int     i ;
+
+    if (d==NULL || f==NULL) return ;
+    for (i=0 ; i<d->size ; i++) {
+        if (d->key[i]==NULL)
+            continue ;
+        if (d->val[i]!=NULL) {
+            fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]);
+        } else {
+            fprintf(f, "[%s]=UNDEF\n", d->key[i]);
+        }
+    }
+    return ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Save a dictionary to a loadable ini file
+  @param    d   Dictionary to dump
+  @param    f   Opened file pointer to dump to
+  @return   void
+
+  This function dumps a given dictionary into a loadable ini file.
+  It is Ok to specify @c stderr or @c stdout as output files.
+ */
+/*--------------------------------------------------------------------------*/
+void iniparser_dump_ini(const dictionary * d, FILE * f)
+{
+    int     i, j ;
+    char    keym[ASCIILINESZ+1];
+    int     nsec ;
+    const char *  secname ;
+    int     seclen ;
+
+    if (d==NULL || f==NULL) return ;
+
+    nsec = iniparser_getnsec(d);
+    if (nsec<1) {
+        /* No section in file: dump all keys as they are */
+        for (i=0 ; i<d->size ; i++) {
+            if (d->key[i]==NULL)
+                continue ;
+            fprintf(f, "%s = %s\n", d->key[i], d->val[i]);
+        }
+        return ;
+    }
+    for (i=0 ; i<nsec ; i++) {
+        secname = iniparser_getsecname(d, i) ;
+        seclen  = (int)strlen(secname);
+        fprintf(f, "\n[%s]\n", secname);
+        sprintf(keym, "%s:", secname);
+        for (j=0 ; j<d->size ; j++) {
+            if (d->key[j]==NULL)
+                continue ;
+            if (!strncmp(d->key[j], keym, seclen+1)) {
+                fprintf(f,
+                        "%-30s = %s\n",
+                        d->key[j]+seclen+1,
+                        d->val[j] ? d->val[j] : "");
+            }
+        }
+    }
+    fprintf(f, "\n");
+    return ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Get the string associated to a key
+  @param    d       Dictionary to search
+  @param    section Section to search
+  @param    key     Key string to look for
+  @param    def     Default value to return if key not found.
+  @return   pointer to statically allocated character string
+
+  This function queries a dictionary for a key. A key as read from an
+  ini file is given as "section:key". If the key cannot be found,
+  the pointer passed as 'def' is returned.
+  The returned char pointer is pointing to a string allocated in
+  the dictionary, do not free or modify it.
+ */
+/*--------------------------------------------------------------------------*/
+const char * iniparser_getstring(const dictionary * d, const char *section, const char * key, const char * def)
+{
+    const char * sval ;
+
+    if (d==NULL || key==NULL)
+        return def ;
+
+    sval = dictionary_get(d, section, key, def);
+    return sval ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Get the string associated to a key
+  @param    d       Dictionary to search
+  @param    section Section to search
+  @param    key     Key string to look for
+  @param    def     Default value to return if key not found.
+  @return   pointer to statically allocated character string
+
+  This function queries a dictionary for a key. A key as read from an
+  ini file is given as "section:key". If the key cannot be found,
+  the pointer passed as 'def' is returned.
+  The returned char pointer a strdup'ed allocated string, so the caller must free it.
+ */
+/*--------------------------------------------------------------------------*/
+char * iniparser_getstrdup(const dictionary * d, const char *section, const char * key, const char * def)
+{
+    const char * sval ;
+
+    if (d==NULL || key==NULL)
+        return NULL;
+
+    if ((sval = dictionary_get(d, section, key, def)))
+        return strdup(sval);
+    return NULL;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Get the string associated to a key, convert to an int
+  @param    d        Dictionary to search
+  @param    section  Section to search
+  @param    key      Key string to look for
+  @param    notfound Value to return in case of error
+  @return   integer
+
+  This function queries a dictionary for a key. A key as read from an
+  ini file is given as "section:key". If the key cannot be found,
+  the notfound value is returned.
+
+  Supported values for integers include the usual C notation
+  so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
+  are supported. Examples:
+
+  "42"      ->  42
+  "042"     ->  34 (octal -> decimal)
+  "0x42"    ->  66 (hexa  -> decimal)
+
+  Warning: the conversion may overflow in various ways. Conversion is
+  totally outsourced to strtol(), see the associated man page for overflow
+  handling.
+
+  Credits: Thanks to A. Becker for suggesting strtol()
+ */
+/*--------------------------------------------------------------------------*/
+int iniparser_getint(const dictionary * d, const char *section, const char * key, int notfound)
+{
+    const char    *   str ;
+
+    str = iniparser_getstring(d, section, key, INI_INVALID_KEY);
+    if (str==INI_INVALID_KEY) return notfound ;
+    return (int)strtol(str, NULL, 0);
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Get the string associated to a key, convert to a double
+  @param    d        Dictionary to search
+  @param    section  Section to search
+  @param    key      Key string to look for
+  @param    notfound Value to return in case of error
+  @return   double
+
+  This function queries a dictionary for a key. A key as read from an
+  ini file is given as "section:key". If the key cannot be found,
+  the notfound value is returned.
+ */
+/*--------------------------------------------------------------------------*/
+double iniparser_getdouble(const dictionary * d, const char *section, const char * key, double notfound)
+{
+    const char    *   str ;
+
+    str = iniparser_getstring(d, section, key, INI_INVALID_KEY);
+    if (str==INI_INVALID_KEY) return notfound ;
+    return atof(str);
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Get the string associated to a key, convert to a boolean
+  @param    d        Dictionary to search
+  @param    section  Section to search
+  @param    key      Key string to look for
+  @param    notfound Value to return in case of error
+  @return   integer
+
+  This function queries a dictionary for a key. A key as read from an
+  ini file is given as "section:key". If the key cannot be found,
+  the notfound value is returned.
+
+  A true boolean is found if one of the following is matched:
+
+  - A string starting with 'y'
+  - A string starting with 'Y'
+  - A string starting with 't'
+  - A string starting with 'T'
+  - A string starting with '1'
+
+  A false boolean is found if one of the following is matched:
+
+  - A string starting with 'n'
+  - A string starting with 'N'
+  - A string starting with 'f'
+  - A string starting with 'F'
+  - A string starting with '0'
+
+  The notfound value returned if no boolean is identified, does not
+  necessarily have to be 0 or 1.
+ */
+/*--------------------------------------------------------------------------*/
+int iniparser_getboolean(const dictionary * d, const char *section, const char * key, int notfound)
+{
+    const char    *   c ;
+    int         ret ;
+
+    c = iniparser_getstring(d, section, key, INI_INVALID_KEY);
+    if (c==INI_INVALID_KEY) return notfound ;
+    if (c[0]=='y' || c[0]=='Y' || c[0]=='1' || c[0]=='t' || c[0]=='T') {
+        ret = 1 ;
+    } else if (c[0]=='n' || c[0]=='N' || c[0]=='0' || c[0]=='f' || c[0]=='F') {
+        ret = 0 ;
+    } else {
+        ret = notfound ;
+    }
+    return ret;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Finds out if a given entry exists in a dictionary
+  @param    ini     Dictionary to search
+  @param    entry   Name of the entry to look for
+  @return   integer 1 if entry exists, 0 otherwise
+
+  Finds out if a given entry exists in the dictionary. Since sections
+  are stored as keys with NULL associated values, this is the only way
+  of querying for the presence of sections in a dictionary.
+ */
+/*--------------------------------------------------------------------------*/
+int iniparser_find_entry(const dictionary *ini, const char *entry)
+{
+    int found=0 ;
+    if (iniparser_getstring(ini, entry, NULL, INI_INVALID_KEY)!=INI_INVALID_KEY) {
+        found = 1 ;
+    }
+    return found ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Set an entry in a dictionary.
+  @param    ini     Dictionary to modify.
+  @param    section Entry to modify (entry section)
+  @param    key     Entry to modify (entry key)
+  @param    val     New value to associate to the entry.
+  @return   int 0 if Ok, -1 otherwise.
+
+  If the given entry can be found in the dictionary, it is modified to
+  contain the provided value. If it cannot be found, -1 is returned.
+  It is Ok to set val to NULL.
+ */
+/*--------------------------------------------------------------------------*/
+int iniparser_set(dictionary * ini, char *section, char * key, char * val)
+{
+    return dictionary_set(ini, section, key, val) ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Delete an entry in a dictionary
+  @param    ini     Dictionary to modify
+  @param    section Entry to delete (entry section)
+  @param    key     Entry to delete (entry key)
+  @return   void
+
+  If the given entry can be found, it is deleted from the dictionary.
+ */
+/*--------------------------------------------------------------------------*/
+void iniparser_unset(dictionary * ini, char *section, char * key)
+{
+    dictionary_unset(ini, section, key);
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief       Load a single line from an INI file
+  @param    input_line  Input line, may be concatenated multi-line input
+  @param    section     Output space to store section
+  @param    key         Output space to store key
+  @param    value       Output space to store value
+  @return   line_status value
+ */
+/*--------------------------------------------------------------------------*/
+static line_status iniparser_line(
+    char * input_line,
+    char * section,
+    char * key,
+    char * value)
+{   
+    line_status sta ;
+    char        line[ASCIILINESZ+1];
+    int         len ;
+
+    strcpy(line, strstrip(input_line));
+    len = (int)strlen(line);
+
+    sta = LINE_UNPROCESSED ;
+    if (len<1) {
+        /* Empty line */
+        sta = LINE_EMPTY ;
+    } else if (line[0]=='#' || line[0]==';') {
+        /* Comment line */
+        sta = LINE_COMMENT ; 
+    } else if (line[0]=='[' && line[len-1]==']') {
+        /* Section name */
+        sscanf(line, "[%[^]]", section);
+        strcpy(section, strstrip(section));
+        strcpy(section, section);
+        sta = LINE_SECTION ;
+    } else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2
+           ||  sscanf (line, "%[^=] = '%[^\']'",   key, value) == 2
+           ||  sscanf (line, "%[^=] = %[^;#]",     key, value) == 2) {
+        /* Usual key=value, with or without comments */
+        strcpy(key, strstrip(key));
+        strcpy(key, key);
+        strcpy(value, strstrip(value));
+        /*
+         * sscanf cannot handle '' or "" as empty values
+         * this is done here
+         */
+        if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) {
+            value[0]=0 ;
+        }
+        sta = LINE_VALUE ;
+    } else if (sscanf(line, "%[^=] = %[;#]", key, value)==2
+           ||  sscanf(line, "%[^=] %[=]", key, value) == 2) {
+        /*
+         * Special cases:
+         * key=
+         * key=;
+         * key=#
+         */
+        strcpy(key, strstrip(key));
+        strcpy(key, key);
+        value[0]=0 ;
+        sta = LINE_VALUE ;
+    } else {
+        /* Generate syntax error */
+        sta = LINE_ERROR ;
+    }
+    return sta ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Parse an ini file and return an allocated dictionary object
+  @param    ininame Name of the ini file to read.
+  @return   Pointer to newly allocated dictionary
+
+  This is the parser for ini files. This function is called, providing
+  the name of the file to be read. It returns a dictionary object that
+  should not be accessed directly, but through accessor functions
+  instead.
+
+  The returned dictionary must be freed using iniparser_freedict().
+ */
+/*--------------------------------------------------------------------------*/
+dictionary * iniparser_load(const char * ininame)
+{
+    FILE *in, *include = NULL, *inifile;
+
+    char line    [ASCIILINESZ+1] ;
+    char section [ASCIILINESZ+1] ;
+    char key     [ASCIILINESZ+1] ;
+    char tmp     [ASCIILINESZ+1] ;
+    char val     [ASCIILINESZ+1] ;
+
+    int  last=0 ;
+    int  len ;
+    int  lineno=0 ;
+    int  errs=0;
+
+    dictionary * dict ;
+
+    if ((inifile=fopen(ininame, "r"))==NULL) {
+        LOG(logtype_default, log_error, "iniparser: cannot open \"%s\"", ininame);
+        return NULL ;
+    }
+
+    dict = dictionary_new(0) ;
+    if (!dict) {
+        fclose(inifile);
+        return NULL ;
+    }
+
+    memset(line,    0, ASCIILINESZ);
+    memset(section, 0, ASCIILINESZ);
+    memset(key,     0, ASCIILINESZ);
+    memset(val,     0, ASCIILINESZ);
+    last=0 ;
+
+    in = inifile;
+    while (1) {
+        if (fgets(line+last, ASCIILINESZ-last, in) == NULL) {
+            if (include) {
+                fclose(include);
+                include = NULL;
+                in = inifile;
+                continue;
+            }
+            break;
+        }
+        lineno++ ;
+        len = (int)strlen(line)-1;
+        if (len==0)
+            continue;
+        /* Safety check against buffer overflows */
+        if (line[len]!='\n') {
+            LOG(logtype_default, log_error, "iniparser: input line too long in \"%s\" (lineno: %d)",
+                ininame, lineno);
+            dictionary_del(dict);
+            fclose(in);
+            return NULL ;
+        }
+        /* Get rid of \n and spaces at end of line */
+        while ((len>=0) &&
+                ((line[len]=='\n') || (isspace(line[len])))) {
+            line[len]=0 ;
+            len-- ;
+        }
+        /* Detect multi-line */
+        if (line[len]=='\\') {
+            /* Multi-line value */
+            last=len ;
+            continue ;
+        } else {
+            last=0 ;
+        }
+        switch (iniparser_line(line, section, key, val)) {
+        case LINE_EMPTY:
+        case LINE_COMMENT:
+            break ;
+        case LINE_SECTION:
+            errs = dictionary_set(dict, section, NULL, NULL);
+            break ;
+        case LINE_VALUE:
+            if (strcmp(key, "include") == 0) {
+                if ((include = fopen(val, "r")) == NULL) {
+                    LOG(logtype_default, log_error, "iniparser: cannot open \"%s\"", val);
+                    continue;
+                }
+                in = include;
+                continue;
+            }
+            errs = dictionary_set(dict, section, key, val) ;
+            break ;
+        case LINE_ERROR:
+            LOG(logtype_default, log_error, "iniparser: syntax error in %s (lineno: %d): %s",
+                ininame, lineno, line);
+            errs++ ;
+            break;
+        default:
+            break ;
+        }
+        memset(line, 0, ASCIILINESZ);
+        last=0;
+        if (errs<0) {
+            LOG(logtype_default, log_error, "iniparser: memory allocation failure");
+            break ;
+        }
+    }
+    if (errs) {
+        dictionary_del(dict);
+        dict = NULL ;
+    }
+    fclose(in);
+    return dict ;
+}
+
+/*-------------------------------------------------------------------------*/
+/**
+  @brief    Free all memory associated to an ini dictionary
+  @param    d Dictionary to free
+  @return   void
+
+  Free all memory associated to an ini dictionary.
+  It is mandatory to call this function before the dictionary object
+  gets out of the current context.
+ */
+/*--------------------------------------------------------------------------*/
+void iniparser_freedict(dictionary * d)
+{
+    dictionary_del(d);
+}
+
diff --git a/libatalk/libatalk-3.0beta1.abi b/libatalk/libatalk-3.0beta1.abi
new file mode 100644 (file)
index 0000000..f87258d
--- /dev/null
@@ -0,0 +1,550 @@
+acl_ldap_readconfig: int (dictionary *)
+ad_close: int (struct adouble *, int)
+ad_convert: int (const char *, const struct stat *, const struct vol *, const char **)
+ad_copy_header: int (struct adouble *, struct adouble *)
+add_cachebyname: int (const char *, const uuidp_t, const uuidtype_t, const long unsigned int)
+add_cachebyuuid: int (uuidp_t, const char *, uuidtype_t, const long unsigned int)
+add_charset: charset_t (const char *)
+ad_dir: char *(const char *)
+ad_dtruncate: int (struct adouble *, const off_t)
+adflags2logstr: const char *(int)
+ad_flush: int (struct adouble *)
+ad_forcegetid: uint32_t (struct adouble *)
+adf_pread: ssize_t (struct ad_fd *, void *, size_t, off_t)
+adf_pwrite: ssize_t (struct ad_fd *, const void *, size_t, off_t)
+ad_getattr: int (const struct adouble *, uint16_t *)
+ad_getdate: int (const struct adouble *, unsigned int, uint32_t *)
+ad_getentryoff: off_t (const struct adouble *, int)
+ad_getfuid: uid_t (void)
+ad_getid: uint32_t (struct adouble *, const dev_t, const ino_t, const cnid_t, const void *)
+ad_hf_mode: mode_t (mode_t)
+ad_init: void (struct adouble *, const struct vol *)
+ad_init_old: void (struct adouble *, int, int)
+ad_lock: int (struct adouble *, uint32_t, int, off_t, off_t, int)
+ad_metadata: int (const char *, int, struct adouble *)
+ad_metadataat: int (int, const char *, int, struct adouble *)
+ad_mkdir: int (const char *, mode_t)
+ad_mode: int (const char *, mode_t)
+ad_open: int (struct adouble *, const char *, int, ...)
+ad_openat: int (struct adouble *, int, const char *, int, ...)
+ad_openforks: uint16_t (struct adouble *, uint16_t)
+ad_path: const char *(const char *, int)
+ad_path_ea: const char *(const char *, int)
+ad_path_osx: const char *(const char *, int)
+ad_read: ssize_t (struct adouble *, const uint32_t, off_t, char *, const size_t)
+ad_readfile_init: int (const struct adouble *, const int, off_t *, const int)
+ad_rebuild_adouble_header_ea: int (struct adouble *)
+ad_rebuild_adouble_header_v2: int (struct adouble *)
+ad_refresh: int (const char *, struct adouble *)
+ad_rtruncate: int (struct adouble *, const off_t)
+ad_setattr: int (const struct adouble *, const uint16_t)
+ad_setdate: int (struct adouble *, unsigned int, uint32_t)
+ad_setfuid: int (const uid_t)
+ad_setid: int (struct adouble *, const dev_t, const ino_t, const uint32_t, const cnid_t, const void *)
+ad_setname: int (struct adouble *, const char *)
+ad_size: off_t (const struct adouble *, const uint32_t)
+ad_stat: int (const char *, struct stat *)
+ad_testlock: int (struct adouble *, int, const off_t)
+ad_tmplock: int (struct adouble *, uint32_t, int, off_t, off_t, int)
+ad_unlock: void (struct adouble *, const int, int)
+ad_valid_header_osx: int (const char *)
+ad_write: ssize_t (struct adouble *, uint32_t, off_t, int, const char *, size_t)
+afp_config_parse: int (AFPObj *, char *)
+allow_severity: 5
+apply_ip_mask: void (struct sockaddr *, int)
+atalk_iconv: size_t (atalk_iconv_t, const char **, size_t *, char **, size_t *)
+atalk_iconv_close: int (atalk_iconv_t)
+atalk_iconv_open: atalk_iconv_t (const char *, const char *)
+atalk_register_charset: int (struct charset_functions *)
+balloc: int (bstring, int)
+ballocmin: int (bstring, int)
+bassign: int (bstring, const_bstring)
+bassignblk: int (bstring, const void *, int)
+bassigncstr: int (bstring, const char *)
+bassignformat: int (bstring, const char *, ...)
+bassigngets: int (bstring, bNgetc, void *, char)
+bassignmidstr: int (bstring, const_bstring, int, int)
+bcatblk: int (bstring, const void *, int)
+bcatcstr: int (bstring, const char *)
+bconcat: int (bstring, const_bstring)
+bconchar: int (bstring, char)
+bcstrfree: int (char *)
+bdelete: int (bstring, int, int)
+bdestroy: int (bstring)
+become_root: void (void)
+bfindreplace: int (bstring, const_bstring, const_bstring, int)
+bfindreplacecaseless: int (bstring, const_bstring, const_bstring, int)
+bformat: bstring (const char *, ...)
+bformata: int (bstring, const char *, ...)
+bfromcstr: bstring (const char *)
+bfromcstralloc: bstring (int, const char *)
+bgetsa: int (bstring, bNgetc, void *, char)
+bgetstream: bstring (bNgetc, void *, char)
+binchr: int (const_bstring, int, const_bstring)
+binchrr: int (const_bstring, int, const_bstring)
+binsert: int (bstring, int, const_bstring, unsigned char)
+binsertch: int (bstring, int, int, unsigned char)
+binstr: int (const_bstring, int, const_bstring)
+binstrcaseless: int (const_bstring, int, const_bstring)
+binstrr: int (const_bstring, int, const_bstring)
+binstrrcaseless: int (const_bstring, int, const_bstring)
+biseq: int (const_bstring, const_bstring)
+biseqcaseless: int (const_bstring, const_bstring)
+biseqcstr: int (const_bstring, const char *)
+biseqcstrcaseless: int (const_bstring, const char *)
+bisstemeqblk: int (const_bstring, const void *, int)
+bisstemeqcaselessblk: int (const_bstring, const void *, int)
+bjoin: bstring (const struct bstrList *, const_bstring)
+bjoinInv: bstring (const struct bstrList *, const_bstring)
+blk2bstr: bstring (const void *, int)
+bltrimws: int (bstring)
+bmidstr: bstring (const_bstring, int, int)
+bninchr: int (const_bstring, int, const_bstring)
+bninchrr: int (const_bstring, int, const_bstring)
+bpattern: int (bstring, int)
+bread: bstring (bNread, void *)
+breada: int (bstring, bNread, void *)
+brefcstr: bstring (char *)
+breplace: int (bstring, int, int, const_bstring, unsigned char)
+brtrimws: int (bstring)
+bsbufflength: int (struct bStream *, int)
+bsclose: void *(struct bStream *)
+bseof: int (const struct bStream *)
+bsetstr: int (bstring, int, const_bstring, unsigned char)
+bsopen: struct bStream *(bNread, void *)
+bspeek: int (bstring, const struct bStream *)
+bsplit: struct bstrList *(const_bstring, unsigned char)
+bsplitcb: int (const_bstring, unsigned char, int, int (*)(void *, int, int), void *)
+bsplits: struct bstrList *(const_bstring, const_bstring)
+bsplitscb: int (const_bstring, const_bstring, int, int (*)(void *, int, int), void *)
+bsplitstr: struct bstrList *(const_bstring, const_bstring)
+bsplitstrcb: int (const_bstring, const_bstring, int, int (*)(void *, int, int), void *)
+bsread: int (bstring, struct bStream *, int)
+bsreada: int (bstring, struct bStream *, int)
+bsreadln: int (bstring, struct bStream *, char)
+bsreadlna: int (bstring, struct bStream *, char)
+bsreadlns: int (bstring, struct bStream *, const_bstring)
+bsreadlnsa: int (bstring, struct bStream *, const_bstring)
+bssplitscb: int (struct bStream *, const_bstring, int (*)(void *, int, const_bstring), void *)
+bssplitstrcb: int (struct bStream *, const_bstring, int (*)(void *, int, const_bstring), void *)
+bstr2cstr: char *(const_bstring, char)
+bstrchrp: int (const_bstring, int, int)
+bstrcmp: int (const_bstring, const_bstring)
+bstrcpy: bstring (const_bstring)
+bstricmp: int (const_bstring, const_bstring)
+bstrListAlloc: int (struct bstrList *, int)
+bstrListAllocMin: int (struct bstrList *, int)
+bstrListCreate: struct bstrList *(void)
+bstrListCreateMin: struct bstrList *(int)
+bstrListDestroy: int (struct bstrList *)
+bstrListPop: bstring (struct bstrList *)
+bstrListPush: int (struct bstrList *, bstring)
+bstrncmp: int (const_bstring, const_bstring, int)
+bstrnicmp: int (const_bstring, const_bstring, int)
+bstrrchrp: int (const_bstring, int, int)
+bsunread: int (struct bStream *, const_bstring)
+btolower: int (bstring)
+btoupper: int (bstring)
+btrimws: int (bstring)
+btrunc: int (bstring, int)
+bunrefcstr: int (bstring)
+bvcformata: int (bstring, int, const char *, struct __va_list_tag *)
+charset_decompose: size_t (charset_t, char *, size_t, char *, size_t)
+charset_mac_centraleurope: {name = "MAC_CENTRALEUROPE", kTextEncoding = 29, pull = <mac_centraleurope_pull>, push = <mac_centraleurope_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_chinese_simp: {name = "MAC_CHINESE_SIMP", kTextEncoding = 25, pull = <mac_chinese_simp_pull>, push = <mac_chinese_simp_push>, flags = 85, iname = "EUC-CN", prev = 0x0, next = 0x0}
+charset_mac_chinese_trad: {name = "MAC_CHINESE_TRAD", kTextEncoding = 2, pull = <mac_chinese_trad_pull>, push = <mac_chinese_trad_push>, flags = 85, iname = "BIG-5", prev = 0x0, next = 0x0}
+charset_mac_cyrillic: {name = "MAC_CYRILLIC", kTextEncoding = 7, pull = <mac_cyrillic_pull>, push = <mac_cyrillic_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_greek: {name = "MAC_GREEK", kTextEncoding = 6, pull = <mac_greek_pull>, push = <mac_greek_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_hebrew: {name = "MAC_HEBREW", kTextEncoding = 5, pull = <mac_hebrew_pull>, push = <mac_hebrew_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_japanese: {name = "MAC_JAPANESE", kTextEncoding = 1, pull = <mac_japanese_pull>, push = <mac_japanese_push>, flags = 85, iname = "SHIFT_JIS", prev = 0x0, next = 0x0}
+charset_mac_korean: {name = "MAC_KOREAN", kTextEncoding = 3, pull = <mac_korean_pull>, push = <mac_korean_push>, flags = 85, iname = "EUC-KR", prev = 0x0, next = 0x0}
+charset_mac_roman: {name = "MAC_ROMAN", kTextEncoding = 0, pull = <mac_roman_pull>, push = <mac_roman_push>, flags = 21, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_turkish: {name = "MAC_TURKISH", kTextEncoding = 35, pull = <mac_turkish_pull>, push = <mac_turkish_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_names: 
+charset_precompose: size_t (charset_t, char *, size_t, char *, size_t)
+charset_strlower: size_t (charset_t, const char *, size_t, char *, size_t)
+charset_strupper: size_t (charset_t, const char *, size_t, char *, size_t)
+charset_to_ucs2_allocate: size_t (charset_t, uint16_t **, const char *)
+charset_to_utf8_allocate: size_t (charset_t, char **, const char *)
+charset_utf8: {name = "UTF8", kTextEncoding = 134217987, pull = <utf8_pull>, push = <utf8_push>, flags = 22, iname = 0x0, prev = 0x0, next = 0x0}
+charset_utf8_mac: {name = "UTF8-MAC", kTextEncoding = 134217987, pull = <utf8_pull>, push = <utf8_push>, flags = 27, iname = 0x0, prev = 0x0, next = 0x0}
+check_lockfile: int (const char *, const char *)
+cjk_char_pull: size_t (uint16_t, uint16_t *, const uint32_t *)
+cjk_char_push: size_t (uint16_t, uint8_t *)
+cjk_compose: uint16_t (uint16_t, uint16_t, const uint32_t *, size_t)
+cjk_compose_seq: uint16_t (const uint16_t *, size_t *, const uint32_t *, size_t)
+cjk_generic_pull: size_t (size_t (*)(uint16_t *, const uint8_t *, size_t *), void *, char **, size_t *, char **, size_t *)
+cjk_generic_push: size_t (size_t (*)(uint8_t *, const uint16_t *, size_t *), void *, char **, size_t *, char **, size_t *)
+cjk_lookup: uint16_t (uint16_t, const cjk_index_t *, const uint16_t *)
+cnid_add: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, const char *, const size_t, cnid_t)
+cnid_close: void (struct _cnid_db *)
+cnid_dbd_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_dbd_close: void (struct _cnid_db *)
+cnid_dbd_delete: int (struct _cnid_db *, const cnid_t)
+cnid_dbd_find: int (struct _cnid_db *, const char *, size_t, void *, size_t)
+cnid_dbd_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_dbd_getstamp: int (struct _cnid_db *, void *, const size_t)
+cnid_dbd_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_dbd_module: {name = "dbd", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 0}
+cnid_dbd_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_dbd_rebuild_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_dbd_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_dbd_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_delete: int (struct _cnid_db *, cnid_t)
+cnid_find: int (struct _cnid_db *, const char *, size_t, void *, size_t)
+cnid_get: cnid_t (struct _cnid_db *, const cnid_t, char *, const size_t)
+cnid_getstamp: int (struct _cnid_db *, void *, const size_t)
+cnid_init: void (void)
+cnid_last_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_last_close: void (struct _cnid_db *)
+cnid_last_delete: int (struct _cnid_db *, const cnid_t)
+cnid_last_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_last_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_last_module: {name = "last", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 0}
+cnid_last_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_last_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_last_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_lookup: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, char *, const size_t)
+cnid_open: struct _cnid_db *(const char *, mode_t, char *, int, const char *, const char *)
+cnid_rebuild_add: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, char *, const size_t, cnid_t)
+cnid_register: void (struct _cnid_module *)
+cnid_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_tdb_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_tdb_close: void (struct _cnid_db *)
+cnid_tdb_delete: int (struct _cnid_db *, const cnid_t)
+cnid_tdb_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_tdb_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_tdb_module: {name = "tdb", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 12}
+cnid_tdb_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_tdb_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_tdb_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_update: int (struct _cnid_db *, const cnid_t, const struct stat *, const cnid_t, char *, const size_t)
+compare_ip: int (const struct sockaddr *, const struct sockaddr *)
+convert_charset: size_t (charset_t, charset_t, charset_t, const char *, size_t, char *, size_t, uint16_t *)
+convert_string: size_t (charset_t, charset_t, const void *, size_t, void *, size_t)
+convert_string_allocate: size_t (charset_t, charset_t, const void *, size_t, char **)
+copy_ea: int (const char *, int, const char *, const char *, mode_t)
+copy_file: int (int, const char *, const char *, mode_t)
+copy_file_fd: int (int, int)
+copy_fork: int (int, struct adouble *, struct adouble *)
+create_lockfile: int (const char *, const char *)
+daemonize: int (int, int)
+decompose_w: size_t (uint16_t *, size_t, uint16_t *, size_t *)
+deny_severity: 3
+dequeue: void *(q_t *)
+_diacasemap: {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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 231, 203, 229, 128, 204, 129, 130, 131, 233, 230, 232, 234, 237, 235, 236, 132, 238, 241, 239, 133, 205, 242, 244, 243, 134, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 198, 183, 184, 184, 186, 187, 188, 189, 174, 175, 192, 193, 194, 195, 196, 197, 198, 199...}
+_dialowermap: {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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 138, 140, 141, 142, 150, 154, 159, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 132, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 190, 191, 176, 177, 178, 179, 180, 181, 198, 183, 185, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199...}
+dictionary_del: void (dictionary *)
+dictionary_dump: void (dictionary *, FILE *)
+dictionary_get: const char *(const dictionary *, const char *, const char *, const char *)
+dictionary_hash: unsigned int (char *)
+dictionary_new: dictionary *(int)
+dictionary_set: int (dictionary *, char *, char *, char *)
+dictionary_unset: void (dictionary *, char *, char *)
+dir_rx_set: int (mode_t)
+dsi_attention: int (DSI *, AFPUserBytes)
+dsi_close: void (DSI *)
+dsi_cmdreply: int (DSI *, const int)
+dsi_disconnect: int (DSI *)
+dsi_getsession: int (DSI *, server_child *, int, afp_child_t **)
+dsi_getstatus: void (DSI *)
+dsi_init: DSI *(AFPObj *, const char *, const char *, const char *)
+dsi_opensession: void (DSI *)
+dsi_read: ssize_t (DSI *, void *, const size_t)
+dsi_readdone: void (DSI *)
+dsi_readinit: ssize_t (DSI *, void *, const size_t, const size_t, const int)
+dsi_stream_read: size_t (DSI *, void *, const size_t)
+dsi_stream_read_file: ssize_t (DSI *, const int, off_t, const size_t, const int)
+dsi_stream_receive: int (DSI *)
+dsi_stream_send: int (DSI *, void *, size_t)
+dsi_stream_write: ssize_t (DSI *, void *, const size_t, int)
+dsi_tcp_init: int (DSI *, const char *, const char *, const char *)
+dsi_tickle: int (DSI *)
+dsi_write: size_t (DSI *, void *, const size_t)
+dsi_writeflush: void (DSI *)
+dsi_writeinit: size_t (DSI *, void *, const size_t)
+ea_chmod_dir: int (const struct vol *, const char *, mode_t, struct stat *)
+ea_chmod_file: int (const struct vol *, const char *, mode_t, struct stat *)
+ea_chown: int (const struct vol *, const char *, uid_t, gid_t)
+ea_close: int (struct ea *)
+ea_copyfile: int (const struct vol *, int, const char *, const char *)
+ea_deletefile: int (const struct vol *, int, const char *)
+ea_open: int (const struct vol *, const char *, eaflags_t, struct ea *)
+ea_openat: int (const struct vol *, int, const char *, eaflags_t, struct ea *)
+ea_path: char *(const struct ea *, const char *, int)
+ea_renamefile: int (const struct vol *, int, const char *, const char *)
+enqueue: qnode_t *(q_t *, void *)
+fault_setup: void (void (*)(void *))
+fdset_add_fd: void (int, struct pollfd **, struct polldata **, int *, int *, int, enum fdtype, void *)
+fdset_del_fd: void (struct pollfd **, struct polldata **, int *, int *, int)
+find_charset_functions: struct charset_functions *(const char *)
+_fini: <text variable, no debug info>
+freeifacelist: void (char **)
+fullpathname: const char *(const char *)
+getcwdpath: const char *(void)
+get_eacontent: int (const struct vol *, char *, size_t *, const char *, int, const char *, int)
+get_easize: int (const struct vol *, char *, size_t *, const char *, int, const char *)
+getifacelist: char **(void)
+getip_port: unsigned int (const struct sockaddr *)
+getip_string: const char *(const struct sockaddr *)
+getnamefromuuid: int (const uuidp_t, char **, uuidtype_t *)
+getuuidfromname: int (const char *, uuidtype_t, unsigned char *)
+getvolbyname: struct vol *(const char *)
+getvolbypath: struct vol *(AFPObj *, const char *)
+getvolbyvid: struct vol *(const uint16_t)
+getvolumes: struct vol *(void)
+gmem: int (gid_t, int, gid_t *)
+iniparser_dump: void (const dictionary *, FILE *)
+iniparser_dump_ini: void (const dictionary *, FILE *)
+iniparser_find_entry: int (const dictionary *, const char *)
+iniparser_freedict: void (dictionary *)
+iniparser_getboolean: int (const dictionary *, const char *, const char *, int)
+iniparser_getdouble: double (const dictionary *, const char *, const char *, double)
+iniparser_getint: int (const dictionary *, const char *, const char *, int)
+iniparser_getnsec: int (const dictionary *)
+iniparser_getsecname: const char *(const dictionary *, int)
+iniparser_getstrdup: char *(const dictionary *, const char *, const char *, const char *)
+iniparser_getstring: const char *(const dictionary *, const char *, const char *, const char *)
+iniparser_load: dictionary *(const char *)
+iniparser_set: int (dictionary *, char *, char *, char *)
+iniparser_unset: void (dictionary *, char *, char *)
+_init: <text variable, no debug info>
+init_iconv: void (void)
+initvol_vfs: void (struct vol *)
+ipc_child_write: int (int, uint16_t, int, void *)
+ipc_client_uds: int (const char *)
+ipc_server_read: int (server_child *, int)
+ipc_server_uds: int (const char *)
+islower_sp: int (uint32_t)
+islower_w: int (uint16_t)
+isupper_sp: int (uint32_t)
+isupper_w: int (uint16_t)
+lchdir: int (const char *)
+ldap_auth_dn: 0x0
+ldap_auth_method: 0
+ldap_auth_pw: 0x0
+ldap_config_valid: 0
+ldap_getnamefromuuid: int (const char *, char **, uuidtype_t *)
+ldap_getuuidfromname: int (const char *, uuidtype_t, char **)
+ldap_group_attr: 0x0
+ldap_groupbase: 0x0
+ldap_groupscope: 0
+ldap_name_attr: 0x0
+ldap_prefs: {{pref = 0x0, name = "ldap server", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap auth method", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap auth dn", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap auth pw", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap userbase", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap userscope", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap groupbase", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap groupscope", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap uuid attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap uuid string", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap name attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap group attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap uid attr", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = 0x0, strorint = 0, intfromarray = 0, valid = -1}}
+ldap_server: 0x0
+ldap_uid_attr: 0x0
+ldap_userbase: 0x0
+ldap_userscope: 0
+ldap_uuid_attr: 0x0
+ldap_uuid_string: 0x0
+list_eas: int (const struct vol *, char *, size_t *, const char *, int)
+load_charset: int (struct vol *)
+load_volumes: int (AFPObj *, void (*)(const AFPObj *, struct vol *))
+localuuid_from_id: void (unsigned char *, uuidtype_t, unsigned int)
+lock_reg: int (int, int, int, off_t, int, off_t)
+log_config: {inited = false, syslog_opened = false, console = false, processname = '\0' <repeats 15 times>, syslog_facility = 0, syslog_display_options = 0}
+lstatat: int (int, const char *, struct stat *)
+make_log_entry: void (enum loglevels, enum logtypes, const char *, int, char *, ...)
+make_tdb_data: unsigned char *(uint32_t, const struct stat *, const cnid_t, const char *, const size_t)
+mb_generic_pull: size_t (int (*)(uint16_t *, const unsigned char *), void *, char **, size_t *, char **, size_t *)
+mb_generic_push: size_t (int (*)(unsigned char *, uint16_t), void *, char **, size_t *, char **, size_t *)
+namecache: {<repeats 256 times>}
+netatalk_panic: void (const char *)
+netatalk_rmdir: int (int, const char *)
+netatalk_rmdir_all_errors: int (int, const char *)
+netatalk_unlink: int (const char *)
+netatalk_unlinkat: int (int, const char *)
+nftw: int (const char *, nftw_func_t, dir_notification_func_t, int, int)
+opendirat: DIR *(int, const char *)
+openflags2logstr: const char *(int)
+posix_chmod: int (const char *, mode_t)
+posix_fchmod: int (int, mode_t)
+precompose_w: size_t (uint16_t *, size_t, uint16_t *, size_t *)
+prefs_array: {{pref = "ldap auth method", valuestring = "none", value = 0}, {pref = "ldap auth method", valuestring = "simple", value = 128}, {pref = "ldap auth method", valuestring = "sasl", value = 163}, {pref = "ldap userscope", valuestring = "base", value = 0}, {pref = "ldap userscope", valuestring = "one", value = 1}, {pref = "ldap userscope", valuestring = "sub", value = 2}, {pref = "ldap groupscope", valuestring = "base", value = 0}, {pref = "ldap groupscope", valuestring = "one", value = 1}, {pref = "ldap groupscope", valuestring = "sub", value = 2}, {pref = 0x0, valuestring = 0x0, value = 0}}
+prequeue: qnode_t *(q_t *, void *)
+queue_destroy: void (q_t *, void (*)(void *))
+queue_init: q_t *(void)
+randombytes: void (void *, int)
+readt: ssize_t (int, void *, const size_t, int, int)
+reconnect_ipc: int (AFPObj *)
+recv_fd: int (int, int)
+rel_path_in_vol: bstring (const char *, const char *)
+remove_acl_vfs: int (const char *)
+remove_ea: int (const struct vol *, const char *, const char *, int)
+run_cmd: int (const char *, char **)
+search_cachebyname: int (const char *, uuidtype_t *, unsigned char *)
+search_cachebyuuid: int (uuidp_t, char **, uuidtype_t *)
+send_fd: int (int, int)
+server_child_add: afp_child_t *(server_child *, int, pid_t, int)
+server_child_alloc: server_child *(const int, const int)
+server_child_free: void (server_child *)
+server_child_kill: void (server_child *, int, int)
+server_child_kill_one_by_id: void (server_child *, int, pid_t, uid_t, uint32_t, char *, uint32_t)
+server_child_remove: int (server_child *, const int, pid_t)
+server_child_setup: void (server_child *, const int, void (*)(const pid_t))
+server_child_transfer_session: int (server_child *, int, pid_t, uid_t, int, uint16_t)
+server_lock: pid_t (char *, char *, int)
+server_reset_signal: void (void)
+set_ea: int (const struct vol *, const char *, const char *, const char *, size_t, int)
+setfilmode: int (const char *, mode_t, struct stat *, mode_t)
+setnonblock: int (int, int)
+set_processname: void (const char *)
+setuplog: void (const char *, const char *)
+statat: int (int, const char *, struct stat *)
+strcasechr_sp: uint16_t *(const uint16_t *, uint32_t)
+strcasechr_w: uint16_t *(const uint16_t *, uint16_t)
+strcasecmp_w: int (const uint16_t *, const uint16_t *)
+strcasestr_w: uint16_t *(const uint16_t *, const uint16_t *)
+strcat_w: uint16_t *(uint16_t *, const uint16_t *)
+strchr_w: uint16_t *(const uint16_t *, uint16_t)
+strcmp_w: int (const uint16_t *, const uint16_t *)
+strdiacasecmp: int (const char *, const char *)
+strdup_w: uint16_t *(const uint16_t *)
+stripped_slashes_basename: char *(char *)
+strlcat: size_t (char *, const char *, size_t)
+strlcpy: size_t (char *, const char *, size_t)
+strlen_w: size_t (const uint16_t *)
+strlower_w: int (uint16_t *)
+strncasecmp_w: int (const uint16_t *, const uint16_t *, size_t)
+strncat_w: uint16_t *(uint16_t *, const uint16_t *, const size_t)
+strncmp_w: int (const uint16_t *, const uint16_t *, size_t)
+strncpy_w: uint16_t *(uint16_t *, const uint16_t *, const size_t)
+strndiacasecmp: int (const char *, const char *, size_t)
+strndup_w: uint16_t *(const uint16_t *, size_t)
+strnlen_w: size_t (const uint16_t *, size_t)
+strstr_w: uint16_t *(const uint16_t *, const uint16_t *)
+strupper_w: int (uint16_t *)
+sys_ea_copyfile: int (const struct vol *, int, const char *, const char *)
+sys_fgetxattr: ssize_t (int, const char *, void *, size_t)
+sys_fsetxattr: int (int, const char *, const void *, size_t, int)
+sys_ftruncate: int (int, off_t)
+sys_get_eacontent: int (const struct vol *, char *, size_t *, const char *, int, const char *, int)
+sys_get_easize: int (const struct vol *, char *, size_t *, const char *, int, const char *)
+sys_getxattr: ssize_t (const char *, const char *, void *, size_t)
+sys_getxattrfd: int (int, const char *, int, ...)
+sys_lgetxattr: ssize_t (const char *, const char *, void *, size_t)
+sys_list_eas: int (const struct vol *, char *, size_t *, const char *, int)
+sys_listxattr: ssize_t (const char *, char *, size_t)
+sys_llistxattr: ssize_t (const char *, char *, size_t)
+sys_lremovexattr: int (const char *, const char *)
+sys_lsetxattr: int (const char *, const char *, const void *, size_t, int)
+sys_remove_ea: int (const struct vol *, const char *, const char *, int)
+sys_removexattr: int (const char *, const char *)
+sys_sendfile: ssize_t (int, int, off_t *, size_t)
+sys_set_ea: int (const struct vol *, const char *, const char *, const char *, size_t, int)
+sys_setxattr: int (const char *, const char *, const void *, size_t, int)
+tdb_add_flags: void (struct tdb_context *, unsigned int)
+tdb_allocate: tdb_off_t (struct tdb_context *, tdb_len_t, struct tdb_record *)
+tdb_alloc_read: unsigned char *(struct tdb_context *, tdb_off_t, tdb_len_t)
+tdb_append: int (struct tdb_context *, TDB_DATA, TDB_DATA)
+tdb_brlock: int (struct tdb_context *, tdb_off_t, int, int, int, size_t)
+tdb_brlock_upgrade: int (struct tdb_context *, tdb_off_t, size_t)
+tdb_chainlock: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_mark: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_nonblock: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_read: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_unmark: int (struct tdb_context *, TDB_DATA)
+tdb_chainunlock: int (struct tdb_context *, TDB_DATA)
+tdb_chainunlock_read: int (struct tdb_context *, TDB_DATA)
+tdb_check: int (struct tdb_context *, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_close: int (struct tdb_context *)
+tdb_convert: void *(void *, uint32_t)
+tdb_delete: int (struct tdb_context *, TDB_DATA)
+tdb_do_delete: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_dump_all: void (struct tdb_context *)
+tdb_enable_seqnum: void (struct tdb_context *)
+tdb_error: enum TDB_ERROR (struct tdb_context *)
+tdb_errorstr: const char *(struct tdb_context *)
+tdb_exists: int (struct tdb_context *, TDB_DATA)
+tdb_expand: int (struct tdb_context *, tdb_off_t)
+tdb_fd: int (struct tdb_context *)
+tdb_fetch: TDB_DATA (struct tdb_context *, TDB_DATA)
+tdb_find_lock_hash: tdb_off_t (struct tdb_context *, TDB_DATA, uint32_t, int, struct tdb_record *)
+tdb_firstkey: TDB_DATA (struct tdb_context *)
+tdb_free: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_freelist_size: int (struct tdb_context *)
+tdb_get_flags: int (struct tdb_context *)
+tdb_get_logging_private: void *(struct tdb_context *)
+tdb_get_seqnum: int (struct tdb_context *)
+tdb_hash_size: int (struct tdb_context *)
+tdb_increment_seqnum_nonblock: void (struct tdb_context *)
+tdb_io_init: void (struct tdb_context *)
+tdb_lock: int (struct tdb_context *, int, int)
+tdb_lockall: int (struct tdb_context *)
+tdb_lockall_mark: int (struct tdb_context *)
+tdb_lockall_nonblock: int (struct tdb_context *)
+tdb_lockall_read: int (struct tdb_context *)
+tdb_lockall_read_nonblock: int (struct tdb_context *)
+tdb_lockall_unmark: int (struct tdb_context *)
+tdb_lock_nonblock: int (struct tdb_context *, int, int)
+tdb_lock_record: int (struct tdb_context *, tdb_off_t)
+tdb_log_fn: tdb_log_func (struct tdb_context *)
+tdb_map_size: size_t (struct tdb_context *)
+tdb_mmap: void (struct tdb_context *)
+tdb_munmap: int (struct tdb_context *)
+tdb_name: const char *(struct tdb_context *)
+tdb_nextkey: TDB_DATA (struct tdb_context *, TDB_DATA)
+tdb_null: {dptr = 0x0, dsize = 0}
+tdb_ofs_read: int (struct tdb_context *, tdb_off_t, tdb_off_t *)
+tdb_ofs_write: int (struct tdb_context *, tdb_off_t, tdb_off_t *)
+tdb_open: struct tdb_context *(const char *, int, int, int, mode_t)
+tdb_open_ex: struct tdb_context *(const char *, int, int, int, mode_t, const struct tdb_logging_context *, tdb_hash_func)
+tdb_parse_data: int (struct tdb_context *, TDB_DATA, tdb_off_t, tdb_len_t, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_parse_record: int (struct tdb_context *, TDB_DATA, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_printfreelist: int (struct tdb_context *)
+tdb_rec_free_read: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_rec_read: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_rec_write: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_remove_flags: void (struct tdb_context *, unsigned int)
+tdb_reopen: int (struct tdb_context *)
+tdb_reopen_all: int (int)
+tdb_repack: int (struct tdb_context *)
+tdb_setalarm_sigptr: void (struct tdb_context *, volatile sig_atomic_t *)
+tdb_set_logging_function: void (struct tdb_context *, const struct tdb_logging_context *)
+tdb_set_max_dead: void (struct tdb_context *, int)
+tdb_store: int (struct tdb_context *, TDB_DATA, TDB_DATA, int)
+_tdb_transaction_cancel: int (struct tdb_context *)
+tdb_transaction_cancel: int (struct tdb_context *)
+tdb_transaction_commit: int (struct tdb_context *)
+tdb_transaction_lock: int (struct tdb_context *, int)
+tdb_transaction_prepare_commit: int (struct tdb_context *)
+tdb_transaction_recover: int (struct tdb_context *)
+tdb_transaction_start: int (struct tdb_context *)
+tdb_transaction_unlock: int (struct tdb_context *)
+tdb_traverse: int (struct tdb_context *, tdb_traverse_func, void *)
+tdb_traverse_read: int (struct tdb_context *, tdb_traverse_func, void *)
+tdb_unlock: int (struct tdb_context *, int, int)
+tdb_unlockall: int (struct tdb_context *)
+tdb_unlockall_read: int (struct tdb_context *)
+tdb_unlock_record: int (struct tdb_context *, tdb_off_t)
+tdb_validate_freelist: int (struct tdb_context *, int *)
+tdb_wipe_all: int (struct tdb_context *)
+tdb_write_lock_record: int (struct tdb_context *, tdb_off_t)
+tdb_write_unlock_record: int (struct tdb_context *, tdb_off_t)
+tolower_sp: uint32_t (uint32_t)
+tolower_w: uint16_t (uint16_t)
+toupper_sp: uint32_t (uint32_t)
+toupper_w: uint16_t (uint16_t)
+type_configs: {{set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}}
+ucs2_to_charset: size_t (charset_t, const uint16_t *, char *, size_t)
+ucs2_to_charset_allocate: size_t (charset_t, char **, const uint16_t *)
+unbecome_root: void (void)
+unix_rename: int (int, const char *, int, const char *)
+unix_strlower: size_t (const char *, size_t, char *, size_t)
+unix_strupper: size_t (const char *, size_t, char *, size_t)
+unload_volumes: void (AFPObj *)
+utf8_charlen: size_t (char *)
+utf8_decompose: size_t (char *, size_t, char *, size_t)
+utf8_precompose: size_t (char *, size_t, char *, size_t)
+utf8_strlen_validate: size_t (char *)
+utf8_strlower: size_t (const char *, size_t, char *, size_t)
+utf8_strupper: size_t (const char *, size_t, char *, size_t)
+utf8_to_charset_allocate: size_t (charset_t, char **, const char *)
+uuid_bin2string: const char *(const unsigned char *)
+uuidcache: {<repeats 256 times>}
+uuidcache_dump: void (void)
+uuid_string2bin: void (const char *, unsigned char *)
+uuidtype: {"", "USER", "GROUP", "LOCAL"}
+volume_free: void (struct vol *)
+volume_unlink: void (struct vol *)
+writet: ssize_t (int, void *, const size_t, int, int)
diff --git a/libatalk/libatalk-3.0beta2.abi b/libatalk/libatalk-3.0beta2.abi
new file mode 100644 (file)
index 0000000..0d9dc70
--- /dev/null
@@ -0,0 +1,548 @@
+acl_ldap_readconfig: int (dictionary *)
+ad_close: int (struct adouble *, int)
+ad_convert: int (const char *, const struct stat *, const struct vol *, const char **)
+ad_copy_header: int (struct adouble *, struct adouble *)
+add_cachebyname: int (const char *, const uuidp_t, const uuidtype_t, const long unsigned int)
+add_cachebyuuid: int (uuidp_t, const char *, uuidtype_t, const long unsigned int)
+add_charset: charset_t (const char *)
+ad_dir: char *(const char *)
+ad_dtruncate: int (struct adouble *, const off_t)
+adflags2logstr: const char *(int)
+ad_flush: int (struct adouble *)
+ad_forcegetid: uint32_t (struct adouble *)
+adf_pread: ssize_t (struct ad_fd *, void *, size_t, off_t)
+adf_pwrite: ssize_t (struct ad_fd *, const void *, size_t, off_t)
+ad_getattr: int (const struct adouble *, uint16_t *)
+ad_getdate: int (const struct adouble *, unsigned int, uint32_t *)
+ad_getentryoff: off_t (const struct adouble *, int)
+ad_getfuid: uid_t (void)
+ad_getid: uint32_t (struct adouble *, const dev_t, const ino_t, const cnid_t, const void *)
+ad_hf_mode: mode_t (mode_t)
+ad_init: void (struct adouble *, const struct vol *)
+ad_init_old: void (struct adouble *, int, int)
+ad_lock: int (struct adouble *, uint32_t, int, off_t, off_t, int)
+ad_metadata: int (const char *, int, struct adouble *)
+ad_metadataat: int (int, const char *, int, struct adouble *)
+ad_mkdir: int (const char *, mode_t)
+ad_mode: int (const char *, mode_t)
+ad_open: int (struct adouble *, const char *, int, ...)
+ad_openat: int (struct adouble *, int, const char *, int, ...)
+ad_openforks: uint16_t (struct adouble *, uint16_t)
+ad_path: const char *(const char *, int)
+ad_path_ea: const char *(const char *, int)
+ad_path_osx: const char *(const char *, int)
+ad_read: ssize_t (struct adouble *, const uint32_t, off_t, char *, const size_t)
+ad_readfile_init: int (const struct adouble *, const int, off_t *, const int)
+ad_rebuild_adouble_header_ea: int (struct adouble *)
+ad_rebuild_adouble_header_v2: int (struct adouble *)
+ad_refresh: int (const char *, struct adouble *)
+ad_rtruncate: int (struct adouble *, const off_t)
+ad_setattr: int (const struct adouble *, const uint16_t)
+ad_setdate: int (struct adouble *, unsigned int, uint32_t)
+ad_setfuid: int (const uid_t)
+ad_setid: int (struct adouble *, const dev_t, const ino_t, const uint32_t, const cnid_t, const void *)
+ad_setname: int (struct adouble *, const char *)
+ad_size: off_t (const struct adouble *, const uint32_t)
+ad_stat: int (const char *, struct stat *)
+ad_testlock: int (struct adouble *, int, const off_t)
+ad_tmplock: int (struct adouble *, uint32_t, int, off_t, off_t, int)
+ad_unlock: void (struct adouble *, const int, int)
+ad_valid_header_osx: int (const char *)
+ad_write: ssize_t (struct adouble *, uint32_t, off_t, int, const char *, size_t)
+afp_config_parse: int (AFPObj *, char *)
+allow_severity: 5
+apply_ip_mask: void (struct sockaddr *, int)
+atalk_iconv: size_t (atalk_iconv_t, const char **, size_t *, char **, size_t *)
+atalk_iconv_close: int (atalk_iconv_t)
+atalk_iconv_open: atalk_iconv_t (const char *, const char *)
+atalk_register_charset: int (struct charset_functions *)
+balloc: int (bstring, int)
+ballocmin: int (bstring, int)
+bassign: int (bstring, const_bstring)
+bassignblk: int (bstring, const void *, int)
+bassigncstr: int (bstring, const char *)
+bassignformat: int (bstring, const char *, ...)
+bassigngets: int (bstring, bNgetc, void *, char)
+bassignmidstr: int (bstring, const_bstring, int, int)
+bcatblk: int (bstring, const void *, int)
+bcatcstr: int (bstring, const char *)
+bconcat: int (bstring, const_bstring)
+bconchar: int (bstring, char)
+bcstrfree: int (char *)
+bdelete: int (bstring, int, int)
+bdestroy: int (bstring)
+become_root: void (void)
+bfindreplace: int (bstring, const_bstring, const_bstring, int)
+bfindreplacecaseless: int (bstring, const_bstring, const_bstring, int)
+bformat: bstring (const char *, ...)
+bformata: int (bstring, const char *, ...)
+bfromcstr: bstring (const char *)
+bfromcstralloc: bstring (int, const char *)
+bgetsa: int (bstring, bNgetc, void *, char)
+bgetstream: bstring (bNgetc, void *, char)
+binchr: int (const_bstring, int, const_bstring)
+binchrr: int (const_bstring, int, const_bstring)
+binsert: int (bstring, int, const_bstring, unsigned char)
+binsertch: int (bstring, int, int, unsigned char)
+binstr: int (const_bstring, int, const_bstring)
+binstrcaseless: int (const_bstring, int, const_bstring)
+binstrr: int (const_bstring, int, const_bstring)
+binstrrcaseless: int (const_bstring, int, const_bstring)
+biseq: int (const_bstring, const_bstring)
+biseqcaseless: int (const_bstring, const_bstring)
+biseqcstr: int (const_bstring, const char *)
+biseqcstrcaseless: int (const_bstring, const char *)
+bisstemeqblk: int (const_bstring, const void *, int)
+bisstemeqcaselessblk: int (const_bstring, const void *, int)
+bjoin: bstring (const struct bstrList *, const_bstring)
+bjoinInv: bstring (const struct bstrList *, const_bstring)
+blk2bstr: bstring (const void *, int)
+bltrimws: int (bstring)
+bmidstr: bstring (const_bstring, int, int)
+bninchr: int (const_bstring, int, const_bstring)
+bninchrr: int (const_bstring, int, const_bstring)
+bpattern: int (bstring, int)
+bread: bstring (bNread, void *)
+breada: int (bstring, bNread, void *)
+brefcstr: bstring (char *)
+breplace: int (bstring, int, int, const_bstring, unsigned char)
+brtrimws: int (bstring)
+bsbufflength: int (struct bStream *, int)
+bsclose: void *(struct bStream *)
+bseof: int (const struct bStream *)
+bsetstr: int (bstring, int, const_bstring, unsigned char)
+bsopen: struct bStream *(bNread, void *)
+bspeek: int (bstring, const struct bStream *)
+bsplit: struct bstrList *(const_bstring, unsigned char)
+bsplitcb: int (const_bstring, unsigned char, int, int (*)(void *, int, int), void *)
+bsplits: struct bstrList *(const_bstring, const_bstring)
+bsplitscb: int (const_bstring, const_bstring, int, int (*)(void *, int, int), void *)
+bsplitstr: struct bstrList *(const_bstring, const_bstring)
+bsplitstrcb: int (const_bstring, const_bstring, int, int (*)(void *, int, int), void *)
+bsread: int (bstring, struct bStream *, int)
+bsreada: int (bstring, struct bStream *, int)
+bsreadln: int (bstring, struct bStream *, char)
+bsreadlna: int (bstring, struct bStream *, char)
+bsreadlns: int (bstring, struct bStream *, const_bstring)
+bsreadlnsa: int (bstring, struct bStream *, const_bstring)
+bssplitscb: int (struct bStream *, const_bstring, int (*)(void *, int, const_bstring), void *)
+bssplitstrcb: int (struct bStream *, const_bstring, int (*)(void *, int, const_bstring), void *)
+bstr2cstr: char *(const_bstring, char)
+bstrchrp: int (const_bstring, int, int)
+bstrcmp: int (const_bstring, const_bstring)
+bstrcpy: bstring (const_bstring)
+bstricmp: int (const_bstring, const_bstring)
+bstrListAlloc: int (struct bstrList *, int)
+bstrListAllocMin: int (struct bstrList *, int)
+bstrListCreate: struct bstrList *(void)
+bstrListCreateMin: struct bstrList *(int)
+bstrListDestroy: int (struct bstrList *)
+bstrListPop: bstring (struct bstrList *)
+bstrListPush: int (struct bstrList *, bstring)
+bstrncmp: int (const_bstring, const_bstring, int)
+bstrnicmp: int (const_bstring, const_bstring, int)
+bstrrchrp: int (const_bstring, int, int)
+bsunread: int (struct bStream *, const_bstring)
+btolower: int (bstring)
+btoupper: int (bstring)
+btrimws: int (bstring)
+btrunc: int (bstring, int)
+bunrefcstr: int (bstring)
+bvcformata: int (bstring, int, const char *, struct __va_list_tag *)
+charset_decompose: size_t (charset_t, char *, size_t, char *, size_t)
+charset_mac_centraleurope: {name = "MAC_CENTRALEUROPE", kTextEncoding = 29, pull = <mac_centraleurope_pull>, push = <mac_centraleurope_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_chinese_simp: {name = "MAC_CHINESE_SIMP", kTextEncoding = 25, pull = <mac_chinese_simp_pull>, push = <mac_chinese_simp_push>, flags = 85, iname = "EUC-CN", prev = 0x0, next = 0x0}
+charset_mac_chinese_trad: {name = "MAC_CHINESE_TRAD", kTextEncoding = 2, pull = <mac_chinese_trad_pull>, push = <mac_chinese_trad_push>, flags = 85, iname = "BIG-5", prev = 0x0, next = 0x0}
+charset_mac_cyrillic: {name = "MAC_CYRILLIC", kTextEncoding = 7, pull = <mac_cyrillic_pull>, push = <mac_cyrillic_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_greek: {name = "MAC_GREEK", kTextEncoding = 6, pull = <mac_greek_pull>, push = <mac_greek_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_hebrew: {name = "MAC_HEBREW", kTextEncoding = 5, pull = <mac_hebrew_pull>, push = <mac_hebrew_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_japanese: {name = "MAC_JAPANESE", kTextEncoding = 1, pull = <mac_japanese_pull>, push = <mac_japanese_push>, flags = 85, iname = "SHIFT_JIS", prev = 0x0, next = 0x0}
+charset_mac_korean: {name = "MAC_KOREAN", kTextEncoding = 3, pull = <mac_korean_pull>, push = <mac_korean_push>, flags = 85, iname = "EUC-KR", prev = 0x0, next = 0x0}
+charset_mac_roman: {name = "MAC_ROMAN", kTextEncoding = 0, pull = <mac_roman_pull>, push = <mac_roman_push>, flags = 21, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_turkish: {name = "MAC_TURKISH", kTextEncoding = 35, pull = <mac_turkish_pull>, push = <mac_turkish_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_precompose: size_t (charset_t, char *, size_t, char *, size_t)
+charset_strlower: size_t (charset_t, const char *, size_t, char *, size_t)
+charset_strupper: size_t (charset_t, const char *, size_t, char *, size_t)
+charset_to_ucs2_allocate: size_t (charset_t, uint16_t **, const char *)
+charset_to_utf8_allocate: size_t (charset_t, char **, const char *)
+charset_utf8: {name = "UTF8", kTextEncoding = 134217987, pull = <utf8_pull>, push = <utf8_push>, flags = 22, iname = 0x0, prev = 0x0, next = 0x0}
+charset_utf8_mac: {name = "UTF8-MAC", kTextEncoding = 134217987, pull = <utf8_pull>, push = <utf8_push>, flags = 27, iname = 0x0, prev = 0x0, next = 0x0}
+check_lockfile: int (const char *, const char *)
+cjk_char_pull: size_t (uint16_t, uint16_t *, const uint32_t *)
+cjk_char_push: size_t (uint16_t, uint8_t *)
+cjk_compose: uint16_t (uint16_t, uint16_t, const uint32_t *, size_t)
+cjk_compose_seq: uint16_t (const uint16_t *, size_t *, const uint32_t *, size_t)
+cjk_generic_pull: size_t (size_t (*)(uint16_t *, const uint8_t *, size_t *), void *, char **, size_t *, char **, size_t *)
+cjk_generic_push: size_t (size_t (*)(uint8_t *, const uint16_t *, size_t *), void *, char **, size_t *, char **, size_t *)
+cjk_lookup: uint16_t (uint16_t, const cjk_index_t *, const uint16_t *)
+cnid_add: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, const char *, const size_t, cnid_t)
+cnid_close: void (struct _cnid_db *)
+cnid_dbd_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_dbd_close: void (struct _cnid_db *)
+cnid_dbd_delete: int (struct _cnid_db *, const cnid_t)
+cnid_dbd_find: int (struct _cnid_db *, const char *, size_t, void *, size_t)
+cnid_dbd_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_dbd_getstamp: int (struct _cnid_db *, void *, const size_t)
+cnid_dbd_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_dbd_module: {name = "dbd", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 0}
+cnid_dbd_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_dbd_rebuild_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_dbd_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_dbd_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_delete: int (struct _cnid_db *, cnid_t)
+cnid_find: int (struct _cnid_db *, const char *, size_t, void *, size_t)
+cnid_get: cnid_t (struct _cnid_db *, const cnid_t, char *, const size_t)
+cnid_getstamp: int (struct _cnid_db *, void *, const size_t)
+cnid_init: void (void)
+cnid_last_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_last_close: void (struct _cnid_db *)
+cnid_last_delete: int (struct _cnid_db *, const cnid_t)
+cnid_last_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_last_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_last_module: {name = "last", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 0}
+cnid_last_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_last_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_last_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_lookup: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, char *, const size_t)
+cnid_open: struct _cnid_db *(const char *, mode_t, char *, int, const char *, const char *)
+cnid_rebuild_add: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, char *, const size_t, cnid_t)
+cnid_register: void (struct _cnid_module *)
+cnid_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_tdb_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_tdb_close: void (struct _cnid_db *)
+cnid_tdb_delete: int (struct _cnid_db *, const cnid_t)
+cnid_tdb_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_tdb_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_tdb_module: {name = "tdb", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 12}
+cnid_tdb_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_tdb_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_tdb_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_update: int (struct _cnid_db *, const cnid_t, const struct stat *, const cnid_t, char *, const size_t)
+compare_ip: int (const struct sockaddr *, const struct sockaddr *)
+convert_charset: size_t (charset_t, charset_t, charset_t, const char *, size_t, char *, size_t, uint16_t *)
+convert_string: size_t (charset_t, charset_t, const void *, size_t, void *, size_t)
+convert_string_allocate: size_t (charset_t, charset_t, const void *, size_t, char **)
+copy_ea: int (const char *, int, const char *, const char *, mode_t)
+copy_file: int (int, const char *, const char *, mode_t)
+copy_file_fd: int (int, int)
+copy_fork: int (int, struct adouble *, struct adouble *)
+create_lockfile: int (const char *, const char *)
+daemonize: int (int, int)
+decompose_w: size_t (uint16_t *, size_t, uint16_t *, size_t *)
+deny_severity: 3
+dequeue: void *(q_t *)
+_diacasemap: {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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 231, 203, 229, 128, 204, 129, 130, 131, 233, 230, 232, 234, 237, 235, 236, 132, 238, 241, 239, 133, 205, 242, 244, 243, 134, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 198, 183, 184, 184, 186, 187, 188, 189, 174, 175, 192, 193, 194, 195, 196, 197, 198, 199...}
+_dialowermap: {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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 138, 140, 141, 142, 150, 154, 159, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 132, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 190, 191, 176, 177, 178, 179, 180, 181, 198, 183, 185, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199...}
+dictionary_del: void (dictionary *)
+dictionary_dump: void (dictionary *, FILE *)
+dictionary_get: const char *(const dictionary *, const char *, const char *, const char *)
+dictionary_hash: unsigned int (char *)
+dictionary_new: dictionary *(int)
+dictionary_set: int (dictionary *, char *, char *, char *)
+dictionary_unset: void (dictionary *, char *, char *)
+dir_rx_set: int (mode_t)
+dsi_attention: int (DSI *, AFPUserBytes)
+dsi_close: void (DSI *)
+dsi_cmdreply: int (DSI *, const int)
+dsi_disconnect: int (DSI *)
+dsi_getsession: int (DSI *, server_child *, int, afp_child_t **)
+dsi_getstatus: void (DSI *)
+dsi_init: DSI *(AFPObj *, const char *, const char *, const char *)
+dsi_opensession: void (DSI *)
+dsi_read: ssize_t (DSI *, void *, const size_t)
+dsi_readdone: void (DSI *)
+dsi_readinit: ssize_t (DSI *, void *, const size_t, const size_t, const int)
+dsi_stream_read: size_t (DSI *, void *, const size_t)
+dsi_stream_read_file: ssize_t (DSI *, const int, off_t, const size_t, const int)
+dsi_stream_receive: int (DSI *)
+dsi_stream_send: int (DSI *, void *, size_t)
+dsi_stream_write: ssize_t (DSI *, void *, const size_t, int)
+dsi_tcp_init: int (DSI *, const char *, const char *, const char *)
+dsi_tickle: int (DSI *)
+dsi_write: size_t (DSI *, void *, const size_t)
+dsi_writeflush: void (DSI *)
+dsi_writeinit: size_t (DSI *, void *, const size_t)
+ea_chmod_dir: int (const struct vol *, const char *, mode_t, struct stat *)
+ea_chmod_file: int (const struct vol *, const char *, mode_t, struct stat *)
+ea_chown: int (const struct vol *, const char *, uid_t, gid_t)
+ea_close: int (struct ea *)
+ea_copyfile: int (const struct vol *, int, const char *, const char *)
+ea_deletefile: int (const struct vol *, int, const char *)
+ea_open: int (const struct vol *, const char *, eaflags_t, struct ea *)
+ea_openat: int (const struct vol *, int, const char *, eaflags_t, struct ea *)
+ea_path: char *(const struct ea *, const char *, int)
+ea_renamefile: int (const struct vol *, int, const char *, const char *)
+enqueue: qnode_t *(q_t *, void *)
+fault_setup: void (void (*)(void *))
+fdset_add_fd: void (int, struct pollfd **, struct polldata **, int *, int *, int, enum fdtype, void *)
+fdset_del_fd: void (struct pollfd **, struct polldata **, int *, int *, int)
+find_charset_functions: struct charset_functions *(const char *)
+_fini: <text variable, no debug info>
+freeifacelist: void (char **)
+fullpathname: const char *(const char *)
+getcwdpath: const char *(void)
+get_eacontent: int (const struct vol *, char *, size_t *, const char *, int, const char *, int)
+get_easize: int (const struct vol *, char *, size_t *, const char *, int, const char *)
+getifacelist: char **(void)
+getip_port: unsigned int (const struct sockaddr *)
+getip_string: const char *(const struct sockaddr *)
+getnamefromuuid: int (const uuidp_t, char **, uuidtype_t *)
+getuuidfromname: int (const char *, uuidtype_t, unsigned char *)
+getvolbyname: struct vol *(const char *)
+getvolbypath: struct vol *(AFPObj *, const char *)
+getvolbyvid: struct vol *(const uint16_t)
+getvolumes: struct vol *(void)
+gmem: int (gid_t, int, gid_t *)
+iniparser_dump: void (const dictionary *, FILE *)
+iniparser_dump_ini: void (const dictionary *, FILE *)
+iniparser_find_entry: int (const dictionary *, const char *)
+iniparser_freedict: void (dictionary *)
+iniparser_getboolean: int (const dictionary *, const char *, const char *, int)
+iniparser_getdouble: double (const dictionary *, const char *, const char *, double)
+iniparser_getint: int (const dictionary *, const char *, const char *, int)
+iniparser_getnsec: int (const dictionary *)
+iniparser_getsecname: const char *(const dictionary *, int)
+iniparser_getstrdup: char *(const dictionary *, const char *, const char *, const char *)
+iniparser_getstring: const char *(const dictionary *, const char *, const char *, const char *)
+iniparser_load: dictionary *(const char *)
+iniparser_set: int (dictionary *, char *, char *, char *)
+iniparser_unset: void (dictionary *, char *, char *)
+_init: <text variable, no debug info>
+init_iconv: void (void)
+initvol_vfs: void (struct vol *)
+ipc_child_write: int (int, uint16_t, int, void *)
+ipc_client_uds: int (const char *)
+ipc_server_read: int (server_child *, int)
+ipc_server_uds: int (const char *)
+islower_sp: int (uint32_t)
+islower_w: int (uint16_t)
+isupper_sp: int (uint32_t)
+isupper_w: int (uint16_t)
+lchdir: int (const char *)
+ldap_auth_dn: 0x0
+ldap_auth_method: 0
+ldap_auth_pw: 0x0
+ldap_config_valid: 0
+ldap_getnamefromuuid: int (const char *, char **, uuidtype_t *)
+ldap_getuuidfromname: int (const char *, uuidtype_t, char **)
+ldap_group_attr: 0x0
+ldap_groupbase: 0x0
+ldap_groupscope: 0
+ldap_name_attr: 0x0
+ldap_prefs: {{pref = 0x0, name = "ldap server", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap auth method", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap auth dn", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap auth pw", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap userbase", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap userscope", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap groupbase", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap groupscope", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap uuid attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap uuid string", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap name attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap group attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap uid attr", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = 0x0, strorint = 0, intfromarray = 0, valid = -1}}
+ldap_server: 0x0
+ldap_uid_attr: 0x0
+ldap_userbase: 0x0
+ldap_userscope: 0
+ldap_uuid_attr: 0x0
+ldap_uuid_string: 0x0
+list_eas: int (const struct vol *, char *, size_t *, const char *, int)
+load_charset: int (struct vol *)
+load_volumes: int (AFPObj *, void (*)(const AFPObj *, struct vol *))
+localuuid_from_id: void (unsigned char *, uuidtype_t, unsigned int)
+lock_reg: int (int, int, int, off_t, int, off_t)
+log_config: {inited = false, syslog_opened = false, console = false, processname = '\0' <repeats 15 times>, syslog_facility = 0, syslog_display_options = 0}
+lstatat: int (int, const char *, struct stat *)
+make_log_entry: void (enum loglevels, enum logtypes, const char *, int, char *, ...)
+make_tdb_data: unsigned char *(uint32_t, const struct stat *, const cnid_t, const char *, const size_t)
+mb_generic_pull: size_t (int (*)(uint16_t *, const unsigned char *), void *, char **, size_t *, char **, size_t *)
+mb_generic_push: size_t (int (*)(unsigned char *, uint16_t), void *, char **, size_t *, char **, size_t *)
+netatalk_panic: void (const char *)
+netatalk_rmdir: int (int, const char *)
+netatalk_rmdir_all_errors: int (int, const char *)
+netatalk_unlink: int (const char *)
+netatalk_unlinkat: int (int, const char *)
+nftw: int (const char *, nftw_func_t, dir_notification_func_t, int, int)
+opendirat: DIR *(int, const char *)
+openflags2logstr: const char *(int)
+posix_chmod: int (const char *, mode_t)
+posix_fchmod: int (int, mode_t)
+precompose_w: size_t (uint16_t *, size_t, uint16_t *, size_t *)
+prefs_array: {{pref = "ldap auth method", valuestring = "none", value = 0}, {pref = "ldap auth method", valuestring = "simple", value = 128}, {pref = "ldap auth method", valuestring = "sasl", value = 163}, {pref = "ldap userscope", valuestring = "base", value = 0}, {pref = "ldap userscope", valuestring = "one", value = 1}, {pref = "ldap userscope", valuestring = "sub", value = 2}, {pref = "ldap groupscope", valuestring = "base", value = 0}, {pref = "ldap groupscope", valuestring = "one", value = 1}, {pref = "ldap groupscope", valuestring = "sub", value = 2}, {pref = 0x0, valuestring = 0x0, value = 0}}
+prequeue: qnode_t *(q_t *, void *)
+queue_destroy: void (q_t *, void (*)(void *))
+queue_init: q_t *(void)
+randombytes: void (void *, int)
+readt: ssize_t (int, void *, const size_t, int, int)
+reconnect_ipc: int (AFPObj *)
+recv_fd: int (int, int)
+rel_path_in_vol: bstring (const char *, const char *)
+remove_acl_vfs: int (const char *)
+remove_ea: int (const struct vol *, const char *, const char *, int)
+run_cmd: int (const char *, char **)
+search_cachebyname: int (const char *, uuidtype_t *, unsigned char *)
+search_cachebyuuid: int (uuidp_t, char **, uuidtype_t *)
+send_fd: int (int, int)
+server_child_add: afp_child_t *(server_child *, int, pid_t, int)
+server_child_alloc: server_child *(const int, const int)
+server_child_free: void (server_child *)
+server_child_kill: void (server_child *, int, int)
+server_child_kill_one_by_id: void (server_child *, int, pid_t, uid_t, uint32_t, char *, uint32_t)
+server_child_remove: int (server_child *, const int, pid_t)
+server_child_setup: void (server_child *, const int, void (*)(const pid_t))
+server_child_transfer_session: int (server_child *, int, pid_t, uid_t, int, uint16_t)
+server_lock: pid_t (char *, char *, int)
+server_reset_signal: void (void)
+set_charset_name: int (charset_t, const char *)
+set_ea: int (const struct vol *, const char *, const char *, const char *, size_t, int)
+setfilmode: int (const char *, mode_t, struct stat *, mode_t)
+setnonblock: int (int, int)
+set_processname: void (const char *)
+setuplog: void (const char *, const char *)
+statat: int (int, const char *, struct stat *)
+strcasechr_sp: uint16_t *(const uint16_t *, uint32_t)
+strcasechr_w: uint16_t *(const uint16_t *, uint16_t)
+strcasecmp_w: int (const uint16_t *, const uint16_t *)
+strcasestr_w: uint16_t *(const uint16_t *, const uint16_t *)
+strcat_w: uint16_t *(uint16_t *, const uint16_t *)
+strchr_w: uint16_t *(const uint16_t *, uint16_t)
+strcmp_w: int (const uint16_t *, const uint16_t *)
+strdiacasecmp: int (const char *, const char *)
+strdup_w: uint16_t *(const uint16_t *)
+stripped_slashes_basename: char *(char *)
+strlcat: size_t (char *, const char *, size_t)
+strlcpy: size_t (char *, const char *, size_t)
+strlen_w: size_t (const uint16_t *)
+strlower_w: int (uint16_t *)
+strncasecmp_w: int (const uint16_t *, const uint16_t *, size_t)
+strncat_w: uint16_t *(uint16_t *, const uint16_t *, const size_t)
+strncmp_w: int (const uint16_t *, const uint16_t *, size_t)
+strncpy_w: uint16_t *(uint16_t *, const uint16_t *, const size_t)
+strndiacasecmp: int (const char *, const char *, size_t)
+strndup_w: uint16_t *(const uint16_t *, size_t)
+strnlen_w: size_t (const uint16_t *, size_t)
+strstr_w: uint16_t *(const uint16_t *, const uint16_t *)
+strupper_w: int (uint16_t *)
+sys_ea_copyfile: int (const struct vol *, int, const char *, const char *)
+sys_fgetxattr: ssize_t (int, const char *, void *, size_t)
+sys_fsetxattr: int (int, const char *, const void *, size_t, int)
+sys_ftruncate: int (int, off_t)
+sys_get_eacontent: int (const struct vol *, char *, size_t *, const char *, int, const char *, int)
+sys_get_easize: int (const struct vol *, char *, size_t *, const char *, int, const char *)
+sys_getxattr: ssize_t (const char *, const char *, void *, size_t)
+sys_getxattrfd: int (int, const char *, int, ...)
+sys_lgetxattr: ssize_t (const char *, const char *, void *, size_t)
+sys_list_eas: int (const struct vol *, char *, size_t *, const char *, int)
+sys_listxattr: ssize_t (const char *, char *, size_t)
+sys_llistxattr: ssize_t (const char *, char *, size_t)
+sys_lremovexattr: int (const char *, const char *)
+sys_lsetxattr: int (const char *, const char *, const void *, size_t, int)
+sys_remove_ea: int (const struct vol *, const char *, const char *, int)
+sys_removexattr: int (const char *, const char *)
+sys_sendfile: ssize_t (int, int, off_t *, size_t)
+sys_set_ea: int (const struct vol *, const char *, const char *, const char *, size_t, int)
+sys_setxattr: int (const char *, const char *, const void *, size_t, int)
+tdb_add_flags: void (struct tdb_context *, unsigned int)
+tdb_allocate: tdb_off_t (struct tdb_context *, tdb_len_t, struct tdb_record *)
+tdb_alloc_read: unsigned char *(struct tdb_context *, tdb_off_t, tdb_len_t)
+tdb_append: int (struct tdb_context *, TDB_DATA, TDB_DATA)
+tdb_brlock: int (struct tdb_context *, tdb_off_t, int, int, int, size_t)
+tdb_brlock_upgrade: int (struct tdb_context *, tdb_off_t, size_t)
+tdb_chainlock: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_mark: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_nonblock: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_read: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_unmark: int (struct tdb_context *, TDB_DATA)
+tdb_chainunlock: int (struct tdb_context *, TDB_DATA)
+tdb_chainunlock_read: int (struct tdb_context *, TDB_DATA)
+tdb_check: int (struct tdb_context *, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_close: int (struct tdb_context *)
+tdb_convert: void *(void *, uint32_t)
+tdb_delete: int (struct tdb_context *, TDB_DATA)
+tdb_do_delete: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_dump_all: void (struct tdb_context *)
+tdb_enable_seqnum: void (struct tdb_context *)
+tdb_error: enum TDB_ERROR (struct tdb_context *)
+tdb_errorstr: const char *(struct tdb_context *)
+tdb_exists: int (struct tdb_context *, TDB_DATA)
+tdb_expand: int (struct tdb_context *, tdb_off_t)
+tdb_fd: int (struct tdb_context *)
+tdb_fetch: TDB_DATA (struct tdb_context *, TDB_DATA)
+tdb_find_lock_hash: tdb_off_t (struct tdb_context *, TDB_DATA, uint32_t, int, struct tdb_record *)
+tdb_firstkey: TDB_DATA (struct tdb_context *)
+tdb_free: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_freelist_size: int (struct tdb_context *)
+tdb_get_flags: int (struct tdb_context *)
+tdb_get_logging_private: void *(struct tdb_context *)
+tdb_get_seqnum: int (struct tdb_context *)
+tdb_hash_size: int (struct tdb_context *)
+tdb_increment_seqnum_nonblock: void (struct tdb_context *)
+tdb_io_init: void (struct tdb_context *)
+tdb_lock: int (struct tdb_context *, int, int)
+tdb_lockall: int (struct tdb_context *)
+tdb_lockall_mark: int (struct tdb_context *)
+tdb_lockall_nonblock: int (struct tdb_context *)
+tdb_lockall_read: int (struct tdb_context *)
+tdb_lockall_read_nonblock: int (struct tdb_context *)
+tdb_lockall_unmark: int (struct tdb_context *)
+tdb_lock_nonblock: int (struct tdb_context *, int, int)
+tdb_lock_record: int (struct tdb_context *, tdb_off_t)
+tdb_log_fn: tdb_log_func (struct tdb_context *)
+tdb_map_size: size_t (struct tdb_context *)
+tdb_mmap: void (struct tdb_context *)
+tdb_munmap: int (struct tdb_context *)
+tdb_name: const char *(struct tdb_context *)
+tdb_nextkey: TDB_DATA (struct tdb_context *, TDB_DATA)
+tdb_null: {dptr = 0x0, dsize = 0}
+tdb_ofs_read: int (struct tdb_context *, tdb_off_t, tdb_off_t *)
+tdb_ofs_write: int (struct tdb_context *, tdb_off_t, tdb_off_t *)
+tdb_open: struct tdb_context *(const char *, int, int, int, mode_t)
+tdb_open_ex: struct tdb_context *(const char *, int, int, int, mode_t, const struct tdb_logging_context *, tdb_hash_func)
+tdb_parse_data: int (struct tdb_context *, TDB_DATA, tdb_off_t, tdb_len_t, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_parse_record: int (struct tdb_context *, TDB_DATA, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_printfreelist: int (struct tdb_context *)
+tdb_rec_free_read: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_rec_read: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_rec_write: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_remove_flags: void (struct tdb_context *, unsigned int)
+tdb_reopen: int (struct tdb_context *)
+tdb_reopen_all: int (int)
+tdb_repack: int (struct tdb_context *)
+tdb_setalarm_sigptr: void (struct tdb_context *, volatile sig_atomic_t *)
+tdb_set_logging_function: void (struct tdb_context *, const struct tdb_logging_context *)
+tdb_set_max_dead: void (struct tdb_context *, int)
+tdb_store: int (struct tdb_context *, TDB_DATA, TDB_DATA, int)
+_tdb_transaction_cancel: int (struct tdb_context *)
+tdb_transaction_cancel: int (struct tdb_context *)
+tdb_transaction_commit: int (struct tdb_context *)
+tdb_transaction_lock: int (struct tdb_context *, int)
+tdb_transaction_prepare_commit: int (struct tdb_context *)
+tdb_transaction_recover: int (struct tdb_context *)
+tdb_transaction_start: int (struct tdb_context *)
+tdb_transaction_unlock: int (struct tdb_context *)
+tdb_traverse: int (struct tdb_context *, tdb_traverse_func, void *)
+tdb_traverse_read: int (struct tdb_context *, tdb_traverse_func, void *)
+tdb_unlock: int (struct tdb_context *, int, int)
+tdb_unlockall: int (struct tdb_context *)
+tdb_unlockall_read: int (struct tdb_context *)
+tdb_unlock_record: int (struct tdb_context *, tdb_off_t)
+tdb_validate_freelist: int (struct tdb_context *, int *)
+tdb_wipe_all: int (struct tdb_context *)
+tdb_write_lock_record: int (struct tdb_context *, tdb_off_t)
+tdb_write_unlock_record: int (struct tdb_context *, tdb_off_t)
+tolower_sp: uint32_t (uint32_t)
+tolower_w: uint16_t (uint16_t)
+toupper_sp: uint32_t (uint32_t)
+toupper_w: uint16_t (uint16_t)
+type_configs: {{set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}}
+ucs2_to_charset: size_t (charset_t, const uint16_t *, char *, size_t)
+ucs2_to_charset_allocate: size_t (charset_t, char **, const uint16_t *)
+unbecome_root: void (void)
+unix_rename: int (int, const char *, int, const char *)
+unix_strlower: size_t (const char *, size_t, char *, size_t)
+unix_strupper: size_t (const char *, size_t, char *, size_t)
+unload_volumes: void (AFPObj *)
+utf8_charlen: size_t (char *)
+utf8_decompose: size_t (char *, size_t, char *, size_t)
+utf8_precompose: size_t (char *, size_t, char *, size_t)
+utf8_strlen_validate: size_t (char *)
+utf8_strlower: size_t (const char *, size_t, char *, size_t)
+utf8_strupper: size_t (const char *, size_t, char *, size_t)
+utf8_to_charset_allocate: size_t (charset_t, char **, const char *)
+uuid_bin2string: const char *(const unsigned char *)
+uuidcache_dump: void (void)
+uuid_string2bin: void (const char *, unsigned char *)
+uuidtype: {"", "USER", "GROUP", "LOCAL"}
+volume_free: void (struct vol *)
+volume_unlink: void (struct vol *)
+writet: ssize_t (int, void *, const size_t, int, int)
diff --git a/libatalk/libatalk-3.0dev.abi b/libatalk/libatalk-3.0dev.abi
new file mode 100644 (file)
index 0000000..0d9dc70
--- /dev/null
@@ -0,0 +1,548 @@
+acl_ldap_readconfig: int (dictionary *)
+ad_close: int (struct adouble *, int)
+ad_convert: int (const char *, const struct stat *, const struct vol *, const char **)
+ad_copy_header: int (struct adouble *, struct adouble *)
+add_cachebyname: int (const char *, const uuidp_t, const uuidtype_t, const long unsigned int)
+add_cachebyuuid: int (uuidp_t, const char *, uuidtype_t, const long unsigned int)
+add_charset: charset_t (const char *)
+ad_dir: char *(const char *)
+ad_dtruncate: int (struct adouble *, const off_t)
+adflags2logstr: const char *(int)
+ad_flush: int (struct adouble *)
+ad_forcegetid: uint32_t (struct adouble *)
+adf_pread: ssize_t (struct ad_fd *, void *, size_t, off_t)
+adf_pwrite: ssize_t (struct ad_fd *, const void *, size_t, off_t)
+ad_getattr: int (const struct adouble *, uint16_t *)
+ad_getdate: int (const struct adouble *, unsigned int, uint32_t *)
+ad_getentryoff: off_t (const struct adouble *, int)
+ad_getfuid: uid_t (void)
+ad_getid: uint32_t (struct adouble *, const dev_t, const ino_t, const cnid_t, const void *)
+ad_hf_mode: mode_t (mode_t)
+ad_init: void (struct adouble *, const struct vol *)
+ad_init_old: void (struct adouble *, int, int)
+ad_lock: int (struct adouble *, uint32_t, int, off_t, off_t, int)
+ad_metadata: int (const char *, int, struct adouble *)
+ad_metadataat: int (int, const char *, int, struct adouble *)
+ad_mkdir: int (const char *, mode_t)
+ad_mode: int (const char *, mode_t)
+ad_open: int (struct adouble *, const char *, int, ...)
+ad_openat: int (struct adouble *, int, const char *, int, ...)
+ad_openforks: uint16_t (struct adouble *, uint16_t)
+ad_path: const char *(const char *, int)
+ad_path_ea: const char *(const char *, int)
+ad_path_osx: const char *(const char *, int)
+ad_read: ssize_t (struct adouble *, const uint32_t, off_t, char *, const size_t)
+ad_readfile_init: int (const struct adouble *, const int, off_t *, const int)
+ad_rebuild_adouble_header_ea: int (struct adouble *)
+ad_rebuild_adouble_header_v2: int (struct adouble *)
+ad_refresh: int (const char *, struct adouble *)
+ad_rtruncate: int (struct adouble *, const off_t)
+ad_setattr: int (const struct adouble *, const uint16_t)
+ad_setdate: int (struct adouble *, unsigned int, uint32_t)
+ad_setfuid: int (const uid_t)
+ad_setid: int (struct adouble *, const dev_t, const ino_t, const uint32_t, const cnid_t, const void *)
+ad_setname: int (struct adouble *, const char *)
+ad_size: off_t (const struct adouble *, const uint32_t)
+ad_stat: int (const char *, struct stat *)
+ad_testlock: int (struct adouble *, int, const off_t)
+ad_tmplock: int (struct adouble *, uint32_t, int, off_t, off_t, int)
+ad_unlock: void (struct adouble *, const int, int)
+ad_valid_header_osx: int (const char *)
+ad_write: ssize_t (struct adouble *, uint32_t, off_t, int, const char *, size_t)
+afp_config_parse: int (AFPObj *, char *)
+allow_severity: 5
+apply_ip_mask: void (struct sockaddr *, int)
+atalk_iconv: size_t (atalk_iconv_t, const char **, size_t *, char **, size_t *)
+atalk_iconv_close: int (atalk_iconv_t)
+atalk_iconv_open: atalk_iconv_t (const char *, const char *)
+atalk_register_charset: int (struct charset_functions *)
+balloc: int (bstring, int)
+ballocmin: int (bstring, int)
+bassign: int (bstring, const_bstring)
+bassignblk: int (bstring, const void *, int)
+bassigncstr: int (bstring, const char *)
+bassignformat: int (bstring, const char *, ...)
+bassigngets: int (bstring, bNgetc, void *, char)
+bassignmidstr: int (bstring, const_bstring, int, int)
+bcatblk: int (bstring, const void *, int)
+bcatcstr: int (bstring, const char *)
+bconcat: int (bstring, const_bstring)
+bconchar: int (bstring, char)
+bcstrfree: int (char *)
+bdelete: int (bstring, int, int)
+bdestroy: int (bstring)
+become_root: void (void)
+bfindreplace: int (bstring, const_bstring, const_bstring, int)
+bfindreplacecaseless: int (bstring, const_bstring, const_bstring, int)
+bformat: bstring (const char *, ...)
+bformata: int (bstring, const char *, ...)
+bfromcstr: bstring (const char *)
+bfromcstralloc: bstring (int, const char *)
+bgetsa: int (bstring, bNgetc, void *, char)
+bgetstream: bstring (bNgetc, void *, char)
+binchr: int (const_bstring, int, const_bstring)
+binchrr: int (const_bstring, int, const_bstring)
+binsert: int (bstring, int, const_bstring, unsigned char)
+binsertch: int (bstring, int, int, unsigned char)
+binstr: int (const_bstring, int, const_bstring)
+binstrcaseless: int (const_bstring, int, const_bstring)
+binstrr: int (const_bstring, int, const_bstring)
+binstrrcaseless: int (const_bstring, int, const_bstring)
+biseq: int (const_bstring, const_bstring)
+biseqcaseless: int (const_bstring, const_bstring)
+biseqcstr: int (const_bstring, const char *)
+biseqcstrcaseless: int (const_bstring, const char *)
+bisstemeqblk: int (const_bstring, const void *, int)
+bisstemeqcaselessblk: int (const_bstring, const void *, int)
+bjoin: bstring (const struct bstrList *, const_bstring)
+bjoinInv: bstring (const struct bstrList *, const_bstring)
+blk2bstr: bstring (const void *, int)
+bltrimws: int (bstring)
+bmidstr: bstring (const_bstring, int, int)
+bninchr: int (const_bstring, int, const_bstring)
+bninchrr: int (const_bstring, int, const_bstring)
+bpattern: int (bstring, int)
+bread: bstring (bNread, void *)
+breada: int (bstring, bNread, void *)
+brefcstr: bstring (char *)
+breplace: int (bstring, int, int, const_bstring, unsigned char)
+brtrimws: int (bstring)
+bsbufflength: int (struct bStream *, int)
+bsclose: void *(struct bStream *)
+bseof: int (const struct bStream *)
+bsetstr: int (bstring, int, const_bstring, unsigned char)
+bsopen: struct bStream *(bNread, void *)
+bspeek: int (bstring, const struct bStream *)
+bsplit: struct bstrList *(const_bstring, unsigned char)
+bsplitcb: int (const_bstring, unsigned char, int, int (*)(void *, int, int), void *)
+bsplits: struct bstrList *(const_bstring, const_bstring)
+bsplitscb: int (const_bstring, const_bstring, int, int (*)(void *, int, int), void *)
+bsplitstr: struct bstrList *(const_bstring, const_bstring)
+bsplitstrcb: int (const_bstring, const_bstring, int, int (*)(void *, int, int), void *)
+bsread: int (bstring, struct bStream *, int)
+bsreada: int (bstring, struct bStream *, int)
+bsreadln: int (bstring, struct bStream *, char)
+bsreadlna: int (bstring, struct bStream *, char)
+bsreadlns: int (bstring, struct bStream *, const_bstring)
+bsreadlnsa: int (bstring, struct bStream *, const_bstring)
+bssplitscb: int (struct bStream *, const_bstring, int (*)(void *, int, const_bstring), void *)
+bssplitstrcb: int (struct bStream *, const_bstring, int (*)(void *, int, const_bstring), void *)
+bstr2cstr: char *(const_bstring, char)
+bstrchrp: int (const_bstring, int, int)
+bstrcmp: int (const_bstring, const_bstring)
+bstrcpy: bstring (const_bstring)
+bstricmp: int (const_bstring, const_bstring)
+bstrListAlloc: int (struct bstrList *, int)
+bstrListAllocMin: int (struct bstrList *, int)
+bstrListCreate: struct bstrList *(void)
+bstrListCreateMin: struct bstrList *(int)
+bstrListDestroy: int (struct bstrList *)
+bstrListPop: bstring (struct bstrList *)
+bstrListPush: int (struct bstrList *, bstring)
+bstrncmp: int (const_bstring, const_bstring, int)
+bstrnicmp: int (const_bstring, const_bstring, int)
+bstrrchrp: int (const_bstring, int, int)
+bsunread: int (struct bStream *, const_bstring)
+btolower: int (bstring)
+btoupper: int (bstring)
+btrimws: int (bstring)
+btrunc: int (bstring, int)
+bunrefcstr: int (bstring)
+bvcformata: int (bstring, int, const char *, struct __va_list_tag *)
+charset_decompose: size_t (charset_t, char *, size_t, char *, size_t)
+charset_mac_centraleurope: {name = "MAC_CENTRALEUROPE", kTextEncoding = 29, pull = <mac_centraleurope_pull>, push = <mac_centraleurope_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_chinese_simp: {name = "MAC_CHINESE_SIMP", kTextEncoding = 25, pull = <mac_chinese_simp_pull>, push = <mac_chinese_simp_push>, flags = 85, iname = "EUC-CN", prev = 0x0, next = 0x0}
+charset_mac_chinese_trad: {name = "MAC_CHINESE_TRAD", kTextEncoding = 2, pull = <mac_chinese_trad_pull>, push = <mac_chinese_trad_push>, flags = 85, iname = "BIG-5", prev = 0x0, next = 0x0}
+charset_mac_cyrillic: {name = "MAC_CYRILLIC", kTextEncoding = 7, pull = <mac_cyrillic_pull>, push = <mac_cyrillic_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_greek: {name = "MAC_GREEK", kTextEncoding = 6, pull = <mac_greek_pull>, push = <mac_greek_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_hebrew: {name = "MAC_HEBREW", kTextEncoding = 5, pull = <mac_hebrew_pull>, push = <mac_hebrew_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_japanese: {name = "MAC_JAPANESE", kTextEncoding = 1, pull = <mac_japanese_pull>, push = <mac_japanese_push>, flags = 85, iname = "SHIFT_JIS", prev = 0x0, next = 0x0}
+charset_mac_korean: {name = "MAC_KOREAN", kTextEncoding = 3, pull = <mac_korean_pull>, push = <mac_korean_push>, flags = 85, iname = "EUC-KR", prev = 0x0, next = 0x0}
+charset_mac_roman: {name = "MAC_ROMAN", kTextEncoding = 0, pull = <mac_roman_pull>, push = <mac_roman_push>, flags = 21, iname = 0x0, prev = 0x0, next = 0x0}
+charset_mac_turkish: {name = "MAC_TURKISH", kTextEncoding = 35, pull = <mac_turkish_pull>, push = <mac_turkish_push>, flags = 17, iname = 0x0, prev = 0x0, next = 0x0}
+charset_precompose: size_t (charset_t, char *, size_t, char *, size_t)
+charset_strlower: size_t (charset_t, const char *, size_t, char *, size_t)
+charset_strupper: size_t (charset_t, const char *, size_t, char *, size_t)
+charset_to_ucs2_allocate: size_t (charset_t, uint16_t **, const char *)
+charset_to_utf8_allocate: size_t (charset_t, char **, const char *)
+charset_utf8: {name = "UTF8", kTextEncoding = 134217987, pull = <utf8_pull>, push = <utf8_push>, flags = 22, iname = 0x0, prev = 0x0, next = 0x0}
+charset_utf8_mac: {name = "UTF8-MAC", kTextEncoding = 134217987, pull = <utf8_pull>, push = <utf8_push>, flags = 27, iname = 0x0, prev = 0x0, next = 0x0}
+check_lockfile: int (const char *, const char *)
+cjk_char_pull: size_t (uint16_t, uint16_t *, const uint32_t *)
+cjk_char_push: size_t (uint16_t, uint8_t *)
+cjk_compose: uint16_t (uint16_t, uint16_t, const uint32_t *, size_t)
+cjk_compose_seq: uint16_t (const uint16_t *, size_t *, const uint32_t *, size_t)
+cjk_generic_pull: size_t (size_t (*)(uint16_t *, const uint8_t *, size_t *), void *, char **, size_t *, char **, size_t *)
+cjk_generic_push: size_t (size_t (*)(uint8_t *, const uint16_t *, size_t *), void *, char **, size_t *, char **, size_t *)
+cjk_lookup: uint16_t (uint16_t, const cjk_index_t *, const uint16_t *)
+cnid_add: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, const char *, const size_t, cnid_t)
+cnid_close: void (struct _cnid_db *)
+cnid_dbd_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_dbd_close: void (struct _cnid_db *)
+cnid_dbd_delete: int (struct _cnid_db *, const cnid_t)
+cnid_dbd_find: int (struct _cnid_db *, const char *, size_t, void *, size_t)
+cnid_dbd_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_dbd_getstamp: int (struct _cnid_db *, void *, const size_t)
+cnid_dbd_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_dbd_module: {name = "dbd", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 0}
+cnid_dbd_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_dbd_rebuild_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_dbd_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_dbd_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_delete: int (struct _cnid_db *, cnid_t)
+cnid_find: int (struct _cnid_db *, const char *, size_t, void *, size_t)
+cnid_get: cnid_t (struct _cnid_db *, const cnid_t, char *, const size_t)
+cnid_getstamp: int (struct _cnid_db *, void *, const size_t)
+cnid_init: void (void)
+cnid_last_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_last_close: void (struct _cnid_db *)
+cnid_last_delete: int (struct _cnid_db *, const cnid_t)
+cnid_last_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_last_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_last_module: {name = "last", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 0}
+cnid_last_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_last_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_last_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_lookup: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, char *, const size_t)
+cnid_open: struct _cnid_db *(const char *, mode_t, char *, int, const char *, const char *)
+cnid_rebuild_add: cnid_t (struct _cnid_db *, const struct stat *, const cnid_t, char *, const size_t, cnid_t)
+cnid_register: void (struct _cnid_module *)
+cnid_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_tdb_add: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t, cnid_t)
+cnid_tdb_close: void (struct _cnid_db *)
+cnid_tdb_delete: int (struct _cnid_db *, const cnid_t)
+cnid_tdb_get: cnid_t (struct _cnid_db *, cnid_t, const char *, size_t)
+cnid_tdb_lookup: cnid_t (struct _cnid_db *, const struct stat *, cnid_t, const char *, size_t)
+cnid_tdb_module: {name = "tdb", db_list = {next = 0x0, prev = 0x0}, cnid_open = 0, flags = 12}
+cnid_tdb_open: struct _cnid_db *(struct cnid_open_args *)
+cnid_tdb_resolve: char *(struct _cnid_db *, cnid_t *, void *, size_t)
+cnid_tdb_update: int (struct _cnid_db *, cnid_t, const struct stat *, cnid_t, const char *, size_t)
+cnid_update: int (struct _cnid_db *, const cnid_t, const struct stat *, const cnid_t, char *, const size_t)
+compare_ip: int (const struct sockaddr *, const struct sockaddr *)
+convert_charset: size_t (charset_t, charset_t, charset_t, const char *, size_t, char *, size_t, uint16_t *)
+convert_string: size_t (charset_t, charset_t, const void *, size_t, void *, size_t)
+convert_string_allocate: size_t (charset_t, charset_t, const void *, size_t, char **)
+copy_ea: int (const char *, int, const char *, const char *, mode_t)
+copy_file: int (int, const char *, const char *, mode_t)
+copy_file_fd: int (int, int)
+copy_fork: int (int, struct adouble *, struct adouble *)
+create_lockfile: int (const char *, const char *)
+daemonize: int (int, int)
+decompose_w: size_t (uint16_t *, size_t, uint16_t *, size_t *)
+deny_severity: 3
+dequeue: void *(q_t *)
+_diacasemap: {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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 231, 203, 229, 128, 204, 129, 130, 131, 233, 230, 232, 234, 237, 235, 236, 132, 238, 241, 239, 133, 205, 242, 244, 243, 134, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 198, 183, 184, 184, 186, 187, 188, 189, 174, 175, 192, 193, 194, 195, 196, 197, 198, 199...}
+_dialowermap: {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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 138, 140, 141, 142, 150, 154, 159, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 132, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 190, 191, 176, 177, 178, 179, 180, 181, 198, 183, 185, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199...}
+dictionary_del: void (dictionary *)
+dictionary_dump: void (dictionary *, FILE *)
+dictionary_get: const char *(const dictionary *, const char *, const char *, const char *)
+dictionary_hash: unsigned int (char *)
+dictionary_new: dictionary *(int)
+dictionary_set: int (dictionary *, char *, char *, char *)
+dictionary_unset: void (dictionary *, char *, char *)
+dir_rx_set: int (mode_t)
+dsi_attention: int (DSI *, AFPUserBytes)
+dsi_close: void (DSI *)
+dsi_cmdreply: int (DSI *, const int)
+dsi_disconnect: int (DSI *)
+dsi_getsession: int (DSI *, server_child *, int, afp_child_t **)
+dsi_getstatus: void (DSI *)
+dsi_init: DSI *(AFPObj *, const char *, const char *, const char *)
+dsi_opensession: void (DSI *)
+dsi_read: ssize_t (DSI *, void *, const size_t)
+dsi_readdone: void (DSI *)
+dsi_readinit: ssize_t (DSI *, void *, const size_t, const size_t, const int)
+dsi_stream_read: size_t (DSI *, void *, const size_t)
+dsi_stream_read_file: ssize_t (DSI *, const int, off_t, const size_t, const int)
+dsi_stream_receive: int (DSI *)
+dsi_stream_send: int (DSI *, void *, size_t)
+dsi_stream_write: ssize_t (DSI *, void *, const size_t, int)
+dsi_tcp_init: int (DSI *, const char *, const char *, const char *)
+dsi_tickle: int (DSI *)
+dsi_write: size_t (DSI *, void *, const size_t)
+dsi_writeflush: void (DSI *)
+dsi_writeinit: size_t (DSI *, void *, const size_t)
+ea_chmod_dir: int (const struct vol *, const char *, mode_t, struct stat *)
+ea_chmod_file: int (const struct vol *, const char *, mode_t, struct stat *)
+ea_chown: int (const struct vol *, const char *, uid_t, gid_t)
+ea_close: int (struct ea *)
+ea_copyfile: int (const struct vol *, int, const char *, const char *)
+ea_deletefile: int (const struct vol *, int, const char *)
+ea_open: int (const struct vol *, const char *, eaflags_t, struct ea *)
+ea_openat: int (const struct vol *, int, const char *, eaflags_t, struct ea *)
+ea_path: char *(const struct ea *, const char *, int)
+ea_renamefile: int (const struct vol *, int, const char *, const char *)
+enqueue: qnode_t *(q_t *, void *)
+fault_setup: void (void (*)(void *))
+fdset_add_fd: void (int, struct pollfd **, struct polldata **, int *, int *, int, enum fdtype, void *)
+fdset_del_fd: void (struct pollfd **, struct polldata **, int *, int *, int)
+find_charset_functions: struct charset_functions *(const char *)
+_fini: <text variable, no debug info>
+freeifacelist: void (char **)
+fullpathname: const char *(const char *)
+getcwdpath: const char *(void)
+get_eacontent: int (const struct vol *, char *, size_t *, const char *, int, const char *, int)
+get_easize: int (const struct vol *, char *, size_t *, const char *, int, const char *)
+getifacelist: char **(void)
+getip_port: unsigned int (const struct sockaddr *)
+getip_string: const char *(const struct sockaddr *)
+getnamefromuuid: int (const uuidp_t, char **, uuidtype_t *)
+getuuidfromname: int (const char *, uuidtype_t, unsigned char *)
+getvolbyname: struct vol *(const char *)
+getvolbypath: struct vol *(AFPObj *, const char *)
+getvolbyvid: struct vol *(const uint16_t)
+getvolumes: struct vol *(void)
+gmem: int (gid_t, int, gid_t *)
+iniparser_dump: void (const dictionary *, FILE *)
+iniparser_dump_ini: void (const dictionary *, FILE *)
+iniparser_find_entry: int (const dictionary *, const char *)
+iniparser_freedict: void (dictionary *)
+iniparser_getboolean: int (const dictionary *, const char *, const char *, int)
+iniparser_getdouble: double (const dictionary *, const char *, const char *, double)
+iniparser_getint: int (const dictionary *, const char *, const char *, int)
+iniparser_getnsec: int (const dictionary *)
+iniparser_getsecname: const char *(const dictionary *, int)
+iniparser_getstrdup: char *(const dictionary *, const char *, const char *, const char *)
+iniparser_getstring: const char *(const dictionary *, const char *, const char *, const char *)
+iniparser_load: dictionary *(const char *)
+iniparser_set: int (dictionary *, char *, char *, char *)
+iniparser_unset: void (dictionary *, char *, char *)
+_init: <text variable, no debug info>
+init_iconv: void (void)
+initvol_vfs: void (struct vol *)
+ipc_child_write: int (int, uint16_t, int, void *)
+ipc_client_uds: int (const char *)
+ipc_server_read: int (server_child *, int)
+ipc_server_uds: int (const char *)
+islower_sp: int (uint32_t)
+islower_w: int (uint16_t)
+isupper_sp: int (uint32_t)
+isupper_w: int (uint16_t)
+lchdir: int (const char *)
+ldap_auth_dn: 0x0
+ldap_auth_method: 0
+ldap_auth_pw: 0x0
+ldap_config_valid: 0
+ldap_getnamefromuuid: int (const char *, char **, uuidtype_t *)
+ldap_getuuidfromname: int (const char *, uuidtype_t, char **)
+ldap_group_attr: 0x0
+ldap_groupbase: 0x0
+ldap_groupscope: 0
+ldap_name_attr: 0x0
+ldap_prefs: {{pref = 0x0, name = "ldap server", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap auth method", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap auth dn", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap auth pw", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap userbase", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap userscope", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap groupbase", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap groupscope", strorint = 1, intfromarray = 1, valid = -1}, {pref = 0x0, name = "ldap uuid attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap uuid string", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = "ldap name attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap group attr", strorint = 0, intfromarray = 0, valid = -1}, {pref = 0x0, name = "ldap uid attr", strorint = 0, intfromarray = 0, valid = 0}, {pref = 0x0, name = 0x0, strorint = 0, intfromarray = 0, valid = -1}}
+ldap_server: 0x0
+ldap_uid_attr: 0x0
+ldap_userbase: 0x0
+ldap_userscope: 0
+ldap_uuid_attr: 0x0
+ldap_uuid_string: 0x0
+list_eas: int (const struct vol *, char *, size_t *, const char *, int)
+load_charset: int (struct vol *)
+load_volumes: int (AFPObj *, void (*)(const AFPObj *, struct vol *))
+localuuid_from_id: void (unsigned char *, uuidtype_t, unsigned int)
+lock_reg: int (int, int, int, off_t, int, off_t)
+log_config: {inited = false, syslog_opened = false, console = false, processname = '\0' <repeats 15 times>, syslog_facility = 0, syslog_display_options = 0}
+lstatat: int (int, const char *, struct stat *)
+make_log_entry: void (enum loglevels, enum logtypes, const char *, int, char *, ...)
+make_tdb_data: unsigned char *(uint32_t, const struct stat *, const cnid_t, const char *, const size_t)
+mb_generic_pull: size_t (int (*)(uint16_t *, const unsigned char *), void *, char **, size_t *, char **, size_t *)
+mb_generic_push: size_t (int (*)(unsigned char *, uint16_t), void *, char **, size_t *, char **, size_t *)
+netatalk_panic: void (const char *)
+netatalk_rmdir: int (int, const char *)
+netatalk_rmdir_all_errors: int (int, const char *)
+netatalk_unlink: int (const char *)
+netatalk_unlinkat: int (int, const char *)
+nftw: int (const char *, nftw_func_t, dir_notification_func_t, int, int)
+opendirat: DIR *(int, const char *)
+openflags2logstr: const char *(int)
+posix_chmod: int (const char *, mode_t)
+posix_fchmod: int (int, mode_t)
+precompose_w: size_t (uint16_t *, size_t, uint16_t *, size_t *)
+prefs_array: {{pref = "ldap auth method", valuestring = "none", value = 0}, {pref = "ldap auth method", valuestring = "simple", value = 128}, {pref = "ldap auth method", valuestring = "sasl", value = 163}, {pref = "ldap userscope", valuestring = "base", value = 0}, {pref = "ldap userscope", valuestring = "one", value = 1}, {pref = "ldap userscope", valuestring = "sub", value = 2}, {pref = "ldap groupscope", valuestring = "base", value = 0}, {pref = "ldap groupscope", valuestring = "one", value = 1}, {pref = "ldap groupscope", valuestring = "sub", value = 2}, {pref = 0x0, valuestring = 0x0, value = 0}}
+prequeue: qnode_t *(q_t *, void *)
+queue_destroy: void (q_t *, void (*)(void *))
+queue_init: q_t *(void)
+randombytes: void (void *, int)
+readt: ssize_t (int, void *, const size_t, int, int)
+reconnect_ipc: int (AFPObj *)
+recv_fd: int (int, int)
+rel_path_in_vol: bstring (const char *, const char *)
+remove_acl_vfs: int (const char *)
+remove_ea: int (const struct vol *, const char *, const char *, int)
+run_cmd: int (const char *, char **)
+search_cachebyname: int (const char *, uuidtype_t *, unsigned char *)
+search_cachebyuuid: int (uuidp_t, char **, uuidtype_t *)
+send_fd: int (int, int)
+server_child_add: afp_child_t *(server_child *, int, pid_t, int)
+server_child_alloc: server_child *(const int, const int)
+server_child_free: void (server_child *)
+server_child_kill: void (server_child *, int, int)
+server_child_kill_one_by_id: void (server_child *, int, pid_t, uid_t, uint32_t, char *, uint32_t)
+server_child_remove: int (server_child *, const int, pid_t)
+server_child_setup: void (server_child *, const int, void (*)(const pid_t))
+server_child_transfer_session: int (server_child *, int, pid_t, uid_t, int, uint16_t)
+server_lock: pid_t (char *, char *, int)
+server_reset_signal: void (void)
+set_charset_name: int (charset_t, const char *)
+set_ea: int (const struct vol *, const char *, const char *, const char *, size_t, int)
+setfilmode: int (const char *, mode_t, struct stat *, mode_t)
+setnonblock: int (int, int)
+set_processname: void (const char *)
+setuplog: void (const char *, const char *)
+statat: int (int, const char *, struct stat *)
+strcasechr_sp: uint16_t *(const uint16_t *, uint32_t)
+strcasechr_w: uint16_t *(const uint16_t *, uint16_t)
+strcasecmp_w: int (const uint16_t *, const uint16_t *)
+strcasestr_w: uint16_t *(const uint16_t *, const uint16_t *)
+strcat_w: uint16_t *(uint16_t *, const uint16_t *)
+strchr_w: uint16_t *(const uint16_t *, uint16_t)
+strcmp_w: int (const uint16_t *, const uint16_t *)
+strdiacasecmp: int (const char *, const char *)
+strdup_w: uint16_t *(const uint16_t *)
+stripped_slashes_basename: char *(char *)
+strlcat: size_t (char *, const char *, size_t)
+strlcpy: size_t (char *, const char *, size_t)
+strlen_w: size_t (const uint16_t *)
+strlower_w: int (uint16_t *)
+strncasecmp_w: int (const uint16_t *, const uint16_t *, size_t)
+strncat_w: uint16_t *(uint16_t *, const uint16_t *, const size_t)
+strncmp_w: int (const uint16_t *, const uint16_t *, size_t)
+strncpy_w: uint16_t *(uint16_t *, const uint16_t *, const size_t)
+strndiacasecmp: int (const char *, const char *, size_t)
+strndup_w: uint16_t *(const uint16_t *, size_t)
+strnlen_w: size_t (const uint16_t *, size_t)
+strstr_w: uint16_t *(const uint16_t *, const uint16_t *)
+strupper_w: int (uint16_t *)
+sys_ea_copyfile: int (const struct vol *, int, const char *, const char *)
+sys_fgetxattr: ssize_t (int, const char *, void *, size_t)
+sys_fsetxattr: int (int, const char *, const void *, size_t, int)
+sys_ftruncate: int (int, off_t)
+sys_get_eacontent: int (const struct vol *, char *, size_t *, const char *, int, const char *, int)
+sys_get_easize: int (const struct vol *, char *, size_t *, const char *, int, const char *)
+sys_getxattr: ssize_t (const char *, const char *, void *, size_t)
+sys_getxattrfd: int (int, const char *, int, ...)
+sys_lgetxattr: ssize_t (const char *, const char *, void *, size_t)
+sys_list_eas: int (const struct vol *, char *, size_t *, const char *, int)
+sys_listxattr: ssize_t (const char *, char *, size_t)
+sys_llistxattr: ssize_t (const char *, char *, size_t)
+sys_lremovexattr: int (const char *, const char *)
+sys_lsetxattr: int (const char *, const char *, const void *, size_t, int)
+sys_remove_ea: int (const struct vol *, const char *, const char *, int)
+sys_removexattr: int (const char *, const char *)
+sys_sendfile: ssize_t (int, int, off_t *, size_t)
+sys_set_ea: int (const struct vol *, const char *, const char *, const char *, size_t, int)
+sys_setxattr: int (const char *, const char *, const void *, size_t, int)
+tdb_add_flags: void (struct tdb_context *, unsigned int)
+tdb_allocate: tdb_off_t (struct tdb_context *, tdb_len_t, struct tdb_record *)
+tdb_alloc_read: unsigned char *(struct tdb_context *, tdb_off_t, tdb_len_t)
+tdb_append: int (struct tdb_context *, TDB_DATA, TDB_DATA)
+tdb_brlock: int (struct tdb_context *, tdb_off_t, int, int, int, size_t)
+tdb_brlock_upgrade: int (struct tdb_context *, tdb_off_t, size_t)
+tdb_chainlock: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_mark: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_nonblock: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_read: int (struct tdb_context *, TDB_DATA)
+tdb_chainlock_unmark: int (struct tdb_context *, TDB_DATA)
+tdb_chainunlock: int (struct tdb_context *, TDB_DATA)
+tdb_chainunlock_read: int (struct tdb_context *, TDB_DATA)
+tdb_check: int (struct tdb_context *, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_close: int (struct tdb_context *)
+tdb_convert: void *(void *, uint32_t)
+tdb_delete: int (struct tdb_context *, TDB_DATA)
+tdb_do_delete: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_dump_all: void (struct tdb_context *)
+tdb_enable_seqnum: void (struct tdb_context *)
+tdb_error: enum TDB_ERROR (struct tdb_context *)
+tdb_errorstr: const char *(struct tdb_context *)
+tdb_exists: int (struct tdb_context *, TDB_DATA)
+tdb_expand: int (struct tdb_context *, tdb_off_t)
+tdb_fd: int (struct tdb_context *)
+tdb_fetch: TDB_DATA (struct tdb_context *, TDB_DATA)
+tdb_find_lock_hash: tdb_off_t (struct tdb_context *, TDB_DATA, uint32_t, int, struct tdb_record *)
+tdb_firstkey: TDB_DATA (struct tdb_context *)
+tdb_free: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_freelist_size: int (struct tdb_context *)
+tdb_get_flags: int (struct tdb_context *)
+tdb_get_logging_private: void *(struct tdb_context *)
+tdb_get_seqnum: int (struct tdb_context *)
+tdb_hash_size: int (struct tdb_context *)
+tdb_increment_seqnum_nonblock: void (struct tdb_context *)
+tdb_io_init: void (struct tdb_context *)
+tdb_lock: int (struct tdb_context *, int, int)
+tdb_lockall: int (struct tdb_context *)
+tdb_lockall_mark: int (struct tdb_context *)
+tdb_lockall_nonblock: int (struct tdb_context *)
+tdb_lockall_read: int (struct tdb_context *)
+tdb_lockall_read_nonblock: int (struct tdb_context *)
+tdb_lockall_unmark: int (struct tdb_context *)
+tdb_lock_nonblock: int (struct tdb_context *, int, int)
+tdb_lock_record: int (struct tdb_context *, tdb_off_t)
+tdb_log_fn: tdb_log_func (struct tdb_context *)
+tdb_map_size: size_t (struct tdb_context *)
+tdb_mmap: void (struct tdb_context *)
+tdb_munmap: int (struct tdb_context *)
+tdb_name: const char *(struct tdb_context *)
+tdb_nextkey: TDB_DATA (struct tdb_context *, TDB_DATA)
+tdb_null: {dptr = 0x0, dsize = 0}
+tdb_ofs_read: int (struct tdb_context *, tdb_off_t, tdb_off_t *)
+tdb_ofs_write: int (struct tdb_context *, tdb_off_t, tdb_off_t *)
+tdb_open: struct tdb_context *(const char *, int, int, int, mode_t)
+tdb_open_ex: struct tdb_context *(const char *, int, int, int, mode_t, const struct tdb_logging_context *, tdb_hash_func)
+tdb_parse_data: int (struct tdb_context *, TDB_DATA, tdb_off_t, tdb_len_t, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_parse_record: int (struct tdb_context *, TDB_DATA, int (*)(TDB_DATA, TDB_DATA, void *), void *)
+tdb_printfreelist: int (struct tdb_context *)
+tdb_rec_free_read: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_rec_read: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_rec_write: int (struct tdb_context *, tdb_off_t, struct tdb_record *)
+tdb_remove_flags: void (struct tdb_context *, unsigned int)
+tdb_reopen: int (struct tdb_context *)
+tdb_reopen_all: int (int)
+tdb_repack: int (struct tdb_context *)
+tdb_setalarm_sigptr: void (struct tdb_context *, volatile sig_atomic_t *)
+tdb_set_logging_function: void (struct tdb_context *, const struct tdb_logging_context *)
+tdb_set_max_dead: void (struct tdb_context *, int)
+tdb_store: int (struct tdb_context *, TDB_DATA, TDB_DATA, int)
+_tdb_transaction_cancel: int (struct tdb_context *)
+tdb_transaction_cancel: int (struct tdb_context *)
+tdb_transaction_commit: int (struct tdb_context *)
+tdb_transaction_lock: int (struct tdb_context *, int)
+tdb_transaction_prepare_commit: int (struct tdb_context *)
+tdb_transaction_recover: int (struct tdb_context *)
+tdb_transaction_start: int (struct tdb_context *)
+tdb_transaction_unlock: int (struct tdb_context *)
+tdb_traverse: int (struct tdb_context *, tdb_traverse_func, void *)
+tdb_traverse_read: int (struct tdb_context *, tdb_traverse_func, void *)
+tdb_unlock: int (struct tdb_context *, int, int)
+tdb_unlockall: int (struct tdb_context *)
+tdb_unlockall_read: int (struct tdb_context *)
+tdb_unlock_record: int (struct tdb_context *, tdb_off_t)
+tdb_validate_freelist: int (struct tdb_context *, int *)
+tdb_wipe_all: int (struct tdb_context *)
+tdb_write_lock_record: int (struct tdb_context *, tdb_off_t)
+tdb_write_unlock_record: int (struct tdb_context *, tdb_off_t)
+tolower_sp: uint32_t (uint32_t)
+tolower_w: uint16_t (uint16_t)
+toupper_sp: uint32_t (uint32_t)
+toupper_w: uint16_t (uint16_t)
+type_configs: {{set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}, {set = false, syslog = false, fd = -1, level = log_none, display_options = 0}}
+ucs2_to_charset: size_t (charset_t, const uint16_t *, char *, size_t)
+ucs2_to_charset_allocate: size_t (charset_t, char **, const uint16_t *)
+unbecome_root: void (void)
+unix_rename: int (int, const char *, int, const char *)
+unix_strlower: size_t (const char *, size_t, char *, size_t)
+unix_strupper: size_t (const char *, size_t, char *, size_t)
+unload_volumes: void (AFPObj *)
+utf8_charlen: size_t (char *)
+utf8_decompose: size_t (char *, size_t, char *, size_t)
+utf8_precompose: size_t (char *, size_t, char *, size_t)
+utf8_strlen_validate: size_t (char *)
+utf8_strlower: size_t (const char *, size_t, char *, size_t)
+utf8_strupper: size_t (const char *, size_t, char *, size_t)
+utf8_to_charset_allocate: size_t (charset_t, char **, const char *)
+uuid_bin2string: const char *(const unsigned char *)
+uuidcache_dump: void (void)
+uuid_string2bin: void (const char *, unsigned char *)
+uuidtype: {"", "USER", "GROUP", "LOCAL"}
+volume_free: void (struct vol *)
+volume_unlink: void (struct vol *)
+writet: ssize_t (int, void *, const size_t, int, int)
diff --git a/libatalk/locking/.gitignore b/libatalk/locking/.gitignore
new file mode 100644 (file)
index 0000000..604ff3c
--- /dev/null
@@ -0,0 +1,7 @@
+Makefile
+Makefile.in
+*.lo
+*.la
+.deps
+.libs
+
diff --git a/libatalk/locking/Makefile.am b/libatalk/locking/Makefile.am
new file mode 100644 (file)
index 0000000..866510c
--- /dev/null
@@ -0,0 +1,4 @@
+# Makefile.am for libatalk/locking/
+
+noinst_LTLIBRARIES = liblocking.la
+liblocking_la_SOURCES = locking.c
diff --git a/libatalk/locking/locking.c b/libatalk/locking/locking.c
new file mode 100644 (file)
index 0000000..db0b513
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2011 Frank Lahm
+ * All Rights Reserved.  See COPYRIGHT.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include <atalk/logger.h>
+#include <atalk/errchk.h>
+#include <atalk/locking.h>
+#include <atalk/cnid.h>
+#include <atalk/paths.h>
+
+/***************************************************************************
+ * structures and defines
+ ***************************************************************************/
+
+#define LOCKTABLE_PATH         "/tmp/netatalk-afp-locks.tdb" 
+
+/* 
+ * Struct for building the the main database of file locks.
+ * vid + cnid build the primary key for database access.
+ */
+typedef struct afp_lock {
+    /* Keys */
+    uint32_t l_vid;
+    cnid_t   l_cnid;
+    uint64_t l_dev;
+    uint64_t l_ino;
+
+    /* pid holding the lock, also secondary key */
+    pid_t    l_pid;
+
+    /* Refcounting access and deny modes */
+    uint16_t l_amode_r;
+    uint16_t l_amode_w;
+    uint16_t l_dmode_r;
+    uint16_t l_dmode_w;
+} afp_lock_t;
+
+#define PACKED_AFP_LOCK_SIZE                 \
+    sizeof(((afp_lock_t *)0)->l_vid) +       \
+    sizeof(((afp_lock_t *)0)->l_cnid) +      \
+    sizeof(((afp_lock_t *)0)->l_dev) +       \
+    sizeof(((afp_lock_t *)0)->l_ino) +       \
+    sizeof(((afp_lock_t *)0)->l_pid) +       \
+    sizeof(((afp_lock_t *)0)->l_amode_r) +   \
+    sizeof(((afp_lock_t *)0)->l_amode_w) +   \
+    sizeof(((afp_lock_t *)0)->l_dmode_r) +   \
+    sizeof(((afp_lock_t *)0)->l_dmode_r)
+
+/***************************************************************************
+ * Data
+ ***************************************************************************/
+
+static struct smbdb_ctx *tdb;
+
+/***************************************************************************
+ * Private functions
+ ***************************************************************************/
+
+/***************************************************************************
+ * Public functions
+ ***************************************************************************/
+
+/*!
+ * Open locktable from path
+ */
+int locktable_init(const char *path)
+{
+    EC_INIT;
+
+//    EC_NULL_LOG(tdb = smb_share_mode_db_open(path));
+
+EC_CLEANUP:
+    EC_EXIT;
+}
+
diff --git a/libatalk/nbp/.gitignore b/libatalk/nbp/.gitignore
deleted file mode 100644 (file)
index aae291d..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Makefile
-Makefile.in
-*.lo
-*.la
-.deps
-.libs
-.gitignore
-nbp_lkup.o nbp_rgstr.o nbp_unrgstr.o nbp_util.o
diff --git a/libatalk/nbp/Makefile.am b/libatalk/nbp/Makefile.am
deleted file mode 100644 (file)
index 1a6404d..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-# Makefile.am for libatalk/nbp/
-
-noinst_LTLIBRARIES = libnbp.la
-
-libnbp_la_SOURCES = nbp_util.c nbp_lkup.c nbp_rgstr.c nbp_unrgstr.c
-
-noinst_HEADERS = nbp_conf.h
diff --git a/libatalk/nbp/nbp_conf.h b/libatalk/nbp/nbp_conf.h
deleted file mode 100644 (file)
index 66029a6..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * $Id: nbp_conf.h,v 1.3 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#ifndef NBP_CONF_H
-#define NBP_CONF_H 1
-
-#include <sys/cdefs.h>
-#include <atalk/nbp.h>
-
-extern char            nbp_send[ 1024 ];
-extern char            nbp_recv[ 1024 ];
-extern u_char          nbp_port;
-extern unsigned char    nbp_id;
-
-
-int nbp_parse (char *, struct nbpnve *, int);
-int nbp_match (struct nbpnve *, struct nbpnve *, int);
-
-#endif /* NBP_CONF_H */
diff --git a/libatalk/nbp/nbp_lkup.c b/libatalk/nbp/nbp_lkup.c
deleted file mode 100644 (file)
index 6a99126..0000000
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * $Id: nbp_lkup.c,v 1.5 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1997 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <errno.h>
-#include <signal.h>
-
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <netatalk/ddp.h>
-#include <atalk/compat.h>
-#include <atalk/nbp.h>
-#include <atalk/netddp.h>
-#include <atalk/ddp.h>
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif /* HAVE_NETDB_H */
-
-#include  "nbp_conf.h"
-
-/* FIXME/SOCKLEN_T: socklen_t is a unix98 feature. */
-#ifndef SOCKLEN_T
-#define SOCKLEN_T unsigned int
-#endif /* ! SOCKLEN_T */
-
-int nbp_lookup( const char *obj, const char *type, const char *zone, struct nbpnve *nn,
-    int                        nncnt,
-    const struct at_addr *ataddr)
-{
-    struct sockaddr_at addr, from;
-    struct timeval     tv, tv_begin, tv_end;
-    fd_set             fds;
-    struct nbpnve      nve;
-    struct nbphdr      nh;
-    struct nbptuple    nt;
-    struct servent     *se;
-    char               *data = nbp_send;
-    SOCKLEN_T          namelen;
-    int                        s, cnt, tries, sc, cc, i, c;
-
-    memset(&addr, 0, sizeof(addr));
-    memset(&from, 0, sizeof(from));
-    if (ataddr) 
-      memcpy(&addr.sat_addr, ataddr, sizeof(struct at_addr));
-    if ((s = netddp_open(&addr, &from)) < 0)
-      return -1;
-
-    *data++ = DDPTYPE_NBP;
-#ifdef MACOSX_SERVER
-    nh.nh_op = from.sat_addr.s_node ? NBPOP_BRRQ : NBPOP_LKUP;
-#else /* MACOSX_SERVER */
-    nh.nh_op = NBPOP_BRRQ;
-#endif /* MACOSX_SERVER */
-
-    nh.nh_cnt = 1;
-    nh.nh_id = ++nbp_id;
-    memcpy( data, &nh, SZ_NBPHDR );
-    data += SZ_NBPHDR;
-
-    memset(&nt, 0, sizeof(nt));
-    nt.nt_net = addr.sat_addr.s_net;
-    nt.nt_node = addr.sat_addr.s_node;
-    nt.nt_port = addr.sat_port;
-
-    memcpy( data, &nt, SZ_NBPTUPLE);
-    data += SZ_NBPTUPLE;
-
-    if ( obj ) {
-       if (( cc = strlen( obj )) > NBPSTRLEN ) goto lookup_err;
-       *data++ = cc;
-       memcpy( data, obj, cc );
-       data += cc;
-    } else {
-       *data++ = 1;
-       *data++ = '='; /* match anything */
-    }
-
-    if ( type ) {
-       if (( cc = strlen( type )) > NBPSTRLEN ) goto lookup_err;
-       *data++ = cc;
-       memcpy( data, type, cc );
-       data += cc;
-    } else {
-       *data++ = 1;
-       *data++ = '='; /* match anything */
-    }
-
-    if ( zone ) {
-       if (( cc = strlen( zone )) > NBPSTRLEN ) goto lookup_err;
-       *data++ = cc;
-       memcpy( data, zone, cc );
-       data += cc;
-    } else {
-       *data++ = 1;
-       *data++ = '*'; /* default zone */
-    }
-
-    if ( nbp_port == 0 ) {
-      if (( se = getservbyname( "nbp", "ddp" )) == NULL ) {
-                   nbp_port = 2;
-      } else {
-                   nbp_port = ntohs( se->s_port );
-      }
-    }
-
-#ifdef MACOSX_SERVER
-    if (from.sat_addr.s_node) {
-      memcpy(&addr.sat_addr, &from.sat_addr, sizeof(addr.sat_addr));
-    } else {
-      addr.sat_addr.s_net = ATADDR_ANYNET;
-      addr.sat_addr.s_node = ATADDR_BCAST;
-    }
-#endif /* MACOSX_SERVER */
-    addr.sat_port = nbp_port;
-
-    cnt = 0;
-    tries = 3;
-    sc = data - nbp_send;
-    while ( tries > 0 ) {
-       if ( netddp_sendto( s, nbp_send, sc, 0, (struct sockaddr *)&addr,
-               sizeof( struct sockaddr_at )) < 0 ) {
-           goto lookup_err;
-       }
-
-       tv.tv_sec = 2L;
-       tv.tv_usec = 0;
-
-       for (;;) {
-           FD_ZERO( &fds );
-           FD_SET( s, &fds );
-           if ( gettimeofday( &tv_begin, NULL ) < 0 ) {
-               goto lookup_err;
-           }
-           if (( c = select( s + 1, &fds, NULL, NULL, &tv )) < 0 ) {
-               goto lookup_err;
-           }
-           if ( c == 0 || FD_ISSET( s, &fds ) == 0 ) {
-               break;
-           }
-           if ( gettimeofday( &tv_end, NULL ) < 0 ) {
-               goto lookup_err;
-           }
-           if ( tv_begin.tv_usec > tv_end.tv_sec ) {
-               tv_end.tv_usec += 1000000;
-               tv_end.tv_sec -= 1;
-           }
-           if (( tv.tv_usec -= ( tv_end.tv_usec - tv_begin.tv_usec )) < 0 ) {
-               tv.tv_usec += 1000000;
-               tv.tv_sec -= 1;
-           }
-           if (( tv.tv_sec -= ( tv_end.tv_sec - tv_begin.tv_sec )) < 0 ) {
-               break;
-           }
-
-           namelen = sizeof( struct sockaddr_at );
-           if (( cc = netddp_recvfrom( s, nbp_recv, sizeof( nbp_recv ), 0,
-                   (struct sockaddr *)&from, &namelen )) < 0 ) {
-               goto lookup_err;
-           }
-
-           data = nbp_recv;
-           if ( *data++ != DDPTYPE_NBP ) {
-               continue;
-           }
-           cc--;
-
-           memcpy( &nh, data, SZ_NBPHDR );
-           data += SZ_NBPHDR;
-           if ( nh.nh_op != NBPOP_LKUPREPLY ) {
-               continue;
-           }
-           cc -= SZ_NBPHDR;
-
-           while (( i = nbp_parse( data, &nve, cc )) >= 0 ) {
-               data += cc - i;
-               cc = i;
-               /*
-                * Check to see if nve is already in nn. If not,
-                * put it in, and increment cnt.
-                */
-               for ( i = 0; i < cnt; i++ ) {
-                   if ( nbp_match( &nve, &nn[ i ],
-                           NBPMATCH_NOZONE|NBPMATCH_NOGLOB )) {
-                       break;
-                   }
-               }
-               if ( i == cnt ) {
-                   nn[ cnt++ ] = nve;
-               }
-               if ( cnt == nncnt ) {
-                   tries = 0;
-                   break;
-               }
-           }
-           if ( cnt == nncnt ) {
-               tries = 0;
-               break;
-           }
-       }
-       tries--;
-    }
-
-    netddp_close(s);
-    errno = 0;
-    return( cnt );
-
-lookup_err:
-    netddp_close(s);
-    return -1;
-}
diff --git a/libatalk/nbp/nbp_rgstr.c b/libatalk/nbp/nbp_rgstr.c
deleted file mode 100644 (file)
index d09e866..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * $Id: nbp_rgstr.c,v 1.6 2009-10-14 02:24:05 didg Exp $
- *
- * Copyright (c) 1990,1993 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <errno.h>
-#include <signal.h>
-
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <atalk/nbp.h>
-#include <atalk/ddp.h>
-#include <atalk/netddp.h>
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif /* HAVE_NETDB_H */
-#include  "nbp_conf.h"
-
-/* FIXME/SOCKLEN_T: socklen_t is a unix98 feature. */
-#ifndef SOCKLEN_T
-#define SOCKLEN_T unsigned int
-#endif /* ! SOCKLEN_T */
-
-int nbp_rgstr( struct sockaddr_at *sat, const char *obj, const char *type, const char *zone)
-{
-    struct sockaddr_at to;
-    struct nbpnve      nn;
-    struct nbphdr      nh;
-    struct nbptuple    nt;
-    struct timeval     timeout;
-    fd_set             readfd;
-    struct servent     *se;
-    char               *data;
-    int                        s, cc;
-    SOCKLEN_T          namelen;
-
-    if ( nbp_lookup( obj, type, zone, &nn, 1, &sat->sat_addr ) > 0 ) {
-        errno = EADDRINUSE;
-       return( -1 );
-    }
-
-    memset(&to, 0, sizeof(to));
-    if ((s = netddp_open(&to, NULL)) < 0)
-        return -1;
-
-    data = nbp_send;
-    *data++ = DDPTYPE_NBP;
-    nh.nh_op = NBPOP_RGSTR;
-    nh.nh_cnt = 1;
-    nh.nh_id = ++nbp_id;
-    memcpy( data, &nh, SZ_NBPHDR );
-    data += SZ_NBPHDR;
-
-    memset(&nt, 0, sizeof(nt));
-    nt.nt_net = sat->sat_addr.s_net;
-    nt.nt_node = sat->sat_addr.s_node;
-    nt.nt_port = sat->sat_port;
-    memcpy( data, &nt, SZ_NBPTUPLE);
-    data += SZ_NBPTUPLE;
-
-    if ( obj ) {
-       if (( cc = strlen( obj )) > NBPSTRLEN ) return( -1 );
-       *data++ = cc;
-       memcpy( data, obj, cc );
-       data += cc;
-    } else {
-       *data++ = 0;
-    }
-
-    if ( type ) {
-       if (( cc = strlen( type )) > NBPSTRLEN ) return( -1 );
-       *data++ = cc;
-       memcpy( data, type, cc );
-       data += cc;
-    } else {
-       *data++ = 0;
-    }
-
-    if ( zone ) {
-       if (( cc = strlen( zone )) > NBPSTRLEN ) return( -1 );
-       *data++ = cc;
-       memcpy( data, zone, cc );
-       data += cc;
-    } else {
-       *data++ = 1;
-       *data++ = '*'; /* default zone */
-    }
-
-    
-    if ( nbp_port == 0 ) {
-       if (( se = getservbyname( "nbp", "ddp" )) == NULL ) {
-           nbp_port = 2;
-       } else {
-           nbp_port = ntohs( se->s_port );
-       }
-    }
-    to.sat_port = nbp_port;
-
-    if ( netddp_sendto( s, nbp_send, data - nbp_send, 0, 
-                       (struct sockaddr *)&to,
-                       sizeof( struct sockaddr_at )) < 0 ) {
-        goto register_err;
-    }
-
-    FD_ZERO( &readfd );
-    FD_SET( s, &readfd );
-    timeout.tv_sec = 2;
-    timeout.tv_usec = 0;
-    if (( cc = select( s + 1, &readfd, NULL, NULL, &timeout )) < 0 ) {
-        goto register_err;
-    }
-    if ( cc == 0 ) {
-       errno = ETIMEDOUT;
-       goto register_err;
-    }
-
-    namelen = sizeof( struct sockaddr_at );
-    if (( cc = netddp_recvfrom( s, nbp_recv, sizeof( nbp_recv ), 0,
-                       (struct sockaddr *)&to, &namelen )) < 0 ) {
-        goto register_err;
-    }
-
-    netddp_close( s );
-
-    data = nbp_recv;
-    if ( *data++ != DDPTYPE_NBP ) {
-       return( -1 );
-    }
-    memcpy( &nh, data, SZ_NBPHDR );
-    if ( nh.nh_op != NBPOP_OK ) {
-        return -1;
-    }
-    return( 0 );
-
-register_err:
-    netddp_close(s);
-    return -1;
-}
diff --git a/libatalk/nbp/nbp_unrgstr.c b/libatalk/nbp/nbp_unrgstr.c
deleted file mode 100644 (file)
index b16497d..0000000
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * $Id: nbp_unrgstr.c,v 1.6 2009-10-14 02:24:05 didg Exp $
- *
- * Copyright (c) 1990,1997 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <errno.h>
-#include <signal.h>
-
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <atalk/nbp.h>
-#include <atalk/netddp.h>
-#include <atalk/ddp.h>
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif /* HAVE_NETDB_H */
-#include  "nbp_conf.h"
-
-/* FIXME/SOCKLEN_T: socklen_t is a unix98 feature. */
-#ifndef SOCKLEN_T
-#define SOCKLEN_T unsigned int
-#endif /* ! SOCKLEN_T */
-
-int nbp_unrgstr(const char *obj,const char *type,const char  *zone, const struct at_addr *addr)
-{
-    struct sockaddr_at to;
-    struct nbphdr      nh;
-    struct timeval     timeout;
-    fd_set             readfd;
-    struct servent     *se;
-    char               *data;
-    int                        s, cc;
-    SOCKLEN_T          namelen;
-
-
-    memset(&to, 0, sizeof(to));
-    if ((s = netddp_open(&to, NULL)) < 0)
-       return -1;
-
-    data = nbp_send;
-    *data++ = DDPTYPE_NBP;
-    nh.nh_op = NBPOP_UNRGSTR;
-    nh.nh_cnt = 1;
-    nh.nh_id = ++nbp_id;
-    memcpy( data, &nh, SZ_NBPHDR );
-    data += SZ_NBPHDR;
-
-    memset(data, 0, SZ_NBPTUPLE);
-    data += SZ_NBPTUPLE;
-
-    if ( obj ) {
-       if (( cc = strlen( obj )) > NBPSTRLEN ) return( -1 );
-       *data++ = cc;
-       memcpy( data, obj, cc );
-       data += cc;
-    } else {
-       *data++ = 0;
-    }
-
-    if ( type ) {
-       if (( cc = strlen( type )) > NBPSTRLEN ) return( -1 );
-       *data++ = cc;
-       memcpy( data, type, cc );
-       data += cc;
-    } else {
-       *data++ = 0;
-    }
-
-    if ( zone ) {
-       if (( cc = strlen( zone )) > NBPSTRLEN ) return( -1 );
-       *data++ = cc;
-       memcpy( data, zone, cc );
-       data += cc;
-    } else {
-       *data++ = 0;
-    }
-
-    memset( &to, 0, sizeof( struct sockaddr_at ));
-    to.sat_family = AF_APPLETALK;
-    if (addr) 
-      memcpy(&to.sat_addr, addr, sizeof(struct at_addr));
-#ifdef BSD4_4
-    to.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-
-    if ( nbp_port == 0 ) {
-       if (( se = getservbyname( "nbp", "ddp" )) == NULL ) {
-           nbp_port = 2;
-       } else {
-           nbp_port = ntohs( se->s_port );
-       }
-    }
-    to.sat_port = nbp_port;
-
-    if ( netddp_sendto( s, nbp_send, data - nbp_send, 0,
-                       (struct sockaddr *)&to,
-                       sizeof( struct sockaddr_at )) < 0 ) {
-        goto unregister_err;
-    }
-
-    FD_ZERO( &readfd );
-    FD_SET( s, &readfd );
-    timeout.tv_sec = 2;
-    timeout.tv_usec = 0;
-    if (( cc = select( s + 1, &readfd, NULL, NULL, &timeout )) < 0 ) {
-        goto unregister_err;
-    }
-    if ( cc == 0 ) {
-       errno = ETIMEDOUT;
-        goto unregister_err;
-    }
-
-    namelen = sizeof( struct sockaddr_at );
-    if (( cc = netddp_recvfrom( s, nbp_recv, sizeof( nbp_recv ), 0,
-                       (struct sockaddr *)&to, &namelen )) < 0 ) {
-        goto unregister_err;
-    }
-    netddp_close( s );
-
-    data = nbp_recv;
-    if ( *data++ != DDPTYPE_NBP ) {
-       return( -1 );
-    }
-    memcpy( &nh, data, SZ_NBPHDR );
-    if ( nh.nh_op != NBPOP_OK ) {
-       return( -1 );
-    }
-    return( 0 );
-
-unregister_err:
-    netddp_close(s);
-    return -1;
-}
diff --git a/libatalk/nbp/nbp_util.c b/libatalk/nbp/nbp_util.c
deleted file mode 100644 (file)
index 4cbea4b..0000000
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * $Id: nbp_util.c,v 1.5 2009-10-13 22:55:37 didg Exp $
- *
- * Copyright (c) 1990,1997 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <string.h>
-#include <signal.h>
-
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-
-#include <atalk/nbp.h>
-#include <atalk/ddp.h>
-#include <atalk/util.h>
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif /* HAVE_NETDB_H */
-
-#include  "nbp_conf.h"
-
-char           nbp_send[ 1024 ];
-char           nbp_recv[ 1024 ];
-u_char         nbp_port = 0;
-unsigned char   nbp_id = 0;
-
-int nbp_parse(char *data, struct nbpnve *nn, int len)
-{
-    struct nbptuple    nt;
-
-    memcpy( &nt, data, SZ_NBPTUPLE);
-    data += SZ_NBPTUPLE;
-    len -= SZ_NBPTUPLE;
-    if ( len < 0 ) {
-       return( -1 );
-    }
-
-#ifdef BSD4_4
-    nn->nn_sat.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    nn->nn_sat.sat_family = AF_APPLETALK;
-    nn->nn_sat.sat_addr.s_net = nt.nt_net;
-    nn->nn_sat.sat_addr.s_node = nt.nt_node;
-    nn->nn_sat.sat_port = nt.nt_port;
-
-    nn->nn_objlen = *data++;
-    len -= nn->nn_objlen + 1;
-    if ( len < 0 ) {
-       return( -1 );
-    }
-    if ( nn->nn_objlen > NBPSTRLEN ) {
-       return( -1 );
-    }
-    memcpy( nn->nn_obj, data, nn->nn_objlen );
-    data += nn->nn_objlen;
-
-    nn->nn_typelen = *data++;
-    len -= nn->nn_typelen + 1;
-    if ( len < 0 ) {
-       return( -1 );
-    }
-    if ( nn->nn_typelen > NBPSTRLEN ) {
-       return( 1 );
-    }
-    memcpy( nn->nn_type, data, nn->nn_typelen );
-
-    data += nn->nn_typelen;
-    nn->nn_zonelen = *data++;
-    len -= nn->nn_zonelen + 1;
-    if ( len < 0 ) {
-       return( -1 );
-    }
-    if ( nn->nn_zonelen > NBPSTRLEN ) {
-       return( 1 );
-    }
-    memcpy( nn->nn_zone, data, nn->nn_zonelen );
-
-    return( len );
-}
-
-#define NBPM_OBJ       (1<<1)
-#define NBPM_TYPE      (1<<2)
-#define NBPM_ZONE      (1<<3)
-
-int nbp_match(struct nbpnve *n1, struct nbpnve *n2, int flags)
-{
-    int                        match = 0;
-
-    if ( flags & NBPMATCH_NOZONE ) {
-       match |= NBPM_ZONE;
-    }
-
-    if ( !( flags & NBPMATCH_NOGLOB )) {
-       if ( n1->nn_objlen == 1 && n1->nn_obj[0] == '=' ) {
-           match |= NBPM_OBJ;
-       }
-       if ( n1->nn_typelen == 1 && n1->nn_type[0] == '=' ) {
-           match |= NBPM_TYPE;
-       }
-    }
-
-    if ( !( match & NBPM_OBJ )) {
-       if ( n1->nn_objlen != n2->nn_objlen ||
-               strndiacasecmp( n1->nn_obj, n2->nn_obj, n1->nn_objlen )) {
-           return( 0 );
-       }
-    }
-    if ( !( match & NBPM_TYPE )) {
-       if ( n1->nn_typelen != n2->nn_typelen ||
-               strndiacasecmp( n1->nn_type, n2->nn_type, n1->nn_typelen )) {
-           return( 0 );
-       }
-    }
-    if ( !( match & NBPM_ZONE )) {
-       if ( n1->nn_zonelen != n2->nn_zonelen ||
-               strndiacasecmp( n1->nn_zone, n2->nn_zone, n1->nn_zonelen )) {
-           return( 0 );
-       }
-    }
-
-    return( 1 );
-}
-
-int nbp_name(const char  *name, char **objp,char **typep,char **zonep)
-{
-    static char        buf[ 32 + 1 + 32 + 1 + 32 + 1 ];
-    char       *p;
-
-    if ( name ) {
-       if ( strlen( name ) + 1 > sizeof( buf )) {
-           return( -1 );
-       }
-       strcpy( buf, name );
-
-       if (( p = strrchr( buf, '@' )) != NULL ) {
-           *p++ = '\0';
-           *zonep = p;
-       }
-       if (( p = strrchr( buf, ':' )) != NULL ) {
-           *p++ = '\0';
-           *typep = p;
-       }
-       if ( *buf != '\0' ) {
-           *objp = buf;
-       }
-    }
-
-    return( 0 );
-}
diff --git a/libatalk/netddp/.gitignore b/libatalk/netddp/.gitignore
deleted file mode 100644 (file)
index b8c114c..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Makefile
-Makefile.in
-*.lo
-*.la
-.deps
-.libs
-.gitignore
-netddp_open.o netddp_recvfrom.o netddp_sendto.o
diff --git a/libatalk/netddp/Makefile.am b/libatalk/netddp/Makefile.am
deleted file mode 100644 (file)
index 9f62087..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# Makefile.am for libatalk/netddp/
-
-noinst_LTLIBRARIES = libnetddp.la
-
-libnetddp_la_SOURCES = netddp_open.c netddp_sendto.c netddp_recvfrom.c
diff --git a/libatalk/netddp/netddp_open.c b/libatalk/netddp/netddp_open.c
deleted file mode 100644 (file)
index 20ab8ef..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/* 
- * $Id: netddp_open.c,v 1.9 2005-04-28 20:50:02 bfernhomberg Exp $
- *
- * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * open a ddp socket and return the port and address assigned. return
- * various address info if requested as well.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <stdio.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#ifdef MACOSX_SERVER
-#include <netat/appletalk.h>
-#include <netat/ddp.h>
-#endif /* MACOSX_SERVER */
-
-#include <netatalk/at.h>
-#include <atalk/netddp.h>
-
-int netddp_open(struct sockaddr_at *addr, struct sockaddr_at *bridge)
-{
-
-#ifdef NO_DDP
-    return -1;
-#else /* !NO_DDP */
-
-    int s;
-
-#ifdef MACOSX_SERVER
-    at_inet_t address, baddress;
-
-    if ((s = ddp_open(addr ? &addr->sat_port : NULL)) < 0)
-        return -1;
-
-    if (!addr)
-      return s;
-
-    if (rtmp_netinfo(s, &address, &baddress) < 0) {
-        ddp_close(s);
-       return -1;
-    }
-    
-    memcpy(&addr->sat_addr.s_net, &address.net, sizeof(addr->sat_addr.s_net));
-    addr->sat_addr.s_node = address.node;
-    addr->sat_port = address.socket;
-    if (bridge) {
-      memcpy(&bridge->sat_addr.s_net, &baddress.net, 
-            sizeof(bridge->sat_addr.s_net));
-      bridge->sat_addr.s_node = baddress.node;
-      bridge->sat_port = baddress.socket;
-    }
-#else /* MACOSX_SERVER */
-    socklen_t len;
-
-    if ((s = socket( AF_APPLETALK, SOCK_DGRAM, 0 )) < 0) 
-       return -1;
-    
-    if (!addr)
-       return s;
-
-    addr->sat_family = AF_APPLETALK;
-    /* rest of address should be initialized by the caller */
-    if (bind(s, (struct sockaddr *) addr, sizeof( struct sockaddr_at )) < 0 ) {
-        close(s);
-       return -1;
-    }
-
-    /* get the real address from the kernel */
-    len = sizeof( struct sockaddr_at);
-    if ( getsockname( s, (struct sockaddr *) addr, &len ) != 0 ) {
-        close(s);
-       return -1;
-    }
-#endif /* MACOSX_SERVER */
-
-    return s;
-#endif /* NO_DDP */
-}
diff --git a/libatalk/netddp/netddp_recvfrom.c b/libatalk/netddp/netddp_recvfrom.c
deleted file mode 100644 (file)
index 6e7a942..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/* 
- * $Id: netddp_recvfrom.c,v 1.5 2003-02-17 02:02:25 srittau Exp $
- *
- * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * receive data.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifndef NO_DDP
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/uio.h>
-#include <errno.h>
-
-#ifdef MACOSX_SERVER
-#include <netat/appletalk.h>
-#include <netat/ddp.h>
-#endif /* MACOSX_SERVER */
-
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <netatalk/ddp.h>
-#include <atalk/netddp.h>
-
-#ifndef MAX
-#define MAX(a, b)  ((a) < (b) ? (b) : (a))
-#endif /* ! MAX */
-
-#ifdef MACOSX_SERVER
-int netddp_recvfrom(int fd, void *buf, int buflen, unsigned int dummy, 
-                    struct sockaddr *addr, unsigned int *addrlen)
-{
-    ssize_t i;
-    struct ddpehdr ddphdr;
-    struct sockaddr_at *sat = (struct sockaddr_at *) addr;
-    struct iovec iov[2];
-
-    iov[0].iov_base = (void *) &ddphdr;
-    iov[0].iov_len = sizeof(ddphdr);
-    iov[1].iov_base = buf;
-    iov[1].iov_len = buflen;
-
-    while ((i = readv(fd, iov, 2)) < 0) {
-      if (errno != EINTR)
-       return -1;
-    }
-
-    if (addr) {
-      sat->sat_addr.s_net = ddphdr.deh_snet;
-      sat->sat_addr.s_node = ddphdr.deh_snode;
-      sat->sat_port = ddphdr.deh_sport;
-    }
-
-    return MAX(0, i - sizeof(ddphdr));
-}
-
-#endif /* os x server */
-#endif /* no ddp */
diff --git a/libatalk/netddp/netddp_sendto.c b/libatalk/netddp/netddp_sendto.c
deleted file mode 100644 (file)
index 407b94d..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/* 
- * $Id: netddp_sendto.c,v 1.7 2005-04-28 20:50:02 bfernhomberg Exp $
- *
- * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * send data.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifndef NO_DDP
-#include <string.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif /* HAVE_UNISTD_H */
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/uio.h>
-#include <errno.h>
-
-#ifdef MACOSX_SERVER
-#include <netat/appletalk.h>
-#include <netat/ddp.h>
-#endif /* MACOSX_SERVER */
-
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <netatalk/ddp.h>
-#include <atalk/netddp.h>
-
-#ifndef MAX
-#define MAX(a, b)  ((a) < (b) ? (b) : (a))
-#endif /* ! MAX */
-
-#ifdef MACOSX_SERVER
-int netddp_sendto(int fd, void *buf, size_t buflen, unsigned int dummy, 
-                 const struct sockaddr *addr, unsigned int addrlen)
-{
-    ssize_t i;
-    struct ddpehdr ddphdr;
-    const struct sockaddr_at *sat = (const struct sockaddr_at *) addr;
-    struct iovec iov[2];
-
-    iov[0].iov_base = (void *) &ddphdr;
-    iov[0].iov_len = sizeof(ddphdr);
-    iov[1].iov_base = buf;
-    iov[1].iov_len = buflen;
-
-    if (!addr)
-      return -1;
-
-    memset(&ddphdr, 0, sizeof(ddphdr));
-    ddphdr.deh_len = htons(sizeof(ddphdr) + (u_int16_t) buflen);
-    ddphdr.deh_dnet = sat->sat_addr.s_net;
-    ddphdr.deh_dnode = sat->sat_addr.s_node;
-    ddphdr.deh_dport = sat->sat_port;
-    while ((i = writev(fd, iov, 2)) < 0) {
-      if (errno != EINTR)
-       return -1;
-    }
-
-    return MAX(0, i - sizeof(ddphdr));
-}
-
-#endif /* os x server */
-#endif /* no ddp */
index e2dc8b278ddf9bb0b8613829b9e9263df9b8d494..874baef6cbdb35f63c63a8c63d5402d14d25a14f 100644 (file)
@@ -1,8 +1,16 @@
 # Makefile.am for libatalk/tdb/
 
 noinst_LTLIBRARIES = libtdb.la
-
-libtdb_la_SOURCES = tdb.c \
-                    spinlock.c \
-                    spinlock.h
+noinst_HEADERS = tdb_private.h
+libtdb_la_SOURCES = check.c \
+       dump.c                  \
+       error.c                 \
+       freelist.c              \
+       freelistcheck.c \
+       io.c                    \
+       lock.c                  \
+       open.c                  \
+       tdb.c                   \
+       transaction.c   \
+       traverse.c
 
diff --git a/libatalk/tdb/check.c b/libatalk/tdb/check.c
new file mode 100644 (file)
index 0000000..f0a15f8
--- /dev/null
@@ -0,0 +1,423 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Rusty Russell            2009
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+#include "tdb_private.h"
+
+/* Since we opened it, these shouldn't fail unless it's recent corruption. */
+static bool tdb_check_header(struct tdb_context *tdb, tdb_off_t *recovery)
+{
+       struct tdb_header hdr;
+
+       if (tdb->methods->tdb_read(tdb, 0, &hdr, sizeof(hdr), DOCONV()) == -1)
+               return false;
+       if (strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0)
+               goto corrupt;
+
+       CONVERT(hdr);
+       if (hdr.version != TDB_VERSION)
+               goto corrupt;
+
+       if (hdr.rwlocks != 0)
+               goto corrupt;
+
+       if (hdr.hash_size == 0)
+               goto corrupt;
+
+       if (hdr.hash_size != tdb->header.hash_size)
+               goto corrupt;
+
+       if (hdr.recovery_start != 0 &&
+           hdr.recovery_start < TDB_DATA_START(tdb->header.hash_size))
+               goto corrupt;
+
+       *recovery = hdr.recovery_start;
+       return true;
+
+corrupt:
+       tdb->ecode = TDB_ERR_CORRUPT;
+       TDB_LOG((tdb, TDB_DEBUG_ERROR, "Header is corrupt\n"));
+       return false;
+}
+
+/* Generic record header check. */
+static bool tdb_check_record(struct tdb_context *tdb,
+                            tdb_off_t off,
+                            const struct tdb_record *rec)
+{
+       tdb_off_t tailer;
+
+       /* Check rec->next: 0 or points to record offset, aligned. */
+       if (rec->next > 0 && rec->next < TDB_DATA_START(tdb->header.hash_size)){
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Record offset %d too small next %d\n",
+                        off, rec->next));
+               goto corrupt;
+       }
+       if (rec->next + sizeof(*rec) < rec->next) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Record offset %d too large next %d\n",
+                        off, rec->next));
+               goto corrupt;
+       }
+       if ((rec->next % TDB_ALIGNMENT) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Record offset %d misaligned next %d\n",
+                        off, rec->next));
+               goto corrupt;
+       }
+       if (tdb->methods->tdb_oob(tdb, rec->next+sizeof(*rec), 0))
+               goto corrupt;
+
+       /* Check rec_len: similar to rec->next, implies next record. */
+       if ((rec->rec_len % TDB_ALIGNMENT) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Record offset %d misaligned length %d\n",
+                        off, rec->rec_len));
+               goto corrupt;
+       }
+       /* Must fit tailer. */
+       if (rec->rec_len < sizeof(tailer)) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Record offset %d too short length %d\n",
+                        off, rec->rec_len));
+               goto corrupt;
+       }
+       /* OOB allows "right at the end" access, so this works for last rec. */
+       if (tdb->methods->tdb_oob(tdb, off+sizeof(*rec)+rec->rec_len, 0))
+               goto corrupt;
+
+       /* Check tailer. */
+       if (tdb_ofs_read(tdb, off+sizeof(*rec)+rec->rec_len-sizeof(tailer),
+                        &tailer) == -1)
+               goto corrupt;
+       if (tailer != sizeof(*rec) + rec->rec_len) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Record offset %d invalid tailer\n", off));
+               goto corrupt;
+       }
+
+       return true;
+
+corrupt:
+       tdb->ecode = TDB_ERR_CORRUPT;
+       return false;
+}
+
+/* Grab some bytes: may copy if can't use mmap.
+   Caller has already done bounds check. */
+static TDB_DATA get_bytes(struct tdb_context *tdb,
+                         tdb_off_t off, tdb_len_t len)
+{
+       TDB_DATA d;
+
+       d.dsize = len;
+
+       if (tdb->transaction == NULL && tdb->map_ptr != NULL)
+               d.dptr = (unsigned char *)tdb->map_ptr + off;
+       else
+               d.dptr = tdb_alloc_read(tdb, off, d.dsize);
+       return d;
+}
+
+/* Frees data if we're not able to simply use mmap. */
+static void put_bytes(struct tdb_context *tdb, TDB_DATA d)
+{
+       if (tdb->transaction == NULL && tdb->map_ptr != NULL)
+               return;
+       free(d.dptr);
+}
+
+/* We use the excellent Jenkins lookup3 hash; this is based on hash_word2.
+ * See: http://burtleburtle.net/bob/c/lookup3.c
+ */
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+static void hash(uint32_t key, uint32_t *pc, uint32_t *pb)
+{
+       uint32_t a,b,c;
+
+       /* Set up the internal state */
+       a = b = c = 0xdeadbeef + *pc;
+       c += *pb;
+       a += key;
+       c ^= b; c -= rot(b,14);
+       a ^= c; a -= rot(c,11);
+       b ^= a; b -= rot(a,25);
+       c ^= b; c -= rot(b,16);
+       a ^= c; a -= rot(c,4);
+       b ^= a; b -= rot(a,14);
+       c ^= b; c -= rot(b,24);
+       *pc=c; *pb=b;
+}
+
+/*
+  We want to check that all free records are in the free list
+  (only once), and all free list entries are free records.  Similarly
+  for each hash chain of used records.
+
+  Doing that naively (without walking hash chains, since we want to be
+  linear) means keeping a list of records which have been seen in each
+  hash chain, and another of records pointed to (ie. next pointers
+  from records and the initial hash chain heads).  These two lists
+  should be equal.  This will take 8 bytes per record, and require
+  sorting at the end.
+
+  So instead, we record each offset in a bitmap such a way that
+  recording it twice will cancel out.  Since each offset should appear
+  exactly twice, the bitmap should be zero at the end.
+
+  The approach was inspired by Bloom Filters (see Wikipedia).  For
+  each value, we flip K bits in a bitmap of size N.  The number of
+  distinct arrangements is:
+
+       N! / (K! * (N-K)!)
+
+  Of course, not all arrangements are actually distinct, but testing
+  shows this formula to be close enough.
+
+  So, if K == 8 and N == 256, the probability of two things flipping the same
+  bits is 1 in 409,663,695,276,000.
+
+  Given that ldb uses a hash size of 10000, using 32 bytes per hash chain
+  (320k) seems reasonable.
+*/
+#define NUM_HASHES 8
+#define BITMAP_BITS 256
+
+static void bit_flip(unsigned char bits[], unsigned int idx)
+{
+       bits[idx / CHAR_BIT] ^= (1 << (idx % CHAR_BIT));
+}
+
+/* We record offsets in a bitmap for the particular chain it should be in.  */
+static void record_offset(unsigned char bits[], tdb_off_t off)
+{
+       uint32_t h1 = off, h2 = 0;
+       unsigned int i;
+
+       /* We get two good hash values out of jhash2, so we use both.  Then
+        * we keep going to produce further hash values. */
+       for (i = 0; i < NUM_HASHES / 2; i++) {
+               hash(off, &h1, &h2);
+               bit_flip(bits, h1 % BITMAP_BITS);
+               bit_flip(bits, h2 % BITMAP_BITS);
+               h2++;
+       }
+}
+
+/* Check that an in-use record is valid. */
+static bool tdb_check_used_record(struct tdb_context *tdb,
+                                 tdb_off_t off,
+                                 const struct tdb_record *rec,
+                                 unsigned char **hashes,
+                                 int (*check)(TDB_DATA, TDB_DATA, void *),
+                                 void *private_data)
+{
+       TDB_DATA key, data;
+
+       if (!tdb_check_record(tdb, off, rec))
+               return false;
+
+       /* key + data + tailer must fit in record */
+       if (rec->key_len + rec->data_len + sizeof(tdb_off_t) > rec->rec_len) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Record offset %d too short for contents\n", off));
+               return false;
+       }
+
+       key = get_bytes(tdb, off + sizeof(*rec), rec->key_len);
+       if (!key.dptr)
+               return false;
+
+       if (tdb->hash_fn(&key) != rec->full_hash) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Record offset %d has incorrect hash\n", off));
+               goto fail_put_key;
+       }
+
+       /* Mark this offset as a known value for this hash bucket. */
+       record_offset(hashes[BUCKET(rec->full_hash)+1], off);
+       /* And similarly if the next pointer is valid. */
+       if (rec->next)
+               record_offset(hashes[BUCKET(rec->full_hash)+1], rec->next);
+
+       /* If they supply a check function and this record isn't dead,
+          get data and feed it. */
+       if (check && rec->magic != TDB_DEAD_MAGIC) {
+               data = get_bytes(tdb, off + sizeof(*rec) + rec->key_len,
+                                rec->data_len);
+               if (!data.dptr)
+                       goto fail_put_key;
+
+               if (check(key, data, private_data) == -1)
+                       goto fail_put_data;
+               put_bytes(tdb, data);
+       }
+
+       put_bytes(tdb, key);
+       return true;
+
+fail_put_data:
+       put_bytes(tdb, data);
+fail_put_key:
+       put_bytes(tdb, key);
+       return false;
+}
+
+/* Check that an unused record is valid. */
+static bool tdb_check_free_record(struct tdb_context *tdb,
+                                 tdb_off_t off,
+                                 const struct tdb_record *rec,
+                                 unsigned char **hashes)
+{
+       if (!tdb_check_record(tdb, off, rec))
+               return false;
+
+       /* Mark this offset as a known value for the free list. */
+       record_offset(hashes[0], off);
+       /* And similarly if the next pointer is valid. */
+       if (rec->next)
+               record_offset(hashes[0], rec->next);
+       return true;
+}
+
+int tdb_check(struct tdb_context *tdb,
+             int (*check)(TDB_DATA key, TDB_DATA data, void *private_data),
+             void *private_data)
+{
+       unsigned int h;
+       unsigned char **hashes;
+       tdb_off_t off, recovery_start;
+       struct tdb_record rec;
+       bool found_recovery = false;
+
+       if (tdb_lockall(tdb) == -1)
+               return -1;
+
+       /* Make sure we know true size of the underlying file. */
+       tdb->methods->tdb_oob(tdb, tdb->map_size + 1, 1);
+
+       /* Header must be OK: also gets us the recovery ptr, if any. */
+       if (!tdb_check_header(tdb, &recovery_start))
+               goto unlock;
+
+       /* We should have the whole header, too. */
+       if (tdb->map_size < TDB_DATA_START(tdb->header.hash_size)) {
+               tdb->ecode = TDB_ERR_CORRUPT;
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "File too short for hashes\n"));
+               goto unlock;
+       }
+
+       /* One big malloc: pointers then bit arrays. */
+       hashes = (unsigned char **)calloc(
+                       1, sizeof(hashes[0]) * (1+tdb->header.hash_size)
+                       + BITMAP_BITS / CHAR_BIT * (1+tdb->header.hash_size));
+       if (!hashes) {
+               tdb->ecode = TDB_ERR_OOM;
+               goto unlock;
+       }
+
+       /* Initialize pointers */
+       hashes[0] = (unsigned char *)(&hashes[1+tdb->header.hash_size]);
+       for (h = 1; h < 1+tdb->header.hash_size; h++)
+               hashes[h] = hashes[h-1] + BITMAP_BITS / CHAR_BIT;
+
+       /* Freelist and hash headers are all in a row: read them. */
+       for (h = 0; h < 1+tdb->header.hash_size; h++) {
+               if (tdb_ofs_read(tdb, FREELIST_TOP + h*sizeof(tdb_off_t),
+                                &off) == -1)
+                       goto free;
+               if (off)
+                       record_offset(hashes[h], off);
+       }
+
+       /* For each record, read it in and check it's ok. */
+       for (off = TDB_DATA_START(tdb->header.hash_size);
+            off < tdb->map_size;
+            off += sizeof(rec) + rec.rec_len) {
+               if (tdb->methods->tdb_read(tdb, off, &rec, sizeof(rec),
+                                          DOCONV()) == -1)
+                       goto free;
+               switch (rec.magic) {
+               case TDB_MAGIC:
+               case TDB_DEAD_MAGIC:
+                       if (!tdb_check_used_record(tdb, off, &rec, hashes,
+                                                  check, private_data))
+                               goto free;
+                       break;
+               case TDB_FREE_MAGIC:
+                       if (!tdb_check_free_record(tdb, off, &rec, hashes))
+                               goto free;
+                       break;
+               case TDB_RECOVERY_MAGIC:
+               case 0: /* Used for invalid (or in-progress) recovery area. */
+                       if (recovery_start != off) {
+                               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                                        "Unexpected recovery record at offset %d\n",
+                                        off));
+                               goto free;
+                       }
+                       found_recovery = true;
+                       break;
+               default:
+                       tdb->ecode = TDB_ERR_CORRUPT;
+                       TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                                "Bad magic 0x%x at offset %d\n",
+                                rec.magic, off));
+                       goto free;
+               }
+       }
+
+       /* Now, hashes should all be empty: each record exists and is referred
+        * to by one other. */
+       for (h = 0; h < 1+tdb->header.hash_size; h++) {
+               unsigned int i;
+               for (i = 0; i < BITMAP_BITS / CHAR_BIT; i++) {
+                       if (hashes[h][i] != 0) {
+                               tdb->ecode = TDB_ERR_CORRUPT;
+                               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                                        "Hashes do not match records\n"));
+                               goto free;
+                       }
+               }
+       }
+
+       /* We must have found recovery area if there was one. */
+       if (recovery_start != 0 && !found_recovery) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,
+                        "Expected %s recovery area, got %s\n",
+                        recovery_start ? "a" : "no",
+                        found_recovery ? "one" : "none"));
+               goto free;
+       }
+
+       free(hashes);
+       tdb_unlockall(tdb);
+       return 0;
+
+free:
+       free(hashes);
+unlock:
+       tdb_unlockall(tdb);
+       return -1;
+}
diff --git a/libatalk/tdb/dump.c b/libatalk/tdb/dump.c
new file mode 100644 (file)
index 0000000..bdcbfab
--- /dev/null
@@ -0,0 +1,137 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+   
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb_private.h"
+
+static tdb_off_t tdb_dump_record(struct tdb_context *tdb, int hash,
+                                tdb_off_t offset)
+{
+       struct tdb_record rec;
+       tdb_off_t tailer_ofs, tailer;
+
+       if (tdb->methods->tdb_read(tdb, offset, (char *)&rec, 
+                                  sizeof(rec), DOCONV()) == -1) {
+               printf("ERROR: failed to read record at %u\n", offset);
+               return 0;
+       }
+
+       printf(" rec: hash=%d offset=0x%08x next=0x%08x rec_len=%d "
+              "key_len=%d data_len=%d full_hash=0x%x magic=0x%x\n",
+              hash, offset, rec.next, rec.rec_len, rec.key_len, rec.data_len,
+              rec.full_hash, rec.magic);
+
+       tailer_ofs = offset + sizeof(rec) + rec.rec_len - sizeof(tdb_off_t);
+
+       if (tdb_ofs_read(tdb, tailer_ofs, &tailer) == -1) {
+               printf("ERROR: failed to read tailer at %u\n", tailer_ofs);
+               return rec.next;
+       }
+
+       if (tailer != rec.rec_len + sizeof(rec)) {
+               printf("ERROR: tailer does not match record! tailer=%u totalsize=%u\n",
+                               (unsigned int)tailer, (unsigned int)(rec.rec_len + sizeof(rec)));
+       }
+       return rec.next;
+}
+
+static int tdb_dump_chain(struct tdb_context *tdb, int i)
+{
+       tdb_off_t rec_ptr, top;
+
+       top = TDB_HASH_TOP(i);
+
+       if (tdb_lock(tdb, i, F_WRLCK) != 0)
+               return -1;
+
+       if (tdb_ofs_read(tdb, top, &rec_ptr) == -1)
+               return tdb_unlock(tdb, i, F_WRLCK);
+
+       if (rec_ptr)
+               printf("hash=%d\n", i);
+
+       while (rec_ptr) {
+               rec_ptr = tdb_dump_record(tdb, i, rec_ptr);
+       }
+
+       return tdb_unlock(tdb, i, F_WRLCK);
+}
+
+void tdb_dump_all(struct tdb_context *tdb)
+{
+       int i;
+       for (i=0;i<tdb->header.hash_size;i++) {
+               tdb_dump_chain(tdb, i);
+       }
+       printf("freelist:\n");
+       tdb_dump_chain(tdb, -1);
+}
+
+int tdb_printfreelist(struct tdb_context *tdb)
+{
+       int ret;
+       long total_free = 0;
+       tdb_off_t offset, rec_ptr;
+       struct tdb_record rec;
+
+       if ((ret = tdb_lock(tdb, -1, F_WRLCK)) != 0)
+               return ret;
+
+       offset = FREELIST_TOP;
+
+       /* read in the freelist top */
+       if (tdb_ofs_read(tdb, offset, &rec_ptr) == -1) {
+               tdb_unlock(tdb, -1, F_WRLCK);
+               return 0;
+       }
+
+       printf("freelist top=[0x%08x]\n", rec_ptr );
+       while (rec_ptr) {
+               if (tdb->methods->tdb_read(tdb, rec_ptr, (char *)&rec, 
+                                          sizeof(rec), DOCONV()) == -1) {
+                       tdb_unlock(tdb, -1, F_WRLCK);
+                       return -1;
+               }
+
+               if (rec.magic != TDB_FREE_MAGIC) {
+                       printf("bad magic 0x%08x in free list\n", rec.magic);
+                       tdb_unlock(tdb, -1, F_WRLCK);
+                       return -1;
+               }
+
+               printf("entry offset=[0x%08x], rec.rec_len = [0x%08x (%d)] (end = 0x%08x)\n", 
+                      rec_ptr, rec.rec_len, rec.rec_len, rec_ptr + rec.rec_len);
+               total_free += rec.rec_len;
+
+               /* move to the next record */
+               rec_ptr = rec.next;
+       }
+       printf("total rec_len = [0x%08x (%d)]\n", (int)total_free, 
+               (int)total_free);
+
+       return tdb_unlock(tdb, -1, F_WRLCK);
+}
+
diff --git a/libatalk/tdb/error.c b/libatalk/tdb/error.c
new file mode 100644 (file)
index 0000000..195ab23
--- /dev/null
@@ -0,0 +1,57 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+   
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb_private.h"
+
+enum TDB_ERROR tdb_error(struct tdb_context *tdb)
+{
+       return tdb->ecode;
+}
+
+static struct tdb_errname {
+       enum TDB_ERROR ecode; const char *estring;
+} emap[] = { {TDB_SUCCESS, "Success"},
+            {TDB_ERR_CORRUPT, "Corrupt database"},
+            {TDB_ERR_IO, "IO Error"},
+            {TDB_ERR_LOCK, "Locking error"},
+            {TDB_ERR_OOM, "Out of memory"},
+            {TDB_ERR_EXISTS, "Record exists"},
+            {TDB_ERR_NOLOCK, "Lock exists on other keys"},
+            {TDB_ERR_EINVAL, "Invalid parameter"},
+            {TDB_ERR_NOEXIST, "Record does not exist"},
+            {TDB_ERR_RDONLY, "write not permitted"} };
+
+/* Error string for the last tdb error */
+const char *tdb_errorstr(struct tdb_context *tdb)
+{
+       uint32_t i;
+       for (i = 0; i < sizeof(emap) / sizeof(struct tdb_errname); i++)
+               if (tdb->ecode == emap[i].ecode)
+                       return emap[i].estring;
+       return "Invalid error code";
+}
+
diff --git a/libatalk/tdb/freelist.c b/libatalk/tdb/freelist.c
new file mode 100644 (file)
index 0000000..8113b54
--- /dev/null
@@ -0,0 +1,386 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+   
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb_private.h"
+
+/* 'right' merges can involve O(n^2) cost when combined with a
+   traverse, so they are disabled until we find a way to do them in 
+   O(1) time
+*/
+#define USE_RIGHT_MERGES 0
+
+/* read a freelist record and check for simple errors */
+int tdb_rec_free_read(struct tdb_context *tdb, tdb_off_t off, struct tdb_record *rec)
+{
+       if (tdb->methods->tdb_read(tdb, off, rec, sizeof(*rec),DOCONV()) == -1)
+               return -1;
+
+       if (rec->magic == TDB_MAGIC) {
+               /* this happens when a app is showdown while deleting a record - we should
+                  not completely fail when this happens */
+               TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_rec_free_read non-free magic 0x%x at offset=%d - fixing\n", 
+                        rec->magic, off));
+               rec->magic = TDB_FREE_MAGIC;
+               if (tdb->methods->tdb_write(tdb, off, rec, sizeof(*rec)) == -1)
+                       return -1;
+       }
+
+       if (rec->magic != TDB_FREE_MAGIC) {
+               /* Ensure ecode is set for log fn. */
+               tdb->ecode = TDB_ERR_CORRUPT;
+               TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_rec_free_read bad magic 0x%x at offset=%d\n", 
+                          rec->magic, off));
+               return -1;
+       }
+       if (tdb->methods->tdb_oob(tdb, rec->next+sizeof(*rec), 0) != 0)
+               return -1;
+       return 0;
+}
+
+
+#if USE_RIGHT_MERGES
+/* Remove an element from the freelist.  Must have alloc lock. */
+static int remove_from_freelist(struct tdb_context *tdb, tdb_off_t off, tdb_off_t next)
+{
+       tdb_off_t last_ptr, i;
+
+       /* read in the freelist top */
+       last_ptr = FREELIST_TOP;
+       while (tdb_ofs_read(tdb, last_ptr, &i) != -1 && i != 0) {
+               if (i == off) {
+                       /* We've found it! */
+                       return tdb_ofs_write(tdb, last_ptr, &next);
+               }
+               /* Follow chain (next offset is at start of record) */
+               last_ptr = i;
+       }
+       tdb->ecode = TDB_ERR_CORRUPT;
+       TDB_LOG((tdb, TDB_DEBUG_FATAL,"remove_from_freelist: not on list at off=%d\n", off));
+       return -1;
+}
+#endif
+
+
+/* update a record tailer (must hold allocation lock) */
+static int update_tailer(struct tdb_context *tdb, tdb_off_t offset,
+                        const struct tdb_record *rec)
+{
+       tdb_off_t totalsize;
+
+       /* Offset of tailer from record header */
+       totalsize = sizeof(*rec) + rec->rec_len;
+       return tdb_ofs_write(tdb, offset + totalsize - sizeof(tdb_off_t),
+                        &totalsize);
+}
+
+/* Add an element into the freelist. Merge adjacent records if
+   neccessary. */
+int tdb_free(struct tdb_context *tdb, tdb_off_t offset, struct tdb_record *rec)
+{
+       /* Allocation and tailer lock */
+       if (tdb_lock(tdb, -1, F_WRLCK) != 0)
+               return -1;
+
+       /* set an initial tailer, so if we fail we don't leave a bogus record */
+       if (update_tailer(tdb, offset, rec) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: update_tailer failed!\n"));
+               goto fail;
+       }
+
+#if USE_RIGHT_MERGES
+       /* Look right first (I'm an Australian, dammit) */
+       if (offset + sizeof(*rec) + rec->rec_len + sizeof(*rec) <= tdb->map_size) {
+               tdb_off_t right = offset + sizeof(*rec) + rec->rec_len;
+               struct tdb_record r;
+
+               if (tdb->methods->tdb_read(tdb, right, &r, sizeof(r), DOCONV()) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: right read failed at %u\n", right));
+                       goto left;
+               }
+
+               /* If it's free, expand to include it. */
+               if (r.magic == TDB_FREE_MAGIC) {
+                       if (remove_from_freelist(tdb, right, r.next) == -1) {
+                               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: right free failed at %u\n", right));
+                               goto left;
+                       }
+                       rec->rec_len += sizeof(r) + r.rec_len;
+                       if (update_tailer(tdb, offset, rec) == -1) {
+                               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: update_tailer failed at %u\n", offset));
+                               goto fail;
+                       }
+               }
+       }
+left:
+#endif
+
+       /* Look left */
+       if (offset - sizeof(tdb_off_t) > TDB_DATA_START(tdb->header.hash_size)) {
+               tdb_off_t left = offset - sizeof(tdb_off_t);
+               struct tdb_record l;
+               tdb_off_t leftsize;
+               
+               /* Read in tailer and jump back to header */
+               if (tdb_ofs_read(tdb, left, &leftsize) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: left offset read failed at %u\n", left));
+                       goto update;
+               }
+
+               /* it could be uninitialised data */
+               if (leftsize == 0 || leftsize == TDB_PAD_U32) {
+                       goto update;
+               }
+
+               left = offset - leftsize;
+
+               if (leftsize > offset ||
+                   left < TDB_DATA_START(tdb->header.hash_size)) {
+                       goto update;
+               }
+
+               /* Now read in the left record */
+               if (tdb->methods->tdb_read(tdb, left, &l, sizeof(l), DOCONV()) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: left read failed at %u (%u)\n", left, leftsize));
+                       goto update;
+               }
+
+               /* If it's free, expand to include it. */
+               if (l.magic == TDB_FREE_MAGIC) {
+                       /* we now merge the new record into the left record, rather than the other 
+                          way around. This makes the operation O(1) instead of O(n). This change
+                          prevents traverse from being O(n^2) after a lot of deletes */
+                       l.rec_len += sizeof(*rec) + rec->rec_len;
+                       if (tdb_rec_write(tdb, left, &l) == -1) {
+                               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: update_left failed at %u\n", left));
+                               goto fail;
+                       }
+                       if (update_tailer(tdb, left, &l) == -1) {
+                               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free: update_tailer failed at %u\n", offset));
+                               goto fail;
+                       }
+                       tdb_unlock(tdb, -1, F_WRLCK);
+                       return 0;
+               }
+       }
+
+update:
+
+       /* Now, prepend to free list */
+       rec->magic = TDB_FREE_MAGIC;
+
+       if (tdb_ofs_read(tdb, FREELIST_TOP, &rec->next) == -1 ||
+           tdb_rec_write(tdb, offset, rec) == -1 ||
+           tdb_ofs_write(tdb, FREELIST_TOP, &offset) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_free record write failed at offset=%d\n", offset));
+               goto fail;
+       }
+
+       /* And we're done. */
+       tdb_unlock(tdb, -1, F_WRLCK);
+       return 0;
+
+ fail:
+       tdb_unlock(tdb, -1, F_WRLCK);
+       return -1;
+}
+
+
+
+/* 
+   the core of tdb_allocate - called when we have decided which
+   free list entry to use
+
+   Note that we try to allocate by grabbing data from the end of an existing record,
+   not the beginning. This is so the left merge in a free is more likely to be
+   able to free up the record without fragmentation
+ */
+static tdb_off_t tdb_allocate_ofs(struct tdb_context *tdb, 
+                                 tdb_len_t length, tdb_off_t rec_ptr,
+                                 struct tdb_record *rec, tdb_off_t last_ptr)
+{
+#define MIN_REC_SIZE (sizeof(struct tdb_record) + sizeof(tdb_off_t) + 8)
+
+       if (rec->rec_len < length + MIN_REC_SIZE) {
+               /* we have to grab the whole record */
+
+               /* unlink it from the previous record */
+               if (tdb_ofs_write(tdb, last_ptr, &rec->next) == -1) {
+                       return 0;
+               }
+
+               /* mark it not free */
+               rec->magic = TDB_MAGIC;
+               if (tdb_rec_write(tdb, rec_ptr, rec) == -1) {
+                       return 0;
+               }
+               return rec_ptr;
+       }
+
+       /* we're going to just shorten the existing record */
+       rec->rec_len -= (length + sizeof(*rec));
+       if (tdb_rec_write(tdb, rec_ptr, rec) == -1) {
+               return 0;
+       }
+       if (update_tailer(tdb, rec_ptr, rec) == -1) {
+               return 0;
+       }
+
+       /* and setup the new record */
+       rec_ptr += sizeof(*rec) + rec->rec_len; 
+
+       memset(rec, '\0', sizeof(*rec));
+       rec->rec_len = length;
+       rec->magic = TDB_MAGIC;
+
+       if (tdb_rec_write(tdb, rec_ptr, rec) == -1) {
+               return 0;
+       }
+
+       if (update_tailer(tdb, rec_ptr, rec) == -1) {
+               return 0;
+       }
+
+       return rec_ptr;
+}
+
+/* allocate some space from the free list. The offset returned points
+   to a unconnected tdb_record within the database with room for at
+   least length bytes of total data
+
+   0 is returned if the space could not be allocated
+ */
+tdb_off_t tdb_allocate(struct tdb_context *tdb, tdb_len_t length, struct tdb_record *rec)
+{
+       tdb_off_t rec_ptr, last_ptr, newrec_ptr;
+       struct {
+               tdb_off_t rec_ptr, last_ptr;
+               tdb_len_t rec_len;
+       } bestfit;
+       float multiplier = 1.0;
+
+       if (tdb_lock(tdb, -1, F_WRLCK) == -1)
+               return 0;
+
+       /* over-allocate to reduce fragmentation */
+       length *= 1.25;
+
+       /* Extra bytes required for tailer */
+       length += sizeof(tdb_off_t);
+       length = TDB_ALIGN(length, TDB_ALIGNMENT);
+
+ again:
+       last_ptr = FREELIST_TOP;
+
+       /* read in the freelist top */
+       if (tdb_ofs_read(tdb, FREELIST_TOP, &rec_ptr) == -1)
+               goto fail;
+
+       bestfit.rec_ptr = 0;
+       bestfit.last_ptr = 0;
+       bestfit.rec_len = 0;
+
+       /* 
+          this is a best fit allocation strategy. Originally we used
+          a first fit strategy, but it suffered from massive fragmentation
+          issues when faced with a slowly increasing record size.
+        */
+       while (rec_ptr) {
+               if (tdb_rec_free_read(tdb, rec_ptr, rec) == -1) {
+                       goto fail;
+               }
+
+               if (rec->rec_len >= length) {
+                       if (bestfit.rec_ptr == 0 ||
+                           rec->rec_len < bestfit.rec_len) {
+                               bestfit.rec_len = rec->rec_len;
+                               bestfit.rec_ptr = rec_ptr;
+                               bestfit.last_ptr = last_ptr;
+                       }
+               }
+
+               /* move to the next record */
+               last_ptr = rec_ptr;
+               rec_ptr = rec->next;
+
+               /* if we've found a record that is big enough, then
+                  stop searching if its also not too big. The
+                  definition of 'too big' changes as we scan
+                  through */
+               if (bestfit.rec_len > 0 &&
+                   bestfit.rec_len < length * multiplier) {
+                       break;
+               }
+               
+               /* this multiplier means we only extremely rarely
+                  search more than 50 or so records. At 50 records we
+                  accept records up to 11 times larger than what we
+                  want */
+               multiplier *= 1.05;
+       }
+
+       if (bestfit.rec_ptr != 0) {
+               if (tdb_rec_free_read(tdb, bestfit.rec_ptr, rec) == -1) {
+                       goto fail;
+               }
+
+               newrec_ptr = tdb_allocate_ofs(tdb, length, bestfit.rec_ptr, 
+                                             rec, bestfit.last_ptr);
+               tdb_unlock(tdb, -1, F_WRLCK);
+               return newrec_ptr;
+       }
+
+       /* we didn't find enough space. See if we can expand the
+          database and if we can then try again */
+       if (tdb_expand(tdb, length + sizeof(*rec)) == 0)
+               goto again;
+ fail:
+       tdb_unlock(tdb, -1, F_WRLCK);
+       return 0;
+}
+
+
+
+/* 
+   return the size of the freelist - used to decide if we should repack 
+*/
+int tdb_freelist_size(struct tdb_context *tdb)
+{
+       tdb_off_t ptr;
+       int count=0;
+
+       if (tdb_lock(tdb, -1, F_RDLCK) == -1) {
+               return -1;
+       }
+
+       ptr = FREELIST_TOP;
+       while (tdb_ofs_read(tdb, ptr, &ptr) == 0 && ptr != 0) {
+               count++;
+       }
+
+       tdb_unlock(tdb, -1, F_RDLCK);
+       return count;
+}
diff --git a/libatalk/tdb/freelistcheck.c b/libatalk/tdb/freelistcheck.c
new file mode 100644 (file)
index 0000000..8d1ebab
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Jeremy Allison                    2006
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb_private.h"
+
+/* Check the freelist is good and contains no loops.
+   Very memory intensive - only do this as a consistency
+   checker. Heh heh - uses an in memory tdb as the storage
+   for the "seen" record list. For some reason this strikes
+   me as extremely clever as I don't have to write another tree
+   data structure implementation :-).
+ */
+
+static int seen_insert(struct tdb_context *mem_tdb, tdb_off_t rec_ptr)
+{
+       TDB_DATA key, data;
+
+       memset(&data, '\0', sizeof(data));
+       key.dptr = (unsigned char *)&rec_ptr;
+       key.dsize = sizeof(rec_ptr);
+       return tdb_store(mem_tdb, key, data, TDB_INSERT);
+}
+
+int tdb_validate_freelist(struct tdb_context *tdb, int *pnum_entries)
+{
+       struct tdb_context *mem_tdb = NULL;
+       struct tdb_record rec;
+       tdb_off_t rec_ptr, last_ptr;
+       int ret = -1;
+
+       *pnum_entries = 0;
+
+       mem_tdb = tdb_open("flval", tdb->header.hash_size,
+                               TDB_INTERNAL, O_RDWR, 0600);
+       if (!mem_tdb) {
+               return -1;
+       }
+
+       if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
+               tdb_close(mem_tdb);
+               return 0;
+       }
+
+       last_ptr = FREELIST_TOP;
+
+       /* Store the FREELIST_TOP record. */
+       if (seen_insert(mem_tdb, last_ptr) == -1) {
+               tdb->ecode = TDB_ERR_CORRUPT;
+               ret = -1;
+               goto fail;
+       }
+
+       /* read in the freelist top */
+       if (tdb_ofs_read(tdb, FREELIST_TOP, &rec_ptr) == -1) {
+               goto fail;
+       }
+
+       while (rec_ptr) {
+
+               /* If we can't store this record (we've seen it
+                  before) then the free list has a loop and must
+                  be corrupt. */
+
+               if (seen_insert(mem_tdb, rec_ptr)) {
+                       tdb->ecode = TDB_ERR_CORRUPT;
+                       ret = -1;
+                       goto fail;
+               }
+
+               if (tdb_rec_free_read(tdb, rec_ptr, &rec) == -1) {
+                       goto fail;
+               }
+
+               /* move to the next record */
+               last_ptr = rec_ptr;
+               rec_ptr = rec.next;
+               *pnum_entries += 1;
+       }
+
+       ret = 0;
+
+  fail:
+
+       tdb_close(mem_tdb);
+       tdb_unlock(tdb, -1, F_WRLCK);
+       return ret;
+}
diff --git a/libatalk/tdb/io.c b/libatalk/tdb/io.c
new file mode 100644 (file)
index 0000000..d549715
--- /dev/null
@@ -0,0 +1,473 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+   
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+
+#include "tdb_private.h"
+
+/* check for an out of bounds access - if it is out of bounds then
+   see if the database has been expanded by someone else and expand
+   if necessary 
+   note that "len" is the minimum length needed for the db
+*/
+static int tdb_oob(struct tdb_context *tdb, tdb_off_t len, int probe)
+{
+       struct stat st;
+       if (len <= tdb->map_size)
+               return 0;
+       if (tdb->flags & TDB_INTERNAL) {
+               if (!probe) {
+                       /* Ensure ecode is set for log fn. */
+                       tdb->ecode = TDB_ERR_IO;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_oob len %d beyond internal malloc size %d\n",
+                                (int)len, (int)tdb->map_size));
+               }
+               return -1;
+       }
+
+       if (fstat(tdb->fd, &st) == -1) {
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+
+       if (st.st_size < (size_t)len) {
+               if (!probe) {
+                       /* Ensure ecode is set for log fn. */
+                       tdb->ecode = TDB_ERR_IO;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_oob len %d beyond eof at %d\n",
+                                (int)len, (int)st.st_size));
+               }
+               return -1;
+       }
+
+       /* Unmap, update size, remap */
+       if (tdb_munmap(tdb) == -1) {
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+       tdb->map_size = st.st_size;
+       tdb_mmap(tdb);
+       return 0;
+}
+
+/* write a lump of data at a specified offset */
+static int tdb_write(struct tdb_context *tdb, tdb_off_t off, 
+                    const void *buf, tdb_len_t len)
+{
+       if (len == 0) {
+               return 0;
+       }
+
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB_ERR_RDONLY;
+               return -1;
+       }
+
+       if (tdb->methods->tdb_oob(tdb, off + len, 0) != 0)
+               return -1;
+
+       if (tdb->map_ptr) {
+               memcpy(off + (char *)tdb->map_ptr, buf, len);
+       } else {
+               ssize_t written = pwrite(tdb->fd, buf, len, off);
+               if ((written != (ssize_t)len) && (written != -1)) {
+                       /* try once more */
+                       tdb->ecode = TDB_ERR_IO;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_write: wrote only "
+                                "%d of %d bytes at %d, trying once more\n",
+                                (int)written, len, off));
+                       written = pwrite(tdb->fd, (const char *)buf+written,
+                                        len-written,
+                                        off+written);
+               }
+               if (written == -1) {
+                       /* Ensure ecode is set for log fn. */
+                       tdb->ecode = TDB_ERR_IO;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_write failed at %d "
+                                "len=%d (%s)\n", off, len, strerror(errno)));
+                       return -1;
+               } else if (written != (ssize_t)len) {
+                       tdb->ecode = TDB_ERR_IO;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_write: failed to "
+                                "write %d bytes at %d in two attempts\n",
+                                len, off));
+                       return -1;
+               }
+       }
+       return 0;
+}
+
+/* Endian conversion: we only ever deal with 4 byte quantities */
+void *tdb_convert(void *buf, uint32_t size)
+{
+       uint32_t i, *p = (uint32_t *)buf;
+       for (i = 0; i < size / 4; i++)
+               p[i] = TDB_BYTEREV(p[i]);
+       return buf;
+}
+
+
+/* read a lump of data at a specified offset, maybe convert */
+static int tdb_read(struct tdb_context *tdb, tdb_off_t off, void *buf, 
+                   tdb_len_t len, int cv)
+{
+       if (tdb->methods->tdb_oob(tdb, off + len, 0) != 0) {
+               return -1;
+       }
+
+       if (tdb->map_ptr) {
+               memcpy(buf, off + (char *)tdb->map_ptr, len);
+       } else {
+               ssize_t ret = pread(tdb->fd, buf, len, off);
+               if (ret != (ssize_t)len) {
+                       /* Ensure ecode is set for log fn. */
+                       tdb->ecode = TDB_ERR_IO;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_read failed at %d "
+                                "len=%d ret=%d (%s) map_size=%d\n",
+                                (int)off, (int)len, (int)ret, strerror(errno),
+                                (int)tdb->map_size));
+                       return -1;
+               }
+       }
+       if (cv) {
+               tdb_convert(buf, len);
+       }
+       return 0;
+}
+
+
+
+/*
+  do an unlocked scan of the hash table heads to find the next non-zero head. The value
+  will then be confirmed with the lock held
+*/             
+static void tdb_next_hash_chain(struct tdb_context *tdb, uint32_t *chain)
+{
+       uint32_t h = *chain;
+       if (tdb->map_ptr) {
+               for (;h < tdb->header.hash_size;h++) {
+                       if (0 != *(uint32_t *)(TDB_HASH_TOP(h) + (unsigned char *)tdb->map_ptr)) {
+                               break;
+                       }
+               }
+       } else {
+               uint32_t off=0;
+               for (;h < tdb->header.hash_size;h++) {
+                       if (tdb_ofs_read(tdb, TDB_HASH_TOP(h), &off) != 0 || off != 0) {
+                               break;
+                       }
+               }
+       }
+       (*chain) = h;
+}
+
+
+int tdb_munmap(struct tdb_context *tdb)
+{
+       if (tdb->flags & TDB_INTERNAL)
+               return 0;
+
+#ifdef HAVE_MMAP
+       if (tdb->map_ptr) {
+               int ret;
+
+               ret = munmap(tdb->map_ptr, tdb->map_size);
+               if (ret != 0)
+                       return ret;
+       }
+#endif
+       tdb->map_ptr = NULL;
+       return 0;
+}
+
+void tdb_mmap(struct tdb_context *tdb)
+{
+       if (tdb->flags & TDB_INTERNAL)
+               return;
+
+#ifdef HAVE_MMAP
+       if (!(tdb->flags & TDB_NOMMAP)) {
+               tdb->map_ptr = mmap(NULL, tdb->map_size, 
+                                   PROT_READ|(tdb->read_only? 0:PROT_WRITE), 
+                                   MAP_SHARED|MAP_FILE, tdb->fd, 0);
+
+               /*
+                * NB. When mmap fails it returns MAP_FAILED *NOT* NULL !!!!
+                */
+
+               if (tdb->map_ptr == MAP_FAILED) {
+                       tdb->map_ptr = NULL;
+                       TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_mmap failed for size %d (%s)\n", 
+                                tdb->map_size, strerror(errno)));
+               }
+       } else {
+               tdb->map_ptr = NULL;
+       }
+#else
+       tdb->map_ptr = NULL;
+#endif
+}
+
+/* expand a file.  we prefer to use ftruncate, as that is what posix
+  says to use for mmap expansion */
+static int tdb_expand_file(struct tdb_context *tdb, tdb_off_t size, tdb_off_t addition)
+{
+       char buf[8192];
+
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB_ERR_RDONLY;
+               return -1;
+       }
+
+       if (ftruncate(tdb->fd, size+addition) == -1) {
+               char b = 0;
+               ssize_t written = pwrite(tdb->fd,  &b, 1, (size+addition) - 1);
+               if (written == 0) {
+                       /* try once more, potentially revealing errno */
+                       written = pwrite(tdb->fd,  &b, 1, (size+addition) - 1);
+               }
+               if (written == 0) {
+                       /* again - give up, guessing errno */
+                       errno = ENOSPC;
+               }
+               if (written != 1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "expand_file to %d failed (%s)\n", 
+                                size+addition, strerror(errno)));
+                       return -1;
+               }
+       }
+
+       /* now fill the file with something. This ensures that the
+          file isn't sparse, which would be very bad if we ran out of
+          disk. This must be done with write, not via mmap */
+       memset(buf, TDB_PAD_BYTE, sizeof(buf));
+       while (addition) {
+               size_t n = addition>sizeof(buf)?sizeof(buf):addition;
+               ssize_t written = pwrite(tdb->fd, buf, n, size);
+               if (written == 0) {
+                       /* prevent infinite loops: try _once_ more */
+                       written = pwrite(tdb->fd, buf, n, size);
+               }
+               if (written == 0) {
+                       /* give up, trying to provide a useful errno */
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "expand_file write "
+                               "returned 0 twice: giving up!\n"));
+                       errno = ENOSPC;
+                       return -1;
+               } else if (written == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "expand_file write of "
+                                "%d bytes failed (%s)\n", (int)n,
+                                strerror(errno)));
+                       return -1;
+               } else if (written != n) {
+                       TDB_LOG((tdb, TDB_DEBUG_WARNING, "expand_file: wrote "
+                                "only %d of %d bytes - retrying\n", (int)written,
+                                (int)n));
+               }
+               addition -= written;
+               size += written;
+       }
+       return 0;
+}
+
+
+/* expand the database at least size bytes by expanding the underlying
+   file and doing the mmap again if necessary */
+int tdb_expand(struct tdb_context *tdb, tdb_off_t size)
+{
+       struct tdb_record rec;
+       tdb_off_t offset, new_size;     
+
+       if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "lock failed in tdb_expand\n"));
+               return -1;
+       }
+
+       /* must know about any previous expansions by another process */
+       tdb->methods->tdb_oob(tdb, tdb->map_size + 1, 1);
+
+       /* always make room for at least 100 more records, and at
+           least 25% more space. Round the database up to a multiple
+           of the page size */
+       new_size = MAX(tdb->map_size + size*100, tdb->map_size * 1.25);
+       size = TDB_ALIGN(new_size, tdb->page_size) - tdb->map_size;
+
+       if (!(tdb->flags & TDB_INTERNAL))
+               tdb_munmap(tdb);
+
+       /*
+        * We must ensure the file is unmapped before doing this
+        * to ensure consistency with systems like OpenBSD where
+        * writes and mmaps are not consistent.
+        */
+
+       /* expand the file itself */
+       if (!(tdb->flags & TDB_INTERNAL)) {
+               if (tdb->methods->tdb_expand_file(tdb, tdb->map_size, size) != 0)
+                       goto fail;
+       }
+
+       tdb->map_size += size;
+
+       if (tdb->flags & TDB_INTERNAL) {
+               char *new_map_ptr = (char *)realloc(tdb->map_ptr,
+                                                   tdb->map_size);
+               if (!new_map_ptr) {
+                       tdb->map_size -= size;
+                       goto fail;
+               }
+               tdb->map_ptr = new_map_ptr;
+       } else {
+               /*
+                * We must ensure the file is remapped before adding the space
+                * to ensure consistency with systems like OpenBSD where
+                * writes and mmaps are not consistent.
+                */
+
+               /* We're ok if the mmap fails as we'll fallback to read/write */
+               tdb_mmap(tdb);
+       }
+
+       /* form a new freelist record */
+       memset(&rec,'\0',sizeof(rec));
+       rec.rec_len = size - sizeof(rec);
+
+       /* link it into the free list */
+       offset = tdb->map_size - size;
+       if (tdb_free(tdb, offset, &rec) == -1)
+               goto fail;
+
+       tdb_unlock(tdb, -1, F_WRLCK);
+       return 0;
+ fail:
+       tdb_unlock(tdb, -1, F_WRLCK);
+       return -1;
+}
+
+/* read/write a tdb_off_t */
+int tdb_ofs_read(struct tdb_context *tdb, tdb_off_t offset, tdb_off_t *d)
+{
+       return tdb->methods->tdb_read(tdb, offset, (char*)d, sizeof(*d), DOCONV());
+}
+
+int tdb_ofs_write(struct tdb_context *tdb, tdb_off_t offset, tdb_off_t *d)
+{
+       tdb_off_t off = *d;
+       return tdb->methods->tdb_write(tdb, offset, CONVERT(off), sizeof(*d));
+}
+
+
+/* read a lump of data, allocating the space for it */
+unsigned char *tdb_alloc_read(struct tdb_context *tdb, tdb_off_t offset, tdb_len_t len)
+{
+       unsigned char *buf;
+
+       /* some systems don't like zero length malloc */
+
+       if (!(buf = (unsigned char *)malloc(len ? len : 1))) {
+               /* Ensure ecode is set for log fn. */
+               tdb->ecode = TDB_ERR_OOM;
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,"tdb_alloc_read malloc failed len=%d (%s)\n",
+                          len, strerror(errno)));
+               return NULL;
+       }
+       if (tdb->methods->tdb_read(tdb, offset, buf, len, 0) == -1) {
+               SAFE_FREE(buf);
+               return NULL;
+       }
+       return buf;
+}
+
+/* Give a piece of tdb data to a parser */
+
+int tdb_parse_data(struct tdb_context *tdb, TDB_DATA key,
+                  tdb_off_t offset, tdb_len_t len,
+                  int (*parser)(TDB_DATA key, TDB_DATA data,
+                                void *private_data),
+                  void *private_data)
+{
+       TDB_DATA data;
+       int result;
+
+       data.dsize = len;
+
+       if ((tdb->transaction == NULL) && (tdb->map_ptr != NULL)) {
+               /*
+                * Optimize by avoiding the malloc/memcpy/free, point the
+                * parser directly at the mmap area.
+                */
+               if (tdb->methods->tdb_oob(tdb, offset+len, 0) != 0) {
+                       return -1;
+               }
+               data.dptr = offset + (unsigned char *)tdb->map_ptr;
+               return parser(key, data, private_data);
+       }
+
+       if (!(data.dptr = tdb_alloc_read(tdb, offset, len))) {
+               return -1;
+       }
+
+       result = parser(key, data, private_data);
+       free(data.dptr);
+       return result;
+}
+
+/* read/write a record */
+int tdb_rec_read(struct tdb_context *tdb, tdb_off_t offset, struct tdb_record *rec)
+{
+       if (tdb->methods->tdb_read(tdb, offset, rec, sizeof(*rec),DOCONV()) == -1)
+               return -1;
+       if (TDB_BAD_MAGIC(rec)) {
+               /* Ensure ecode is set for log fn. */
+               tdb->ecode = TDB_ERR_CORRUPT;
+               TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_rec_read bad magic 0x%x at offset=%d\n", rec->magic, offset));
+               return -1;
+       }
+       return tdb->methods->tdb_oob(tdb, rec->next+sizeof(*rec), 0);
+}
+
+int tdb_rec_write(struct tdb_context *tdb, tdb_off_t offset, struct tdb_record *rec)
+{
+       struct tdb_record r = *rec;
+       return tdb->methods->tdb_write(tdb, offset, CONVERT(r), sizeof(r));
+}
+
+static const struct tdb_methods io_methods = {
+       tdb_read,
+       tdb_write,
+       tdb_next_hash_chain,
+       tdb_oob,
+       tdb_expand_file,
+       tdb_brlock
+};
+
+/*
+  initialise the default methods table
+*/
+void tdb_io_init(struct tdb_context *tdb)
+{
+       tdb->methods = &io_methods;
+}
diff --git a/libatalk/tdb/lock.c b/libatalk/tdb/lock.c
new file mode 100644 (file)
index 0000000..0984e51
--- /dev/null
@@ -0,0 +1,592 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+   
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb_private.h"
+
+#define TDB_MARK_LOCK 0x80000000
+
+void tdb_setalarm_sigptr(struct tdb_context *tdb, volatile sig_atomic_t *ptr)
+{
+       tdb->interrupt_sig_ptr = ptr;
+}
+
+/* a byte range locking function - return 0 on success
+   this functions locks/unlocks 1 byte at the specified offset.
+
+   On error, errno is also set so that errors are passed back properly
+   through tdb_open(). 
+
+   note that a len of zero means lock to end of file
+*/
+int tdb_brlock(struct tdb_context *tdb, tdb_off_t offset, 
+              int rw_type, int lck_type, int probe, size_t len)
+{
+       struct flock fl;
+       int ret;
+
+       if (tdb->flags & TDB_NOLOCK) {
+               return 0;
+       }
+
+       if ((rw_type == F_WRLCK) && (tdb->read_only || tdb->traverse_read)) {
+               tdb->ecode = TDB_ERR_RDONLY;
+               return -1;
+       }
+
+       fl.l_type = rw_type;
+       fl.l_whence = SEEK_SET;
+       fl.l_start = offset;
+       fl.l_len = len;
+       fl.l_pid = 0;
+
+       do {
+               ret = fcntl(tdb->fd,lck_type,&fl);
+
+               /* Check for a sigalarm break. */
+               if (ret == -1 && errno == EINTR &&
+                               tdb->interrupt_sig_ptr &&
+                               *tdb->interrupt_sig_ptr) {
+                       break;
+               }
+       } while (ret == -1 && errno == EINTR);
+
+       if (ret == -1) {
+               tdb->ecode = TDB_ERR_LOCK;
+               /* Generic lock error. errno set by fcntl.
+                * EAGAIN is an expected return from non-blocking
+                * locks. */
+               if (!probe && lck_type != F_SETLK) {
+                       TDB_LOG((tdb, TDB_DEBUG_TRACE,"tdb_brlock failed (fd=%d) at offset %d rw_type=%d lck_type=%d len=%d\n", 
+                                tdb->fd, offset, rw_type, lck_type, (int)len));
+               }
+               return -1;
+       }
+       return 0;
+}
+
+
+/*
+  upgrade a read lock to a write lock. This needs to be handled in a
+  special way as some OSes (such as solaris) have too conservative
+  deadlock detection and claim a deadlock when progress can be
+  made. For those OSes we may loop for a while.  
+*/
+int tdb_brlock_upgrade(struct tdb_context *tdb, tdb_off_t offset, size_t len)
+{
+       int count = 1000;
+       while (count--) {
+               struct timeval tv;
+               if (tdb_brlock(tdb, offset, F_WRLCK, F_SETLKW, 1, len) == 0) {
+                       return 0;
+               }
+               if (errno != EDEADLK) {
+                       break;
+               }
+               /* sleep for as short a time as we can - more portable than usleep() */
+               tv.tv_sec = 0;
+               tv.tv_usec = 1;
+               select(0, NULL, NULL, NULL, &tv);
+       }
+       TDB_LOG((tdb, TDB_DEBUG_TRACE,"tdb_brlock_upgrade failed at offset %d\n", offset));
+       return -1;
+}
+
+
+/* lock a list in the database. list -1 is the alloc list */
+static int _tdb_lock(struct tdb_context *tdb, int list, int ltype, int op)
+{
+       struct tdb_lock_type *new_lck;
+       int i;
+       bool mark_lock = ((ltype & TDB_MARK_LOCK) == TDB_MARK_LOCK);
+
+       ltype &= ~TDB_MARK_LOCK;
+
+       /* a global lock allows us to avoid per chain locks */
+       if (tdb->global_lock.count && 
+           (ltype == tdb->global_lock.ltype || ltype == F_RDLCK)) {
+               return 0;
+       }
+
+       if (tdb->global_lock.count) {
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+
+       if (list < -1 || list >= (int)tdb->header.hash_size) {
+               tdb->ecode = TDB_ERR_LOCK;
+               TDB_LOG((tdb, TDB_DEBUG_ERROR,"tdb_lock: invalid list %d for ltype=%d\n", 
+                          list, ltype));
+               return -1;
+       }
+       if (tdb->flags & TDB_NOLOCK)
+               return 0;
+
+       for (i=0; i<tdb->num_lockrecs; i++) {
+               if (tdb->lockrecs[i].list == list) {
+                       if (tdb->lockrecs[i].count == 0) {
+                               /*
+                                * Can't happen, see tdb_unlock(). It should
+                                * be an assert.
+                                */
+                               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lock: "
+                                        "lck->count == 0 for list %d", list));
+                       }
+                       /*
+                        * Just increment the in-memory struct, posix locks
+                        * don't stack.
+                        */
+                       tdb->lockrecs[i].count++;
+                       return 0;
+               }
+       }
+
+       new_lck = (struct tdb_lock_type *)realloc(
+               tdb->lockrecs,
+               sizeof(*tdb->lockrecs) * (tdb->num_lockrecs+1));
+       if (new_lck == NULL) {
+               errno = ENOMEM;
+               return -1;
+       }
+       tdb->lockrecs = new_lck;
+
+       /* Since fcntl locks don't nest, we do a lock for the first one,
+          and simply bump the count for future ones */
+       if (!mark_lock &&
+           tdb->methods->tdb_brlock(tdb,FREELIST_TOP+4*list, ltype, op,
+                                    0, 1)) {
+               return -1;
+       }
+
+       tdb->num_locks++;
+
+       tdb->lockrecs[tdb->num_lockrecs].list = list;
+       tdb->lockrecs[tdb->num_lockrecs].count = 1;
+       tdb->lockrecs[tdb->num_lockrecs].ltype = ltype;
+       tdb->num_lockrecs += 1;
+
+       return 0;
+}
+
+/* lock a list in the database. list -1 is the alloc list */
+int tdb_lock(struct tdb_context *tdb, int list, int ltype)
+{
+       int ret;
+       ret = _tdb_lock(tdb, list, ltype, F_SETLKW);
+       if (ret) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lock failed on list %d "
+                        "ltype=%d (%s)\n",  list, ltype, strerror(errno)));
+       }
+       return ret;
+}
+
+/* lock a list in the database. list -1 is the alloc list. non-blocking lock */
+int tdb_lock_nonblock(struct tdb_context *tdb, int list, int ltype)
+{
+       return _tdb_lock(tdb, list, ltype, F_SETLK);
+}
+
+
+/* unlock the database: returns void because it's too late for errors. */
+       /* changed to return int it may be interesting to know there
+          has been an error  --simo */
+int tdb_unlock(struct tdb_context *tdb, int list, int ltype)
+{
+       int ret = -1;
+       int i;
+       struct tdb_lock_type *lck = NULL;
+       bool mark_lock = ((ltype & TDB_MARK_LOCK) == TDB_MARK_LOCK);
+
+       ltype &= ~TDB_MARK_LOCK;
+
+       /* a global lock allows us to avoid per chain locks */
+       if (tdb->global_lock.count && 
+           (ltype == tdb->global_lock.ltype || ltype == F_RDLCK)) {
+               return 0;
+       }
+
+       if (tdb->global_lock.count) {
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->flags & TDB_NOLOCK)
+               return 0;
+
+       /* Sanity checks */
+       if (list < -1 || list >= (int)tdb->header.hash_size) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: list %d invalid (%d)\n", list, tdb->header.hash_size));
+               return ret;
+       }
+
+       for (i=0; i<tdb->num_lockrecs; i++) {
+               if (tdb->lockrecs[i].list == list) {
+                       lck = &tdb->lockrecs[i];
+                       break;
+               }
+       }
+
+       if ((lck == NULL) || (lck->count == 0)) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: count is 0\n"));
+               return -1;
+       }
+
+       if (lck->count > 1) {
+               lck->count--;
+               return 0;
+       }
+
+       /*
+        * This lock has count==1 left, so we need to unlock it in the
+        * kernel. We don't bother with decrementing the in-memory array
+        * element, we're about to overwrite it with the last array element
+        * anyway.
+        */
+
+       if (mark_lock) {
+               ret = 0;
+       } else {
+               ret = tdb->methods->tdb_brlock(tdb, FREELIST_TOP+4*list, F_UNLCK,
+                                              F_SETLKW, 0, 1);
+       }
+       tdb->num_locks--;
+
+       /*
+        * Shrink the array by overwriting the element just unlocked with the
+        * last array element.
+        */
+
+       if (tdb->num_lockrecs > 1) {
+               *lck = tdb->lockrecs[tdb->num_lockrecs-1];
+       }
+       tdb->num_lockrecs -= 1;
+
+       /*
+        * We don't bother with realloc when the array shrinks, but if we have
+        * a completely idle tdb we should get rid of the locked array.
+        */
+
+       if (tdb->num_lockrecs == 0) {
+               SAFE_FREE(tdb->lockrecs);
+       }
+
+       if (ret)
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: An error occurred unlocking!\n")); 
+       return ret;
+}
+
+/*
+  get the transaction lock
+ */
+int tdb_transaction_lock(struct tdb_context *tdb, int ltype)
+{
+       if (tdb->global_lock.count) {
+               return 0;
+       }
+       if (tdb->transaction_lock_count > 0) {
+               tdb->transaction_lock_count++;
+               return 0;
+       }
+
+       if (tdb->methods->tdb_brlock(tdb, TRANSACTION_LOCK, ltype, 
+                                    F_SETLKW, 0, 1) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_lock: failed to get transaction lock\n"));
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+       tdb->transaction_lock_count++;
+       return 0;
+}
+
+/*
+  release the transaction lock
+ */
+int tdb_transaction_unlock(struct tdb_context *tdb)
+{
+       int ret;
+       if (tdb->global_lock.count) {
+               return 0;
+       }
+       if (tdb->transaction_lock_count > 1) {
+               tdb->transaction_lock_count--;
+               return 0;
+       }
+       ret = tdb->methods->tdb_brlock(tdb, TRANSACTION_LOCK, F_UNLCK, F_SETLKW, 0, 1);
+       if (ret == 0) {
+               tdb->transaction_lock_count = 0;
+       }
+       return ret;
+}
+
+
+
+
+/* lock/unlock entire database */
+static int _tdb_lockall(struct tdb_context *tdb, int ltype, int op)
+{
+       bool mark_lock = ((ltype & TDB_MARK_LOCK) == TDB_MARK_LOCK);
+
+       ltype &= ~TDB_MARK_LOCK;
+
+       /* There are no locks on read-only dbs */
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->global_lock.count && tdb->global_lock.ltype == ltype) {
+               tdb->global_lock.count++;
+               return 0;
+       }
+
+       if (tdb->global_lock.count) {
+               /* a global lock of a different type exists */
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+       
+       if (tdb->num_locks != 0) {
+               /* can't combine global and chain locks */
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+
+       if (!mark_lock &&
+           tdb->methods->tdb_brlock(tdb, FREELIST_TOP, ltype, op,
+                                    0, 4*tdb->header.hash_size)) {
+               if (op == F_SETLKW) {
+                       TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lockall failed (%s)\n", strerror(errno)));
+               }
+               return -1;
+       }
+
+       tdb->global_lock.count = 1;
+       tdb->global_lock.ltype = ltype;
+
+       return 0;
+}
+
+
+
+/* unlock entire db */
+static int _tdb_unlockall(struct tdb_context *tdb, int ltype)
+{
+       bool mark_lock = ((ltype & TDB_MARK_LOCK) == TDB_MARK_LOCK);
+
+       ltype &= ~TDB_MARK_LOCK;
+
+       /* There are no locks on read-only dbs */
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->global_lock.ltype != ltype || tdb->global_lock.count == 0) {
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->global_lock.count > 1) {
+               tdb->global_lock.count--;
+               return 0;
+       }
+
+       if (!mark_lock &&
+           tdb->methods->tdb_brlock(tdb, FREELIST_TOP, F_UNLCK, F_SETLKW, 
+                                    0, 4*tdb->header.hash_size)) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlockall failed (%s)\n", strerror(errno)));
+               return -1;
+       }
+
+       tdb->global_lock.count = 0;
+       tdb->global_lock.ltype = 0;
+
+       return 0;
+}
+
+/* lock entire database with write lock */
+int tdb_lockall(struct tdb_context *tdb)
+{
+       tdb_trace(tdb, "tdb_lockall");
+       return _tdb_lockall(tdb, F_WRLCK, F_SETLKW);
+}
+
+/* lock entire database with write lock - mark only */
+int tdb_lockall_mark(struct tdb_context *tdb)
+{
+       tdb_trace(tdb, "tdb_lockall_mark");
+       return _tdb_lockall(tdb, F_WRLCK | TDB_MARK_LOCK, F_SETLKW);
+}
+
+/* unlock entire database with write lock - unmark only */
+int tdb_lockall_unmark(struct tdb_context *tdb)
+{
+       tdb_trace(tdb, "tdb_lockall_unmark");
+       return _tdb_unlockall(tdb, F_WRLCK | TDB_MARK_LOCK);
+}
+
+/* lock entire database with write lock - nonblocking varient */
+int tdb_lockall_nonblock(struct tdb_context *tdb)
+{
+       int ret = _tdb_lockall(tdb, F_WRLCK, F_SETLK);
+       tdb_trace_ret(tdb, "tdb_lockall_nonblock", ret);
+       return ret;
+}
+
+/* unlock entire database with write lock */
+int tdb_unlockall(struct tdb_context *tdb)
+{
+       tdb_trace(tdb, "tdb_unlockall");
+       return _tdb_unlockall(tdb, F_WRLCK);
+}
+
+/* lock entire database with read lock */
+int tdb_lockall_read(struct tdb_context *tdb)
+{
+       tdb_trace(tdb, "tdb_lockall_read");
+       return _tdb_lockall(tdb, F_RDLCK, F_SETLKW);
+}
+
+/* lock entire database with read lock - nonblock varient */
+int tdb_lockall_read_nonblock(struct tdb_context *tdb)
+{
+       int ret = _tdb_lockall(tdb, F_RDLCK, F_SETLK);
+       tdb_trace_ret(tdb, "tdb_lockall_read_nonblock", ret);
+       return ret;
+}
+
+/* unlock entire database with read lock */
+int tdb_unlockall_read(struct tdb_context *tdb)
+{
+       tdb_trace(tdb, "tdb_unlockall_read");
+       return _tdb_unlockall(tdb, F_RDLCK);
+}
+
+/* lock/unlock one hash chain. This is meant to be used to reduce
+   contention - it cannot guarantee how many records will be locked */
+int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key)
+{
+       int ret = tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
+       tdb_trace_1rec(tdb, "tdb_chainlock", key);
+       return ret;
+}
+
+/* lock/unlock one hash chain, non-blocking. This is meant to be used
+   to reduce contention - it cannot guarantee how many records will be
+   locked */
+int tdb_chainlock_nonblock(struct tdb_context *tdb, TDB_DATA key)
+{
+       int ret = tdb_lock_nonblock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
+       tdb_trace_1rec_ret(tdb, "tdb_chainlock_nonblock", key, ret);
+       return ret;
+}
+
+/* mark a chain as locked without actually locking it. Warning! use with great caution! */
+int tdb_chainlock_mark(struct tdb_context *tdb, TDB_DATA key)
+{
+       int ret = tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK | TDB_MARK_LOCK);
+       tdb_trace_1rec(tdb, "tdb_chainlock_mark", key);
+       return ret;
+}
+
+/* unmark a chain as locked without actually locking it. Warning! use with great caution! */
+int tdb_chainlock_unmark(struct tdb_context *tdb, TDB_DATA key)
+{
+       tdb_trace_1rec(tdb, "tdb_chainlock_unmark", key);
+       return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK | TDB_MARK_LOCK);
+}
+
+int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key)
+{
+       tdb_trace_1rec(tdb, "tdb_chainunlock", key);
+       return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
+}
+
+int tdb_chainlock_read(struct tdb_context *tdb, TDB_DATA key)
+{
+       int ret;
+       ret = tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_RDLCK);
+       tdb_trace_1rec(tdb, "tdb_chainlock_read", key);
+       return ret;
+}
+
+int tdb_chainunlock_read(struct tdb_context *tdb, TDB_DATA key)
+{
+       tdb_trace_1rec(tdb, "tdb_chainunlock_read", key);
+       return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_RDLCK);
+}
+
+
+
+/* record lock stops delete underneath */
+int tdb_lock_record(struct tdb_context *tdb, tdb_off_t off)
+{
+       if (tdb->global_lock.count) {
+               return 0;
+       }
+       return off ? tdb->methods->tdb_brlock(tdb, off, F_RDLCK, F_SETLKW, 0, 1) : 0;
+}
+
+/*
+  Write locks override our own fcntl readlocks, so check it here.
+  Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
+  an error to fail to get the lock here.
+*/
+int tdb_write_lock_record(struct tdb_context *tdb, tdb_off_t off)
+{
+       struct tdb_traverse_lock *i;
+       for (i = &tdb->travlocks; i; i = i->next)
+               if (i->off == off)
+                       return -1;
+       return tdb->methods->tdb_brlock(tdb, off, F_WRLCK, F_SETLK, 1, 1);
+}
+
+/*
+  Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
+  an error to fail to get the lock here.
+*/
+int tdb_write_unlock_record(struct tdb_context *tdb, tdb_off_t off)
+{
+       return tdb->methods->tdb_brlock(tdb, off, F_UNLCK, F_SETLK, 0, 1);
+}
+
+/* fcntl locks don't stack: avoid unlocking someone else's */
+int tdb_unlock_record(struct tdb_context *tdb, tdb_off_t off)
+{
+       struct tdb_traverse_lock *i;
+       uint32_t count = 0;
+
+       if (tdb->global_lock.count) {
+               return 0;
+       }
+
+       if (off == 0)
+               return 0;
+       for (i = &tdb->travlocks; i; i = i->next)
+               if (i->off == off)
+                       count++;
+       return (count == 1 ? tdb->methods->tdb_brlock(tdb, off, F_UNLCK, F_SETLKW, 0, 1) : 0);
+}
diff --git a/libatalk/tdb/open.c b/libatalk/tdb/open.c
new file mode 100644 (file)
index 0000000..4d4f95a
--- /dev/null
@@ -0,0 +1,552 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+   
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb_private.h"
+
+/* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
+static struct tdb_context *tdbs = NULL;
+
+
+/* This is based on the hash algorithm from gdbm */
+static unsigned int default_tdb_hash(TDB_DATA *key)
+{
+       uint32_t value; /* Used to compute the hash value.  */
+       uint32_t   i;   /* Used to cycle through random values. */
+
+       /* Set the initial value from the key size. */
+       for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
+               value = (value + (key->dptr[i] << (i*5 % 24)));
+
+       return (1103515243 * value + 12345);  
+}
+
+
+/* initialise a new database with a specified hash size */
+static int tdb_new_database(struct tdb_context *tdb, int hash_size)
+{
+       struct tdb_header *newdb;
+       size_t size;
+       int ret = -1;
+       ssize_t written;
+
+       /* We make it up in memory, then write it out if not internal */
+       size = sizeof(struct tdb_header) + (hash_size+1)*sizeof(tdb_off_t);
+       if (!(newdb = (struct tdb_header *)calloc(size, 1))) {
+               tdb->ecode = TDB_ERR_OOM;
+               return -1;
+       }
+
+       /* Fill in the header */
+       newdb->version = TDB_VERSION;
+       newdb->hash_size = hash_size;
+       if (tdb->flags & TDB_INTERNAL) {
+               tdb->map_size = size;
+               tdb->map_ptr = (char *)newdb;
+               memcpy(&tdb->header, newdb, sizeof(tdb->header));
+               /* Convert the `ondisk' version if asked. */
+               CONVERT(*newdb);
+               return 0;
+       }
+       if (lseek(tdb->fd, 0, SEEK_SET) == -1)
+               goto fail;
+
+       if (ftruncate(tdb->fd, 0) == -1)
+               goto fail;
+
+       /* This creates an endian-converted header, as if read from disk */
+       CONVERT(*newdb);
+       memcpy(&tdb->header, newdb, sizeof(tdb->header));
+       /* Don't endian-convert the magic food! */
+       memcpy(newdb->magic_food, TDB_MAGIC_FOOD, strlen(TDB_MAGIC_FOOD)+1);
+       /* we still have "ret == -1" here */
+       written = write(tdb->fd, newdb, size);
+       if (written == size) {
+               ret = 0;
+       } else if (written != -1) {
+               /* call write once again, this usually should return -1 and
+                * set errno appropriately */
+               size -= written;
+               written = write(tdb->fd, newdb+written, size);
+               if (written == size) {
+               ret = 0;
+               } else if (written >= 0) {
+                       /* a second incomplete write - we give up.
+                        * guessing the errno... */
+                       errno = ENOSPC;
+               }
+       }
+
+  fail:
+       SAFE_FREE(newdb);
+       return ret;
+}
+
+
+
+static int tdb_already_open(dev_t device,
+                           ino_t ino)
+{
+       struct tdb_context *i;
+       
+       for (i = tdbs; i; i = i->next) {
+               if (i->device == device && i->inode == ino) {
+                       return 1;
+               }
+       }
+
+       return 0;
+}
+
+/* open the database, creating it if necessary 
+
+   The open_flags and mode are passed straight to the open call on the
+   database file. A flags value of O_WRONLY is invalid. The hash size
+   is advisory, use zero for a default value.
+
+   Return is NULL on error, in which case errno is also set.  Don't 
+   try to call tdb_error or tdb_errname, just do strerror(errno).
+
+   @param name may be NULL for internal databases. */
+struct tdb_context *tdb_open(const char *name, int hash_size, int tdb_flags,
+                     int open_flags, mode_t mode)
+{
+       return tdb_open_ex(name, hash_size, tdb_flags, open_flags, mode, NULL, NULL);
+}
+
+/* a default logging function */
+static void null_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4);
+static void null_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...)
+{
+}
+
+
+struct tdb_context *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
+                               int open_flags, mode_t mode,
+                               const struct tdb_logging_context *log_ctx,
+                               tdb_hash_func hash_fn)
+{
+       struct tdb_context *tdb;
+       struct stat st;
+       int rev = 0, locked = 0;
+       unsigned char *vp;
+       uint32_t vertest;
+       unsigned v;
+
+       if (!(tdb = (struct tdb_context *)calloc(1, sizeof *tdb))) {
+               /* Can't log this */
+               errno = ENOMEM;
+               goto fail;
+       }
+       tdb_io_init(tdb);
+       tdb->fd = -1;
+#ifdef TDB_TRACE
+       tdb->tracefd = -1;
+#endif
+       tdb->name = NULL;
+       tdb->map_ptr = NULL;
+       tdb->flags = tdb_flags;
+       tdb->open_flags = open_flags;
+       if (log_ctx) {
+               tdb->log = *log_ctx;
+       } else {
+               tdb->log.log_fn = null_log_fn;
+               tdb->log.log_private = NULL;
+       }
+       tdb->hash_fn = hash_fn ? hash_fn : default_tdb_hash;
+
+       /* cache the page size */
+       tdb->page_size = getpagesize();
+       if (tdb->page_size <= 0) {
+               tdb->page_size = 0x2000;
+       }
+
+       tdb->max_dead_records = (tdb_flags & TDB_VOLATILE) ? 5 : 0;
+
+       if ((open_flags & O_ACCMODE) == O_WRONLY) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: can't open tdb %s write-only\n",
+                        name));
+               errno = EINVAL;
+               goto fail;
+       }
+       
+       if (hash_size == 0)
+               hash_size = DEFAULT_HASH_SIZE;
+       if ((open_flags & O_ACCMODE) == O_RDONLY) {
+               tdb->read_only = 1;
+               /* read only databases don't do locking or clear if first */
+               tdb->flags |= TDB_NOLOCK;
+               tdb->flags &= ~TDB_CLEAR_IF_FIRST;
+       }
+
+       if ((tdb->flags & TDB_ALLOW_NESTING) &&
+           (tdb->flags & TDB_DISALLOW_NESTING)) {
+               tdb->ecode = TDB_ERR_NESTING;
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
+                       "allow_nesting and disallow_nesting are not allowed together!"));
+               errno = EINVAL;
+               goto fail;
+       }
+
+       /*
+        * TDB_ALLOW_NESTING is the default behavior.
+        * Note: this may change in future versions!
+        */
+       if (!(tdb->flags & TDB_DISALLOW_NESTING)) {
+               tdb->flags |= TDB_ALLOW_NESTING;
+       }
+
+       /* internal databases don't mmap or lock, and start off cleared */
+       if (tdb->flags & TDB_INTERNAL) {
+               tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
+               tdb->flags &= ~TDB_CLEAR_IF_FIRST;
+               if (tdb_new_database(tdb, hash_size) != 0) {
+                       TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: tdb_new_database failed!"));
+                       goto fail;
+               }
+               goto internal;
+       }
+
+       if ((tdb->fd = open(name, open_flags, mode)) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_open_ex: could not open file %s: %s\n",
+                        name, strerror(errno)));
+               goto fail;      /* errno set by open(2) */
+       }
+
+       /* on exec, don't inherit the fd */
+       v = fcntl(tdb->fd, F_GETFD, 0);
+        fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
+
+       /* ensure there is only one process initialising at once */
+       if (tdb->methods->tdb_brlock(tdb, GLOBAL_LOCK, F_WRLCK, F_SETLKW, 0, 1) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to get global lock on %s: %s\n",
+                        name, strerror(errno)));
+               goto fail;      /* errno set by tdb_brlock */
+       }
+
+       /* we need to zero database if we are the only one with it open */
+       if ((tdb_flags & TDB_CLEAR_IF_FIRST) &&
+           (!tdb->read_only) &&
+           (locked = (tdb->methods->tdb_brlock(tdb, ACTIVE_LOCK, F_WRLCK, F_SETLK, 0, 1) == 0))) {
+               open_flags |= O_CREAT;
+               if (ftruncate(tdb->fd, 0) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
+                                "failed to truncate %s: %s\n",
+                                name, strerror(errno)));
+                       goto fail; /* errno set by ftruncate */
+               }
+       }
+
+       errno = 0;
+       if (read(tdb->fd, &tdb->header, sizeof(tdb->header)) != sizeof(tdb->header)
+           || strcmp(tdb->header.magic_food, TDB_MAGIC_FOOD) != 0) {
+               if (!(open_flags & O_CREAT) || tdb_new_database(tdb, hash_size) == -1) {
+                       if (errno == 0) {
+                               errno = EIO; /* ie bad format or something */
+                       }
+                       goto fail;
+               }
+               rev = (tdb->flags & TDB_CONVERT);
+       } else if (tdb->header.version != TDB_VERSION
+                  && !(rev = (tdb->header.version==TDB_BYTEREV(TDB_VERSION)))) {
+               /* wrong version */
+               errno = EIO;
+               goto fail;
+       }
+       vp = (unsigned char *)&tdb->header.version;
+       vertest = (((uint32_t)vp[0]) << 24) | (((uint32_t)vp[1]) << 16) |
+                 (((uint32_t)vp[2]) << 8) | (uint32_t)vp[3];
+       tdb->flags |= (vertest==TDB_VERSION) ? TDB_BIGENDIAN : 0;
+       if (!rev)
+               tdb->flags &= ~TDB_CONVERT;
+       else {
+               tdb->flags |= TDB_CONVERT;
+               tdb_convert(&tdb->header, sizeof(tdb->header));
+       }
+       if (fstat(tdb->fd, &st) == -1)
+               goto fail;
+
+       if (tdb->header.rwlocks != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: spinlocks no longer supported\n"));
+               goto fail;
+       }
+
+       /* Is it already in the open list?  If so, fail. */
+       if (tdb_already_open(st.st_dev, st.st_ino)) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
+                        "%s (%d,%d) is already open in this process\n",
+                        name, (int)st.st_dev, (int)st.st_ino));
+               errno = EBUSY;
+               goto fail;
+       }
+
+       if (!(tdb->name = (char *)strdup(name))) {
+               errno = ENOMEM;
+               goto fail;
+       }
+
+       tdb->map_size = st.st_size;
+       tdb->device = st.st_dev;
+       tdb->inode = st.st_ino;
+       tdb_mmap(tdb);
+       if (locked) {
+               if (tdb->methods->tdb_brlock(tdb, ACTIVE_LOCK, F_UNLCK, F_SETLK, 0, 1) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
+                                "failed to take ACTIVE_LOCK on %s: %s\n",
+                                name, strerror(errno)));
+                       goto fail;
+               }
+
+       }
+
+       /* We always need to do this if the CLEAR_IF_FIRST flag is set, even if
+          we didn't get the initial exclusive lock as we need to let all other
+          users know we're using it. */
+
+       if (tdb_flags & TDB_CLEAR_IF_FIRST) {
+               /* leave this lock in place to indicate it's in use */
+               if (tdb->methods->tdb_brlock(tdb, ACTIVE_LOCK, F_RDLCK, F_SETLKW, 0, 1) == -1)
+                       goto fail;
+       }
+
+       /* if needed, run recovery */
+       if (tdb_transaction_recover(tdb) == -1) {
+               goto fail;
+       }
+
+#ifdef TDB_TRACE
+       {
+               char tracefile[strlen(name) + 32];
+
+               snprintf(tracefile, sizeof(tracefile),
+                        "%s.trace.%li", name, (long)getpid());
+               tdb->tracefd = open(tracefile, O_WRONLY|O_CREAT|O_EXCL, 0600);
+               if (tdb->tracefd >= 0) {
+                       tdb_enable_seqnum(tdb);
+                       tdb_trace_open(tdb, "tdb_open", hash_size, tdb_flags,
+                                      open_flags);
+               } else
+                       TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to open trace file %s!\n", tracefile));
+       }
+#endif
+
+ internal:
+       /* Internal (memory-only) databases skip all the code above to
+        * do with disk files, and resume here by releasing their
+        * global lock and hooking into the active list. */
+       if (tdb->methods->tdb_brlock(tdb, GLOBAL_LOCK, F_UNLCK, F_SETLKW, 0, 1) == -1)
+               goto fail;
+       tdb->next = tdbs;
+       tdbs = tdb;
+       return tdb;
+
+ fail:
+       { int save_errno = errno;
+
+       if (!tdb)
+               return NULL;
+
+#ifdef TDB_TRACE
+       close(tdb->tracefd);
+#endif
+       if (tdb->map_ptr) {
+               if (tdb->flags & TDB_INTERNAL)
+                       SAFE_FREE(tdb->map_ptr);
+               else
+                       tdb_munmap(tdb);
+       }
+       SAFE_FREE(tdb->name);
+       if (tdb->fd != -1)
+               if (close(tdb->fd) != 0)
+                       TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to close tdb->fd on error!\n"));
+       SAFE_FREE(tdb);
+       errno = save_errno;
+       return NULL;
+       }
+}
+
+/*
+ * Set the maximum number of dead records per hash chain
+ */
+
+void tdb_set_max_dead(struct tdb_context *tdb, int max_dead)
+{
+       tdb->max_dead_records = max_dead;
+}
+
+/**
+ * Close a database.
+ *
+ * @returns -1 for error; 0 for success.
+ **/
+int tdb_close(struct tdb_context *tdb)
+{
+       struct tdb_context **i;
+       int ret = 0;
+
+       tdb_trace(tdb, "tdb_close");
+       if (tdb->transaction) {
+               _tdb_transaction_cancel(tdb);
+       }
+
+       if (tdb->map_ptr) {
+               if (tdb->flags & TDB_INTERNAL)
+                       SAFE_FREE(tdb->map_ptr);
+               else
+                       tdb_munmap(tdb);
+       }
+       SAFE_FREE(tdb->name);
+       if (tdb->fd != -1) {
+               ret = close(tdb->fd);
+               tdb->fd = -1;
+       }
+       SAFE_FREE(tdb->lockrecs);
+
+       /* Remove from contexts list */
+       for (i = &tdbs; *i; i = &(*i)->next) {
+               if (*i == tdb) {
+                       *i = tdb->next;
+                       break;
+               }
+       }
+
+#ifdef TDB_TRACE
+       close(tdb->tracefd);
+#endif
+       memset(tdb, 0, sizeof(*tdb));
+       SAFE_FREE(tdb);
+
+       return ret;
+}
+
+/* register a loging function */
+void tdb_set_logging_function(struct tdb_context *tdb,
+                              const struct tdb_logging_context *log_ctx)
+{
+        tdb->log = *log_ctx;
+}
+
+void *tdb_get_logging_private(struct tdb_context *tdb)
+{
+       return tdb->log.log_private;
+}
+
+static int tdb_reopen_internal(struct tdb_context *tdb, bool active_lock)
+{
+#if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
+       !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
+       struct stat st;
+#endif
+
+       if (tdb->flags & TDB_INTERNAL) {
+               return 0; /* Nothing to do. */
+       }
+
+       if (tdb->num_locks != 0 || tdb->global_lock.count) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_reopen: reopen not allowed with locks held\n"));
+               goto fail;
+       }
+
+       if (tdb->transaction != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_reopen: reopen not allowed inside a transaction\n"));
+               goto fail;
+       }
+
+/* If we have real pread & pwrite, we can skip reopen. */
+#if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
+       !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
+       if (tdb_munmap(tdb) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: munmap failed (%s)\n", strerror(errno)));
+               goto fail;
+       }
+       if (close(tdb->fd) != 0)
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: WARNING closing tdb->fd failed!\n"));
+       tdb->fd = open(tdb->name, tdb->open_flags & ~(O_CREAT|O_TRUNC), 0);
+       if (tdb->fd == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: open failed (%s)\n", strerror(errno)));
+               goto fail;
+       }
+       if (fstat(tdb->fd, &st) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: fstat failed (%s)\n", strerror(errno)));
+               goto fail;
+       }
+       if (st.st_ino != tdb->inode || st.st_dev != tdb->device) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: file dev/inode has changed!\n"));
+               goto fail;
+       }
+       tdb_mmap(tdb);
+#endif /* fake pread or pwrite */
+
+       if (active_lock &&
+           (tdb->methods->tdb_brlock(tdb, ACTIVE_LOCK, F_RDLCK, F_SETLKW, 0, 1) == -1)) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: failed to obtain active lock\n"));
+               goto fail;
+       }
+
+       return 0;
+
+fail:
+       tdb_close(tdb);
+       return -1;
+}
+
+/* reopen a tdb - this can be used after a fork to ensure that we have an independent
+   seek pointer from our parent and to re-establish locks */
+int tdb_reopen(struct tdb_context *tdb)
+{
+       return tdb_reopen_internal(tdb, tdb->flags & TDB_CLEAR_IF_FIRST);
+}
+
+/* reopen all tdb's */
+int tdb_reopen_all(int parent_longlived)
+{
+       struct tdb_context *tdb;
+
+       for (tdb=tdbs; tdb; tdb = tdb->next) {
+               bool active_lock = (tdb->flags & TDB_CLEAR_IF_FIRST);
+
+               /*
+                * If the parent is longlived (ie. a
+                * parent daemon architecture), we know
+                * it will keep it's active lock on a
+                * tdb opened with CLEAR_IF_FIRST. Thus
+                * for child processes we don't have to
+                * add an active lock. This is essential
+                * to improve performance on systems that
+                * keep POSIX locks as a non-scalable data
+                * structure in the kernel.
+                */
+               if (parent_longlived) {
+                       /* Ensure no clear-if-first. */
+                       active_lock = false;
+               }
+
+               if (tdb_reopen_internal(tdb, active_lock) != 0)
+                       return -1;
+       }
+
+       return 0;
+}
diff --git a/libatalk/tdb/spinlock.c b/libatalk/tdb/spinlock.c
deleted file mode 100644 (file)
index 7d20106..0000000
+++ /dev/null
@@ -1,431 +0,0 @@
-/* 
-   Unix SMB/CIFS implementation.
-   Samba database functions
-   Copyright (C) Anton Blanchard                   2001
-   
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
-   (at your option) any later version.
-   
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
-   
-   You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-*/
-#define STANDALONE 1
-
-#if HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#if STANDALONE
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <sys/stat.h>
-#include <time.h>
-#include <signal.h>
-#include "spinlock.h"
-
-#define DEBUG
-#else
-#include "includes.h"
-#endif
-
-#ifdef USE_SPINLOCKS
-
-/*
- * ARCH SPECIFIC
- */
-
-#if defined(SPARC_SPINLOCKS)
-
-static inline int __spin_trylock(spinlock_t *lock)
-{
-       unsigned int result;
-
-       asm volatile("ldstub    [%1], %0"
-               : "=r" (result)
-               : "r" (lock)
-               : "memory");
-
-       return (result == 0) ? 0 : EBUSY;
-}
-
-static inline void __spin_unlock(spinlock_t *lock)
-{
-       asm volatile("":::"memory");
-       *lock = 0;
-}
-
-static inline void __spin_lock_init(spinlock_t *lock)
-{
-       *lock = 0;
-}
-
-static inline int __spin_is_locked(spinlock_t *lock)
-{
-       return (*lock != 0);
-}
-
-#elif defined(POWERPC_SPINLOCKS) 
-
-static inline int __spin_trylock(spinlock_t *lock)
-{
-       unsigned int result;
-
-       __asm__ __volatile__(
-"1:    lwarx           %0,0,%1\n\
-       cmpwi           0,%0,0\n\
-       li              %0,0\n\
-       bne-            2f\n\
-       li              %0,1\n\
-       stwcx.          %0,0,%1\n\
-       bne-            1b\n\
-       isync\n\
-2:"    : "=&r"(result)
-       : "r"(lock)
-       : "cr0", "memory");
-
-       return (result == 1) ? 0 : EBUSY;
-}
-
-static inline void __spin_unlock(spinlock_t *lock)
-{
-       asm volatile("eieio":::"memory");
-       *lock = 0;
-}
-
-static inline void __spin_lock_init(spinlock_t *lock)
-{
-       *lock = 0;
-}
-
-static inline int __spin_is_locked(spinlock_t *lock)
-{
-       return (*lock != 0);
-}
-
-#elif defined(INTEL_SPINLOCKS) 
-
-static inline int __spin_trylock(spinlock_t *lock)
-{
-       int oldval;
-
-       asm volatile("xchgl %0,%1"
-               : "=r" (oldval), "=m" (*lock)
-               : "0" (0)
-               : "memory");
-
-       return oldval > 0 ? 0 : EBUSY;
-}
-
-static inline void __spin_unlock(spinlock_t *lock)
-{
-       asm volatile("":::"memory");
-       *lock = 1;
-}
-
-static inline void __spin_lock_init(spinlock_t *lock)
-{
-       *lock = 1;
-}
-
-static inline int __spin_is_locked(spinlock_t *lock)
-{
-       return (*lock != 1);
-}
-
-#elif defined(MIPS_SPINLOCKS) 
-
-static inline unsigned int load_linked(unsigned long addr)
-{
-       unsigned int res;
-
-       __asm__ __volatile__("ll\t%0,(%1)"
-               : "=r" (res)
-               : "r" (addr));
-
-       return res;
-}
-
-static inline unsigned int store_conditional(unsigned long addr, unsigned int value)
-{
-       unsigned int res;
-
-       __asm__ __volatile__("sc\t%0,(%2)"
-               : "=r" (res)
-               : "0" (value), "r" (addr));
-       return res;
-}
-
-static inline int __spin_trylock(spinlock_t *lock)
-{
-       unsigned int mw;
-
-       do {
-               mw = load_linked(lock);
-               if (mw) 
-                       return EBUSY;
-       } while (!store_conditional(lock, 1));
-
-       asm volatile("":::"memory");
-
-       return 0;
-}
-
-static inline void __spin_unlock(spinlock_t *lock)
-{
-       asm volatile("":::"memory");
-       *lock = 0;
-}
-
-static inline void __spin_lock_init(spinlock_t *lock)
-{
-       *lock = 0;
-}
-
-static inline int __spin_is_locked(spinlock_t *lock)
-{
-       return (*lock != 0);
-}
-
-#else
-#error Need to implement spinlock code in spinlock.c
-#endif
-
-/*
- * OS SPECIFIC
- */
-
-static void yield_cpu(void)
-{
-       struct timespec tm;
-
-#ifdef USE_SCHED_YIELD
-       sched_yield();
-#else
-       /* Linux will busy loop for delays < 2ms on real time tasks */
-       tm.tv_sec = 0;
-       tm.tv_nsec = 2000000L + 1;
-       nanosleep(&tm, NULL);
-#endif
-}
-
-static int this_is_smp(void)
-{
-       return 0;
-}
-
-/*
- * GENERIC
- */
-
-static int smp_machine = 0;
-
-static inline void __spin_lock(spinlock_t *lock)
-{
-       int ntries = 0;
-
-       while(__spin_trylock(lock)) {
-               while(__spin_is_locked(lock)) {
-                       if (smp_machine && ntries++ < MAX_BUSY_LOOPS)
-                               continue;
-                       yield_cpu();
-               }
-       }
-}
-
-static void __read_lock(tdb_rwlock_t *rwlock)
-{
-       int ntries = 0;
-
-       while(1) {
-               __spin_lock(&rwlock->lock);
-
-               if (!(rwlock->count & RWLOCK_BIAS)) {
-                       rwlock->count++;
-                       __spin_unlock(&rwlock->lock);
-                       return;
-               }
-       
-               __spin_unlock(&rwlock->lock);
-
-               while(rwlock->count & RWLOCK_BIAS) {
-                       if (smp_machine && ntries++ < MAX_BUSY_LOOPS)
-                               continue;
-                       yield_cpu();
-               }
-       }
-}
-
-static void __write_lock(tdb_rwlock_t *rwlock)
-{
-       int ntries = 0;
-
-       while(1) {
-               __spin_lock(&rwlock->lock);
-
-               if (rwlock->count == 0) {
-                       rwlock->count |= RWLOCK_BIAS;
-                       __spin_unlock(&rwlock->lock);
-                       return;
-               }
-
-               __spin_unlock(&rwlock->lock);
-
-               while(rwlock->count != 0) {
-                       if (smp_machine && ntries++ < MAX_BUSY_LOOPS)
-                               continue;
-                       yield_cpu();
-               }
-       }
-}
-
-static void __write_unlock(tdb_rwlock_t *rwlock)
-{
-       __spin_lock(&rwlock->lock);
-
-#ifdef DEBUG
-       if (!(rwlock->count & RWLOCK_BIAS))
-               fprintf(stderr, "bug: write_unlock\n");
-#endif
-
-       rwlock->count &= ~RWLOCK_BIAS;
-       __spin_unlock(&rwlock->lock);
-}
-
-static void __read_unlock(tdb_rwlock_t *rwlock)
-{
-       __spin_lock(&rwlock->lock);
-
-#ifdef DEBUG
-       if (!rwlock->count)
-               fprintf(stderr, "bug: read_unlock\n");
-
-       if (rwlock->count & RWLOCK_BIAS)
-               fprintf(stderr, "bug: read_unlock\n");
-#endif
-
-       rwlock->count--;
-       __spin_unlock(&rwlock->lock);
-}
-
-/* TDB SPECIFIC */
-
-/* lock a list in the database. list -1 is the alloc list */
-int tdb_spinlock(TDB_CONTEXT *tdb, int list, int rw_type)
-{
-       tdb_rwlock_t *rwlocks;
-
-       if (!tdb->map_ptr) return -1;
-       rwlocks = (tdb_rwlock_t *)((char *)tdb->map_ptr + tdb->header.rwlocks);
-
-       switch(rw_type) {
-       case F_RDLCK:
-               __read_lock(&rwlocks[list+1]);
-               break;
-
-       case F_WRLCK:
-               __write_lock(&rwlocks[list+1]);
-               break;
-
-       default:
-               return TDB_ERRCODE(TDB_ERR_LOCK, -1);
-       }
-       return 0;
-}
-
-/* unlock the database. */
-int tdb_spinunlock(TDB_CONTEXT *tdb, int list, int rw_type)
-{
-       tdb_rwlock_t *rwlocks;
-
-       if (!tdb->map_ptr) return -1;
-       rwlocks = (tdb_rwlock_t *)((char *)tdb->map_ptr + tdb->header.rwlocks);
-
-       switch(rw_type) {
-       case F_RDLCK:
-               __read_unlock(&rwlocks[list+1]);
-               break;
-
-       case F_WRLCK:
-               __write_unlock(&rwlocks[list+1]);
-               break;
-
-       default:
-               return TDB_ERRCODE(TDB_ERR_LOCK, -1);
-       }
-
-       return 0;
-}
-
-int tdb_create_rwlocks(int fd, unsigned int hash_size)
-{
-       unsigned size, i;
-       tdb_rwlock_t *rwlocks;
-
-       size = (hash_size + 1) * sizeof(tdb_rwlock_t);
-       rwlocks = malloc(size);
-       if (!rwlocks)
-               return -1;
-
-       for(i = 0; i < hash_size+1; i++) {
-               __spin_lock_init(&rwlocks[i].lock);
-               rwlocks[i].count = 0;
-       }
-
-       /* Write it out (appending to end) */
-       if (write(fd, rwlocks, size) != size) {
-               free(rwlocks);
-               return -1;
-       }
-       smp_machine = this_is_smp();
-       free(rwlocks);
-       return 0;
-}
-
-int tdb_clear_spinlocks(TDB_CONTEXT *tdb)
-{
-       tdb_rwlock_t *rwlocks;
-       unsigned i;
-
-       if (tdb->header.rwlocks == 0) return 0;
-       if (!tdb->map_ptr) return -1;
-
-       /* We're mmapped here */
-       rwlocks = (tdb_rwlock_t *)((char *)tdb->map_ptr + tdb->header.rwlocks);
-       for(i = 0; i < tdb->header.hash_size+1; i++) {
-               __spin_lock_init(&rwlocks[i].lock);
-               rwlocks[i].count = 0;
-       }
-       return 0;
-}
-#else
-int tdb_create_rwlocks(int fd, unsigned int hash_size) { return 0; }
-int tdb_spinlock(TDB_CONTEXT *tdb, int list, int rw_type) { return -1; }
-int tdb_spinunlock(TDB_CONTEXT *tdb, int list, int rw_type) { return -1; }
-
-/* Non-spinlock version: remove spinlock pointer */
-int tdb_clear_spinlocks(TDB_CONTEXT *tdb)
-{
-       tdb_off off = (tdb_off)((char *)&tdb->header.rwlocks
-                               - (char *)&tdb->header);
-
-       tdb->header.rwlocks = 0;
-       if (lseek(tdb->fd, off, SEEK_SET) != off
-           || write(tdb->fd, (void *)&tdb->header.rwlocks,
-                    sizeof(tdb->header.rwlocks)) 
-           != sizeof(tdb->header.rwlocks))
-               return -1;
-       return 0;
-}
-#endif
diff --git a/libatalk/tdb/spinlock.h b/libatalk/tdb/spinlock.h
deleted file mode 100644 (file)
index 3c5d47a..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-#ifndef __SPINLOCK_H__
-#define __SPINLOCK_H__
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <atalk/tdb.h>
-
-#ifdef USE_SPINLOCKS
-
-#define RWLOCK_BIAS 0x1000UL
-
-/* OS SPECIFIC */
-#define MAX_BUSY_LOOPS 1000
-#undef USE_SCHED_YIELD
-
-/* ARCH SPECIFIC */
-/* We should make sure these are padded to a cache line */
-#if defined(SPARC_SPINLOCKS)
-typedef volatile char spinlock_t;
-#elif defined(POWERPC_SPINLOCKS)
-typedef volatile unsigned long spinlock_t;
-#elif defined(INTEL_SPINLOCKS)
-typedef volatile int spinlock_t;
-#elif defined(MIPS_SPINLOCKS)
-typedef volatile unsigned long spinlock_t;
-#else
-#error Need to implement spinlock code in spinlock.h
-#endif
-
-typedef struct {
-       spinlock_t lock;
-       volatile int count;
-} tdb_rwlock_t;
-
-int tdb_spinlock(TDB_CONTEXT *tdb, int list, int rw_type);
-int tdb_spinunlock(TDB_CONTEXT *tdb, int list, int rw_type);
-int tdb_create_rwlocks(int fd, unsigned int hash_size);
-int tdb_clear_spinlocks(TDB_CONTEXT *tdb);
-
-#else /* !USE_SPINLOCKS */
-#if 0
-#define tdb_create_rwlocks(fd, hash_size) 0
-#define tdb_spinlock(tdb, list, rw_type) (-1)
-#define tdb_spinunlock(tdb, list, rw_type) (-1)
-#else
-int tdb_spinlock(TDB_CONTEXT *tdb, int list, int rw_type);
-int tdb_spinunlock(TDB_CONTEXT *tdb, int list, int rw_type);
-int tdb_create_rwlocks(int fd, unsigned int hash_size);
-#endif
-int tdb_clear_spinlocks(TDB_CONTEXT *tdb);
-#endif
-
-#endif
index f258010100f080c06572b94c19b6552c7033957c..d2688def04743ae4e03cc84489cf251bec30dc8b 100644 (file)
  /* 
    Unix SMB/CIFS implementation.
-   Samba database functions
-   Copyright (C) Andrew Tridgell              1999-2000
-   Copyright (C) Luke Kenneth Casson Leighton      2000
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
    Copyright (C) Paul `Rusty' Russell             2000
    Copyright (C) Jeremy Allison                           2000-2003
    
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
-   (at your option) any later version.
-   
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
    
-   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., 675 Mass Ave, Cambridge, MA 02139, USA.
-*/
-
-#define STANDALONE 1
-
-/* NOTE: If you use tdbs under valgrind, and in particular if you run
- * tdbtorture, you may get spurious "uninitialized value" warnings.  I
- * think this is because valgrind doesn't understand that the mmap'd
- * area may be written to by other processes.  Memory can, from the
- * point of view of the grinded process, spontaneously become
- * initialized.
- *
- * I can think of a few solutions.  [mbp 20030311]
- *
- * 1 - Write suppressions for Valgrind so that it doesn't complain
- * about this.  Probably the most reasonable but people need to
- * remember to use them.
- *
- * 2 - Use IO not mmap when running under valgrind.  Not so nice.
- *
- * 3 - Use the special valgrind macros to mark memory as valid at the
- * right time.  Probably too hard -- the process just doesn't know.
- */ 
-
-#ifdef STANDALONE
-#if HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#define _XOPEN_SOURCE 600
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <string.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <sys/mman.h>
-#include <sys/stat.h>
-#include <signal.h>
-#include "spinlock.h"
-#else
-#include "includes.h"
-#endif
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
 
-#define TDB_MAGIC_FOOD "TDB file\n"
-#define TDB_VERSION (0x26011967 + 6)
-#define TDB_MAGIC (0x26011999U)
-#define TDB_FREE_MAGIC (~TDB_MAGIC)
-#define TDB_DEAD_MAGIC (0xFEE1DEAD)
-#define TDB_ALIGNMENT 4
-#define MIN_REC_SIZE (2*sizeof(struct list_struct) + TDB_ALIGNMENT)
-#define DEFAULT_HASH_SIZE 131
-#define TDB_PAGE_SIZE 0x2000
-#define FREELIST_TOP (sizeof(struct tdb_header))
-#define TDB_ALIGN(x,a) (((x) + (a)-1) & ~((a)-1))
-#define TDB_BYTEREV(x) (((((x)&0xff)<<24)|((x)&0xFF00)<<8)|(((x)>>8)&0xFF00)|((x)>>24))
-#define TDB_DEAD(r) ((r)->magic == TDB_DEAD_MAGIC)
-#define TDB_BAD_MAGIC(r) ((r)->magic != TDB_MAGIC && !TDB_DEAD(r))
-#define TDB_HASH_TOP(hash) (FREELIST_TOP + (BUCKET(hash)+1)*sizeof(tdb_off))
-
-/* NB assumes there is a local variable called "tdb" that is the
- * current context, also takes doubly-parenthesized print-style
- * argument. */
-#define TDB_LOG(x) (tdb->log_fn?((tdb->log_fn x),0) : 0)
-
-/* lock offsets */
-#define GLOBAL_LOCK 0
-#define ACTIVE_LOCK 4
-
-#ifndef MAP_FILE
-#define MAP_FILE 0
-#endif
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
 
-#ifndef MAP_FAILED
-#define MAP_FAILED ((void *)-1)
-#endif
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
 
-/* free memory if the pointer is valid and zero the pointer */
-#ifndef SAFE_FREE
-#define SAFE_FREE(x) do { if ((x) != NULL) {free((x)); (x)=NULL;} } while(0)
-#endif
+#include "tdb_private.h"
 
-#define BUCKET(hash) ((hash) % tdb->header.hash_size)
 TDB_DATA tdb_null;
 
-/* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
-static TDB_CONTEXT *tdbs = NULL;
-
-static int tdb_munmap(TDB_CONTEXT *tdb)
-{
-       if (tdb->flags & TDB_INTERNAL)
-               return 0;
-
-#ifdef HAVE_MMAP
-       if (tdb->map_ptr) {
-               int ret = munmap(tdb->map_ptr, tdb->map_size);
-               if (ret != 0)
-                       return ret;
-       }
-#endif
-       tdb->map_ptr = NULL;
-       return 0;
-}
-
-static void tdb_mmap(TDB_CONTEXT *tdb)
+/*
+  non-blocking increment of the tdb sequence number if the tdb has been opened using
+  the TDB_SEQNUM flag
+*/
+void tdb_increment_seqnum_nonblock(struct tdb_context *tdb)
 {
-       if (tdb->flags & TDB_INTERNAL)
+       tdb_off_t seqnum=0;
+       
+       if (!(tdb->flags & TDB_SEQNUM)) {
                return;
-
-#ifdef HAVE_MMAP
-       if (!(tdb->flags & TDB_NOMMAP)) {
-               tdb->map_ptr = mmap(NULL, tdb->map_size, 
-                                   PROT_READ|(tdb->read_only? 0:PROT_WRITE), 
-                                   MAP_SHARED|MAP_FILE, tdb->fd, 0);
-
-               /*
-                * NB. When mmap fails it returns MAP_FAILED *NOT* NULL !!!!
-                */
-
-               if (tdb->map_ptr == MAP_FAILED) {
-                       tdb->map_ptr = NULL;
-                       TDB_LOG((tdb, 2, "tdb_mmap failed for size %d (%s)\n", 
-                                tdb->map_size, strerror(errno)));
-               }
-       } else {
-               tdb->map_ptr = NULL;
        }
-#else
-       tdb->map_ptr = NULL;
-#endif
-}
 
-/* Endian conversion: we only ever deal with 4 byte quantities */
-static void *convert(void *buf, u32 size)
-{
-       u32 i, *p = buf;
-       for (i = 0; i < size / 4; i++)
-               p[i] = TDB_BYTEREV(p[i]);
-       return buf;
-}
-#define DOCONV() (tdb->flags & TDB_CONVERT)
-#define CONVERT(x) (DOCONV() ? convert(&x, sizeof(x)) : &x)
-
-/* the body of the database is made of one list_struct for the free space
-   plus a separate data list for each hash value */
-struct list_struct {
-       tdb_off next; /* offset of the next record in the list */
-       tdb_len rec_len; /* total byte length of record */
-       tdb_len key_len; /* byte length of key */
-       tdb_len data_len; /* byte length of data */
-       u32 full_hash; /* the full 32 bit hash of the key */
-       u32 magic;   /* try to catch errors */
-       /* the following union is implied:
-               union {
-                       char record[rec_len];
-                       struct {
-                               char key[key_len];
-                               char data[data_len];
-                       }
-                       u32 totalsize; (tailer)
-               }
+       /* we ignore errors from this, as we have no sane way of
+          dealing with them.
        */
-};
-
-/***************************************************************
- Allow a caller to set a "alarm" flag that tdb can check to abort
- a blocking lock on SIGALRM.
-***************************************************************/
-
-static sig_atomic_t *palarm_fired;
-
-void tdb_set_lock_alarm(sig_atomic_t *palarm)
-{
-       palarm_fired = palarm;
+       tdb_ofs_read(tdb, TDB_SEQNUM_OFS, &seqnum);
+       seqnum++;
+       tdb_ofs_write(tdb, TDB_SEQNUM_OFS, &seqnum);
 }
 
-/* a byte range locking function - return 0 on success
-   this functions locks/unlocks 1 byte at the specified offset.
-
-   On error, errno is also set so that errors are passed back properly
-   through tdb_open(). */
-static int tdb_brlock(TDB_CONTEXT *tdb, tdb_off offset, 
-                     int rw_type, int lck_type, int probe)
-{
-       struct flock fl;
-       int ret;
-
-       if (tdb->flags & TDB_NOLOCK)
-               return 0;
-       if ((rw_type == F_WRLCK) && (tdb->read_only)) {
-               errno = EACCES;
-               return -1;
-       }
-
-       fl.l_type = rw_type;
-       fl.l_whence = SEEK_SET;
-       fl.l_start = offset;
-       fl.l_len = 1;
-       fl.l_pid = 0;
-
-       do {
-               ret = fcntl(tdb->fd,lck_type,&fl);
-               if (ret == -1 && errno == EINTR && palarm_fired && *palarm_fired)
-                       break;
-       } while (ret == -1 && errno == EINTR);
-
-       if (ret == -1) {
-               if (!probe && lck_type != F_SETLK) {
-                       /* Ensure error code is set for log fun to examine. */
-                       if (errno == EINTR && palarm_fired && *palarm_fired)
-                               tdb->ecode = TDB_ERR_LOCK_TIMEOUT;
-                       else
-                               tdb->ecode = TDB_ERR_LOCK;
-                       TDB_LOG((tdb, 5,"tdb_brlock failed (fd=%d) at offset %d rw_type=%d lck_type=%d\n", 
-                                tdb->fd, offset, rw_type, lck_type));
-               }
-               /* Was it an alarm timeout ? */
-               if (errno == EINTR && palarm_fired && *palarm_fired)
-                       return TDB_ERRCODE(TDB_ERR_LOCK_TIMEOUT, -1);
-               /* Otherwise - generic lock error. */
-               /* errno set by fcntl */
-               return TDB_ERRCODE(TDB_ERR_LOCK, -1);
-       }
-       return 0;
-}
-
-/* lock a list in the database. list -1 is the alloc list */
-static int tdb_lock(TDB_CONTEXT *tdb, int list, int ltype)
-{
-       if (list < -1 || list >= (int)tdb->header.hash_size) {
-               TDB_LOG((tdb, 0,"tdb_lock: invalid list %d for ltype=%d\n", 
-                          list, ltype));
-               return -1;
-       }
-       if (tdb->flags & TDB_NOLOCK)
-               return 0;
-
-       /* Since fcntl locks don't nest, we do a lock for the first one,
-          and simply bump the count for future ones */
-       if (tdb->locked[list+1].count == 0) {
-               if (!tdb->read_only && tdb->header.rwlocks) {
-                       if (tdb_spinlock(tdb, list, ltype)) {
-                               TDB_LOG((tdb, 0, "tdb_lock spinlock failed on list ltype=%d\n", 
-                                          list, ltype));
-                               return -1;
-                       }
-               } else if (tdb_brlock(tdb,FREELIST_TOP+4*list,ltype,F_SETLKW, 0)) {
-                       TDB_LOG((tdb, 0,"tdb_lock failed on list %d ltype=%d (%s)\n", 
-                                          list, ltype, strerror(errno)));
-                       return -1;
-               }
-               tdb->locked[list+1].ltype = ltype;
-       }
-       tdb->locked[list+1].count++;
-       return 0;
-}
-
-/* unlock the database: returns void because it's too late for errors. */
-       /* changed to return int it may be interesting to know there
-          has been an error  --simo */
-static int tdb_unlock(TDB_CONTEXT *tdb, int list, int ltype)
-{
-       int ret = -1;
-
-       if (tdb->flags & TDB_NOLOCK)
-               return 0;
-
-       /* Sanity checks */
-       if (list < -1 || list >= (int)tdb->header.hash_size) {
-               TDB_LOG((tdb, 0, "tdb_unlock: list %d invalid (%d)\n", list, tdb->header.hash_size));
-               return ret;
-       }
-
-       if (tdb->locked[list+1].count==0) {
-               TDB_LOG((tdb, 0, "tdb_unlock: count is 0\n"));
-               return ret;
-       }
-
-       if (tdb->locked[list+1].count == 1) {
-               /* Down to last nested lock: unlock underneath */
-               if (!tdb->read_only && tdb->header.rwlocks) {
-                       ret = tdb_spinunlock(tdb, list, ltype);
-               } else {
-                       ret = tdb_brlock(tdb, FREELIST_TOP+4*list, F_UNLCK, F_SETLKW, 0);
-               }
-       } else {
-               ret = 0;
-       }
-       tdb->locked[list+1].count--;
-
-       if (ret)
-               TDB_LOG((tdb, 0,"tdb_unlock: An error occurred unlocking!\n")); 
-       return ret;
-}
-
-/* This is based on the hash algorithm from gdbm */
-static u32 tdb_hash(TDB_DATA *key)
-{
-       u32 value;      /* Used to compute the hash value.  */
-       u32   i;        /* Used to cycle through random values. */
-
-       /* Set the initial value from the key size. */
-       for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
-               value = (value + (key->dptr[i] << (i*5 % 24)));
-
-       return (1103515243 * value + 12345);  
-}
-
-/* check for an out of bounds access - if it is out of bounds then
-   see if the database has been expanded by someone else and expand
-   if necessary 
-   note that "len" is the minimum length needed for the db
+/*
+  increment the tdb sequence number if the tdb has been opened using
+  the TDB_SEQNUM flag
 */
-static int tdb_oob(TDB_CONTEXT *tdb, tdb_off len, int probe)
-{
-       struct stat st;
-       if (len <= tdb->map_size)
-               return 0;
-       if (tdb->flags & TDB_INTERNAL) {
-               if (!probe) {
-                       /* Ensure ecode is set for log fn. */
-                       tdb->ecode = TDB_ERR_IO;
-                       TDB_LOG((tdb, 0,"tdb_oob len %d beyond internal malloc size %d\n",
-                                (int)len, (int)tdb->map_size));
-               }
-               return TDB_ERRCODE(TDB_ERR_IO, -1);
-       }
-
-       if (fstat(tdb->fd, &st) == -1)
-               return TDB_ERRCODE(TDB_ERR_IO, -1);
-
-       if (st.st_size < (size_t)len) {
-               if (!probe) {
-                       /* Ensure ecode is set for log fn. */
-                       tdb->ecode = TDB_ERR_IO;
-                       TDB_LOG((tdb, 0,"tdb_oob len %d beyond eof at %d\n",
-                                (int)len, (int)st.st_size));
-               }
-               return TDB_ERRCODE(TDB_ERR_IO, -1);
-       }
-
-       /* Unmap, update size, remap */
-       if (tdb_munmap(tdb) == -1)
-               return TDB_ERRCODE(TDB_ERR_IO, -1);
-       tdb->map_size = st.st_size;
-       tdb_mmap(tdb);
-       return 0;
-}
-
-/* write a lump of data at a specified offset */
-static int tdb_write(TDB_CONTEXT *tdb, tdb_off off, void *buf, tdb_len len)
-{
-       if (tdb_oob(tdb, off + len, 0) != 0)
-               return -1;
-
-       if (tdb->map_ptr)
-               memcpy(off + (char *)tdb->map_ptr, buf, len);
-#ifdef HAVE_PWRITE
-       else if (pwrite(tdb->fd, buf, len, off) != (ssize_t)len) {
-#else
-       else if (lseek(tdb->fd, off, SEEK_SET) != off
-                || write(tdb->fd, buf, len) != (ssize_t)len) {
-#endif
-               /* Ensure ecode is set for log fn. */
-               tdb->ecode = TDB_ERR_IO;
-               TDB_LOG((tdb, 0,"tdb_write failed at %d len=%d (%s)\n",
-                          off, len, strerror(errno)));
-               return TDB_ERRCODE(TDB_ERR_IO, -1);
-       }
-       return 0;
-}
-
-/* read a lump of data at a specified offset, maybe convert */
-static int tdb_read(TDB_CONTEXT *tdb,tdb_off off,void *buf,tdb_len len,int cv)
-{
-       if (tdb_oob(tdb, off + len, 0) != 0)
-               return -1;
-
-       if (tdb->map_ptr)
-               memcpy(buf, off + (char *)tdb->map_ptr, len);
-#ifdef HAVE_PREAD
-       else if (pread(tdb->fd, buf, len, off) != (ssize_t)len) {
-#else
-       else if (lseek(tdb->fd, off, SEEK_SET) != off
-                || read(tdb->fd, buf, len) != (ssize_t)len) {
-#endif
-               /* Ensure ecode is set for log fn. */
-               tdb->ecode = TDB_ERR_IO;
-               TDB_LOG((tdb, 0,"tdb_read failed at %d len=%d (%s)\n",
-                          off, len, strerror(errno)));
-               return TDB_ERRCODE(TDB_ERR_IO, -1);
-       }
-       if (cv)
-               convert(buf, len);
-       return 0;
-}
-
-/* read a lump of data, allocating the space for it */
-static char *tdb_alloc_read(TDB_CONTEXT *tdb, tdb_off offset, tdb_len len)
-{
-       char *buf;
-
-       if (!(buf = malloc(len))) {
-               /* Ensure ecode is set for log fn. */
-               tdb->ecode = TDB_ERR_OOM;
-               TDB_LOG((tdb, 0,"tdb_alloc_read malloc failed len=%d (%s)\n",
-                          len, strerror(errno)));
-               return TDB_ERRCODE(TDB_ERR_OOM, buf);
-       }
-       if (tdb_read(tdb, offset, buf, len, 0) == -1) {
-               SAFE_FREE(buf);
-               return NULL;
-       }
-       return buf;
-}
-
-/* read/write a tdb_off */
-static int ofs_read(TDB_CONTEXT *tdb, tdb_off offset, tdb_off *d)
-{
-       return tdb_read(tdb, offset, (char*)d, sizeof(*d), DOCONV());
-}
-static int ofs_write(TDB_CONTEXT *tdb, tdb_off offset, tdb_off *d)
-{
-       tdb_off off = *d;
-       return tdb_write(tdb, offset, CONVERT(off), sizeof(*d));
-}
-
-/* read/write a record */
-static int rec_read(TDB_CONTEXT *tdb, tdb_off offset, struct list_struct *rec)
-{
-       if (tdb_read(tdb, offset, rec, sizeof(*rec),DOCONV()) == -1)
-               return -1;
-       if (TDB_BAD_MAGIC(rec)) {
-               /* Ensure ecode is set for log fn. */
-               tdb->ecode = TDB_ERR_CORRUPT;
-               TDB_LOG((tdb, 0,"rec_read bad magic 0x%x at offset=%d\n", rec->magic, offset));
-               return TDB_ERRCODE(TDB_ERR_CORRUPT, -1);
-       }
-       return tdb_oob(tdb, rec->next+sizeof(*rec), 0);
-}
-static int rec_write(TDB_CONTEXT *tdb, tdb_off offset, struct list_struct *rec)
-{
-       struct list_struct r = *rec;
-       return tdb_write(tdb, offset, CONVERT(r), sizeof(r));
-}
-
-/* read a freelist record and check for simple errors */
-static int rec_free_read(TDB_CONTEXT *tdb, tdb_off off, struct list_struct *rec)
-{
-       if (tdb_read(tdb, off, rec, sizeof(*rec),DOCONV()) == -1)
-               return -1;
-
-       if (rec->magic == TDB_MAGIC) {
-               /* this happens when a app is showdown while deleting a record - we should
-                  not completely fail when this happens */
-               TDB_LOG((tdb, 0,"rec_free_read non-free magic at offset=%d - fixing\n", 
-                        rec->magic, off));
-               rec->magic = TDB_FREE_MAGIC;
-               if (tdb_write(tdb, off, rec, sizeof(*rec)) == -1)
-                       return -1;
-       }
-
-       if (rec->magic != TDB_FREE_MAGIC) {
-               /* Ensure ecode is set for log fn. */
-               tdb->ecode = TDB_ERR_CORRUPT;
-               TDB_LOG((tdb, 0,"rec_free_read bad magic 0x%x at offset=%d\n", 
-                          rec->magic, off));
-               return TDB_ERRCODE(TDB_ERR_CORRUPT, -1);
-       }
-       if (tdb_oob(tdb, rec->next+sizeof(*rec), 0) != 0)
-               return -1;
-       return 0;
-}
-
-/* update a record tailer (must hold allocation lock) */
-static int update_tailer(TDB_CONTEXT *tdb, tdb_off offset,
-                        const struct list_struct *rec)
-{
-       tdb_off totalsize;
-
-       /* Offset of tailer from record header */
-       totalsize = sizeof(*rec) + rec->rec_len;
-       return ofs_write(tdb, offset + totalsize - sizeof(tdb_off),
-                        &totalsize);
-}
-
-static tdb_off tdb_dump_record(TDB_CONTEXT *tdb, tdb_off offset)
-{
-       struct list_struct rec;
-       tdb_off tailer_ofs, tailer;
-
-       if (tdb_read(tdb, offset, (char *)&rec, sizeof(rec), DOCONV()) == -1) {
-               printf("ERROR: failed to read record at %u\n", offset);
-               return 0;
-       }
-
-       printf(" rec: offset=%u next=%d rec_len=%d key_len=%d data_len=%d full_hash=0x%x magic=0x%x\n",
-              offset, rec.next, rec.rec_len, rec.key_len, rec.data_len, rec.full_hash, rec.magic);
-
-       tailer_ofs = offset + sizeof(rec) + rec.rec_len - sizeof(tdb_off);
-       if (ofs_read(tdb, tailer_ofs, &tailer) == -1) {
-               printf("ERROR: failed to read tailer at %u\n", tailer_ofs);
-               return rec.next;
-       }
-
-       if (tailer != rec.rec_len + sizeof(rec)) {
-               printf("ERROR: tailer does not match record! tailer=%u totalsize=%u\n",
-                               (unsigned)tailer, (unsigned)(rec.rec_len + sizeof(rec)));
-       }
-       return rec.next;
-}
-
-static int tdb_dump_chain(TDB_CONTEXT *tdb, int i)
-{
-       tdb_off rec_ptr, top;
-
-       top = TDB_HASH_TOP(i);
-
-       if (tdb_lock(tdb, i, F_WRLCK) != 0)
-               return -1;
-
-       if (ofs_read(tdb, top, &rec_ptr) == -1)
-               return tdb_unlock(tdb, i, F_WRLCK);
-
-       if (rec_ptr)
-               printf("hash=%d\n", i);
-
-       while (rec_ptr) {
-               rec_ptr = tdb_dump_record(tdb, rec_ptr);
-       }
-
-       return tdb_unlock(tdb, i, F_WRLCK);
-}
-
-void tdb_dump_all(TDB_CONTEXT *tdb)
-{
-       unsigned int i;
-       for (i=0;i<tdb->header.hash_size;i++) {
-               tdb_dump_chain(tdb, i);
-       }
-       printf("freelist:\n");
-       tdb_dump_chain(tdb, -1);
-}
-
-int tdb_printfreelist(TDB_CONTEXT *tdb)
-{
-       int ret;
-       long total_free = 0;
-       tdb_off offset, rec_ptr;
-       struct list_struct rec;
-
-       if ((ret = tdb_lock(tdb, -1, F_WRLCK)) != 0)
-               return ret;
-
-       offset = FREELIST_TOP;
-
-       /* read in the freelist top */
-       if (ofs_read(tdb, offset, &rec_ptr) == -1) {
-               tdb_unlock(tdb, -1, F_WRLCK);
-               return 0;
-       }
-
-       printf("freelist top=[0x%08x]\n", rec_ptr );
-       while (rec_ptr) {
-               if (tdb_read(tdb, rec_ptr, (char *)&rec, sizeof(rec), DOCONV()) == -1) {
-                       tdb_unlock(tdb, -1, F_WRLCK);
-                       return -1;
-               }
-
-               if (rec.magic != TDB_FREE_MAGIC) {
-                       printf("bad magic 0x%08x in free list\n", rec.magic);
-                       tdb_unlock(tdb, -1, F_WRLCK);
-                       return -1;
-               }
-
-               printf("entry offset=[0x%08x], rec.rec_len = [0x%08x (%d)]\n", rec.next, rec.rec_len, rec.rec_len );
-               total_free += rec.rec_len;
-
-               /* move to the next record */
-               rec_ptr = rec.next;
-       }
-       printf("total rec_len = [0x%08x (%d)]\n", (int)total_free, 
-               (int)total_free);
-
-       return tdb_unlock(tdb, -1, F_WRLCK);
-}
-
-/* Remove an element from the freelist.  Must have alloc lock. */
-static int remove_from_freelist(TDB_CONTEXT *tdb, tdb_off off, tdb_off next)
-{
-       tdb_off last_ptr, i;
-
-       /* read in the freelist top */
-       last_ptr = FREELIST_TOP;
-       while (ofs_read(tdb, last_ptr, &i) != -1 && i != 0) {
-               if (i == off) {
-                       /* We've found it! */
-                       return ofs_write(tdb, last_ptr, &next);
-               }
-               /* Follow chain (next offset is at start of record) */
-               last_ptr = i;
-       }
-       TDB_LOG((tdb, 0,"remove_from_freelist: not on list at off=%d\n", off));
-       return TDB_ERRCODE(TDB_ERR_CORRUPT, -1);
-}
-
-/* Add an element into the freelist. Merge adjacent records if
-   neccessary. */
-static int tdb_free(TDB_CONTEXT *tdb, tdb_off offset, struct list_struct *rec)
-{
-       tdb_off right, left;
-
-       /* Allocation and tailer lock */
-       if (tdb_lock(tdb, -1, F_WRLCK) != 0)
-               return -1;
-
-       /* set an initial tailer, so if we fail we don't leave a bogus record */
-       if (update_tailer(tdb, offset, rec) != 0) {
-               TDB_LOG((tdb, 0, "tdb_free: upfate_tailer failed!\n"));
-               goto fail;
-       }
-
-       /* Look right first (I'm an Australian, dammit) */
-       right = offset + sizeof(*rec) + rec->rec_len;
-       if (right + sizeof(*rec) <= tdb->map_size) {
-               struct list_struct r;
-
-               if (tdb_read(tdb, right, &r, sizeof(r), DOCONV()) == -1) {
-                       TDB_LOG((tdb, 0, "tdb_free: right read failed at %u\n", right));
-                       goto left;
-               }
-
-               /* If it's free, expand to include it. */
-               if (r.magic == TDB_FREE_MAGIC) {
-                       if (remove_from_freelist(tdb, right, r.next) == -1) {
-                               TDB_LOG((tdb, 0, "tdb_free: right free failed at %u\n", right));
-                               goto left;
-                       }
-                       rec->rec_len += sizeof(r) + r.rec_len;
-               }
-       }
-
-left:
-       /* Look left */
-       left = offset - sizeof(tdb_off);
-       if (left > TDB_HASH_TOP(tdb->header.hash_size-1)) {
-               struct list_struct l;
-               tdb_off leftsize;
-
-               /* Read in tailer and jump back to header */
-               if (ofs_read(tdb, left, &leftsize) == -1) {
-                       TDB_LOG((tdb, 0, "tdb_free: left offset read failed at %u\n", left));
-                       goto update;
-               }
-               left = offset - leftsize;
-
-               /* Now read in record */
-               if (tdb_read(tdb, left, &l, sizeof(l), DOCONV()) == -1) {
-                       TDB_LOG((tdb, 0, "tdb_free: left read failed at %u (%u)\n", left, leftsize));
-                       goto update;
-               }
-
-               /* If it's free, expand to include it. */
-               if (l.magic == TDB_FREE_MAGIC) {
-                       if (remove_from_freelist(tdb, left, l.next) == -1) {
-                               TDB_LOG((tdb, 0, "tdb_free: left free failed at %u\n", left));
-                               goto update;
-                       } else {
-                               offset = left;
-                               rec->rec_len += leftsize;
-                       }
-               }
-       }
-
-update:
-       if (update_tailer(tdb, offset, rec) == -1) {
-               TDB_LOG((tdb, 0, "tdb_free: update_tailer failed at %u\n", offset));
-               goto fail;
-       }
-
-       /* Now, prepend to free list */
-       rec->magic = TDB_FREE_MAGIC;
-
-       if (ofs_read(tdb, FREELIST_TOP, &rec->next) == -1 ||
-           rec_write(tdb, offset, rec) == -1 ||
-           ofs_write(tdb, FREELIST_TOP, &offset) == -1) {
-               TDB_LOG((tdb, 0, "tdb_free record write failed at offset=%d\n", offset));
-               goto fail;
-       }
-
-       /* And we're done. */
-       tdb_unlock(tdb, -1, F_WRLCK);
-       return 0;
-
- fail:
-       tdb_unlock(tdb, -1, F_WRLCK);
-       return -1;
-}
-
-
-/* expand a file.  we prefer to use ftruncate, as that is what posix
-  says to use for mmap expansion */
-static int expand_file(TDB_CONTEXT *tdb, tdb_off size, tdb_off addition)
-{
-       char buf[1024];
-#if HAVE_FTRUNCATE_EXTEND
-       if (ftruncate(tdb->fd, size+addition) != 0) {
-               TDB_LOG((tdb, 0, "expand_file ftruncate to %d failed (%s)\n", 
-                          size+addition, strerror(errno)));
-               return -1;
-       }
-#else
-       char b = 0;
-
-#ifdef HAVE_PWRITE
-       if (pwrite(tdb->fd,  &b, 1, (size+addition) - 1) != 1) {
-#else
-       if (lseek(tdb->fd, (size+addition) - 1, SEEK_SET) != (size+addition) - 1 || 
-           write(tdb->fd, &b, 1) != 1) {
-#endif
-               TDB_LOG((tdb, 0, "expand_file to %d failed (%s)\n", 
-                          size+addition, strerror(errno)));
-               return -1;
-       }
-#endif
-
-       /* now fill the file with something. This ensures that the file isn't sparse, which would be
-          very bad if we ran out of disk. This must be done with write, not via mmap */
-       memset(buf, 0x42, sizeof(buf));
-       while (addition) {
-               int n = addition>sizeof(buf)?sizeof(buf):addition;
-#ifdef HAVE_PWRITE
-               int ret = pwrite(tdb->fd, buf, n, size);
-#else
-               int ret;
-               if (lseek(tdb->fd, size, SEEK_SET) != size)
-                       return -1;
-               ret = write(tdb->fd, buf, n);
-#endif
-               if (ret != n) {
-                       TDB_LOG((tdb, 0, "expand_file write of %d failed (%s)\n", 
-                                  n, strerror(errno)));
-                       return -1;
-               }
-               addition -= n;
-               size += n;
-       }
-       return 0;
-}
-
-
-/* expand the database at least size bytes by expanding the underlying
-   file and doing the mmap again if necessary */
-static int tdb_expand(TDB_CONTEXT *tdb, tdb_off size)
+static void tdb_increment_seqnum(struct tdb_context *tdb)
 {
-       struct list_struct rec;
-       tdb_off offset;
-
-       if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
-               TDB_LOG((tdb, 0, "lock failed in tdb_expand\n"));
-               return -1;
-       }
-
-       /* must know about any previous expansions by another process */
-       tdb_oob(tdb, tdb->map_size + 1, 1);
-
-       /* always make room for at least 10 more records, and round
-           the database up to a multiple of TDB_PAGE_SIZE */
-       size = TDB_ALIGN(tdb->map_size + size*10, TDB_PAGE_SIZE) - tdb->map_size;
-
-       if (!(tdb->flags & TDB_INTERNAL))
-               tdb_munmap(tdb);
-
-       /*
-        * We must ensure the file is unmapped before doing this
-        * to ensure consistency with systems like OpenBSD where
-        * writes and mmaps are not consistent.
-        */
-
-       /* expand the file itself */
-       if (!(tdb->flags & TDB_INTERNAL)) {
-               if (expand_file(tdb, tdb->map_size, size) != 0)
-                       goto fail;
+       if (!(tdb->flags & TDB_SEQNUM)) {
+               return;
        }
 
-       tdb->map_size += size;
-
-       if (tdb->flags & TDB_INTERNAL)
-               tdb->map_ptr = realloc(tdb->map_ptr, tdb->map_size);
-       else {
-               /*
-                * We must ensure the file is remapped before adding the space
-                * to ensure consistency with systems like OpenBSD where
-                * writes and mmaps are not consistent.
-                */
-
-               /* We're ok if the mmap fails as we'll fallback to read/write */
-               tdb_mmap(tdb);
+       if (tdb_brlock(tdb, TDB_SEQNUM_OFS, F_WRLCK, F_SETLKW, 1, 1) != 0) {
+               return;
        }
 
-       /* form a new freelist record */
-       memset(&rec,'\0',sizeof(rec));
-       rec.rec_len = size - sizeof(rec);
+       tdb_increment_seqnum_nonblock(tdb);
 
-       /* link it into the free list */
-       offset = tdb->map_size - size;
-       if (tdb_free(tdb, offset, &rec) == -1)
-               goto fail;
-
-       tdb_unlock(tdb, -1, F_WRLCK);
-       return 0;
- fail:
-       tdb_unlock(tdb, -1, F_WRLCK);
-       return -1;
+       tdb_brlock(tdb, TDB_SEQNUM_OFS, F_UNLCK, F_SETLKW, 1, 1);
 }
 
-/* allocate some space from the free list. The offset returned points
-   to a unconnected list_struct within the database with room for at
-   least length bytes of total data
-
-   0 is returned if the space could not be allocated
- */
-static tdb_off tdb_allocate(TDB_CONTEXT *tdb, tdb_len length,
-                           struct list_struct *rec)
+static int tdb_key_compare(TDB_DATA key, TDB_DATA data, void *private_data)
 {
-       tdb_off rec_ptr, last_ptr, newrec_ptr;
-       struct list_struct newrec;
-
-       if (tdb_lock(tdb, -1, F_WRLCK) == -1)
-               return 0;
-
-       /* Extra bytes required for tailer */
-       length += sizeof(tdb_off);
-
- again:
-       last_ptr = FREELIST_TOP;
-
-       /* read in the freelist top */
-       if (ofs_read(tdb, FREELIST_TOP, &rec_ptr) == -1)
-               goto fail;
-
-       /* keep looking until we find a freelist record big enough */
-       while (rec_ptr) {
-               if (rec_free_read(tdb, rec_ptr, rec) == -1)
-                       goto fail;
-
-               if (rec->rec_len >= length) {
-                       /* found it - now possibly split it up  */
-                       if (rec->rec_len > length + MIN_REC_SIZE) {
-                               /* Length of left piece */
-                               length = TDB_ALIGN(length, TDB_ALIGNMENT);
-
-                               /* Right piece to go on free list */
-                               newrec.rec_len = rec->rec_len
-                                       - (sizeof(*rec) + length);
-                               newrec_ptr = rec_ptr + sizeof(*rec) + length;
-
-                               /* And left record is shortened */
-                               rec->rec_len = length;
-                       } else
-                               newrec_ptr = 0;
-
-                       /* Remove allocated record from the free list */
-                       if (ofs_write(tdb, last_ptr, &rec->next) == -1)
-                               goto fail;
-
-                       /* Update header: do this before we drop alloc
-                           lock, otherwise tdb_free() might try to
-                           merge with us, thinking we're free.
-                           (Thanks Jeremy Allison). */
-                       rec->magic = TDB_MAGIC;
-                       if (rec_write(tdb, rec_ptr, rec) == -1)
-                               goto fail;
-
-                       /* Did we create new block? */
-                       if (newrec_ptr) {
-                               /* Update allocated record tailer (we
-                                   shortened it). */
-                               if (update_tailer(tdb, rec_ptr, rec) == -1)
-                                       goto fail;
-
-                               /* Free new record */
-                               if (tdb_free(tdb, newrec_ptr, &newrec) == -1)
-                                       goto fail;
-                       }
-
-                       /* all done - return the new record offset */
-                       tdb_unlock(tdb, -1, F_WRLCK);
-                       return rec_ptr;
-               }
-               /* move to the next record */
-               last_ptr = rec_ptr;
-               rec_ptr = rec->next;
-       }
-       /* we didn't find enough space. See if we can expand the
-          database and if we can then try again */
-       if (tdb_expand(tdb, length + sizeof(*rec)) == 0)
-               goto again;
- fail:
-       tdb_unlock(tdb, -1, F_WRLCK);
-       return 0;
-}
-
-/* initialise a new database with a specified hash size */
-static int tdb_new_database(TDB_CONTEXT *tdb, int hash_size)
-{
-       struct tdb_header *newdb;
-       int size, ret = -1;
-
-       /* We make it up in memory, then write it out if not internal */
-       size = sizeof(struct tdb_header) + (hash_size+1)*sizeof(tdb_off);
-       if (!(newdb = calloc(size, 1)))
-               return TDB_ERRCODE(TDB_ERR_OOM, -1);
-
-       /* Fill in the header */
-       newdb->version = TDB_VERSION;
-       newdb->hash_size = hash_size;
-#ifdef USE_SPINLOCKS
-       newdb->rwlocks = size;
-#endif
-       if (tdb->flags & TDB_INTERNAL) {
-               tdb->map_size = size;
-               tdb->map_ptr = (char *)newdb;
-               memcpy(&tdb->header, newdb, sizeof(tdb->header));
-               /* Convert the `ondisk' version if asked. */
-               CONVERT(*newdb);
-               return 0;
-       }
-       if (lseek(tdb->fd, 0, SEEK_SET) == -1)
-               goto fail;
-
-       if (ftruncate(tdb->fd, 0) == -1)
-               goto fail;
-
-       /* This creates an endian-converted header, as if read from disk */
-       CONVERT(*newdb);
-       memcpy(&tdb->header, newdb, sizeof(tdb->header));
-       /* Don't endian-convert the magic food! */
-       memcpy(newdb->magic_food, TDB_MAGIC_FOOD, strlen(TDB_MAGIC_FOOD)+1);
-       if (write(tdb->fd, newdb, size) != size)
-               ret = -1;
-       else
-               ret = tdb_create_rwlocks(tdb->fd, hash_size);
-
-  fail:
-       SAFE_FREE(newdb);
-       return ret;
+       return memcmp(data.dptr, key.dptr, data.dsize);
 }
 
 /* Returns 0 on fail.  On success, return offset of record, and fills
    in rec */
-static tdb_off tdb_find(TDB_CONTEXT *tdb, TDB_DATA key, u32 hash,
-                       struct list_struct *r)
+static tdb_off_t tdb_find(struct tdb_context *tdb, TDB_DATA key, uint32_t hash,
+                       struct tdb_record *r)
 {
-       tdb_off rec_ptr;
+       tdb_off_t rec_ptr;
        
        /* read in the hash top */
-       if (ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
+       if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
                return 0;
 
        /* keep looking until we find the right record */
        while (rec_ptr) {
-               if (rec_read(tdb, rec_ptr, r) == -1)
+               if (tdb_rec_read(tdb, rec_ptr, r) == -1)
                        return 0;
 
-               if (!TDB_DEAD(r) && hash==r->full_hash && key.dsize==r->key_len) {
-                       char *k;
-                       /* a very likely hit - read the key */
-                       k = tdb_alloc_read(tdb, rec_ptr + sizeof(*r), 
-                                          r->key_len);
-                       if (!k)
-                               return 0;
-
-                       if (memcmp(key.dptr, k, key.dsize) == 0) {
-                               SAFE_FREE(k);
-                               return rec_ptr;
-                       }
-                       SAFE_FREE(k);
+               if (!TDB_DEAD(r) && hash==r->full_hash
+                   && key.dsize==r->key_len
+                   && tdb_parse_data(tdb, key, rec_ptr + sizeof(*r),
+                                     r->key_len, tdb_key_compare,
+                                     NULL) == 0) {
+                       return rec_ptr;
+               }
+               /* detect tight infinite loop */
+               if (rec_ptr == r->next) {
+                       tdb->ecode = TDB_ERR_CORRUPT;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_find: loop detected.\n"));
+                       return 0;
                }
                rec_ptr = r->next;
        }
-       return TDB_ERRCODE(TDB_ERR_NOEXIST, 0);
-}
-
-/* If they do lockkeys, check that this hash is one they locked */
-static int tdb_keylocked(TDB_CONTEXT *tdb, u32 hash)
-{
-       u32 i;
-       if (!tdb->lockedkeys)
-               return 1;
-       for (i = 0; i < tdb->lockedkeys[0]; i++)
-               if (tdb->lockedkeys[i+1] == hash)
-                       return 1;
-       return TDB_ERRCODE(TDB_ERR_NOLOCK, 0);
+       tdb->ecode = TDB_ERR_NOEXIST;
+       return 0;
 }
 
 /* As tdb_find, but if you succeed, keep the lock */
-static tdb_off tdb_find_lock(TDB_CONTEXT *tdb, TDB_DATA key, int locktype,
-                            struct list_struct *rec)
+tdb_off_t tdb_find_lock_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash, int locktype,
+                          struct tdb_record *rec)
 {
-       u32 hash, rec_ptr;
+       uint32_t rec_ptr;
 
-       hash = tdb_hash(&key);
-       if (!tdb_keylocked(tdb, hash))
-               return 0;
        if (tdb_lock(tdb, BUCKET(hash), locktype) == -1)
                return 0;
        if (!(rec_ptr = tdb_find(tdb, key, hash, rec)))
@@ -1032,60 +121,54 @@ static tdb_off tdb_find_lock(TDB_CONTEXT *tdb, TDB_DATA key, int locktype,
        return rec_ptr;
 }
 
-enum TDB_ERROR tdb_error(TDB_CONTEXT *tdb)
-{
-       return tdb->ecode;
-}
-
-static struct tdb_errname {
-       enum TDB_ERROR ecode; const char *estring;
-} emap[] = { {TDB_SUCCESS, "Success"},
-            {TDB_ERR_CORRUPT, "Corrupt database"},
-            {TDB_ERR_IO, "IO Error"},
-            {TDB_ERR_LOCK, "Locking error"},
-            {TDB_ERR_OOM, "Out of memory"},
-            {TDB_ERR_EXISTS, "Record exists"},
-            {TDB_ERR_NOLOCK, "Lock exists on other keys"},
-            {TDB_ERR_NOEXIST, "Record does not exist"} };
-
-/* Error string for the last tdb error */
-const char *tdb_errorstr(TDB_CONTEXT *tdb)
-{
-       u32 i;
-       for (i = 0; i < sizeof(emap) / sizeof(struct tdb_errname); i++)
-               if (tdb->ecode == emap[i].ecode)
-                       return emap[i].estring;
-       return "Invalid error code";
-}
+static TDB_DATA _tdb_fetch(struct tdb_context *tdb, TDB_DATA key);
 
 /* update an entry in place - this only works if the new data size
    is <= the old data size and the key exists.
    on failure return -1.
 */
-
-static int tdb_update(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf)
+static int tdb_update_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash, TDB_DATA dbuf)
 {
-       struct list_struct rec;
-       tdb_off rec_ptr;
+       struct tdb_record rec;
+       tdb_off_t rec_ptr;
 
        /* find entry */
-       if (!(rec_ptr = tdb_find(tdb, key, tdb_hash(&key), &rec)))
+       if (!(rec_ptr = tdb_find(tdb, key, hash, &rec)))
                return -1;
 
+       /* it could be an exact duplicate of what is there - this is
+        * surprisingly common (eg. with a ldb re-index). */
+       if (rec.key_len == key.dsize && 
+           rec.data_len == dbuf.dsize &&
+           rec.full_hash == hash) {
+               TDB_DATA data = _tdb_fetch(tdb, key);
+               if (data.dsize == dbuf.dsize &&
+                   memcmp(data.dptr, dbuf.dptr, data.dsize) == 0) {
+                       if (data.dptr) {
+                               free(data.dptr);
+                       }
+                       return 0;
+               }
+               if (data.dptr) {
+                       free(data.dptr);
+               }
+       }
+        
+
        /* must be long enough key, data and tailer */
-       if (rec.rec_len < key.dsize + dbuf.dsize + sizeof(tdb_off)) {
+       if (rec.rec_len < key.dsize + dbuf.dsize + sizeof(tdb_off_t)) {
                tdb->ecode = TDB_SUCCESS; /* Not really an error */
                return -1;
        }
 
-       if (tdb_write(tdb, rec_ptr + sizeof(rec) + rec.key_len,
+       if (tdb->methods->tdb_write(tdb, rec_ptr + sizeof(rec) + rec.key_len,
                      dbuf.dptr, dbuf.dsize) == -1)
                return -1;
 
        if (dbuf.dsize != rec.data_len) {
                /* update size */
                rec.data_len = dbuf.dsize;
-               return rec_write(tdb, rec_ptr, &rec);
+               return tdb_rec_write(tdb, rec_ptr, &rec);
        }
  
        return 0;
@@ -1094,116 +177,134 @@ static int tdb_update(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf)
 /* find an entry in the database given a key */
 /* If an entry doesn't exist tdb_err will be set to
  * TDB_ERR_NOEXIST. If a key has no data attached
- * tdb_err will not be set. Both will return a
- * zero pptr and zero dsize.
+ * then the TDB_DATA will have zero length but
+ * a non-zero pointer
  */
-
-TDB_DATA tdb_fetch(TDB_CONTEXT *tdb, TDB_DATA key)
+static TDB_DATA _tdb_fetch(struct tdb_context *tdb, TDB_DATA key)
 {
-       tdb_off rec_ptr;
-       struct list_struct rec;
+       tdb_off_t rec_ptr;
+       struct tdb_record rec;
        TDB_DATA ret;
+       uint32_t hash;
 
        /* find which hash bucket it is in */
-       if (!(rec_ptr = tdb_find_lock(tdb,key,F_RDLCK,&rec)))
+       hash = tdb->hash_fn(&key);
+       if (!(rec_ptr = tdb_find_lock_hash(tdb,key,hash,F_RDLCK,&rec)))
                return tdb_null;
 
-       if (rec.data_len)
-               ret.dptr = tdb_alloc_read(tdb, rec_ptr + sizeof(rec) + rec.key_len,
-                                         rec.data_len);
-       else
-               ret.dptr = NULL;
+       ret.dptr = tdb_alloc_read(tdb, rec_ptr + sizeof(rec) + rec.key_len,
+                                 rec.data_len);
        ret.dsize = rec.data_len;
        tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
        return ret;
 }
 
+TDB_DATA tdb_fetch(struct tdb_context *tdb, TDB_DATA key)
+{
+       TDB_DATA ret = _tdb_fetch(tdb, key);
+
+       tdb_trace_1rec_retrec(tdb, "tdb_fetch", key, ret);
+       return ret;
+}
+
+/*
+ * Find an entry in the database and hand the record's data to a parsing
+ * function. The parsing function is executed under the chain read lock, so it
+ * should be fast and should not block on other syscalls.
+ *
+ * DONT CALL OTHER TDB CALLS FROM THE PARSER, THIS MIGHT LEAD TO SEGFAULTS.
+ *
+ * For mmapped tdb's that do not have a transaction open it points the parsing
+ * function directly at the mmap area, it avoids the malloc/memcpy in this
+ * case. If a transaction is open or no mmap is available, it has to do
+ * malloc/read/parse/free.
+ *
+ * This is interesting for all readers of potentially large data structures in
+ * the tdb records, ldb indexes being one example.
+ */
+
+int tdb_parse_record(struct tdb_context *tdb, TDB_DATA key,
+                    int (*parser)(TDB_DATA key, TDB_DATA data,
+                                  void *private_data),
+                    void *private_data)
+{
+       tdb_off_t rec_ptr;
+       struct tdb_record rec;
+       int ret;
+       uint32_t hash;
+
+       /* find which hash bucket it is in */
+       hash = tdb->hash_fn(&key);
+
+       if (!(rec_ptr = tdb_find_lock_hash(tdb,key,hash,F_RDLCK,&rec))) {
+               tdb_trace_1rec_ret(tdb, "tdb_parse_record", key, -1);
+               tdb->ecode = TDB_ERR_NOEXIST;
+               return 0;
+       }
+       tdb_trace_1rec_ret(tdb, "tdb_parse_record", key, 0);
+
+       ret = tdb_parse_data(tdb, key, rec_ptr + sizeof(rec) + rec.key_len,
+                            rec.data_len, parser, private_data);
+
+       tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
+
+       return ret;
+}
+
 /* check if an entry in the database exists 
 
    note that 1 is returned if the key is found and 0 is returned if not found
    this doesn't match the conventions in the rest of this module, but is
    compatible with gdbm
 */
-int tdb_exists(TDB_CONTEXT *tdb, TDB_DATA key)
+static int tdb_exists_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash)
 {
-       struct list_struct rec;
+       struct tdb_record rec;
        
-       if (tdb_find_lock(tdb, key, F_RDLCK, &rec) == 0)
+       if (tdb_find_lock_hash(tdb, key, hash, F_RDLCK, &rec) == 0)
                return 0;
        tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
        return 1;
 }
 
-/* record lock stops delete underneath */
-static int lock_record(TDB_CONTEXT *tdb, tdb_off off)
-{
-       return off ? tdb_brlock(tdb, off, F_RDLCK, F_SETLKW, 0) : 0;
-}
-/*
-  Write locks override our own fcntl readlocks, so check it here.
-  Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
-  an error to fail to get the lock here.
-*/
-static int write_lock_record(TDB_CONTEXT *tdb, tdb_off off)
-{
-       struct tdb_traverse_lock *i;
-       for (i = &tdb->travlocks; i; i = i->next)
-               if (i->off == off)
-                       return -1;
-       return tdb_brlock(tdb, off, F_WRLCK, F_SETLK, 1);
-}
-
-/*
-  Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
-  an error to fail to get the lock here.
-*/
-
-static int write_unlock_record(TDB_CONTEXT *tdb, tdb_off off)
+int tdb_exists(struct tdb_context *tdb, TDB_DATA key)
 {
-       return tdb_brlock(tdb, off, F_UNLCK, F_SETLK, 0);
-}
-/* fcntl locks don't stack: avoid unlocking someone else's */
-static int unlock_record(TDB_CONTEXT *tdb, tdb_off off)
-{
-       struct tdb_traverse_lock *i;
-       u32 count = 0;
+       uint32_t hash = tdb->hash_fn(&key);
+       int ret;
 
-       if (off == 0)
-               return 0;
-       for (i = &tdb->travlocks; i; i = i->next)
-               if (i->off == off)
-                       count++;
-       return (count == 1 ? tdb_brlock(tdb, off, F_UNLCK, F_SETLKW, 0) : 0);
+       ret = tdb_exists_hash(tdb, key, hash);
+       tdb_trace_1rec_ret(tdb, "tdb_exists", key, ret);
+       return ret;
 }
 
 /* actually delete an entry in the database given the offset */
-static int do_delete(TDB_CONTEXT *tdb, tdb_off rec_ptr, struct list_struct*rec)
+int tdb_do_delete(struct tdb_context *tdb, tdb_off_t rec_ptr, struct tdb_record *rec)
 {
-       tdb_off last_ptr, i;
-       struct list_struct lastrec;
+       tdb_off_t last_ptr, i;
+       struct tdb_record lastrec;
 
-       if (tdb->read_only) return -1;
+       if (tdb->read_only || tdb->traverse_read) return -1;
 
-       if (write_lock_record(tdb, rec_ptr) == -1) {
+       if (((tdb->traverse_write != 0) && (!TDB_DEAD(rec))) ||
+           tdb_write_lock_record(tdb, rec_ptr) == -1) {
                /* Someone traversing here: mark it as dead */
                rec->magic = TDB_DEAD_MAGIC;
-               return rec_write(tdb, rec_ptr, rec);
+               return tdb_rec_write(tdb, rec_ptr, rec);
        }
-       if (write_unlock_record(tdb, rec_ptr) != 0)
+       if (tdb_write_unlock_record(tdb, rec_ptr) != 0)
                return -1;
 
        /* find previous record in hash chain */
-       if (ofs_read(tdb, TDB_HASH_TOP(rec->full_hash), &i) == -1)
+       if (tdb_ofs_read(tdb, TDB_HASH_TOP(rec->full_hash), &i) == -1)
                return -1;
        for (last_ptr = 0; i != rec_ptr; last_ptr = i, i = lastrec.next)
-               if (rec_read(tdb, i, &lastrec) == -1)
+               if (tdb_rec_read(tdb, i, &lastrec) == -1)
                        return -1;
 
        /* unlink it: next ptr is at start of record. */
        if (last_ptr == 0)
                last_ptr = TDB_HASH_TOP(rec->full_hash);
-       if (ofs_write(tdb, last_ptr, &rec->next) == -1)
+       if (tdb_ofs_write(tdb, last_ptr, &rec->next) == -1)
                return -1;
 
        /* recover the space */
@@ -1212,257 +313,183 @@ static int do_delete(TDB_CONTEXT *tdb, tdb_off rec_ptr, struct list_struct*rec)
        return 0;
 }
 
-/* Uses traverse lock: 0 = finish, -1 = error, other = record offset */
-static int tdb_next_lock(TDB_CONTEXT *tdb, struct tdb_traverse_lock *tlock,
-                        struct list_struct *rec)
+static int tdb_count_dead(struct tdb_context *tdb, uint32_t hash)
 {
-       int want_next = (tlock->off != 0);
-
-       /* No traversal allows if you've called tdb_lockkeys() */
-       if (tdb->lockedkeys)
-               return TDB_ERRCODE(TDB_ERR_NOLOCK, -1);
-
-       /* Lock each chain from the start one. */
-       for (; tlock->hash < tdb->header.hash_size; tlock->hash++) {
-               if (tdb_lock(tdb, tlock->hash, F_WRLCK) == -1)
-                       return -1;
-
-               /* No previous record?  Start at top of chain. */
-               if (!tlock->off) {
-                       if (ofs_read(tdb, TDB_HASH_TOP(tlock->hash),
-                                    &tlock->off) == -1)
-                               goto fail;
-               } else {
-                       /* Otherwise unlock the previous record. */
-                       if (unlock_record(tdb, tlock->off) != 0)
-                               goto fail;
-               }
+       int res = 0;
+       tdb_off_t rec_ptr;
+       struct tdb_record rec;
+       
+       /* read in the hash top */
+       if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
+               return 0;
 
-               if (want_next) {
-                       /* We have offset of old record: grab next */
-                       if (rec_read(tdb, tlock->off, rec) == -1)
-                               goto fail;
-                       tlock->off = rec->next;
-               }
+       while (rec_ptr) {
+               if (tdb_rec_read(tdb, rec_ptr, &rec) == -1)
+                       return 0;
 
-               /* Iterate through chain */
-               while( tlock->off) {
-                       tdb_off current;
-                       if (rec_read(tdb, tlock->off, rec) == -1)
-                               goto fail;
-                       if (!TDB_DEAD(rec)) {
-                               /* Woohoo: we found one! */
-                               if (lock_record(tdb, tlock->off) != 0)
-                                       goto fail;
-                               return tlock->off;
-                       }
-                       /* Try to clean dead ones from old traverses */
-                       current = tlock->off;
-                       tlock->off = rec->next;
-                       if (do_delete(tdb, current, rec) != 0)
-                               goto fail;
+               if (rec.magic == TDB_DEAD_MAGIC) {
+                       res += 1;
                }
-               tdb_unlock(tdb, tlock->hash, F_WRLCK);
-               want_next = 0;
+               rec_ptr = rec.next;
        }
-       /* We finished iteration without finding anything */
-       return TDB_ERRCODE(TDB_SUCCESS, 0);
-
- fail:
-       tlock->off = 0;
-       if (tdb_unlock(tdb, tlock->hash, F_WRLCK) != 0)
-               TDB_LOG((tdb, 0, "tdb_next_lock: On error unlock failed!\n"));
-       return -1;
+       return res;
 }
 
-/* traverse the entire database - calling fn(tdb, key, data) on each element.
-   return -1 on error or the record count traversed
-   if fn is NULL then it is not called
-   a non-zero return value from fn() indicates that the traversal should stop
-  */
-int tdb_traverse(TDB_CONTEXT *tdb, tdb_traverse_func fn, void *state)
+/*
+ * Purge all DEAD records from a hash chain
+ */
+static int tdb_purge_dead(struct tdb_context *tdb, uint32_t hash)
 {
-       TDB_DATA key, dbuf;
-       struct list_struct rec;
-       struct tdb_traverse_lock tl = { NULL, 0, 0 };
-       int ret, count = 0;
+       int res = -1;
+       struct tdb_record rec;
+       tdb_off_t rec_ptr;
 
-       /* This was in the initializaton, above, but the IRIX compiler
-        * did not like it.  crh
-        */
-       tl.next = tdb->travlocks.next;
-
-       /* fcntl locks don't stack: beware traverse inside traverse */
-       tdb->travlocks.next = &tl;
-
-       /* tdb_next_lock places locks on the record returned, and its chain */
-       while ((ret = tdb_next_lock(tdb, &tl, &rec)) > 0) {
-               count++;
-               /* now read the full record */
-               key.dptr = tdb_alloc_read(tdb, tl.off + sizeof(rec), 
-                                         rec.key_len + rec.data_len);
-               if (!key.dptr) {
-                       ret = -1;
-                       if (tdb_unlock(tdb, tl.hash, F_WRLCK) != 0)
-                               goto out;
-                       if (unlock_record(tdb, tl.off) != 0)
-                               TDB_LOG((tdb, 0, "tdb_traverse: key.dptr == NULL and unlock_record failed!\n"));
-                       goto out;
-               }
-               key.dsize = rec.key_len;
-               dbuf.dptr = key.dptr + rec.key_len;
-               dbuf.dsize = rec.data_len;
-
-               /* Drop chain lock, call out */
-               if (tdb_unlock(tdb, tl.hash, F_WRLCK) != 0) {
-                       ret = -1;
-                       goto out;
+       if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
+               return -1;
+       }
+       
+       /* read in the hash top */
+       if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
+               goto fail;
+
+       while (rec_ptr) {
+               tdb_off_t next;
+
+               if (tdb_rec_read(tdb, rec_ptr, &rec) == -1) {
+                       goto fail;
                }
-               if (fn && fn(tdb, key, dbuf, state)) {
-                       /* They want us to terminate traversal */
-                       ret = count;
-                       if (unlock_record(tdb, tl.off) != 0) {
-                               TDB_LOG((tdb, 0, "tdb_traverse: unlock_record failed!\n"));;
-                               ret = -1;
-                       }
-                       tdb->travlocks.next = tl.next;
-                       SAFE_FREE(key.dptr);
-                       return count;
+
+               next = rec.next;
+
+               if (rec.magic == TDB_DEAD_MAGIC
+                   && tdb_do_delete(tdb, rec_ptr, &rec) == -1) {
+                       goto fail;
                }
-               SAFE_FREE(key.dptr);
+               rec_ptr = next;
        }
-out:
-       tdb->travlocks.next = tl.next;
-       if (ret < 0)
-               return -1;
-       else
-               return count;
+       res = 0;
+ fail:
+       tdb_unlock(tdb, -1, F_WRLCK);
+       return res;
 }
 
-/* find the first entry in the database and return its key */
-TDB_DATA tdb_firstkey(TDB_CONTEXT *tdb)
+/* delete an entry in the database given a key */
+static int tdb_delete_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash)
 {
-       TDB_DATA key;
-       struct list_struct rec;
+       tdb_off_t rec_ptr;
+       struct tdb_record rec;
+       int ret;
 
-       /* release any old lock */
-       if (unlock_record(tdb, tdb->travlocks.off) != 0)
-               return tdb_null;
-       tdb->travlocks.off = tdb->travlocks.hash = 0;
+       if (tdb->max_dead_records != 0) {
 
-       if (tdb_next_lock(tdb, &tdb->travlocks, &rec) <= 0)
-               return tdb_null;
-       /* now read the key */
-       key.dsize = rec.key_len;
-       key.dptr =tdb_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),key.dsize);
-       if (tdb_unlock(tdb, BUCKET(tdb->travlocks.hash), F_WRLCK) != 0)
-               TDB_LOG((tdb, 0, "tdb_firstkey: error occurred while tdb_unlocking!\n"));
-       return key;
-}
+               /*
+                * Allow for some dead records per hash chain, mainly for
+                * tdb's with a very high create/delete rate like locking.tdb.
+                */
 
-/* find the next entry in the database, returning its key */
-TDB_DATA tdb_nextkey(TDB_CONTEXT *tdb, TDB_DATA oldkey)
-{
-       u32 oldhash;
-       TDB_DATA key = tdb_null;
-       struct list_struct rec;
-       char *k = NULL;
-
-       /* Is locked key the old key?  If so, traverse will be reliable. */
-       if (tdb->travlocks.off) {
-               if (tdb_lock(tdb,tdb->travlocks.hash,F_WRLCK))
-                       return tdb_null;
-               if (rec_read(tdb, tdb->travlocks.off, &rec) == -1
-                   || !(k = tdb_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),
-                                           rec.key_len))
-                   || memcmp(k, oldkey.dptr, oldkey.dsize) != 0) {
-                       /* No, it wasn't: unlock it and start from scratch */
-                       if (unlock_record(tdb, tdb->travlocks.off) != 0)
-                               return tdb_null;
-                       if (tdb_unlock(tdb, tdb->travlocks.hash, F_WRLCK) != 0)
-                               return tdb_null;
-                       tdb->travlocks.off = 0;
+               if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
+                       return -1;
+
+               if (tdb_count_dead(tdb, hash) >= tdb->max_dead_records) {
+                       /*
+                        * Don't let the per-chain freelist grow too large,
+                        * delete all existing dead records
+                        */
+                       tdb_purge_dead(tdb, hash);
+               }
+
+               if (!(rec_ptr = tdb_find(tdb, key, hash, &rec))) {
+                       tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
+                       return -1;
                }
 
-               SAFE_FREE(k);
+               /*
+                * Just mark the record as dead.
+                */
+               rec.magic = TDB_DEAD_MAGIC;
+               ret = tdb_rec_write(tdb, rec_ptr, &rec);
        }
+       else {
+               if (!(rec_ptr = tdb_find_lock_hash(tdb, key, hash, F_WRLCK,
+                                                  &rec)))
+                       return -1;
 
-       if (!tdb->travlocks.off) {
-               /* No previous element: do normal find, and lock record */
-               tdb->travlocks.off = tdb_find_lock(tdb, oldkey, F_WRLCK, &rec);
-               if (!tdb->travlocks.off)
-                       return tdb_null;
-               tdb->travlocks.hash = BUCKET(rec.full_hash);
-               if (lock_record(tdb, tdb->travlocks.off) != 0) {
-                       TDB_LOG((tdb, 0, "tdb_nextkey: lock_record failed (%s)!\n", strerror(errno)));
-                       return tdb_null;
-               }
+               ret = tdb_do_delete(tdb, rec_ptr, &rec);
        }
-       oldhash = tdb->travlocks.hash;
-
-       /* Grab next record: locks chain and returned record,
-          unlocks old record */
-       if (tdb_next_lock(tdb, &tdb->travlocks, &rec) > 0) {
-               key.dsize = rec.key_len;
-               key.dptr = tdb_alloc_read(tdb, tdb->travlocks.off+sizeof(rec),
-                                         key.dsize);
-               /* Unlock the chain of this new record */
-               if (tdb_unlock(tdb, tdb->travlocks.hash, F_WRLCK) != 0)
-                       TDB_LOG((tdb, 0, "tdb_nextkey: WARNING tdb_unlock failed!\n"));
+
+       if (ret == 0) {
+               tdb_increment_seqnum(tdb);
        }
-       /* Unlock the chain of old record */
-       if (tdb_unlock(tdb, BUCKET(oldhash), F_WRLCK) != 0)
-               TDB_LOG((tdb, 0, "tdb_nextkey: WARNING tdb_unlock failed!\n"));
-       return key;
+
+       if (tdb_unlock(tdb, BUCKET(rec.full_hash), F_WRLCK) != 0)
+               TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_delete: WARNING tdb_unlock failed!\n"));
+       return ret;
 }
 
-/* delete an entry in the database given a key */
-int tdb_delete(TDB_CONTEXT *tdb, TDB_DATA key)
+int tdb_delete(struct tdb_context *tdb, TDB_DATA key)
 {
-       tdb_off rec_ptr;
-       struct list_struct rec;
+       uint32_t hash = tdb->hash_fn(&key);
        int ret;
 
-       if (!(rec_ptr = tdb_find_lock(tdb, key, F_WRLCK, &rec)))
-               return -1;
-       ret = do_delete(tdb, rec_ptr, &rec);
-       if (tdb_unlock(tdb, BUCKET(rec.full_hash), F_WRLCK) != 0)
-               TDB_LOG((tdb, 0, "tdb_delete: WARNING tdb_unlock failed!\n"));
+       ret = tdb_delete_hash(tdb, key, hash);
+       tdb_trace_1rec_ret(tdb, "tdb_delete", key, ret);
        return ret;
 }
 
-/* store an element in the database, replacing any existing element
-   with the same key 
+/*
+ * See if we have a dead record around with enough space
+ */
+static tdb_off_t tdb_find_dead(struct tdb_context *tdb, uint32_t hash,
+                              struct tdb_record *r, tdb_len_t length)
+{
+       tdb_off_t rec_ptr;
+       
+       /* read in the hash top */
+       if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
+               return 0;
+
+       /* keep looking until we find the right record */
+       while (rec_ptr) {
+               if (tdb_rec_read(tdb, rec_ptr, r) == -1)
+                       return 0;
+
+               if (TDB_DEAD(r) && r->rec_len >= length) {
+                       /*
+                        * First fit for simple coding, TODO: change to best
+                        * fit
+                        */
+                       return rec_ptr;
+               }
+               rec_ptr = r->next;
+       }
+       return 0;
+}
 
-   return 0 on success, -1 on failure
-*/
-int tdb_store(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf, int flag)
+static int _tdb_store(struct tdb_context *tdb, TDB_DATA key,
+                      TDB_DATA dbuf, int flag, uint32_t hash)
 {
-       struct list_struct rec;
-       u32 hash;
-       tdb_off rec_ptr;
+       struct tdb_record rec;
+       tdb_off_t rec_ptr;
        char *p = NULL;
-       int ret = 0;
-
-       /* find which hash bucket it is in */
-       hash = tdb_hash(&key);
-       if (!tdb_keylocked(tdb, hash))
-               return -1;
-       if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
-               return -1;
+       int ret = -1;
 
        /* check for it existing, on insert. */
        if (flag == TDB_INSERT) {
-               if (tdb_exists(tdb, key)) {
+               if (tdb_exists_hash(tdb, key, hash)) {
                        tdb->ecode = TDB_ERR_EXISTS;
                        goto fail;
                }
        } else {
                /* first try in-place update, on modify or replace. */
-               if (tdb_update(tdb, key, dbuf) == 0)
-                       goto out;
-               if (flag == TDB_MODIFY && tdb->ecode == TDB_ERR_NOEXIST)
+               if (tdb_update_hash(tdb, key, hash, dbuf) == 0) {
+                       goto done;
+               }
+               if (tdb->ecode == TDB_ERR_NOEXIST &&
+                   flag == TDB_MODIFY) {
+                       /* if the record doesn't exist and we are in TDB_MODIFY mode then
+                        we should fail the store */
                        goto fail;
+               }
        }
        /* reset the error code potentially set by the tdb_update() */
        tdb->ecode = TDB_SUCCESS;
@@ -1471,7 +498,7 @@ int tdb_store(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf, int flag)
            care.  Doing this first reduces fragmentation, and avoids
            coalescing with `allocated' block before it's updated. */
        if (flag != TDB_INSERT)
-               tdb_delete(tdb, key);
+               tdb_delete_hash(tdb, key, hash);
 
        /* Copy key+value *before* allocating free space in case malloc
           fails and we are left with a dead spot in the tdb. */
@@ -1485,14 +512,59 @@ int tdb_store(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf, int flag)
        if (dbuf.dsize)
                memcpy(p+key.dsize, dbuf.dptr, dbuf.dsize);
 
-       /* now we're into insert / modify / replace of a record which
-        * we know could not be optimised by an in-place store (for
-        * various reasons).  */
-       if (!(rec_ptr = tdb_allocate(tdb, key.dsize + dbuf.dsize, &rec)))
+       if (tdb->max_dead_records != 0) {
+               /*
+                * Allow for some dead records per hash chain, look if we can
+                * find one that can hold the new record. We need enough space
+                * for key, data and tailer. If we find one, we don't have to
+                * consult the central freelist.
+                */
+               rec_ptr = tdb_find_dead(
+                       tdb, hash, &rec,
+                       key.dsize + dbuf.dsize + sizeof(tdb_off_t));
+
+               if (rec_ptr != 0) {
+                       rec.key_len = key.dsize;
+                       rec.data_len = dbuf.dsize;
+                       rec.full_hash = hash;
+                       rec.magic = TDB_MAGIC;
+                       if (tdb_rec_write(tdb, rec_ptr, &rec) == -1
+                           || tdb->methods->tdb_write(
+                                   tdb, rec_ptr + sizeof(rec),
+                                   p, key.dsize + dbuf.dsize) == -1) {
+                               goto fail;
+                       }
+                       goto done;
+               }
+       }
+
+       /*
+        * We have to allocate some space from the freelist, so this means we
+        * have to lock it. Use the chance to purge all the DEAD records from
+        * the hash chain under the freelist lock.
+        */
+
+       if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
+               goto fail;
+       }
+
+       if ((tdb->max_dead_records != 0)
+           && (tdb_purge_dead(tdb, hash) == -1)) {
+               tdb_unlock(tdb, -1, F_WRLCK);
+               goto fail;
+       }
+
+       /* we have to allocate some space */
+       rec_ptr = tdb_allocate(tdb, key.dsize + dbuf.dsize, &rec);
+
+       tdb_unlock(tdb, -1, F_WRLCK);
+
+       if (rec_ptr == 0) {
                goto fail;
+       }
 
        /* Read hash top into next ptr */
-       if (ofs_read(tdb, TDB_HASH_TOP(hash), &rec.next) == -1)
+       if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec.next) == -1)
                goto fail;
 
        rec.key_len = key.dsize;
@@ -1501,547 +573,568 @@ int tdb_store(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf, int flag)
        rec.magic = TDB_MAGIC;
 
        /* write out and point the top of the hash chain at it */
-       if (rec_write(tdb, rec_ptr, &rec) == -1
-           || tdb_write(tdb, rec_ptr+sizeof(rec), p, key.dsize+dbuf.dsize)==-1
-           || ofs_write(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1) {
+       if (tdb_rec_write(tdb, rec_ptr, &rec) == -1
+           || tdb->methods->tdb_write(tdb, rec_ptr+sizeof(rec), p, key.dsize+dbuf.dsize)==-1
+           || tdb_ofs_write(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1) {
                /* Need to tdb_unallocate() here */
                goto fail;
        }
- out:
+
+ done:
+       ret = 0;
+ fail:
+       if (ret == 0) {
+               tdb_increment_seqnum(tdb);
+       }
+
        SAFE_FREE(p); 
-       tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
        return ret;
-fail:
-       ret = -1;
-       goto out;
 }
 
-/* Attempt to append data to an entry in place - this only works if the new data size
-   is <= the old data size and the key exists.
-   on failure return -1. Record must be locked before calling.
+/* store an element in the database, replacing any existing element
+   with the same key
+
+   return 0 on success, -1 on failure
 */
-static int tdb_append_inplace(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA new_dbuf)
+int tdb_store(struct tdb_context *tdb, TDB_DATA key, TDB_DATA dbuf, int flag)
 {
-       struct list_struct rec;
-       tdb_off rec_ptr;
-
-       /* find entry */
-       if (!(rec_ptr = tdb_find(tdb, key, tdb_hash(&key), &rec)))
-               return -1;
-
-       /* Append of 0 is always ok. */
-       if (new_dbuf.dsize == 0)
-               return 0;
+       uint32_t hash;
+       int ret;
 
-       /* must be long enough for key, old data + new data and tailer */
-       if (rec.rec_len < key.dsize + rec.data_len + new_dbuf.dsize + sizeof(tdb_off)) {
-               /* No room. */
-               tdb->ecode = TDB_SUCCESS; /* Not really an error */
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB_ERR_RDONLY;
+               tdb_trace_2rec_flag_ret(tdb, "tdb_store", key, dbuf, flag, -1);
                return -1;
        }
 
-       if (tdb_write(tdb, rec_ptr + sizeof(rec) + rec.key_len + rec.data_len,
-                     new_dbuf.dptr, new_dbuf.dsize) == -1)
+       /* find which hash bucket it is in */
+       hash = tdb->hash_fn(&key);
+       if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
                return -1;
 
-       /* update size */
-       rec.data_len += new_dbuf.dsize;
-       return rec_write(tdb, rec_ptr, &rec);
+       ret = _tdb_store(tdb, key, dbuf, flag, hash);
+       tdb_trace_2rec_flag_ret(tdb, "tdb_store", key, dbuf, flag, ret);
+       tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
+       return ret;
 }
 
 /* Append to an entry. Create if not exist. */
-
-int tdb_append(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA new_dbuf)
+int tdb_append(struct tdb_context *tdb, TDB_DATA key, TDB_DATA new_dbuf)
 {
-       struct list_struct rec;
-       u32 hash;
-       tdb_off rec_ptr;
-       char *p = NULL;
-       int ret = 0;
-       size_t new_data_size = 0;
+       uint32_t hash;
+       TDB_DATA dbuf;
+       int ret = -1;
 
        /* find which hash bucket it is in */
-       hash = tdb_hash(&key);
-       if (!tdb_keylocked(tdb, hash))
-               return -1;
+       hash = tdb->hash_fn(&key);
        if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
                return -1;
 
-       /* first try in-place. */
-       if (tdb_append_inplace(tdb, key, new_dbuf) == 0)
-               goto out;
-
-       /* reset the error code potentially set by the tdb_append_inplace() */
-       tdb->ecode = TDB_SUCCESS;
-
-       /* find entry */
-       if (!(rec_ptr = tdb_find(tdb, key, hash, &rec))) {
-               if (tdb->ecode != TDB_ERR_NOEXIST)
-                       goto fail;
+       dbuf = _tdb_fetch(tdb, key);
 
-               /* Not found - create. */
-
-               ret = tdb_store(tdb, key, new_dbuf, TDB_INSERT);
-               goto out;
+       if (dbuf.dptr == NULL) {
+               dbuf.dptr = (unsigned char *)malloc(new_dbuf.dsize);
+       } else {
+               unsigned int new_len = dbuf.dsize + new_dbuf.dsize;
+               unsigned char *new_dptr;
+
+               /* realloc '0' is special: don't do that. */
+               if (new_len == 0)
+                       new_len = 1;
+               new_dptr = (unsigned char *)realloc(dbuf.dptr, new_len);
+               if (new_dptr == NULL) {
+                       free(dbuf.dptr);
+               }
+               dbuf.dptr = new_dptr;
        }
 
-       new_data_size = rec.data_len + new_dbuf.dsize;
-
-       /* Copy key+old_value+value *before* allocating free space in case malloc
-          fails and we are left with a dead spot in the tdb. */
-
-       if (!(p = (char *)malloc(key.dsize + new_data_size))) {
+       if (dbuf.dptr == NULL) {
                tdb->ecode = TDB_ERR_OOM;
-               goto fail;
+               goto failed;
        }
 
-       /* Copy the key in place. */
-       memcpy(p, key.dptr, key.dsize);
+       memcpy(dbuf.dptr + dbuf.dsize, new_dbuf.dptr, new_dbuf.dsize);
+       dbuf.dsize += new_dbuf.dsize;
 
-       /* Now read the old data into place. */
-       if (rec.data_len &&
-               tdb_read(tdb, rec_ptr + sizeof(rec) + rec.key_len, p + key.dsize, rec.data_len, 0) == -1)
-                       goto fail;
+       ret = _tdb_store(tdb, key, dbuf, 0, hash);
+       tdb_trace_2rec_retrec(tdb, "tdb_append", key, new_dbuf, dbuf);
+       
+failed:
+       tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
+       SAFE_FREE(dbuf.dptr);
+       return ret;
+}
 
-       /* Finally append the new data. */
-       if (new_dbuf.dsize)
-               memcpy(p+key.dsize+rec.data_len, new_dbuf.dptr, new_dbuf.dsize);
 
-       /* delete any existing record - if it doesn't exist we don't
-           care.  Doing this first reduces fragmentation, and avoids
-           coalescing with `allocated' block before it's updated. */
+/*
+  return the name of the current tdb file
+  useful for external logging functions
+*/
+const char *tdb_name(struct tdb_context *tdb)
+{
+       return tdb->name;
+}
 
-       tdb_delete(tdb, key);
+/*
+  return the underlying file descriptor being used by tdb, or -1
+  useful for external routines that want to check the device/inode
+  of the fd
+*/
+int tdb_fd(struct tdb_context *tdb)
+{
+       return tdb->fd;
+}
 
-       if (!(rec_ptr = tdb_allocate(tdb, key.dsize + new_data_size, &rec)))
-               goto fail;
+/*
+  return the current logging function
+  useful for external tdb routines that wish to log tdb errors
+*/
+tdb_log_func tdb_log_fn(struct tdb_context *tdb)
+{
+       return tdb->log.log_fn;
+}
 
-       /* Read hash top into next ptr */
-       if (ofs_read(tdb, TDB_HASH_TOP(hash), &rec.next) == -1)
-               goto fail;
 
-       rec.key_len = key.dsize;
-       rec.data_len = new_data_size;
-       rec.full_hash = hash;
-       rec.magic = TDB_MAGIC;
+/*
+  get the tdb sequence number. Only makes sense if the writers opened
+  with TDB_SEQNUM set. Note that this sequence number will wrap quite
+  quickly, so it should only be used for a 'has something changed'
+  test, not for code that relies on the count of the number of changes
+  made. If you want a counter then use a tdb record.
+
+  The aim of this sequence number is to allow for a very lightweight
+  test of a possible tdb change.
+*/
+int tdb_get_seqnum(struct tdb_context *tdb)
+{
+       tdb_off_t seqnum=0;
 
-       /* write out and point the top of the hash chain at it */
-       if (rec_write(tdb, rec_ptr, &rec) == -1
-           || tdb_write(tdb, rec_ptr+sizeof(rec), p, key.dsize+new_data_size)==-1
-           || ofs_write(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1) {
-               /* Need to tdb_unallocate() here */
-               goto fail;
-       }
+       tdb_ofs_read(tdb, TDB_SEQNUM_OFS, &seqnum);
+       return seqnum;
+}
 
- out:
-       SAFE_FREE(p); 
-       tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
-       return ret;
+int tdb_hash_size(struct tdb_context *tdb)
+{
+       return tdb->header.hash_size;
+}
 
-fail:
-       ret = -1;
-       goto out;
+size_t tdb_map_size(struct tdb_context *tdb)
+{
+       return tdb->map_size;
 }
 
-static int tdb_already_open(dev_t device,
-                           ino_t ino)
+int tdb_get_flags(struct tdb_context *tdb)
 {
-       TDB_CONTEXT *i;
-       
-       for (i = tdbs; i; i = i->next) {
-               if (i->device == device && i->inode == ino) {
-                       return 1;
-               }
+       return tdb->flags;
+}
+
+void tdb_add_flags(struct tdb_context *tdb, unsigned flags)
+{
+       if ((flags & TDB_ALLOW_NESTING) &&
+           (flags & TDB_DISALLOW_NESTING)) {
+               tdb->ecode = TDB_ERR_NESTING;
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_add_flags: "
+                       "allow_nesting and disallow_nesting are not allowed together!"));
+               return;
        }
 
-       return 0;
+       if (flags & TDB_ALLOW_NESTING) {
+               tdb->flags &= ~TDB_DISALLOW_NESTING;
+       }
+       if (flags & TDB_DISALLOW_NESTING) {
+               tdb->flags &= ~TDB_ALLOW_NESTING;
+       }
+
+       tdb->flags |= flags;
 }
 
-/* open the database, creating it if necessary 
+void tdb_remove_flags(struct tdb_context *tdb, unsigned flags)
+{
+       if ((flags & TDB_ALLOW_NESTING) &&
+           (flags & TDB_DISALLOW_NESTING)) {
+               tdb->ecode = TDB_ERR_NESTING;
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_remove_flags: "
+                       "allow_nesting and disallow_nesting are not allowed together!"));
+               return;
+       }
+
+       if (flags & TDB_ALLOW_NESTING) {
+               tdb->flags |= TDB_DISALLOW_NESTING;
+       }
+       if (flags & TDB_DISALLOW_NESTING) {
+               tdb->flags |= TDB_ALLOW_NESTING;
+       }
 
-   The open_flags and mode are passed straight to the open call on the
-   database file. A flags value of O_WRONLY is invalid. The hash size
-   is advisory, use zero for a default value.
+       tdb->flags &= ~flags;
+}
 
-   Return is NULL on error, in which case errno is also set.  Don't 
-   try to call tdb_error or tdb_errname, just do strerror(errno).
 
-   @param name may be NULL for internal databases. */
-TDB_CONTEXT *tdb_open(const char *name, int hash_size, int tdb_flags,
-                     int open_flags, mode_t mode)
+/*
+  enable sequence number handling on an open tdb
+*/
+void tdb_enable_seqnum(struct tdb_context *tdb)
 {
-       return tdb_open_ex(name, hash_size, tdb_flags, open_flags, mode, NULL);
+       tdb->flags |= TDB_SEQNUM;
 }
 
 
-TDB_CONTEXT *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
-                        int open_flags, mode_t mode,
-                        tdb_log_func log_fn)
+/*
+  add a region of the file to the freelist. Length is the size of the region in bytes, 
+  which includes the free list header that needs to be added
+ */
+static int tdb_free_region(struct tdb_context *tdb, tdb_off_t offset, ssize_t length)
 {
-       TDB_CONTEXT *tdb;
-       struct stat st;
-       int rev = 0, locked;
-       unsigned char *vp;
-       u32 vertest;
-
-       if (!(tdb = calloc(1, sizeof *tdb))) {
-               /* Can't log this */
-               errno = ENOMEM;
-               goto fail;
+       struct tdb_record rec;
+       if (length <= sizeof(rec)) {
+               /* the region is not worth adding */
+               return 0;
        }
-       tdb->fd = -1;
-       tdb->name = NULL;
-       tdb->map_ptr = NULL;
-       tdb->lockedkeys = NULL;
-       tdb->flags = tdb_flags;
-       tdb->open_flags = open_flags;
-       tdb->log_fn = log_fn;
-       
-       if ((open_flags & O_ACCMODE) == O_WRONLY) {
-               TDB_LOG((tdb, 0, "tdb_open_ex: can't open tdb %s write-only\n",
-                        name));
-               errno = EINVAL;
-               goto fail;
+       if (length + offset > tdb->map_size) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_free_region: adding region beyond end of file\n"));
+               return -1;              
        }
-       
-       if (hash_size == 0)
-               hash_size = DEFAULT_HASH_SIZE;
-       if ((open_flags & O_ACCMODE) == O_RDONLY) {
-               tdb->read_only = 1;
-               /* read only databases don't do locking or clear if first */
-               tdb->flags |= TDB_NOLOCK;
-               tdb->flags &= ~TDB_CLEAR_IF_FIRST;
+       memset(&rec,'\0',sizeof(rec));
+       rec.rec_len = length - sizeof(rec);
+       if (tdb_free(tdb, offset, &rec) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_free_region: failed to add free record\n"));
+               return -1;
        }
+       return 0;
+}
 
-       /* internal databases don't mmap or lock, and start off cleared */
-       if (tdb->flags & TDB_INTERNAL) {
-               tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
-               tdb->flags &= ~TDB_CLEAR_IF_FIRST;
-               if (tdb_new_database(tdb, hash_size) != 0) {
-                       TDB_LOG((tdb, 0, "tdb_open_ex: tdb_new_database failed!"));
-                       goto fail;
-               }
-               goto internal;
+/*
+  wipe the entire database, deleting all records. This can be done
+  very fast by using a global lock. The entire data portion of the
+  file becomes a single entry in the freelist.
+
+  This code carefully steps around the recovery area, leaving it alone
+ */
+int tdb_wipe_all(struct tdb_context *tdb)
+{
+       int i;
+       tdb_off_t offset = 0;
+       ssize_t data_len;
+       tdb_off_t recovery_head;
+       tdb_len_t recovery_size = 0;
+
+       if (tdb_lockall(tdb) != 0) {
+               return -1;
        }
 
-       if ((tdb->fd = open(name, open_flags, mode)) == -1) {
-               TDB_LOG((tdb, 5, "tdb_open_ex: could not open file %s: %s\n",
-                        name, strerror(errno)));
-               goto fail;      /* errno set by open(2) */
+       tdb_trace(tdb, "tdb_wipe_all");
+
+       /* see if the tdb has a recovery area, and remember its size
+          if so. We don't want to lose this as otherwise each
+          tdb_wipe_all() in a transaction will increase the size of
+          the tdb by the size of the recovery area */
+       if (tdb_ofs_read(tdb, TDB_RECOVERY_HEAD, &recovery_head) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_wipe_all: failed to read recovery head\n"));
+               goto failed;
        }
 
-       /* ensure there is only one process initialising at once */
-       if (tdb_brlock(tdb, GLOBAL_LOCK, F_WRLCK, F_SETLKW, 0) == -1) {
-               TDB_LOG((tdb, 0, "tdb_open_ex: failed to get global lock on %s: %s\n",
-                        name, strerror(errno)));
-               goto fail;      /* errno set by tdb_brlock */
+       if (recovery_head != 0) {
+               struct tdb_record rec;
+               if (tdb->methods->tdb_read(tdb, recovery_head, &rec, sizeof(rec), DOCONV()) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_wipe_all: failed to read recovery record\n"));
+                       return -1;
+               }       
+               recovery_size = rec.rec_len + sizeof(rec);
        }
 
-       /* we need to zero database if we are the only one with it open */
-       if ((locked = (tdb_brlock(tdb, ACTIVE_LOCK, F_WRLCK, F_SETLK, 0) == 0))
-           && (tdb_flags & TDB_CLEAR_IF_FIRST)) {
-               open_flags |= O_CREAT;
-               if (ftruncate(tdb->fd, 0) == -1) {
-                       TDB_LOG((tdb, 0, "tdb_open_ex: "
-                                "failed to truncate %s: %s\n",
-                                name, strerror(errno)));
-                       goto fail; /* errno set by ftruncate */
+       /* wipe the hashes */
+       for (i=0;i<tdb->header.hash_size;i++) {
+               if (tdb_ofs_write(tdb, TDB_HASH_TOP(i), &offset) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_wipe_all: failed to write hash %d\n", i));
+                       goto failed;
                }
        }
 
-       if (read(tdb->fd, &tdb->header, sizeof(tdb->header)) != sizeof(tdb->header)
-           || strcmp(tdb->header.magic_food, TDB_MAGIC_FOOD) != 0
-           || (tdb->header.version != TDB_VERSION
-               && !(rev = (tdb->header.version==TDB_BYTEREV(TDB_VERSION))))) {
-               /* its not a valid database - possibly initialise it */
-               if (!(open_flags & O_CREAT) || tdb_new_database(tdb, hash_size) == -1) {
-                       errno = EIO; /* ie bad format or something */
-                       goto fail;
-               }
-               rev = (tdb->flags & TDB_CONVERT);
+       /* wipe the freelist */
+       if (tdb_ofs_write(tdb, FREELIST_TOP, &offset) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_wipe_all: failed to write freelist\n"));
+               goto failed;
        }
-       vp = (unsigned char *)&tdb->header.version;
-       vertest = (((u32)vp[0]) << 24) | (((u32)vp[1]) << 16) |
-                 (((u32)vp[2]) << 8) | (u32)vp[3];
-       tdb->flags |= (vertest==TDB_VERSION) ? TDB_BIGENDIAN : 0;
-       if (!rev)
-               tdb->flags &= ~TDB_CONVERT;
-       else {
-               tdb->flags |= TDB_CONVERT;
-               convert(&tdb->header, sizeof(tdb->header));
+
+       /* add all the rest of the file to the freelist, possibly leaving a gap 
+          for the recovery area */
+       if (recovery_size == 0) {
+               /* the simple case - the whole file can be used as a freelist */
+               data_len = (tdb->map_size - TDB_DATA_START(tdb->header.hash_size));
+               if (tdb_free_region(tdb, TDB_DATA_START(tdb->header.hash_size), data_len) != 0) {
+                       goto failed;
+               }
+       } else {
+               /* we need to add two freelist entries - one on either
+                  side of the recovery area 
+
+                  Note that we cannot shift the recovery area during
+                  this operation. Only the transaction.c code may
+                  move the recovery area or we risk subtle data
+                  corruption
+               */
+               data_len = (recovery_head - TDB_DATA_START(tdb->header.hash_size));
+               if (tdb_free_region(tdb, TDB_DATA_START(tdb->header.hash_size), data_len) != 0) {
+                       goto failed;
+               }
+               /* and the 2nd free list entry after the recovery area - if any */
+               data_len = tdb->map_size - (recovery_head+recovery_size);
+               if (tdb_free_region(tdb, recovery_head+recovery_size, data_len) != 0) {
+                       goto failed;
+               }
        }
-       if (fstat(tdb->fd, &st) == -1)
-               goto fail;
 
-       /* Is it already in the open list?  If so, fail. */
-       if (tdb_already_open(st.st_dev, st.st_ino)) {
-               TDB_LOG((tdb, 2, "tdb_open_ex: "
-                        "%s (%d,%d) is already open in this process\n",
-                        name, st.st_dev, st.st_ino));
-               errno = EBUSY;
-               goto fail;
+       if (tdb_unlockall(tdb) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_wipe_all: failed to unlock\n"));
+               goto failed;
        }
 
-       if (!(tdb->name = (char *)strdup(name))) {
-               errno = ENOMEM;
-               goto fail;
+       return 0;
+
+failed:
+       tdb_unlockall(tdb);
+       return -1;
+}
+
+struct traverse_state {
+       bool error;
+       struct tdb_context *dest_db;
+};
+
+/*
+  traverse function for repacking
+ */
+static int repack_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private_data)
+{
+       struct traverse_state *state = (struct traverse_state *)private_data;
+       if (tdb_store(state->dest_db, key, data, TDB_INSERT) != 0) {
+               state->error = true;
+               return -1;
        }
+       return 0;
+}
 
-       tdb->map_size = st.st_size;
-       tdb->device = st.st_dev;
-       tdb->inode = st.st_ino;
-       tdb->locked = calloc(tdb->header.hash_size+1, sizeof(tdb->locked[0]));
-       if (!tdb->locked) {
-               TDB_LOG((tdb, 2, "tdb_open_ex: "
-                        "failed to allocate lock structure for %s\n",
-                        name));
-               errno = ENOMEM;
-               goto fail;
+/*
+  repack a tdb
+ */
+int tdb_repack(struct tdb_context *tdb)
+{
+       struct tdb_context *tmp_db;
+       struct traverse_state state;
+
+       tdb_trace(tdb, "tdb_repack");
+
+       if (tdb_transaction_start(tdb) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to start transaction\n"));
+               return -1;
        }
-       tdb_mmap(tdb);
-       if (locked) {
-               if (!tdb->read_only)
-                       if (tdb_clear_spinlocks(tdb) != 0) {
-                               TDB_LOG((tdb, 0, "tdb_open_ex: "
-                               "failed to clear spinlock\n"));
-                               goto fail;
-                       }
-               if (tdb_brlock(tdb, ACTIVE_LOCK, F_UNLCK, F_SETLK, 0) == -1) {
-                       TDB_LOG((tdb, 0, "tdb_open_ex: "
-                                "failed to take ACTIVE_LOCK on %s: %s\n",
-                                name, strerror(errno)));
-                       goto fail;
-               }
+
+       tmp_db = tdb_open("tmpdb", tdb_hash_size(tdb), TDB_INTERNAL, O_RDWR|O_CREAT, 0);
+       if (tmp_db == NULL) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to create tmp_db\n"));
+               tdb_transaction_cancel(tdb);
+               return -1;
        }
-       /* leave this lock in place to indicate it's in use */
-       if (tdb_brlock(tdb, ACTIVE_LOCK, F_RDLCK, F_SETLKW, 0) == -1)
-               goto fail;
 
- internal:
-       /* Internal (memory-only) databases skip all the code above to
-        * do with disk files, and resume here by releasing their
-        * global lock and hooking into the active list. */
-       if (tdb_brlock(tdb, GLOBAL_LOCK, F_UNLCK, F_SETLKW, 0) == -1)
-               goto fail;
-       tdb->next = tdbs;
-       tdbs = tdb;
-       return tdb;
+       state.error = false;
+       state.dest_db = tmp_db;
 
- fail:
-       { int save_errno = errno;
+       if (tdb_traverse_read(tdb, repack_traverse, &state) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to traverse copying out\n"));
+               tdb_transaction_cancel(tdb);
+               tdb_close(tmp_db);
+               return -1;              
+       }
 
-       if (!tdb)
-               return NULL;
-       
-       if (tdb->map_ptr) {
-               if (tdb->flags & TDB_INTERNAL)
-                       SAFE_FREE(tdb->map_ptr);
-               else
-                       tdb_munmap(tdb);
+       if (state.error) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Error during traversal\n"));
+               tdb_transaction_cancel(tdb);
+               tdb_close(tmp_db);
+               return -1;
        }
-       SAFE_FREE(tdb->name);
-       if (tdb->fd != -1)
-               if (close(tdb->fd) != 0)
-                       TDB_LOG((tdb, 5, "tdb_open_ex: failed to close tdb->fd on error!\n"));
-       SAFE_FREE(tdb->locked);
-       SAFE_FREE(tdb);
-       errno = save_errno;
-       return NULL;
+
+       if (tdb_wipe_all(tdb) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to wipe database\n"));
+               tdb_transaction_cancel(tdb);
+               tdb_close(tmp_db);
+               return -1;
        }
-}
 
-/**
- * Close a database.
- *
- * @returns -1 for error; 0 for success.
- **/
-int tdb_close(TDB_CONTEXT *tdb)
-{
-       TDB_CONTEXT **i;
-       int ret = 0;
-
-       if (tdb->map_ptr) {
-               if (tdb->flags & TDB_INTERNAL)
-                       SAFE_FREE(tdb->map_ptr);
-               else
-                       tdb_munmap(tdb);
+       state.error = false;
+       state.dest_db = tdb;
+
+       if (tdb_traverse_read(tmp_db, repack_traverse, &state) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to traverse copying back\n"));
+               tdb_transaction_cancel(tdb);
+               tdb_close(tmp_db);
+               return -1;              
        }
-       SAFE_FREE(tdb->name);
-       if (tdb->fd != -1)
-               ret = close(tdb->fd);
-       SAFE_FREE(tdb->locked);
-       SAFE_FREE(tdb->lockedkeys);
-
-       /* Remove from contexts list */
-       for (i = &tdbs; *i; i = &(*i)->next) {
-               if (*i == tdb) {
-                       *i = tdb->next;
-                       break;
-               }
+
+       if (state.error) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Error during second traversal\n"));
+               tdb_transaction_cancel(tdb);
+               tdb_close(tmp_db);
+               return -1;
        }
 
-       memset(tdb, 0, sizeof(*tdb));
-       SAFE_FREE(tdb);
+       tdb_close(tmp_db);
 
-       return ret;
+       if (tdb_transaction_commit(tdb) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to commit\n"));
+               return -1;
+       }
+
+       return 0;
 }
 
-/* lock/unlock entire database */
-int tdb_lockall(TDB_CONTEXT *tdb)
+#ifdef TDB_TRACE
+static void tdb_trace_write(struct tdb_context *tdb, const char *str)
 {
-       u32 i;
-
-       /* There are no locks on read-only dbs */
-       if (tdb->read_only)
-               return TDB_ERRCODE(TDB_ERR_LOCK, -1);
-       if (tdb->lockedkeys)
-               return TDB_ERRCODE(TDB_ERR_NOLOCK, -1);
-       for (i = 0; i < tdb->header.hash_size; i++) 
-               if (tdb_lock(tdb, i, F_WRLCK))
-                       break;
-
-       /* If error, release locks we have... */
-       if (i < tdb->header.hash_size) {
-               u32 j;
-
-               for ( j = 0; j < i; j++)
-                       tdb_unlock(tdb, j, F_WRLCK);
-               return TDB_ERRCODE(TDB_ERR_NOLOCK, -1);
+       if (write(tdb->tracefd, str, strlen(str)) != strlen(str)) {
+               close(tdb->tracefd);
+               tdb->tracefd = -1;
        }
+}
 
-       return 0;
+static void tdb_trace_start(struct tdb_context *tdb)
+{
+       tdb_off_t seqnum=0;
+       char msg[sizeof(tdb_off_t) * 4 + 1];
+
+       tdb_ofs_read(tdb, TDB_SEQNUM_OFS, &seqnum);
+       snprintf(msg, sizeof(msg), "%u ", seqnum);
+       tdb_trace_write(tdb, msg);
 }
-void tdb_unlockall(TDB_CONTEXT *tdb)
+
+static void tdb_trace_end(struct tdb_context *tdb)
 {
-       u32 i;
-       for (i=0; i < tdb->header.hash_size; i++)
-               tdb_unlock(tdb, i, F_WRLCK);
+       tdb_trace_write(tdb, "\n");
 }
 
-int tdb_lockkeys(TDB_CONTEXT *tdb, u32 number, TDB_DATA keys[])
+static void tdb_trace_end_ret(struct tdb_context *tdb, int ret)
 {
-       u32 i, j, hash;
-
-       /* Can't lock more keys if already locked */
-       if (tdb->lockedkeys)
-               return TDB_ERRCODE(TDB_ERR_NOLOCK, -1);
-       if (!(tdb->lockedkeys = malloc(sizeof(u32) * (number+1))))
-               return TDB_ERRCODE(TDB_ERR_OOM, -1);
-       /* First number in array is # keys */
-       tdb->lockedkeys[0] = number;
-
-       /* Insertion sort by bucket */
-       for (i = 0; i < number; i++) {
-               hash = tdb_hash(&keys[i]);
-               for (j = 0; j < i && BUCKET(tdb->lockedkeys[j+1]) < BUCKET(hash); j++);
-                       memmove(&tdb->lockedkeys[j+2], &tdb->lockedkeys[j+1], sizeof(u32) * (i-j));
-               tdb->lockedkeys[j+1] = hash;
-       }
-       /* Finally, lock in order */
-       for (i = 0; i < number; i++)
-               if (tdb_lock(tdb, i, F_WRLCK))
-                       break;
-
-       /* If error, release locks we have... */
-       if (i < number) {
-               for ( j = 0; j < i; j++)
-                       tdb_unlock(tdb, j, F_WRLCK);
-               SAFE_FREE(tdb->lockedkeys);
-               return TDB_ERRCODE(TDB_ERR_NOLOCK, -1);
-       }
-       return 0;
+       char msg[sizeof(ret) * 4 + 4];
+       snprintf(msg, sizeof(msg), " = %i\n", ret);
+       tdb_trace_write(tdb, msg);
 }
 
-/* Unlock the keys previously locked by tdb_lockkeys() */
-void tdb_unlockkeys(TDB_CONTEXT *tdb)
+static void tdb_trace_record(struct tdb_context *tdb, TDB_DATA rec)
 {
-       u32 i;
-       if (!tdb->lockedkeys)
+       char msg[20 + rec.dsize*2], *p;
+       unsigned int i;
+
+       /* We differentiate zero-length records from non-existent ones. */
+       if (rec.dptr == NULL) {
+               tdb_trace_write(tdb, " NULL");
                return;
-       for (i = 0; i < tdb->lockedkeys[0]; i++)
-               tdb_unlock(tdb, tdb->lockedkeys[i+1], F_WRLCK);
-       SAFE_FREE(tdb->lockedkeys);
+       }
+
+       /* snprintf here is purely cargo-cult programming. */
+       p = msg;
+       p += snprintf(p, sizeof(msg), " %zu:", rec.dsize);
+       for (i = 0; i < rec.dsize; i++)
+               p += snprintf(p, 2, "%02x", rec.dptr[i]);
+
+       tdb_trace_write(tdb, msg);
 }
 
-/* lock/unlock one hash chain. This is meant to be used to reduce
-   contention - it cannot guarantee how many records will be locked */
-int tdb_chainlock(TDB_CONTEXT *tdb, TDB_DATA key)
+void tdb_trace(struct tdb_context *tdb, const char *op)
 {
-       return tdb_lock(tdb, BUCKET(tdb_hash(&key)), F_WRLCK);
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, op);
+       tdb_trace_end(tdb);
 }
 
-int tdb_chainunlock(TDB_CONTEXT *tdb, TDB_DATA key)
+void tdb_trace_seqnum(struct tdb_context *tdb, uint32_t seqnum, const char *op)
 {
-       return tdb_unlock(tdb, BUCKET(tdb_hash(&key)), F_WRLCK);
+       char msg[sizeof(tdb_off_t) * 4 + 1];
+
+       snprintf(msg, sizeof(msg), "%u ", seqnum);
+       tdb_trace_write(tdb, msg);
+       tdb_trace_write(tdb, op);
+       tdb_trace_end(tdb);
 }
 
-#if 0
-static int tdb_chainlock_read(TDB_CONTEXT *tdb, TDB_DATA key)
+void tdb_trace_open(struct tdb_context *tdb, const char *op,
+                   unsigned hash_size, unsigned tdb_flags, unsigned open_flags)
 {
-       return tdb_lock(tdb, BUCKET(tdb_hash(&key)), F_RDLCK);
+       char msg[128];
+
+       snprintf(msg, sizeof(msg),
+                "%s %u 0x%x 0x%x", op, hash_size, tdb_flags, open_flags);
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, msg);
+       tdb_trace_end(tdb);
 }
-#endif
 
-#if 0
-static int tdb_chainunlock_read(TDB_CONTEXT *tdb, TDB_DATA key)
+void tdb_trace_ret(struct tdb_context *tdb, const char *op, int ret)
 {
-       return tdb_unlock(tdb, BUCKET(tdb_hash(&key)), F_RDLCK);
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, op);
+       tdb_trace_end_ret(tdb, ret);
 }
-#endif
 
-/* register a loging function */
-void tdb_logging_function(TDB_CONTEXT *tdb, void (*fn)(TDB_CONTEXT *, int , const char *, ...))
+void tdb_trace_retrec(struct tdb_context *tdb, const char *op, TDB_DATA ret)
 {
-       tdb->log_fn = fn;
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, op);
+       tdb_trace_write(tdb, " =");
+       tdb_trace_record(tdb, ret);
+       tdb_trace_end(tdb);
 }
 
-
-/* reopen a tdb - this is used after a fork to ensure that we have an independent
-   seek pointer from our parent and to re-establish locks */
-int tdb_reopen(TDB_CONTEXT *tdb)
+void tdb_trace_1rec(struct tdb_context *tdb, const char *op,
+                   TDB_DATA rec)
 {
-       struct stat st;
-
-       if (tdb_munmap(tdb) != 0) {
-               TDB_LOG((tdb, 0, "tdb_reopen: munmap failed (%s)\n", strerror(errno)));
-               goto fail;
-       }
-       if (close(tdb->fd) != 0)
-               TDB_LOG((tdb, 0, "tdb_reopen: WARNING closing tdb->fd failed!\n"));
-       tdb->fd = open(tdb->name, tdb->open_flags & ~(O_CREAT|O_TRUNC), 0);
-       if (tdb->fd == -1) {
-               TDB_LOG((tdb, 0, "tdb_reopen: open failed (%s)\n", strerror(errno)));
-               goto fail;
-       }
-       if (fstat(tdb->fd, &st) != 0) {
-               TDB_LOG((tdb, 0, "tdb_reopen: fstat failed (%s)\n", strerror(errno)));
-               goto fail;
-       }
-       if (st.st_ino != tdb->inode || st.st_dev != tdb->device) {
-               TDB_LOG((tdb, 0, "tdb_reopen: file dev/inode has changed!\n"));
-               goto fail;
-       }
-       tdb_mmap(tdb);
-       if (tdb_brlock(tdb, ACTIVE_LOCK, F_RDLCK, F_SETLKW, 0) == -1) {
-               TDB_LOG((tdb, 0, "tdb_reopen: failed to obtain active lock\n"));
-               goto fail;
-       }
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, op);
+       tdb_trace_record(tdb, rec);
+       tdb_trace_end(tdb);
+}
 
-       return 0;
+void tdb_trace_1rec_ret(struct tdb_context *tdb, const char *op,
+                       TDB_DATA rec, int ret)
+{
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, op);
+       tdb_trace_record(tdb, rec);
+       tdb_trace_end_ret(tdb, ret);
+}
 
-fail:
-       tdb_close(tdb);
-       return -1;
+void tdb_trace_1rec_retrec(struct tdb_context *tdb, const char *op,
+                          TDB_DATA rec, TDB_DATA ret)
+{
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, op);
+       tdb_trace_record(tdb, rec);
+       tdb_trace_write(tdb, " =");
+       tdb_trace_record(tdb, ret);
+       tdb_trace_end(tdb);
 }
 
-/* reopen all tdb's */
-int tdb_reopen_all(void)
+void tdb_trace_2rec_flag_ret(struct tdb_context *tdb, const char *op,
+                            TDB_DATA rec1, TDB_DATA rec2, unsigned flag,
+                            int ret)
 {
-       TDB_CONTEXT *tdb;
+       char msg[1 + sizeof(ret) * 4];
 
-       for (tdb=tdbs; tdb; tdb = tdb->next) {
-               if (tdb_reopen(tdb) != 0) return -1;
-       }
+       snprintf(msg, sizeof(msg), " %#x", flag);
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, op);
+       tdb_trace_record(tdb, rec1);
+       tdb_trace_record(tdb, rec2);
+       tdb_trace_write(tdb, msg);
+       tdb_trace_end_ret(tdb, ret);
+}
 
-       return 0;
+void tdb_trace_2rec_retrec(struct tdb_context *tdb, const char *op,
+                          TDB_DATA rec1, TDB_DATA rec2, TDB_DATA ret)
+{
+       tdb_trace_start(tdb);
+       tdb_trace_write(tdb, op);
+       tdb_trace_record(tdb, rec1);
+       tdb_trace_record(tdb, rec2);
+       tdb_trace_write(tdb, " =");
+       tdb_trace_record(tdb, ret);
+       tdb_trace_end(tdb);
 }
+#endif
diff --git a/libatalk/tdb/tdb_private.h b/libatalk/tdb/tdb_private.h
new file mode 100644 (file)
index 0000000..41389c4
--- /dev/null
@@ -0,0 +1,288 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library - private includes
+
+   Copyright (C) Andrew Tridgell              2005
+   
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#if 0
+#include "replace.h"
+#include "system/filesys.h"
+#include "system/time.h"
+#include "system/shmem.h"
+#include "system/select.h"
+#include "system/wait.h"
+#include "tdb.h"
+#endif
+
+#include <unistd.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/select.h>
+#include <sys/mman.h>
+#include <sys/time.h>
+#include <time.h>
+#include <utime.h>
+#include <sys/wait.h>
+#include <string.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <stdio.h>
+#include <errno.h>
+#include <sys/param.h>
+
+#ifndef __STRING
+#define __STRING(x)    #x
+#endif
+
+#ifndef __STRINGSTRING
+#define __STRINGSTRING(x) __STRING(x)
+#endif
+
+#ifndef __LINESTR__
+#define __LINESTR__ __STRINGSTRING(__LINE__)
+#endif
+
+#ifndef __location__
+#define __location__ __FILE__ ":" __LINESTR__
+#endif
+
+#include <atalk/util.h>
+#include "atalk/tdb.h"
+
+/* #define TDB_TRACE 1 */
+#ifndef HAVE_GETPAGESIZE
+#define getpagesize() 0x2000
+#endif
+
+typedef uint32_t tdb_len_t;
+typedef uint32_t tdb_off_t;
+
+#ifndef offsetof
+#define offsetof(t,f) ((unsigned int)&((t *)0)->f)
+#endif
+
+#define TDB_MAGIC_FOOD "TDB file\n"
+#define TDB_VERSION (0x26011967 + 6)
+#define TDB_MAGIC (0x26011999U)
+#define TDB_FREE_MAGIC (~TDB_MAGIC)
+#define TDB_DEAD_MAGIC (0xFEE1DEAD)
+#define TDB_RECOVERY_MAGIC (0xf53bc0e7U)
+#define TDB_ALIGNMENT 4
+#define DEFAULT_HASH_SIZE 131
+#define FREELIST_TOP (sizeof(struct tdb_header))
+#define TDB_ALIGN(x,a) (((x) + (a)-1) & ~((a)-1))
+#define TDB_BYTEREV(x) (((((x)&0xff)<<24)|((x)&0xFF00)<<8)|(((x)>>8)&0xFF00)|((x)>>24))
+#define TDB_DEAD(r) ((r)->magic == TDB_DEAD_MAGIC)
+#define TDB_BAD_MAGIC(r) ((r)->magic != TDB_MAGIC && !TDB_DEAD(r))
+#define TDB_HASH_TOP(hash) (FREELIST_TOP + (BUCKET(hash)+1)*sizeof(tdb_off_t))
+#define TDB_HASHTABLE_SIZE(tdb) ((tdb->header.hash_size+1)*sizeof(tdb_off_t))
+#define TDB_DATA_START(hash_size) (TDB_HASH_TOP(hash_size-1) + sizeof(tdb_off_t))
+#define TDB_RECOVERY_HEAD offsetof(struct tdb_header, recovery_start)
+#define TDB_SEQNUM_OFS    offsetof(struct tdb_header, sequence_number)
+#define TDB_PAD_BYTE 0x42
+#define TDB_PAD_U32  0x42424242
+
+/* NB assumes there is a local variable called "tdb" that is the
+ * current context, also takes doubly-parenthesized print-style
+ * argument. */
+#define TDB_LOG(x) tdb->log.log_fn x
+
+#ifdef TDB_TRACE
+void tdb_trace(struct tdb_context *tdb, const char *op);
+void tdb_trace_seqnum(struct tdb_context *tdb, uint32_t seqnum, const char *op);
+void tdb_trace_open(struct tdb_context *tdb, const char *op,
+                   unsigned hash_size, unsigned tdb_flags, unsigned open_flags);
+void tdb_trace_ret(struct tdb_context *tdb, const char *op, int ret);
+void tdb_trace_retrec(struct tdb_context *tdb, const char *op, TDB_DATA ret);
+void tdb_trace_1rec(struct tdb_context *tdb, const char *op,
+                   TDB_DATA rec);
+void tdb_trace_1rec_ret(struct tdb_context *tdb, const char *op,
+                       TDB_DATA rec, int ret);
+void tdb_trace_1rec_retrec(struct tdb_context *tdb, const char *op,
+                          TDB_DATA rec, TDB_DATA ret);
+void tdb_trace_2rec_flag_ret(struct tdb_context *tdb, const char *op,
+                            TDB_DATA rec1, TDB_DATA rec2, unsigned flag,
+                            int ret);
+void tdb_trace_2rec_retrec(struct tdb_context *tdb, const char *op,
+                          TDB_DATA rec1, TDB_DATA rec2, TDB_DATA ret);
+#else
+#define tdb_trace(tdb, op)
+#define tdb_trace_seqnum(tdb, seqnum, op)
+#define tdb_trace_open(tdb, op, hash_size, tdb_flags, open_flags)
+#define tdb_trace_ret(tdb, op, ret)
+#define tdb_trace_retrec(tdb, op, ret)
+#define tdb_trace_1rec(tdb, op, rec)
+#define tdb_trace_1rec_ret(tdb, op, rec, ret)
+#define tdb_trace_1rec_retrec(tdb, op, rec, ret)
+#define tdb_trace_2rec_flag_ret(tdb, op, rec1, rec2, flag, ret)
+#define tdb_trace_2rec_retrec(tdb, op, rec1, rec2, ret)
+#endif /* !TDB_TRACE */
+
+/* lock offsets */
+#define GLOBAL_LOCK      0
+#define ACTIVE_LOCK      4
+#define TRANSACTION_LOCK 8
+
+/* free memory if the pointer is valid and zero the pointer */
+#ifndef SAFE_FREE
+#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); (x)=NULL;} } while(0)
+#endif
+
+#define BUCKET(hash) ((hash) % tdb->header.hash_size)
+
+#define DOCONV() (tdb->flags & TDB_CONVERT)
+#define CONVERT(x) (DOCONV() ? tdb_convert(&x, sizeof(x)) : &x)
+
+
+/* the body of the database is made of one tdb_record for the free space
+   plus a separate data list for each hash value */
+struct tdb_record {
+       tdb_off_t next; /* offset of the next record in the list */
+       tdb_len_t rec_len; /* total byte length of record */
+       tdb_len_t key_len; /* byte length of key */
+       tdb_len_t data_len; /* byte length of data */
+       uint32_t full_hash; /* the full 32 bit hash of the key */
+       uint32_t magic;   /* try to catch errors */
+       /* the following union is implied:
+               union {
+                       char record[rec_len];
+                       struct {
+                               char key[key_len];
+                               char data[data_len];
+                       }
+                       uint32_t totalsize; (tailer)
+               }
+       */
+};
+
+
+/* this is stored at the front of every database */
+struct tdb_header {
+       char magic_food[32]; /* for /etc/magic */
+       uint32_t version; /* version of the code */
+       uint32_t hash_size; /* number of hash entries */
+       tdb_off_t rwlocks; /* obsolete - kept to detect old formats */
+       tdb_off_t recovery_start; /* offset of transaction recovery region */
+       tdb_off_t sequence_number; /* used when TDB_SEQNUM is set */
+       tdb_off_t reserved[29];
+};
+
+struct tdb_lock_type {
+       int list;
+       uint32_t count;
+       uint32_t ltype;
+};
+
+struct tdb_traverse_lock {
+       struct tdb_traverse_lock *next;
+       uint32_t off;
+       uint32_t hash;
+       int lock_rw;
+};
+
+
+struct tdb_methods {
+       int (*tdb_read)(struct tdb_context *, tdb_off_t , void *, tdb_len_t , int );
+       int (*tdb_write)(struct tdb_context *, tdb_off_t, const void *, tdb_len_t);
+       void (*next_hash_chain)(struct tdb_context *, uint32_t *);
+       int (*tdb_oob)(struct tdb_context *, tdb_off_t , int );
+       int (*tdb_expand_file)(struct tdb_context *, tdb_off_t , tdb_off_t );
+       int (*tdb_brlock)(struct tdb_context *, tdb_off_t , int, int, int, size_t);
+};
+
+struct tdb_context {
+       char *name; /* the name of the database */
+       void *map_ptr; /* where it is currently mapped */
+       int fd; /* open file descriptor for the database */
+       tdb_len_t map_size; /* how much space has been mapped */
+       int read_only; /* opened read-only */
+       int traverse_read; /* read-only traversal */
+       int traverse_write; /* read-write traversal */
+       struct tdb_lock_type global_lock;
+       int num_lockrecs;
+       struct tdb_lock_type *lockrecs; /* only real locks, all with count>0 */
+       enum TDB_ERROR ecode; /* error code for last tdb error */
+       struct tdb_header header; /* a cached copy of the header */
+       uint32_t flags; /* the flags passed to tdb_open */
+       struct tdb_traverse_lock travlocks; /* current traversal locks */
+       struct tdb_context *next; /* all tdbs to avoid multiple opens */
+       dev_t device;   /* uniquely identifies this tdb */
+       ino_t inode;    /* uniquely identifies this tdb */
+       struct tdb_logging_context log;
+       unsigned int (*hash_fn)(TDB_DATA *key);
+       int open_flags; /* flags used in the open - needed by reopen */
+       unsigned int num_locks; /* number of chain locks held */
+       const struct tdb_methods *methods;
+       struct tdb_transaction *transaction;
+       int page_size;
+       int max_dead_records;
+       int transaction_lock_count;
+#ifdef TDB_TRACE
+       int tracefd;
+#endif
+       volatile sig_atomic_t *interrupt_sig_ptr;
+};
+
+
+/*
+  internal prototypes
+*/
+int tdb_munmap(struct tdb_context *tdb);
+void tdb_mmap(struct tdb_context *tdb);
+int tdb_lock(struct tdb_context *tdb, int list, int ltype);
+int tdb_lock_nonblock(struct tdb_context *tdb, int list, int ltype);
+int tdb_unlock(struct tdb_context *tdb, int list, int ltype);
+int tdb_brlock(struct tdb_context *tdb, tdb_off_t offset, int rw_type, int lck_type, int probe, size_t len);
+int tdb_transaction_lock(struct tdb_context *tdb, int ltype);
+int tdb_transaction_unlock(struct tdb_context *tdb);
+int tdb_brlock_upgrade(struct tdb_context *tdb, tdb_off_t offset, size_t len);
+int tdb_write_lock_record(struct tdb_context *tdb, tdb_off_t off);
+int tdb_write_unlock_record(struct tdb_context *tdb, tdb_off_t off);
+int tdb_ofs_read(struct tdb_context *tdb, tdb_off_t offset, tdb_off_t *d);
+int tdb_ofs_write(struct tdb_context *tdb, tdb_off_t offset, tdb_off_t *d);
+void *tdb_convert(void *buf, uint32_t size);
+int tdb_free(struct tdb_context *tdb, tdb_off_t offset, struct tdb_record *rec);
+tdb_off_t tdb_allocate(struct tdb_context *tdb, tdb_len_t length, struct tdb_record *rec);
+int tdb_ofs_read(struct tdb_context *tdb, tdb_off_t offset, tdb_off_t *d);
+int tdb_ofs_write(struct tdb_context *tdb, tdb_off_t offset, tdb_off_t *d);
+int tdb_lock_record(struct tdb_context *tdb, tdb_off_t off);
+int tdb_unlock_record(struct tdb_context *tdb, tdb_off_t off);
+int _tdb_transaction_cancel(struct tdb_context *tdb);
+int tdb_rec_read(struct tdb_context *tdb, tdb_off_t offset, struct tdb_record *rec);
+int tdb_rec_write(struct tdb_context *tdb, tdb_off_t offset, struct tdb_record *rec);
+int tdb_do_delete(struct tdb_context *tdb, tdb_off_t rec_ptr, struct tdb_record *rec);
+unsigned char *tdb_alloc_read(struct tdb_context *tdb, tdb_off_t offset, tdb_len_t len);
+int tdb_parse_data(struct tdb_context *tdb, TDB_DATA key,
+                  tdb_off_t offset, tdb_len_t len,
+                  int (*parser)(TDB_DATA key, TDB_DATA data,
+                                void *private_data),
+                  void *private_data);
+tdb_off_t tdb_find_lock_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash, int locktype,
+                          struct tdb_record *rec);
+void tdb_io_init(struct tdb_context *tdb);
+int tdb_expand(struct tdb_context *tdb, tdb_off_t size);
+int tdb_rec_free_read(struct tdb_context *tdb, tdb_off_t off,
+                     struct tdb_record *rec);
+
+
diff --git a/libatalk/tdb/transaction.c b/libatalk/tdb/transaction.c
new file mode 100644 (file)
index 0000000..b8988ea
--- /dev/null
@@ -0,0 +1,1236 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              2005
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb_private.h"
+
+/*
+  transaction design:
+
+  - only allow a single transaction at a time per database. This makes
+    using the transaction API simpler, as otherwise the caller would
+    have to cope with temporary failures in transactions that conflict
+    with other current transactions
+
+  - keep the transaction recovery information in the same file as the
+    database, using a special 'transaction recovery' record pointed at
+    by the header. This removes the need for extra journal files as
+    used by some other databases
+
+  - dynamically allocated the transaction recover record, re-using it
+    for subsequent transactions. If a larger record is needed then
+    tdb_free() the old record to place it on the normal tdb freelist
+    before allocating the new record
+
+  - during transactions, keep a linked list of writes all that have
+    been performed by intercepting all tdb_write() calls. The hooked
+    transaction versions of tdb_read() and tdb_write() check this
+    linked list and try to use the elements of the list in preference
+    to the real database.
+
+  - don't allow any locks to be held when a transaction starts,
+    otherwise we can end up with deadlock (plus lack of lock nesting
+    in posix locks would mean the lock is lost)
+
+  - if the caller gains a lock during the transaction but doesn't
+    release it then fail the commit
+
+  - allow for nested calls to tdb_transaction_start(), re-using the
+    existing transaction record. If the inner transaction is cancelled
+    then a subsequent commit will fail
+  - keep a mirrored copy of the tdb hash chain heads to allow for the
+    fast hash heads scan on traverse, updating the mirrored copy in
+    the transaction version of tdb_write
+
+  - allow callers to mix transaction and non-transaction use of tdb,
+    although once a transaction is started then an exclusive lock is
+    gained until the transaction is committed or cancelled
+
+  - the commit stategy involves first saving away all modified data
+    into a linearised buffer in the transaction recovery area, then
+    marking the transaction recovery area with a magic value to
+    indicate a valid recovery record. In total 4 fsync/msync calls are
+    needed per commit to prevent race conditions. It might be possible
+    to reduce this to 3 or even 2 with some more work.
+
+  - check for a valid recovery record on open of the tdb, while the
+    global lock is held. Automatically recover from the transaction
+    recovery area if needed, then continue with the open as
+    usual. This allows for smooth crash recovery with no administrator
+    intervention.
+
+  - if TDB_NOSYNC is passed to flags in tdb_open then transactions are
+    still available, but no transaction recovery area is used and no
+    fsync/msync calls are made.
+
+  - if TDB_ALLOW_NESTING is passed to flags in tdb open, or added using
+    tdb_add_flags() transaction nesting is enabled.
+    It resets the TDB_DISALLOW_NESTING flag, as both cannot be used together.
+    The default is that transaction nesting is allowed.
+    Note: this default may change in future versions of tdb.
+
+    Beware. when transactions are nested a transaction successfully
+    completed with tdb_transaction_commit() can be silently unrolled later.
+
+  - if TDB_DISALLOW_NESTING is passed to flags in tdb open, or added using
+    tdb_add_flags() transaction nesting is disabled.
+    It resets the TDB_ALLOW_NESTING flag, as both cannot be used together.
+    An attempt create a nested transaction will fail with TDB_ERR_NESTING.
+    The default is that transaction nesting is allowed.
+    Note: this default may change in future versions of tdb.
+*/
+
+
+/*
+  hold the context of any current transaction
+*/
+struct tdb_transaction {
+       /* we keep a mirrored copy of the tdb hash heads here so
+          tdb_next_hash_chain() can operate efficiently */
+       uint32_t *hash_heads;
+
+       /* the original io methods - used to do IOs to the real db */
+       const struct tdb_methods *io_methods;
+
+       /* the list of transaction blocks. When a block is first
+          written to, it gets created in this list */
+       uint8_t **blocks;
+       uint32_t num_blocks;
+       uint32_t block_size;      /* bytes in each block */
+       uint32_t last_block_size; /* number of valid bytes in the last block */
+
+       /* non-zero when an internal transaction error has
+          occurred. All write operations will then fail until the
+          transaction is ended */
+       int transaction_error;
+
+       /* when inside a transaction we need to keep track of any
+          nested tdb_transaction_start() calls, as these are allowed,
+          but don't create a new transaction */
+       int nesting;
+
+       /* set when a prepare has already occurred */
+       bool prepared;
+       tdb_off_t magic_offset;
+
+       /* set when the GLOBAL_LOCK has been taken */
+       bool global_lock_taken;
+
+       /* old file size before transaction */
+       tdb_len_t old_map_size;
+
+       /* we should re-pack on commit */
+       bool need_repack;
+};
+
+
+/*
+  read while in a transaction. We need to check first if the data is in our list
+  of transaction elements, then if not do a real read
+*/
+static int transaction_read(struct tdb_context *tdb, tdb_off_t off, void *buf, 
+                           tdb_len_t len, int cv)
+{
+       uint32_t blk;
+
+       /* break it down into block sized ops */
+       while (len + (off % tdb->transaction->block_size) > tdb->transaction->block_size) {
+               tdb_len_t len2 = tdb->transaction->block_size - (off % tdb->transaction->block_size);
+               if (transaction_read(tdb, off, buf, len2, cv) != 0) {
+                       return -1;
+               }
+               len -= len2;
+               off += len2;
+               buf = (void *)(len2 + (char *)buf);
+       }
+
+       if (len == 0) {
+               return 0;
+       }
+
+       blk = off / tdb->transaction->block_size;
+
+       /* see if we have it in the block list */
+       if (tdb->transaction->num_blocks <= blk ||
+           tdb->transaction->blocks[blk] == NULL) {
+               /* nope, do a real read */
+               if (tdb->transaction->io_methods->tdb_read(tdb, off, buf, len, cv) != 0) {
+                       goto fail;
+               }
+               return 0;
+       }
+
+       /* it is in the block list. Now check for the last block */
+       if (blk == tdb->transaction->num_blocks-1) {
+               if (len > tdb->transaction->last_block_size) {
+                       goto fail;
+               }
+       }
+       
+       /* now copy it out of this block */
+       memcpy(buf, tdb->transaction->blocks[blk] + (off % tdb->transaction->block_size), len);
+       if (cv) {
+               tdb_convert(buf, len);
+       }
+       return 0;
+
+fail:
+       TDB_LOG((tdb, TDB_DEBUG_FATAL, "transaction_read: failed at off=%d len=%d\n", off, len));
+       tdb->ecode = TDB_ERR_IO;
+       tdb->transaction->transaction_error = 1;
+       return -1;
+}
+
+
+/*
+  write while in a transaction
+*/
+static int transaction_write(struct tdb_context *tdb, tdb_off_t off, 
+                            const void *buf, tdb_len_t len)
+{
+       uint32_t blk;
+
+       /* Only a commit is allowed on a prepared transaction */
+       if (tdb->transaction->prepared) {
+               tdb->ecode = TDB_ERR_EINVAL;
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "transaction_write: transaction already prepared, write not allowed\n"));
+               tdb->transaction->transaction_error = 1;
+               return -1;
+       }
+
+       /* if the write is to a hash head, then update the transaction
+          hash heads */
+       if (len == sizeof(tdb_off_t) && off >= FREELIST_TOP &&
+           off < FREELIST_TOP+TDB_HASHTABLE_SIZE(tdb)) {
+               uint32_t chain = (off-FREELIST_TOP) / sizeof(tdb_off_t);
+               memcpy(&tdb->transaction->hash_heads[chain], buf, len);
+       }
+
+       /* break it up into block sized chunks */
+       while (len + (off % tdb->transaction->block_size) > tdb->transaction->block_size) {
+               tdb_len_t len2 = tdb->transaction->block_size - (off % tdb->transaction->block_size);
+               if (transaction_write(tdb, off, buf, len2) != 0) {
+                       return -1;
+               }
+               len -= len2;
+               off += len2;
+               if (buf != NULL) {
+                       buf = (const void *)(len2 + (const char *)buf);
+               }
+       }
+
+       if (len == 0) {
+               return 0;
+       }
+
+       blk = off / tdb->transaction->block_size;
+       off = off % tdb->transaction->block_size;
+
+       if (tdb->transaction->num_blocks <= blk) {
+               uint8_t **new_blocks;
+               /* expand the blocks array */
+               if (tdb->transaction->blocks == NULL) {
+                       new_blocks = (uint8_t **)malloc(
+                               (blk+1)*sizeof(uint8_t *));
+               } else {
+                       new_blocks = (uint8_t **)realloc(
+                               tdb->transaction->blocks,
+                               (blk+1)*sizeof(uint8_t *));
+               }
+               if (new_blocks == NULL) {
+                       tdb->ecode = TDB_ERR_OOM;
+                       goto fail;
+               }
+               memset(&new_blocks[tdb->transaction->num_blocks], 0, 
+                      (1+(blk - tdb->transaction->num_blocks))*sizeof(uint8_t *));
+               tdb->transaction->blocks = new_blocks;
+               tdb->transaction->num_blocks = blk+1;
+               tdb->transaction->last_block_size = 0;
+       }
+
+       /* allocate and fill a block? */
+       if (tdb->transaction->blocks[blk] == NULL) {
+               tdb->transaction->blocks[blk] = (uint8_t *)calloc(tdb->transaction->block_size, 1);
+               if (tdb->transaction->blocks[blk] == NULL) {
+                       tdb->ecode = TDB_ERR_OOM;
+                       tdb->transaction->transaction_error = 1;
+                       return -1;                      
+               }
+               if (tdb->transaction->old_map_size > blk * tdb->transaction->block_size) {
+                       tdb_len_t len2 = tdb->transaction->block_size;
+                       if (len2 + (blk * tdb->transaction->block_size) > tdb->transaction->old_map_size) {
+                               len2 = tdb->transaction->old_map_size - (blk * tdb->transaction->block_size);
+                       }
+                       if (tdb->transaction->io_methods->tdb_read(tdb, blk * tdb->transaction->block_size, 
+                                                                  tdb->transaction->blocks[blk], 
+                                                                  len2, 0) != 0) {
+                               SAFE_FREE(tdb->transaction->blocks[blk]);                               
+                               tdb->ecode = TDB_ERR_IO;
+                               goto fail;
+                       }
+                       if (blk == tdb->transaction->num_blocks-1) {
+                               tdb->transaction->last_block_size = len2;
+                       }                       
+               }
+       }
+       
+       /* overwrite part of an existing block */
+       if (buf == NULL) {
+               memset(tdb->transaction->blocks[blk] + off, 0, len);
+       } else {
+               memcpy(tdb->transaction->blocks[blk] + off, buf, len);
+       }
+       if (blk == tdb->transaction->num_blocks-1) {
+               if (len + off > tdb->transaction->last_block_size) {
+                       tdb->transaction->last_block_size = len + off;
+               }
+       }
+
+       return 0;
+
+fail:
+       TDB_LOG((tdb, TDB_DEBUG_FATAL, "transaction_write: failed at off=%d len=%d\n", 
+                (blk*tdb->transaction->block_size) + off, len));
+       tdb->transaction->transaction_error = 1;
+       return -1;
+}
+
+
+/*
+  write while in a transaction - this varient never expands the transaction blocks, it only
+  updates existing blocks. This means it cannot change the recovery size
+*/
+static int transaction_write_existing(struct tdb_context *tdb, tdb_off_t off, 
+                                     const void *buf, tdb_len_t len)
+{
+       uint32_t blk;
+
+       /* break it up into block sized chunks */
+       while (len + (off % tdb->transaction->block_size) > tdb->transaction->block_size) {
+               tdb_len_t len2 = tdb->transaction->block_size - (off % tdb->transaction->block_size);
+               if (transaction_write_existing(tdb, off, buf, len2) != 0) {
+                       return -1;
+               }
+               len -= len2;
+               off += len2;
+               if (buf != NULL) {
+                       buf = (const void *)(len2 + (const char *)buf);
+               }
+       }
+
+       if (len == 0) {
+               return 0;
+       }
+
+       blk = off / tdb->transaction->block_size;
+       off = off % tdb->transaction->block_size;
+
+       if (tdb->transaction->num_blocks <= blk ||
+           tdb->transaction->blocks[blk] == NULL) {
+               return 0;
+       }
+
+       if (blk == tdb->transaction->num_blocks-1 &&
+           off + len > tdb->transaction->last_block_size) {
+               if (off >= tdb->transaction->last_block_size) {
+                       return 0;
+               }
+               len = tdb->transaction->last_block_size - off;
+       }
+
+       /* overwrite part of an existing block */
+       memcpy(tdb->transaction->blocks[blk] + off, buf, len);
+
+       return 0;
+}
+
+
+/*
+  accelerated hash chain head search, using the cached hash heads
+*/
+static void transaction_next_hash_chain(struct tdb_context *tdb, uint32_t *chain)
+{
+       uint32_t h = *chain;
+       for (;h < tdb->header.hash_size;h++) {
+               /* the +1 takes account of the freelist */
+               if (0 != tdb->transaction->hash_heads[h+1]) {
+                       break;
+               }
+       }
+       (*chain) = h;
+}
+
+/*
+  out of bounds check during a transaction
+*/
+static int transaction_oob(struct tdb_context *tdb, tdb_off_t len, int probe)
+{
+       if (len <= tdb->map_size) {
+               return 0;
+       }
+       tdb->ecode = TDB_ERR_IO;
+       return -1;
+}
+
+/*
+  transaction version of tdb_expand().
+*/
+static int transaction_expand_file(struct tdb_context *tdb, tdb_off_t size, 
+                                  tdb_off_t addition)
+{
+       /* add a write to the transaction elements, so subsequent
+          reads see the zero data */
+       if (transaction_write(tdb, size, NULL, addition) != 0) {
+               return -1;
+       }
+
+       tdb->transaction->need_repack = true;
+
+       return 0;
+}
+
+/*
+  brlock during a transaction - ignore them
+*/
+static int transaction_brlock(struct tdb_context *tdb, tdb_off_t offset, 
+                             int rw_type, int lck_type, int probe, size_t len)
+{
+       return 0;
+}
+
+static const struct tdb_methods transaction_methods = {
+       transaction_read,
+       transaction_write,
+       transaction_next_hash_chain,
+       transaction_oob,
+       transaction_expand_file,
+       transaction_brlock
+};
+
+
+/*
+  start a tdb transaction. No token is returned, as only a single
+  transaction is allowed to be pending per tdb_context
+*/
+int tdb_transaction_start(struct tdb_context *tdb)
+{
+       /* some sanity checks */
+       if (tdb->read_only || (tdb->flags & TDB_INTERNAL) || tdb->traverse_read) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_start: cannot start a transaction on a read-only or internal db\n"));
+               tdb->ecode = TDB_ERR_EINVAL;
+               return -1;
+       }
+
+       /* cope with nested tdb_transaction_start() calls */
+       if (tdb->transaction != NULL) {
+               if (!(tdb->flags & TDB_ALLOW_NESTING)) {
+                       tdb->ecode = TDB_ERR_NESTING;
+                       return -1;
+               }
+               tdb->transaction->nesting++;
+               TDB_LOG((tdb, TDB_DEBUG_TRACE, "tdb_transaction_start: nesting %d\n", 
+                        tdb->transaction->nesting));
+               return 0;
+       }
+
+       if (tdb->num_locks != 0 || tdb->global_lock.count) {
+               /* the caller must not have any locks when starting a
+                  transaction as otherwise we'll be screwed by lack
+                  of nested locks in posix */
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_start: cannot start a transaction with locks held\n"));
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->travlocks.next != NULL) {
+               /* you cannot use transactions inside a traverse (although you can use
+                  traverse inside a transaction) as otherwise you can end up with
+                  deadlock */
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_start: cannot start a transaction within a traverse\n"));
+               tdb->ecode = TDB_ERR_LOCK;
+               return -1;
+       }
+
+       tdb->transaction = (struct tdb_transaction *)
+               calloc(sizeof(struct tdb_transaction), 1);
+       if (tdb->transaction == NULL) {
+               tdb->ecode = TDB_ERR_OOM;
+               return -1;
+       }
+
+       /* a page at a time seems like a reasonable compromise between compactness and efficiency */
+       tdb->transaction->block_size = tdb->page_size;
+
+       /* get the transaction write lock. This is a blocking lock. As
+          discussed with Volker, there are a number of ways we could
+          make this async, which we will probably do in the future */
+       if (tdb_transaction_lock(tdb, F_WRLCK) == -1) {
+               SAFE_FREE(tdb->transaction->blocks);
+               SAFE_FREE(tdb->transaction);
+               return -1;
+       }
+       
+       /* get a read lock from the freelist to the end of file. This
+          is upgraded to a write lock during the commit */
+       if (tdb_brlock(tdb, FREELIST_TOP, F_RDLCK, F_SETLKW, 0, 0) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_start: failed to get hash locks\n"));
+               tdb->ecode = TDB_ERR_LOCK;
+               goto fail;
+       }
+
+       /* setup a copy of the hash table heads so the hash scan in
+          traverse can be fast */
+       tdb->transaction->hash_heads = (uint32_t *)
+               calloc(tdb->header.hash_size+1, sizeof(uint32_t));
+       if (tdb->transaction->hash_heads == NULL) {
+               tdb->ecode = TDB_ERR_OOM;
+               goto fail;
+       }
+       if (tdb->methods->tdb_read(tdb, FREELIST_TOP, tdb->transaction->hash_heads,
+                                  TDB_HASHTABLE_SIZE(tdb), 0) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_start: failed to read hash heads\n"));
+               tdb->ecode = TDB_ERR_IO;
+               goto fail;
+       }
+
+       /* make sure we know about any file expansions already done by
+          anyone else */
+       tdb->methods->tdb_oob(tdb, tdb->map_size + 1, 1);
+       tdb->transaction->old_map_size = tdb->map_size;
+
+       /* finally hook the io methods, replacing them with
+          transaction specific methods */
+       tdb->transaction->io_methods = tdb->methods;
+       tdb->methods = &transaction_methods;
+
+       /* Trace at the end, so we get sequence number correct. */
+       tdb_trace(tdb, "tdb_transaction_start");
+       return 0;
+       
+fail:
+       tdb_brlock(tdb, FREELIST_TOP, F_UNLCK, F_SETLKW, 0, 0);
+       tdb_transaction_unlock(tdb);
+       SAFE_FREE(tdb->transaction->blocks);
+       SAFE_FREE(tdb->transaction->hash_heads);
+       SAFE_FREE(tdb->transaction);
+       return -1;
+}
+
+
+/*
+  sync to disk
+*/
+static int transaction_sync(struct tdb_context *tdb, tdb_off_t offset, tdb_len_t length)
+{      
+       if (tdb->flags & TDB_NOSYNC) {
+               return 0;
+       }
+
+       if (fsync(tdb->fd) != 0) {
+               tdb->ecode = TDB_ERR_IO;
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction: fsync failed\n"));
+               return -1;
+       }
+#ifdef HAVE_MMAP
+       if (tdb->map_ptr) {
+               tdb_off_t moffset = offset & ~(tdb->page_size-1);
+               if (msync(moffset + (char *)tdb->map_ptr, 
+                         length + (offset - moffset), MS_SYNC) != 0) {
+                       tdb->ecode = TDB_ERR_IO;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction: msync failed - %s\n",
+                                strerror(errno)));
+                       return -1;
+               }
+       }
+#endif
+       return 0;
+}
+
+
+int _tdb_transaction_cancel(struct tdb_context *tdb)
+{      
+       int i, ret = 0;
+
+       if (tdb->transaction == NULL) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_cancel: no transaction\n"));
+               return -1;
+       }
+
+       if (tdb->transaction->nesting != 0) {
+               tdb->transaction->transaction_error = 1;
+               tdb->transaction->nesting--;
+               return 0;
+       }               
+
+       tdb->map_size = tdb->transaction->old_map_size;
+
+       /* free all the transaction blocks */
+       for (i=0;i<tdb->transaction->num_blocks;i++) {
+               if (tdb->transaction->blocks[i] != NULL) {
+                       free(tdb->transaction->blocks[i]);
+               }
+       }
+       SAFE_FREE(tdb->transaction->blocks);
+
+       if (tdb->transaction->magic_offset) {
+               const struct tdb_methods *methods = tdb->transaction->io_methods;
+               uint32_t zero = 0;
+
+               /* remove the recovery marker */
+               if (methods->tdb_write(tdb, tdb->transaction->magic_offset, &zero, 4) == -1 ||
+               transaction_sync(tdb, tdb->transaction->magic_offset, 4) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_cancel: failed to remove recovery magic\n"));
+                       ret = -1;
+               }
+       }
+
+       if (tdb->transaction->global_lock_taken) {
+               tdb_brlock(tdb, GLOBAL_LOCK, F_UNLCK, F_SETLKW, 0, 1);
+               tdb->transaction->global_lock_taken = false;
+       }
+
+       /* remove any global lock created during the transaction */
+       if (tdb->global_lock.count != 0) {
+               tdb_brlock(tdb, FREELIST_TOP, F_UNLCK, F_SETLKW, 0, 4*tdb->header.hash_size);
+               tdb->global_lock.count = 0;
+       }
+
+       /* remove any locks created during the transaction */
+       if (tdb->num_locks != 0) {
+               for (i=0;i<tdb->num_lockrecs;i++) {
+                       tdb_brlock(tdb,FREELIST_TOP+4*tdb->lockrecs[i].list,
+                                  F_UNLCK,F_SETLKW, 0, 1);
+               }
+               tdb->num_locks = 0;
+               tdb->num_lockrecs = 0;
+               SAFE_FREE(tdb->lockrecs);
+       }
+
+       /* restore the normal io methods */
+       tdb->methods = tdb->transaction->io_methods;
+
+       tdb_brlock(tdb, FREELIST_TOP, F_UNLCK, F_SETLKW, 0, 0);
+       tdb_transaction_unlock(tdb);
+       SAFE_FREE(tdb->transaction->hash_heads);
+       SAFE_FREE(tdb->transaction);
+       
+       return ret;
+}
+
+/*
+  cancel the current transaction
+*/
+int tdb_transaction_cancel(struct tdb_context *tdb)
+{
+       tdb_trace(tdb, "tdb_transaction_cancel");
+       return _tdb_transaction_cancel(tdb);
+}
+
+/*
+  work out how much space the linearised recovery data will consume
+*/
+static tdb_len_t tdb_recovery_size(struct tdb_context *tdb)
+{
+       tdb_len_t recovery_size = 0;
+       int i;
+
+       recovery_size = sizeof(uint32_t);
+       for (i=0;i<tdb->transaction->num_blocks;i++) {
+               if (i * tdb->transaction->block_size >= tdb->transaction->old_map_size) {
+                       break;
+               }
+               if (tdb->transaction->blocks[i] == NULL) {
+                       continue;
+               }
+               recovery_size += 2*sizeof(tdb_off_t);
+               if (i == tdb->transaction->num_blocks-1) {
+                       recovery_size += tdb->transaction->last_block_size;
+               } else {
+                       recovery_size += tdb->transaction->block_size;
+               }
+       }       
+
+       return recovery_size;
+}
+
+/*
+  allocate the recovery area, or use an existing recovery area if it is
+  large enough
+*/
+static int tdb_recovery_allocate(struct tdb_context *tdb, 
+                                tdb_len_t *recovery_size,
+                                tdb_off_t *recovery_offset,
+                                tdb_len_t *recovery_max_size)
+{
+       struct tdb_record rec;
+       const struct tdb_methods *methods = tdb->transaction->io_methods;
+       tdb_off_t recovery_head;
+
+       if (tdb_ofs_read(tdb, TDB_RECOVERY_HEAD, &recovery_head) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_recovery_allocate: failed to read recovery head\n"));
+               return -1;
+       }
+
+       rec.rec_len = 0;
+
+       if (recovery_head != 0 && 
+           methods->tdb_read(tdb, recovery_head, &rec, sizeof(rec), DOCONV()) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_recovery_allocate: failed to read recovery record\n"));
+               return -1;
+       }
+
+       *recovery_size = tdb_recovery_size(tdb);
+
+       if (recovery_head != 0 && *recovery_size <= rec.rec_len) {
+               /* it fits in the existing area */
+               *recovery_max_size = rec.rec_len;
+               *recovery_offset = recovery_head;
+               return 0;
+       }
+
+       /* we need to free up the old recovery area, then allocate a
+          new one at the end of the file. Note that we cannot use
+          tdb_allocate() to allocate the new one as that might return
+          us an area that is being currently used (as of the start of
+          the transaction) */
+       if (recovery_head != 0) {
+               if (tdb_free(tdb, recovery_head, &rec) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_recovery_allocate: failed to free previous recovery area\n"));
+                       return -1;
+               }
+       }
+
+       /* the tdb_free() call might have increased the recovery size */
+       *recovery_size = tdb_recovery_size(tdb);
+
+       /* round up to a multiple of page size */
+       *recovery_max_size = TDB_ALIGN(sizeof(rec) + *recovery_size, tdb->page_size) - sizeof(rec);
+       *recovery_offset = tdb->map_size;
+       recovery_head = *recovery_offset;
+
+       if (methods->tdb_expand_file(tdb, tdb->transaction->old_map_size, 
+                                    (tdb->map_size - tdb->transaction->old_map_size) +
+                                    sizeof(rec) + *recovery_max_size) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_recovery_allocate: failed to create recovery area\n"));
+               return -1;
+       }
+
+       /* remap the file (if using mmap) */
+       methods->tdb_oob(tdb, tdb->map_size + 1, 1);
+
+       /* we have to reset the old map size so that we don't try to expand the file
+          again in the transaction commit, which would destroy the recovery area */
+       tdb->transaction->old_map_size = tdb->map_size;
+
+       /* write the recovery header offset and sync - we can sync without a race here
+          as the magic ptr in the recovery record has not been set */
+       CONVERT(recovery_head);
+       if (methods->tdb_write(tdb, TDB_RECOVERY_HEAD, 
+                              &recovery_head, sizeof(tdb_off_t)) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_recovery_allocate: failed to write recovery head\n"));
+               return -1;
+       }
+       if (transaction_write_existing(tdb, TDB_RECOVERY_HEAD, &recovery_head, sizeof(tdb_off_t)) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_recovery_allocate: failed to write recovery head\n"));
+               return -1;
+       }
+
+       return 0;
+}
+
+
+/*
+  setup the recovery data that will be used on a crash during commit
+*/
+static int transaction_setup_recovery(struct tdb_context *tdb, 
+                                     tdb_off_t *magic_offset)
+{
+       tdb_len_t recovery_size;
+       unsigned char *data, *p;
+       const struct tdb_methods *methods = tdb->transaction->io_methods;
+       struct tdb_record *rec;
+       tdb_off_t recovery_offset, recovery_max_size;
+       tdb_off_t old_map_size = tdb->transaction->old_map_size;
+       uint32_t magic, tailer;
+       int i;
+
+       /*
+         check that the recovery area has enough space
+       */
+       if (tdb_recovery_allocate(tdb, &recovery_size, 
+                                 &recovery_offset, &recovery_max_size) == -1) {
+               return -1;
+       }
+
+       data = (unsigned char *)malloc(recovery_size + sizeof(*rec));
+       if (data == NULL) {
+               tdb->ecode = TDB_ERR_OOM;
+               return -1;
+       }
+
+       rec = (struct tdb_record *)data;
+       memset(rec, 0, sizeof(*rec));
+
+       rec->magic    = 0;
+       rec->data_len = recovery_size;
+       rec->rec_len  = recovery_max_size;
+       rec->key_len  = old_map_size;
+       CONVERT(rec);
+
+       /* build the recovery data into a single blob to allow us to do a single
+          large write, which should be more efficient */
+       p = data + sizeof(*rec);
+       for (i=0;i<tdb->transaction->num_blocks;i++) {
+               tdb_off_t offset;
+               tdb_len_t length;
+
+               if (tdb->transaction->blocks[i] == NULL) {
+                       continue;
+               }
+
+               offset = i * tdb->transaction->block_size;
+               length = tdb->transaction->block_size;
+               if (i == tdb->transaction->num_blocks-1) {
+                       length = tdb->transaction->last_block_size;
+               }
+               
+               if (offset >= old_map_size) {
+                       continue;
+               }
+               if (offset + length > tdb->transaction->old_map_size) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_setup_recovery: transaction data over new region boundary\n"));
+                       free(data);
+                       tdb->ecode = TDB_ERR_CORRUPT;
+                       return -1;
+               }
+               memcpy(p, &offset, 4);
+               memcpy(p+4, &length, 4);
+               if (DOCONV()) {
+                       tdb_convert(p, 8);
+               }
+               /* the recovery area contains the old data, not the
+                  new data, so we have to call the original tdb_read
+                  method to get it */
+               if (methods->tdb_read(tdb, offset, p + 8, length, 0) != 0) {
+                       free(data);
+                       tdb->ecode = TDB_ERR_IO;
+                       return -1;
+               }
+               p += 8 + length;
+       }
+
+       /* and the tailer */
+       tailer = sizeof(*rec) + recovery_max_size;
+       memcpy(p, &tailer, 4);
+       CONVERT(p);
+
+       /* write the recovery data to the recovery area */
+       if (methods->tdb_write(tdb, recovery_offset, data, sizeof(*rec) + recovery_size) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_setup_recovery: failed to write recovery data\n"));
+               free(data);
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+       if (transaction_write_existing(tdb, recovery_offset, data, sizeof(*rec) + recovery_size) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_setup_recovery: failed to write secondary recovery data\n"));
+               free(data);
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+
+       /* as we don't have ordered writes, we have to sync the recovery
+          data before we update the magic to indicate that the recovery
+          data is present */
+       if (transaction_sync(tdb, recovery_offset, sizeof(*rec) + recovery_size) == -1) {
+               free(data);
+               return -1;
+       }
+
+       free(data);
+
+       magic = TDB_RECOVERY_MAGIC;
+       CONVERT(magic);
+
+       *magic_offset = recovery_offset + offsetof(struct tdb_record, magic);
+
+       if (methods->tdb_write(tdb, *magic_offset, &magic, sizeof(magic)) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_setup_recovery: failed to write recovery magic\n"));
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+       if (transaction_write_existing(tdb, *magic_offset, &magic, sizeof(magic)) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_setup_recovery: failed to write secondary recovery magic\n"));
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+
+       /* ensure the recovery magic marker is on disk */
+       if (transaction_sync(tdb, *magic_offset, sizeof(magic)) == -1) {
+               return -1;
+       }
+
+       return 0;
+}
+
+static int _tdb_transaction_prepare_commit(struct tdb_context *tdb)
+{      
+       const struct tdb_methods *methods;
+
+       if (tdb->transaction == NULL) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_prepare_commit: no transaction\n"));
+               return -1;
+       }
+
+       if (tdb->transaction->prepared) {
+               tdb->ecode = TDB_ERR_EINVAL;
+               _tdb_transaction_cancel(tdb);
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_prepare_commit: transaction already prepared\n"));
+               return -1;
+       }
+
+       if (tdb->transaction->transaction_error) {
+               tdb->ecode = TDB_ERR_IO;
+               _tdb_transaction_cancel(tdb);
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_prepare_commit: transaction error pending\n"));
+               return -1;
+       }
+
+
+       if (tdb->transaction->nesting != 0) {
+               return 0;
+       }               
+
+       /* check for a null transaction */
+       if (tdb->transaction->blocks == NULL) {
+               return 0;
+       }
+
+       methods = tdb->transaction->io_methods;
+       
+       /* if there are any locks pending then the caller has not
+          nested their locks properly, so fail the transaction */
+       if (tdb->num_locks || tdb->global_lock.count) {
+               tdb->ecode = TDB_ERR_LOCK;
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_prepare_commit: locks pending on commit\n"));
+               _tdb_transaction_cancel(tdb);
+               return -1;
+       }
+
+       /* upgrade the main transaction lock region to a write lock */
+       if (tdb_brlock_upgrade(tdb, FREELIST_TOP, 0) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_prepare_commit: failed to upgrade hash locks\n"));
+               tdb->ecode = TDB_ERR_LOCK;
+               _tdb_transaction_cancel(tdb);
+               return -1;
+       }
+
+       /* get the global lock - this prevents new users attaching to the database
+          during the commit */
+       if (tdb_brlock(tdb, GLOBAL_LOCK, F_WRLCK, F_SETLKW, 0, 1) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_prepare_commit: failed to get global lock\n"));
+               tdb->ecode = TDB_ERR_LOCK;
+               _tdb_transaction_cancel(tdb);
+               return -1;
+       }
+
+       tdb->transaction->global_lock_taken = true;
+
+       if (!(tdb->flags & TDB_NOSYNC)) {
+               /* write the recovery data to the end of the file */
+               if (transaction_setup_recovery(tdb, &tdb->transaction->magic_offset) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_prepare_commit: failed to setup recovery data\n"));
+                       _tdb_transaction_cancel(tdb);
+                       return -1;
+               }
+       }
+
+       tdb->transaction->prepared = true;
+
+       /* expand the file to the new size if needed */
+       if (tdb->map_size != tdb->transaction->old_map_size) {
+               if (methods->tdb_expand_file(tdb, tdb->transaction->old_map_size, 
+                                            tdb->map_size - 
+                                            tdb->transaction->old_map_size) == -1) {
+                       tdb->ecode = TDB_ERR_IO;
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_prepare_commit: expansion failed\n"));
+                       _tdb_transaction_cancel(tdb);
+                       return -1;
+               }
+               tdb->map_size = tdb->transaction->old_map_size;
+               methods->tdb_oob(tdb, tdb->map_size + 1, 1);
+       }
+
+       /* Keep the global lock until the actual commit */
+
+       return 0;
+}
+
+/*
+   prepare to commit the current transaction
+*/
+int tdb_transaction_prepare_commit(struct tdb_context *tdb)
+{      
+       tdb_trace(tdb, "tdb_transaction_prepare_commit");
+       return _tdb_transaction_prepare_commit(tdb);
+}
+
+/*
+  commit the current transaction
+*/
+int tdb_transaction_commit(struct tdb_context *tdb)
+{      
+       const struct tdb_methods *methods;
+       int i;
+       bool need_repack;
+
+       if (tdb->transaction == NULL) {
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_commit: no transaction\n"));
+               return -1;
+       }
+
+       tdb_trace(tdb, "tdb_transaction_commit");
+
+       if (tdb->transaction->transaction_error) {
+               tdb->ecode = TDB_ERR_IO;
+               _tdb_transaction_cancel(tdb);
+               TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_commit: transaction error pending\n"));
+               return -1;
+       }
+
+
+       if (tdb->transaction->nesting != 0) {
+               tdb->transaction->nesting--;
+               return 0;
+       }
+
+       /* check for a null transaction */
+       if (tdb->transaction->blocks == NULL) {
+               _tdb_transaction_cancel(tdb);
+               return 0;
+       }
+
+       if (!tdb->transaction->prepared) {
+               int ret = _tdb_transaction_prepare_commit(tdb);
+               if (ret)
+                       return ret;
+       }
+
+       methods = tdb->transaction->io_methods;
+
+       /* perform all the writes */
+       for (i=0;i<tdb->transaction->num_blocks;i++) {
+               tdb_off_t offset;
+               tdb_len_t length;
+
+               if (tdb->transaction->blocks[i] == NULL) {
+                       continue;
+               }
+
+               offset = i * tdb->transaction->block_size;
+               length = tdb->transaction->block_size;
+               if (i == tdb->transaction->num_blocks-1) {
+                       length = tdb->transaction->last_block_size;
+               }
+
+               if (methods->tdb_write(tdb, offset, tdb->transaction->blocks[i], length) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_commit: write failed during commit\n"));
+                       
+                       /* we've overwritten part of the data and
+                          possibly expanded the file, so we need to
+                          run the crash recovery code */
+                       tdb->methods = methods;
+                       tdb_transaction_recover(tdb); 
+
+                       _tdb_transaction_cancel(tdb);
+
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_commit: write failed\n"));
+                       return -1;
+               }
+               SAFE_FREE(tdb->transaction->blocks[i]);
+       } 
+
+       SAFE_FREE(tdb->transaction->blocks);
+       tdb->transaction->num_blocks = 0;
+
+       /* ensure the new data is on disk */
+       if (transaction_sync(tdb, 0, tdb->map_size) == -1) {
+               return -1;
+       }
+
+       /*
+         TODO: maybe write to some dummy hdr field, or write to magic
+         offset without mmap, before the last sync, instead of the
+         utime() call
+       */
+
+       /* on some systems (like Linux 2.6.x) changes via mmap/msync
+          don't change the mtime of the file, this means the file may
+          not be backed up (as tdb rounding to block sizes means that
+          file size changes are quite rare too). The following forces
+          mtime changes when a transaction completes */
+#ifdef HAVE_UTIME
+       utime(tdb->name, NULL);
+#endif
+
+       need_repack = tdb->transaction->need_repack;
+
+       /* use a transaction cancel to free memory and remove the
+          transaction locks */
+       _tdb_transaction_cancel(tdb);
+
+       if (need_repack) {
+               return tdb_repack(tdb);
+       }
+
+       return 0;
+}
+
+
+/*
+  recover from an aborted transaction. Must be called with exclusive
+  database write access already established (including the global
+  lock to prevent new processes attaching)
+*/
+int tdb_transaction_recover(struct tdb_context *tdb)
+{
+       tdb_off_t recovery_head, recovery_eof;
+       unsigned char *data, *p;
+       uint32_t zero = 0;
+       struct tdb_record rec;
+
+       /* find the recovery area */
+       if (tdb_ofs_read(tdb, TDB_RECOVERY_HEAD, &recovery_head) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to read recovery head\n"));
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+
+       if (recovery_head == 0) {
+               /* we have never allocated a recovery record */
+               return 0;
+       }
+
+       /* read the recovery record */
+       if (tdb->methods->tdb_read(tdb, recovery_head, &rec, 
+                                  sizeof(rec), DOCONV()) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to read recovery record\n"));           
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+
+       if (rec.magic != TDB_RECOVERY_MAGIC) {
+               /* there is no valid recovery data */
+               return 0;
+       }
+
+       if (tdb->read_only) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: attempt to recover read only database\n"));
+               tdb->ecode = TDB_ERR_CORRUPT;
+               return -1;
+       }
+
+       recovery_eof = rec.key_len;
+
+       data = (unsigned char *)malloc(rec.data_len);
+       if (data == NULL) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to allocate recovery data\n"));         
+               tdb->ecode = TDB_ERR_OOM;
+               return -1;
+       }
+
+       /* read the full recovery data */
+       if (tdb->methods->tdb_read(tdb, recovery_head + sizeof(rec), data,
+                                  rec.data_len, 0) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to read recovery data\n"));             
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+
+       /* recover the file data */
+       p = data;
+       while (p+8 < data + rec.data_len) {
+               uint32_t ofs, len;
+               if (DOCONV()) {
+                       tdb_convert(p, 8);
+               }
+               memcpy(&ofs, p, 4);
+               memcpy(&len, p+4, 4);
+
+               if (tdb->methods->tdb_write(tdb, ofs, p+8, len) == -1) {
+                       free(data);
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to recover %d bytes at offset %d\n", len, ofs));
+                       tdb->ecode = TDB_ERR_IO;
+                       return -1;
+               }
+               p += 8 + len;
+       }
+
+       free(data);
+
+       if (transaction_sync(tdb, 0, tdb->map_size) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to sync recovery\n"));
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+
+       /* if the recovery area is after the recovered eof then remove it */
+       if (recovery_eof <= recovery_head) {
+               if (tdb_ofs_write(tdb, TDB_RECOVERY_HEAD, &zero) == -1) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to remove recovery head\n"));
+                       tdb->ecode = TDB_ERR_IO;
+                       return -1;                      
+               }
+       }
+
+       /* remove the recovery magic */
+       if (tdb_ofs_write(tdb, recovery_head + offsetof(struct tdb_record, magic),
+                         &zero) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to remove recovery magic\n"));
+               tdb->ecode = TDB_ERR_IO;
+               return -1;                      
+       }
+       
+       /* reduce the file size to the old size */
+       tdb_munmap(tdb);
+       if (ftruncate(tdb->fd, recovery_eof) != 0) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to reduce to recovery size\n"));
+               tdb->ecode = TDB_ERR_IO;
+               return -1;                      
+       }
+       tdb->map_size = recovery_eof;
+       tdb_mmap(tdb);
+
+       if (transaction_sync(tdb, 0, recovery_eof) == -1) {
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_transaction_recover: failed to sync2 recovery\n"));
+               tdb->ecode = TDB_ERR_IO;
+               return -1;
+       }
+
+       TDB_LOG((tdb, TDB_DEBUG_TRACE, "tdb_transaction_recover: recovered %d byte database\n", 
+                recovery_eof));
+
+       /* all done */
+       return 0;
+}
diff --git a/libatalk/tdb/traverse.c b/libatalk/tdb/traverse.c
new file mode 100644 (file)
index 0000000..c340dd3
--- /dev/null
@@ -0,0 +1,366 @@
+ /* 
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+   
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+   
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb_private.h"
+
+#define TDB_NEXT_LOCK_ERR ((tdb_off_t)-1)
+
+/* Uses traverse lock: 0 = finish, TDB_NEXT_LOCK_ERR = error,
+   other = record offset */
+static tdb_off_t tdb_next_lock(struct tdb_context *tdb, struct tdb_traverse_lock *tlock,
+                        struct tdb_record *rec)
+{
+       int want_next = (tlock->off != 0);
+
+       /* Lock each chain from the start one. */
+       for (; tlock->hash < tdb->header.hash_size; tlock->hash++) {
+               if (!tlock->off && tlock->hash != 0) {
+                       /* this is an optimisation for the common case where
+                          the hash chain is empty, which is particularly
+                          common for the use of tdb with ldb, where large
+                          hashes are used. In that case we spend most of our
+                          time in tdb_brlock(), locking empty hash chains.
+                          
+                          To avoid this, we do an unlocked pre-check to see
+                          if the hash chain is empty before starting to look
+                          inside it. If it is empty then we can avoid that
+                          hash chain. If it isn't empty then we can't believe
+                          the value we get back, as we read it without a
+                          lock, so instead we get the lock and re-fetch the
+                          value below.
+                          
+                          Notice that not doing this optimisation on the
+                          first hash chain is critical. We must guarantee
+                          that we have done at least one fcntl lock at the
+                          start of a search to guarantee that memory is
+                          coherent on SMP systems. If records are added by
+                          others during the search then thats OK, and we
+                          could possibly miss those with this trick, but we
+                          could miss them anyway without this trick, so the
+                          semantics don't change.
+                          
+                          With a non-indexed ldb search this trick gains us a
+                          factor of around 80 in speed on a linux 2.6.x
+                          system (testing using ldbtest).
+                       */
+                       tdb->methods->next_hash_chain(tdb, &tlock->hash);
+                       if (tlock->hash == tdb->header.hash_size) {
+                               continue;
+                       }
+               }
+
+               if (tdb_lock(tdb, tlock->hash, tlock->lock_rw) == -1)
+                       return TDB_NEXT_LOCK_ERR;
+
+               /* No previous record?  Start at top of chain. */
+               if (!tlock->off) {
+                       if (tdb_ofs_read(tdb, TDB_HASH_TOP(tlock->hash),
+                                    &tlock->off) == -1)
+                               goto fail;
+               } else {
+                       /* Otherwise unlock the previous record. */
+                       if (tdb_unlock_record(tdb, tlock->off) != 0)
+                               goto fail;
+               }
+
+               if (want_next) {
+                       /* We have offset of old record: grab next */
+                       if (tdb_rec_read(tdb, tlock->off, rec) == -1)
+                               goto fail;
+                       tlock->off = rec->next;
+               }
+
+               /* Iterate through chain */
+               while( tlock->off) {
+                       tdb_off_t current;
+                       if (tdb_rec_read(tdb, tlock->off, rec) == -1)
+                               goto fail;
+
+                       /* Detect infinite loops. From "Shlomi Yaakobovich" <Shlomi@exanet.com>. */
+                       if (tlock->off == rec->next) {
+                               tdb->ecode = TDB_ERR_CORRUPT;
+                               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_next_lock: loop detected.\n"));
+                               goto fail;
+                       }
+
+                       if (!TDB_DEAD(rec)) {
+                               /* Woohoo: we found one! */
+                               if (tdb_lock_record(tdb, tlock->off) != 0)
+                                       goto fail;
+                               return tlock->off;
+                       }
+
+                       /* Try to clean dead ones from old traverses */
+                       current = tlock->off;
+                       tlock->off = rec->next;
+                       if (!(tdb->read_only || tdb->traverse_read) && 
+                           tdb_do_delete(tdb, current, rec) != 0)
+                               goto fail;
+               }
+               tdb_unlock(tdb, tlock->hash, tlock->lock_rw);
+               want_next = 0;
+       }
+       /* We finished iteration without finding anything */
+       tdb->ecode = TDB_SUCCESS;
+       return 0;
+
+ fail:
+       tlock->off = 0;
+       if (tdb_unlock(tdb, tlock->hash, tlock->lock_rw) != 0)
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_next_lock: On error unlock failed!\n"));
+       return TDB_NEXT_LOCK_ERR;
+}
+
+/* traverse the entire database - calling fn(tdb, key, data) on each element.
+   return -1 on error or the record count traversed
+   if fn is NULL then it is not called
+   a non-zero return value from fn() indicates that the traversal should stop
+  */
+static int tdb_traverse_internal(struct tdb_context *tdb, 
+                                tdb_traverse_func fn, void *private_data,
+                                struct tdb_traverse_lock *tl)
+{
+       TDB_DATA key, dbuf;
+       struct tdb_record rec;
+       int ret = 0, count = 0;
+       tdb_off_t off;
+
+       /* This was in the initializaton, above, but the IRIX compiler
+        * did not like it.  crh
+        */
+       tl->next = tdb->travlocks.next;
+
+       /* fcntl locks don't stack: beware traverse inside traverse */
+       tdb->travlocks.next = tl;
+
+       /* tdb_next_lock places locks on the record returned, and its chain */
+       while ((off = tdb_next_lock(tdb, tl, &rec)) != 0) {
+               if (off == TDB_NEXT_LOCK_ERR) {
+                       ret = -1;
+                       goto out;
+               }
+               count++;
+               /* now read the full record */
+               key.dptr = tdb_alloc_read(tdb, tl->off + sizeof(rec), 
+                                         rec.key_len + rec.data_len);
+               if (!key.dptr) {
+                       ret = -1;
+                       if (tdb_unlock(tdb, tl->hash, tl->lock_rw) != 0)
+                               goto out;
+                       if (tdb_unlock_record(tdb, tl->off) != 0)
+                               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_traverse: key.dptr == NULL and unlock_record failed!\n"));
+                       goto out;
+               }
+               key.dsize = rec.key_len;
+               dbuf.dptr = key.dptr + rec.key_len;
+               dbuf.dsize = rec.data_len;
+
+               tdb_trace_1rec_retrec(tdb, "traverse", key, dbuf);
+
+               /* Drop chain lock, call out */
+               if (tdb_unlock(tdb, tl->hash, tl->lock_rw) != 0) {
+                       ret = -1;
+                       SAFE_FREE(key.dptr);
+                       goto out;
+               }
+               if (fn && fn(tdb, key, dbuf, private_data)) {
+                       /* They want us to terminate traversal */
+                       tdb_trace_ret(tdb, "tdb_traverse_end", count);
+                       if (tdb_unlock_record(tdb, tl->off) != 0) {
+                               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_traverse: unlock_record failed!\n"));;
+                               ret = -1;
+                       }
+                       SAFE_FREE(key.dptr);
+                       goto out;
+               }
+               SAFE_FREE(key.dptr);
+       }
+       tdb_trace(tdb, "tdb_traverse_end");
+out:
+       tdb->travlocks.next = tl->next;
+       if (ret < 0)
+               return -1;
+       else
+               return count;
+}
+
+
+/*
+  a write style traverse - temporarily marks the db read only
+*/
+int tdb_traverse_read(struct tdb_context *tdb, 
+                     tdb_traverse_func fn, void *private_data)
+{
+       struct tdb_traverse_lock tl = { NULL, 0, 0, F_RDLCK };
+       int ret;
+
+       /* we need to get a read lock on the transaction lock here to
+          cope with the lock ordering semantics of solaris10 */
+       if (tdb_transaction_lock(tdb, F_RDLCK)) {
+               return -1;
+       }
+
+       tdb->traverse_read++;
+       tdb_trace(tdb, "tdb_traverse_read_start");
+       ret = tdb_traverse_internal(tdb, fn, private_data, &tl);
+       tdb->traverse_read--;
+
+       tdb_transaction_unlock(tdb);
+
+       return ret;
+}
+
+/*
+  a write style traverse - needs to get the transaction lock to
+  prevent deadlocks
+
+  WARNING: The data buffer given to the callback fn does NOT meet the
+  alignment restrictions malloc gives you.
+*/
+int tdb_traverse(struct tdb_context *tdb, 
+                tdb_traverse_func fn, void *private_data)
+{
+       struct tdb_traverse_lock tl = { NULL, 0, 0, F_WRLCK };
+       int ret;
+
+       if (tdb->read_only || tdb->traverse_read) {
+               return tdb_traverse_read(tdb, fn, private_data);
+       }
+
+       if (tdb_transaction_lock(tdb, F_WRLCK)) {
+               return -1;
+       }
+
+       tdb->traverse_write++;
+       tdb_trace(tdb, "tdb_traverse_start");
+       ret = tdb_traverse_internal(tdb, fn, private_data, &tl);
+       tdb->traverse_write--;
+
+       tdb_transaction_unlock(tdb);
+
+       return ret;
+}
+
+
+/* find the first entry in the database and return its key */
+TDB_DATA tdb_firstkey(struct tdb_context *tdb)
+{
+       TDB_DATA key;
+       struct tdb_record rec;
+       tdb_off_t off;
+
+       /* release any old lock */
+       if (tdb_unlock_record(tdb, tdb->travlocks.off) != 0)
+               return tdb_null;
+       tdb->travlocks.off = tdb->travlocks.hash = 0;
+       tdb->travlocks.lock_rw = F_RDLCK;
+
+       /* Grab first record: locks chain and returned record. */
+       off = tdb_next_lock(tdb, &tdb->travlocks, &rec);
+       if (off == 0 || off == TDB_NEXT_LOCK_ERR) {
+               tdb_trace_retrec(tdb, "tdb_firstkey", tdb_null);
+               return tdb_null;
+       }
+       /* now read the key */
+       key.dsize = rec.key_len;
+       key.dptr =tdb_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),key.dsize);
+
+       tdb_trace_retrec(tdb, "tdb_firstkey", key);
+
+       /* Unlock the hash chain of the record we just read. */
+       if (tdb_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0)
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_firstkey: error occurred while tdb_unlocking!\n"));
+       return key;
+}
+
+/* find the next entry in the database, returning its key */
+TDB_DATA tdb_nextkey(struct tdb_context *tdb, TDB_DATA oldkey)
+{
+       uint32_t oldhash;
+       TDB_DATA key = tdb_null;
+       struct tdb_record rec;
+       unsigned char *k = NULL;
+       tdb_off_t off;
+
+       /* Is locked key the old key?  If so, traverse will be reliable. */
+       if (tdb->travlocks.off) {
+               if (tdb_lock(tdb,tdb->travlocks.hash,tdb->travlocks.lock_rw))
+                       return tdb_null;
+               if (tdb_rec_read(tdb, tdb->travlocks.off, &rec) == -1
+                   || !(k = tdb_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),
+                                           rec.key_len))
+                   || memcmp(k, oldkey.dptr, oldkey.dsize) != 0) {
+                       /* No, it wasn't: unlock it and start from scratch */
+                       if (tdb_unlock_record(tdb, tdb->travlocks.off) != 0) {
+                               tdb_trace_1rec_retrec(tdb, "tdb_nextkey",
+                                                     oldkey, tdb_null);
+                               SAFE_FREE(k);
+                               return tdb_null;
+                       }
+                       if (tdb_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0) {
+                               SAFE_FREE(k);
+                               return tdb_null;
+                       }
+                       tdb->travlocks.off = 0;
+               }
+
+               SAFE_FREE(k);
+       }
+
+       if (!tdb->travlocks.off) {
+               /* No previous element: do normal find, and lock record */
+               tdb->travlocks.off = tdb_find_lock_hash(tdb, oldkey, tdb->hash_fn(&oldkey), tdb->travlocks.lock_rw, &rec);
+               if (!tdb->travlocks.off) {
+                       tdb_trace_1rec_retrec(tdb, "tdb_nextkey", oldkey, tdb_null);
+                       return tdb_null;
+               }
+               tdb->travlocks.hash = BUCKET(rec.full_hash);
+               if (tdb_lock_record(tdb, tdb->travlocks.off) != 0) {
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_nextkey: lock_record failed (%s)!\n", strerror(errno)));
+                       return tdb_null;
+               }
+       }
+       oldhash = tdb->travlocks.hash;
+
+       /* Grab next record: locks chain and returned record,
+          unlocks old record */
+       off = tdb_next_lock(tdb, &tdb->travlocks, &rec);
+       if (off != TDB_NEXT_LOCK_ERR && off != 0) {
+               key.dsize = rec.key_len;
+               key.dptr = tdb_alloc_read(tdb, tdb->travlocks.off+sizeof(rec),
+                                         key.dsize);
+               /* Unlock the chain of this new record */
+               if (tdb_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0)
+                       TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_nextkey: WARNING tdb_unlock failed!\n"));
+       }
+       /* Unlock the chain of old record */
+       if (tdb_unlock(tdb, BUCKET(oldhash), tdb->travlocks.lock_rw) != 0)
+               TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_nextkey: WARNING tdb_unlock failed!\n"));
+       tdb_trace_1rec_retrec(tdb, "tdb_nextkey", oldkey, key);
+       return key;
+}
+
index 3cf3dccf4b84c5a6f10ec5cc8a0095fa29039399..cc9a7f02a12bf580216e05fda91ec0c666b3c5f2 100644 (file)
@@ -20,7 +20,7 @@
 
 #ifndef _BYTEORDER_H
 #define _BYTEORDER_H
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 
 /*
    This file implements macros for machine independent short and 
@@ -122,8 +122,8 @@ it also defines lots of intermediate macros, just ignore those :-)
 #define SIVALX(buf,pos,val) (SSVALX(buf,pos,val&0xFFFF),SSVALX(buf,pos+2,val>>16))
 #define SVALS(buf,pos) ((int16)SVAL(buf,pos))
 #define IVALS(buf,pos) ((int32_t)IVAL(buf,pos))
-#define SSVAL(buf,pos,val) SSVALX((buf),(pos),((u_int16_t)(val)))
-#define SIVAL(buf,pos,val) SIVALX((buf),(pos),((u_int32_t)(val)))
+#define SSVAL(buf,pos,val) SSVALX((buf),(pos),((uint16_t)(val)))
+#define SIVAL(buf,pos,val) SIVALX((buf),(pos),((uint32_t)(val)))
 #define SSVALS(buf,pos,val) SSVALX((buf),(pos),((int16)(val)))
 #define SIVALS(buf,pos,val) SIVALX((buf),(pos),((int32_t)(val)))
 
@@ -135,8 +135,8 @@ it also defines lots of intermediate macros, just ignore those :-)
 #define SIVALX(buf,pos,val) (SSVALX(buf,pos,val&0xFFFF),SSVALX(buf,pos+2,val>>16))
 #define SVALS(buf,pos) ((int16)SVAL(buf,pos))
 #define IVALS(buf,pos) ((int32_t)IVAL(buf,pos))
-#define SSVAL(buf,pos,val) SSVALX((buf),(pos),((u_int16_t)(val)))
-#define SIVAL(buf,pos,val) SIVALX((buf),(pos),((u_int32_t)(val)))
+#define SSVAL(buf,pos,val) SSVALX((buf),(pos),((uint16_t)(val)))
+#define SIVAL(buf,pos,val) SIVALX((buf),(pos),((uint32_t)(val)))
 #define SSVALS(buf,pos,val) SSVALX((buf),(pos),((int16)(val)))
 #define SIVALS(buf,pos,val) SIVALX((buf),(pos),((int32_t)(val)))
 
@@ -152,18 +152,18 @@ it also defines lots of intermediate macros, just ignore those :-)
 */
 
 /* get single value from an SMB buffer */
-#define SVAL(buf,pos) (*(const u_int16_t *)((const char *)(buf) + (pos)))
-#define SVAL_NC(buf,pos) (*(u_int16_t *)((char *)(buf) + (pos))) /* Non const version of above. */
-#define IVAL(buf,pos) (*(const u_int32_t *)((const char *)(buf) + (pos)))
-#define IVAL_NC(buf,pos) (*(u_int32_t *)((char *)(buf) + (pos))) /* Non const version of above. */
+#define SVAL(buf,pos) (*(const uint16_t *)((const char *)(buf) + (pos)))
+#define SVAL_NC(buf,pos) (*(uint16_t *)((char *)(buf) + (pos))) /* Non const version of above. */
+#define IVAL(buf,pos) (*(const uint32_t *)((const char *)(buf) + (pos)))
+#define IVAL_NC(buf,pos) (*(uint32_t *)((char *)(buf) + (pos))) /* Non const version of above. */
 #define SVALS(buf,pos) (*(const int16_t *)((const char *)(buf) + (pos)))
 #define SVALS_NC(buf,pos) (*(int16 *)((char *)(buf) + (pos))) /* Non const version of above. */
 #define IVALS(buf,pos) (*(const int32_t *)((const char *)(buf) + (pos)))
 #define IVALS_NC(buf,pos) (*(int32_t *)((char *)(buf) + (pos))) /* Non const version of above. */
 
 /* store single value in an SMB buffer */
-#define SSVAL(buf,pos,val) SVAL_NC(buf,pos)=((u_int16_t)(val))
-#define SIVAL(buf,pos,val) IVAL_NC(buf,pos)=((u_int32_t)(val))
+#define SSVAL(buf,pos,val) SVAL_NC(buf,pos)=((uint16_t)(val))
+#define SIVAL(buf,pos,val) IVAL_NC(buf,pos)=((uint32_t)(val))
 #define SSVALS(buf,pos,val) SVALS_NC(buf,pos)=((int16)(val))
 #define SIVALS(buf,pos,val) IVALS_NC(buf,pos)=((int32_t)(val))
 
index 98e8ffccd53b28905f752591777d292725dc7ec8..cd2fe6e5959984f5ecc0604405eb7b498f30c926 100644 (file)
 #ifdef HAVE_USABLE_ICONV
 #include <iconv.h>
 #endif
-#if HAVE_LOCALE_H
-#include <locale.h>
-#endif
-#if HAVE_LANGINFO_H
-#include <langinfo.h>
-#endif
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/logger.h>
 #include <atalk/unicode.h>
 #include <atalk/util.h>
+#include <atalk/compat.h>
+
 #include "byteorder.h"
 
 
@@ -76,29 +72,6 @@ static struct charset_functions* charsets[MAX_CHARSETS];
 static char hexdig[] = "0123456789abcdef";
 #define hextoint( c )   ( isdigit( c ) ? c - '0' : c + 10 - 'a' )
 
-static char* read_charsets_from_env(charset_t ch)
-{
-    char *name;
-
-    switch (ch) {
-    case CH_MAC:
-        if (( name = getenv( "ATALK_MAC_CHARSET" )) != NULL )
-            return name;
-        else
-            return "MAC_ROMAN";
-        break;
-    case CH_UNIX:
-        if (( name = getenv( "ATALK_UNIX_CHARSET" )) != NULL )
-            return name;
-        else
-            return "LOCALE";
-        break;
-    default:
-        break;
-    }
-    return "ASCII";
-}
-
 
 /**
  * Return the name of a charset to give to iconv().
@@ -106,70 +79,22 @@ static char* read_charsets_from_env(charset_t ch)
 static const char *charset_name(charset_t ch)
 {
     const char *ret = NULL;
-    static int first = 1;
-    static char macname[128];
-    static char unixname[128];
-
-    if (first) {
-        memset(macname, 0, sizeof(macname));
-        memset(unixname, 0, sizeof(unixname));
-        first = 0;
-    }
 
     if (ch == CH_UCS2) ret = "UCS-2";
     else if (ch == CH_UTF8) ret = "UTF8";
     else if (ch == CH_UTF8_MAC) ret = "UTF8-MAC";
-    else if (ch == CH_UNIX) {
-        if (unixname[0] == '\0') {
-            ret = read_charsets_from_env(CH_UNIX);
-            strlcpy(unixname, ret, sizeof(unixname));
-        }
-        else
-            ret = unixname;
-    }
-    else if (ch == CH_MAC) {
-        if (macname[0] == '\0') {
-            ret = read_charsets_from_env(CH_MAC);
-            strlcpy(macname, ret, sizeof(macname));
-        }
-        else
-            ret = macname;
-    }
-
-    if (!ret)
-        ret = charset_names[ch];
-
-#if defined(HAVE_NL_LANGINFO) && defined(CODESET)
-    if (ret && strcasecmp(ret, "LOCALE") == 0) {
-        const char *ln = NULL;
-
-#ifdef HAVE_SETLOCALE
-        setlocale(LC_ALL, "");
-#endif
-        ln = nl_langinfo(CODESET);
-        if (ln) {
-            /* Check whether the charset name is supported
-               by iconv */
-            atalk_iconv_t handle = atalk_iconv_open(ln, "UCS-2");
-            if (handle == (atalk_iconv_t) -1) {
-                LOG(log_debug, logtype_default, "Locale charset '%s' unsupported, using ASCII instead", ln);
-                ln = "ASCII";
-            } else {
-                atalk_iconv_close(handle);
-            }
-            if (ch==CH_UNIX)
-                strlcpy(unixname, ln, sizeof(unixname));
-        }
-        ret = ln;
-    }
-#else /* system doesn't have LOCALE support */
-    if (ch == CH_UNIX) ret = NULL;
-#endif
-
-    if (!ret || !*ret) ret = "ASCII";
+    else ret = charset_names[ch];
     return ret;
 }
 
+int set_charset_name(charset_t ch, const char *name)
+{
+    if (ch >= NUM_CHARSETS)
+        return -1;
+    charset_names[ch] = strdup(name);
+    return 0;
+}
+
 static struct charset_functions* get_charset_functions (charset_t ch)
 {
     if (charsets[ch] != NULL)
@@ -768,9 +693,9 @@ char * debug_out ( char * seq, size_t len)
  *      for e.g. HFS cdroms.
  */
 
-static size_t pull_charset_flags (charset_t from_set, charset_t cap_set, const char *src, size_t srclen, char* dest, size_t destlen, u_int16_t *flags)
+static size_t pull_charset_flags (charset_t from_set, charset_t cap_set, const char *src, size_t srclen, char* dest, size_t destlen, uint16_t *flags)
 {
-    const u_int16_t option = (flags ? *flags : 0);
+    const uint16_t option = (flags ? *flags : 0);
     size_t i_len, o_len;
     size_t j = 0;
     const char* inbuf = (const char*)src;
@@ -793,13 +718,11 @@ static size_t pull_charset_flags (charset_t from_set, charset_t cap_set, const c
     o_len=destlen;
 
     while (i_len > 0) {
-        if ((option & CONV_UNESCAPEHEX)) {
-            for (j = 0; j < i_len; ++j) {
-                if (inbuf[j] == ':') break;
-            }
-            j = i_len - j;
-            i_len -= j;
-        }
+        for (j = 0; j < i_len; ++j)
+            if (inbuf[j] == ':')
+                break;
+        j = i_len - j;
+        i_len -= j;
 
         if (i_len > 0 &&
             atalk_iconv(descriptor, &inbuf, &i_len, &outbuf, &o_len) == (size_t)-1) {
@@ -827,36 +750,48 @@ static size_t pull_charset_flags (charset_t from_set, charset_t cap_set, const c
         }
 
         if (j) {
-            /* we're at the start on an hex encoded ucs2 char */
-            char h[MAXPATHLEN];
-            size_t hlen = 0;
-
+            /* we have a ':' */
             i_len = j, j = 0;
-            while (i_len >= 3 && inbuf[0] == ':' &&
-                   isxdigit(inbuf[1]) && isxdigit(inbuf[2])) {
-                h[hlen++] = (hextoint(inbuf[1]) << 4) | hextoint(inbuf[2]);
-                inbuf += 3;
-                i_len -= 3;
-            }
-            if (hlen) {
-                const char *h_buf = h;
-                if (atalk_iconv(descriptor_cap, &h_buf, &hlen, &outbuf, &o_len) == (size_t)-1) {
-                    i_len += hlen * 3;
-                    inbuf -= hlen * 3;
-                    if (errno == EILSEQ && (option & CONV_IGNORE)) {
+
+            if ((option & CONV_UNESCAPEHEX)) {
+                /* treat it as a CAP hex encoded char */
+                char h[MAXPATHLEN];
+                size_t hlen = 0;
+
+                while (i_len >= 3 && inbuf[0] == ':' &&
+                       isxdigit(inbuf[1]) && isxdigit(inbuf[2])) {
+                    h[hlen++] = (hextoint(inbuf[1]) << 4) | hextoint(inbuf[2]);
+                    inbuf += 3;
+                    i_len -= 3;
+                }
+                if (hlen) {
+                    const char *h_buf = h;
+                    if (atalk_iconv(descriptor_cap, &h_buf, &hlen, &outbuf, &o_len) == (size_t)-1) {
+                        i_len += hlen * 3;
+                        inbuf -= hlen * 3;
+                        if (errno == EILSEQ && (option & CONV_IGNORE)) {
+                            *flags |= CONV_REQMANGLE;
+                            return destlen - o_len;
+                        }
+                        goto end;
+                    }
+                } else {
+                    /* We have an invalid :xx sequence */
+                    errno = EILSEQ;
+                    if ((option & CONV_IGNORE)) {
                         *flags |= CONV_REQMANGLE;
                         return destlen - o_len;
                     }
                     goto end;
                 }
             } else {
-                /* We have an invalid :xx sequence */
-                errno = EILSEQ;
-                if ((option & CONV_IGNORE)) {
-                    *flags |= CONV_REQMANGLE;
-                    return destlen - o_len;
-                }
-                goto end;
+                /* a ':' that we just convert to a '/' */
+                ucs2_t slash = 0x002f;
+                memcpy(outbuf, &slash, sizeof(ucs2_t));
+                outbuf += 2;
+                o_len -= 2;
+                inbuf++;
+                i_len--;
             }
         }
     }
@@ -880,9 +815,9 @@ end:
  */
 
 
-static size_t push_charset_flags (charset_t to_set, charset_t cap_set, char* src, size_t srclen, char* dest, size_t destlen, u_int16_t *flags)
+static size_t push_charset_flags (charset_t to_set, charset_t cap_set, char* src, size_t srclen, char* dest, size_t destlen, uint16_t *flags)
 {
-    const u_int16_t option = (flags ? *flags : 0);
+    const uint16_t option = (flags ? *flags : 0);
     size_t i_len, o_len, i;
     size_t j = 0;
     const char* inbuf = (const char*)src;
@@ -918,25 +853,23 @@ static size_t push_charset_flags (charset_t to_set, charset_t cap_set, char* src
     }
 
     while (i_len >= 2) {
-        if ((option & CONV_ESCAPEHEX)) {
-            for (i = 0; i < i_len; i += 2) {
-                ucs2_t c = SVAL(inbuf, i);
-                switch (c) {
-                case 0x003a: /* 0x003a = ':' */
-                    if ( ! (option & CONV_ALLOW_COLON)) {
-                        errno = EILSEQ;
-                        goto end;
-                    }
-                    escch = c;
-                    j = i_len - i;
-                    i_len = i;
-                    break;
-                case 0x002f: /* 0x002f = '/' */
-                    escch = c;
-                    j = i_len - i;
-                    i_len = i;
-                    break;
+        for (i = 0; i < i_len; i += 2) {
+            ucs2_t c = SVAL(inbuf, i);
+            switch (c) {
+            case 0x003a: /* 0x003a = ':' */
+                if ( ! (option & CONV_ALLOW_COLON)) {
+                    errno = EILSEQ;
+                    goto end;
                 }
+                escch = c;
+                j = i_len - i;
+                i_len = i;
+                break;
+            case 0x002f: /* 0x002f = '/' */
+                escch = c;
+                j = i_len - i;
+                i_len = i;
+                break;
             }
         }
         while (i_len > 0 &&
@@ -989,35 +922,53 @@ static size_t push_charset_flags (charset_t to_set, charset_t cap_set, char* src
         }
 
         if (j) {
+            /* we have a ':' or '/' */
             i_len = j, j = 0;
-            if (o_len < 3) {
-                errno = E2BIG;
-                goto end;
-            }
-            switch (escch) {
-            case '/':
-                *outbuf++ = ':';
-                *outbuf++ = '2';
-                *outbuf++ = 'f';
-                break;
-            case ':':
-                *outbuf++ = ':';
-                *outbuf++ = '3';
-                *outbuf++ = 'a';
-                break;
-            default:
-                /*
-                 *  THIS SHOULD NEVER BE REACHED !!!
-                 *  As a safety net I put in a ' ' here
-                 */
-                *outbuf++ = ':';
-                *outbuf++ = '2';
-                *outbuf++ = '0';
-                break;
+
+            if ((option & CONV_ESCAPEHEX)) {
+                /* CAP hex encode it */
+                if (o_len < 3) {
+                    errno = E2BIG;
+                    goto end;
+                }
+                switch (escch) {
+                case '/':
+                    *outbuf++ = ':';
+                    *outbuf++ = '2';
+                    *outbuf++ = 'f';
+                    break;
+                case ':':
+                    *outbuf++ = ':';
+                    *outbuf++ = '3';
+                    *outbuf++ = 'a';
+                    break;
+                default:
+                    /*
+                     *  THIS SHOULD NEVER BE REACHED !!!
+                     *  As a safety net I put in a ' ' here
+                     */
+                    *outbuf++ = ':';
+                    *outbuf++ = '2';
+                    *outbuf++ = '0';
+                    break;
+                }
+                o_len -= 3;
+                inbuf += 2;
+                i_len -= 2;
+            } else {
+                switch (escch) {
+                case '/':
+                case ':':
+                    *outbuf++ = ':';
+                    break;
+                default: /* should never be reached */
+                    *outbuf++ = ' ';
+                    break;
+                }
+                o_len--;
+                inbuf += 2;
+                i_len -= 2;
             }
-            o_len -= 3;
-            inbuf += 2;
-            i_len -= 2;
         }
     }
     if (i_len > 0) errno = EINVAL;
@@ -1029,7 +980,7 @@ end:
  * FIXME the size is a mess we really need a malloc/free logic
  *`dest size must be dest_len +2
  */
-size_t convert_charset ( charset_t from_set, charset_t to_set, charset_t cap_charset, const char *src, size_t src_len, char *dest, size_t dest_len, u_int16_t *flags)
+size_t convert_charset ( charset_t from_set, charset_t to_set, charset_t cap_charset, const char *src, size_t src_len, char *dest, size_t dest_len, uint16_t *flags)
 {
     size_t i_len, o_len;
     ucs2_t *u;
index 29358a8c8da043f5235c0d92e65dc0a702b6d9ba..461af345ff65ae1cd55b0a6b4563495f47c5d912 100644 (file)
@@ -36,14 +36,14 @@ static size_t cjk_iconv(void *cd, char **inbuf, char *end,
   return n;
 }
 
-size_t cjk_generic_push(size_t (*char_func)(u_int8_t*, const ucs2_t*, size_t*),
+size_t cjk_generic_push(size_t (*char_func)(uint8_t*, const ucs2_t*, size_t*),
                        void *cd, char **inbuf, size_t *inbytesleft,
                        char **outbuf, size_t *outbytesleft)
 {
   char *in = *inbuf;
 
   while (*inbytesleft >= sizeof(ucs2_t) && *outbytesleft > 0) {
-    u_int8_t buf[CJK_PUSH_BUFFER];
+    uint8_t buf[CJK_PUSH_BUFFER];
     size_t size = *inbytesleft / sizeof(ucs2_t);
     size_t n = (char_func)(buf, (const ucs2_t*)in, &size);
     if (n == 0) {
@@ -78,7 +78,7 @@ size_t cjk_generic_push(size_t (*char_func)(u_int8_t*, const ucs2_t*, size_t*),
   return 0;
 }
 
-size_t cjk_generic_pull(size_t (*char_func)(ucs2_t*, const u_int8_t*, size_t*),
+size_t cjk_generic_pull(size_t (*char_func)(ucs2_t*, const uint8_t*, size_t*),
                        void *cd, char **inbuf, size_t *inbytesleft,
                        char **outbuf, size_t *outbytesleft)
 {
@@ -87,7 +87,7 @@ size_t cjk_generic_pull(size_t (*char_func)(ucs2_t*, const u_int8_t*, size_t*),
   while (*inbytesleft > 0 && *outbytesleft >= sizeof(ucs2_t)) {
     ucs2_t buf[CJK_PULL_BUFFER];
     size_t size = *inbytesleft;
-    size_t n = (char_func)(buf, (const u_int8_t*)in, &size);
+    size_t n = (char_func)(buf, (const uint8_t*)in, &size);
     if (n == 0) {
       in += size;
       *inbytesleft -= size;
@@ -120,30 +120,30 @@ size_t cjk_generic_pull(size_t (*char_func)(ucs2_t*, const u_int8_t*, size_t*),
   return 0;
 }
 
-size_t cjk_char_push(u_int16_t c, u_int8_t *out)
+size_t cjk_char_push(uint16_t c, uint8_t *out)
 {
   if (!c) return 0;
-  if (c == (u_int16_t)-1) {
+  if (c == (uint16_t)-1) {
     errno = EILSEQ;
     return (size_t)-1;
   }
   if (c <= 0xff) {
-    out[0] = (u_int8_t)c;
+    out[0] = (uint8_t)c;
     return 1;
   }
-  out[0] = (u_int8_t)(c >> 8);
-  out[1] = (u_int8_t)c;
+  out[0] = (uint8_t)(c >> 8);
+  out[1] = (uint8_t)c;
   return 2;
 }
 
-size_t cjk_char_pull(ucs2_t wc, ucs2_t* out, const u_int32_t* compose)
+size_t cjk_char_pull(ucs2_t wc, ucs2_t* out, const uint32_t* compose)
 {
   if (!wc) return 0;
   if ((wc & 0xf000) == 0xe000) {
     ucs2_t buf[CJK_PULL_BUFFER];
     size_t i = sizeof(buf) / sizeof(*buf) - 1;
     do {
-      u_int32_t v = compose[wc & 0xfff];
+      uint32_t v = compose[wc & 0xfff];
       buf[i] = (ucs2_t)v;
       wc = (ucs2_t)(v >> 16);
     } while (--i && (wc & 0xf000) == 0xe000);
@@ -155,12 +155,12 @@ size_t cjk_char_pull(ucs2_t wc, ucs2_t* out, const u_int32_t* compose)
   return 1;
 }
 
-u_int16_t cjk_lookup(u_int16_t c, const cjk_index_t *index, const u_int16_t *charset)
+uint16_t cjk_lookup(uint16_t c, const cjk_index_t *index, const uint16_t *charset)
 {
   while (index->summary && c >= index->range[0]) {
     if (c <= index->range[1]) {
-      const u_int16_t* summary = index->summary[(c - index->range[0]) >> 4];
-      u_int16_t used = 1 << (c & 15);
+      const uint16_t* summary = index->summary[(c - index->range[0]) >> 4];
+      uint16_t used = 1 << (c & 15);
 
       if (summary[0] & used) {
        used = summary[0] & (used - 1);
@@ -175,9 +175,9 @@ u_int16_t cjk_lookup(u_int16_t c, const cjk_index_t *index, const u_int16_t *cha
   return 0;
 }
 
-ucs2_t cjk_compose(ucs2_t base, ucs2_t comb, const u_int32_t* table, size_t size)
+ucs2_t cjk_compose(ucs2_t base, ucs2_t comb, const uint32_t* table, size_t size)
 {
-  u_int32_t v = ((u_int32_t)base << 16) | comb;
+  uint32_t v = ((uint32_t)base << 16) | comb;
   size_t low = 0;
   while (size > low) {
     size_t n = (low + size) / 2;
@@ -191,9 +191,9 @@ ucs2_t cjk_compose(ucs2_t base, ucs2_t comb, const u_int32_t* table, size_t size
   return 0;
 }
 
-ucs2_t cjk_compose_seq(const ucs2_t* in, size_t* len, const u_int32_t* table, size_t size)
+ucs2_t cjk_compose_seq(const ucs2_t* in, size_t* len, const uint32_t* table, size_t size)
 {
-  static u_int8_t sz[] = { 3, 4, 5, 5, 5, 5, 5, 3 };
+  static uint8_t sz[] = { 3, 4, 5, 5, 5, 5, 5, 3 };
   ucs2_t wc = in[0];
   size_t n = sz[wc & 7];
   size_t i = 0;
index 8c6cbaaf20a212e10ecaa9afdb8152982ba1e728..5dab15a6284a6ce323a245594a9498e90e2b2ebf 100644 (file)
 #define CJK_PULL_BUFFER 8
 
 typedef struct {
-  u_int16_t range[2];
-  const u_int16_t (*summary)[2];
+  uint16_t range[2];
+  const uint16_t (*summary)[2];
 } cjk_index_t;
 
-extern size_t cjk_generic_push (size_t (*)(u_int8_t*, const ucs2_t*, size_t*),
+extern size_t cjk_generic_push (size_t (*)(uint8_t*, const ucs2_t*, size_t*),
                                   void*, char**, size_t*, char**, size_t*);
-extern size_t cjk_generic_pull (size_t (*)(ucs2_t*, const u_int8_t*, size_t*),
+extern size_t cjk_generic_pull (size_t (*)(ucs2_t*, const uint8_t*, size_t*),
                                   void*, char**, size_t*, char**, size_t*);
 
-extern size_t cjk_char_push (u_int16_t, u_int8_t*);
-extern size_t cjk_char_pull (ucs2_t, ucs2_t*, const u_int32_t*);
+extern size_t cjk_char_push (uint16_t, uint8_t*);
+extern size_t cjk_char_pull (ucs2_t, ucs2_t*, const uint32_t*);
 
-extern u_int16_t cjk_lookup (u_int16_t, const cjk_index_t*, const u_int16_t*);
-extern ucs2_t cjk_compose (ucs2_t, ucs2_t, const u_int32_t*, size_t);
-extern ucs2_t cjk_compose_seq (const ucs2_t*, size_t*, const u_int32_t*, size_t);
+extern uint16_t cjk_lookup (uint16_t, const cjk_index_t*, const uint16_t*);
+extern ucs2_t cjk_compose (ucs2_t, ucs2_t, const uint32_t*, size_t);
+extern ucs2_t cjk_compose_seq (const ucs2_t*, size_t*, const uint32_t*, size_t);
index 0fc36b758cc544e94d269b34af4e3771b956bea7..7b36997d804a035a4f6b86f1d0686d95df9b6759 100644 (file)
@@ -31,8 +31,8 @@
 #include <unistd.h>
 #include <string.h>
 #include <errno.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/unicode.h>
 #include <atalk/logger.h>
 
index 3effc6856ca1b076021fd1f6a30226501475ee31..40784be3c5deb0e632cd9200b9936801dc056c0a 100644 (file)
@@ -28,7 +28,8 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 #include <stdlib.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/unicode.h>
 
 #include "mac_centraleurope.h"
index f0ad4640af2af16e2b108084b593555aa49229b7..2ff6c2a069aa0f5a535d307d6a22b4c7d5ad37fd 100644 (file)
@@ -43,20 +43,20 @@ struct charset_functions charset_mac_chinese_simp = {
   NULL, NULL
 };
 
-static size_t mac_chinese_simp_char_push(u_int8_t* out, const ucs2_t* in, size_t* size)
+static size_t mac_chinese_simp_char_push(uint8_t* out, const ucs2_t* in, size_t* size)
 {
   ucs2_t wc = in[0];
 
   if (wc <= 0x7f) {
     *size = 1;
-    out[0] = (u_int8_t)wc;
+    out[0] = (uint8_t)wc;
     return 1;
   } else if ((wc & 0xf000) == 0xe000) {
     *size = 1;
     return 0;
   } else if (*size >= 2 && (in[1] & ~15) == 0xf870) {
     ucs2_t comp = cjk_compose(wc, in[1], mac_chinese_simp_compose,
-                             sizeof(mac_chinese_simp_compose) / sizeof(u_int32_t));
+                             sizeof(mac_chinese_simp_compose) / sizeof(uint32_t));
     if (comp) {
       wc = comp;
       *size = 2;
@@ -77,9 +77,9 @@ static size_t mac_chinese_simp_push(void *cd, char **inbuf, size_t *inbytesleft,
                          cd, inbuf, inbytesleft, outbuf, outbytesleft);
 }
 
-static size_t mac_chinese_simp_char_pull(ucs2_t* out, const u_int8_t* in, size_t* size)
+static size_t mac_chinese_simp_char_pull(ucs2_t* out, const uint8_t* in, size_t* size)
 {
-  u_int16_t c = in[0];
+  uint16_t c = in[0];
 
   if (c <= 0x7f) {
     *size = 1;
@@ -87,7 +87,7 @@ static size_t mac_chinese_simp_char_pull(ucs2_t* out, const u_int8_t* in, size_t
     return 1;
   } else if (c >= 0xa1 && c <= 0xfc) {
     if (*size >= 2) {
-      u_int8_t c2 = in[1];
+      uint8_t c2 = in[1];
 
       if (c2 >= 0xa1 && c2 <= 0xfe) {
        *size = 2;
index 9e7d8cea88a922d48b07f5f5f06a297aa0118b72..25216256639c9aad9b53d5c2ebfe33746f856357 100644 (file)
@@ -20,7 +20,7 @@
  * http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/
  */
 
-static const u_int16_t mac_chinese_simp_uni2_page00[][2] = {
+static const uint16_t mac_chinese_simp_uni2_page00[][2] = {
   /* 0x00a */ { 0x022d,    0 }, { 0x0080,    5 },
   /* 0x00c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x010 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
@@ -31,42 +31,42 @@ static const u_int16_t mac_chinese_simp_uni2_page00[][2] = {
   /* 0x024 */ { 0x0000,    0 }, { 0x0002,    9 }, { 0x0002,   10 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_page1e[][2] = {
+static const uint16_t mac_chinese_simp_uni2_page1e[][2] = {
   /* 0x1e3 */ { 0x8000,   11 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_page20[][2] = {
+static const uint16_t mac_chinese_simp_uni2_page20[][2] = {
   /* 0x201 */ { 0x0070,   12 }, { 0x0040,   15 }, { 0x4000,   16 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_page21[][2] = {
+static const uint16_t mac_chinese_simp_uni2_page21[][2] = {
   /* 0x212 */ { 0x0004,   17 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_page22[][2] = {
+static const uint16_t mac_chinese_simp_uni2_page22[][2] = {
   /* 0x22e */ { 0x8000,   18 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_page30[][2] = {
+static const uint16_t mac_chinese_simp_uni2_page30[][2] = {
   /* 0x301 */ { 0x1000,   19 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x304 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x308 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x30c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0800,   20 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_pagee0[][2] = {
+static const uint16_t mac_chinese_simp_uni2_pagee0[][2] = {
   /* 0xe00 */ { 0x07ff,   21 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_pagef8[][2] = {
+static const uint16_t mac_chinese_simp_uni2_pagef8[][2] = {
   /* 0xf88 */ { 0x0003,   32 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_pagefe[][2] = {
+static const uint16_t mac_chinese_simp_uni2_pagefe[][2] = {
   /* 0xfe3 */ { 0xfffa,   34 }, { 0x001f,   48 },
 };
 
-static const u_int16_t mac_chinese_simp_uni2_pageff[][2] = {
+static const uint16_t mac_chinese_simp_uni2_pageff[][2] = {
   /* 0xff5 */ { 0x4000,   53 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0xff8 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0xffc */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x002b,   54 },
@@ -86,7 +86,7 @@ static const cjk_index_t mac_chinese_simp_uni2_index[] = {
   { { 0, 0 }, NULL }
 };
 
-static const u_int16_t mac_chinese_simp_uni2_charset[] = {
+static const uint16_t mac_chinese_simp_uni2_charset[] = {
   0x00a0, 0xa1e9, 0xa1ea, 0xa3a4, 0x00fd, 0xa1a4, 0xa8bd, 0xa8be,
   0xa8bf, 0xa8bb, 0xa8c0, 0xa8bc, 0xa1aa, 0xffff, 0xa1ac, 0x00ff,
   0xa3fe, 0x00fe, 0xa1ad, 0xa1ab, 0xffff, 0x0080, 0xa6f3, 0xa6db,
@@ -97,26 +97,26 @@ static const u_int16_t mac_chinese_simp_uni2_charset[] = {
   0xffff, 0xffff,
 };
 
-static const u_int16_t mac_chinese_simp_2uni_page00[][2] = {
+static const uint16_t mac_chinese_simp_2uni_page00[][2] = {
   /* 0x008 */ { 0x0007,    0 }, { 0x0000,    0 }, { 0x0001,    3 }, { 0x0000,    0 },
   /* 0x00c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0xe000,    4 },
 };
 
-static const u_int16_t mac_chinese_simp_2uni_pagea1[][2] = {
+static const uint16_t mac_chinese_simp_2uni_pagea1[][2] = {
   /* 0xa1a */ { 0x3c10,    7 }, { 0x0000,    0 },
   /* 0xa1c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0600,   12 },
 };
 
-static const u_int16_t mac_chinese_simp_2uni_pagea3[][2] = {
+static const uint16_t mac_chinese_simp_2uni_pagea3[][2] = {
   /* 0xa3a */ { 0x0010,   14 }, { 0x0000,    0 },
   /* 0xa3c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x4000,   15 },
 };
 
-static const u_int16_t mac_chinese_simp_2uni_pagea6[][2] = {
+static const uint16_t mac_chinese_simp_2uni_pagea6[][2] = {
   /* 0xa6d */ { 0xfe00,   16 }, { 0xffff,   23 }, { 0x003f,   39 },
 };
 
-static const u_int16_t mac_chinese_simp_2uni_pagea8[][2] = {
+static const uint16_t mac_chinese_simp_2uni_pagea8[][2] = {
   /* 0xa8b */ { 0xf800,   45 }, { 0x0001,   50 },
 };
 
@@ -129,7 +129,7 @@ static const cjk_index_t mac_chinese_simp_2uni_index[] = {
   { { 0, 0 }, NULL }
 };
 
-static const u_int16_t mac_chinese_simp_2uni_charset[] = {
+static const uint16_t mac_chinese_simp_2uni_charset[] = {
   0xe000, 0xf880, 0xf881, 0x00a0, 0x00a9, 0x2122, 0x2026, 0x00b7,
   0x2014, 0x301c, 0x2016, 0x22ef, 0x00a2, 0x00a3, 0x00a5, 0x203e,
   0xe007, 0xe003, 0xe002, 0xe008, 0xe009, 0xe006, 0xe00a, 0xfe35,
@@ -139,7 +139,7 @@ static const u_int16_t mac_chinese_simp_2uni_charset[] = {
   0x0148, 0x01f9, 0x0261,
 };
 
-static const u_int32_t mac_chinese_simp_compose[] = {
+static const uint32_t mac_chinese_simp_compose[] = {
   0x00fcf87f, 0x22eff87e, 0x3001f87e, 0x3002f87e,
   0x3016f87e, 0x3017f87e, 0xff01f87e, 0xff0cf87e,
   0xff1af87e, 0xff1bf87e, 0xff1ff87e,
index 7412beeccb421e1e5527a60f518c530cc36176d6..116e8cd5e3f88d905a50ab0c3e1c181ed3048a95 100644 (file)
@@ -43,7 +43,7 @@ struct charset_functions charset_mac_chinese_trad = {
   NULL, NULL
 };
 
-static size_t mac_chinese_trad_char_push(u_int8_t* out, const ucs2_t* in, size_t* size)
+static size_t mac_chinese_trad_char_push(uint8_t* out, const ucs2_t* in, size_t* size)
 {
   ucs2_t wc = in[0];
 
@@ -53,7 +53,7 @@ static size_t mac_chinese_trad_char_push(u_int8_t* out, const ucs2_t* in, size_t
       out[0] = 0x80;
     } else {
       *size = 1;
-      out[0] = (u_int8_t)wc;
+      out[0] = (uint8_t)wc;
     }
     return 1;
   } else if ((wc & 0xf000) == 0xe000) {
@@ -61,7 +61,7 @@ static size_t mac_chinese_trad_char_push(u_int8_t* out, const ucs2_t* in, size_t
     return 0;
   } else if (*size >= 2 && (in[1] & ~15) == 0xf870) {
     ucs2_t comp = cjk_compose(wc, in[1], mac_chinese_trad_compose,
-                             sizeof(mac_chinese_trad_compose) / sizeof(u_int32_t));
+                             sizeof(mac_chinese_trad_compose) / sizeof(uint32_t));
     if (comp) {
       wc = comp;
       *size = 2;
@@ -82,9 +82,9 @@ static size_t mac_chinese_trad_push(void *cd, char **inbuf, size_t *inbytesleft,
                          cd, inbuf, inbytesleft, outbuf, outbytesleft);
 }
 
-static size_t mac_chinese_trad_char_pull(ucs2_t* out, const u_int8_t* in, size_t* size)
+static size_t mac_chinese_trad_char_pull(ucs2_t* out, const uint8_t* in, size_t* size)
 {
-  u_int16_t c = in[0];
+  uint16_t c = in[0];
 
   if (c <= 0x7f) {
     *size = 1;
@@ -92,7 +92,7 @@ static size_t mac_chinese_trad_char_pull(ucs2_t* out, const u_int8_t* in, size_t
     return 1;
   } else if (c >= 0xa1 && c <= 0xfc) {
     if (*size >= 2) {
-      u_int8_t c2 = in[1];
+      uint8_t c2 = in[1];
 
       if ((c2 >= 0x40 && c2 <= 0x7e) || (c2 >= 0xa1 && c2 <= 0xfe)) {
        *size = 2;
index a5c94eb1f6fdc434d8bf2429177b1ad6caf6d286..00e0c518e62ef593a00bb0f3bc117a568003a5ec 100644 (file)
  * http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/
  */
 
-static const u_int16_t mac_chinese_trad_uni2_page00[][2] = {
+static const uint16_t mac_chinese_trad_uni2_page00[][2] = {
   /* 0x00a */ { 0x0201,    0 }, { 0x0080,    2 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_page20[][2] = {
+static const uint16_t mac_chinese_trad_uni2_page20[][2] = {
   /* 0x202 */ { 0x0044,    3 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_page21[][2] = {
+static const uint16_t mac_chinese_trad_uni2_page21[][2] = {
   /* 0x212 */ { 0x0004,    5 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_page22[][2] = {
+static const uint16_t mac_chinese_trad_uni2_page22[][2] = {
   /* 0x229 */ { 0x0020,    6 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x22c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x8000,    7 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_page25[][2] = {
+static const uint16_t mac_chinese_trad_uni2_page25[][2] = {
   /* 0x259 */ { 0x0020,    8 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_page26[][2] = {
+static const uint16_t mac_chinese_trad_uni2_page26[][2] = {
   /* 0x264 */ { 0x0002,    9 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_pagee0[][2] = {
+static const uint16_t mac_chinese_trad_uni2_pagee0[][2] = {
   /* 0xe00 */ { 0xffff,   10 }, { 0x00ff,   26 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_pagef8[][2] = {
+static const uint16_t mac_chinese_trad_uni2_pagef8[][2] = {
   /* 0xf88 */ { 0x0003,   34 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_pagefe[][2] = {
+static const uint16_t mac_chinese_trad_uni2_pagefe[][2] = {
   /* 0xfe4 */ { 0x1000,   36 }, { 0x7ef5,   37 },
 };
 
-static const u_int16_t mac_chinese_trad_uni2_pageff[][2] = {
+static const uint16_t mac_chinese_trad_uni2_pageff[][2] = {
   /* 0xff6 */ { 0x0010,   49 },
 };
 
@@ -75,7 +75,7 @@ static const cjk_index_t mac_chinese_trad_uni2_index[] = {
   { { 0, 0 }, NULL }
 };
 
-static const u_int16_t mac_chinese_trad_uni2_charset[] = {
+static const uint16_t mac_chinese_trad_uni2_charset[] = {
   0x00a0, 0x00fd, 0xa145, 0xffff, 0x00ff, 0x00fe, 0xa1f2, 0xa14b,
   0xffff, 0xffff, 0x0080, 0xa1c3, 0xa279, 0xa14e, 0xa1a3, 0xa1a4,
   0xa2cc, 0xa2ce, 0xa1cb, 0xa154, 0xa17d, 0xa17e, 0xa14d, 0xa14f,
@@ -85,12 +85,12 @@ static const u_int16_t mac_chinese_trad_uni2_charset[] = {
   0xffff, 0xffff,
 };
 
-static const u_int16_t mac_chinese_trad_2uni_page00[][2] = {
+static const uint16_t mac_chinese_trad_2uni_page00[][2] = {
   /* 0x008 */ { 0x0007,    0 }, { 0x0000,    0 }, { 0x0001,    3 }, { 0x0000,    0 },
   /* 0x00c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0xe000,    4 },
 };
 
-static const u_int16_t mac_chinese_trad_2uni_pagea1[][2] = {
+static const uint16_t mac_chinese_trad_2uni_pagea1[][2] = {
   /* 0xa14 */ { 0xe820,    7 }, { 0x041f,   12 }, { 0x0000,    0 }, { 0x6000,   18 },
   /* 0xa18 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x001e,   20 }, { 0x0000,    0 },
   /* 0xa1c */ { 0x0828,   24 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x4004,   27 },
@@ -106,7 +106,7 @@ static const cjk_index_t mac_chinese_trad_2uni_index[] = {
   { { 0, 0 }, NULL }
 };
 
-static const u_int16_t mac_chinese_trad_2uni_charset[] = {
+static const uint16_t mac_chinese_trad_2uni_charset[] = {
   0xe000, 0xf880, 0xf881, 0x00a0, 0x00a9, 0x2122, 0x2026, 0x00b7,
   0x22ef, 0xe00c, 0xe003, 0xe00d, 0xe00e, 0xe011, 0xe010, 0xe012,
   0xe009, 0xe015, 0xe00a, 0xe00b, 0xe016, 0xe017, 0xe004, 0xe005,
@@ -114,7 +114,7 @@ static const u_int16_t mac_chinese_trad_2uni_charset[] = {
   0xe007,
 };
 
-static const u_int32_t mac_chinese_trad_compose[] = {
+static const uint32_t mac_chinese_trad_compose[] = {
   0x005cf87f, 0x203ef87c, 0x2502f87f, 0x3001f87d,
   0x3014f87f, 0x3015f87f, 0x5341f87f, 0x5345f87f,
   0xfe4bf87c, 0xff01f87d, 0xff08f87f, 0xff09f87f,
index d20a8cec851a0aeb7e60ef3f9165fe4e7753cb60..fde6486130d6ea1b3d8915afa5f30fe0060b1caf 100644 (file)
@@ -28,8 +28,8 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 #include <stdlib.h> /* for size_t */
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/unicode.h>
 
 #include "mac_cyrillic.h"
index 933ba3751ae33ccfcc5324700754acb64fa81f42..e48237b68ed066258a2a58912a19255ecd442ba6 100644 (file)
@@ -30,7 +30,8 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 #include <stdlib.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/unicode.h>
 
 #include "mac_greek.h"
index 8b7bdca94ddad58f72741a520c841de0744ebcd0..91a022bd330983a0dcb2df6eb5decefba8cbf7c6 100644 (file)
@@ -30,8 +30,8 @@
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/unicode.h>
 #include <atalk/logger.h>
 
index b78ce01416a6453c97761f20c25eafb899387b62..9f32f66246f7fbe0bfcd59dd3d732a853a186a6f 100644 (file)
@@ -43,29 +43,29 @@ struct charset_functions charset_mac_japanese = {
   NULL, NULL
 };
 
-static size_t mac_japanese_char_push(u_int8_t* out, const ucs2_t* in, size_t* size)
+static size_t mac_japanese_char_push(uint8_t* out, const ucs2_t* in, size_t* size)
 {
   ucs2_t wc = in[0];
 
   if (wc <= 0x7f) {
     *size = 1;
-    out[0] = (u_int8_t)(wc == 0x5c ? 0x80 : wc);
+    out[0] = (uint8_t)(wc == 0x5c ? 0x80 : wc);
     return 1;
   } else if ((wc & 0xf000) == 0xe000) { /* user defined */
     *size = 1;
     if (wc > 0xe98b) return 0;
     wc -= 0xe000;
-    out[0] = (u_int8_t)(wc / 188 + 0xf0);
-    out[1] = (u_int8_t)(wc % 188 + 0x40);
+    out[0] = (uint8_t)(wc / 188 + 0xf0);
+    out[1] = (uint8_t)(wc % 188 + 0x40);
     if (out[1] >= 0x7f) ++out[1];
     return 2;
   } else if ((wc & ~7) == 0xf860) {
     wc = cjk_compose_seq(in, size, mac_japanese_compose,
-                        sizeof(mac_japanese_compose) / sizeof(u_int32_t));
+                        sizeof(mac_japanese_compose) / sizeof(uint32_t));
     if (!wc) return (size_t)-1;
   } else if (*size >= 2 && ((in[1] & ~15) == 0xf870 || in[1] == 0x20dd)) {
     ucs2_t comp = cjk_compose(wc, in[1], mac_japanese_compose,
-                             sizeof(mac_japanese_compose) / sizeof(u_int32_t));
+                             sizeof(mac_japanese_compose) / sizeof(uint32_t));
     if (comp) {
       wc = comp;
       *size = 2;
@@ -86,9 +86,9 @@ static size_t mac_japanese_push(void *cd, char **inbuf, size_t *inbytesleft,
                          cd, inbuf, inbytesleft, outbuf, outbytesleft);
 }
 
-static size_t mac_japanese_char_pull(ucs2_t* out, const u_int8_t* in, size_t* size)
+static size_t mac_japanese_char_pull(ucs2_t* out, const uint8_t* in, size_t* size)
 {
-  u_int16_t c = in[0];
+  uint16_t c = in[0];
 
   if (c <= 0x7f) {
     *size = 1;
@@ -96,7 +96,7 @@ static size_t mac_japanese_char_pull(ucs2_t* out, const u_int8_t* in, size_t* si
     return 1;
   } else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)) {
     if (*size >= 2) {
-      u_int8_t c2 = in[1];
+      uint8_t c2 = in[1];
 
       if ((c2 >= 0x40 && c2 <= 0x7e) || (c2 >= 0x80 && c2 <= 0xfc)) {
        *size = 2;
index b0be8697177e07664a20807321b62a2849ef8a4f..e27e450d7fc2f13357f9c479a7b1880d5a4d194e 100644 (file)
  * http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/
  */
 
-static const u_int16_t mac_japanese_uni2_page00[][2] = {
+static const uint16_t mac_japanese_uni2_page00[][2] = {
   /* 0x00a */ { 0x0201,    1 },
 };
 
-static const u_int16_t mac_japanese_uni2_page20[][2] = {
+static const uint16_t mac_japanese_uni2_page20[][2] = {
   /* 0x201 */ { 0x0030,    3 }, { 0x0000,    0 }, { 0x4000,    5 },
   /* 0x204 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x208 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
@@ -38,12 +38,12 @@ static const u_int16_t mac_japanese_uni2_page20[][2] = {
   /* 0x228 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x8000,   44 },
 };
 
-static const u_int16_t mac_japanese_uni2_page24[][2] = {
+static const uint16_t mac_japanese_uni2_page24[][2] = {
   /* 0x246 */ { 0xffff,   45 }, { 0xffff,   61 },
   /* 0x248 */ { 0xffff,   77 }, { 0xf001,   93 }, { 0xffff,   98 }, { 0x003f,  114 },
 };
 
-static const u_int16_t mac_japanese_uni2_page26[][2] = {
+static const uint16_t mac_japanese_uni2_page26[][2] = {
   /* 0x260 */ { 0x4000,  120 }, { 0xf000,  121 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x264 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x00ff,  125 }, { 0x0000,    0 },
   /* 0x268 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
@@ -52,14 +52,14 @@ static const u_int16_t mac_japanese_uni2_page26[][2] = {
   /* 0x274 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x7fc0,  133 },
 };
 
-static const u_int16_t mac_japanese_uni2_page30[][2] = {
+static const uint16_t mac_japanese_uni2_page30[][2] = {
   /* 0x300 */ { 0x0010,  142 }, { 0xa000,  143 }, { 0x0001,  145 }, { 0x0000,    0 },
   /* 0x304 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x308 */ { 0x0000,    0 }, { 0x0010,  146 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x30c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0780,  147 },
 };
 
-static const u_int16_t mac_japanese_uni2_page32[][2] = {
+static const uint16_t mac_japanese_uni2_page32[][2] = {
   /* 0x322 */ { 0xfc00,  151 }, { 0xffff,  157 },
   /* 0x324 */ { 0x000d,  173 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x328 */ { 0x0000,    0 }, { 0x6340,  176 }, { 0x03f0,  181 }, { 0x0000,    0 },
@@ -70,12 +70,12 @@ static const u_int16_t mac_japanese_uni2_page32[][2] = {
   /* 0x33c */ { 0x2810,  242 }, { 0x0010,  245 },
 };
 
-static const u_int16_t mac_japanese_uni2_pagee0[][2] = {
+static const uint16_t mac_japanese_uni2_pagee0[][2] = {
   /* 0xe00 */ { 0xffff,  246 }, { 0xffff,  262 }, { 0x0fff,  278 }, { 0x001f,  290 },
   /* 0xe04 */ { 0x7f00,  295 },
 };
 
-static const u_int16_t mac_japanese_uni2_pagefe[][2] = {
+static const uint16_t mac_japanese_uni2_pagefe[][2] = {
   /* 0xfe3 */ { 0xffeb,  302 },
   /* 0xfe4 */ { 0x001f,  316 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0xfe8 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
@@ -95,7 +95,7 @@ static const cjk_index_t mac_japanese_uni2_index[] = {
   { { 0, 0 }, NULL }
 };
 
-static const u_int16_t mac_japanese_uni2_charset[] = {
+static const uint16_t mac_japanese_uni2_charset[] = {
   0x0080, 0x00a0, 0x00fd, 0x815c, 0xffff, 0xffff, 0x8656, 0x8650,
   0x869b, 0x869d, 0x00fe, 0x859f, 0x85a0, 0x85a1, 0x85a2, 0x85a3,
   0x85a4, 0x85a5, 0x85a6, 0x85a7, 0x85a8, 0x85a9, 0x85aa, 0x85b3,
@@ -139,16 +139,16 @@ static const u_int16_t mac_japanese_uni2_charset[] = {
   0xeb78, 0x815f,
 };
 
-static const u_int16_t mac_japanese_2uni_page00[][2] = {
+static const uint16_t mac_japanese_2uni_page00[][2] = {
   /* 0x008 */ { 0x0001,    0 }, { 0x0000,    0 }, { 0x0001,    1 }, { 0x0000,    0 },
   /* 0x00c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0xe000,    2 },
 };
 
-static const u_int16_t mac_japanese_2uni_page81[][2] = {
+static const uint16_t mac_japanese_2uni_page81[][2] = {
   /* 0x815 */ { 0x9000,    5 },
 };
 
-static const u_int16_t mac_japanese_2uni_page85[][2] = {
+static const uint16_t mac_japanese_2uni_page85[][2] = {
   /* 0x854 */ { 0xffff,    7 }, { 0xc00f,   23 }, { 0xffff,   29 }, { 0x7003,   45 },
   /* 0x858 */ { 0x003f,   50 }, { 0x87fe,   56 }, { 0x3fff,   67 }, { 0xfff8,   81 },
   /* 0x85c */ { 0x0003,   94 }, { 0xf800,   96 }, { 0xffff,  101 }, { 0x001f,  117 },
@@ -164,7 +164,7 @@ static const u_int16_t mac_japanese_2uni_page85[][2] = {
   /* 0x884 */ { 0x0007,  257 }, { 0x0030,  260 }, { 0x3d00,  262 },
 };
 
-static const u_int16_t mac_japanese_2uni_pageeb[][2] = {
+static const uint16_t mac_japanese_2uni_pageeb[][2] = {
   /* 0xeb4 */ { 0x0006,  267 }, { 0x3803,  269 }, { 0xfe1f,  274 }, { 0x07ff,  286 },
   /* 0xeb8 */ { 0x0002,  297 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0xebc */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
@@ -185,7 +185,7 @@ static const cjk_index_t mac_japanese_2uni_index[] = {
   { { 0, 0 }, NULL }
 };
 
-static const u_int16_t mac_japanese_2uni_charset[] = {
+static const uint16_t mac_japanese_2uni_charset[] = {
   0x005c, 0x00a0, 0x00a9, 0x2122, 0xe003, 0x2014, 0xff3c, 0x2460,
   0x2461, 0x2462, 0x2463, 0x2464, 0x2465, 0x2466, 0x2467, 0x2468,
   0x2469, 0x246a, 0x246b, 0x246c, 0x246d, 0x246e, 0x246f, 0x2470,
@@ -228,7 +228,7 @@ static const u_int16_t mac_japanese_2uni_charset[] = {
   0xe019, 0xe01a, 0xe01b, 0xe01c, 0xe01d, 0xe01e, 0xe01f, 0xe020,
 };
 
-static const u_int32_t mac_japanese_compose[] = {
+static const uint32_t mac_japanese_compose[] = {
   0x2010f87e, 0x2016f87e, 0x2026f87e, 0x2026f87f,
   0x21e6f87a, 0x21e7f87a, 0x21e8f87a, 0x21e9f87a,
   0x3001f87e, 0x3002f87e, 0x301cf87e, 0x3041f87e,
index a16f4a0359997d8bcc166d9cb2331444f318816e..26f387d78fa9bf8e0845d6d49135c9140c8efad5 100644 (file)
@@ -43,13 +43,13 @@ struct charset_functions charset_mac_korean = {
   NULL, NULL
 };
 
-static size_t mac_korean_char_push(u_int8_t* out, const ucs2_t* in, size_t* size)
+static size_t mac_korean_char_push(uint8_t* out, const ucs2_t* in, size_t* size)
 {
   ucs2_t wc = in[0];
 
   if ((wc & ~7) == 0xf860) {
     wc = cjk_compose_seq(in, size, mac_korean_compose,
-                        sizeof(mac_korean_compose) / sizeof(u_int32_t));
+                        sizeof(mac_korean_compose) / sizeof(uint32_t));
     if (!wc) return (size_t)-1;
   } else if ((wc & 0xf000) == 0xe000) {
     *size = 1;
@@ -62,7 +62,7 @@ static size_t mac_korean_char_push(u_int8_t* out, const ucs2_t* in, size_t* size
           (comb >= 0x0300 && comb <= 0x036f) ||
           (comb >= 0x20d0 && comb <= 0x20ea)) {
       ucs2_t comp = cjk_compose(wc, comb, mac_korean_compose,
-                               sizeof(mac_korean_compose) / sizeof(u_int32_t));
+                               sizeof(mac_korean_compose) / sizeof(uint32_t));
       if (!comp) break;
       wc = comp;
       if (++n == *size) break;
@@ -73,7 +73,7 @@ static size_t mac_korean_char_push(u_int8_t* out, const ucs2_t* in, size_t* size
     *size = 1;
   }
   if (wc <= 0x7f) {
-    out[0] = (u_int8_t)wc;
+    out[0] = (uint8_t)wc;
     return 1;
   }
   return cjk_char_push(cjk_lookup(wc, mac_korean_uni2_index,
@@ -87,9 +87,9 @@ static size_t mac_korean_push(void *cd, char **inbuf, size_t *inbytesleft,
                          cd, inbuf, inbytesleft, outbuf, outbytesleft);
 }
 
-static size_t mac_korean_char_pull(ucs2_t* out, const u_int8_t* in, size_t* size)
+static size_t mac_korean_char_pull(ucs2_t* out, const uint8_t* in, size_t* size)
 {
-  u_int16_t c = in[0];
+  uint16_t c = in[0];
 
   if (c <= 0x7f) {
     *size = 1;
@@ -97,7 +97,7 @@ static size_t mac_korean_char_pull(ucs2_t* out, const u_int8_t* in, size_t* size
     return 1;
   } else if (c >= 0xa1 && c <= 0xfe) {
     if (*size >= 2) {
-      u_int8_t c2 = in[1];
+      uint8_t c2 = in[1];
       if ((c2 >= 0x41 && c2 <= 0x7d) || (c2 >= 0x81 && c2 <= 0xfe)) {
        *size = 2;
        c = (c << 8) + c2;
index 4e990533d266f78ed40190a632a5299d716aa6fb..2febaa28779b7c55d42ed29c13edf207dcc5e306 100644 (file)
  * http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/
  */
 
-static const u_int16_t mac_korean_uni2_page00[][2] = {
+static const uint16_t mac_korean_uni2_page00[][2] = {
   /* 0x00a */ { 0x7a2d,    0 }, { 0x0880,    9 },
 };
 
-static const u_int16_t mac_korean_uni2_page02[][2] = {
+static const uint16_t mac_korean_uni2_page02[][2] = {
   /* 0x02b */ { 0x1000,   11 },
   /* 0x02c */ { 0x0000,    0 }, { 0x1001,   12 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x030 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
@@ -33,7 +33,7 @@ static const u_int16_t mac_korean_uni2_page02[][2] = {
   /* 0x03c */ { 0x0000,    0 }, { 0x0020,   14 },
 };
 
-static const u_int16_t mac_korean_uni2_page20[][2] = {
+static const uint16_t mac_korean_uni2_page20[][2] = {
   /* 0x201 */ { 0x8878,   15 }, { 0x0004,   21 }, { 0x5670,   22 },
   /* 0x204 */ { 0x7284,   29 }, { 0x0002,   35 }, { 0x0000,    0 }, { 0x7c00,   36 },
   /* 0x208 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x1200,   41 }, { 0x0000,    0 },
@@ -49,7 +49,7 @@ static const u_int16_t mac_korean_uni2_page20[][2] = {
   /* 0x230 */ { 0x0040,  118 }, { 0x0010,  119 },
 };
 
-static const u_int16_t mac_korean_uni2_page24[][2] = {
+static const uint16_t mac_korean_uni2_page24[][2] = {
   /* 0x246 */ { 0x8000,  120 }, { 0x000f,  121 },
   /* 0x248 */ { 0x00f8,  125 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0xffc0,  130 },
   /* 0x24c */ { 0xffff,  140 }, { 0x0000,    0 }, { 0xf800,  156 }, { 0x001f,  161 },
@@ -66,7 +66,7 @@ static const u_int16_t mac_korean_uni2_page24[][2] = {
   /* 0x278 */ { 0xfc00,  210 }, { 0x581f,  216 }, { 0x0012,  224 }, { 0x0024,  226 },
 };
 
-static const u_int16_t mac_korean_uni2_page29[][2] = {
+static const uint16_t mac_korean_uni2_page29[][2] = {
   /* 0x293 */ { 0x02f0,  228 },
   /* 0x294 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x003c,  233 }, { 0x0000,    0 },
   /* 0x298 */ { 0x0062,  237 }, { 0x0180,  240 }, { 0x0008,  242 }, { 0xc000,  243 },
@@ -77,21 +77,21 @@ static const u_int16_t mac_korean_uni2_page29[][2] = {
   /* 0x2ac */ { 0x1860,  253 }, { 0x0000,    0 }, { 0x0100,  257 },
 };
 
-static const u_int16_t mac_korean_uni2_page30[][2] = {
+static const uint16_t mac_korean_uni2_page30[][2] = {
   /* 0x301 */ { 0xd3c4,  258 }, { 0x0001,  266 }, { 0x0040,  267 },
 };
 
-static const u_int16_t mac_korean_uni2_page32[][2] = {
+static const uint16_t mac_korean_uni2_page32[][2] = {
   /* 0x323 */ { 0x0202,  268 },
   /* 0x324 */ { 0x0000,    0 }, { 0x07fe,  270 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x328 */ { 0xfc00,  280 }, { 0x4011,  286 }, { 0x0020,  289 },
 };
 
-static const u_int16_t mac_korean_uni2_page33[][2] = {
+static const uint16_t mac_korean_uni2_page33[][2] = {
   /* 0x33c */ { 0x0800,  290 },
 };
 
-static const u_int16_t mac_korean_uni2_pagee0[][2] = {
+static const uint16_t mac_korean_uni2_pagee0[][2] = {
   /* 0xe00 */ { 0xffff,  291 }, { 0xffff,  307 }, { 0xffff,  323 }, { 0xffff,  339 },
   /* 0xe04 */ { 0xffff,  355 }, { 0xffff,  371 }, { 0xffff,  387 }, { 0xffff,  403 },
   /* 0xe08 */ { 0xffff,  419 }, { 0xffff,  435 }, { 0xffff,  451 }, { 0xffff,  467 },
@@ -111,12 +111,12 @@ static const u_int16_t mac_korean_uni2_pagee0[][2] = {
   /* 0xe40 */ { 0x0000,    0 }, { 0x1ffc, 1126 },
 };
 
-static const u_int16_t mac_korean_uni2_pagef8[][2] = {
+static const uint16_t mac_korean_uni2_pagef8[][2] = {
   /* 0xf80 */ { 0x1fe0, 1137 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x2000, 1145 },
   /* 0xf84 */ { 0xffff, 1146 },
 };
 
-static const u_int16_t mac_korean_uni2_pagefe[][2] = {
+static const uint16_t mac_korean_uni2_pagefe[][2] = {
   /* 0xfe5 */ { 0x0600, 1162 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0xfe8 */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0xfec */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
@@ -141,7 +141,7 @@ static const cjk_index_t mac_korean_uni2_index[] = {
   { { 0, 0 }, NULL }
 };
 
-static const u_int16_t mac_korean_uni2_charset[] = {
+static const uint16_t mac_korean_uni2_charset[] = {
   0x0080, 0xa1cb, 0xa1cc, 0xa1cd, 0x0083, 0xa65c, 0xa1fe, 0xffff,
   0xffff, 0xa1a4, 0xa65d, 0xa198, 0xa2b0, 0xa2a6, 0xa76a, 0xa1a9,
   0xa1aa, 0xffff, 0xa1ab, 0xa170, 0xa16f, 0xa655, 0xa5de, 0xadad,
@@ -291,12 +291,12 @@ static const u_int16_t mac_korean_uni2_charset[] = {
   0xffff, 0xffff,
 };
 
-static const u_int16_t mac_korean_2uni_page00[][2] = {
+static const uint16_t mac_korean_2uni_page00[][2] = {
   /* 0x008 */ { 0x001f,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 },
   /* 0x00c */ { 0x0000,    0 }, { 0x0000,    0 }, { 0x0000,    0 }, { 0x8000,    5 },
 };
 
-static const u_int16_t mac_korean_2uni_pagea1[][2] = {
+static const uint16_t mac_korean_2uni_pagea1[][2] = {
   /* 0xa14 */ { 0xfffe,    6 }, { 0xffff,   21 }, { 0xffff,   37 }, { 0x3fff,   53 },
   /* 0xa18 */ { 0xfffe,   67 }, { 0xf7ff,   82 }, { 0x2e11,   97 }, { 0x0000,    0 },
   /* 0xa1c */ { 0x3800,  103 }, { 0x0000,    0 }, { 0x3000,  106 }, { 0x4000,  108 },
@@ -355,7 +355,7 @@ static const cjk_index_t mac_korean_2uni_index[] = {
   { { 0, 0 }, NULL }
 };
 
-static const u_int16_t mac_korean_2uni_charset[] = {
+static const uint16_t mac_korean_2uni_charset[] = {
   0x00a0, 0x20a9, 0xe022, 0x00a9, 0xe41c, 0xe02b, 0xe12a, 0xe12e,
   0xe128, 0xe12c, 0xe129, 0xe12d, 0xe130, 0xe132, 0xe125, 0xe126,
   0xe123, 0xe124, 0xfe59, 0xfe5a, 0xe413, 0xe415, 0xe118, 0xe11e,
@@ -503,7 +503,7 @@ static const u_int16_t mac_korean_2uni_charset[] = {
   0x2036, 0xe02e, 0x2035, 0xe02c, 0xe08d, 0xe001,
 };
 
-static const u_int32_t mac_korean_compose[] = {
+static const uint32_t mac_korean_compose[] = {
   0x0021f877, 0x0021f87f, 0x0028f87c, 0x0028f87f,
   0x0029f87c, 0x0029f87f, 0x002af877, 0x002d0308,
   0x003020de, 0x003120de, 0x003220de, 0x003320de,
index e703d2149332fb38b806f5564f17755cb847d1ad..34ccaaf93ee7f0a93d837de63e07ed0a22ee9293 100644 (file)
@@ -29,7 +29,8 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 #include <stdlib.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/unicode.h>
 
 #include "mac_roman.h"
index 44b18a13ef3946086f9870f4a38e3332d7a43a7a..619f4b015ea6cbded179e81eb3a65230a3dd53c5 100644 (file)
@@ -28,7 +28,8 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 #include <stdlib.h>
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
+
 #include <atalk/unicode.h>
 
 #include "mac_turkish.h"
index 17125004d7fde59c4e3d39ff8af39bdd75d8a6e9..7c5eb67e3ce0ddd653696ef014d657d324e07c15 100644 (file)
@@ -39,8 +39,8 @@
 #ifdef HAVE_USABLE_ICONV
 #include <iconv.h>
 #endif
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/unicode.h>
 #include <atalk/logger.h>
 #include "byteorder.h"
index c3146d0c65caed582f04cea18babfe9fc5fcaf22..896a2611e6b4857485b7a5e85b7a2db146ecdc3c 100644 (file)
@@ -29,8 +29,8 @@
 #endif /* HAVE_CONFIG_H */
 #include <stdlib.h>
 #include <errno.h>
+#include <arpa/inet.h>
 
-#include <netatalk/endian.h>
 #include <atalk/unicode.h>
 #include <atalk/logger.h>
 #include <atalk/unicode.h>
index decd8c0a5019980274e81404200f2de0573c0bb9..ce3355df980c84c0f65e65f13f9b55ddd6556a86 100644 (file)
@@ -19,8 +19,7 @@
 #include <sys/stat.h>
 #include <atalk/logger.h>
 #include <errno.h>
-
-#include <netatalk/endian.h>
+#include <arpa/inet.h>
 
 #include <atalk/unicode.h>
 #include "precompose.h"
@@ -39,8 +38,8 @@ int strlower_w(ucs2_t *s)
        while (*s) {
                if ((0xD800 <= *s) && (*s < 0xDC00)) {
                        if ((0xDC00 <= s[1]) && (s[1] < 0xE000)) {
-                               u_int32_t s_sp = (u_int32_t)*s << 16 | (u_int32_t)s[1];
-                               u_int32_t v_sp = tolower_sp(s_sp);
+                               uint32_t s_sp = (uint32_t)*s << 16 | (uint32_t)s[1];
+                               uint32_t v_sp = tolower_sp(s_sp);
                                if (v_sp != s_sp) {
                                        *s = v_sp >> 16;
                                        s++;
@@ -73,8 +72,8 @@ int strupper_w(ucs2_t *s)
        while (*s) {
                if ((0xD800 <= *s) && (*s < 0xDC00)) {
                        if ((0xDC00 <= s[1]) && (s[1] < 0xE000)) {
-                               u_int32_t s_sp = (u_int32_t)*s << 16 | (u_int32_t)s[1];
-                               u_int32_t v_sp = toupper_sp(s_sp);
+                               uint32_t s_sp = (uint32_t)*s << 16 | (uint32_t)s[1];
+                               uint32_t v_sp = toupper_sp(s_sp);
                                if (v_sp != s_sp) {
                                        *s = v_sp >> 16;
                                        s++;
@@ -105,7 +104,7 @@ int islower_w(ucs2_t c)
        return ( c == tolower_w(c));
 }
 
-int islower_sp(u_int32_t c_sp)
+int islower_sp(uint32_t c_sp)
 {
        return ( c_sp == tolower_sp(c_sp));
 }
@@ -121,7 +120,7 @@ int isupper_w(ucs2_t c)
        return ( c == toupper_w(c));
 }
 
-int isupper_sp(u_int32_t c_sp)
+int isupper_sp(uint32_t c_sp)
 {
        return ( c_sp == toupper_sp(c_sp));
 }
@@ -188,11 +187,11 @@ ucs2_t *strcasechr_w(const ucs2_t *s, ucs2_t c)
        return NULL;
 }
 
-ucs2_t *strcasechr_sp(const ucs2_t *s, u_int32_t c_sp)
+ucs2_t *strcasechr_sp(const ucs2_t *s, uint32_t c_sp)
 {
        if (*s == 0) return NULL;
        while (s[1] != 0) {
-               if (tolower_sp(c_sp) == tolower_sp((u_int32_t)*s << 16 | (u_int32_t)s[1])) return (ucs2_t *)s;
+               if (tolower_sp(c_sp) == tolower_sp((uint32_t)*s << 16 | (uint32_t)s[1])) return (ucs2_t *)s;
                s++;
        }
 
@@ -263,7 +262,7 @@ ucs2_t *strcasestr_w(const ucs2_t *s, const ucs2_t *ins)
 
        if ((0xD800 <= *ins) && (*ins < 0xDC00)) {
                if ((0xDC00 <= ins[1]) && (ins[1] < 0xE000)) {
-                       u_int32_t ins_sp = (u_int32_t)*ins << 16 | (u_int32_t)ins[1];
+                       uint32_t ins_sp = (uint32_t)*ins << 16 | (uint32_t)ins[1];
                        while ((r = strcasechr_sp(r, ins_sp))) {
                                if (strncasecmp_w(r, ins, inslen) == 0) return r;
                                r++;
@@ -292,7 +291,7 @@ int strcasecmp_w(const ucs2_t *a, const ucs2_t *b)
 
        while (*a && *b) {
                if ((0xD800 <= *a) && (*a < 0xDC00)) {
-                       if (ret = tolower_sp((u_int32_t)*a << 16 | (u_int32_t)a[1]) - tolower_sp((u_int32_t)*b << 16 | (u_int32_t)b[1])) return ret;
+                       if (ret = tolower_sp((uint32_t)*a << 16 | (uint32_t)a[1]) - tolower_sp((uint32_t)*b << 16 | (uint32_t)b[1])) return ret;
                        a++;
                        b++;
                        if (!(*a && *b)) return (tolower_w(*a) - tolower_w(*b)); /* avoid buffer over run */
@@ -318,7 +317,7 @@ int strncasecmp_w(const ucs2_t *a, const ucs2_t *b, size_t len)
 
        while ((n < len) && *a && *b) {
                if ((0xD800 <= *a) && (*a < 0xDC00)) {
-                       if (ret = tolower_sp((u_int32_t)*a << 16 | (u_int32_t)a[1]) - tolower_sp((u_int32_t)*b << 16 | (u_int32_t)b[1])) return ret;
+                       if (ret = tolower_sp((uint32_t)*a << 16 | (uint32_t)a[1]) - tolower_sp((uint32_t)*b << 16 | (uint32_t)b[1])) return ret;
                        a++;
                        b++;
                        n++;
@@ -438,7 +437,7 @@ static ucs2_t do_precomposition(unsigned int base, unsigned int comb)
        int min = 0;
        int max = PRECOMP_COUNT - 1;
        int mid;
-       u_int32_t sought = (base << 16) | comb, that;
+       uint32_t sought = (base << 16) | comb, that;
 
        /* binary search */
        while (max >= min) {
@@ -457,17 +456,17 @@ static ucs2_t do_precomposition(unsigned int base, unsigned int comb)
 }
 
 /* ------------------------ */
-static u_int32_t do_precomposition_sp(unsigned int base_sp, unsigned int comb_sp) 
+static uint32_t do_precomposition_sp(unsigned int base_sp, unsigned int comb_sp) 
 {
        int min = 0;
        int max = PRECOMP_SP_COUNT - 1;
        int mid;
-       u_int64_t sought_sp = ((u_int64_t)base_sp << 32) | (u_int64_t)comb_sp, that_sp;
+       uint64_t sought_sp = ((uint64_t)base_sp << 32) | (uint64_t)comb_sp, that_sp;
 
        /* binary search */
        while (max >= min) {
                mid = (min + max) / 2;
-               that_sp = ((u_int64_t)precompositions_sp[mid].base_sp << 32) | ((u_int64_t)precompositions_sp[mid].comb_sp);
+               that_sp = ((uint64_t)precompositions_sp[mid].base_sp << 32) | ((uint64_t)precompositions_sp[mid].comb_sp);
                if (that_sp < sought_sp) {
                        min = mid + 1;
                } else if (that_sp > sought_sp) {
@@ -481,13 +480,13 @@ static u_int32_t do_precomposition_sp(unsigned int base_sp, unsigned int comb_sp
 }
 
 /* -------------------------- */
-static u_int32_t do_decomposition(ucs2_t base) 
+static uint32_t do_decomposition(ucs2_t base) 
 {
        int min = 0;
        int max = DECOMP_COUNT - 1;
        int mid;
-       u_int32_t sought = base;
-       u_int32_t result, that;
+       uint32_t sought = base;
+       uint32_t result, that;
 
        /* binary search */
        while (max >= min) {
@@ -507,14 +506,14 @@ static u_int32_t do_decomposition(ucs2_t base)
 }
 
 /* -------------------------- */
-static u_int64_t do_decomposition_sp(unsigned int base_sp) 
+static uint64_t do_decomposition_sp(unsigned int base_sp) 
 {
        int min = 0;
        int max = DECOMP_SP_COUNT - 1;
        int mid;
-       u_int32_t sought_sp = base_sp;
-       u_int32_t that_sp;
-       u_int64_t result_sp;
+       uint32_t sought_sp = base_sp;
+       uint32_t that_sp;
+       uint64_t result_sp;
 
        /* binary search */
        while (max >= min) {
@@ -525,7 +524,7 @@ static u_int64_t do_decomposition_sp(unsigned int base_sp)
                } else if (that_sp > sought_sp) {
                        max = mid - 1;
                } else {
-                       result_sp = ((u_int64_t)decompositions_sp[mid].base_sp << 32) | ((u_int64_t)decompositions_sp[mid].comb_sp);
+                       result_sp = ((uint64_t)decompositions_sp[mid].base_sp << 32) | ((uint64_t)decompositions_sp[mid].comb_sp);
                        return result_sp;
                }
        }
@@ -552,11 +551,11 @@ size_t precompose_w (ucs2_t *name, size_t inplen, ucs2_t *comp, size_t *outlen)
 {
        size_t i;
        ucs2_t base, comb;
-       u_int32_t base_sp, comb_sp;
+       uint32_t base_sp, comb_sp;
        ucs2_t *in, *out;
        ucs2_t lindex, vindex;
        ucs2_t result;
-       u_int32_t result_sp;
+       uint32_t result_sp;
        size_t o_len = *outlen;
        
        if (!inplen || (inplen & 1) || inplen > o_len)
@@ -605,9 +604,9 @@ size_t precompose_w (ucs2_t *name, size_t inplen, ucs2_t *comp, size_t *outlen)
                /* Binary Search for Surrogate Pair */
                else if ((0xD800 <= base) && (base < 0xDC00)) {
                        if ((0xDC00 <= comb) && (comb < 0xE000) && (i + 6 <= inplen)) {
-                               base_sp = ((u_int32_t)base << 16) | (u_int32_t)comb;
+                               base_sp = ((uint32_t)base << 16) | (uint32_t)comb;
                                do {
-                                       comb_sp = ((u_int32_t)in[1] << 16) | (u_int32_t)in[2];
+                                       comb_sp = ((uint32_t)in[1] << 16) | (uint32_t)in[2];
                                        if (result_sp = do_precomposition_sp(base_sp, comb_sp)) {
                                                base_sp = result_sp;
                                                i += 4;
@@ -664,11 +663,11 @@ size_t decompose_w (ucs2_t *name, size_t inplen, ucs2_t *comp, size_t *outlen)
        size_t i;
        size_t comblen;
        ucs2_t base, comb[COMBBUFLEN];
-       u_int32_t base_sp;
+       uint32_t base_sp;
        ucs2_t sindex, tjamo;
        ucs2_t *in, *out;
        unsigned int result;
-       u_int64_t result_sp;
+       uint64_t result_sp;
        size_t o_len = *outlen;
 
        if (!inplen || (inplen & 1))
@@ -706,7 +705,7 @@ size_t decompose_w (ucs2_t *name, size_t inplen, ucs2_t *comp, size_t *outlen)
                /* Binary Search for Surrogate Pair */
                else if ((0xD800 <= base) && (base < 0xDC00)) {
                        if (i + 2 < inplen) {
-                               base_sp =  ((u_int32_t)base << 16) | (u_int32_t)in[1];
+                               base_sp =  ((uint32_t)base << 16) | (uint32_t)in[1];
                                do {
                                        if ( !(result_sp = do_decomposition_sp(base_sp))) break;
                                        comblen += 2;
index c1d674e78984fb5b219d0d0b50dcecfbd85e610e..c38bb9ea753c5d763ac8930fc94d2f6945fcd613 100644 (file)
@@ -4,5 +4,4 @@ Makefile.in
 *.la
 .deps
 .libs
-.gitignore
-atalk_addr.o bprint.o fault.o getiface.o locking.o logger.o module.o server_child.o server_ipc.o server_lock.o socket.o strcasestr.o strdicasecmp.o strlcpy.o unix.o volinfo.o
+*.o
index af5d3c9ff6b10515d0aaebc26b6350ea3531c022..65ad1d6ca9704b8e535a1aa6e71d2d1b5847e7fd 100644 (file)
@@ -1,11 +1,10 @@
 # Makefile.am for libatalk/util/
 
-noinst_LTLIBRARIES = libutil.la
+pkgconfdir = @PKGCONFDIR@
 
-AM_CFLAGS = -I$(top_srcdir)/sys
+noinst_LTLIBRARIES = libutil.la
 
 libutil_la_SOURCES = \
-       atalk_addr.c    \
        bprint.c        \
        cnid.c          \
        fault.c         \
@@ -13,17 +12,22 @@ libutil_la_SOURCES = \
        locking.c   \
        logger.c        \
        module.c        \
+       netatalk_conf.c \
        queue.c     \
        server_child.c  \
        server_ipc.c    \
        server_lock.c   \
        socket.c        \
-       strcasestr.c    \
        strdicasecmp.c  \
-       strlcpy.c       \
-       volinfo.c \
        unix.c
 
+libutil_la_CFLAGS = \
+       -D_PATH_CONFDIR='"$(pkgconfdir)/"' \
+       -DSERVERTEXT='"$(SERVERTEXT)/"' \
+       -D_PATH_AFPDPWFILE='"$(pkgconfdir)/afppasswd"' \
+       -D_PATH_AFPDUAMPATH='"$(UAMS_PATH)/"' \
+       -D_PATH_STATEDIR='"$(localstatedir)/netatalk/"'
+
 if HAVE_ATFUNCS
 libutil_la_SOURCES += ftw.c
 endif
diff --git a/libatalk/util/atalk_addr.c b/libatalk/util/atalk_addr.c
deleted file mode 100644 (file)
index e151441..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifndef NO_DDP
-
-#include <sys/types.h>
-#include <netatalk/at.h>
-#include <netatalk/endian.h>
-#include <atalk/util.h>
-#include <ctype.h>
-
-/* 
- * Check whether "cp" is a valid ascii representation
- * of an AppleTalk address and convert to a binary address.
- * Examples of accepted forms are (in decimal, net of 4321,
- * node of 65):
- *
- *     4321.65
- *     0x10E1.41
- *     16.225.65
- *     0x10.E1.41
- *
- * If hex is used, and the first digit is one of A-F, the leading
- * 0x is redundant. Returns 1 if the address is valid, 0 if not.
- *
- * Unlike Internet addresses, AppleTalk addresses can have leading
- * 0's. This means that we can't support octal addressing.
- */
-
-int atalk_aton(char *cp, struct at_addr *addr)
-{
-    u_int32_t val, base, n;
-    char c;
-
-    val = 0; base = 10;
-    if ( *cp == '0' && ( *++cp == 'x' || *cp == 'X' )) {
-       base = 16, cp++;
-    }
-    if ( !isdigit( *cp ) && isxdigit( *cp )) {
-       base = 16;
-    }
-
-    for ( n = 0;; n++ ) {
-       while (( c = *cp ) != '\0') {
-           if ( isascii( c ) && isdigit( c )) {
-               val = (val * base) + (c - '0');
-               cp++;
-               continue;
-           }
-
-           if ( base == 16 && isascii( c ) && isxdigit( c )) {
-               val = ( val << 4 ) + ( c + 10 - ( islower( c ) ? 'a' : 'A' ));
-               cp++;
-               continue;
-           }
-           break;
-       }
-
-       if ( c != '.' && c != '\0' ) {
-           return( 0 );
-       }
-
-       switch ( n ) {
-       case 0:
-           if ( addr ) {
-               if ( val > 65535 ) {
-                   return( 0 );
-               }
-               addr->s_net = val;
-           }
-           if ( *cp++ ) {
-               val = 0;
-           } else {
-               break;
-           }
-           continue;
-
-       case 2:
-           if ( addr ) {
-               if ( addr->s_net > 255 ) {
-                   return( 0 );
-               }
-               addr->s_net <<= 8;
-               addr->s_net += addr->s_node;
-           }
-           /*FALLTHROUGH*/
-
-       case 1:
-           if ( addr ) {
-               if ( val > 255 ) {
-                   return( 0 );
-               }
-               addr->s_node = val;
-           }
-           if ( *cp++ ) {
-               val = 0;
-           } else {
-               break;
-           }
-           continue;
-
-       default:
-           return( 0 );
-       }
-       break;
-    }
-
-    if ( n < 1 ) {
-       return( 0 );
-    }
-    if ( addr ) {
-       addr->s_net = htons( addr->s_net );
-    }
-    return (1);
-}
-
-#endif  /* NO_DDP */
index 7841f6a4045566442366271bdb483173eb094a7c..87b5746f091df9dbfde1d3e1687120be332d309e 100644 (file)
@@ -2,7 +2,7 @@
 #include "config.h"
 #endif
 
-#ifdef DEBUG1
+#ifdef DEBUG
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
index 375309071d57bce7f5fd5317a69231069d343d52..0cc56d49514ea4ae5ba454a009c4bdf3e5620948 100644 (file)
@@ -48,7 +48,6 @@
 
 #include <atalk/util.h>
 #include <atalk/cnid.h>
-#include <atalk/volinfo.h>
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
 #include <atalk/logger.h>
index 2b9ef64455f403d34201c7936cc43ef6806e63cd..48c4fe058d715c094d9e5a9035866eade4d2bf1d 100644 (file)
@@ -36,7 +36,7 @@
 #include <atalk/logger.h>
 
 #ifndef SIGNAL_CAST
-#define SIGNAL_CAST (RETSIGTYPE (*)(int))
+#define SIGNAL_CAST (void (*)(int))
 #endif
 #ifndef SAFE_FREE /* Oh no this is also defined in tdb.h */
 #define SAFE_FREE(x) do { if ((x) != NULL) {free(x); x=NULL;} } while(0)
@@ -93,6 +93,7 @@ void netatalk_panic(const char *why)
        backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
        backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
 
+       LOG(log_severe, logtype_default, "PANIC: %s", why);
        LOG(log_severe, logtype_default, "BACKTRACE: %d stack frames:", backtrace_size);
        
        if (backtrace_strings) {
index 05af80b1d0b35cea7432f9ce38a5c69ec6c2237b..bf79fff7f49e62f63983583aeb0b2b7cb4934d0c 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-
-#ifdef HAVE_STDINT_H
 #include <stdint.h>
-#endif
-
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/ioctl.h>
index 241b22df092285aff506350c137d6c2122df9385..a7cdd2c12a402ecd8bd8d89a199ff4dd92b4cce2 100644 (file)
@@ -39,18 +39,18 @@ Netatalk 2001 (c)
 #define MAXLOGSIZE 512
 
 #define LOGLEVEL_STRING_IDENTIFIERS { \
-  "LOG_NOTHING",                      \
-  "LOG_SEVERE",                       \
-  "LOG_ERROR",                        \
-  "LOG_WARN",                         \
-  "LOG_NOTE",                         \
-  "LOG_INFO",                         \
-  "LOG_DEBUG",                        \
-  "LOG_DEBUG6",                       \
-  "LOG_DEBUG7",                       \
-  "LOG_DEBUG8",                       \
-  "LOG_DEBUG9",                       \
-  "LOG_MAXDEBUG"}                        
+  "NOTHING",                      \
+  "SEVERE",                       \
+  "ERROR",                        \
+  "WARN",                         \
+  "NOTE",                         \
+  "INFO",                         \
+  "DEBUG",                        \
+  "DEBUG6",                       \
+  "DEBUG7",                       \
+  "DEBUG8",                       \
+  "DEBUG9",                       \
+  "MAXDEBUG"}                        
 
 /* these are the string identifiers corresponding to each logtype */
 #define LOGTYPE_STRING_IDENTIFIERS { \
@@ -90,16 +90,20 @@ UAM_MODULE_EXPORT logtype_conf_t type_configs[logtype_end_of_list_marker] = {
     DEFAULT_LOG_CONFIG /* logtype_uams */
 };
 
+static void syslog_setup(int loglevel, enum logtypes logtype, int display_options, int facility);
+
 /* We use this in order to track the last n log messages in order to prevent flooding */
 #define LOG_FLOODING_MINCOUNT 5 /* this controls after how many consecutive messages must be detected
                                    before we start to hide them */
 #define LOG_FLOODING_MAXCOUNT 1000 /* this controls after how many consecutive messages we force a 
                                       "repeated x times" message */
 #define LOG_FLOODING_ARRAY_SIZE 3 /* this contols how many messages in flow we track */
+
 struct log_flood_entry {
     int count;
     unsigned int hash;
 };
+
 static struct log_flood_entry log_flood_array[LOG_FLOODING_ARRAY_SIZE];
 static int log_flood_entries;
 
@@ -136,56 +140,6 @@ static unsigned int hash_message(const char *message)
     return hash;
 }
 
-/*
- * If filename == NULL its for syslog logging, otherwise its for file-logging.
- * "unsetuplog" calls with loglevel == NULL.
- * loglevel == NULL means:
- *    if logtype == default
- *       disable logging
- *    else
- *       set to default logging
- */
-static void setuplog_internal(const char *loglevel, const char *logtype, const char *filename)
-{
-    unsigned int typenum, levelnum;
-
-    /* Parse logtype */
-    for( typenum=0; typenum < num_logtype_strings; typenum++) {
-        if (strcasecmp(logtype, arr_logtype_strings[typenum]) == 0)
-            break;
-    }
-    if (typenum >= num_logtype_strings) {
-        return;
-    }
-
-    /* Parse loglevel */
-    if (loglevel == NULL) {
-        levelnum = 0;
-    } else {
-        for(levelnum=1; levelnum < num_loglevel_strings; levelnum++) {
-            if (strcasecmp(loglevel, arr_loglevel_strings[levelnum]) == 0)
-                break;
-        }
-        if (levelnum >= num_loglevel_strings) {
-            return;
-        }
-    }
-
-    /* is this a syslog setup or a filelog setup ? */
-    if (filename == NULL) {
-        /* must be syslog */
-        syslog_setup(levelnum,
-                     typenum,
-                     logoption_ndelay | logoption_pid,
-                     logfacility_daemon);
-    } else {
-        /* this must be a filelog */
-        log_setup(filename, levelnum, typenum);
-    }
-
-    return;
-}
-
 static void generate_message_details(char *message_details_buffer,
                                      int message_details_buffer_length,
                                      int display_options,
@@ -279,11 +233,20 @@ static int get_syslog_equivalent(enum loglevels loglevel)
     }
 }
 
-/* =========================================================================
-   Global function definitions
-   ========================================================================= */
+/* Called by the LOG macro for syslog messages */
+static void make_syslog_entry(enum loglevels loglevel, enum logtypes logtype _U_, char *message)
+{
+    if ( !log_config.syslog_opened ) {
+        openlog(log_config.processname,
+                log_config.syslog_display_options,
+                log_config.syslog_facility);
+        log_config.syslog_opened = true;
+    }
+
+    syslog(get_syslog_equivalent(loglevel), "%s", message);
+}
 
-void log_init(void)
+static void log_init(void)
 {
     syslog_setup(log_info,
                  logtype_default,
@@ -291,7 +254,7 @@ void log_init(void)
                  logfacility_daemon);
 }
 
-void log_setup(const char *filename, enum loglevels loglevel, enum logtypes logtype)
+static void log_setup(const char *filename, enum loglevels loglevel, enum logtypes logtype)
 {
     uid_t process_uid;
 
@@ -407,7 +370,7 @@ void log_setup(const char *filename, enum loglevels loglevel, enum logtypes logt
 }
 
 /* Setup syslog logging */
-void syslog_setup(int loglevel, enum logtypes logtype, int display_options, int facility)
+static void syslog_setup(int loglevel, enum logtypes logtype, int display_options, int facility)
 {
     /* 
      * FIXME:
@@ -440,10 +403,60 @@ void syslog_setup(int loglevel, enum logtypes logtype, int display_options, int
         arr_loglevel_strings[loglevel]);
 }
 
-void log_close(void)
+/*
+ * If filename == NULL its for syslog logging, otherwise its for file-logging.
+ * "unsetuplog" calls with loglevel == NULL.
+ * loglevel == NULL means:
+ *    if logtype == default
+ *       disable logging
+ *    else
+ *       set to default logging
+ */
+static void setuplog_internal(const char *loglevel, const char *logtype, const char *filename)
 {
+    unsigned int typenum, levelnum;
+
+    /* Parse logtype */
+    for( typenum=0; typenum < num_logtype_strings; typenum++) {
+        if (strcasecmp(logtype, arr_logtype_strings[typenum]) == 0)
+            break;
+    }
+    if (typenum >= num_logtype_strings) {
+        return;
+    }
+
+    /* Parse loglevel */
+    if (loglevel == NULL) {
+        levelnum = 0;
+    } else {
+        for(levelnum=1; levelnum < num_loglevel_strings; levelnum++) {
+            if (strcasecmp(loglevel, arr_loglevel_strings[levelnum]) == 0)
+                break;
+        }
+        if (levelnum >= num_loglevel_strings) {
+            return;
+        }
+    }
+
+    /* is this a syslog setup or a filelog setup ? */
+    if (filename == NULL) {
+        /* must be syslog */
+        syslog_setup(levelnum,
+                     typenum,
+                     logoption_ndelay | logoption_pid,
+                     logfacility_daemon);
+    } else {
+        /* this must be a filelog */
+        log_setup(filename, levelnum, typenum);
+    }
+
+    return;
 }
 
+/* =========================================================================
+   Global function definitions
+   ========================================================================= */
+
 /* This function sets up the processname */
 void set_processname(const char *processname)
 {
@@ -451,19 +464,6 @@ void set_processname(const char *processname)
     log_config.processname[15] = 0;
 }
 
-/* Called by the LOG macro for syslog messages */
-static void make_syslog_entry(enum loglevels loglevel, enum logtypes logtype _U_, char *message)
-{
-    if ( !log_config.syslog_opened ) {
-        openlog(log_config.processname,
-                log_config.syslog_display_options,
-                log_config.syslog_facility);
-        log_config.syslog_opened = true;
-    }
-
-    syslog(get_syslog_equivalent(loglevel), "%s", message);
-}
-
 /* -------------------------------------------------------------------------
    make_log_entry has 1 main flaws:
    The message in its entirity, must fit into the tempbuffer.
@@ -619,57 +619,39 @@ exit:
     inlog = 0;
 }
 
-
-void setuplog(const char *logstr)
+void setuplog(const char *logstr, const char *logfile)
 {
-    char *ptr, *ptrbak, *logtype, *loglevel = NULL, *filename = NULL;
-    ptr = strdup(logstr);
-    ptrbak = ptr;
-
-    /* logtype */
-    logtype = ptr;
-
-    /* get loglevel */
-    ptr = strpbrk(ptr, " \t");
-    if (ptr) {
-        *ptr++ = 0;
-        while (*ptr && isspace(*ptr))
-            ptr++;
-        loglevel = ptr;
+    char *ptr, *save;
+    char *logtype, *loglevel;
+    char c;
+
+    save = ptr = strdup(logstr);
+
+    ptr = strtok(ptr, ", ");
 
-        /* get filename */
-        ptr = strpbrk(ptr, " \t");
-        if (ptr) {
-            *ptr++ = 0;
+    while (ptr) {
+        while (*ptr) {
             while (*ptr && isspace(*ptr))
                 ptr++;
+
+            logtype = ptr;
+            ptr = strpbrk(ptr, ":");
+            if (!ptr)
+                break;
+            *ptr = 0;
+
+            ptr++;
+            loglevel = ptr;
+            while (*ptr && !isspace(*ptr))
+                ptr++;
+            c = *ptr;
+            *ptr = 0;
+            setuplog_internal(loglevel, logtype, logfile);
+            *ptr = c;
         }
-        filename = ptr;
-        if (filename && *filename == 0)
-            filename = NULL;
+        ptr = strtok(NULL, ", ");
     }
 
-    /* finally call setuplog, filename can be NULL */
-    setuplog_internal(loglevel, logtype, filename);
-
-    free(ptrbak);
+    free(save);
 }
 
-void unsetuplog(const char *logstr)
-{
-    char *str, *logtype, *filename;
-
-    str = strdup(logstr);
-
-    /* logtype */
-    logtype = str;
-
-    /* get filename, can be NULL */
-    strtok(str, " \t");
-    filename = strtok(NULL, " \t");
-
-    /* finally call setuplog, filename can be NULL */
-    setuplog_internal(NULL, str, filename);
-
-    free(str);
-}
diff --git a/libatalk/util/netatalk_conf.c b/libatalk/util/netatalk_conf.c
new file mode 100644 (file)
index 0000000..4479116
--- /dev/null
@@ -0,0 +1,1602 @@
+/*
+  Copyright (c) 2012 Frank Lahm <franklahm@gmail.com>
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <pwd.h>
+#include <grp.h>
+#include <utime.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <inttypes.h>
+#include <time.h>
+#include <regex.h>
+#if HAVE_LOCALE_H
+#include <locale.h>
+#endif
+#if HAVE_LANGINFO_H
+#include <langinfo.h>
+#endif
+
+#include <atalk/afp.h>
+#include <atalk/util.h>
+#include <atalk/logger.h>
+#include <atalk/ea.h>
+#include <atalk/globals.h>
+#include <atalk/errchk.h>
+#include <atalk/iniparser.h>
+#include <atalk/unix.h>
+#include <atalk/cnid.h>
+#include <atalk/dsi.h>
+#include <atalk/uuid.h>
+#include <atalk/netatalk_conf.h>
+#include <atalk/bstrlib.h>
+
+#define VOLPASSLEN  8
+#ifndef UUID_PRINTABLE_STRING_LENGTH
+#define UUID_PRINTABLE_STRING_LENGTH 37
+#endif
+
+#define IS_VAR(a, b) (strncmp((a), (b), 2) == 0)
+
+/**************************************************************
+ * Locals
+ **************************************************************/
+
+static int have_uservol = 0; /* whether there's generic user home share in config ("~" or "~/path", but not "~user") */
+static struct vol *Volumes = NULL;
+static uint16_t    lastvid = 0;
+
+/* 
+ * Get a volumes UUID from the config file.
+ * If there is none, it is generated and stored there.
+ *
+ * Returns pointer to allocated storage on success, NULL on error.
+ */
+static char *get_vol_uuid(const AFPObj *obj, const char *volname)
+{
+    char *volname_conf;
+    char buf[1024], uuid[UUID_PRINTABLE_STRING_LENGTH], *p;
+    FILE *fp;
+    struct stat tmpstat;
+    int fd;
+    
+    if ((fp = fopen(obj->options.uuidconf, "r")) != NULL) {  /* read open? */
+        /* scan in the conf file */
+        while (fgets(buf, sizeof(buf), fp) != NULL) { 
+            p = buf;
+            while (p && isblank(*p))
+                p++;
+            if (!p || (*p == '#') || (*p == '\n'))
+                continue;                             /* invalid line */
+            if (*p == '"') {
+                p++;
+                if ((volname_conf = strtok( p, "\"" )) == NULL)
+                    continue;                         /* syntax error */
+            } else {
+                if ((volname_conf = strtok( p, " \t" )) == NULL)
+                    continue;                         /* syntax error: invalid name */
+            }
+            p = strchr(p, '\0');
+            p++;
+            if (*p == '\0')
+                continue;                             /* syntax error */
+            
+            if (strcmp(volname, volname_conf) != 0)
+                continue;                             /* another volume name */
+                
+            while (p && isblank(*p))
+                p++;
+
+            if (sscanf(p, "%36s", uuid) == 1 ) {
+                for (int i=0; uuid[i]; i++)
+                    uuid[i] = toupper(uuid[i]);
+                LOG(log_debug, logtype_afpd, "get_uuid('%s'): UUID: '%s'", volname, uuid);
+                fclose(fp);
+                return strdup(uuid);
+            }
+        }
+    }
+
+    if (fp)
+        fclose(fp);
+
+    /*  not found or no file, reopen in append mode */
+
+    if (stat(obj->options.uuidconf, &tmpstat)) {                /* no file */
+        if (( fd = creat(obj->options.uuidconf, 0644 )) < 0 ) {
+            LOG(log_error, logtype_afpd, "ERROR: Cannot create %s (%s).",
+                obj->options.uuidconf, strerror(errno));
+            return NULL;
+        }
+        if (( fp = fdopen( fd, "w" )) == NULL ) {
+            LOG(log_error, logtype_afpd, "ERROR: Cannot fdopen %s (%s).",
+                obj->options.uuidconf, strerror(errno));
+            close(fd);
+            return NULL;
+        }
+    } else if ((fp = fopen(obj->options.uuidconf, "a+")) == NULL) { /* not found */
+        LOG(log_error, logtype_afpd, "Cannot create or append to %s (%s).",
+            obj->options.uuidconf, strerror(errno));
+        return NULL;
+    }
+    fseek(fp, 0L, SEEK_END);
+    if(ftell(fp) == 0) {                     /* size = 0 */
+        fprintf(fp, "# DON'T TOUCH NOR COPY THOUGHTLESSLY!\n");
+        fprintf(fp, "# This file is auto-generated by afpd\n");
+        fprintf(fp, "# and stores UUIDs for Time Machine volumes.\n\n");
+    } else {
+        fseek(fp, -1L, SEEK_END);
+        if(fgetc(fp) != '\n') fputc('\n', fp); /* last char is \n? */
+    }                    
+    
+    /* generate uuid and write to file */
+    atalk_uuid_t id;
+    const char *cp;
+    randombytes((void *)id, 16);
+    cp = uuid_bin2string(id);
+
+    LOG(log_debug, logtype_afpd, "get_uuid('%s'): generated UUID '%s'", volname, cp);
+
+    fprintf(fp, "\"%s\"\t%36s\n", volname, cp);
+    fclose(fp);
+    
+    return strdup(cp);
+}
+
+/*
+  Check if the underlying filesystem supports EAs.
+  If not, switch to ea:ad.
+  As we can't check (requires write access) on ro-volumes, we switch ea:auto
+  volumes that are options:ro to ea:none.
+*/
+#define EABUFSZ 4
+static int do_check_ea_support(const struct vol *vol)
+{
+    int haseas;
+    const char *eaname = "org.netatalk.has-Extended-Attributes";
+    const char *eacontent = "yes";
+    char buf[EABUFSZ];
+
+    if (sys_lgetxattr(vol->v_path, eaname, buf, EABUFSZ) != -1)
+        return 1;
+
+    if (vol->v_flags & AFPVOL_RO) {
+        LOG(log_debug, logtype_afpd, "read-only volume '%s', can't test for EA support, assuming yes", vol->v_localname);
+        return 1;
+    }
+
+    become_root();
+
+    if ((sys_setxattr(vol->v_path, eaname, eacontent, strlen(eacontent) + 1, 0)) == 0) {
+        haseas = 1;
+    } else {
+        LOG(log_warning, logtype_afpd, "volume \"%s\" does not support Extended Attributes or read-only volume",
+            vol->v_localname);
+        haseas = 0;
+    }
+
+    unbecome_root();
+
+    return haseas;
+}
+
+static void check_ea_support(struct vol *vol)
+{
+    int haseas;
+
+    haseas = do_check_ea_support(vol);
+
+    if (vol->v_vfs_ea == AFPVOL_EA_AUTO) {
+        if (haseas)
+            vol->v_vfs_ea = AFPVOL_EA_SYS;
+        else
+            vol->v_vfs_ea = AFPVOL_EA_NONE;
+    }
+
+    if (vol->v_adouble == AD_VERSION_EA) {
+        if (!haseas)
+            vol->v_adouble = AD_VERSION2;
+    }
+}
+
+/*!
+ * Check whether a volume supports ACLs
+ *
+ * @param vol  (r) volume
+ *
+ * @returns        0 if not, 1 if yes
+ */
+static int check_vol_acl_support(const struct vol *vol)
+{
+    int ret = 0;
+
+#ifdef HAVE_SOLARIS_ACLS
+    ace_t *aces = NULL;
+    ret = 1;
+    if (get_nfsv4_acl(vol->v_path, &aces) == -1)
+        ret = 0;
+#endif
+#ifdef HAVE_POSIX_ACLS
+    acl_t acl = NULL;
+    ret = 1;
+    if ((acl = acl_get_file(vol->v_path, ACL_TYPE_ACCESS)) == NULL)
+        ret = 0;
+#endif
+
+#ifdef HAVE_SOLARIS_ACLS
+    if (aces) free(aces);
+#endif
+#ifdef HAVE_POSIX_ACLS
+    if (acl) acl_free(acl);
+#endif /* HAVE_POSIX_ACLS */
+
+    LOG(log_debug, logtype_afpd, "Volume \"%s\" ACL support: %s",
+        vol->v_path, ret ? "yes" : "no");
+    return ret;
+}
+
+/*
+ * Handle variable substitutions. here's what we understand:
+ * $b   -> basename of path
+ * $c   -> client ip/appletalk address
+ * $d   -> volume pathname on server
+ * $f   -> full name (whatever's in the gecos field)
+ * $g   -> group
+ * $h   -> hostname
+ * $i   -> client ip/appletalk address without port
+ * $s   -> server name (hostname if it doesn't exist)
+ * $u   -> username (guest is usually nobody)
+ * $v   -> volume name or basename if null
+ * $$   -> $
+ *
+ * This get's called from readvolfile with
+ * path = NULL, volname = NULL for xlating the volumes path
+ * path = path, volname = NULL for xlating the volumes name
+ * ... and from volumes options parsing code when xlating eg dbpath with
+ * path = path, volname = volname
+ *
+ * Using this information we can reject xlation of any variable depeninding on a login
+ * context which is not given in the afp master, where we must evaluate this whole stuff
+ * too for the Zeroconf announcements.
+ */
+static char *volxlate(const AFPObj *obj,
+                      char *dest,
+                      size_t destlen,
+                      const char *src,
+                      const struct passwd *pwd,
+                      const char *path,
+                      const char *volname)
+{
+    char *p, *r;
+    const char *q;
+    int len;
+    char *ret;
+    int xlatevolname = 0;
+
+    if (path && !volname)
+        /* cf above */
+        xlatevolname = 1;
+
+    if (!src) {
+        return NULL;
+    }
+    if (!dest) {
+        dest = calloc(destlen +1, 1);
+    }
+    ret = dest;
+    if (!ret) {
+        return NULL;
+    }
+    strlcpy(dest, src, destlen +1);
+    if ((p = strchr(src, '$')) == NULL) /* nothing to do */
+        return ret;
+
+    /* first part of the path. just forward to the next variable. */
+    len = MIN((size_t)(p - src), destlen);
+    if (len > 0) {
+        destlen -= len;
+        dest += len;
+    }
+
+    while (p && destlen > 0) {
+        /* now figure out what the variable is */
+        q = NULL;
+        if (IS_VAR(p, "$b")) {
+            if (path) {
+                if ((q = strrchr(path, '/')) == NULL)
+                    q = path;
+                else if (*(q + 1) != '\0')
+                    q++;
+            }
+        } else if (IS_VAR(p, "$c")) {
+            if (IS_AFP_SESSION(obj)) {
+                DSI *dsi = obj->dsi;
+                len = sprintf(dest, "%s:%u",
+                              getip_string((struct sockaddr *)&dsi->client),
+                              getip_port((struct sockaddr *)&dsi->client));
+                dest += len;
+                destlen -= len;
+            }
+        } else if (IS_VAR(p, "$d")) {
+            q = path;
+        } else if (pwd && IS_VAR(p, "$f")) {
+            if ((r = strchr(pwd->pw_gecos, ',')))
+                *r = '\0';
+            q = pwd->pw_gecos;
+        } else if (pwd && IS_VAR(p, "$g")) {
+            struct group *grp = getgrgid(pwd->pw_gid);
+            if (grp)
+                q = grp->gr_name;
+        } else if (IS_VAR(p, "$h")) {
+            q = obj->options.hostname;
+        } else if (IS_VAR(p, "$i")) {
+            DSI *dsi = obj->dsi;
+            q = getip_string((struct sockaddr *)&dsi->client);
+        } else if (IS_VAR(p, "$s")) {
+            q = obj->options.hostname;
+        } else if (obj->username[0] && IS_VAR(p, "$u")) {
+            char* sep = NULL;
+            if ( obj->options.ntseparator && (sep = strchr(obj->username, obj->options.ntseparator[0])) != NULL)
+                q = sep+1;
+            else
+                q = obj->username;
+        } else if (IS_VAR(p, "$v")) {
+            if (volname) {
+                q = volname;
+            }
+            else if (path) {
+                if ((q = strrchr(path, '/')) == NULL)
+                    q = path;
+                else if (*(q + 1) != '\0')
+                    q++;
+            }
+        } else if (IS_VAR(p, "$$")) {
+            q = "$";
+        } else
+            q = p;
+
+        /* copy the stuff over. if we don't understand something that we
+         * should, just skip it over. */
+        if (q) {
+            len = MIN(p == q ? 2 : strlen(q), destlen);
+            strncpy(dest, q, len);
+            dest += len;
+            destlen -= len;
+        }
+
+        /* stuff up to next $ */
+        src = p + 2;
+        p = strchr(src, '$');
+        len = p ? MIN((size_t)(p - src), destlen) : destlen;
+        if (len > 0) {
+            strncpy(dest, src, len);
+            dest += len;
+            destlen -= len;
+        }
+    }
+    return ret;
+}
+
+/*!
+ * check access list
+ *
+ * this function wants something of the following form:
+ * "@group,name,name2,@group2,name3" or "@group name name2 @group2 name3"
+ * A NULL argument allows everybody to have access.
+ * We return three things:
+ *     -1: no list
+ *      0: list exists, but name isn't in it
+ *      1: in list
+ */
+static int accessvol(const AFPObj *obj, const char *args, const char *name)
+{
+    char buf[MAXPATHLEN + 1], *p;
+    struct group *gr;
+
+    if (!args)
+        return -1;
+
+    strlcpy(buf, args, sizeof(buf));
+    if ((p = strtok(buf, ", ")) == NULL) /* nothing, return okay */
+        return -1;
+
+    while (p) {
+        if (*p == '@') { /* it's a group */
+            if ((gr = getgrnam(p + 1)) && gmem(gr->gr_gid, obj->ngroups, obj->groups))
+                return 1;
+        } else if (strcasecmp(p, name) == 0) /* it's a user name */
+            return 1;
+        p = strtok(NULL, ", ");
+    }
+
+    return 0;
+}
+
+static int hostaccessvol(const AFPObj *obj, const char *volname, const char *args)
+{
+    int mask_int;
+    char buf[MAXPATHLEN + 1], *p, *b;
+    struct sockaddr_storage client;
+    const DSI *dsi = obj->dsi;
+
+    if (!args || !dsi)
+        return -1;
+
+    strlcpy(buf, args, sizeof(buf));
+    if ((p = strtok_r(buf, ", ", &b)) == NULL) /* nothing, return okay */
+        return -1;
+
+    while (p) {
+        int ret;
+        char *ipaddr, *mask_char;
+        struct addrinfo hints, *ai;
+
+        ipaddr = strtok(p, "/");
+        mask_char = strtok(NULL,"/");
+
+        /* Get address from string with getaddrinfo */
+        memset(&hints, 0, sizeof hints);
+        hints.ai_family = AF_UNSPEC;
+        hints.ai_socktype = SOCK_STREAM;
+        if ((ret = getaddrinfo(ipaddr, NULL, &hints, &ai)) != 0) {
+            LOG(log_error, logtype_afpd, "hostaccessvol: getaddrinfo: %s\n", gai_strerror(ret));
+            continue;
+        }
+
+        /* netmask */
+        if (mask_char != NULL)
+            mask_int = atoi(mask_char); /* apply_ip_mask does range checking on it */
+        else {
+            if (ai->ai_family == AF_INET) /* IPv4 */
+                mask_int = 32;
+            else                          /* IPv6 */
+                mask_int = 128;
+        }
+
+        /* Apply mask to addresses */
+        client = dsi->client;
+        apply_ip_mask((struct sockaddr *)&client, mask_int);
+        apply_ip_mask(ai->ai_addr, mask_int);
+
+        if (compare_ip((struct sockaddr *)&client, ai->ai_addr) == 0) {
+            freeaddrinfo(ai);
+            return 1;
+        }
+
+        /* next address */
+        freeaddrinfo(ai);
+        p = strtok_r(NULL, ", ", &b);
+    }
+
+    return 0;
+}
+
+/*!
+ * Get option string from config, use default value if not set
+ *
+ * @param conf    (r) config handle
+ * @param vol     (r) volume name (must be section name ie wo vars expanded)
+ * @param opt     (r) option
+ * @param defsec  (r) if "option" is not found in "vol", try to find it in section "defsec"
+ * @param defval  (r) if neither "vol" nor "defsec" contain "opt" return "defval"
+ *
+ * @returns       const option string from "vol" or "defsec", or "defval" if not found
+ */
+static const char *getoption(const dictionary *conf, const char *vol, const char *opt, const char *defsec, const char *defval)
+{
+    EC_INIT;
+    const char *result;
+
+    if ((!(result = iniparser_getstring(conf, vol, opt, NULL))) && (defsec != NULL))
+        result = iniparser_getstring(conf, defsec, opt, NULL);
+    
+EC_CLEANUP:
+    if (result == NULL)
+        result = defval;
+    return result;
+}
+
+/*!
+ * Get boolean option from config, use default value if not set
+ *
+ * @param conf    (r) config handle
+ * @param vol     (r) volume name (must be section name ie wo vars expanded)
+ * @param opt     (r) option
+ * @param defsec  (r) if "option" is not found in "vol", try to find it in section "defsec"
+ * @param defval  (r) if neither "vol" nor "defsec" contain "opt" return "defval"
+ *
+ * @returns       const option string from "vol" or "defsec", or "defval" if not found
+ */
+static int getoption_bool(const dictionary *conf, const char *vol, const char *opt, const char *defsec, int defval)
+{
+    EC_INIT;
+    int result;
+
+    if (((result = iniparser_getboolean(conf, vol, opt, -1)) == -1) && (defsec != NULL))
+        result = iniparser_getboolean(conf, defsec, opt, -1);
+    
+EC_CLEANUP:
+    if (result == -1)
+        result = defval;
+    return result;
+}
+
+/*!
+ * Create volume struct
+ *
+ * @param obj      (r) handle
+ * @param pwd      (r) struct passwd of logged in user, may be NULL in master afpd
+ * @param section  (r) volume name wo variables expanded (exactly as in iniconfig)
+ * @param name     (r) volume name
+ * @param path     (r) volume path
+ * @param preset   (r) default preset, may be NULL
+ * @returns            vol on success, NULL on error
+ */
+static struct vol *creatvol(AFPObj *obj,
+                            const struct passwd *pwd,
+                            const char *section,
+                            const char *name,
+                            const char *path,
+                            const char *preset)
+{
+    EC_INIT;
+    struct vol  *volume = NULL;
+    int         suffixlen, vlen, tmpvlen, u8mvlen, macvlen;
+    char        tmpname[AFPVOL_U8MNAMELEN+1];
+    ucs2_t      u8mtmpname[(AFPVOL_U8MNAMELEN+1)*2], mactmpname[(AFPVOL_MACNAMELEN+1)*2];
+    char        suffix[6]; /* max is #FFFF */
+    uint16_t    flags;
+    const char  *val;
+    char        *p, *q;
+
+    LOG(log_debug, logtype_afpd, "createvol(volume: '%s', path: \"%s\", preset: '%s'): BEGIN",
+        name, path, preset ? preset : "-");
+
+    if ( name == NULL || *name == '\0' ) {
+        if ((name = strrchr( path, '/' )) == NULL) {
+            EC_FAIL;
+        }
+
+        /* if you wish to share /, you need to specify a name. */
+        if (*++name == '\0')
+            EC_FAIL;
+    }
+
+    /* Once volumes are loaded, we never change options again, we just delete em when they're removed from afp.conf */
+    for (struct vol *vol = Volumes; vol; vol = vol->v_next) {
+        if (STRCMP(path, ==, vol->v_path)) {
+            LOG(log_debug, logtype_afpd, "createvol('%s'): already loaded", name);
+            vol->v_deleted = 0;
+            volume = vol;
+            goto EC_CLEANUP;
+        }
+    }
+
+    /*
+     * Check allow/deny lists:
+     * allow -> either no list (-1), or in list (1)
+     * deny -> either no list (-1), or not in list (0)
+     */
+    if (pwd) {
+        if (accessvol(obj, getoption(obj->iniconfig, section, "invalid users", preset, NULL), pwd->pw_name) == 1)
+            goto EC_CLEANUP;
+        if (accessvol(obj, getoption(obj->iniconfig, section, "valid users", preset, NULL), pwd->pw_name) == 0)
+            goto EC_CLEANUP;
+        if (hostaccessvol(obj, section, getoption(obj->iniconfig, section, "hosts deny", preset, NULL)) == 1)
+            goto EC_CLEANUP;
+        if (hostaccessvol(obj, section, getoption(obj->iniconfig, section, "hosts allow", preset, NULL)) == 0)
+            goto EC_CLEANUP;
+    }
+
+    EC_NULL( volume = calloc(1, sizeof(struct vol)) );
+
+    EC_NULL( volume->v_configname = strdup(section));
+
+    volume->v_vfs_ea = AFPVOL_EA_AUTO;
+    volume->v_umask = obj->options.umask;
+
+    if (val = getoption(obj->iniconfig, section, "password", preset, NULL))
+        EC_NULL( volume->v_password = strdup(val) );
+
+    if (val = getoption(obj->iniconfig, section, "veto files", preset, NULL))
+        EC_NULL( volume->v_veto = strdup(val) );
+
+    /* vol charset is in [G] and [V] */
+    if (val = getoption(obj->iniconfig, section, "vol charset", preset, NULL)) {
+        if (strcasecmp(val, "UTF-8") == 0) {
+            val = strdup("UTF8");
+        }
+        EC_NULL( volume->v_volcodepage = strdup(val) );
+    }
+    else
+        EC_NULL( volume->v_volcodepage = strdup(obj->options.volcodepage) );
+
+    /* mac charset is in [G] and [V] */
+    if (val = getoption(obj->iniconfig, section, "mac charset", preset, NULL)) {
+        if (strncasecmp(val, "MAC", 3) != 0) {
+            LOG(log_warning, logtype_afpd, "Is '%s' really mac charset? ", val);
+        }
+        EC_NULL( volume->v_maccodepage = strdup(val) );
+    }
+    else
+    EC_NULL( volume->v_maccodepage = strdup(obj->options.maccodepage) );
+
+    bstring dbpath;
+    EC_NULL_LOG( val = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "vol dbpath", _PATH_STATEDIR "CNID/") );
+    EC_NULL_LOG( dbpath = bformat("%s/%s/", val, name) );
+    EC_NULL_LOG( volume->v_dbpath = strdup(bdata(dbpath)) );
+    bdestroy(dbpath);
+
+    if (val = getoption(obj->iniconfig, section, "cnid scheme", preset, NULL))
+        EC_NULL( volume->v_cnidscheme = strdup(val) );
+    else
+        volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
+
+    if (val = getoption(obj->iniconfig, section, "umask", preset, NULL))
+        volume->v_umask = (int)strtol(val, NULL, 8);
+
+    if (val = getoption(obj->iniconfig, section, "directory perm", preset, NULL))
+        volume->v_dperm = (int)strtol(val, NULL, 8);
+
+    if (val = getoption(obj->iniconfig, section, "file perm", preset, NULL))
+        volume->v_fperm = (int)strtol(val, NULL, 8);
+
+    if (val = getoption(obj->iniconfig, section, "vol size limit", preset, NULL))
+        volume->v_limitsize = (uint32_t)strtoul(val, NULL, 10);
+
+    if (val = getoption(obj->iniconfig, section, "preexec", preset, NULL))
+        EC_NULL( volume->v_preexec = volxlate(obj, NULL, MAXPATHLEN, val, pwd, path, name) );
+
+    if (val = getoption(obj->iniconfig, section, "postexec", preset, NULL))
+        EC_NULL( volume->v_postexec = volxlate(obj, NULL, MAXPATHLEN, val, pwd, path, name) );
+
+    if (val = getoption(obj->iniconfig, section, "root preexec", preset, NULL))
+        EC_NULL( volume->v_root_preexec = volxlate(obj, NULL, MAXPATHLEN, val, pwd, path, name) );
+
+    if (val = getoption(obj->iniconfig, section, "root postexec", preset, NULL))
+        EC_NULL( volume->v_root_postexec = volxlate(obj, NULL, MAXPATHLEN, val, pwd, path, name) );
+
+    if (val = getoption(obj->iniconfig, section, "appledouble", preset, NULL)) {
+        if (strcmp(val, "v2") == 0)
+            volume->v_adouble = AD_VERSION2;
+        else if (strcmp(val, "ea") == 0)
+            volume->v_adouble = AD_VERSION_EA;
+    } else {
+        volume->v_adouble = AD_VERSION;
+    }
+
+    if (val = getoption(obj->iniconfig, section, "cnid server", preset, NULL)) {
+        EC_NULL( p = strdup(val) );
+        volume->v_cnidserver = p;
+        if (q = strrchr(val, ':')) {
+            *q++ = 0;
+            volume->v_cnidport = strdup(q);
+        } else {
+            volume->v_cnidport = strdup("4700");
+        }
+
+    } else {
+        volume->v_cnidserver = strdup(obj->options.Cnid_srv);
+        volume->v_cnidport = strdup(obj->options.Cnid_port);
+    }
+
+    if (val = getoption(obj->iniconfig, section, "ea", preset, NULL)) {
+        if (strcasecmp(val, "ad") == 0)
+            volume->v_vfs_ea = AFPVOL_EA_AD;
+        else if (strcasecmp(val, "sys") == 0)
+            volume->v_vfs_ea = AFPVOL_EA_SYS;
+        else if (strcasecmp(val, "none") == 0)
+            volume->v_vfs_ea = AFPVOL_EA_NONE;
+    }
+
+    if (val = getoption(obj->iniconfig, section, "casefold", preset, NULL)) {
+        if (strcasecmp(val, "tolower") == 0)
+            volume->v_casefold = AFPVOL_UMLOWER;
+        else if (strcasecmp(val, "toupper") == 0)
+            volume->v_casefold = AFPVOL_UMUPPER;
+        else if (strcasecmp(val, "xlatelower") == 0)
+            volume->v_casefold = AFPVOL_UUPPERMLOWER;
+        else if (strcasecmp(val, "xlateupper") == 0)
+            volume->v_casefold = AFPVOL_ULOWERMUPPER;
+    }
+
+    if (getoption_bool(obj->iniconfig, section, "read only", preset, 0))
+        volume->v_flags |= AFPVOL_RO;
+    if (getoption_bool(obj->iniconfig, section, "invisible dots", preset, 0))
+        volume->v_flags |= AFPVOL_INV_DOTS;
+    if (!getoption_bool(obj->iniconfig, section, "stat vol", preset, 1))
+        volume->v_flags |= AFPVOL_NOSTAT;
+    if (getoption_bool(obj->iniconfig, section, "unix priv", preset, 1))
+        volume->v_flags |= AFPVOL_UNIX_PRIV;
+    if (!getoption_bool(obj->iniconfig, section, "cnid dev", preset, 1))
+        volume->v_flags |= AFPVOL_NODEV;
+    if (getoption_bool(obj->iniconfig, section, "illegal seq", preset, 0))
+        volume->v_flags |= AFPVOL_EILSEQ;
+    if (getoption_bool(obj->iniconfig, section, "time machine", preset, 0))
+        volume->v_flags |= AFPVOL_TM;
+    if (getoption_bool(obj->iniconfig, section, "search db", preset, 0))
+        volume->v_flags |= AFPVOL_SEARCHDB;
+    if (!getoption_bool(obj->iniconfig, section, "network ids", preset, 1))
+        volume->v_flags |= AFPVOL_NONETIDS;
+#ifdef HAVE_ACLS
+    if (getoption_bool(obj->iniconfig, section, "acls", preset, 1))
+        volume->v_flags |= AFPVOL_ACLS;
+#endif
+    if (!getoption_bool(obj->iniconfig, section, "convert appledouble", preset, 1))
+        volume->v_flags |= AFPVOL_NOV2TOEACONV;
+
+    if (getoption_bool(obj->iniconfig, section, "preexec close", preset, 0))
+        volume->v_preexec_close = 1;
+    if (getoption_bool(obj->iniconfig, section, "root preexec close", preset, 0))
+        volume->v_root_preexec_close = 1;
+
+    /*
+     * Handle read-only behaviour. semantics:
+     * 1) neither the rolist nor the rwlist exist -> rw
+     * 2) rolist exists -> ro if user is in it.
+     * 3) rwlist exists -> ro unless user is in it.
+     * 4) cnid scheme = last -> ro forcibly.
+     */
+    if (pwd) {
+        if (accessvol(obj, getoption(obj->iniconfig, section, "rolist", preset, NULL), pwd->pw_name) == 1
+            || accessvol(obj, getoption(obj->iniconfig, section, "rwlist", preset, NULL), pwd->pw_name) == 0)
+            volume->v_flags |= AFPVOL_RO;
+    }
+    if (0 == strcmp(volume->v_cnidscheme, "last"))
+        volume->v_flags |= AFPVOL_RO;
+
+    if ((volume->v_flags & AFPVOL_NODEV))
+        volume->v_ad_options |= ADVOL_NODEV;
+    if ((volume->v_flags & AFPVOL_UNIX_PRIV))
+        volume->v_ad_options |= ADVOL_UNIXPRIV;
+    if ((volume->v_flags & AFPVOL_INV_DOTS))
+        volume->v_ad_options |= ADVOL_INVDOTS;
+
+    /* Mac to Unix conversion flags*/
+    if ((volume->v_flags & AFPVOL_EILSEQ))
+        volume->v_mtou_flags |= CONV__EILSEQ;
+
+    if ((volume->v_casefold & AFPVOL_MTOUUPPER))
+        volume->v_mtou_flags |= CONV_TOUPPER;
+    else if ((volume->v_casefold & AFPVOL_MTOULOWER))
+        volume->v_mtou_flags |= CONV_TOLOWER;
+
+    /* Unix to Mac conversion flags*/
+    volume->v_utom_flags = CONV_IGNORE;
+    if ((volume->v_casefold & AFPVOL_UTOMUPPER))
+        volume->v_utom_flags |= CONV_TOUPPER;
+    else if ((volume->v_casefold & AFPVOL_UTOMLOWER))
+        volume->v_utom_flags |= CONV_TOLOWER;
+    if ((volume->v_flags & AFPVOL_EILSEQ))
+        volume->v_utom_flags |= CONV__EILSEQ;
+
+    /* suffix for mangling use (lastvid + 1)   */
+    /* because v_vid has not been decided yet. */
+    suffixlen = sprintf(suffix, "#%X", lastvid + 1 );
+
+
+    vlen = strlen( name );
+
+    /* Unicode Volume Name */
+    /* Firstly convert name from unixcharset to UTF8-MAC */
+    flags = CONV_IGNORE;
+    tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
+    if (tmpvlen <= 0) {
+        strcpy(tmpname, "???");
+        tmpvlen = 3;
+    }
+
+    /* Do we have to mangle ? */
+    if ( (flags & CONV_REQMANGLE) || (tmpvlen > obj->options.volnamelen)) {
+        if (tmpvlen + suffixlen > obj->options.volnamelen) {
+            flags = CONV_FORCE;
+            tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, obj->options.volnamelen - suffixlen, &flags);
+            tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
+        }
+        strcat(tmpname, suffix);
+        tmpvlen = strlen(tmpname);
+    }
+
+    /* Secondly convert name from UTF8-MAC to UCS2 */
+    if ( 0 >= ( u8mvlen = convert_string(CH_UTF8_MAC, CH_UCS2, tmpname, tmpvlen, u8mtmpname, AFPVOL_U8MNAMELEN*2)) )
+        EC_FAIL;
+
+    LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' -> UTF8-MAC Name: '%s'", name, tmpname);
+
+    /* Maccharset Volume Name */
+    /* Firsty convert name from unixcharset to maccharset */
+    flags = CONV_IGNORE;
+    tmpvlen = convert_charset(obj->options.unixcharset, obj->options.maccharset, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
+    if (tmpvlen <= 0) {
+        strcpy(tmpname, "???");
+        tmpvlen = 3;
+    }
+
+    /* Do we have to mangle ? */
+    if ( (flags & CONV_REQMANGLE) || (tmpvlen > AFPVOL_MACNAMELEN)) {
+        if (tmpvlen + suffixlen > AFPVOL_MACNAMELEN) {
+            flags = CONV_FORCE;
+            tmpvlen = convert_charset(obj->options.unixcharset,
+                                      obj->options.maccharset,
+                                      0,
+                                      name,
+                                      vlen,
+                                      tmpname,
+                                      AFPVOL_MACNAMELEN - suffixlen,
+                                      &flags);
+            tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
+        }
+        strcat(tmpname, suffix);
+        tmpvlen = strlen(tmpname);
+    }
+
+    /* Secondly convert name from maccharset to UCS2 */
+    if ( 0 >= ( macvlen = convert_string(obj->options.maccharset,
+                                         CH_UCS2,
+                                         tmpname,
+                                         tmpvlen,
+                                         mactmpname,
+                                         AFPVOL_U8MNAMELEN*2)) )
+        EC_FAIL;
+
+    LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' ->  Longname: '%s'", name, tmpname);
+
+    EC_NULL( volume->v_localname = strdup(name) );
+    EC_NULL( volume->v_u8mname = strdup_w(u8mtmpname) );
+    EC_NULL( volume->v_macname = strdup_w(mactmpname) );
+    EC_NULL( volume->v_path = malloc(strlen(path) + 1) );
+
+    volume->v_name = utf8_encoding(obj) ? volume->v_u8mname : volume->v_macname;
+    strcpy(volume->v_path, path);
+
+#ifdef __svr4__
+    volume->v_qfd = -1;
+#endif /* __svr4__ */
+
+    /* os X start at 1 and use network order ie. 1 2 3 */
+    volume->v_vid = ++lastvid;
+    volume->v_vid = htons(volume->v_vid);
+
+#ifdef HAVE_ACLS
+    if (!check_vol_acl_support(volume)) {
+        LOG(log_debug, logtype_afpd, "creatvol(\"%s\"): disabling ACL support", volume->v_path);
+        volume->v_flags &= ~AFPVOL_ACLS;
+    }
+#endif
+
+    /* Check EA support on volume */
+    if (volume->v_vfs_ea == AFPVOL_EA_AUTO || volume->v_adouble == AD_VERSION_EA)
+        check_ea_support(volume);
+    initvol_vfs(volume);
+
+    /* get/store uuid from file in afpd master*/
+    if (!(pwd) && (volume->v_flags & AFPVOL_TM)) {
+        char *uuid = get_vol_uuid(obj, volume->v_localname);
+        if (!uuid) {
+            LOG(log_error, logtype_afpd, "Volume '%s': couldn't get UUID",
+                volume->v_localname);
+        } else {
+            volume->v_uuid = uuid;
+            LOG(log_debug, logtype_afpd, "Volume '%s': UUID '%s'",
+                volume->v_localname, volume->v_uuid);
+        }
+    }
+
+    /* no errors shall happen beyond this point because the cleanup would mess the volume chain up */
+    volume->v_next = Volumes;
+    Volumes = volume;
+    volume->v_obj = obj;
+
+EC_CLEANUP:
+    LOG(log_debug, logtype_afpd, "createvol: END: %d", ret);
+    if (ret != 0) {
+        if (volume) {
+            volume_free(volume);
+            free(volume);
+        }
+        return NULL;
+    }
+    return volume;
+}
+
+/* ----------------------
+ */
+static int volfile_changed(struct afp_options *p)
+{
+    struct stat st;
+
+    if (!stat(p->configfile, &st) && st.st_mtime > p->volfile.mtime) {
+        p->volfile.mtime = st.st_mtime;
+        return 1;
+    }
+    return 0;
+}
+
+static int vol_section(const char *sec)
+{
+    if (STRCMP(sec, ==, INISEC_GLOBAL))
+        return 0;
+    return 1;
+}
+
+#define MAXPRESETLEN 100
+/*!
+ * Read volumes from iniconfig and add the volumes contained within to
+ * the global volume list. This gets called from the forked afpd childs.
+ * The master now reads this too for Zeroconf announcements.
+ */
+static int readvolfile(AFPObj *obj, const struct passwd *pwent)
+{
+    EC_INIT;
+    static int regexerr = -1;
+    static regex_t reg;
+    char        path[MAXPATHLEN + 1];
+    char        volname[AFPVOL_U8MNAMELEN + 1];
+    char        tmp[MAXPATHLEN + 1];
+    const char  *preset, *default_preset, *p, *basedir;
+    char        *q, *u;
+    int         i;
+    struct passwd   *pw;
+    regmatch_t match[1];
+
+    LOG(log_debug, logtype_afpd, "readvolfile: BEGIN");
+
+    int secnum = iniparser_getnsec(obj->iniconfig);    
+    LOG(log_debug, logtype_afpd, "readvolfile: sections: %d", secnum);
+    const char *secname;
+
+    if ((default_preset = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "vol preset", NULL))) {
+        LOG(log_debug, logtype_afpd, "readvolfile: default_preset: %s", default_preset);
+    }
+
+    for (i = 0; i < secnum; i++) { 
+        secname = iniparser_getsecname(obj->iniconfig, i);
+
+        if (!vol_section(secname))
+            continue;
+        if (STRCMP(secname, ==, INISEC_HOMES)) {
+            have_uservol = 1;
+            if (!IS_AFP_SESSION(obj)
+                || strcmp(obj->username, obj->options.guest) == 0)
+                /* not an AFP session, but cnid daemon, dbd or ad util, or guest login */
+                continue;
+            if (pwent->pw_dir == NULL || STRCMP("", ==, pwent->pw_dir))
+                /* no user home */
+                continue;
+
+            /* check if user home matches our "basedir regex" */
+            if ((basedir = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "basedir regex", NULL)) == NULL) {
+                LOG(log_error, logtype_afpd, "\"basedir regex =\" must be defined in [Homes] section");
+                continue;
+            }
+            LOG(log_debug, logtype_afpd, "readvolfile: basedir regex: '%s'", basedir);
+
+            if (regexerr != 0 && (regexerr = regcomp(&reg, basedir, REG_EXTENDED)) != 0) {
+                char errbuf[1024];
+                regerror(regexerr, &reg, errbuf, sizeof(errbuf));
+                LOG(log_debug, logtype_default, "readvolfile: bad basedir regex: %s", errbuf);
+            }
+
+            if (regexec(&reg, pwent->pw_dir, 1, match, 0) == REG_NOMATCH) {
+                LOG(log_debug, logtype_default, "readvolfile: user home \"%s\" doesn't match basedir regex \"%s\"",
+                    pwent->pw_dir, basedir);
+                continue;
+            }
+
+            strlcpy(tmp, pwent->pw_dir, MAXPATHLEN);
+            strlcat(tmp, "/", MAXPATHLEN);
+            if (p = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "path", NULL))
+                strlcat(tmp, p, MAXPATHLEN);
+        } else {
+            /* Get path */
+            if ((p = iniparser_getstring(obj->iniconfig, secname, "path", NULL)) == NULL)
+                continue;
+            strlcpy(tmp, p, MAXPATHLEN);
+        }
+
+        if (volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL) == NULL)
+            continue;
+
+        /* do variable substitution for volume name */
+        if (STRCMP(secname, ==, INISEC_HOMES)) {
+            p = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "home name", "$u's home");
+            if (strstr(p, "$u") == NULL) {
+                LOG(log_warning, logtype_afpd, "home name must contain $u.");
+                p = "$u's home";
+            }
+            strlcpy(tmp, p, MAXPATHLEN);
+        } else {
+            strlcpy(tmp, secname, AFPVOL_U8MNAMELEN);
+        }
+        if (volxlate(obj, volname, sizeof(volname) - 1, tmp, pwent, path, NULL) == NULL)
+            continue;
+
+        preset = iniparser_getstring(obj->iniconfig, secname, "vol preset", NULL);
+
+        creatvol(obj, pwent, secname, volname, path, preset ? preset : default_preset ? default_preset : NULL);
+    }
+
+EC_CLEANUP:
+    EC_EXIT;
+}
+
+/**************************************************************
+ * API functions
+ **************************************************************/
+
+/*!
+ * Remove a volume from the linked list of volumes
+ */
+void volume_unlink(struct vol *volume)
+{
+    struct vol *vol, *ovol, *nvol;
+
+    if (volume == Volumes) {
+        Volumes = NULL;
+        return;
+    }
+    for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
+        nvol = vol->v_next;
+
+        if (vol == volume) {
+            ovol->v_next = nvol;
+            break;
+        }
+        else {
+            ovol = vol;
+        }
+    }
+}
+
+/*!
+ * Free all resources allocated in a struct vol, only struct dir *v_root can't be freed
+ */
+void volume_free(struct vol *vol)
+{
+    LOG(log_debug, logtype_afpd, "volume_free('%s'): BEGIN", vol->v_localname);
+
+    free(vol->v_localname);
+    free(vol->v_u8mname);
+    free(vol->v_macname);
+    free(vol->v_path);
+    free(vol->v_password);
+    free(vol->v_veto);
+    free(vol->v_volcodepage);
+    free(vol->v_maccodepage);
+    free(vol->v_cnidscheme);
+    free(vol->v_dbpath);
+    free(vol->v_gvs);
+    free(vol->v_uuid);
+    free(vol->v_cnidserver);
+    free(vol->v_cnidport);
+    free(vol->v_root_preexec);
+    free(vol->v_postexec);
+
+    LOG(log_debug, logtype_afpd, "volume_free: END");
+}
+
+/*!
+ * Load charsets for a volume
+ */
+int load_charset(struct vol *vol)
+{
+    if ((vol->v_maccharset = add_charset(vol->v_maccodepage)) == (charset_t)-1) {
+        LOG(log_error, logtype_default, "Setting mac charset '%s' failed", vol->v_maccodepage);
+        return -1;
+    }
+
+    if ((vol->v_volcharset = add_charset(vol->v_volcodepage)) == (charset_t)-1) {
+        LOG(log_error, logtype_default, "Setting vol charset '%s' failed", vol->v_volcodepage);
+        return -1;
+    }
+
+    return 0;
+}
+
+/*!
+ * Initialize volumes and load ini configfile
+ *
+ * Depending on the value of obj->uid either access checks are done (!=0) or skipped (=0)
+ *
+ * @param obj       (r) handle
+ * @param delvol_fn (r) callback called for deleted volumes
+ */
+int load_volumes(AFPObj *obj, void (*delvol_fn)(const AFPObj *obj, struct vol *))
+{
+    EC_INIT;
+    int fd = -1;
+    struct passwd   *pwent = NULL;
+    struct stat         st;
+    int retries = 0;
+    struct vol *vol;
+
+    LOG(log_debug, logtype_afpd, "load_volumes: BEGIN");
+
+    if (Volumes) {
+        if (!volfile_changed(&obj->options))
+            goto EC_CLEANUP;
+        have_uservol = 0;
+        for (vol = Volumes; vol; vol = vol->v_next) {
+            vol->v_deleted = 1;
+        }
+    } else {
+        LOG(log_debug, logtype_afpd, "load_volumes: no volumes yet");
+        EC_ZERO_LOG( lstat(obj->options.configfile, &st) );
+        obj->options.volfile.mtime = st.st_mtime;
+    }
+
+    /* try putting a read lock on the volume file twice, sleep 1 second if first attempt fails */
+
+    fd = open(obj->options.configfile, O_RDONLY);
+
+    while (retries < 2) {
+        if ((read_lock(fd, 0, SEEK_SET, 0)) != 0) {
+            retries++;
+            if (!retries) {
+                LOG(log_error, logtype_afpd, "readvolfile: can't lock configfile \"%s\"",
+                    obj->options.configfile);
+                EC_FAIL;
+            }
+            sleep(1);
+            continue;
+        }
+        break;
+    }
+
+    if (obj->uid)
+        pwent = getpwuid(obj->uid);
+
+    if (obj->iniconfig)
+        iniparser_freedict(obj->iniconfig);
+    LOG(log_debug, logtype_afpd, "load_volumes: loading: %s", obj->options.configfile);
+    obj->iniconfig = iniparser_load(obj->options.configfile);
+
+    EC_ZERO_LOG( readvolfile(obj, pwent) );
+
+    for ( vol = Volumes; vol; vol = vol->v_next ) {
+        if (vol->v_deleted) {
+            LOG(log_debug, logtype_afpd, "load_volumes: deleted: %s", vol->v_localname);
+            if (delvol_fn)
+                delvol_fn(obj, vol);
+            vol = Volumes;
+        }
+    }
+
+EC_CLEANUP:
+    if (fd != -1)
+        (void)close(fd);
+
+    LOG(log_debug, logtype_afpd, "load_volumes: END");
+    EC_EXIT;
+}
+
+void unload_volumes(AFPObj *obj)
+{
+    struct vol *vol;
+
+    LOG(log_debug, logtype_afpd, "unload_volumes: BEGIN");
+
+    for (vol = Volumes; vol; vol = vol->v_next)
+        volume_free(vol);
+    Volumes = NULL;
+    obj->options.volfile.mtime = 0;
+    
+    LOG(log_debug, logtype_afpd, "unload_volumes: END");
+}
+
+struct vol *getvolumes(void)
+{
+    return Volumes;
+}
+
+struct vol *getvolbyvid(const uint16_t vid )
+{
+    struct vol  *vol;
+
+    for ( vol = Volumes; vol; vol = vol->v_next ) {
+        if ( vid == vol->v_vid ) {
+            break;
+        }
+    }
+    if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
+        return( NULL );
+    }
+
+    return( vol );
+}
+
+/*!
+ * Search volume by path, creating user home vols as necessary
+ *
+ * Path may be absolute or relative. Ordinary volume structs are created when
+ * the ini config is initially parsed (load_volumes()), but user volumes are
+ * as load_volumes() only can create the user volume of the logged in user
+ * in an AFP session in afpd, but not when called from eg cnid_metad or dbd.
+ * Both cnid_metad and dbd thus need a way to lookup and create struct vols
+ * for user home by path. This is what this func does as well.
+ *
+ * (1) Search "normal" volume list 
+ * (2) Check if theres a [Homes] section, load_volumes() remembers this for us
+ * (3) If there is, match "path" with "basedir regex" to get the user home parent dir
+ * (4) Built user home path by appending the basedir matched in (3) and appending the username
+ * (5) The next path element then is the username
+ * (6) Append [Homes]->path subdirectory if defined
+ * (7) Create volume
+ *
+ * @param obj  (rw) handle
+ * @param path (r)  path, may be relative or absolute
+ */
+struct vol *getvolbypath(AFPObj *obj, const char *path)
+{
+    EC_INIT;
+    static int regexerr = -1;
+    static regex_t reg;
+    struct vol *vol;
+    struct vol *tmp;
+    const struct passwd *pw;
+    char        volname[AFPVOL_U8MNAMELEN + 1];
+    char        abspath[MAXPATHLEN + 1];
+    char        volpath[MAXPATHLEN + 1];
+    char        tmpbuf[MAXPATHLEN + 1];
+    const char *secname, *basedir, *p = NULL, *subpath = NULL, *subpathconfig;
+    char *user = NULL, *prw;
+    regmatch_t match[1];
+
+    LOG(log_debug, logtype_afpd, "getvolbypath(\"%s\")", path);
+
+    if (path[0] != '/') {
+        /* relative path, build absolute path */
+        EC_NULL_LOG( getcwd(abspath, MAXPATHLEN) );
+        strlcat(abspath, "/", MAXPATHLEN);
+        strlcat(abspath, path, MAXPATHLEN);
+        path = abspath;
+    }
+
+
+    for (tmp = Volumes; tmp; tmp = tmp->v_next) { /* (1) */
+        if (strncmp(path, tmp->v_path, strlen(tmp->v_path)) == 0) {
+            vol = tmp;
+            goto EC_CLEANUP;
+        }
+    }
+
+    if (!have_uservol) /* (2) */
+        EC_FAIL_LOG("getvolbypath(\"%s\"): no volume for path", path);
+
+    int secnum = iniparser_getnsec(obj->iniconfig);
+
+    for (int i = 0; i < secnum; i++) { 
+        secname = iniparser_getsecname(obj->iniconfig, i);
+        if (STRCMP(secname, ==, INISEC_HOMES))
+            break;
+    }
+
+    if (STRCMP(secname, !=, INISEC_HOMES))
+        EC_FAIL_LOG("getvolbypath(\"%s\"): no volume for path", path);
+
+    /* (3) */
+    EC_NULL_LOG( basedir = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "basedir regex", NULL) );
+    LOG(log_debug, logtype_afpd, "getvolbypath: user home section: '%s', basedir: '%s'", secname, basedir);
+
+    if (regexerr != 0 && (regexerr = regcomp(&reg, basedir, REG_EXTENDED)) != 0) {
+        char errbuf[1024];
+        regerror(regexerr, &reg, errbuf, sizeof(errbuf));
+        printf("error: %s\n", errbuf);
+        EC_FAIL_LOG("getvolbypath(\"%s\"): bad basedir regex: %s", errbuf);
+    }
+
+    if (regexec(&reg, path, 1, match, 0) == REG_NOMATCH)
+        EC_FAIL_LOG("getvolbypath(\"%s\"): no volume for path", path);
+
+    if (match[0].rm_eo - match[0].rm_so > MAXPATHLEN)
+        EC_FAIL_LOG("getvolbypath(\"%s\"): path too long", path);
+
+    /* (4) */
+    strncpy(tmpbuf, path + match[0].rm_so, match[0].rm_eo - match[0].rm_so);
+    tmpbuf[match[0].rm_eo - match[0].rm_so] = 0;
+
+    LOG(log_debug, logtype_afpd, "getvolbypath: basedir regex: '%s', basedir match: \"%s\"",
+        basedir, tmpbuf);
+
+    strlcat(tmpbuf, "/", MAXPATHLEN);
+
+    /* (5) */
+    p = path + strlen(basedir);
+    while (*p == '/')
+        p++;
+    EC_NULL_LOG( user = strdup(p) );
+
+    if (prw = strchr(user, '/'))
+        *prw++ = 0;
+    if (prw != 0)
+        subpath = prw;
+
+    strlcat(tmpbuf, user, MAXPATHLEN);
+    strlcat(obj->username, user, MAXUSERLEN);
+    strlcat(tmpbuf, "/", MAXPATHLEN);
+
+    /* (6) */
+    if (subpathconfig = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "path", NULL)) {
+        if (!subpath || strncmp(subpathconfig, subpath, strlen(subpathconfig)) != 0) {
+            EC_FAIL;
+        }
+        strlcat(tmpbuf, subpathconfig, MAXPATHLEN);
+        strlcat(tmpbuf, "/", MAXPATHLEN);
+    }
+
+
+    /* (7) */
+    if (volxlate(obj, volpath, sizeof(volpath) - 1, tmpbuf, pw, NULL, NULL) == NULL)
+        return NULL;
+
+    EC_NULL( pw = getpwnam(user) );
+
+    LOG(log_debug, logtype_afpd, "getvolbypath(\"%s\"): user: %s, homedir: %s => volpath: \"%s\"",
+        path, user, pw->pw_dir, volpath);
+
+    /* do variable substitution for volume name */
+    p = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "home name", "$u's home");
+    if (strstr(p, "$u") == NULL)
+        p = "$u's home";
+    strlcpy(tmpbuf, p, AFPVOL_U8MNAMELEN);
+    EC_NULL_LOG( volxlate(obj, volname, sizeof(volname) - 1, tmpbuf, pw, volpath, NULL) );
+
+    const char  *preset, *default_preset;
+    default_preset = iniparser_getstring(obj->iniconfig, INISEC_GLOBAL, "vol preset", NULL);
+    preset = iniparser_getstring(obj->iniconfig, INISEC_HOMES, "vol preset", NULL);
+
+    vol = creatvol(obj, pw, INISEC_HOMES, volname, volpath, preset ? preset : default_preset ? default_preset : NULL);
+
+EC_CLEANUP:
+    if (user)
+        free(user);
+    if (ret != 0)
+        vol = NULL;
+    return vol;
+}
+
+struct vol *getvolbyname(const char *name)
+{
+    struct vol *vol = NULL;
+    struct vol *tmp;
+
+    for (tmp = Volumes; tmp; tmp = tmp->v_next) {
+        if (strncmp(name, tmp->v_configname, strlen(tmp->v_configname)) == 0) {
+            vol = tmp;
+            break;
+        }
+    }
+    return vol;
+}
+
+#define MAXVAL 1024
+/*!
+ * Initialize an AFPObj and options from ini config file
+ */
+int afp_config_parse(AFPObj *AFPObj, char *processname)
+{
+    EC_INIT;
+    dictionary *config;
+    struct afp_options *options = &AFPObj->options;
+    int i, c;
+    const char *p, *tmp;
+    char *q, *r;
+    char val[MAXVAL];
+
+    if (processname != NULL)
+        set_processname(processname);
+
+    AFPObj->afp_version = 11;
+    options->configfile  = AFPObj->cmdlineconfigfile ? strdup(AFPObj->cmdlineconfigfile) : strdup(_PATH_CONFDIR "afp.conf");
+    options->sigconffile = strdup(_PATH_STATEDIR "afp_signature.conf");
+    options->uuidconf    = strdup(_PATH_STATEDIR "afp_voluuid.conf");
+    options->flags       = OPTION_UUID | AFPObj->cmdlineflags;
+    
+    if ((config = iniparser_load(AFPObj->options.configfile)) == NULL)
+        return -1;
+    AFPObj->iniconfig = config;
+
+    /* [Global] */
+    options->logconfig = iniparser_getstrdup(config, INISEC_GLOBAL, "log level", "default:note");
+    options->logfile   = iniparser_getstrdup(config, INISEC_GLOBAL, "log file",  NULL);
+
+    setuplog(options->logconfig, options->logfile);
+
+    /* "server options" boolean options */
+    if (!iniparser_getboolean(config, INISEC_GLOBAL, "zeroconf", 1))
+        options->flags |= OPTION_NOZEROCONF;
+    if (iniparser_getboolean(config, INISEC_GLOBAL, "advertise ssh", 0))
+        options->flags |= OPTION_ANNOUNCESSH;
+    if (iniparser_getboolean(config, INISEC_GLOBAL, "map acls", 1))
+        options->flags |= OPTION_ACL2MACCESS;
+    if (iniparser_getboolean(config, INISEC_GLOBAL, "keep sessions", 0))
+        options->flags |= OPTION_KEEPSESSIONS;
+    if (iniparser_getboolean(config, INISEC_GLOBAL, "close vol", 0))
+        options->flags |= OPTION_CLOSEVOL;
+    if (!iniparser_getboolean(config, INISEC_GLOBAL, "client polling", 0))
+        options->flags |= OPTION_SERVERNOTIF;
+    if (!iniparser_getboolean(config, INISEC_GLOBAL, "use sendfile", 1))
+        options->flags |= OPTION_NOSENDFILE;
+    if (iniparser_getboolean(config, INISEC_GLOBAL, "solaris share reservations", 1))
+        options->flags |= OPTION_SHARE_RESERV;
+    if (iniparser_getboolean(config, INISEC_GLOBAL, "afp read locks", 0))
+        options->flags |= OPTION_AFP_READ_LOCK;
+    if (!iniparser_getboolean(config, INISEC_GLOBAL, "save password", 1))
+        options->passwdbits |= PASSWD_NOSAVE;
+    if (iniparser_getboolean(config, INISEC_GLOBAL, "set password", 0))
+        options->passwdbits |= PASSWD_SET;
+
+    /* figure out options w values */
+    options->loginmesg      = iniparser_getstrdup(config, INISEC_GLOBAL, "login message",  NULL);
+    options->guest          = iniparser_getstrdup(config, INISEC_GLOBAL, "guest account",  "nobody");
+    options->passwdfile     = iniparser_getstrdup(config, INISEC_GLOBAL, "passwd file",_PATH_AFPDPWFILE);
+    options->uampath        = iniparser_getstrdup(config, INISEC_GLOBAL, "uam path",       _PATH_AFPDUAMPATH);
+    options->uamlist        = iniparser_getstrdup(config, INISEC_GLOBAL, "uam list",       "uams_dhx.so uams_dhx2.so");
+    options->port           = iniparser_getstrdup(config, INISEC_GLOBAL, "afp port",       "548");
+    options->signatureopt   = iniparser_getstrdup(config, INISEC_GLOBAL, "signature",      "");
+    options->k5service      = iniparser_getstrdup(config, INISEC_GLOBAL, "k5 service",     NULL);
+    options->k5realm        = iniparser_getstrdup(config, INISEC_GLOBAL, "k5 realm",       NULL);
+    options->listen         = iniparser_getstrdup(config, INISEC_GLOBAL, "afp listen",     NULL);
+    options->ntdomain       = iniparser_getstrdup(config, INISEC_GLOBAL, "nt domain",      NULL);
+    options->ntseparator    = iniparser_getstrdup(config, INISEC_GLOBAL, "nt separator",   NULL);
+    options->mimicmodel     = iniparser_getstrdup(config, INISEC_GLOBAL, "mimic model",    NULL);
+    options->adminauthuser  = iniparser_getstrdup(config, INISEC_GLOBAL, "admin auth user",NULL);
+    options->connections    = iniparser_getint   (config, INISEC_GLOBAL, "max connections",200);
+    options->passwdminlen   = iniparser_getint   (config, INISEC_GLOBAL, "passwd minlen",  0);
+    options->tickleval      = iniparser_getint   (config, INISEC_GLOBAL, "tickleval",      30);
+    options->timeout        = iniparser_getint   (config, INISEC_GLOBAL, "timeout",        4);
+    options->dsireadbuf     = iniparser_getint   (config, INISEC_GLOBAL, "dsireadbuf",     12);
+    options->server_quantum = iniparser_getint   (config, INISEC_GLOBAL, "server quantum", DSI_SERVQUANT_DEF);
+    options->volnamelen     = iniparser_getint   (config, INISEC_GLOBAL, "volnamelen",     80);
+    options->dircachesize   = iniparser_getint   (config, INISEC_GLOBAL, "dircachesize",   DEFAULT_MAX_DIRCACHE_SIZE);
+    options->tcp_sndbuf     = iniparser_getint   (config, INISEC_GLOBAL, "tcpsndbuf",      0);
+    options->tcp_rcvbuf     = iniparser_getint   (config, INISEC_GLOBAL, "tcprcvbuf",      0);
+    options->fce_fmodwait   = iniparser_getint   (config, INISEC_GLOBAL, "fce holdfmod",   60);
+    options->sleep          = iniparser_getint   (config, INISEC_GLOBAL, "sleep time",     10);
+    options->disconnected   = iniparser_getint   (config, INISEC_GLOBAL, "disconnect time",24);
+
+    if ((p = iniparser_getstring(config, INISEC_GLOBAL, "hostname", NULL))) {
+        EC_NULL_LOG( options->hostname = strdup(p) );
+    } else {
+        if (gethostname(val, sizeof(val)) < 0 ) {
+            perror( "gethostname" );
+            EC_FAIL;
+        }
+        if ((q = strchr(val, '.')))
+            *q = '\0';
+        options->hostname = strdup(val);
+    }
+
+    if ((p = iniparser_getstring(config, INISEC_GLOBAL, "k5 keytab", NULL))) {
+        EC_NULL_LOG( options->k5keytab = malloc(strlen(p) + 14) );
+        snprintf(options->k5keytab, strlen(p) + 14, "KRB5_KTNAME=%s", p);
+        putenv(options->k5keytab);
+    }
+
+#ifdef ADMIN_GRP
+    if ((p = iniparser_getstring(config, INISEC_GLOBAL, "admin group",  NULL))) {
+         struct group *gr = getgrnam(p);
+         if (gr != NULL)
+             options->admingid = gr->gr_gid;
+    }
+#endif /* ADMIN_GRP */
+
+    q = iniparser_getstrdup(config, INISEC_GLOBAL, "cnid server", "localhost:4700");
+    r = strrchr(q, ':');
+    if (r)
+        *r = 0;
+    options->Cnid_srv = strdup(q);
+    if (r)
+        options->Cnid_port = strdup(r + 1);
+    else
+        options->Cnid_port = strdup("4700");
+    LOG(log_debug, logtype_afpd, "CNID Server: %s:%s", options->Cnid_srv, options->Cnid_port);
+    if (q)
+        free(q);
+
+    if ((q = iniparser_getstrdup(config, INISEC_GLOBAL, "fqdn", NULL))) {
+        /* do a little checking for the domain name. */
+        r = strchr(q, ':');
+        if (r)
+            *r = '\0';
+        if (gethostbyname(q)) {
+            if (r)
+                *r = ':';
+            EC_NULL_LOG( options->fqdn = strdup(q) );
+        } else {
+            LOG(log_error, logtype_afpd, "error parsing -fqdn, gethostbyname failed for: %s", c);
+        }
+        free(q);
+    }
+
+    /* Charset Options */
+
+    /* unix charset is in [G] only */
+    if (!(p = iniparser_getstring(config, INISEC_GLOBAL, "unix charset", NULL))) {
+        options->unixcodepage = strdup("UTF8");
+        set_charset_name(CH_UNIX, "UTF8");
+    } else {
+        if (strcasecmp(p, "LOCALE") == 0) {
+#if defined(CODESET)
+            setlocale(LC_ALL, "");
+            p = nl_langinfo(CODESET);
+            LOG(log_debug, logtype_afpd, "Locale charset is '%s'", p);
+#else /* system doesn't have LOCALE support */
+            LOG(log_warning, logtype_afpd, "system doesn't have LOCALE support");
+            p = strdup("UTF8");
+#endif
+        }
+        if (strcasecmp(p, "UTF-8") == 0) {
+            p = strdup("UTF8");
+        }
+        options->unixcodepage = strdup(p);
+        set_charset_name(CH_UNIX, p);
+    }
+    options->unixcharset = CH_UNIX;
+    LOG(log_debug, logtype_afpd, "Global unix charset is %s", options->unixcodepage);
+
+    /* vol charset is in [G] and [V] */
+    if (!(p = iniparser_getstring(config, INISEC_GLOBAL, "vol charset", NULL))) {
+        options->volcodepage = strdup(options->unixcodepage);
+    } else {
+        if (strcasecmp(p, "UTF-8") == 0) {
+            p = strdup("UTF8");
+        }
+        options->volcodepage = strdup(p);
+    }
+    LOG(log_debug, logtype_afpd, "Global vol charset is %s", options->volcodepage);
+    
+    /* mac charset is in [G] and [V] */
+    if (!(p = iniparser_getstring(config, INISEC_GLOBAL, "mac charset", NULL))) {
+        options->maccodepage = strdup("MAC_ROMAN");
+        set_charset_name(CH_MAC, "MAC_ROMAN");
+    } else {
+        if (strncasecmp(p, "MAC", 3) != 0) {
+            LOG(log_warning, logtype_afpd, "Is '%s' really mac charset? ", p);
+        }
+        options->maccodepage = strdup(p);
+        set_charset_name(CH_MAC, p);
+    }
+    options->maccharset = CH_MAC;
+    LOG(log_debug, logtype_afpd, "Global mac charset is %s", options->maccodepage);
+
+    /* Check for sane values */
+    if (options->tickleval <= 0)
+        options->tickleval = 30;
+        options->disconnected *= 3600 / options->tickleval;
+        options->sleep *= 3600 / options->tickleval;
+    if (options->timeout <= 0)
+        options->timeout = 4;
+    if (options->sleep <= 4)
+        options->disconnected = options->sleep = 4;
+    if (options->dsireadbuf < 6)
+        options->dsireadbuf = 6;
+    if (options->volnamelen < 8)
+        options->volnamelen = 8; /* max mangled volname "???#FFFF" */
+    if (options->volnamelen > 255)
+        options->volnamelen = 255; /* AFP3 spec */
+
+EC_CLEANUP:
+    EC_EXIT;
+}
index 86f05a09230a0ed5b4dd785f48197dd3050f3d06..ada3e61052353b972776eae3fa85046dac7057f1 100644 (file)
 
 #include <stdlib.h>
 #include <string.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif /* HAVE_UNISTD_H */
 #include <signal.h>
 #include <errno.h>
-
-/* POSIX.1 sys/wait.h check */
 #include <sys/types.h>
-#ifdef HAVE_SYS_WAIT_H
 #include <sys/wait.h>
-#endif /* HAVE_SYS_WAIT_H */
 #include <sys/time.h>
 
 #include <atalk/logger.h>
@@ -61,8 +55,6 @@ typedef struct server_child_fork {
     void (*cleanup)(const pid_t);
 } server_child_fork;
 
-int parent_or_child; /* 0: parent, 1: child */
-
 static inline void hash_child(struct server_child_data **htable,
                               struct server_child_data *child)
 {
index e74ce91b1f5a13b1358543e93aa1f21959d84dea..d40e3a49ea4cb07bf1b7984fc418cb5ec11521ee 100644 (file)
@@ -9,9 +9,7 @@
 #endif 
 
 #include <sys/types.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -71,8 +69,8 @@ static int ipc_kill_token(struct ipc_header *ipc, server_child *children)
 /* ----------------- */
 static int ipc_get_session(struct ipc_header *ipc, server_child *children)
 {
-    u_int32_t boottime;
-    u_int32_t idlen;
+    uint32_t boottime;
+    uint32_t idlen;
     char     *clientid, *p;
 
     
@@ -349,4 +347,3 @@ int ipc_child_write(int fd, uint16_t command, int len, void *msg)
 
    return 0;
 }
-
index eaa0c9a7b2c43d4034d4d9f99aaa075618f3c1cf..0251eadaeba94652c2b45474881f648ea1c5dde2 100644 (file)
@@ -37,7 +37,8 @@ pid_t server_lock(char *program, char *pidfile, int debug)
   FILE *pf;
   pid_t pid;
   int mask;
-  
+
+  if ( !debug ) {
   mask = umask(022);
   /* check for pid. this can get fooled by stale pid's. */
   if ((pf = fopen(pidfile, "r"))) {
@@ -60,7 +61,7 @@ pid_t server_lock(char *program, char *pidfile, int debug)
   /*
    * Disassociate from controlling tty.
    */
-  if ( !debug ) {
+
     int                i;
 
     getitimer(ITIMER_PROF, &itimer);
@@ -90,10 +91,11 @@ pid_t server_lock(char *program, char *pidfile, int debug)
       fclose(pf);
       return pid;
     }
-  } 
 
   fprintf(pf, "%d\n", getpid());
   fclose(pf);
+  } 
+
   return 0;
 }
 
diff --git a/libatalk/util/strcasestr.c b/libatalk/util/strcasestr.c
deleted file mode 100644 (file)
index b26c89f..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
-/* Return the offset of one string within another.
-   Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
-   This file is part of the GNU C Library.
-
-   The GNU C Library is free software; you can redistribute it and/or
-   modify it under the terms of the GNU Library General Public License as
-   published by the Free Software Foundation; either version 2 of the
-   License, or (at your option) any later version.
-
-   The GNU C Library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   Library General Public License for more details.
-
-   You should have received a copy of the GNU Library General Public
-   License along with the GNU C Library; see the file COPYING.LIB.  If not,
-   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-   Boston, MA 02111-1307, USA.  */
-
-/*
- * My personal strstr() implementation that beats most other algorithms.
- * Until someone tells me otherwise, I assume that this is the
- * fastest implementation of strstr() in C.
- * I deliberately chose not to comment it.  You should have at least
- * as much fun trying to understand it, as I had to write it :-).
- *
- * Stephen R. van den Berg, berg@pool.informatik.rwth-aachen.de        */
-/* added strcasestr support, davidm@lineo.com */
-
-#if HAVE_CONFIG_H
-# include <config.h>
-#endif
-
-#ifndef HAVE_STRCASESTR 
-
-#if  defined HAVE_STRING_H
-# include <string.h>
-#endif
-
-typedef unsigned chartype;
-
-#include <ctype.h>
-#define VAL(x) tolower(x)
-#define FUNC strcasestr
-#undef strcasestr
-
-char * FUNC ( const char *phaystack, const char *pneedle)
-{
-       register const unsigned char *haystack, *needle;
-       register chartype b, c;
-
-       haystack = (const unsigned char *) phaystack;
-       needle = (const unsigned char *) pneedle;
-
-       b = *needle;
-       if (b != '\0') {
-               haystack--;                             /* possible ANSI violation */
-               do {
-                       c = *++haystack;
-                       if (c == '\0')
-                               goto ret0;
-               }
-               while (VAL(c) != VAL(b));
-
-               c = *++needle;
-               if (c == '\0')
-                       goto foundneedle;
-               ++needle;
-               goto jin;
-
-               for (;;) {
-                       register chartype a;
-                       register const unsigned char *rhaystack, *rneedle;
-
-                       do {
-                               a = *++haystack;
-                               if (a == '\0')
-                                       goto ret0;
-                               if (VAL(a) == VAL(b))
-                                       break;
-                               a = *++haystack;
-                               if (a == '\0')
-                                       goto ret0;
-                 shloop:;}
-                       while (VAL(a) != VAL(b));
-
-                 jin:a = *++haystack;
-                       if (a == '\0')
-                               goto ret0;
-
-                       if (VAL(a) != VAL(c))
-                               goto shloop;
-
-                       rhaystack = haystack-- + 1;
-                       rneedle = needle;
-                       a = *rneedle;
-
-                       if (VAL(*rhaystack) == VAL(a))
-                               do {
-                                       if (a == '\0')
-                                               goto foundneedle;
-                                       ++rhaystack;
-                                       a = *++needle;
-                                       if (VAL(*rhaystack) != VAL(a))
-                                               break;
-                                       if (a == '\0')
-                                               goto foundneedle;
-                                       ++rhaystack;
-                                       a = *++needle;
-                               }
-                               while (VAL(*rhaystack) == VAL(a));
-
-                       needle = rneedle;       /* took the register-poor approach */
-
-                       if (a == '\0')
-                               break;
-               }
-       }
-  foundneedle:
-       return (char *) haystack;
-  ret0:
-       return 0;
-}
-#endif
diff --git a/libatalk/util/strlcpy.c b/libatalk/util/strlcpy.c
deleted file mode 100644 (file)
index 314b039..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
-   Copy from samba lib/replace.c
-
-   Unix SMB/CIFS implementation.
-   replacement routines for broken systems
-   Copyright (C) Andrew Tridgell 1992-1998
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
-   (at your option) any later version.
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
-   You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
-   strlcpy strlcat functions.
-*/
-                          
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <atalk/util.h>
-#include <string.h>
-
-#ifndef HAVE_STRLCPY
-/* like strncpy but does not 0 fill the buffer and always null
-   terminates. bufsize is the size of the destination buffer */
- size_t strlcpy(char *d, const char *s, size_t bufsize)
-{
-        size_t len = strlen(s);
-        size_t ret = len;
-
-        if (bufsize <= 0) 
-               return 0;
-
-        if (len >= bufsize) 
-               len = bufsize-1;
-
-        memcpy(d, s, len);
-        d[len] = 0;
-        return ret;
-}
-#endif
-#ifndef HAVE_STRLCAT
-/* like strncat but does not 0 fill the buffer and always null
-   terminates. bufsize is the length of the buffer, which should
-   be one more than the maximum resulting string length */
- size_t strlcat(char *d, const char *s, size_t bufsize)
-{
-        size_t len1 = strlen(d);
-        size_t len2 = strlen(s);
-        size_t ret = len1 + len2;
-
-       if (len1 >= bufsize) {
-               return 0;
-       } 
-        if (len1+len2 >= bufsize) {
-                len2 = bufsize - (len1+1);
-        }
-        if (len2 > 0) {
-                memcpy(d+len1, s, len2);
-                d[len1+len2] = 0;
-        }
-        return ret;
-}
-#endif
index 0e466307bcd30d6ad13ec3af0c8444be0b26bd45..56c3e168eaea05c05705464a0f21830aedf60c03 100644 (file)
@@ -32,6 +32,7 @@
 #include <dirent.h>
 #include <sys/time.h>
 #include <time.h>
+#include <sys/wait.h>
 
 #include <atalk/adouble.h>
 #include <atalk/ea.h>
@@ -40,6 +41,8 @@
 #include <atalk/vfs.h>
 #include <atalk/util.h>
 #include <atalk/unix.h>
+#include <atalk/compat.h>
+#include <atalk/errchk.h>
 
 /* close all FDs >= a specified value */
 static void closeall(int fd)
@@ -50,6 +53,55 @@ static void closeall(int fd)
         close(fd++);
 }
 
+/*!
+ * Run command in a child and wait for it to finish
+ */
+int run_cmd(const char *cmd, char **cmd_argv)
+{
+    EC_INIT;
+    pid_t pid, wpid;
+    sigset_t sigs, oldsigs;
+       int status = 0;
+
+    sigfillset(&sigs);
+    pthread_sigmask(SIG_SETMASK, &sigs, &oldsigs);
+
+    if ((pid = fork()) < 0) {
+        LOG(log_error, logtype_default, "run_cmd: fork: %s", strerror(errno));
+        return -1;
+    }
+
+    if (pid == 0) {
+        /* child */
+        closeall(3);
+        execvp("mv", cmd_argv);
+    }
+
+    /* parent */
+       while ((wpid = waitpid(pid, &status, 0)) < 0) {
+           if (errno == EINTR)
+            continue;
+           break;
+       }
+       if (wpid != pid) {
+           LOG(log_error, logtype_default, "waitpid(%d): %s", (int)pid, strerror(errno));
+        EC_FAIL;
+       }
+
+    if (WIFEXITED(status))
+        status = WEXITSTATUS(status);
+    else if (WIFSIGNALED(status))
+        status = WTERMSIG(status);
+
+    LOG(log_note, logtype_default, "run_cmd(\"%s\"): status: %d", cmd, status);
+
+EC_CLEANUP:
+    if (status != 0)
+        ret = status;
+    pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
+    EC_EXIT;
+}
+
 /*!
  * Daemonize
  *
@@ -94,6 +146,29 @@ int daemonize(int nochdir, int noclose)
     return 0;
 }
 
+static uid_t saved_uid = -1;
+
+/*
+ * seteuid(0) and back, if either fails and panic != 0 we PANIC
+ */
+void become_root(void)
+{
+    if (getuid() == 0) {
+        saved_uid = geteuid();
+        if (seteuid(0) != 0)
+            AFP_PANIC("Can't seteuid(0)");
+    }
+}
+
+void unbecome_root(void)
+{
+    if (getuid() == 0) {
+        if (saved_uid == -1 || seteuid(saved_uid) < 0)
+            AFP_PANIC("Can't seteuid back");
+        saved_uid = -1;
+    }
+}
+
 /*!
  * @brief get cwd in static buffer
  *
@@ -255,3 +330,15 @@ void randombytes(void *buf, int n)
 
     return;
 }
+
+int gmem(gid_t gid, int ngroups, gid_t *groups)
+{
+    int                i;
+
+    for ( i = 0; i < ngroups; i++ ) {
+        if ( groups[ i ] == gid ) {
+            return( 1 );
+        }
+    }
+    return( 0 );
+}
diff --git a/libatalk/util/volinfo.c b/libatalk/util/volinfo.c
deleted file mode 100644 (file)
index 671f57f..0000000
+++ /dev/null
@@ -1,624 +0,0 @@
-/*
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
-   (at your option) any later version.
-
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
-
-   You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
-   .volinfo file handling, command line utilities
-   copyright Bjoern Fernhomberg, 2004
-*/
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <unistd.h>
-#include <sys/types.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#ifdef HAVE_STRINGS_H
-#include <strings.h>
-#endif
-#ifdef STDC_HEADERS
-#include <string.h>
-#endif
-#include <sys/param.h>
-
-#include <atalk/adouble.h>
-#include <atalk/util.h>
-#include <atalk/logger.h>
-#include <atalk/volinfo.h>
-#include <atalk/volume.h>
-#ifdef CNID_DB
-#include <atalk/cnid.h>
-#endif /* CNID_DB*/
-
-static const vol_opt_name_t vol_opt_names[] = {
-    {AFPVOL_A2VOL,      "PRODOS"},      /* prodos volume */
-    {AFPVOL_CRLF,       "CRLF"},        /* cr/lf translation */
-    {AFPVOL_NOADOUBLE,  "NOADOUBLE"},   /* don't create .AppleDouble by default */
-    {AFPVOL_RO,         "READONLY"},    /* read-only volume */
-    {AFPVOL_MSWINDOWS,  "MSWINDOWS"},   /* deal with ms-windows yuckiness. this is going away. */
-    {AFPVOL_NOHEX,      "NOHEX"},       /* don't do :hex translation */
-    {AFPVOL_USEDOTS,    "USEDOTS"},     /* use real dots */
-    {AFPVOL_LIMITSIZE,  "LIMITSIZE"},   /* limit size for older macs */
-    {AFPVOL_MAPASCII,   "MAPASCII"},    /* map the ascii range as well */
-    {AFPVOL_DROPBOX,    "DROPBOX"},     /* dropkludge dropbox support */
-    {AFPVOL_NOFILEID,   "NOFILEID"},    /* don't advertise createid resolveid and deleteid calls */
-    {AFPVOL_NOSTAT,     "NOSTAT"},      /* advertise the volume even if we can't stat() it
-                                         * maybe because it will be mounted later in preexec */
-    {AFPVOL_UNIX_PRIV,  "UNIXPRIV"},    /* support unix privileges */
-    {AFPVOL_NODEV,      "NODEV"},       /* always use 0 for device number in cnid calls */
-    {AFPVOL_CASEINSEN,  "CASEINSENSITIVE"}, /* volume is case insensitive */
-    {AFPVOL_EILSEQ,     "ILLEGALSEQ"},  /* encode illegal sequence */
-    {AFPVOL_CACHE,      "CACHEID"},     /* Use adouble v2 CNID caching, default don't use it */
-    {AFPVOL_INV_DOTS,   "INVISIBLEDOTS"}, 
-    {AFPVOL_ACLS,       "ACLS"},        /* Vol supports ACLs */
-    {AFPVOL_TM,         "TM"},          /* Set "kSupportsTMLockSteal" is volume attributes */
-    {0, NULL}
-};
-
-static const vol_opt_name_t vol_opt_casefold[] = {
-    {AFPVOL_MTOUUPPER,  "MTOULOWER"},
-    {AFPVOL_MTOULOWER,  "MTOULOWER"},
-    {AFPVOL_UTOMUPPER,  "UTOMUPPER"},
-    {AFPVOL_UTOMLOWER,  "UTOMLOWER"},
-    {0, NULL}
-};
-
-typedef struct {
-    const char *name;
-    int type;
-} info_option_t;
-
-#define MAC_CHARSET 0
-#define VOL_CHARSET 1
-#define ADOUBLE_VER 2
-#define CNIDBACKEND 3
-#define CNIDDBDHOST 4
-#define CNIDDBDPORT 5
-#define CNID_DBPATH 6
-#define VOLUME_OPTS 7
-#define VOLCASEFOLD 8
-#define EXTATTRTYPE 9
-
-static const info_option_t info_options[] = {
-    {"MAC_CHARSET", MAC_CHARSET},
-    {"VOL_CHARSET", VOL_CHARSET},
-    {"ADOUBLE_VER", ADOUBLE_VER},
-    {"CNIDBACKEND", CNIDBACKEND},
-    {"CNIDDBDHOST", CNIDDBDHOST},
-    {"CNIDDBDPORT", CNIDDBDPORT},
-    {"CNID_DBPATH", CNID_DBPATH},
-    {"VOLUME_OPTS", VOLUME_OPTS},
-    {"VOLCASEFOLD", VOLCASEFOLD},
-    {"EXTATTRTYPE", EXTATTRTYPE},
-   {NULL, 0}
-};
-
-static char* find_in_path( char *path, char *subdir, size_t maxlen)
-{
-    char       *pos;
-    struct stat st;
-
-    strlcat(path, subdir, maxlen);
-    pos = strrchr(path, '/');
-
-    while ( stat(path, &st) != 0) {
-        path[pos-path]=0;
-        if ((pos = strrchr(path, '/'))) {
-            path[pos-path]=0;
-            strlcat(path, subdir, maxlen);
-        }
-        else {
-            return NULL;
-        }
-    }
-
-    path[pos-path] = '/';
-    path[pos-path+1] = 0;
-
-    return path;
-}
-
-static char * make_path_absolute(char *path, size_t bufsize)
-{
-    struct     stat st;
-    char       savecwd[MAXPATHLEN];
-    char       abspath[MAXPATHLEN];
-    char       *p;
-
-    strlcpy(abspath, path, sizeof(abspath));
-
-    /* we might be called from `ad cp ...` with non existing target */
-    if (stat(abspath, &st) != 0) {
-        if (errno != ENOENT)
-            return NULL;
-
-        if (NULL == (p = strrchr(abspath, '/')) )
-            /* single component `ad cp SOURCEFILE TARGETFILE`, use "." instead */
-            strcpy(abspath, ".");
-        else
-            /* try without the last path element */
-            *p = '\0';
-
-        if (stat(abspath, &st) != 0) {
-            return NULL;
-        }
-    }
-
-    if (S_ISREG(st.st_mode)) {
-        /* single file copy SOURCE */
-        if (NULL == (p = strrchr(abspath, '/')) )
-            /* no path, use "." instead */
-            strcpy(abspath, ".");
-        else
-            /* try without the last path element */
-            *p = '\0';
-    }
-
-    if (!getcwd(savecwd, sizeof(savecwd)) || chdir(abspath) < 0)       
-        return NULL;
-
-    if (!getcwd(abspath, sizeof(abspath)) || chdir (savecwd) < 0)
-        return NULL;
-    
-    if (strlen(abspath) > bufsize)
-        return NULL;
-
-    strlcpy(path, abspath, bufsize);
-    return path;
-}
-
-static char * find_volumeroot(char *path, size_t maxlen)
-{
-    char *volume = make_path_absolute(path, maxlen);
-        
-    if (volume == NULL)
-       return NULL;
-
-    if (NULL == (find_in_path(volume, "/.AppleDesktop", maxlen)) )
-       return NULL;
-
-    return volume;
-}
-
-int vol_load_charsets( struct volinfo *vol)
-{
-    if ( (charset_t) -1 == ( vol->v_maccharset = add_charset(vol->v_maccodepage)) ) {
-        fprintf( stderr, "Setting codepage %s as Mac codepage failed", vol->v_maccodepage);
-        return (-1);
-    }
-
-    if ( (charset_t) -1 == ( vol->v_volcharset = add_charset(vol->v_volcodepage)) ) {
-        fprintf( stderr, "Setting codepage %s as volume codepage failed", vol->v_volcodepage);
-        return (-1);
-    }
-
-    return 0;
-}
-
-static int parse_options (char *buf, int *flags, const vol_opt_name_t *options)
-{
-    char *p, *q;
-    const vol_opt_name_t *op;
-
-    q = p = buf; 
-
-    while ( *p != '\0') {
-        if (*p == ' ') {
-            *p = '\0';
-            op = options;
-            for (;op->name; op++) {
-                if ( !strcmp(op->name, q )) {
-                    *flags |= op->option;
-                    break;
-                }
-            }
-            q = p+1;
-        }
-        p++;
-    }
-
-    return 0;
-} 
-            
-
-
-static int parseline ( char *buf, struct volinfo *vol)
-{
-    char *value;
-    size_t len;
-    int  option=-1;
-    const info_option_t  *p  = &info_options[0];
-
-    if (NULL == ( value = strchr(buf, ':')) )
-       return 1;
-
-    *value = '\0';
-    value++;
-
-    if ( 0 == (len = strlen(value)) )
-        return 0;
-
-    if (value[len-1] == '\n')
-        value[len-1] = '\0';
-
-    for (;p->name; p++) {
-        if ( !strcmp(p->name, buf )) {
-            option=p->type;
-            break;
-        }
-    }
-
-    switch (option) {
-      case MAC_CHARSET:
-        if ((vol->v_maccodepage = strdup(value)) == NULL) {
-           fprintf (stderr, "strdup: %s", strerror(errno));
-            return -1;
-        }
-        break;
-      case VOL_CHARSET:
-        if ((vol->v_volcodepage = strdup(value)) == NULL) {
-           fprintf (stderr, "strdup: %s", strerror(errno));
-            return -1;
-        }
-        break;
-      case CNIDBACKEND:
-        if ((vol->v_cnidscheme = strdup(value)) == NULL) {
-           fprintf (stderr, "strdup: %s", strerror(errno));
-            return -1;
-        }
-        break;
-      case CNIDDBDHOST:
-        if ((vol->v_dbd_host = strdup(value)) == NULL) {
-           fprintf (stderr, "strdup: %s", strerror(errno));
-            return -1;
-        }
-        break;
-      case CNIDDBDPORT:
-        if ((vol->v_dbd_port = strdup(value)) == NULL) {
-           fprintf (stderr, "strdup: %s", strerror(errno));
-            return -1;            
-        }
-        break;
-      case CNID_DBPATH:
-          if ((vol->v_dbpath = malloc(MAXPATHLEN+1)) == NULL)
-              return -1;
-          strcpy(vol->v_dbpath, value);
-        break;
-      case ADOUBLE_VER:
-        if (strcasecmp(value, "v1") == 0) {
-            vol->v_adouble = AD_VERSION1;
-            vol->ad_path = ad_path;
-        }
-#if AD_VERSION == AD_VERSION2
-        else if (strcasecmp(value, "v2") == 0) {
-            vol->ad_path = ad_path;
-            vol->v_adouble = AD_VERSION2;
-        }
-        else if (strcasecmp(value, "osx") == 0) {
-            vol->v_adouble = AD_VERSION2_OSX;
-            vol->ad_path = ad_path_osx;
-        }
-#endif
-        else  {
-           fprintf (stderr, "unknown adouble version: %s, %s", buf, value);
-           return -1;
-        }
-        break;
-      case VOLUME_OPTS:
-        parse_options(value, &vol->v_flags, &vol_opt_names[0]);
-        break;
-      case VOLCASEFOLD:
-        parse_options(value, &vol->v_casefold, &vol_opt_casefold[0]);
-        break;
-    case EXTATTRTYPE:
-        if (strcasecmp(value, "AFPVOL_EA_AD") == 0)    
-            vol->v_vfs_ea = AFPVOL_EA_AD;
-        else if (strcasecmp(value, "AFPVOL_EA_SYS") == 0)
-            vol->v_vfs_ea = AFPVOL_EA_SYS;
-        break;
-      default:
-       fprintf (stderr, "unknown volume information: %s, %s", buf, value);
-       return (-1);
-        break;
-    }
-        
-    return 0;
-}
-    
-
-int loadvolinfo (char *path, struct volinfo *vol)
-{
-
-    char   volinfofile[MAXPATHLEN];
-    char   buf[MAXPATHLEN];
-    struct flock lock;
-    int    fd, len;
-    FILE   *fp;
-
-    if ( !path || !vol)
-        return -1;
-
-    memset(vol, 0, sizeof(struct volinfo));
-    strlcpy(volinfofile, path, sizeof(volinfofile));
-
-    /* volinfo file is in .AppleDesktop */ 
-    if ( NULL == find_volumeroot(volinfofile, sizeof(volinfofile)))
-        return -1;
-
-    if ((vol->v_path = strdup(volinfofile)) == NULL ) {
-        fprintf (stderr, "strdup: %s", strerror(errno));
-        return (-1);
-    }
-    /* Remove trailing slashes */
-    len = strlen(vol->v_path);
-    while (len && (vol->v_path[len-1] == '/')) {
-        vol->v_path[len-1] = 0;
-        len--;
-    }
-
-    strlcat(volinfofile, ".AppleDesktop/", sizeof(volinfofile));
-    strlcat(volinfofile, VOLINFOFILE, sizeof(volinfofile));
-
-    /* open the file read only */
-    if ( NULL == (fp = fopen( volinfofile, "r")) )  {
-       fprintf (stderr, "error opening volinfo (%s): %s", volinfofile, strerror(errno));
-        return (-1);
-    }
-    fd = fileno(fp); 
-
-    /* try to get a read lock */ 
-    lock.l_start  = 0;
-    lock.l_whence = SEEK_SET;
-    lock.l_len    = 0;
-    lock.l_type   = F_RDLCK;
-
-    /* wait for read lock */
-    if (fcntl(fd, F_SETLKW, &lock) < 0) {
-        fclose(fp);
-        return (-1);
-    }
-
-    /* read the file */
-    while (NULL != fgets(buf, sizeof(buf), fp)) {
-        parseline(buf, vol);
-    }
-
-    /* unlock file */
-    lock.l_type = F_UNLCK;
-    fcntl(fd, F_SETLK, &lock);
-
-    /* Translate vol options to ad options like afp/volume.c does it */
-    vol->v_ad_options = 0;
-    if ((vol->v_flags & AFPVOL_NODEV))
-        vol->v_ad_options |= ADVOL_NODEV;
-    if ((vol->v_flags & AFPVOL_CACHE))
-        vol->v_ad_options |= ADVOL_CACHE;
-    if ((vol->v_flags & AFPVOL_UNIX_PRIV))
-        vol->v_ad_options |= ADVOL_UNIXPRIV;
-    if ((vol->v_flags & AFPVOL_INV_DOTS))
-        vol->v_ad_options |= ADVOL_INVDOTS;
-
-    vol->retaincount = 1;
-
-    fclose(fp);
-    return 0;
-}
-
-/*!
- * Allocate a struct volinfo object for refcounting usage with retain and close, and
- * call loadvolinfo with it
- */
-struct volinfo *allocvolinfo(char *path)
-{
-    struct volinfo *p = malloc(sizeof(struct volinfo));
-    if (p == NULL)
-        return NULL;
-
-    if (loadvolinfo(path, p) == -1)
-        return NULL;
-
-    p->malloced = 1;
-
-    return p;
-}
-
-void retainvolinfo(struct volinfo *vol)
-{
-    vol->retaincount++;
-}
-
-/*!
- * Decrement retain count, free resources when retaincount reaches 0
- */
-int closevolinfo(struct volinfo *volinfo)
-{
-    if (volinfo->retaincount <= 0)
-        abort();
-
-    volinfo->retaincount--;
-
-    if (volinfo->retaincount == 0) {
-        free(volinfo->v_name); volinfo->v_name = NULL;
-        free(volinfo->v_path); volinfo->v_path = NULL;
-        free(volinfo->v_cnidscheme); volinfo->v_cnidscheme = NULL;
-        free(volinfo->v_dbpath); volinfo->v_dbpath = NULL;
-        free(volinfo->v_volcodepage); volinfo->v_volcodepage = NULL;
-        free(volinfo->v_maccodepage); volinfo->v_maccodepage = NULL;
-        free(volinfo->v_dbd_host); volinfo->v_dbd_host = NULL;
-        free(volinfo->v_dbd_port); volinfo->v_dbd_port = NULL;
-        if (volinfo->malloced) {
-            volinfo->malloced = 0;
-            free(volinfo);
-        }
-    }
-
-    return 0;
-}
-
-/*
- * Save the volume options to a file, used by shell utilities. Writing the file
- * everytime a volume is opened is unnecessary, but it shouldn't hurt much.
- */
-int savevolinfo(const struct vol *vol, const char *Cnid_srv, const char *Cnid_port)
-{
-    uid_t process_uid;
-    char buf[16348];
-    char item[MAXPATHLEN];
-    int fd;
-    int ret = 0;
-    struct flock lock;
-    const vol_opt_name_t *op = &vol_opt_names[0];
-    const vol_opt_name_t *cf = &vol_opt_casefold[0];
-
-    strlcpy (item, vol->v_path, sizeof(item));
-    strlcat (item, "/.AppleDesktop/", sizeof(item));
-    strlcat (item, VOLINFOFILE, sizeof(item));
-
-    process_uid = geteuid();
-    if (process_uid) {
-        if (seteuid(0) == -1) {
-            process_uid = 0;
-        }
-    }
-
-    if ((fd = open(item, O_RDWR | O_CREAT , 0666)) <0 ) {
-        LOG(log_debug, logtype_default,"Error opening %s: %s", item, strerror(errno));
-        if (process_uid) {
-            if (seteuid(process_uid) == -1) {
-                LOG(log_error, logtype_default, "can't seteuid back %s", strerror(errno));
-                exit(EXITERR_SYS);
-            }
-        }
-        return (-1);
-    }
-
-    if (process_uid) {
-        if (seteuid(process_uid) == -1) {
-            LOG(log_error, logtype_default, "can't seteuid back %s", strerror(errno));
-            exit(EXITERR_SYS);
-        }
-    }
-
-    /* try to get a lock */
-    lock.l_start  = 0;
-    lock.l_whence = SEEK_SET;
-    lock.l_len    = 0;
-    lock.l_type   = F_WRLCK;
-
-    if (fcntl(fd, F_SETLK, &lock) < 0) {
-        close(fd);
-        if (errno == EACCES || errno == EAGAIN) {
-            /* ignore, other process already writing the file */
-            return 0;
-        } else {
-            LOG(log_error, logtype_default, "savevoloptions: cannot get lock: %s", strerror(errno));
-            return (-1);
-        }
-    }
-
-    /* write volume options */
-    snprintf(buf, sizeof(buf), "MAC_CHARSET:%s\n", vol->v_maccodepage);
-    snprintf(item, sizeof(item), "VOL_CHARSET:%s\n", vol->v_volcodepage);
-    strlcat(buf, item, sizeof(buf));
-
-    switch (vol->v_adouble) {
-        case AD_VERSION1:
-            strlcat(buf, "ADOUBLE_VER:v1\n", sizeof(buf));
-            break;
-        case AD_VERSION2:
-            strlcat(buf, "ADOUBLE_VER:v2\n", sizeof(buf));
-            break;
-        case AD_VERSION2_OSX:
-            strlcat(buf, "ADOUBLE_VER:osx\n", sizeof(buf));
-            break;
-        case AD_VERSION1_SFM:
-            strlcat(buf, "ADOUBLE_VER:sfm\n", sizeof(buf));
-            break;
-    }
-
-    strlcat(buf, "CNIDBACKEND:", sizeof(buf));
-    strlcat(buf, vol->v_cnidscheme, sizeof(buf));
-    strlcat(buf, "\n", sizeof(buf));
-
-    strlcat(buf, "CNIDDBDHOST:", sizeof(buf));
-    strlcat(buf, Cnid_srv, sizeof(buf));
-    strlcat(buf, "\n", sizeof(buf));
-
-    strlcat(buf, "CNIDDBDPORT:", sizeof(buf));
-    strlcat(buf, Cnid_port, sizeof(buf));
-    strlcat(buf, "\n", sizeof(buf));
-
-    strcpy(item, "CNID_DBPATH:");
-    if (vol->v_dbpath)
-        strlcat(item, vol->v_dbpath, sizeof(item));
-    else
-        strlcat(item, vol->v_path, sizeof(item));
-    strlcat(item, "\n", sizeof(item));
-    strlcat(buf, item, sizeof(buf));
-
-    /* volume flags */
-    strcpy(item, "VOLUME_OPTS:");
-    for (;op->name; op++) {
-       if ( (vol->v_flags & op->option) ) {
-            strlcat(item, op->name, sizeof(item));
-            strlcat(item, " ", sizeof(item));
-        }
-    }
-    strlcat(item, "\n", sizeof(item));
-    strlcat(buf, item, sizeof(buf));
-
-    /* casefold flags */
-    strcpy(item, "VOLCASEFOLD:");
-    for (;cf->name; cf++) {
-        if ( (vol->v_casefold & cf->option) ) {
-            strlcat(item, cf->name, sizeof(item));
-            strlcat(item, " ", sizeof(item));
-        }
-    }
-    strlcat(item, "\n", sizeof(item));
-    strlcat(buf, item, sizeof(buf));
-
-    /* ExtendedAttributes */
-    strcpy(item, "EXTATTRTYPE:");
-    switch (vol->v_vfs_ea) {
-    case AFPVOL_EA_SYS:
-        strlcat(item, "AFPVOL_EA_SYS\n", sizeof(item));
-        break;
-    case AFPVOL_EA_AD:
-        strlcat(item, "AFPVOL_EA_AD\n", sizeof(item));
-        break;
-    case AFPVOL_EA_NONE:
-        strlcat(item, "AFPVOL_EA_NONE\n", sizeof(item));
-        break;
-    default:
-        strlcat(item, "AFPVOL_EA_UNKNOWN\n", sizeof(item));
-    }
-
-    strlcat(buf, item, sizeof(buf));
-
-    if (strlen(buf) >= sizeof(buf)-1)
-        LOG(log_debug, logtype_default, "Error writing .volinfo file: buffer too small, %s", buf);
-   if (write( fd, buf, strlen(buf)) < 0 || ftruncate(fd, strlen(buf)) < 0 ) {
-       LOG(log_debug, logtype_default, "Error writing .volinfo file: %s", strerror(errno));
-   }
-
-   lock.l_type = F_UNLCK;
-   fcntl(fd, F_SETLK, &lock);
-   close (fd);
-   return ret;
-}
index 9b8d14374c8e4fbb6aeaa86716ce7aff2af73c09..aa62aebffbd591e4a057b23bfe707bfab9eebdb4 100644 (file)
@@ -2,7 +2,7 @@
 
 noinst_LTLIBRARIES = libvfs.la
 
-libvfs_la_SOURCES = vfs.c unix.c ea.c sys_ea.c ea_sys.c
+libvfs_la_SOURCES = vfs.c unix.c ea_ad.c ea_sys.c extattr.c
 
 if HAVE_ACLS
 libvfs_la_SOURCES += acl.c
diff --git a/libatalk/vfs/ea.c b/libatalk/vfs/ea.c
deleted file mode 100644 (file)
index abe266f..0000000
+++ /dev/null
@@ -1,1770 +0,0 @@
-/*
-  Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
-
-  This program is free software; you can redistribute it and/or modify
-  it under the terms of the GNU General Public License as published by
-  the Free Software Foundation; either version 2 of the License, or
-  (at your option) any later version.
-
-  This program is distributed in the hope that it will be useful,
-  but WITHOUT ANY WARRANTY; without even the implied warranty of
-  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-  GNU General Public License for more details.
-*/
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <unistd.h>
-#include <stdint.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <dirent.h>
-
-#include <atalk/adouble.h>
-#include <atalk/ea.h>
-#include <atalk/afp.h>
-#include <atalk/logger.h>
-#include <atalk/volume.h>
-#include <atalk/vfs.h>
-#include <atalk/util.h>
-#include <atalk/unix.h>
-
-/*
- * Store Extended Attributes inside .AppleDouble folders as follows:
- *
- * filename "fileWithEAs" with EAs "testEA1" and "testEA2"
- *
- * - create header with with the format struct adouble_ea_ondisk, the file is written to
- *   ".AppleDouble/fileWithEAs::EA"
- * - store EAs in files "fileWithEAs::EA::testEA1" and "fileWithEAs::EA::testEA2"
- */
-
-/* 
- * Build mode for EA header from file mode
- */
-static inline mode_t ea_header_mode(mode_t mode)
-{
-    /* Same as ad_hf_mode(mode) */
-    mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
-    /* Owner must be able to open, read and w-lock it, in order to chmod from eg 0000 -> 0xxxx*/
-    mode |= S_IRUSR | S_IWUSR;
-    return mode;
-}
-
-/* 
- * Build mode for EA file from file mode
- */
-static inline mode_t ea_mode(mode_t mode)
-{
-    /* Same as ad_hf_mode(mode) */
-    mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
-    return mode;
-}
-
-/*
-  Taken form afpd/desktop.c
-*/
-static char *mtoupath(const struct vol *vol, const char *mpath)
-{
-    static char  upath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
-    const char   *m;
-    char         *u;
-    size_t       inplen;
-    size_t       outlen;
-    uint16_t     flags = CONV_ESCAPEHEX | CONV_ALLOW_COLON;
-
-    if (!mpath)
-        return NULL;
-
-    if ( *mpath == '\0' ) {
-        return( "." );
-    }
-
-    m = mpath;
-    u = upath;
-
-    inplen = strlen(m);
-    outlen = MAXPATHLEN;
-
-    if ((size_t)-1 == (outlen = convert_charset(CH_UTF8_MAC,
-                                                vol->v_volcharset,
-                                                vol->v_maccharset,
-                                                m, inplen, u, outlen, &flags)) ) {
-        return NULL;
-    }
-
-    return( upath );
-}
-
-
-/*
- * Function: unpack_header
- *
- * Purpose: unpack and verify header file data buffer at ea->ea_data into struct ea
- *
- * Arguments:
- *
- *    ea      (rw) handle to struct ea
- *
- * Returns: 0 on success, -1 on error
- *
- * Effects:
- *
- * Verifies magic and version.
- */
-static int unpack_header(struct ea * restrict ea)
-{
-    int ret = 0;
-    unsigned int count = 0;
-    uint32_t uint32;
-    char *buf;
-
-    /* Check magic and version */
-    buf = ea->ea_data;
-    if (*(uint32_t *)buf != htonl(EA_MAGIC)) {
-        LOG(log_error, logtype_afpd, "unpack_header: wrong magic 0x%08x", *(uint32_t *)buf);
-        ret = -1;
-        goto exit;
-    }
-    buf += 4;
-    if (*(uint16_t *)buf != htons(EA_VERSION)) {
-        LOG(log_error, logtype_afpd, "unpack_header: wrong version 0x%04x", *(uint16_t *)buf);
-        ret = -1;
-        goto exit;
-    }
-    buf += 2;
-
-    /* Get EA count */
-    ea->ea_count = ntohs(*(uint16_t *)buf);
-    LOG(log_debug, logtype_afpd, "unpack_header: number of EAs: %u", ea->ea_count);
-    buf += 2;
-
-    if (ea->ea_count == 0)
-        return 0;
-
-    /* Allocate storage for the ea_entries array */
-    ea->ea_entries = malloc(sizeof(struct ea_entry) * ea->ea_count);
-    if ( ! ea->ea_entries) {
-        LOG(log_error, logtype_afpd, "unpack_header: OOM");
-        ret = -1;
-        goto exit;
-    }
-
-    buf = ea->ea_data + EA_HEADER_SIZE;
-    while (count < ea->ea_count) {
-        memcpy(&uint32, buf, 4); /* EA size */
-        buf += 4;
-        (*(ea->ea_entries))[count].ea_size = ntohl(uint32);
-        (*(ea->ea_entries))[count].ea_name = strdup(buf);
-        if (! (*(ea->ea_entries))[count].ea_name) {
-            LOG(log_error, logtype_afpd, "unpack_header: OOM");
-            ret = -1;
-            goto exit;
-        }
-        (*(ea->ea_entries))[count].ea_namelen = strlen((*(ea->ea_entries))[count].ea_name);
-        buf += (*(ea->ea_entries))[count].ea_namelen + 1;
-
-        LOG(log_maxdebug, logtype_afpd, "unpack_header: entry no:%u,\"%s\", size: %u, namelen: %u", count,
-            (*(ea->ea_entries))[count].ea_name,
-            (*(ea->ea_entries))[count].ea_size,
-            (*(ea->ea_entries))[count].ea_namelen);
-
-        count++;
-    }
-
-exit:
-    return ret;
-}
-
-/*
- * Function: pack_header
- *
- * Purpose: pack everything from struct ea into buffer at ea->ea_data
- *
- * Arguments:
- *
- *    ea      (rw) handle to struct ea
- *
- * Returns: 0 on success, -1 on error
- *
- * Effects:
- *
- * adjust ea->ea_count in case an ea entry deletetion is detected
- */
-static int pack_header(struct ea * restrict ea)
-{
-    unsigned int count = 0, eacount = 0;
-    uint16_t uint16;
-    uint32_t uint32;
-    size_t bufsize = EA_HEADER_SIZE;
-
-    char *buf = ea->ea_data + EA_HEADER_SIZE;
-
-    LOG(log_debug, logtype_afpd, "pack_header('%s'): ea_count: %u, ea_size: %u",
-        ea->filename, ea->ea_count, ea->ea_size);
-
-    if (ea->ea_count == 0)
-        /* nothing to do, magic, version and count are still valid in buffer */
-        return 0;
-
-    while(count < ea->ea_count) { /* the names */
-        /* Check if its a deleted entry */
-        if ( ! ((*ea->ea_entries)[count].ea_name)) {
-            count++;
-            continue;
-        }
-
-        bufsize += (*(ea->ea_entries))[count].ea_namelen + 1;
-        count++;
-        eacount++;
-    }
-
-    bufsize += (eacount * 4); /* header + ea_size for each EA */
-    if (bufsize > ea->ea_size) {
-        /* we must realloc */
-        if ( ! (buf = realloc(ea->ea_data, bufsize)) ) {
-            LOG(log_error, logtype_afpd, "pack_header: OOM");
-            return -1;
-        }
-        ea->ea_data = buf;
-    }
-    ea->ea_size = bufsize;
-
-    /* copy count */
-    uint16 = htons(eacount);
-    memcpy(ea->ea_data + EA_COUNT_OFF, &uint16, 2);
-
-    count = 0;
-    buf = ea->ea_data + EA_HEADER_SIZE;
-    while (count < ea->ea_count) {
-        /* Check if its a deleted entry */
-        if ( ! ((*ea->ea_entries)[count].ea_name)) {
-            count++;
-            continue;
-        }
-
-        /* First: EA size */
-        uint32 = htonl((*(ea->ea_entries))[count].ea_size);
-        memcpy(buf, &uint32, 4);
-        buf += 4;
-
-        /* Second: EA name as C-string */
-        strcpy(buf, (*(ea->ea_entries))[count].ea_name);
-        buf += (*(ea->ea_entries))[count].ea_namelen + 1;
-
-        LOG(log_maxdebug, logtype_afpd, "pack_header: entry no:%u,\"%s\", size: %u, namelen: %u", count,
-            (*(ea->ea_entries))[count].ea_name,
-            (*(ea->ea_entries))[count].ea_size,
-            (*(ea->ea_entries))[count].ea_namelen);
-
-        count++;
-    }
-
-    ea->ea_count = eacount;
-
-    LOG(log_debug, logtype_afpd, "pack_header('%s'): ea_count: %u, ea_size: %u",
-        ea->filename, ea->ea_count, ea->ea_size);
-    
-    return 0;
-}
-
-/*
- * Function: ea_addentry
- *
- * Purpose: add one EA into ea->ea_entries[]
- *
- * Arguments:
- *
- *    ea            (rw) pointer to struct ea
- *    attruname     (r) name of EA
- *    attrsize      (r) size of ea
- *    bitmap        (r) bitmap from FP func
- *
- * Returns: new number of EA entries, -1 on error
- *
- * Effects:
- *
- * Grow array ea->ea_entries[]. If ea->ea_entries is still NULL, start allocating.
- * Otherwise realloc and put entry at the end. Increments ea->ea_count.
- */
-static int ea_addentry(struct ea * restrict ea,
-                       const char * restrict attruname,
-                       size_t attrsize,
-                       int bitmap)
-{
-    int ea_existed = 0;
-    unsigned int count = 0;
-    void *tmprealloc;
-
-    /* First check if an EA of the requested name already exist */
-    if (ea->ea_count > 0) {
-        while (count < ea->ea_count) {
-            if (strcmp(attruname, (*ea->ea_entries)[count].ea_name) == 0) {
-                ea_existed = 1;
-                LOG(log_debug, logtype_afpd, "ea_addentry('%s', bitmap:0x%x): exists", attruname, bitmap);
-                if (bitmap & kXAttrCreate)
-                    /* its like O_CREAT|O_EXCL -> fail */
-                    return -1;
-                (*(ea->ea_entries))[count].ea_size = attrsize;
-                return 0;
-            }
-            count++;
-        }
-    }
-
-    if ((bitmap & kXAttrReplace) && ! ea_existed)
-        /* replace was requested, but EA didn't exist */
-        return -1;
-
-    if (ea->ea_count == 0) {
-        ea->ea_entries = malloc(sizeof(struct ea_entry));
-        if ( ! ea->ea_entries) {
-            LOG(log_error, logtype_afpd, "ea_addentry: OOM");
-            return -1;
-        }
-    } else if (! ea_existed) {
-        tmprealloc = realloc(ea->ea_entries, sizeof(struct ea_entry) * (ea->ea_count + 1));
-        if ( ! tmprealloc) {
-            LOG(log_error, logtype_afpd, "ea_addentry: OOM");
-            return -1;
-        }
-        ea->ea_entries = tmprealloc;
-    }
-
-    /* We've grown the array, now store the entry */
-    (*(ea->ea_entries))[ea->ea_count].ea_size = attrsize;
-    (*(ea->ea_entries))[ea->ea_count].ea_name = strdup(attruname);
-    if ( ! (*(ea->ea_entries))[ea->ea_count].ea_name) {
-        LOG(log_error, logtype_afpd, "ea_addentry: OOM");
-        goto error;
-    }
-    (*(ea->ea_entries))[ea->ea_count].ea_namelen = strlen(attruname);
-
-    ea->ea_count++;
-    return ea->ea_count;
-
-error:
-    if (ea->ea_count == 0 && ea->ea_entries) {
-        /* We just allocated storage but had an error somewhere -> free storage*/
-        free(ea->ea_entries);
-        ea->ea_entries = NULL;
-    }
-    ea->ea_count = 0;
-    return -1;
-}
-
-/*
- * Function: create_ea_header
- *
- * Purpose: create EA header file, only called from ea_open
- *
- * Arguments:
- *
- *    uname       (r)  filename for which we have to create a header
- *    ea          (rw) ea handle with already allocated storage pointed to
- *                     by ea->ea_data
- *
- * Returns: fd of open header file on success, -1 on error, errno semantics:
- *          EEXIST: open with O_CREAT | O_EXCL failed
- *
- * Effects:
- *
- * Creates EA header file and initialize ea->ea_data buffer.
- * Possibe race condition with other afpd processes:
- * we were called because header file didn't exist in eg. ea_open. We then
- * try to create a file with O_CREAT | O_EXCL, but the whole process in not atomic.
- * What do we do then? Someone else is in the process of creating the header too, but
- * it might not have finished it. That means we cant just open, read and use it!
- * We therefor currently just break with an error.
- * On return the header file is still r/w locked.
- */
-static int create_ea_header(const char * restrict uname,
-                            struct ea * restrict ea)
-{
-    int fd = -1, err = 0;
-    char *ptr;
-
-    if ((fd = open(uname, O_RDWR | O_CREAT | O_EXCL, 0666 & ~ea->vol->v_umask)) == -1) {
-        LOG(log_error, logtype_afpd, "ea_create: open race condition with ea header for file: %s", uname);
-        return -1;
-    }
-
-    /* lock it */
-    if ((write_lock(fd, 0, SEEK_SET, 0)) != 0) {
-        LOG(log_error, logtype_afpd, "ea_create: lock race condition with ea header for file: %s", uname);
-        err = -1;
-        goto exit;
-    }
-
-    /* Now init it */
-    ptr = ea->ea_data;
-    *(uint32_t *)ptr = htonl(EA_MAGIC);
-    ptr += EA_MAGIC_LEN;
-    *(uint16_t *)ptr = htons(EA_VERSION);
-    ptr += EA_VERSION_LEN;
-    *(uint16_t *)ptr = 0;       /* count */
-
-    ea->ea_size = EA_HEADER_SIZE;
-    ea->ea_inited = EA_INITED;
-
-exit:
-    if (err != 0) {
-        close(fd);
-        fd = -1;
-    }
-    return fd;
-}
-
-/*
- * Function: write_ea
- *
- * Purpose: write an EA to disk
- *
- * Arguments:
- *
- *    ea         (r) struct ea handle
- *    attruname  (r) EA name
- *    ibuf       (r) buffer with EA content
- *    attrsize   (r) size of EA
- *
- * Returns: 0 on success, -1 on error
- *
- * Effects:
- *
- * Creates/overwrites EA file.
- *
- */
-static int write_ea(const struct ea * restrict ea,
-                    const char * restrict attruname,
-                    const char * restrict ibuf,
-                    size_t attrsize)
-{
-    int fd = -1, ret = AFP_OK;
-    struct stat st;
-    char *eaname;
-
-    if ((eaname = ea_path(ea, attruname, 1)) == NULL) {
-        LOG(log_error, logtype_afpd, "write_ea('%s'): ea_path error", attruname);
-        return AFPERR_MISC;
-    }
-
-    LOG(log_maxdebug, logtype_afpd, "write_ea('%s')", eaname);
-
-    /* Check if it exists, remove if yes*/
-    if ((stat(eaname, &st)) == 0) {
-        if ((unlink(eaname)) != 0) {
-            if (errno == EACCES)
-                return AFPERR_ACCESS;
-            else
-                return AFPERR_MISC;
-        }
-    }
-
-    if ((fd = open(eaname, O_RDWR | O_CREAT | O_EXCL, 0666 & ~ea->vol->v_umask)) == -1) {
-        LOG(log_error, logtype_afpd, "write_ea: open race condition: %s", eaname);
-        return -1;
-    }
-
-    /* lock it */
-    if ((write_lock(fd, 0, SEEK_SET, 0)) != 0) {
-        LOG(log_error, logtype_afpd, "write_ea: open race condition: %s", eaname);
-        ret = -1;
-        goto exit;
-    }
-
-    if (write(fd, ibuf, attrsize) != (ssize_t)attrsize) {
-        LOG(log_error, logtype_afpd, "write_ea('%s'): write: %s", eaname, strerror(errno));
-        ret = -1;
-        goto exit;
-    }
-
-exit:
-    if (fd != -1)
-        close(fd); /* and unlock */
-    return ret;
-}
-
-/*
- * Function: ea_delentry
- *
- * Purpose: delete one EA from ea->ea_entries[]
- *
- * Arguments:
- *
- *    ea            (rw) pointer to struct ea
- *    attruname     (r) EA name
- *
- * Returns: new number of EA entries, -1 on error
- *
- * Effects:
- *
- * Remove entry from  ea->ea_entries[]. Decrement ea->ea_count.
- * Marks it as unused just by freeing name and setting it to NULL.
- * ea_close and pack_buffer must honor this.
- */
-static int ea_delentry(struct ea * restrict ea, const char * restrict attruname)
-{
-    int ret = 0;
-    unsigned int count = 0;
-
-    if (ea->ea_count == 0) {
-        LOG(log_error, logtype_afpd, "ea_delentry('%s'): illegal ea_count of 0 on deletion",
-            attruname);
-        return -1;
-    }
-
-    while (count < ea->ea_count) {
-        /* search matching EA */
-        if ((*ea->ea_entries)[count].ea_name &&
-            strcmp(attruname, (*ea->ea_entries)[count].ea_name) == 0) {
-            free((*ea->ea_entries)[count].ea_name);
-            (*ea->ea_entries)[count].ea_name = NULL;
-
-            LOG(log_debug, logtype_afpd, "ea_delentry('%s'): deleted no %u/%u",
-                attruname, count + 1, ea->ea_count);
-
-            break;
-        }
-        count++;
-    }
-
-    return ret;
-}
-
-/*
- * Function: delete_ea_file
- *
- * Purpose: delete EA file from disk
- *
- * Arguments:
- *
- *    ea         (r) struct ea handle
- *    attruname  (r) EA name
- *
- * Returns: 0 on success, -1 on error
- */
-static int delete_ea_file(const struct ea * restrict ea, const char *eaname)
-{
-    int ret = 0;
-    char *eafile;
-    struct stat st;
-
-    if ((eafile = ea_path(ea, eaname, 1)) == NULL) {
-        LOG(log_error, logtype_afpd, "delete_ea_file('%s'): ea_path error", eaname);
-        return -1;
-    }
-
-    /* Check if it exists, remove if yes*/
-    if ((stat(eafile, &st)) == 0) {
-        if ((unlink(eafile)) != 0) {
-            LOG(log_error, logtype_afpd, "delete_ea_file('%s'): unlink: %s",
-                eafile, strerror(errno));
-            ret = -1;
-        } else
-            LOG(log_debug, logtype_afpd, "delete_ea_file('%s'): success", eafile);
-    }
-
-    return ret;
-}
-
-/*************************************************************************************
- * ea_path, ea_open and ea_close are only global so that dbd can call them
- *************************************************************************************/
-
-/*
- * Function: ea_path
- *
- * Purpose: return name of ea header filename
- *
- * Arguments:
- *
- *    ea           (r) ea handle
- *    eaname       (r) name of EA or NULL
- *    macname      (r) if != 0 call mtoupath on eaname
- *
- * Returns: pointer to name in static buffer, NULL on error
- *
- * Effects:
- *
- * Calls ad_open, copies buffer, appends "::EA" and if supplied append eanme
- * Files: "file" -> "file/.AppleDouble/file::EA"
- * Dirs: "dir" -> "dir/.AppleDouble/.Parent::EA"
- * "file" with EA "myEA" -> "file/.AppleDouble/file::EA:myEA"
- */
-char *ea_path(const struct ea * restrict ea, const char * restrict eaname, int macname)
-{
-    char *adname;
-    static char pathbuf[MAXPATHLEN + 1];
-
-    /* get name of a adouble file from uname */
-    adname = ea->vol->ad_path(ea->filename, (ea->ea_flags & EA_DIR) ? ADFLAGS_DIR : 0);
-    /* copy it so we can work with it */
-    strlcpy(pathbuf, adname, MAXPATHLEN + 1);
-    /* append "::EA" */
-    strlcat(pathbuf, "::EA", MAXPATHLEN + 1);
-
-    if (eaname) {
-        strlcat(pathbuf, "::", MAXPATHLEN + 1);
-        if (macname)
-            if ((eaname = mtoupath(ea->vol, eaname)) == NULL)
-                return NULL;
-        strlcat(pathbuf, eaname, MAXPATHLEN + 1);
-    }
-
-    return pathbuf;
-}
-
-/*
- * Function: ea_open
- *
- * Purpose: open EA header file, create if it doesnt exits and called with O_CREATE
- *
- * Arguments:
- *
- *    vol         (r) current volume
- *    uname       (r) filename for which we have to open a header
- *    flags       (r) EA_CREATE: create if it doesn't exist (without it won't be created)
- *                    EA_RDONLY: open read only
- *                    EA_RDWR: open read/write
- *                    Eiterh EA_RDONLY or EA_RDWR MUST be requested
- *    ea          (w) pointer to a struct ea that we fill
- *
- * Returns: 0 on success
- *         -1 on misc error with errno = EFAULT
- *         -2 if no EA header exists with errno = ENOENT
- *
- * Effects:
- *
- * opens header file and stores fd in ea->ea_fd. Size of file is put into ea->ea_size.
- * number of EAs is stored in ea->ea_count. flags are remembered in ea->ea_flags.
- * file is either read or write locked depending on the open flags.
- * When you're done with struct ea you must call ea_close on it.
- */
-int ea_open(const struct vol * restrict vol,
-            const char * restrict uname,
-            eaflags_t eaflags,
-            struct ea * restrict ea)
-{
-    int ret = 0;
-    char *eaname;
-    struct stat st;
-
-    /* Enforce usage rules! */
-    if ( ! (eaflags & (EA_RDONLY | EA_RDWR))) {
-        LOG(log_error, logtype_afpd, "ea_open: called without EA_RDONLY | EA_RDWR", uname);
-        return -1;
-    }
-
-    /* Set it all to 0 */
-    memset(ea, 0, sizeof(struct ea));
-
-    ea->vol = vol;              /* ea_close needs it */
-    ea->ea_flags = eaflags;
-    ea->dirfd = -1;             /* no *at (cf openat) semantics by default */
-
-    /* Dont care for errors, eg when removing the file is already gone */
-    if (!stat(uname, &st) && S_ISDIR(st.st_mode))
-        ea->ea_flags |=  EA_DIR;
-
-    if ( ! (ea->filename = strdup(uname))) {
-        LOG(log_error, logtype_afpd, "ea_open: OOM");
-        return -1;
-    }
-
-    eaname = ea_path(ea, NULL, 0);
-    LOG(log_maxdebug, logtype_afpd, "ea_open: ea_path: %s", eaname);
-
-    /* Check if it exists, if not create it if EA_CREATE is in eaflags */
-    if ((stat(eaname, &st)) != 0) {
-        if (errno == ENOENT) {
-
-            /* It doesnt exist */
-
-            if ( ! (eaflags & EA_CREATE)) {
-                /* creation was not requested, so return with error */
-                ret = -2;
-                goto exit;
-            }
-
-            /* Now create a header file */
-
-            /* malloc buffer for minimal on disk data */
-            ea->ea_data = malloc(EA_HEADER_SIZE);
-            if (! ea->ea_data) {
-                LOG(log_error, logtype_afpd, "ea_open: OOM");
-                ret = -1;
-                goto exit;
-            }
-
-            /* create it */
-            ea->ea_fd = create_ea_header(eaname, ea);
-            if (ea->ea_fd == -1) {
-                ret = -1;
-                goto exit;
-            }
-
-            return 0;
-
-        } else {/* errno != ENOENT */
-            ret = -1;
-            goto exit;
-        }
-    }
-
-    /* header file exists, so read and parse it */
-
-    /* malloc buffer where we read disk file into */
-    if (st.st_size < EA_HEADER_SIZE) {
-        LOG(log_error, logtype_afpd, "ea_open('%s'): bogus EA header file", eaname);
-        ret = -1;
-        goto exit;
-    }
-    ea->ea_size = st.st_size;
-    ea->ea_data = malloc(st.st_size);
-    if (! ea->ea_data) {
-        LOG(log_error, logtype_afpd, "ea_open: OOM");
-        ret = -1;
-        goto exit;
-    }
-
-    /* Now lock, open and read header file from disk */
-    if ((ea->ea_fd = open(eaname, (ea->ea_flags & EA_RDWR) ? O_RDWR : O_RDONLY)) == -1) {
-        LOG(log_error, logtype_afpd, "ea_open('%s'): error: %s", eaname, strerror(errno));
-        ret = -1;
-        goto exit;
-    }
-
-    /* lock it */
-    if (ea->ea_flags & EA_RDONLY) {
-        /* read lock */
-        if ((read_lock(ea->ea_fd, 0, SEEK_SET, 0)) != 0) {
-            LOG(log_error, logtype_afpd, "ea_open: lock error on  header: %s", eaname);
-            ret = -1;
-            goto exit;
-        }
-    } else {  /* EA_RDWR */
-        /* write lock */
-        if ((write_lock(ea->ea_fd, 0, SEEK_SET, 0)) != 0) {
-            LOG(log_error, logtype_afpd, "ea_open: lock error on  header: %s", eaname);
-            ret = -1;
-            goto exit;
-        }
-    }
-
-    /* read it */
-    if (read(ea->ea_fd, ea->ea_data, ea->ea_size) != (ssize_t)ea->ea_size) {
-        LOG(log_error, logtype_afpd, "ea_open: short read on header: %s", eaname);
-        ret = -1;
-        goto exit;
-    }
-
-    if ((unpack_header(ea)) != 0) {
-        LOG(log_error, logtype_afpd, "ea_open: error unpacking header for: %s", eaname);
-        ret = -1;
-        goto exit;
-    }
-
-exit:
-    switch (ret) {
-    case 0:
-        ea->ea_inited = EA_INITED;
-        break;
-    case -1:
-        errno = EFAULT; /* force some errno distinguishable from ENOENT */
-        /* fall through */
-    case -2:
-        if (ea->ea_data) {
-            free(ea->ea_data);
-            ea->ea_data = NULL;
-        }
-        if (ea->ea_fd) {
-            close(ea->ea_fd);
-            ea->ea_fd = -1;
-        }
-        break;
-    }
-
-    return ret;
-}
-
-/*
- * Function: ea_openat
- *
- * Purpose: openat like wrapper for ea_open, takes a additional file descriptor
- *
- * Arguments:
- *
- *    vol         (r) current volume
- *    sfd         (r) openat like file descriptor
- *    uname       (r) filename for which we have to open a header
- *    flags       (r) EA_CREATE: create if it doesn't exist (without it won't be created)
- *                    EA_RDONLY: open read only
- *                    EA_RDWR: open read/write
- *                    Eiterh EA_RDONLY or EA_RDWR MUST be requested
- *    ea          (w) pointer to a struct ea that we fill
- *
- * Returns: 0 on success
- *         -1 on misc error with errno = EFAULT
- *         -2 if no EA header exists with errno = ENOENT
- *
- * Effects:
- *
- * opens header file and stores fd in ea->ea_fd. Size of file is put into ea->ea_size.
- * number of EAs is stored in ea->ea_count. flags are remembered in ea->ea_flags.
- * file is either read or write locked depending on the open flags.
- * When you're done with struct ea you must call ea_close on it.
- */
-int ea_openat(const struct vol * restrict vol,
-              int dirfd,
-              const char * restrict uname,
-              eaflags_t eaflags,
-              struct ea * restrict ea)
-{
-    int ret = 0;
-    int cwdfd = -1;
-
-    if (dirfd != -1) {
-        if (((cwdfd = open(".", O_RDONLY)) == -1) || (fchdir(dirfd) != 0)) {
-            ret = -1;
-            goto exit;
-        }
-    }
-
-    ret = ea_open(vol, uname, eaflags, ea);
-    ea->dirfd = dirfd;
-
-    if (dirfd != -1) {
-        if (fchdir(cwdfd) != 0) {
-            LOG(log_error, logtype_afpd, "ea_openat: cant chdir back, exiting");
-            exit(EXITERR_SYS);
-        }
-    }
-
-
-exit:
-    if (cwdfd != -1)
-        close(cwdfd);
-
-    return ret;
-
-}
-
-/*
- * Function: ea_close
- *
- * Purpose: flushes and closes an ea handle
- *
- * Arguments:
- *
- *    ea          (rw) pointer to ea handle
- *
- * Returns: 0 on success, -1 on error
- *
- * Effects:
- *
- * Flushes and then closes and frees all resouces held by ea handle.
- * Pack data in ea into ea_data, then write ea_data to disk
- */
-int ea_close(struct ea * restrict ea)
-{
-    int ret = 0; 
-    unsigned int count = 0;
-    char *eaname;
-    struct stat st;
-
-    LOG(log_debug, logtype_afpd, "ea_close('%s')", ea->filename);
-
-    if (ea->ea_inited != EA_INITED) {
-        LOG(log_warning, logtype_afpd, "ea_close('%s'): non initialized ea", ea->filename);
-        return 0;
-    }
-
-    /* pack header and write it to disk if it was opened EA_RDWR*/
-    if (ea->ea_flags & EA_RDWR) {
-        if ((pack_header(ea)) != 0) {
-            LOG(log_error, logtype_afpd, "ea_close: pack header");
-            ret = -1;
-        } else {
-            if (ea->ea_count == 0) {
-                /* Check if EA header exists and remove it */
-                eaname = ea_path(ea, NULL, 0);
-                if ((lstatat(ea->dirfd, eaname, &st)) == 0) {
-                    if ((netatalk_unlinkat(ea->dirfd, eaname)) != 0) {
-                        LOG(log_error, logtype_afpd, "ea_close('%s'): unlink: %s",
-                            eaname, strerror(errno));
-                        ret = -1;
-                    }
-                    else
-                        LOG(log_debug, logtype_afpd, "ea_close(unlink '%s'): success", eaname);
-                } else {
-                    /* stat error */
-                    if (errno != ENOENT) {
-                        LOG(log_error, logtype_afpd, "ea_close('%s'): stat: %s",
-                            eaname, strerror(errno));
-                        ret = -1;
-                    }
-                }
-            } else { /* ea->ea_count > 0 */
-                if ((lseek(ea->ea_fd, 0, SEEK_SET)) == -1) {
-                    LOG(log_error, logtype_afpd, "ea_close: lseek: %s", strerror(errno));
-                    ret = -1;
-                    goto exit;
-                }
-
-                if ((ftruncate(ea->ea_fd, 0)) == -1) {
-                    LOG(log_error, logtype_afpd, "ea_close: ftruncate: %s", strerror(errno));
-                    ret = -1;
-                    goto exit;
-                }
-
-                if (write(ea->ea_fd, ea->ea_data, ea->ea_size) != (ssize_t)ea->ea_size) {
-                    LOG(log_error, logtype_afpd, "ea_close: write: %s", strerror(errno));
-                    ret = -1;
-                }
-            }
-        }
-    }
-
-exit:
-    /* free names */
-    while(count < ea->ea_count) {
-        if ( (*ea->ea_entries)[count].ea_name ) {
-            free((*ea->ea_entries)[count].ea_name);
-            (*ea->ea_entries)[count].ea_name = NULL;
-        }
-        count++;
-    }
-    ea->ea_count = 0;
-
-    if (ea->filename) {
-        free(ea->filename);
-        ea->filename = NULL;
-    }
-
-    if (ea->ea_entries) {
-        free(ea->ea_entries);
-        ea->ea_entries = NULL;
-    }
-
-    if (ea->ea_data) {
-        free(ea->ea_data);
-        ea->ea_data = NULL;
-    }
-    if (ea->ea_fd != -1) {
-        close(ea->ea_fd);       /* also releases the fcntl lock */
-        ea->ea_fd = -1;
-    }
-
-    return 0;
-}
-
-
-
-/************************************************************************************
- * VFS funcs called from afp_ea* funcs
- ************************************************************************************/
-
-/*
- * Function: get_easize
- *
- * Purpose: get size of an EA
- *
- * Arguments:
- *
- *    vol          (r) current volume
- *    rbuf         (w) DSI reply buffer
- *    rbuflen      (rw) current length of data in reply buffer
- *    uname        (r) filename
- *    oflag        (r) link and create flag
- *    attruname    (r) name of attribute
- *
- * Returns: AFP code: AFP_OK on success or appropiate AFP error code
- *
- * Effects:
- *
- * Copies EA size into rbuf in network order. Increments *rbuflen +4.
- */
-int get_easize(VFS_FUNC_ARGS_EA_GETSIZE)
-{
-    int ret = AFPERR_MISC;
-    unsigned int count = 0;
-    uint32_t uint32;
-    struct ea ea;
-
-    LOG(log_debug, logtype_afpd, "get_easize: file: %s", uname);
-
-    if ((ea_open(vol, uname, EA_RDONLY, &ea)) != 0) {
-        if (errno != ENOENT)
-            LOG(log_error, logtype_afpd, "get_easize: error calling ea_open for file: %s", uname);
-
-        memset(rbuf, 0, 4);
-        *rbuflen += 4;
-        return ret;
-    }
-
-    while (count < ea.ea_count) {
-        if (strcmp(attruname, (*ea.ea_entries)[count].ea_name) == 0) {
-            uint32 = htonl((*ea.ea_entries)[count].ea_size);
-            memcpy(rbuf, &uint32, 4);
-            *rbuflen += 4;
-            ret = AFP_OK;
-
-            LOG(log_debug, logtype_afpd, "get_easize(\"%s\"): size: %u",
-                attruname, (*ea.ea_entries)[count].ea_size);
-            break;
-        }
-        count++;
-    }
-
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "get_easize: error closing ea handle for file: %s", uname);
-        return AFPERR_MISC;
-    }
-
-    return ret;
-}
-
-/*
- * Function: get_eacontent
- *
- * Purpose: copy EA into rbuf
- *
- * Arguments:
- *
- *    vol          (r) current volume
- *    rbuf         (w) DSI reply buffer
- *    rbuflen      (rw) current length of data in reply buffer
- *    uname        (r) filename
- *    oflag        (r) link and create flag
- *    attruname    (r) name of attribute
- *    maxreply     (r) maximum EA size as of current specs/real-life
- *
- * Returns: AFP code: AFP_OK on success or appropiate AFP error code
- *
- * Effects:
- *
- * Copies EA into rbuf. Increments *rbuflen accordingly.
- */
-int get_eacontent(VFS_FUNC_ARGS_EA_GETCONTENT)
-{
-    int ret = AFPERR_MISC, fd = -1;
-    unsigned int count = 0;
-    uint32_t uint32;
-    size_t toread;
-    struct ea ea;
-    char *eafile;
-
-    LOG(log_debug, logtype_afpd, "get_eacontent('%s/%s')", uname, attruname);
-
-    if ((ea_open(vol, uname, EA_RDONLY, &ea)) != 0) {
-        if (errno != ENOENT)
-            LOG(log_error, logtype_afpd, "get_eacontent('%s'): ea_open error", uname);
-        memset(rbuf, 0, 4);
-        *rbuflen += 4;
-        return ret;
-    }
-
-    while (count < ea.ea_count) {
-        if (strcmp(attruname, (*ea.ea_entries)[count].ea_name) == 0) {
-            if ( (eafile = ea_path(&ea, attruname, 1)) == NULL) {
-                ret = AFPERR_MISC;
-                break;
-            }
-
-            if ((fd = open(eafile, O_RDONLY)) == -1) {
-                LOG(log_error, logtype_afpd, "get_eacontent('%s'): open error: %s", uname, strerror(errno));
-                ret = AFPERR_MISC;
-                break;
-            }
-
-            /* Check how much the client wants, give him what we think is right */
-            maxreply -= MAX_REPLY_EXTRA_BYTES;
-            if (maxreply > MAX_EA_SIZE)
-                maxreply = MAX_EA_SIZE;
-            toread = (maxreply < (*ea.ea_entries)[count].ea_size) ? maxreply : (*ea.ea_entries)[count].ea_size;
-            LOG(log_debug, logtype_afpd, "get_eacontent('%s'): sending %u bytes", attruname, toread);
-
-            /* Put length of EA data in reply buffer */
-            uint32 = htonl(toread);
-            memcpy(rbuf, &uint32, 4);
-            rbuf += 4;
-            *rbuflen += 4;
-
-            if (read(fd, rbuf, toread) != (ssize_t)toread) {
-                LOG(log_error, logtype_afpd, "get_eacontent('%s/%s'): short read", uname, attruname);
-                close(fd);
-                ret = AFPERR_MISC;
-                break;
-            }
-            *rbuflen += toread;
-            close(fd);
-
-            ret = AFP_OK;
-            break;
-        }
-        count++;
-    }
-
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "get_eacontent('%s'): error closing ea handle", uname);
-        return AFPERR_MISC;
-    }
-
-    return ret;
-
-}
-
-/*
- * Function: list_eas
- *
- * Purpose: copy names of EAs into attrnamebuf
- *
- * Arguments:
- *
- *    vol          (r) current volume
- *    attrnamebuf  (w) store names a consecutive C strings here
- *    buflen       (rw) length of names in attrnamebuf
- *    uname        (r) filename
- *    oflag        (r) link and create flag
- *
- * Returns: AFP code: AFP_OK on success or appropiate AFP error code
- *
- * Effects:
- *
- * Copies names of all EAs of uname as consecutive C strings into rbuf.
- * Increments *buflen accordingly.
- */
-int list_eas(VFS_FUNC_ARGS_EA_LIST)
-{
-    unsigned int count = 0;
-    int attrbuflen = *buflen, ret = AFP_OK, len;
-    char *buf = attrnamebuf;
-    struct ea ea;
-
-    LOG(log_debug, logtype_afpd, "list_eas: file: %s", uname);
-
-    if ((ea_open(vol, uname, EA_RDONLY, &ea)) != 0) {
-        if (errno != ENOENT) {
-            LOG(log_error, logtype_afpd, "list_eas: error calling ea_open for file: %s", uname);
-            return AFPERR_MISC;
-        }
-        else
-            return AFP_OK;
-    }
-
-    while (count < ea.ea_count) {
-        /* Convert name to CH_UTF8_MAC and directly store in in the reply buffer */
-        if ( ( len = convert_string(vol->v_volcharset,
-                                    CH_UTF8_MAC, 
-                                    (*ea.ea_entries)[count].ea_name,
-                                    (*ea.ea_entries)[count].ea_namelen,
-                                    buf + attrbuflen,
-                                    255))
-             <= 0 ) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-        if (len == 255)
-            /* convert_string didn't 0-terminate */
-            attrnamebuf[attrbuflen + 255] = 0;
-
-        LOG(log_debug7, logtype_afpd, "list_eas(%s): EA: %s",
-            uname, (*ea.ea_entries)[count].ea_name);
-
-        attrbuflen += len + 1;
-        if (attrbuflen > (ATTRNAMEBUFSIZ - 256)) {
-            /* Next EA name could overflow, so bail out with error.
-               FIXME: evantually malloc/memcpy/realloc whatever.
-               Is it worth it ? */
-            LOG(log_warning, logtype_afpd, "list_eas(%s): running out of buffer for EA names", uname);
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-        count++;
-    }
-
-exit:
-    *buflen = attrbuflen;
-
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "list_eas: error closing ea handle for file: %s", uname);
-        return AFPERR_MISC;
-    }
-
-    return ret;
-}
-
-/*
- * Function: set_ea
- *
- * Purpose: set a Solaris native EA
- *
- * Arguments:
- *
- *    vol          (r) current volume
- *    uname        (r) filename
- *    attruname    (r) EA name
- *    ibuf         (r) buffer with EA content
- *    attrsize     (r) length EA in ibuf
- *    oflag        (r) link and create flag
- *
- * Returns: AFP code: AFP_OK on success or appropiate AFP error code
- *
- * Effects:
- *
- * Copies names of all EAs of uname as consecutive C strings into rbuf.
- * Increments *rbuflen accordingly.
- */
-int set_ea(VFS_FUNC_ARGS_EA_SET)
-{
-    int ret = AFP_OK;
-    struct ea ea;
-
-    LOG(log_debug, logtype_afpd, "set_ea: file: %s", uname);
-
-    if ((ea_open(vol, uname, EA_CREATE | EA_RDWR, &ea)) != 0) {
-        LOG(log_error, logtype_afpd, "set_ea('%s'): ea_open error", uname);
-        return AFPERR_MISC;
-    }
-
-    if ((ea_addentry(&ea, attruname, attrsize, oflag)) == -1) {
-        LOG(log_error, logtype_afpd, "set_ea('%s'): ea_addentry error", uname);
-        ret = AFPERR_MISC;
-        goto exit;
-    }
-
-    if ((write_ea(&ea, attruname, ibuf, attrsize)) != 0) {
-        LOG(log_error, logtype_afpd, "set_ea('%s'): write_ea error", uname);
-        ret = AFPERR_MISC;
-        goto exit;
-    }
-
-exit:
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "set_ea('%s'): ea_close error", uname);
-        ret = AFPERR_MISC;
-        goto exit;
-    }
-
-    return ret;
-}
-
-/*
- * Function: remove_ea
- *
- * Purpose: remove a EA from a file
- *
- * Arguments:
- *
- *    vol          (r) current volume
- *    uname        (r) filename
- *    attruname    (r) EA name
- *    oflag        (r) link and create flag
- *
- * Returns: AFP code: AFP_OK on success or appropiate AFP error code
- *
- * Effects:
- *
- * Removes EA attruname from file uname.
- */
-int remove_ea(VFS_FUNC_ARGS_EA_REMOVE)
-{
-    int ret = AFP_OK;
-    struct ea ea;
-
-    LOG(log_debug, logtype_afpd, "remove_ea('%s/%s')", uname, attruname);
-
-    if ((ea_open(vol, uname, EA_RDWR, &ea)) != 0) {
-        LOG(log_error, logtype_afpd, "remove_ea('%s'): ea_open error", uname);
-        return AFPERR_MISC;
-    }
-
-    if ((ea_delentry(&ea, attruname)) == -1) {
-        LOG(log_error, logtype_afpd, "remove_ea('%s'): ea_delentry error", uname);
-        ret = AFPERR_MISC;
-        goto exit;
-    }
-
-    if ((delete_ea_file(&ea, attruname)) != 0) {
-        LOG(log_error, logtype_afpd, "remove_ea('%s'): delete_ea error", uname);
-        ret = AFPERR_MISC;
-        goto exit;
-    }
-
-exit:
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "remove_ea('%s'): ea_close error", uname);
-        ret = AFPERR_MISC;
-        goto exit;
-    }
-
-    return ret;
-}
-
-/******************************************************************************************
- * EA VFS funcs that deal with file/dir cp/mv/rm
- ******************************************************************************************/
-
-int ea_deletefile(VFS_FUNC_ARGS_DELETEFILE)
-{
-    unsigned int count = 0;
-    int ret = AFP_OK;
-    int cwd = -1;
-    struct ea ea;
-
-    LOG(log_debug, logtype_afpd, "ea_deletefile('%s')", file);
-
-    /* Open EA stuff */
-    if ((ea_openat(vol, dirfd, file, EA_RDWR, &ea)) != 0) {
-        if (errno == ENOENT)
-            /* no EA files, nothing to do */
-            return AFP_OK;
-        else {
-            LOG(log_error, logtype_afpd, "ea_deletefile('%s'): error calling ea_open", file);
-            return AFPERR_MISC;
-        }
-    }
-
-    if (dirfd != -1) {
-        if (((cwd = open(".", O_RDONLY)) == -1) || (fchdir(dirfd) != 0)) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-    }
-
-    while (count < ea.ea_count) {
-        if ((delete_ea_file(&ea, (*ea.ea_entries)[count].ea_name)) != 0) {
-            ret = AFPERR_MISC;
-            continue;
-        }
-        free((*ea.ea_entries)[count].ea_name);
-        (*ea.ea_entries)[count].ea_name = NULL;
-        count++;
-    }
-
-    /* ea_close removes the EA header file for us because all names are NULL */
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "ea_deletefile('%s'): error closing ea handle", file);
-        ret = AFPERR_MISC;
-    }
-
-    if (dirfd != -1 && fchdir(cwd) != 0) {
-        LOG(log_error, logtype_afpd, "ea_deletefile: cant chdir back. exit!");
-        exit(EXITERR_SYS);
-    }
-
-exit:
-    if (cwd != -1)
-        close(cwd);
-
-    return ret;
-}
-
-int ea_renamefile(VFS_FUNC_ARGS_RENAMEFILE)
-{
-    unsigned int count = 0;
-    int    ret = AFP_OK;
-    size_t easize;
-    char   srceapath[ MAXPATHLEN + 1];
-    char   *eapath;
-    char   *eaname;
-    struct ea srcea;
-    struct ea dstea;
-    struct adouble ad;
-
-    LOG(log_debug, logtype_afpd, "ea_renamefile('%s'/'%s')", src, dst);
-            
-
-    /* Open EA stuff */
-    if ((ea_openat(vol, dirfd, src, EA_RDWR, &srcea)) != 0) {
-        if (errno == ENOENT)
-            /* no EA files, nothing to do */
-            return AFP_OK;
-        else {
-            LOG(log_error, logtype_afpd, "ea_renamefile('%s'/'%s'): ea_open error: '%s'", src, dst, src);
-            return AFPERR_MISC;
-        }
-    }
-
-    if ((ea_open(vol, dst, EA_RDWR | EA_CREATE, &dstea)) != 0) {
-        if (errno == ENOENT) {
-            /* Possibly the .AppleDouble folder didn't exist, we create it and try again */
-            ad_init(&ad, vol->v_adouble, vol->v_ad_options); 
-            if ((ad_open(dst, ADFLAGS_HF, O_RDWR | O_CREAT, 0666, &ad)) != 0) {
-                LOG(log_error, logtype_afpd, "ea_renamefile('%s/%s'): ad_open error: '%s'", src, dst, dst);
-                ret = AFPERR_MISC;
-                goto exit;
-            }
-            ad_close(&ad, ADFLAGS_HF);
-            if ((ea_open(vol, dst, EA_RDWR | EA_CREATE, &dstea)) != 0) {
-                ret = AFPERR_MISC;
-                goto exit;
-            }
-        }
-    }
-
-    /* Loop through all EAs: */
-    while (count < srcea.ea_count) {
-        /* Move EA */
-        eaname = (*srcea.ea_entries)[count].ea_name;
-        easize = (*srcea.ea_entries)[count].ea_size;
-
-        /* Build src and dst paths for rename() */
-        if ((eapath = ea_path(&srcea, eaname, 1)) == NULL) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-        strcpy(srceapath, eapath);
-        if ((eapath = ea_path(&dstea, eaname, 1)) == NULL) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-
-        LOG(log_maxdebug, logtype_afpd, "ea_renamefile('%s/%s'): moving EA '%s' to '%s'",
-            src, dst, srceapath, eapath);
-
-        /* Add EA to dstea */
-        if ((ea_addentry(&dstea, eaname, easize, 0)) == -1) {
-            LOG(log_error, logtype_afpd, "ea_renamefile('%s/%s'): moving EA '%s' to '%s'",
-                src, dst, srceapath, eapath);
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-
-        /* Remove EA entry from srcea */
-        if ((ea_delentry(&srcea, eaname)) == -1) {
-            LOG(log_error, logtype_afpd, "ea_renamefile('%s/%s'): moving EA '%s' to '%s'",
-                src, dst, srceapath, eapath);
-            ea_delentry(&dstea, eaname);
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-
-        /* Now rename the EA */
-        if ((unix_rename(dirfd, srceapath, -1, eapath)) < 0) {
-            LOG(log_error, logtype_afpd, "ea_renamefile('%s/%s'): moving EA '%s' to '%s'",
-                src, dst, srceapath, eapath);
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-
-        count++;
-    }
-
-
-exit:
-    ea_close(&srcea);
-    ea_close(&dstea);
-       return ret;
-}
-
-int ea_copyfile(VFS_FUNC_ARGS_COPYFILE)
-{
-    unsigned int count = 0;
-    int    ret = AFP_OK;
-    size_t easize;
-    char   srceapath[ MAXPATHLEN + 1];
-    char   *eapath;
-    char   *eaname;
-    struct ea srcea;
-    struct ea dstea;
-    struct adouble ad;
-
-    LOG(log_debug, logtype_afpd, "ea_copyfile('%s'/'%s')", src, dst);
-
-    /* Open EA stuff */
-    if ((ea_openat(vol, sfd, src, EA_RDWR, &srcea)) != 0) {
-        if (errno == ENOENT)
-            /* no EA files, nothing to do */
-            return AFP_OK;
-        else {
-            LOG(log_error, logtype_afpd, "ea_copyfile('%s'/'%s'): ea_open error: '%s'", src, dst, src);
-            return AFPERR_MISC;
-        }
-    }
-
-    if ((ea_open(vol, dst, EA_RDWR | EA_CREATE, &dstea)) != 0) {
-        if (errno == ENOENT) {
-            /* Possibly the .AppleDouble folder didn't exist, we create it and try again */
-            ad_init(&ad, vol->v_adouble, vol->v_ad_options); 
-            if ((ad_open(dst, ADFLAGS_HF, O_RDWR | O_CREAT, 0666, &ad)) != 0) {
-                LOG(log_error, logtype_afpd, "ea_copyfile('%s/%s'): ad_open error: '%s'", src, dst, dst);
-                ret = AFPERR_MISC;
-                goto exit;
-            }
-            ad_close(&ad, ADFLAGS_HF);
-            if ((ea_open(vol, dst, EA_RDWR | EA_CREATE, &dstea)) != 0) {
-                ret = AFPERR_MISC;
-                goto exit;
-            }
-        }
-    }
-
-    /* Loop through all EAs: */
-    while (count < srcea.ea_count) {
-        /* Copy EA */
-        eaname = (*srcea.ea_entries)[count].ea_name;
-        easize = (*srcea.ea_entries)[count].ea_size;
-
-        /* Build src and dst paths for copy_file() */
-        if ((eapath = ea_path(&srcea, eaname, 1)) == NULL) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-        strcpy(srceapath, eapath);
-        if ((eapath = ea_path(&dstea, eaname, 1)) == NULL) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-
-        LOG(log_maxdebug, logtype_afpd, "ea_copyfile('%s/%s'): copying EA '%s' to '%s'",
-            src, dst, srceapath, eapath);
-
-        /* Add EA to dstea */
-        if ((ea_addentry(&dstea, eaname, easize, 0)) == -1) {
-            LOG(log_error, logtype_afpd, "ea_copyfile('%s/%s'): ea_addentry('%s') error",
-                src, dst, eaname);
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-
-        /* Now copy the EA */
-        if ((copy_file(sfd, srceapath, eapath, (0666 & ~vol->v_umask))) < 0) {
-            LOG(log_error, logtype_afpd, "ea_copyfile('%s/%s'): copying EA '%s' to '%s'",
-                src, dst, srceapath, eapath);
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-
-        count++;
-    }
-
-exit:
-    ea_close(&srcea);
-    ea_close(&dstea);
-       return ret;
-}
-
-int ea_chown(VFS_FUNC_ARGS_CHOWN)
-{
-
-    unsigned int count = 0;
-    int ret = AFP_OK;
-    char *eaname;
-    struct ea ea;
-
-    LOG(log_debug, logtype_afpd, "ea_chown('%s')", path);
-    /* Open EA stuff */
-    if ((ea_open(vol, path, EA_RDWR, &ea)) != 0) {
-        if (errno == ENOENT)
-            /* no EA files, nothing to do */
-            return AFP_OK;
-        else {
-            LOG(log_error, logtype_afpd, "ea_chown('%s'): error calling ea_open", path);
-            return AFPERR_MISC;
-        }
-    }
-
-    if ((lchown(ea_path(&ea, NULL, 0), uid, gid)) != 0) {
-        switch (errno) {
-        case EPERM:
-        case EACCES:
-            ret = AFPERR_ACCESS;
-            goto exit;
-        default:
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-    }
-
-    while (count < ea.ea_count) {
-        if ((eaname = ea_path(&ea, (*ea.ea_entries)[count].ea_name, 1)) == NULL) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-        if ((lchown(eaname, uid, gid)) != 0) {
-            switch (errno) {
-            case EPERM:
-            case EACCES:
-                ret = AFPERR_ACCESS;
-                goto exit;
-            default:
-                ret = AFPERR_MISC;
-                goto exit;
-            }
-            continue;
-        }
-
-        count++;
-    }
-
-exit:
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "ea_chown('%s'): error closing ea handle", path);
-        return AFPERR_MISC;
-    }
-
-    return ret;
-}
-
-int ea_chmod_file(VFS_FUNC_ARGS_SETFILEMODE)
-{
-
-    unsigned int count = 0;
-    int ret = AFP_OK;
-    const char *eaname;
-    struct ea ea;
-
-    LOG(log_debug, logtype_afpd, "ea_chmod_file('%s')", name);
-    /* Open EA stuff */
-    if ((ea_open(vol, name, EA_RDWR, &ea)) != 0) {
-        if (errno == ENOENT)
-            /* no EA files, nothing to do */
-            return AFP_OK;
-        else
-            return AFPERR_MISC;
-    }
-
-    /* Set mode on EA header file */
-    if ((setfilmode(ea_path(&ea, NULL, 0), ea_header_mode(mode), NULL, vol->v_umask)) != 0) {
-        LOG(log_error, logtype_afpd, "ea_chmod_file('%s'): %s", ea_path(&ea, NULL, 0), strerror(errno));
-        switch (errno) {
-        case EPERM:
-        case EACCES:
-            ret = AFPERR_ACCESS;
-            goto exit;
-        default:
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-    }
-
-    /* Set mode on EA files */
-    while (count < ea.ea_count) {
-        if ((eaname = ea_path(&ea, (*ea.ea_entries)[count].ea_name, 1)) == NULL) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-        if ((setfilmode(eaname, ea_mode(mode), NULL, vol->v_umask)) != 0) {
-            LOG(log_error, logtype_afpd, "ea_chmod_file('%s'): %s", eaname, strerror(errno));
-            switch (errno) {
-            case EPERM:
-            case EACCES:
-                ret = AFPERR_ACCESS;
-                goto exit;
-            default:
-                ret = AFPERR_MISC;
-                goto exit;
-            }
-            continue;
-        }
-
-        count++;
-    }
-
-exit:
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "ea_chmod_file('%s'): error closing ea handle", name);
-        return AFPERR_MISC;
-    }
-
-    return ret;
-}
-
-int ea_chmod_dir(VFS_FUNC_ARGS_SETDIRUNIXMODE)
-{
-
-    int ret = AFP_OK;
-    unsigned int count = 0;
-    uid_t uid;
-    const char *eaname;
-    const char *eaname_safe = NULL;
-    struct ea ea;
-
-    LOG(log_debug, logtype_afpd, "ea_chmod_dir('%s')", name);
-    /* .AppleDouble already might be inaccesible, so we must run as id 0 */
-    uid = geteuid();
-    if (seteuid(0)) {
-        LOG(log_error, logtype_afpd, "ea_chmod_dir('%s'): seteuid: %s", name, strerror(errno));
-        return AFPERR_MISC;
-    }
-
-    /* Open EA stuff */
-    if ((ea_open(vol, name, EA_RDWR, &ea)) != 0) {
-        /* ENOENT --> no EA files, nothing to do */
-        if (errno != ENOENT)
-            ret = AFPERR_MISC;
-        if (seteuid(uid) < 0) {
-            LOG(log_error, logtype_afpd, "can't seteuid back: %s", strerror(errno));
-            exit(EXITERR_SYS);
-        }
-        return ret;
-    }
-
-    /* Set mode on EA header */
-    if ((setfilmode(ea_path(&ea, NULL, 0), ea_header_mode(mode), NULL, vol->v_umask)) != 0) {
-        LOG(log_error, logtype_afpd, "ea_chmod_dir('%s'): %s", ea_path(&ea, NULL, 0), strerror(errno));
-        switch (errno) {
-        case EPERM:
-        case EACCES:
-            ret = AFPERR_ACCESS;
-            goto exit;
-        default:
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-    }
-
-    /* Set mode on EA files */
-    while (count < ea.ea_count) {
-        eaname = (*ea.ea_entries)[count].ea_name;
-        /*
-         * Be careful with EA names from the EA header!
-         * Eg NFS users might have access to them, can inject paths using ../ or /.....
-         * FIXME:
-         * Until the EA code escapes / in EA name requests from the client, these therefor wont work.
-         */
-        if ((eaname_safe = strrchr(eaname, '/'))) {
-            LOG(log_warning, logtype_afpd, "ea_chmod_dir('%s'): contains a slash", eaname);
-            eaname = eaname_safe;
-        }
-        if ((eaname = ea_path(&ea, eaname, 1)) == NULL) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-        if ((setfilmode(eaname, ea_mode(mode), NULL, vol->v_umask)) != 0) {
-            LOG(log_error, logtype_afpd, "ea_chmod_dir('%s'): %s", eaname, strerror(errno));
-            switch (errno) {
-            case EPERM:
-            case EACCES:
-                ret = AFPERR_ACCESS;
-                goto exit;
-            default:
-                ret = AFPERR_MISC;
-                goto exit;
-            }
-            continue;
-        }
-
-        count++;
-    }
-
-exit:
-    if (seteuid(uid) < 0) {
-        LOG(log_error, logtype_afpd, "can't seteuid back: %s", strerror(errno));
-        exit(EXITERR_SYS);
-    }
-
-    if ((ea_close(&ea)) != 0) {
-        LOG(log_error, logtype_afpd, "ea_chmod_dir('%s'): error closing ea handle", name);
-        return AFPERR_MISC;
-    }
-
-    return ret;
-}
diff --git a/libatalk/vfs/ea_ad.c b/libatalk/vfs/ea_ad.c
new file mode 100644 (file)
index 0000000..0bee141
--- /dev/null
@@ -0,0 +1,1772 @@
+/*
+  Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <unistd.h>
+#include <stdint.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <dirent.h>
+#include <arpa/inet.h>
+
+#include <atalk/adouble.h>
+#include <atalk/ea.h>
+#include <atalk/afp.h>
+#include <atalk/logger.h>
+#include <atalk/volume.h>
+#include <atalk/vfs.h>
+#include <atalk/util.h>
+#include <atalk/unix.h>
+#include <atalk/compat.h>
+
+/*
+ * Store Extended Attributes inside .AppleDouble folders as follows:
+ *
+ * filename "fileWithEAs" with EAs "testEA1" and "testEA2"
+ *
+ * - create header with with the format struct adouble_ea_ondisk, the file is written to
+ *   ".AppleDouble/fileWithEAs::EA"
+ * - store EAs in files "fileWithEAs::EA::testEA1" and "fileWithEAs::EA::testEA2"
+ */
+
+/* 
+ * Build mode for EA header from file mode
+ */
+static inline mode_t ea_header_mode(mode_t mode)
+{
+    /* Same as ad_hf_mode(mode) */
+    mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
+    /* Owner must be able to open, read and w-lock it, in order to chmod from eg 0000 -> 0xxxx*/
+    mode |= S_IRUSR | S_IWUSR;
+    return mode;
+}
+
+/* 
+ * Build mode for EA file from file mode
+ */
+static inline mode_t ea_mode(mode_t mode)
+{
+    /* Same as ad_hf_mode(mode) */
+    mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
+    return mode;
+}
+
+/*
+  Taken form afpd/desktop.c
+*/
+static char *mtoupath(const struct vol *vol, const char *mpath)
+{
+    static char  upath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
+    const char   *m;
+    char         *u;
+    size_t       inplen;
+    size_t       outlen;
+    uint16_t     flags = CONV_ESCAPEHEX | CONV_ALLOW_COLON;
+
+    if (!mpath)
+        return NULL;
+
+    if ( *mpath == '\0' ) {
+        return( "." );
+    }
+
+    m = mpath;
+    u = upath;
+
+    inplen = strlen(m);
+    outlen = MAXPATHLEN;
+
+    if ((size_t)-1 == (outlen = convert_charset(CH_UTF8_MAC,
+                                                vol->v_volcharset,
+                                                vol->v_maccharset,
+                                                m, inplen, u, outlen, &flags)) ) {
+        return NULL;
+    }
+
+    return( upath );
+}
+
+
+/*
+ * Function: unpack_header
+ *
+ * Purpose: unpack and verify header file data buffer at ea->ea_data into struct ea
+ *
+ * Arguments:
+ *
+ *    ea      (rw) handle to struct ea
+ *
+ * Returns: 0 on success, -1 on error
+ *
+ * Effects:
+ *
+ * Verifies magic and version.
+ */
+static int unpack_header(struct ea * restrict ea)
+{
+    int ret = 0;
+    unsigned int count = 0;
+    uint32_t uint32;
+    char *buf;
+
+    /* Check magic and version */
+    buf = ea->ea_data;
+    if (*(uint32_t *)buf != htonl(EA_MAGIC)) {
+        LOG(log_error, logtype_afpd, "unpack_header: wrong magic 0x%08x", *(uint32_t *)buf);
+        ret = -1;
+        goto exit;
+    }
+    buf += 4;
+    if (*(uint16_t *)buf != htons(EA_VERSION)) {
+        LOG(log_error, logtype_afpd, "unpack_header: wrong version 0x%04x", *(uint16_t *)buf);
+        ret = -1;
+        goto exit;
+    }
+    buf += 2;
+
+    /* Get EA count */
+    ea->ea_count = ntohs(*(uint16_t *)buf);
+    LOG(log_debug, logtype_afpd, "unpack_header: number of EAs: %u", ea->ea_count);
+    buf += 2;
+
+    if (ea->ea_count == 0)
+        return 0;
+
+    /* Allocate storage for the ea_entries array */
+    ea->ea_entries = malloc(sizeof(struct ea_entry) * ea->ea_count);
+    if ( ! ea->ea_entries) {
+        LOG(log_error, logtype_afpd, "unpack_header: OOM");
+        ret = -1;
+        goto exit;
+    }
+
+    buf = ea->ea_data + EA_HEADER_SIZE;
+    while (count < ea->ea_count) {
+        memcpy(&uint32, buf, 4); /* EA size */
+        buf += 4;
+        (*(ea->ea_entries))[count].ea_size = ntohl(uint32);
+        (*(ea->ea_entries))[count].ea_name = strdup(buf);
+        if (! (*(ea->ea_entries))[count].ea_name) {
+            LOG(log_error, logtype_afpd, "unpack_header: OOM");
+            ret = -1;
+            goto exit;
+        }
+        (*(ea->ea_entries))[count].ea_namelen = strlen((*(ea->ea_entries))[count].ea_name);
+        buf += (*(ea->ea_entries))[count].ea_namelen + 1;
+
+        LOG(log_maxdebug, logtype_afpd, "unpack_header: entry no:%u,\"%s\", size: %u, namelen: %u", count,
+            (*(ea->ea_entries))[count].ea_name,
+            (*(ea->ea_entries))[count].ea_size,
+            (*(ea->ea_entries))[count].ea_namelen);
+
+        count++;
+    }
+
+exit:
+    return ret;
+}
+
+/*
+ * Function: pack_header
+ *
+ * Purpose: pack everything from struct ea into buffer at ea->ea_data
+ *
+ * Arguments:
+ *
+ *    ea      (rw) handle to struct ea
+ *
+ * Returns: 0 on success, -1 on error
+ *
+ * Effects:
+ *
+ * adjust ea->ea_count in case an ea entry deletetion is detected
+ */
+static int pack_header(struct ea * restrict ea)
+{
+    unsigned int count = 0, eacount = 0;
+    uint16_t uint16;
+    uint32_t uint32;
+    size_t bufsize = EA_HEADER_SIZE;
+
+    char *buf = ea->ea_data + EA_HEADER_SIZE;
+
+    LOG(log_debug, logtype_afpd, "pack_header('%s'): ea_count: %u, ea_size: %u",
+        ea->filename, ea->ea_count, ea->ea_size);
+
+    if (ea->ea_count == 0)
+        /* nothing to do, magic, version and count are still valid in buffer */
+        return 0;
+
+    while(count < ea->ea_count) { /* the names */
+        /* Check if its a deleted entry */
+        if ( ! ((*ea->ea_entries)[count].ea_name)) {
+            count++;
+            continue;
+        }
+
+        bufsize += (*(ea->ea_entries))[count].ea_namelen + 1;
+        count++;
+        eacount++;
+    }
+
+    bufsize += (eacount * 4); /* header + ea_size for each EA */
+    if (bufsize > ea->ea_size) {
+        /* we must realloc */
+        if ( ! (buf = realloc(ea->ea_data, bufsize)) ) {
+            LOG(log_error, logtype_afpd, "pack_header: OOM");
+            return -1;
+        }
+        ea->ea_data = buf;
+    }
+    ea->ea_size = bufsize;
+
+    /* copy count */
+    uint16 = htons(eacount);
+    memcpy(ea->ea_data + EA_COUNT_OFF, &uint16, 2);
+
+    count = 0;
+    buf = ea->ea_data + EA_HEADER_SIZE;
+    while (count < ea->ea_count) {
+        /* Check if its a deleted entry */
+        if ( ! ((*ea->ea_entries)[count].ea_name)) {
+            count++;
+            continue;
+        }
+
+        /* First: EA size */
+        uint32 = htonl((*(ea->ea_entries))[count].ea_size);
+        memcpy(buf, &uint32, 4);
+        buf += 4;
+
+        /* Second: EA name as C-string */
+        strcpy(buf, (*(ea->ea_entries))[count].ea_name);
+        buf += (*(ea->ea_entries))[count].ea_namelen + 1;
+
+        LOG(log_maxdebug, logtype_afpd, "pack_header: entry no:%u,\"%s\", size: %u, namelen: %u", count,
+            (*(ea->ea_entries))[count].ea_name,
+            (*(ea->ea_entries))[count].ea_size,
+            (*(ea->ea_entries))[count].ea_namelen);
+
+        count++;
+    }
+
+    ea->ea_count = eacount;
+
+    LOG(log_debug, logtype_afpd, "pack_header('%s'): ea_count: %u, ea_size: %u",
+        ea->filename, ea->ea_count, ea->ea_size);
+    
+    return 0;
+}
+
+/*
+ * Function: ea_addentry
+ *
+ * Purpose: add one EA into ea->ea_entries[]
+ *
+ * Arguments:
+ *
+ *    ea            (rw) pointer to struct ea
+ *    attruname     (r) name of EA
+ *    attrsize      (r) size of ea
+ *    bitmap        (r) bitmap from FP func
+ *
+ * Returns: new number of EA entries, -1 on error
+ *
+ * Effects:
+ *
+ * Grow array ea->ea_entries[]. If ea->ea_entries is still NULL, start allocating.
+ * Otherwise realloc and put entry at the end. Increments ea->ea_count.
+ */
+static int ea_addentry(struct ea * restrict ea,
+                       const char * restrict attruname,
+                       size_t attrsize,
+                       int bitmap)
+{
+    int ea_existed = 0;
+    unsigned int count = 0;
+    void *tmprealloc;
+
+    /* First check if an EA of the requested name already exist */
+    if (ea->ea_count > 0) {
+        while (count < ea->ea_count) {
+            if (strcmp(attruname, (*ea->ea_entries)[count].ea_name) == 0) {
+                ea_existed = 1;
+                LOG(log_debug, logtype_afpd, "ea_addentry('%s', bitmap:0x%x): exists", attruname, bitmap);
+                if (bitmap & kXAttrCreate)
+                    /* its like O_CREAT|O_EXCL -> fail */
+                    return -1;
+                (*(ea->ea_entries))[count].ea_size = attrsize;
+                return 0;
+            }
+            count++;
+        }
+    }
+
+    if ((bitmap & kXAttrReplace) && ! ea_existed)
+        /* replace was requested, but EA didn't exist */
+        return -1;
+
+    if (ea->ea_count == 0) {
+        ea->ea_entries = malloc(sizeof(struct ea_entry));
+        if ( ! ea->ea_entries) {
+            LOG(log_error, logtype_afpd, "ea_addentry: OOM");
+            return -1;
+        }
+    } else if (! ea_existed) {
+        tmprealloc = realloc(ea->ea_entries, sizeof(struct ea_entry) * (ea->ea_count + 1));
+        if ( ! tmprealloc) {
+            LOG(log_error, logtype_afpd, "ea_addentry: OOM");
+            return -1;
+        }
+        ea->ea_entries = tmprealloc;
+    }
+
+    /* We've grown the array, now store the entry */
+    (*(ea->ea_entries))[ea->ea_count].ea_size = attrsize;
+    (*(ea->ea_entries))[ea->ea_count].ea_name = strdup(attruname);
+    if ( ! (*(ea->ea_entries))[ea->ea_count].ea_name) {
+        LOG(log_error, logtype_afpd, "ea_addentry: OOM");
+        goto error;
+    }
+    (*(ea->ea_entries))[ea->ea_count].ea_namelen = strlen(attruname);
+
+    ea->ea_count++;
+    return ea->ea_count;
+
+error:
+    if (ea->ea_count == 0 && ea->ea_entries) {
+        /* We just allocated storage but had an error somewhere -> free storage*/
+        free(ea->ea_entries);
+        ea->ea_entries = NULL;
+    }
+    ea->ea_count = 0;
+    return -1;
+}
+
+/*
+ * Function: create_ea_header
+ *
+ * Purpose: create EA header file, only called from ea_open
+ *
+ * Arguments:
+ *
+ *    uname       (r)  filename for which we have to create a header
+ *    ea          (rw) ea handle with already allocated storage pointed to
+ *                     by ea->ea_data
+ *
+ * Returns: fd of open header file on success, -1 on error, errno semantics:
+ *          EEXIST: open with O_CREAT | O_EXCL failed
+ *
+ * Effects:
+ *
+ * Creates EA header file and initialize ea->ea_data buffer.
+ * Possibe race condition with other afpd processes:
+ * we were called because header file didn't exist in eg. ea_open. We then
+ * try to create a file with O_CREAT | O_EXCL, but the whole process in not atomic.
+ * What do we do then? Someone else is in the process of creating the header too, but
+ * it might not have finished it. That means we cant just open, read and use it!
+ * We therefor currently just break with an error.
+ * On return the header file is still r/w locked.
+ */
+static int create_ea_header(const char * restrict uname,
+                            struct ea * restrict ea)
+{
+    int fd = -1, err = 0;
+    char *ptr;
+
+    if ((fd = open(uname, O_RDWR | O_CREAT | O_EXCL, 0666 & ~ea->vol->v_umask)) == -1) {
+        LOG(log_error, logtype_afpd, "ea_create: open race condition with ea header for file: %s", uname);
+        return -1;
+    }
+
+    /* lock it */
+    if ((write_lock(fd, 0, SEEK_SET, 0)) != 0) {
+        LOG(log_error, logtype_afpd, "ea_create: lock race condition with ea header for file: %s", uname);
+        err = -1;
+        goto exit;
+    }
+
+    /* Now init it */
+    ptr = ea->ea_data;
+    *(uint32_t *)ptr = htonl(EA_MAGIC);
+    ptr += EA_MAGIC_LEN;
+    *(uint16_t *)ptr = htons(EA_VERSION);
+    ptr += EA_VERSION_LEN;
+    *(uint16_t *)ptr = 0;       /* count */
+
+    ea->ea_size = EA_HEADER_SIZE;
+    ea->ea_inited = EA_INITED;
+
+exit:
+    if (err != 0) {
+        close(fd);
+        fd = -1;
+    }
+    return fd;
+}
+
+/*
+ * Function: write_ea
+ *
+ * Purpose: write an EA to disk
+ *
+ * Arguments:
+ *
+ *    ea         (r) struct ea handle
+ *    attruname  (r) EA name
+ *    ibuf       (r) buffer with EA content
+ *    attrsize   (r) size of EA
+ *
+ * Returns: 0 on success, -1 on error
+ *
+ * Effects:
+ *
+ * Creates/overwrites EA file.
+ *
+ */
+static int write_ea(const struct ea * restrict ea,
+                    const char * restrict attruname,
+                    const char * restrict ibuf,
+                    size_t attrsize)
+{
+    int fd = -1, ret = AFP_OK;
+    struct stat st;
+    char *eaname;
+
+    if ((eaname = ea_path(ea, attruname, 1)) == NULL) {
+        LOG(log_error, logtype_afpd, "write_ea('%s'): ea_path error", attruname);
+        return AFPERR_MISC;
+    }
+
+    LOG(log_maxdebug, logtype_afpd, "write_ea('%s')", eaname);
+
+    /* Check if it exists, remove if yes*/
+    if ((stat(eaname, &st)) == 0) {
+        if ((unlink(eaname)) != 0) {
+            if (errno == EACCES)
+                return AFPERR_ACCESS;
+            else
+                return AFPERR_MISC;
+        }
+    }
+
+    if ((fd = open(eaname, O_RDWR | O_CREAT | O_EXCL, 0666 & ~ea->vol->v_umask)) == -1) {
+        LOG(log_error, logtype_afpd, "write_ea: open race condition: %s", eaname);
+        return -1;
+    }
+
+    /* lock it */
+    if ((write_lock(fd, 0, SEEK_SET, 0)) != 0) {
+        LOG(log_error, logtype_afpd, "write_ea: open race condition: %s", eaname);
+        ret = -1;
+        goto exit;
+    }
+
+    if (write(fd, ibuf, attrsize) != (ssize_t)attrsize) {
+        LOG(log_error, logtype_afpd, "write_ea('%s'): write: %s", eaname, strerror(errno));
+        ret = -1;
+        goto exit;
+    }
+
+exit:
+    if (fd != -1)
+        close(fd); /* and unlock */
+    return ret;
+}
+
+/*
+ * Function: ea_delentry
+ *
+ * Purpose: delete one EA from ea->ea_entries[]
+ *
+ * Arguments:
+ *
+ *    ea            (rw) pointer to struct ea
+ *    attruname     (r) EA name
+ *
+ * Returns: new number of EA entries, -1 on error
+ *
+ * Effects:
+ *
+ * Remove entry from  ea->ea_entries[]. Decrement ea->ea_count.
+ * Marks it as unused just by freeing name and setting it to NULL.
+ * ea_close and pack_buffer must honor this.
+ */
+static int ea_delentry(struct ea * restrict ea, const char * restrict attruname)
+{
+    int ret = 0;
+    unsigned int count = 0;
+
+    if (ea->ea_count == 0) {
+        LOG(log_error, logtype_afpd, "ea_delentry('%s'): illegal ea_count of 0 on deletion",
+            attruname);
+        return -1;
+    }
+
+    while (count < ea->ea_count) {
+        /* search matching EA */
+        if ((*ea->ea_entries)[count].ea_name &&
+            strcmp(attruname, (*ea->ea_entries)[count].ea_name) == 0) {
+            free((*ea->ea_entries)[count].ea_name);
+            (*ea->ea_entries)[count].ea_name = NULL;
+
+            LOG(log_debug, logtype_afpd, "ea_delentry('%s'): deleted no %u/%u",
+                attruname, count + 1, ea->ea_count);
+
+            break;
+        }
+        count++;
+    }
+
+    return ret;
+}
+
+/*
+ * Function: delete_ea_file
+ *
+ * Purpose: delete EA file from disk
+ *
+ * Arguments:
+ *
+ *    ea         (r) struct ea handle
+ *    attruname  (r) EA name
+ *
+ * Returns: 0 on success, -1 on error
+ */
+static int delete_ea_file(const struct ea * restrict ea, const char *eaname)
+{
+    int ret = 0;
+    char *eafile;
+    struct stat st;
+
+    if ((eafile = ea_path(ea, eaname, 1)) == NULL) {
+        LOG(log_error, logtype_afpd, "delete_ea_file('%s'): ea_path error", eaname);
+        return -1;
+    }
+
+    /* Check if it exists, remove if yes*/
+    if ((stat(eafile, &st)) == 0) {
+        if ((unlink(eafile)) != 0) {
+            LOG(log_error, logtype_afpd, "delete_ea_file('%s'): unlink: %s",
+                eafile, strerror(errno));
+            ret = -1;
+        } else
+            LOG(log_debug, logtype_afpd, "delete_ea_file('%s'): success", eafile);
+    }
+
+    return ret;
+}
+
+/*************************************************************************************
+ * ea_path, ea_open and ea_close are only global so that dbd can call them
+ *************************************************************************************/
+
+/*
+ * Function: ea_path
+ *
+ * Purpose: return name of ea header filename
+ *
+ * Arguments:
+ *
+ *    ea           (r) ea handle
+ *    eaname       (r) name of EA or NULL
+ *    macname      (r) if != 0 call mtoupath on eaname
+ *
+ * Returns: pointer to name in static buffer, NULL on error
+ *
+ * Effects:
+ *
+ * Calls ad_open, copies buffer, appends "::EA" and if supplied append eanme
+ * Files: "file" -> "file/.AppleDouble/file::EA"
+ * Dirs: "dir" -> "dir/.AppleDouble/.Parent::EA"
+ * "file" with EA "myEA" -> "file/.AppleDouble/file::EA:myEA"
+ */
+char *ea_path(const struct ea * restrict ea, const char * restrict eaname, int macname)
+{
+    const char *adname;
+    static char pathbuf[MAXPATHLEN + 1];
+
+    /* get name of a adouble file from uname */
+    adname = ea->vol->ad_path(ea->filename, (ea->ea_flags & EA_DIR) ? ADFLAGS_DIR : 0);
+    /* copy it so we can work with it */
+    strlcpy(pathbuf, adname, MAXPATHLEN + 1);
+    /* append "::EA" */
+    strlcat(pathbuf, "::EA", MAXPATHLEN + 1);
+
+    if (eaname) {
+        strlcat(pathbuf, "::", MAXPATHLEN + 1);
+        if (macname)
+            if ((eaname = mtoupath(ea->vol, eaname)) == NULL)
+                return NULL;
+        strlcat(pathbuf, eaname, MAXPATHLEN + 1);
+    }
+
+    return pathbuf;
+}
+
+/*
+ * Function: ea_open
+ *
+ * Purpose: open EA header file, create if it doesnt exits and called with O_CREATE
+ *
+ * Arguments:
+ *
+ *    vol         (r) current volume
+ *    uname       (r) filename for which we have to open a header
+ *    flags       (r) EA_CREATE: create if it doesn't exist (without it won't be created)
+ *                    EA_RDONLY: open read only
+ *                    EA_RDWR: open read/write
+ *                    Eiterh EA_RDONLY or EA_RDWR MUST be requested
+ *    ea          (w) pointer to a struct ea that we fill
+ *
+ * Returns: 0 on success
+ *         -1 on misc error with errno = EFAULT
+ *         -2 if no EA header exists with errno = ENOENT
+ *
+ * Effects:
+ *
+ * opens header file and stores fd in ea->ea_fd. Size of file is put into ea->ea_size.
+ * number of EAs is stored in ea->ea_count. flags are remembered in ea->ea_flags.
+ * file is either read or write locked depending on the open flags.
+ * When you're done with struct ea you must call ea_close on it.
+ */
+int ea_open(const struct vol * restrict vol,
+            const char * restrict uname,
+            eaflags_t eaflags,
+            struct ea * restrict ea)
+{
+    int ret = 0;
+    char *eaname;
+    struct stat st;
+
+    /* Enforce usage rules! */
+    if ( ! (eaflags & (EA_RDONLY | EA_RDWR))) {
+        LOG(log_error, logtype_afpd, "ea_open: called without EA_RDONLY | EA_RDWR", uname);
+        return -1;
+    }
+
+    /* Set it all to 0 */
+    memset(ea, 0, sizeof(struct ea));
+
+    ea->vol = vol;              /* ea_close needs it */
+    ea->ea_flags = eaflags;
+    ea->dirfd = -1;             /* no *at (cf openat) semantics by default */
+
+    /* Dont care for errors, eg when removing the file is already gone */
+    if (!stat(uname, &st) && S_ISDIR(st.st_mode))
+        ea->ea_flags |=  EA_DIR;
+
+    if ( ! (ea->filename = strdup(uname))) {
+        LOG(log_error, logtype_afpd, "ea_open: OOM");
+        return -1;
+    }
+
+    eaname = ea_path(ea, NULL, 0);
+    LOG(log_maxdebug, logtype_afpd, "ea_open: ea_path: %s", eaname);
+
+    /* Check if it exists, if not create it if EA_CREATE is in eaflags */
+    if ((stat(eaname, &st)) != 0) {
+        if (errno == ENOENT) {
+
+            /* It doesnt exist */
+
+            if ( ! (eaflags & EA_CREATE)) {
+                /* creation was not requested, so return with error */
+                ret = -2;
+                goto exit;
+            }
+
+            /* Now create a header file */
+
+            /* malloc buffer for minimal on disk data */
+            ea->ea_data = malloc(EA_HEADER_SIZE);
+            if (! ea->ea_data) {
+                LOG(log_error, logtype_afpd, "ea_open: OOM");
+                ret = -1;
+                goto exit;
+            }
+
+            /* create it */
+            ea->ea_fd = create_ea_header(eaname, ea);
+            if (ea->ea_fd == -1) {
+                ret = -1;
+                goto exit;
+            }
+
+            return 0;
+
+        } else {/* errno != ENOENT */
+            ret = -1;
+            goto exit;
+        }
+    }
+
+    /* header file exists, so read and parse it */
+
+    /* malloc buffer where we read disk file into */
+    if (st.st_size < EA_HEADER_SIZE) {
+        LOG(log_error, logtype_afpd, "ea_open('%s'): bogus EA header file", eaname);
+        ret = -1;
+        goto exit;
+    }
+    ea->ea_size = st.st_size;
+    ea->ea_data = malloc(st.st_size);
+    if (! ea->ea_data) {
+        LOG(log_error, logtype_afpd, "ea_open: OOM");
+        ret = -1;
+        goto exit;
+    }
+
+    /* Now lock, open and read header file from disk */
+    if ((ea->ea_fd = open(eaname, (ea->ea_flags & EA_RDWR) ? O_RDWR : O_RDONLY)) == -1) {
+        LOG(log_error, logtype_afpd, "ea_open('%s'): error: %s", eaname, strerror(errno));
+        ret = -1;
+        goto exit;
+    }
+
+    /* lock it */
+    if (ea->ea_flags & EA_RDONLY) {
+        /* read lock */
+        if ((read_lock(ea->ea_fd, 0, SEEK_SET, 0)) != 0) {
+            LOG(log_error, logtype_afpd, "ea_open: lock error on  header: %s", eaname);
+            ret = -1;
+            goto exit;
+        }
+    } else {  /* EA_RDWR */
+        /* write lock */
+        if ((write_lock(ea->ea_fd, 0, SEEK_SET, 0)) != 0) {
+            LOG(log_error, logtype_afpd, "ea_open: lock error on  header: %s", eaname);
+            ret = -1;
+            goto exit;
+        }
+    }
+
+    /* read it */
+    if (read(ea->ea_fd, ea->ea_data, ea->ea_size) != (ssize_t)ea->ea_size) {
+        LOG(log_error, logtype_afpd, "ea_open: short read on header: %s", eaname);
+        ret = -1;
+        goto exit;
+    }
+
+    if ((unpack_header(ea)) != 0) {
+        LOG(log_error, logtype_afpd, "ea_open: error unpacking header for: %s", eaname);
+        ret = -1;
+        goto exit;
+    }
+
+exit:
+    switch (ret) {
+    case 0:
+        ea->ea_inited = EA_INITED;
+        break;
+    case -1:
+        errno = EFAULT; /* force some errno distinguishable from ENOENT */
+        /* fall through */
+    case -2:
+        if (ea->ea_data) {
+            free(ea->ea_data);
+            ea->ea_data = NULL;
+        }
+        if (ea->ea_fd) {
+            close(ea->ea_fd);
+            ea->ea_fd = -1;
+        }
+        break;
+    }
+
+    return ret;
+}
+
+/*
+ * Function: ea_openat
+ *
+ * Purpose: openat like wrapper for ea_open, takes a additional file descriptor
+ *
+ * Arguments:
+ *
+ *    vol         (r) current volume
+ *    sfd         (r) openat like file descriptor
+ *    uname       (r) filename for which we have to open a header
+ *    flags       (r) EA_CREATE: create if it doesn't exist (without it won't be created)
+ *                    EA_RDONLY: open read only
+ *                    EA_RDWR: open read/write
+ *                    Eiterh EA_RDONLY or EA_RDWR MUST be requested
+ *    ea          (w) pointer to a struct ea that we fill
+ *
+ * Returns: 0 on success
+ *         -1 on misc error with errno = EFAULT
+ *         -2 if no EA header exists with errno = ENOENT
+ *
+ * Effects:
+ *
+ * opens header file and stores fd in ea->ea_fd. Size of file is put into ea->ea_size.
+ * number of EAs is stored in ea->ea_count. flags are remembered in ea->ea_flags.
+ * file is either read or write locked depending on the open flags.
+ * When you're done with struct ea you must call ea_close on it.
+ */
+int ea_openat(const struct vol * restrict vol,
+              int dirfd,
+              const char * restrict uname,
+              eaflags_t eaflags,
+              struct ea * restrict ea)
+{
+    int ret = 0;
+    int cwdfd = -1;
+
+    if (dirfd != -1) {
+        if (((cwdfd = open(".", O_RDONLY)) == -1) || (fchdir(dirfd) != 0)) {
+            ret = -1;
+            goto exit;
+        }
+    }
+
+    ret = ea_open(vol, uname, eaflags, ea);
+    ea->dirfd = dirfd;
+
+    if (dirfd != -1) {
+        if (fchdir(cwdfd) != 0) {
+            LOG(log_error, logtype_afpd, "ea_openat: cant chdir back, exiting");
+            exit(EXITERR_SYS);
+        }
+    }
+
+
+exit:
+    if (cwdfd != -1)
+        close(cwdfd);
+
+    return ret;
+
+}
+
+/*
+ * Function: ea_close
+ *
+ * Purpose: flushes and closes an ea handle
+ *
+ * Arguments:
+ *
+ *    ea          (rw) pointer to ea handle
+ *
+ * Returns: 0 on success, -1 on error
+ *
+ * Effects:
+ *
+ * Flushes and then closes and frees all resouces held by ea handle.
+ * Pack data in ea into ea_data, then write ea_data to disk
+ */
+int ea_close(struct ea * restrict ea)
+{
+    int ret = 0; 
+    unsigned int count = 0;
+    char *eaname;
+    struct stat st;
+
+    LOG(log_debug, logtype_afpd, "ea_close('%s')", ea->filename);
+
+    if (ea->ea_inited != EA_INITED) {
+        LOG(log_warning, logtype_afpd, "ea_close('%s'): non initialized ea", ea->filename);
+        return 0;
+    }
+
+    /* pack header and write it to disk if it was opened EA_RDWR*/
+    if (ea->ea_flags & EA_RDWR) {
+        if ((pack_header(ea)) != 0) {
+            LOG(log_error, logtype_afpd, "ea_close: pack header");
+            ret = -1;
+        } else {
+            if (ea->ea_count == 0) {
+                /* Check if EA header exists and remove it */
+                eaname = ea_path(ea, NULL, 0);
+                if ((lstatat(ea->dirfd, eaname, &st)) == 0) {
+                    if ((netatalk_unlinkat(ea->dirfd, eaname)) != 0) {
+                        LOG(log_error, logtype_afpd, "ea_close('%s'): unlink: %s",
+                            eaname, strerror(errno));
+                        ret = -1;
+                    }
+                    else
+                        LOG(log_debug, logtype_afpd, "ea_close(unlink '%s'): success", eaname);
+                } else {
+                    /* stat error */
+                    if (errno != ENOENT) {
+                        LOG(log_error, logtype_afpd, "ea_close('%s'): stat: %s",
+                            eaname, strerror(errno));
+                        ret = -1;
+                    }
+                }
+            } else { /* ea->ea_count > 0 */
+                if ((lseek(ea->ea_fd, 0, SEEK_SET)) == -1) {
+                    LOG(log_error, logtype_afpd, "ea_close: lseek: %s", strerror(errno));
+                    ret = -1;
+                    goto exit;
+                }
+
+                if ((ftruncate(ea->ea_fd, 0)) == -1) {
+                    LOG(log_error, logtype_afpd, "ea_close: ftruncate: %s", strerror(errno));
+                    ret = -1;
+                    goto exit;
+                }
+
+                if (write(ea->ea_fd, ea->ea_data, ea->ea_size) != (ssize_t)ea->ea_size) {
+                    LOG(log_error, logtype_afpd, "ea_close: write: %s", strerror(errno));
+                    ret = -1;
+                }
+            }
+        }
+    }
+
+exit:
+    /* free names */
+    while(count < ea->ea_count) {
+        if ( (*ea->ea_entries)[count].ea_name ) {
+            free((*ea->ea_entries)[count].ea_name);
+            (*ea->ea_entries)[count].ea_name = NULL;
+        }
+        count++;
+    }
+    ea->ea_count = 0;
+
+    if (ea->filename) {
+        free(ea->filename);
+        ea->filename = NULL;
+    }
+
+    if (ea->ea_entries) {
+        free(ea->ea_entries);
+        ea->ea_entries = NULL;
+    }
+
+    if (ea->ea_data) {
+        free(ea->ea_data);
+        ea->ea_data = NULL;
+    }
+    if (ea->ea_fd != -1) {
+        close(ea->ea_fd);       /* also releases the fcntl lock */
+        ea->ea_fd = -1;
+    }
+
+    return 0;
+}
+
+
+
+/************************************************************************************
+ * VFS funcs called from afp_ea* funcs
+ ************************************************************************************/
+
+/*
+ * Function: get_easize
+ *
+ * Purpose: get size of an EA
+ *
+ * Arguments:
+ *
+ *    vol          (r) current volume
+ *    rbuf         (w) DSI reply buffer
+ *    rbuflen      (rw) current length of data in reply buffer
+ *    uname        (r) filename
+ *    oflag        (r) link and create flag
+ *    attruname    (r) name of attribute
+ *
+ * Returns: AFP code: AFP_OK on success or appropiate AFP error code
+ *
+ * Effects:
+ *
+ * Copies EA size into rbuf in network order. Increments *rbuflen +4.
+ */
+int get_easize(VFS_FUNC_ARGS_EA_GETSIZE)
+{
+    int ret = AFPERR_MISC;
+    unsigned int count = 0;
+    uint32_t uint32;
+    struct ea ea;
+
+    LOG(log_debug, logtype_afpd, "get_easize: file: %s", uname);
+
+    if ((ea_open(vol, uname, EA_RDONLY, &ea)) != 0) {
+        if (errno != ENOENT)
+            LOG(log_error, logtype_afpd, "get_easize: error calling ea_open for file: %s", uname);
+
+        memset(rbuf, 0, 4);
+        *rbuflen += 4;
+        return ret;
+    }
+
+    while (count < ea.ea_count) {
+        if (strcmp(attruname, (*ea.ea_entries)[count].ea_name) == 0) {
+            uint32 = htonl((*ea.ea_entries)[count].ea_size);
+            memcpy(rbuf, &uint32, 4);
+            *rbuflen += 4;
+            ret = AFP_OK;
+
+            LOG(log_debug, logtype_afpd, "get_easize(\"%s\"): size: %u",
+                attruname, (*ea.ea_entries)[count].ea_size);
+            break;
+        }
+        count++;
+    }
+
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "get_easize: error closing ea handle for file: %s", uname);
+        return AFPERR_MISC;
+    }
+
+    return ret;
+}
+
+/*
+ * Function: get_eacontent
+ *
+ * Purpose: copy EA into rbuf
+ *
+ * Arguments:
+ *
+ *    vol          (r) current volume
+ *    rbuf         (w) DSI reply buffer
+ *    rbuflen      (rw) current length of data in reply buffer
+ *    uname        (r) filename
+ *    oflag        (r) link and create flag
+ *    attruname    (r) name of attribute
+ *    maxreply     (r) maximum EA size as of current specs/real-life
+ *
+ * Returns: AFP code: AFP_OK on success or appropiate AFP error code
+ *
+ * Effects:
+ *
+ * Copies EA into rbuf. Increments *rbuflen accordingly.
+ */
+int get_eacontent(VFS_FUNC_ARGS_EA_GETCONTENT)
+{
+    int ret = AFPERR_MISC, fd = -1;
+    unsigned int count = 0;
+    uint32_t uint32;
+    size_t toread;
+    struct ea ea;
+    char *eafile;
+
+    LOG(log_debug, logtype_afpd, "get_eacontent('%s/%s')", uname, attruname);
+
+    if ((ea_open(vol, uname, EA_RDONLY, &ea)) != 0) {
+        if (errno != ENOENT)
+            LOG(log_error, logtype_afpd, "get_eacontent('%s'): ea_open error", uname);
+        memset(rbuf, 0, 4);
+        *rbuflen += 4;
+        return ret;
+    }
+
+    while (count < ea.ea_count) {
+        if (strcmp(attruname, (*ea.ea_entries)[count].ea_name) == 0) {
+            if ( (eafile = ea_path(&ea, attruname, 1)) == NULL) {
+                ret = AFPERR_MISC;
+                break;
+            }
+
+            if ((fd = open(eafile, O_RDONLY)) == -1) {
+                LOG(log_error, logtype_afpd, "get_eacontent('%s'): open error: %s", uname, strerror(errno));
+                ret = AFPERR_MISC;
+                break;
+            }
+
+            /* Check how much the client wants, give him what we think is right */
+            maxreply -= MAX_REPLY_EXTRA_BYTES;
+            if (maxreply > MAX_EA_SIZE)
+                maxreply = MAX_EA_SIZE;
+            toread = (maxreply < (*ea.ea_entries)[count].ea_size) ? maxreply : (*ea.ea_entries)[count].ea_size;
+            LOG(log_debug, logtype_afpd, "get_eacontent('%s'): sending %u bytes", attruname, toread);
+
+            /* Put length of EA data in reply buffer */
+            uint32 = htonl(toread);
+            memcpy(rbuf, &uint32, 4);
+            rbuf += 4;
+            *rbuflen += 4;
+
+            if (read(fd, rbuf, toread) != (ssize_t)toread) {
+                LOG(log_error, logtype_afpd, "get_eacontent('%s/%s'): short read", uname, attruname);
+                close(fd);
+                ret = AFPERR_MISC;
+                break;
+            }
+            *rbuflen += toread;
+            close(fd);
+
+            ret = AFP_OK;
+            break;
+        }
+        count++;
+    }
+
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "get_eacontent('%s'): error closing ea handle", uname);
+        return AFPERR_MISC;
+    }
+
+    return ret;
+
+}
+
+/*
+ * Function: list_eas
+ *
+ * Purpose: copy names of EAs into attrnamebuf
+ *
+ * Arguments:
+ *
+ *    vol          (r) current volume
+ *    attrnamebuf  (w) store names a consecutive C strings here
+ *    buflen       (rw) length of names in attrnamebuf
+ *    uname        (r) filename
+ *    oflag        (r) link and create flag
+ *
+ * Returns: AFP code: AFP_OK on success or appropiate AFP error code
+ *
+ * Effects:
+ *
+ * Copies names of all EAs of uname as consecutive C strings into rbuf.
+ * Increments *buflen accordingly.
+ */
+int list_eas(VFS_FUNC_ARGS_EA_LIST)
+{
+    unsigned int count = 0;
+    int attrbuflen = *buflen, ret = AFP_OK, len;
+    char *buf = attrnamebuf;
+    struct ea ea;
+
+    LOG(log_debug, logtype_afpd, "list_eas: file: %s", uname);
+
+    if ((ea_open(vol, uname, EA_RDONLY, &ea)) != 0) {
+        if (errno != ENOENT) {
+            LOG(log_error, logtype_afpd, "list_eas: error calling ea_open for file: %s", uname);
+            return AFPERR_MISC;
+        }
+        else
+            return AFP_OK;
+    }
+
+    while (count < ea.ea_count) {
+        /* Convert name to CH_UTF8_MAC and directly store in in the reply buffer */
+        if ( ( len = convert_string(vol->v_volcharset,
+                                    CH_UTF8_MAC, 
+                                    (*ea.ea_entries)[count].ea_name,
+                                    (*ea.ea_entries)[count].ea_namelen,
+                                    buf + attrbuflen,
+                                    255))
+             <= 0 ) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+        if (len == 255)
+            /* convert_string didn't 0-terminate */
+            attrnamebuf[attrbuflen + 255] = 0;
+
+        LOG(log_debug7, logtype_afpd, "list_eas(%s): EA: %s",
+            uname, (*ea.ea_entries)[count].ea_name);
+
+        attrbuflen += len + 1;
+        if (attrbuflen > (ATTRNAMEBUFSIZ - 256)) {
+            /* Next EA name could overflow, so bail out with error.
+               FIXME: evantually malloc/memcpy/realloc whatever.
+               Is it worth it ? */
+            LOG(log_warning, logtype_afpd, "list_eas(%s): running out of buffer for EA names", uname);
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+        count++;
+    }
+
+exit:
+    *buflen = attrbuflen;
+
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "list_eas: error closing ea handle for file: %s", uname);
+        return AFPERR_MISC;
+    }
+
+    return ret;
+}
+
+/*
+ * Function: set_ea
+ *
+ * Purpose: set a Solaris native EA
+ *
+ * Arguments:
+ *
+ *    vol          (r) current volume
+ *    uname        (r) filename
+ *    attruname    (r) EA name
+ *    ibuf         (r) buffer with EA content
+ *    attrsize     (r) length EA in ibuf
+ *    oflag        (r) link and create flag
+ *
+ * Returns: AFP code: AFP_OK on success or appropiate AFP error code
+ *
+ * Effects:
+ *
+ * Copies names of all EAs of uname as consecutive C strings into rbuf.
+ * Increments *rbuflen accordingly.
+ */
+int set_ea(VFS_FUNC_ARGS_EA_SET)
+{
+    int ret = AFP_OK;
+    struct ea ea;
+
+    LOG(log_debug, logtype_afpd, "set_ea: file: %s", uname);
+
+    if ((ea_open(vol, uname, EA_CREATE | EA_RDWR, &ea)) != 0) {
+        LOG(log_error, logtype_afpd, "set_ea('%s'): ea_open error", uname);
+        return AFPERR_MISC;
+    }
+
+    if ((ea_addentry(&ea, attruname, attrsize, oflag)) == -1) {
+        LOG(log_error, logtype_afpd, "set_ea('%s'): ea_addentry error", uname);
+        ret = AFPERR_MISC;
+        goto exit;
+    }
+
+    if ((write_ea(&ea, attruname, ibuf, attrsize)) != 0) {
+        LOG(log_error, logtype_afpd, "set_ea('%s'): write_ea error", uname);
+        ret = AFPERR_MISC;
+        goto exit;
+    }
+
+exit:
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "set_ea('%s'): ea_close error", uname);
+        ret = AFPERR_MISC;
+        goto exit;
+    }
+
+    return ret;
+}
+
+/*
+ * Function: remove_ea
+ *
+ * Purpose: remove a EA from a file
+ *
+ * Arguments:
+ *
+ *    vol          (r) current volume
+ *    uname        (r) filename
+ *    attruname    (r) EA name
+ *    oflag        (r) link and create flag
+ *
+ * Returns: AFP code: AFP_OK on success or appropiate AFP error code
+ *
+ * Effects:
+ *
+ * Removes EA attruname from file uname.
+ */
+int remove_ea(VFS_FUNC_ARGS_EA_REMOVE)
+{
+    int ret = AFP_OK;
+    struct ea ea;
+
+    LOG(log_debug, logtype_afpd, "remove_ea('%s/%s')", uname, attruname);
+
+    if ((ea_open(vol, uname, EA_RDWR, &ea)) != 0) {
+        LOG(log_error, logtype_afpd, "remove_ea('%s'): ea_open error", uname);
+        return AFPERR_MISC;
+    }
+
+    if ((ea_delentry(&ea, attruname)) == -1) {
+        LOG(log_error, logtype_afpd, "remove_ea('%s'): ea_delentry error", uname);
+        ret = AFPERR_MISC;
+        goto exit;
+    }
+
+    if ((delete_ea_file(&ea, attruname)) != 0) {
+        LOG(log_error, logtype_afpd, "remove_ea('%s'): delete_ea error", uname);
+        ret = AFPERR_MISC;
+        goto exit;
+    }
+
+exit:
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "remove_ea('%s'): ea_close error", uname);
+        ret = AFPERR_MISC;
+        goto exit;
+    }
+
+    return ret;
+}
+
+/******************************************************************************************
+ * EA VFS funcs that deal with file/dir cp/mv/rm
+ ******************************************************************************************/
+
+int ea_deletefile(VFS_FUNC_ARGS_DELETEFILE)
+{
+    unsigned int count = 0;
+    int ret = AFP_OK;
+    int cwd = -1;
+    struct ea ea;
+
+    LOG(log_debug, logtype_afpd, "ea_deletefile('%s')", file);
+
+    /* Open EA stuff */
+    if ((ea_openat(vol, dirfd, file, EA_RDWR, &ea)) != 0) {
+        if (errno == ENOENT)
+            /* no EA files, nothing to do */
+            return AFP_OK;
+        else {
+            LOG(log_error, logtype_afpd, "ea_deletefile('%s'): error calling ea_open", file);
+            return AFPERR_MISC;
+        }
+    }
+
+    if (dirfd != -1) {
+        if (((cwd = open(".", O_RDONLY)) == -1) || (fchdir(dirfd) != 0)) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+    }
+
+    while (count < ea.ea_count) {
+        if ((delete_ea_file(&ea, (*ea.ea_entries)[count].ea_name)) != 0) {
+            ret = AFPERR_MISC;
+            continue;
+        }
+        free((*ea.ea_entries)[count].ea_name);
+        (*ea.ea_entries)[count].ea_name = NULL;
+        count++;
+    }
+
+    /* ea_close removes the EA header file for us because all names are NULL */
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "ea_deletefile('%s'): error closing ea handle", file);
+        ret = AFPERR_MISC;
+    }
+
+    if (dirfd != -1 && fchdir(cwd) != 0) {
+        LOG(log_error, logtype_afpd, "ea_deletefile: cant chdir back. exit!");
+        exit(EXITERR_SYS);
+    }
+
+exit:
+    if (cwd != -1)
+        close(cwd);
+
+    return ret;
+}
+
+int ea_renamefile(VFS_FUNC_ARGS_RENAMEFILE)
+{
+    unsigned int count = 0;
+    int    ret = AFP_OK;
+    size_t easize;
+    char   srceapath[ MAXPATHLEN + 1];
+    char   *eapath;
+    char   *eaname;
+    struct ea srcea;
+    struct ea dstea;
+    struct adouble ad;
+
+    LOG(log_debug, logtype_afpd, "ea_renamefile('%s'/'%s')", src, dst);
+            
+
+    /* Open EA stuff */
+    if ((ea_openat(vol, dirfd, src, EA_RDWR, &srcea)) != 0) {
+        if (errno == ENOENT)
+            /* no EA files, nothing to do */
+            return AFP_OK;
+        else {
+            LOG(log_error, logtype_afpd, "ea_renamefile('%s'/'%s'): ea_open error: '%s'", src, dst, src);
+            return AFPERR_MISC;
+        }
+    }
+
+    if ((ea_open(vol, dst, EA_RDWR | EA_CREATE, &dstea)) != 0) {
+        if (errno == ENOENT) {
+            /* Possibly the .AppleDouble folder didn't exist, we create it and try again */
+            ad_init(&ad, vol); 
+            if ((ad_open(&ad, dst, ADFLAGS_HF | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666)) != 0) {
+                LOG(log_error, logtype_afpd, "ea_renamefile('%s/%s'): ad_open error: '%s'", src, dst, dst);
+                ret = AFPERR_MISC;
+                goto exit;
+            }
+            ad_close(&ad, ADFLAGS_HF);
+            if ((ea_open(vol, dst, EA_RDWR | EA_CREATE, &dstea)) != 0) {
+                ret = AFPERR_MISC;
+                goto exit;
+            }
+        }
+    }
+
+    /* Loop through all EAs: */
+    while (count < srcea.ea_count) {
+        /* Move EA */
+        eaname = (*srcea.ea_entries)[count].ea_name;
+        easize = (*srcea.ea_entries)[count].ea_size;
+
+        /* Build src and dst paths for rename() */
+        if ((eapath = ea_path(&srcea, eaname, 1)) == NULL) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+        strcpy(srceapath, eapath);
+        if ((eapath = ea_path(&dstea, eaname, 1)) == NULL) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+
+        LOG(log_maxdebug, logtype_afpd, "ea_renamefile('%s/%s'): moving EA '%s' to '%s'",
+            src, dst, srceapath, eapath);
+
+        /* Add EA to dstea */
+        if ((ea_addentry(&dstea, eaname, easize, 0)) == -1) {
+            LOG(log_error, logtype_afpd, "ea_renamefile('%s/%s'): moving EA '%s' to '%s'",
+                src, dst, srceapath, eapath);
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+
+        /* Remove EA entry from srcea */
+        if ((ea_delentry(&srcea, eaname)) == -1) {
+            LOG(log_error, logtype_afpd, "ea_renamefile('%s/%s'): moving EA '%s' to '%s'",
+                src, dst, srceapath, eapath);
+            ea_delentry(&dstea, eaname);
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+
+        /* Now rename the EA */
+        if ((unix_rename(dirfd, srceapath, -1, eapath)) < 0) {
+            LOG(log_error, logtype_afpd, "ea_renamefile('%s/%s'): moving EA '%s' to '%s'",
+                src, dst, srceapath, eapath);
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+
+        count++;
+    }
+
+
+exit:
+    ea_close(&srcea);
+    ea_close(&dstea);
+       return ret;
+}
+
+int ea_copyfile(VFS_FUNC_ARGS_COPYFILE)
+{
+    unsigned int count = 0;
+    int    ret = AFP_OK;
+    size_t easize;
+    char   srceapath[ MAXPATHLEN + 1];
+    char   *eapath;
+    char   *eaname;
+    struct ea srcea;
+    struct ea dstea;
+    struct adouble ad;
+
+    LOG(log_debug, logtype_afpd, "ea_copyfile('%s'/'%s')", src, dst);
+
+    /* Open EA stuff */
+    if ((ea_openat(vol, sfd, src, EA_RDWR, &srcea)) != 0) {
+        if (errno == ENOENT)
+            /* no EA files, nothing to do */
+            return AFP_OK;
+        else {
+            LOG(log_error, logtype_afpd, "ea_copyfile('%s'/'%s'): ea_open error: '%s'", src, dst, src);
+            return AFPERR_MISC;
+        }
+    }
+
+    if ((ea_open(vol, dst, EA_RDWR | EA_CREATE, &dstea)) != 0) {
+        if (errno == ENOENT) {
+            /* Possibly the .AppleDouble folder didn't exist, we create it and try again */
+            ad_init(&ad, vol);
+            if ((ad_open(&ad, dst, ADFLAGS_HF | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666)) != 0) {
+                LOG(log_error, logtype_afpd, "ea_copyfile('%s/%s'): ad_open error: '%s'", src, dst, dst);
+                ret = AFPERR_MISC;
+                goto exit;
+            }
+            ad_close(&ad, ADFLAGS_HF);
+            if ((ea_open(vol, dst, EA_RDWR | EA_CREATE, &dstea)) != 0) {
+                ret = AFPERR_MISC;
+                goto exit;
+            }
+        }
+    }
+
+    /* Loop through all EAs: */
+    while (count < srcea.ea_count) {
+        /* Copy EA */
+        eaname = (*srcea.ea_entries)[count].ea_name;
+        easize = (*srcea.ea_entries)[count].ea_size;
+
+        /* Build src and dst paths for copy_file() */
+        if ((eapath = ea_path(&srcea, eaname, 1)) == NULL) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+        strcpy(srceapath, eapath);
+        if ((eapath = ea_path(&dstea, eaname, 1)) == NULL) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+
+        LOG(log_maxdebug, logtype_afpd, "ea_copyfile('%s/%s'): copying EA '%s' to '%s'",
+            src, dst, srceapath, eapath);
+
+        /* Add EA to dstea */
+        if ((ea_addentry(&dstea, eaname, easize, 0)) == -1) {
+            LOG(log_error, logtype_afpd, "ea_copyfile('%s/%s'): ea_addentry('%s') error",
+                src, dst, eaname);
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+
+        /* Now copy the EA */
+        if ((copy_file(sfd, srceapath, eapath, (0666 & ~vol->v_umask))) < 0) {
+            LOG(log_error, logtype_afpd, "ea_copyfile('%s/%s'): copying EA '%s' to '%s'",
+                src, dst, srceapath, eapath);
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+
+        count++;
+    }
+
+exit:
+    ea_close(&srcea);
+    ea_close(&dstea);
+       return ret;
+}
+
+int ea_chown(VFS_FUNC_ARGS_CHOWN)
+{
+
+    unsigned int count = 0;
+    int ret = AFP_OK;
+    char *eaname;
+    struct ea ea;
+
+    LOG(log_debug, logtype_afpd, "ea_chown('%s')", path);
+    /* Open EA stuff */
+    if ((ea_open(vol, path, EA_RDWR, &ea)) != 0) {
+        if (errno == ENOENT)
+            /* no EA files, nothing to do */
+            return AFP_OK;
+        else {
+            LOG(log_error, logtype_afpd, "ea_chown('%s'): error calling ea_open", path);
+            return AFPERR_MISC;
+        }
+    }
+
+    if ((lchown(ea_path(&ea, NULL, 0), uid, gid)) != 0) {
+        switch (errno) {
+        case EPERM:
+        case EACCES:
+            ret = AFPERR_ACCESS;
+            goto exit;
+        default:
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+    }
+
+    while (count < ea.ea_count) {
+        if ((eaname = ea_path(&ea, (*ea.ea_entries)[count].ea_name, 1)) == NULL) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+        if ((lchown(eaname, uid, gid)) != 0) {
+            switch (errno) {
+            case EPERM:
+            case EACCES:
+                ret = AFPERR_ACCESS;
+                goto exit;
+            default:
+                ret = AFPERR_MISC;
+                goto exit;
+            }
+            continue;
+        }
+
+        count++;
+    }
+
+exit:
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "ea_chown('%s'): error closing ea handle", path);
+        return AFPERR_MISC;
+    }
+
+    return ret;
+}
+
+int ea_chmod_file(VFS_FUNC_ARGS_SETFILEMODE)
+{
+
+    unsigned int count = 0;
+    int ret = AFP_OK;
+    const char *eaname;
+    struct ea ea;
+
+    LOG(log_debug, logtype_afpd, "ea_chmod_file('%s')", name);
+    /* Open EA stuff */
+    if ((ea_open(vol, name, EA_RDWR, &ea)) != 0) {
+        if (errno == ENOENT)
+            /* no EA files, nothing to do */
+            return AFP_OK;
+        else
+            return AFPERR_MISC;
+    }
+
+    /* Set mode on EA header file */
+    if ((setfilmode(ea_path(&ea, NULL, 0), ea_header_mode(mode), NULL, vol->v_umask)) != 0) {
+        LOG(log_error, logtype_afpd, "ea_chmod_file('%s'): %s", ea_path(&ea, NULL, 0), strerror(errno));
+        switch (errno) {
+        case EPERM:
+        case EACCES:
+            ret = AFPERR_ACCESS;
+            goto exit;
+        default:
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+    }
+
+    /* Set mode on EA files */
+    while (count < ea.ea_count) {
+        if ((eaname = ea_path(&ea, (*ea.ea_entries)[count].ea_name, 1)) == NULL) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+        if ((setfilmode(eaname, ea_mode(mode), NULL, vol->v_umask)) != 0) {
+            LOG(log_error, logtype_afpd, "ea_chmod_file('%s'): %s", eaname, strerror(errno));
+            switch (errno) {
+            case EPERM:
+            case EACCES:
+                ret = AFPERR_ACCESS;
+                goto exit;
+            default:
+                ret = AFPERR_MISC;
+                goto exit;
+            }
+            continue;
+        }
+
+        count++;
+    }
+
+exit:
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "ea_chmod_file('%s'): error closing ea handle", name);
+        return AFPERR_MISC;
+    }
+
+    return ret;
+}
+
+int ea_chmod_dir(VFS_FUNC_ARGS_SETDIRUNIXMODE)
+{
+
+    int ret = AFP_OK;
+    unsigned int count = 0;
+    uid_t uid;
+    const char *eaname;
+    const char *eaname_safe = NULL;
+    struct ea ea;
+
+    LOG(log_debug, logtype_afpd, "ea_chmod_dir('%s')", name);
+    /* .AppleDouble already might be inaccesible, so we must run as id 0 */
+    uid = geteuid();
+    if (seteuid(0)) {
+        LOG(log_error, logtype_afpd, "ea_chmod_dir('%s'): seteuid: %s", name, strerror(errno));
+        return AFPERR_MISC;
+    }
+
+    /* Open EA stuff */
+    if ((ea_open(vol, name, EA_RDWR, &ea)) != 0) {
+        /* ENOENT --> no EA files, nothing to do */
+        if (errno != ENOENT)
+            ret = AFPERR_MISC;
+        if (seteuid(uid) < 0) {
+            LOG(log_error, logtype_afpd, "can't seteuid back: %s", strerror(errno));
+            exit(EXITERR_SYS);
+        }
+        return ret;
+    }
+
+    /* Set mode on EA header */
+    if ((setfilmode(ea_path(&ea, NULL, 0), ea_header_mode(mode), NULL, vol->v_umask)) != 0) {
+        LOG(log_error, logtype_afpd, "ea_chmod_dir('%s'): %s", ea_path(&ea, NULL, 0), strerror(errno));
+        switch (errno) {
+        case EPERM:
+        case EACCES:
+            ret = AFPERR_ACCESS;
+            goto exit;
+        default:
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+    }
+
+    /* Set mode on EA files */
+    while (count < ea.ea_count) {
+        eaname = (*ea.ea_entries)[count].ea_name;
+        /*
+         * Be careful with EA names from the EA header!
+         * Eg NFS users might have access to them, can inject paths using ../ or /.....
+         * FIXME:
+         * Until the EA code escapes / in EA name requests from the client, these therefor wont work.
+         */
+        if ((eaname_safe = strrchr(eaname, '/'))) {
+            LOG(log_warning, logtype_afpd, "ea_chmod_dir('%s'): contains a slash", eaname);
+            eaname = eaname_safe;
+        }
+        if ((eaname = ea_path(&ea, eaname, 1)) == NULL) {
+            ret = AFPERR_MISC;
+            goto exit;
+        }
+        if ((setfilmode(eaname, ea_mode(mode), NULL, vol->v_umask)) != 0) {
+            LOG(log_error, logtype_afpd, "ea_chmod_dir('%s'): %s", eaname, strerror(errno));
+            switch (errno) {
+            case EPERM:
+            case EACCES:
+                ret = AFPERR_ACCESS;
+                goto exit;
+            default:
+                ret = AFPERR_MISC;
+                goto exit;
+            }
+            continue;
+        }
+
+        count++;
+    }
+
+exit:
+    if (seteuid(uid) < 0) {
+        LOG(log_error, logtype_afpd, "can't seteuid back: %s", strerror(errno));
+        exit(EXITERR_SYS);
+    }
+
+    if ((ea_close(&ea)) != 0) {
+        LOG(log_error, logtype_afpd, "ea_chmod_dir('%s'): error closing ea handle", name);
+        return AFPERR_MISC;
+    }
+
+    return ret;
+}
index 77ab783b04c8d3546f20ecb66e5d6335e387ae82..a30e6d96b5b40121d3d8cebf434cb53fc8942a47 100644 (file)
@@ -1,5 +1,4 @@
 /*
-  $Id: ea_sys.c,v 1.8 2010-04-13 08:05:06 franklahm Exp $
   Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
 
   This program is free software; you can redistribute it and/or modify
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <dirent.h>
-
-#if HAVE_ATTR_XATTR_H
-#include <attr/xattr.h>
-#elif HAVE_SYS_XATTR_H
-#include <sys/xattr.h>
-#endif
-
-#ifdef HAVE_SYS_EA_H
-#include <sys/ea.h>
-#endif
-
-#ifdef HAVE_SYS_EXTATTR_H
-#include <sys/extattr.h>
-#endif
+#include <arpa/inet.h>
 
 #include <atalk/adouble.h>
 #include <atalk/ea.h>
 #include <atalk/unix.h>
 #include <atalk/compat.h>
 
-#ifndef ENOATTR
-#define ENOATTR ENODATA
-#endif
-
-
 /**********************************************************************************
  * EA VFS funcs for storing EAs in nativa filesystem EAs
  **********************************************************************************/
@@ -100,14 +81,15 @@ int sys_get_easize(VFS_FUNC_ARGS_EA_GETSIZE)
         switch(errno) {
         case OPEN_NOFOLLOW_ERRNO:
             /* its a symlink and client requested O_NOFOLLOW  */
-            LOG(log_debug, logtype_afpd, "sys_getextattr_size(%s): encountered symlink with kXAttrNoFollow", uname);
-            return AFP_OK;
+            LOG(log_debug, logtype_afpd, "sys_getextattr_size(%s): symlink with kXAttrNoFollow", uname);
+            return AFPERR_MISC;
 
         case ENOATTR:
+        case ENOENT:
             return AFPERR_MISC;
 
         default:
-            LOG(log_error, logtype_afpd, "sys_getextattr_size: error: %s", strerror(errno));
+            LOG(log_debug, logtype_afpd, "sys_getextattr_size: error: %s", strerror(errno));
             return AFPERR_MISC;
         }
     }
@@ -175,14 +157,14 @@ int sys_get_eacontent(VFS_FUNC_ARGS_EA_GETCONTENT)
         switch(errno) {
         case OPEN_NOFOLLOW_ERRNO:
             /* its a symlink and client requested O_NOFOLLOW  */
-            LOG(log_debug, logtype_afpd, "sys_getextattr_content(%s): encountered symlink with kXAttrNoFollow", uname);
-            return AFP_OK;
+            LOG(log_debug, logtype_afpd, "sys_getextattr_content(%s): symlink with kXAttrNoFollow", uname);
+            return AFPERR_MISC;
 
         case ENOATTR:
             return AFPERR_MISC;
 
         default:
-            LOG(log_error, logtype_afpd, "sys_getextattr_content(%s): error: %s", attruname, strerror(errno));
+            LOG(log_debug, logtype_afpd, "sys_getextattr_content(%s): error: %s", attruname, strerror(errno));
             return AFPERR_MISC;
         }
     }
@@ -215,6 +197,8 @@ int sys_get_eacontent(VFS_FUNC_ARGS_EA_GETCONTENT)
  *
  * Copies names of all EAs of uname as consecutive C strings into rbuf.
  * Increments *rbuflen accordingly.
+ * We hide the adouble:ea extended attributes here, but we currently
+ * allow reading, writing and deleteting them.
  */
 int sys_list_eas(VFS_FUNC_ARGS_EA_LIST)
 {
@@ -236,43 +220,40 @@ int sys_list_eas(VFS_FUNC_ARGS_EA_LIST)
 
     if (ret == -1) switch(errno) {
         case OPEN_NOFOLLOW_ERRNO:
-            /* its a symlink and client requested O_NOFOLLOW */
-            ret = AFPERR_BADTYPE;
-            goto exit;
-#ifdef HAVE_ATTROPEN            /* Solaris */
-        case ENOATTR:
+            /* its a symlink and client requested O_NOFOLLOW, we pretend 0 EAs */
+            LOG(log_debug, logtype_afpd, "sys_list_extattr(%s): symlink with kXAttrNoFollow", uname);
             ret = AFP_OK;
             goto exit;
-#endif
         default:
-            LOG(log_error, logtype_afpd, "sys_list_extattr(%s): error opening atttribute dir: %s", uname, strerror(errno));
-            ret= AFPERR_MISC;
+            LOG(log_debug, logtype_afpd, "sys_list_extattr(%s): error opening atttribute dir: %s", uname, strerror(errno));
+            ret = AFPERR_MISC;
             goto exit;
     }
     
     ptr = buf;
     while (ret > 0)  {
         len = strlen(ptr);
+        if (NOT_NETATALK_EA(ptr)) {
+            /* Convert name to CH_UTF8_MAC and directly store in in the reply buffer */
+            if ( 0 >= ( nlen = convert_string(vol->v_volcharset, CH_UTF8_MAC, ptr, len, attrnamebuf + attrbuflen, 256)) ) {
+                ret = AFPERR_MISC;
+                goto exit;
+            }
 
-        /* Convert name to CH_UTF8_MAC and directly store in in the reply buffer */
-        if ( 0 >= ( nlen = convert_string(vol->v_volcharset, CH_UTF8_MAC, ptr, len, attrnamebuf + attrbuflen, 256)) ) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-
-        LOG(log_debug7, logtype_afpd, "sys_list_extattr(%s): attribute: %s", uname, ptr);
+            LOG(log_debug7, logtype_afpd, "sys_list_extattr(%s): attribute: %s", uname, ptr);
 
-        attrbuflen += nlen + 1;
-        if (attrbuflen > (ATTRNAMEBUFSIZ - 256)) {
-            /* Next EA name could overflow, so bail out with error.
-               FIXME: evantually malloc/memcpy/realloc whatever.
-               Is it worth it ? */
-            LOG(log_warning, logtype_afpd, "sys_list_extattr(%s): running out of buffer for EA names", uname);
-            ret = AFPERR_MISC;
-            goto exit;
+            attrbuflen += nlen + 1;
+            if (attrbuflen > (ATTRNAMEBUFSIZ - 256)) {
+                /* Next EA name could overflow, so bail out with error.
+                   FIXME: evantually malloc/memcpy/realloc whatever.
+                   Is it worth it ? */
+                LOG(log_warning, logtype_afpd, "sys_list_extattr(%s): running out of buffer for EA names", uname);
+                ret = AFPERR_MISC;
+                goto exit;
+            }
         }
-        ret -= len +1;
-        ptr += len +1;
+        ret -= len + 1;
+        ptr += len + 1;
     }
 
     ret = AFP_OK;
@@ -325,8 +306,8 @@ int sys_set_ea(VFS_FUNC_ARGS_EA_SET)
         switch(errno) {
         case OPEN_NOFOLLOW_ERRNO:
             /* its a symlink and client requested O_NOFOLLOW  */
-            LOG(log_debug, logtype_afpd, "sys_set_ea(\"%s/%s\", ea:'%s'): encountered symlink with kXAttrNoFollow",
-                getcwdpath(), uname, attruname);
+            LOG(log_debug, logtype_afpd, "sys_set_ea(\"%s\", ea:'%s'): symlink with kXAttrNoFollow",
+                uname, attruname);
             return AFP_OK;
         case EEXIST:
             LOG(log_debug, logtype_afpd, "sys_set_ea(\"%s/%s\", ea:'%s'): EA already exists",
@@ -379,13 +360,10 @@ int sys_remove_ea(VFS_FUNC_ARGS_EA_REMOVE)
         switch(errno) {
         case OPEN_NOFOLLOW_ERRNO:
             /* its a symlink and client requested O_NOFOLLOW  */
-            LOG(log_debug, logtype_afpd, "sys_remove_ea(%s/%s): encountered symlink with kXAttrNoFollow", uname);
+            LOG(log_debug, logtype_afpd, "sys_remove_ea(%s/%s): symlink with kXAttrNoFollow", uname);
             return AFP_OK;
-        case EACCES:
-            LOG(log_debug, logtype_afpd, "sys_remove_ea(%s/%s): error: %s", uname, attruname, strerror(errno));
-            return AFPERR_ACCESS;
         default:
-            LOG(log_error, logtype_afpd, "sys_remove_ea(%s/%s): error: %s", uname, attruname, strerror(errno));
+            LOG(log_debug, logtype_afpd, "sys_remove_ea(%s/%s): error: %s", uname, attruname, strerror(errno));
             return AFPERR_MISC;
         }
     }
diff --git a/libatalk/vfs/extattr.c b/libatalk/vfs/extattr.c
new file mode 100644 (file)
index 0000000..26da706
--- /dev/null
@@ -0,0 +1,938 @@
+/* 
+   Unix SMB/CIFS implementation.
+   Samba system utilities
+   Copyright (C) Andrew Tridgell 1992-1998
+   Copyright (C) Jeremy Allison  1998-2005
+   Copyright (C) Timur Bakeyev        2005
+   Copyright (C) Bjoern Jacke    2006-2007
+   
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+   
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+   
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   
+   sys_copyxattr modified from LGPL2.1 libattr copyright
+   Copyright (C) 2001-2002 Silicon Graphics, Inc.  All Rights Reserved.
+   Copyright (C) 2001 Andreas Gruenbacher.
+      
+   Samba 3.0.28, modified for netatalk.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <errno.h>
+
+#if HAVE_ATTR_XATTR_H
+#include <attr/xattr.h>
+#elif HAVE_SYS_XATTR_H
+#include <sys/xattr.h>
+#endif
+
+#ifdef HAVE_SYS_EA_H
+#include <sys/ea.h>
+#endif
+
+#ifdef HAVE_ATTROPEN
+
+#include <dirent.h>
+#endif
+
+#ifdef HAVE_SYS_EXTATTR_H
+#include <sys/extattr.h>
+#endif
+
+#include <atalk/adouble.h>
+#include <atalk/util.h>
+#include <atalk/logger.h>
+#include <atalk/ea.h>
+#include <atalk/compat.h>
+#include <atalk/errchk.h>
+
+/******** Solaris EA helper function prototypes ********/
+#ifdef HAVE_ATTROPEN
+#define SOLARIS_ATTRMODE S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH
+static int solaris_write_xattr(int attrfd, const char *value, size_t size);
+static ssize_t solaris_read_xattr(int attrfd, void *value, size_t size);
+static ssize_t solaris_list_xattr(int attrdirfd, char *list, size_t size);
+static int solaris_unlinkat(int attrdirfd, const char *name);
+static int solaris_attropen(const char *path, const char *attrpath, int oflag, mode_t mode);
+static int solaris_openat(int fildes, const char *path, int oflag, mode_t mode);
+#endif
+
+/**************************************************************************
+ Wrappers for extented attribute calls. Based on the Linux package with
+ support for IRIX and (Net|Free)BSD also. Expand as other systems have them.
+****************************************************************************/
+static char attr_name[256 +5] = "user.";
+
+static const char *prefix(const char *uname)
+{
+#if defined(HAVE_ATTROPEN)
+       return uname;
+#else
+       strlcpy(attr_name +5, uname, 256);
+       return attr_name;
+#endif
+}
+
+int sys_getxattrfd(int fd, const char *uname, int oflag, ...)
+{
+#if defined HAVE_ATTROPEN
+    int eafd;
+    va_list args;
+    mode_t mode = 0;
+
+    if (oflag & O_CREAT) {
+        va_start(args, oflag);
+        mode = va_arg(args, mode_t);
+        va_end(args);
+    }
+
+    if (oflag & O_CREAT)
+        eafd = solaris_openat(fd, uname, oflag | O_XATTR, mode);
+    else
+        eafd = solaris_openat(fd, uname, oflag | O_XATTR, mode);
+
+    return eafd;
+#else
+    errno = ENOSYS;
+    return -1;
+#endif
+}
+
+ssize_t sys_getxattr (const char *path, const char *uname, void *value, size_t size)
+{
+       const char *name = prefix(uname);
+
+#if defined(HAVE_GETXATTR)
+#ifndef XATTR_ADD_OPT
+       return getxattr(path, name, value, size);
+#else
+       int options = 0;
+       return getxattr(path, name, value, size, 0, options);
+#endif
+#elif defined(HAVE_GETEA)
+       return getea(path, name, value, size);
+#elif defined(HAVE_EXTATTR_GET_FILE)
+       ssize_t retval;
+       /*
+        * The BSD implementation has a nasty habit of silently truncating
+        * the returned value to the size of the buffer, so we have to check
+        * that the buffer is large enough to fit the returned value.
+        */
+       if((retval = extattr_get_file(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0)) >= 0) {
+        if (size == 0)
+            /* size == 0 means only return size */
+            return retval;
+               if (retval > size) {
+                       errno = ERANGE;
+                       return -1;
+               }
+               if ((retval = extattr_get_file(path, EXTATTR_NAMESPACE_USER, uname, value, size)) >= 0)
+                       return retval;
+       }
+
+       LOG(log_maxdebug, logtype_default, "sys_getxattr: extattr_get_file() failed with: %s\n", strerror(errno));
+       return -1;
+#elif defined(HAVE_ATTR_GET)
+       int retval, flags = 0;
+       int valuelength = (int)size;
+       char *attrname = strchr(name,'.') + 1;
+       
+       if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
+
+       retval = attr_get(path, attrname, (char *)value, &valuelength, flags);
+
+       return retval ? retval : valuelength;
+#elif defined(HAVE_ATTROPEN)
+       ssize_t ret = -1;
+       int attrfd = solaris_attropen(path, name, O_RDONLY, 0);
+       if (attrfd >= 0) {
+               ret = solaris_read_xattr(attrfd, value, size);
+               close(attrfd);
+       }
+       return ret;
+#else
+       errno = ENOSYS;
+       return -1;
+#endif
+}
+
+ssize_t sys_fgetxattr (int filedes, const char *uname, void *value, size_t size)
+{
+    const char *name = prefix(uname);
+
+#if defined(HAVE_FGETXATTR)
+#ifndef XATTR_ADD_OPT
+    return fgetxattr(filedes, name, value, size);
+#else
+    int options = 0;
+    return fgetxattr(filedes, name, value, size, 0, options);
+#endif
+#elif defined(HAVE_FGETEA)
+    return fgetea(filedes, name, value, size);
+#elif defined(HAVE_EXTATTR_GET_FD)
+    char *s;
+    ssize_t retval;
+    int attrnamespace = (strncmp(name, "system", 6) == 0) ? 
+        EXTATTR_NAMESPACE_SYSTEM : EXTATTR_NAMESPACE_USER;
+    const char *attrname = ((s=strchr(name, '.')) == NULL) ? name : s + 1;
+
+    if((retval=extattr_get_fd(filedes, attrnamespace, attrname, NULL, 0)) >= 0) {
+        if(retval > size) {
+            errno = ERANGE;
+            return -1;
+        }
+        if((retval=extattr_get_fd(filedes, attrnamespace, attrname, value, size)) >= 0)
+            return retval;
+    }
+
+    LOG(log_debug, logtype_default, "sys_fgetxattr: extattr_get_fd(): %s", strerror(errno));
+    return -1;
+#elif defined(HAVE_ATTR_GETF)
+    int retval, flags = 0;
+    int valuelength = (int)size;
+    char *attrname = strchr(name,'.') + 1;
+
+    if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
+
+    retval = attr_getf(filedes, attrname, (char *)value, &valuelength, flags);
+
+    return retval ? retval : valuelength;
+#elif defined(HAVE_ATTROPEN)
+    ssize_t ret = -1;
+    int attrfd = solaris_openat(filedes, name, O_RDONLY|O_XATTR, 0);
+    if (attrfd >= 0) {
+        ret = solaris_read_xattr(attrfd, value, size);
+        close(attrfd);
+    }
+    return ret;
+#else
+    errno = ENOSYS;
+    return -1;
+#endif
+}
+
+ssize_t sys_lgetxattr (const char *path, const char *uname, void *value, size_t size)
+{
+       const char *name = prefix(uname);
+
+#if defined(HAVE_LGETXATTR)
+       return lgetxattr(path, name, value, size);
+#elif defined(HAVE_GETXATTR) && defined(XATTR_ADD_OPT)
+       int options = XATTR_NOFOLLOW;
+       return getxattr(path, name, value, size, 0, options);
+#elif defined(HAVE_LGETEA)
+       return lgetea(path, name, value, size);
+#elif defined(HAVE_EXTATTR_GET_LINK)
+       ssize_t retval;
+       if((retval=extattr_get_link(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0)) >= 0) {
+               if(retval > size) {
+                       errno = ERANGE;
+                       return -1;
+               }
+               if((retval=extattr_get_link(path, EXTATTR_NAMESPACE_USER, uname, value, size)) >= 0)
+                       return retval;
+       }
+       
+       LOG(log_maxdebug, logtype_default, "sys_lgetxattr: extattr_get_link() failed with: %s\n", strerror(errno));
+       return -1;
+#elif defined(HAVE_ATTR_GET)
+       int retval, flags = ATTR_DONTFOLLOW;
+       int valuelength = (int)size;
+       char *attrname = strchr(name,'.') + 1;
+       
+       if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
+
+       retval = attr_get(path, attrname, (char *)value, &valuelength, flags);
+
+       return retval ? retval : valuelength;
+#elif defined(HAVE_ATTROPEN)
+       ssize_t ret = -1;
+       int attrfd = solaris_attropen(path, name, O_RDONLY | O_NOFOLLOW, 0);
+       if (attrfd >= 0) {
+               ret = solaris_read_xattr(attrfd, value, size);
+               close(attrfd);
+       }
+       return ret;
+#else
+       errno = ENOSYS;
+       return -1;
+#endif
+}
+
+#if defined(HAVE_EXTATTR_LIST_FILE)
+
+#define EXTATTR_PREFIX(s)      (s), (sizeof((s))-1)
+
+static struct {
+        int space;
+       const char *name;
+       size_t len;
+} 
+extattr[] = {
+       { EXTATTR_NAMESPACE_SYSTEM, EXTATTR_PREFIX("") },
+        { EXTATTR_NAMESPACE_USER, EXTATTR_PREFIX("") },
+};
+
+typedef union {
+       const char *path;
+       int filedes;
+} extattr_arg;
+
+static ssize_t bsd_attr_list (int type, extattr_arg arg, char *list, size_t size)
+{
+       ssize_t list_size;
+       int i, len;
+
+    switch(type) {
+#if defined(HAVE_EXTATTR_LIST_FILE)
+    case 0:
+        list_size = extattr_list_file(arg.path, EXTATTR_NAMESPACE_USER, list, size);
+        break;
+#endif
+#if defined(HAVE_EXTATTR_LIST_LINK)
+    case 1:
+        list_size = extattr_list_link(arg.path, EXTATTR_NAMESPACE_USER, list, size);
+        break;
+#endif
+#if defined(HAVE_EXTATTR_LIST_FD)
+    case 2:
+        list_size = extattr_list_fd(arg.filedes, EXTATTR_NAMESPACE_USER, list, size);
+        break;
+#endif
+    default:
+        errno = ENOSYS;
+        return -1;
+    }
+
+    /* Some error happend. Errno should be set by the previous call */
+    if(list_size < 0)
+        return -1;
+
+    /* No attributes */
+    if(list_size == 0)
+        return 0;
+
+    /* XXX: Call with an empty buffer may be used to calculate
+       necessary buffer size. Unfortunately, we can't say, how
+       many attributes were returned, so here is the potential
+       problem with the emulation.
+    */
+    if(list == NULL)
+        return list_size;
+
+    /* Buffer is too small to fit the results */
+    if(list_size > size) {
+        errno = ERANGE;
+        return -1;
+    }
+
+    /* Convert from pascal strings to C strings */
+    len = list[0];
+    memmove(list, list + 1, list_size);
+
+    for(i = len; i < list_size; ) {
+        LOG(log_maxdebug, logtype_afpd, "len: %d, i: %d", len, i);
+
+        len = list[i];
+        list[i] = '\0';
+        i += len + 1;
+    }
+
+       return list_size;
+}
+
+#endif
+
+#if defined(HAVE_ATTR_LIST) && defined(HAVE_SYS_ATTRIBUTES_H)
+static char attr_buffer[ATTR_MAX_VALUELEN];
+
+static ssize_t irix_attr_list(const char *path, int filedes, char *list, size_t size, int flags)
+{
+       int retval = 0, index;
+       attrlist_cursor_t *cursor = 0;
+       int total_size = 0;
+       attrlist_t * al = (attrlist_t *)attr_buffer;
+       attrlist_ent_t *ae;
+       size_t ent_size, left = size;
+       char *bp = list;
+
+       while (True) {
+           if (filedes)
+               retval = attr_listf(filedes, attr_buffer, ATTR_MAX_VALUELEN, flags, cursor);
+           else
+               retval = attr_list(path, attr_buffer, ATTR_MAX_VALUELEN, flags, cursor);
+           if (retval) break;
+           for (index = 0; index < al->al_count; index++) {
+               ae = ATTR_ENTRY(attr_buffer, index);
+               ent_size = strlen(ae->a_name) + sizeof("user.");
+               if (left >= ent_size) {
+                   strncpy(bp, "user.", sizeof("user."));
+                   strncat(bp, ae->a_name, ent_size - sizeof("user."));
+                   bp += ent_size;
+                   left -= ent_size;
+               } else if (size) {
+                   errno = ERANGE;
+                   retval = -1;
+                   break;
+               }
+               total_size += ent_size;
+           }
+           if (al->al_more == 0) break;
+       }
+       if (retval == 0) {
+           flags |= ATTR_ROOT;
+           cursor = 0;
+           while (True) {
+               if (filedes)
+                   retval = attr_listf(filedes, attr_buffer, ATTR_MAX_VALUELEN, flags, cursor);
+               else
+                   retval = attr_list(path, attr_buffer, ATTR_MAX_VALUELEN, flags, cursor);
+               if (retval) break;
+               for (index = 0; index < al->al_count; index++) {
+                   ae = ATTR_ENTRY(attr_buffer, index);
+                   ent_size = strlen(ae->a_name) + sizeof("system.");
+                   if (left >= ent_size) {
+                       strncpy(bp, "system.", sizeof("system."));
+                       strncat(bp, ae->a_name, ent_size - sizeof("system."));
+                       bp += ent_size;
+                       left -= ent_size;
+                   } else if (size) {
+                       errno = ERANGE;
+                       retval = -1;
+                       break;
+                   }
+                   total_size += ent_size;
+               }
+               if (al->al_more == 0) break;
+           }
+       }
+       return (ssize_t)(retval ? retval : total_size);
+}
+
+#endif
+
+#if defined(HAVE_LISTXATTR)
+static ssize_t remove_user(ssize_t ret, char *list, size_t size)
+{
+       size_t len;
+       char *ptr;
+       char *ptr1;
+       ssize_t ptrsize;
+       
+       if (ret <= 0 || size == 0)
+               return ret;
+       ptrsize = ret;
+       ptr = ptr1 = list;
+       while (ptrsize > 0) {
+               len = strlen(ptr1) +1;
+               ptrsize -= len;
+               if (strncmp(ptr1, "user.",5)) {
+                       ptr1 += len;
+                       continue;
+               }
+               memmove(ptr, ptr1 +5, len -5);
+               ptr += len -5;
+               ptr1 += len;
+       }
+       return ptr -list;
+}
+#endif
+
+ssize_t sys_listxattr (const char *path, char *list, size_t size)
+{
+#if defined(HAVE_LISTXATTR)
+       ssize_t ret;
+
+#ifndef XATTR_ADD_OPT
+       ret = listxattr(path, list, size);
+#else
+       int options = 0;
+       ret = listxattr(path, list, size, options);
+#endif
+       return remove_user(ret, list, size);
+
+#elif defined(HAVE_LISTEA)
+       return listea(path, list, size);
+#elif defined(HAVE_EXTATTR_LIST_FILE)
+       extattr_arg arg;
+       arg.path = path;
+       return bsd_attr_list(0, arg, list, size);
+#elif defined(HAVE_ATTR_LIST) && defined(HAVE_SYS_ATTRIBUTES_H)
+       return irix_attr_list(path, 0, list, size, 0);
+#elif defined(HAVE_ATTROPEN)
+       ssize_t ret = -1;
+       int attrdirfd = solaris_attropen(path, ".", O_RDONLY, 0);
+       if (attrdirfd >= 0) {
+               ret = solaris_list_xattr(attrdirfd, list, size);
+               close(attrdirfd);
+       }
+       return ret;
+#else
+       errno = ENOSYS;
+       return -1;
+#endif
+}
+
+ssize_t sys_llistxattr (const char *path, char *list, size_t size)
+{
+#if defined(HAVE_LLISTXATTR)
+       ssize_t ret;
+
+       ret = llistxattr(path, list, size);
+       return remove_user(ret, list, size);
+#elif defined(HAVE_LISTXATTR) && defined(XATTR_ADD_OPT)
+       ssize_t ret;
+       int options = XATTR_NOFOLLOW;
+
+       ret = listxattr(path, list, size, options);
+       return remove_user(ret, list, size);
+
+#elif defined(HAVE_LLISTEA)
+       return llistea(path, list, size);
+#elif defined(HAVE_EXTATTR_LIST_LINK)
+       extattr_arg arg;
+       arg.path = path;
+       return bsd_attr_list(1, arg, list, size);
+#elif defined(HAVE_ATTR_LIST) && defined(HAVE_SYS_ATTRIBUTES_H)
+       return irix_attr_list(path, 0, list, size, ATTR_DONTFOLLOW);
+#elif defined(HAVE_ATTROPEN)
+       ssize_t ret = -1;
+       int attrdirfd = solaris_attropen(path, ".", O_RDONLY | O_NOFOLLOW, 0);
+       if (attrdirfd >= 0) {
+               ret = solaris_list_xattr(attrdirfd, list, size);
+               close(attrdirfd);
+       }
+       return ret;
+#else
+       errno = ENOSYS;
+       return -1;
+#endif
+}
+
+int sys_removexattr (const char *path, const char *uname)
+{
+       const char *name = prefix(uname);
+#if defined(HAVE_REMOVEXATTR)
+#ifndef XATTR_ADD_OPT
+       return removexattr(path, name);
+#else
+       int options = 0;
+       return removexattr(path, name, options);
+#endif
+#elif defined(HAVE_REMOVEEA)
+       return removeea(path, name);
+#elif defined(HAVE_EXTATTR_DELETE_FILE)
+       return extattr_delete_file(path, EXTATTR_NAMESPACE_USER, uname);
+#elif defined(HAVE_ATTR_REMOVE)
+       int flags = 0;
+       char *attrname = strchr(name,'.') + 1;
+       
+       if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
+
+       return attr_remove(path, attrname, flags);
+#elif defined(HAVE_ATTROPEN)
+       int ret = -1;
+       int attrdirfd = solaris_attropen(path, ".", O_RDONLY, 0);
+       if (attrdirfd >= 0) {
+               ret = solaris_unlinkat(attrdirfd, name);
+               close(attrdirfd);
+       }
+       return ret;
+#else
+       errno = ENOSYS;
+       return -1;
+#endif
+}
+
+int sys_lremovexattr (const char *path, const char *uname)
+{
+       const char *name = prefix(uname);
+#if defined(HAVE_LREMOVEXATTR)
+       return lremovexattr(path, name);
+#elif defined(HAVE_REMOVEXATTR) && defined(XATTR_ADD_OPT)
+       int options = XATTR_NOFOLLOW;
+       return removexattr(path, name, options);
+#elif defined(HAVE_LREMOVEEA)
+       return lremoveea(path, name);
+#elif defined(HAVE_EXTATTR_DELETE_LINK)
+       return extattr_delete_link(path, EXTATTR_NAMESPACE_USER, uname);
+#elif defined(HAVE_ATTR_REMOVE)
+       int flags = ATTR_DONTFOLLOW;
+       char *attrname = strchr(name,'.') + 1;
+       
+       if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
+
+       return attr_remove(path, attrname, flags);
+#elif defined(HAVE_ATTROPEN)
+       int ret = -1;
+       int attrdirfd = solaris_attropen(path, ".", O_RDONLY | O_NOFOLLOW, 0);
+       if (attrdirfd >= 0) {
+               ret = solaris_unlinkat(attrdirfd, name);
+               close(attrdirfd);
+       }
+       return ret;
+#else
+       errno = ENOSYS;
+       return -1;
+#endif
+}
+
+int sys_setxattr (const char *path, const char *uname, const void *value, size_t size, int flags)
+{
+       const char *name = prefix(uname);
+#if defined(HAVE_SETXATTR)
+#ifndef XATTR_ADD_OPT
+       return setxattr(path, name, value, size, flags);
+#else
+       int options = 0;
+       return setxattr(path, name, value, size, 0, options);
+#endif
+#elif defined(HAVE_SETEA)
+       return setea(path, name, value, size, flags);
+#elif defined(HAVE_EXTATTR_SET_FILE)
+       int retval = 0;
+       if (flags) {
+               /* Check attribute existence */
+               retval = extattr_get_file(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0);
+               if (retval < 0) {
+                       /* REPLACE attribute, that doesn't exist */
+                       if (flags & XATTR_REPLACE && errno == ENOATTR) {
+                               errno = ENOATTR;
+                               return -1;
+                       }
+                       /* Ignore other errors */
+               }
+               else {
+                       /* CREATE attribute, that already exists */
+                       if (flags & XATTR_CREATE) {
+                               errno = EEXIST;
+                               return -1;
+                       }
+               }
+       }
+       retval = extattr_set_file(path, EXTATTR_NAMESPACE_USER, uname, value, size);
+       return (retval < 0) ? -1 : 0;
+#elif defined(HAVE_ATTR_SET)
+       int myflags = 0;
+       char *attrname = strchr(name,'.') + 1;
+       
+       if (strncmp(name, "system", 6) == 0) myflags |= ATTR_ROOT;
+       if (flags & XATTR_CREATE) myflags |= ATTR_CREATE;
+       if (flags & XATTR_REPLACE) myflags |= ATTR_REPLACE;
+
+       return attr_set(path, attrname, (const char *)value, size, myflags);
+#elif defined(HAVE_ATTROPEN)
+       int ret = -1;
+       int myflags = O_RDWR;
+       int attrfd;
+       if (flags & XATTR_CREATE) myflags |= O_EXCL;
+       if (!(flags & XATTR_REPLACE)) myflags |= O_CREAT;
+       attrfd = solaris_attropen(path, name, myflags, (mode_t) SOLARIS_ATTRMODE);
+       if (attrfd >= 0) {
+               ret = solaris_write_xattr(attrfd, value, size);
+               close(attrfd);
+       }
+       return ret;
+#else
+       errno = ENOSYS;
+       return -1;
+#endif
+}
+
+int sys_fsetxattr (int filedes, const char *uname, const void *value, size_t size, int flags)
+{
+    const char *name = prefix(uname);
+
+#if defined(HAVE_FSETXATTR)
+#ifndef XATTR_ADD_OPT
+    return fsetxattr(filedes, name, value, size, flags);
+#else
+    int options = 0;
+    return fsetxattr(filedes, name, value, size, 0, options);
+#endif
+#elif defined(HAVE_FSETEA)
+    return fsetea(filedes, name, value, size, flags);
+#elif defined(HAVE_EXTATTR_SET_FD)
+    char *s;
+    int retval = 0;
+    int attrnamespace = (strncmp(name, "system", 6) == 0) ? 
+        EXTATTR_NAMESPACE_SYSTEM : EXTATTR_NAMESPACE_USER;
+    const char *attrname = ((s=strchr(name, '.')) == NULL) ? name : s + 1;
+    if (flags) {
+        /* Check attribute existence */
+        retval = extattr_get_fd(filedes, attrnamespace, attrname, NULL, 0);
+        if (retval < 0) {
+            /* REPLACE attribute, that doesn't exist */
+            if (flags & XATTR_REPLACE && errno == ENOATTR) {
+                errno = ENOATTR;
+                return -1;
+            }
+            /* Ignore other errors */
+        }
+        else {
+            if (flags & XATTR_CREATE) {
+                errno = EEXIST;
+                return -1;
+            }
+        }
+    }
+    retval = extattr_set_fd(filedes, attrnamespace, attrname, value, size);
+    return (retval < 0) ? -1 : 0;
+#elif defined(HAVE_ATTR_SETF)
+    int myflags = 0;
+    char *attrname = strchr(name,'.') + 1;
+
+    if (strncmp(name, "system", 6) == 0) myflags |= ATTR_ROOT;
+    if (flags & XATTR_CREATE) myflags |= ATTR_CREATE;
+    if (flags & XATTR_REPLACE) myflags |= ATTR_REPLACE;
+
+    return attr_setf(filedes, attrname, (const char *)value, size, myflags);
+#elif defined(HAVE_ATTROPEN)
+    int ret = -1;
+    int myflags = O_RDWR | O_XATTR;
+    int attrfd;
+    if (flags & XATTR_CREATE) myflags |= O_EXCL;
+    if (!(flags & XATTR_REPLACE)) myflags |= O_CREAT;
+    attrfd = solaris_openat(filedes, name, myflags, (mode_t) SOLARIS_ATTRMODE);
+    if (attrfd >= 0) {
+        ret = solaris_write_xattr(attrfd, value, size);
+        close(attrfd);
+    }
+    return ret;
+#else
+    errno = ENOSYS;
+    return -1;
+#endif
+}
+
+int sys_lsetxattr (const char *path, const char *uname, const void *value, size_t size, int flags)
+{
+       const char *name = prefix(uname);
+#if defined(HAVE_LSETXATTR)
+       return lsetxattr(path, name, value, size, flags);
+#elif defined(HAVE_SETXATTR) && defined(XATTR_ADD_OPT)
+       int options = XATTR_NOFOLLOW;
+       return setxattr(path, name, value, size, 0, options);
+#elif defined(LSETEA)
+       return lsetea(path, name, value, size, flags);
+#elif defined(HAVE_EXTATTR_SET_LINK)
+       int retval = 0;
+       if (flags) {
+               /* Check attribute existence */
+               retval = extattr_get_link(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0);
+               if (retval < 0) {
+                       /* REPLACE attribute, that doesn't exist */
+                       if (flags & XATTR_REPLACE && errno == ENOATTR) {
+                               errno = ENOATTR;
+                               return -1;
+                       }
+                       /* Ignore other errors */
+               }
+               else {
+                       /* CREATE attribute, that already exists */
+                       if (flags & XATTR_CREATE) {
+                               errno = EEXIST;
+                               return -1;
+                       }
+               }
+       }
+
+       retval = extattr_set_link(path, EXTATTR_NAMESPACE_USER, uname, value, size);
+       return (retval < 0) ? -1 : 0;
+#elif defined(HAVE_ATTR_SET)
+       int myflags = ATTR_DONTFOLLOW;
+       char *attrname = strchr(name,'.') + 1;
+       
+       if (strncmp(name, "system", 6) == 0) myflags |= ATTR_ROOT;
+       if (flags & XATTR_CREATE) myflags |= ATTR_CREATE;
+       if (flags & XATTR_REPLACE) myflags |= ATTR_REPLACE;
+
+       return attr_set(path, attrname, (const char *)value, size, myflags);
+#elif defined(HAVE_ATTROPEN)
+       int ret = -1;
+       int myflags = O_RDWR | O_NOFOLLOW;
+       int attrfd;
+       if (flags & XATTR_CREATE) myflags |= O_EXCL;
+       if (!(flags & XATTR_REPLACE)) myflags |= O_CREAT;
+       attrfd = solaris_attropen(path, name, myflags, (mode_t) SOLARIS_ATTRMODE);
+       if (attrfd >= 0) {
+               ret = solaris_write_xattr(attrfd, value, size);
+               close(attrfd);
+       }
+       return ret;
+#else
+       errno = ENOSYS;
+       return -1;
+#endif
+}
+
+/**************************************************************************
+ helper functions for Solaris' EA support
+****************************************************************************/
+#ifdef HAVE_ATTROPEN
+static ssize_t solaris_read_xattr(int attrfd, void *value, size_t size)
+{
+       struct stat sbuf;
+
+       if (fstat(attrfd, &sbuf) == -1) {
+               return -1;
+       }
+
+       /* This is to return the current size of the named extended attribute */
+       if (size == 0) {
+               return sbuf.st_size;
+       }
+
+       /* check size and read xattr */
+       if (sbuf.st_size > size) {
+               return -1;
+       }
+
+       return read(attrfd, value, sbuf.st_size);
+}
+
+static ssize_t solaris_list_xattr(int attrdirfd, char *list, size_t size)
+{
+       ssize_t len = 0;
+       DIR *dirp;
+       struct dirent *de;
+       int newfd = dup(attrdirfd);
+       /* CAUTION: The originating file descriptor should not be
+                   used again following the call to fdopendir().
+                   For that reason we dup() the file descriptor
+                   here to make things more clear. */
+       dirp = fdopendir(newfd);
+
+       while ((de = readdir(dirp))) {
+               size_t listlen;
+               if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..") ||
+                    !strcmp(de->d_name, "SUNWattr_ro") || !strcmp(de->d_name, "SUNWattr_rw")) 
+               {
+                       /* we don't want "." and ".." here: */
+                       LOG(log_maxdebug, logtype_default, "skipped EA %s\n",de->d_name);
+                       continue;
+               }
+
+               listlen = strlen(de->d_name);
+               if (size == 0) {
+                       /* return the current size of the list of extended attribute names*/
+                       len += listlen + 1;
+               } else {
+                       /* check size and copy entry + nul into list. */
+                       if ((len + listlen + 1) > size) {
+                               errno = ERANGE;
+                               len = -1;
+                               break;
+                       } else {
+                               strcpy(list + len, de->d_name);
+                               len += listlen;
+                               list[len] = '\0';
+                               ++len;
+                       }
+               }
+       }
+
+       if (closedir(dirp) == -1) {
+               LOG(log_error, logtype_default, "closedir dirp: %s",strerror(errno));
+               return -1;
+       }
+       return len;
+}
+
+static int solaris_unlinkat(int attrdirfd, const char *name)
+{
+       if (unlinkat(attrdirfd, name, 0) == -1) {
+               return -1;
+       }
+       return 0;
+}
+
+static int solaris_attropen(const char *path, const char *attrpath, int oflag, mode_t mode)
+{
+    EC_INIT;
+       int filedes = -1, eafd = -1;
+
+    if ((filedes = open(path, O_RDONLY | (oflag & O_NOFOLLOW), mode)) == -1) {
+        switch (errno) {
+        case ENOENT:
+        case EEXIST:
+        case OPEN_NOFOLLOW_ERRNO:
+            EC_FAIL;
+        default:
+            LOG(log_debug, logtype_default, "open(\"%s\"): %s", fullpathname(path), strerror(errno));
+            errno = ENOATTR;
+            EC_FAIL;
+        }
+       }
+
+       if ((eafd = openat(filedes, attrpath, oflag | O_XATTR, mode)) == -1) {
+        switch (errno) {
+        case ENOENT:
+        case EEXIST:
+            EC_FAIL;
+        default:
+            LOG(log_debug, logtype_default, "openat(\"%s\"): %s", fullpathname(path), strerror(errno));
+            errno = ENOATTR;
+            EC_FAIL;
+        }
+       }
+    
+EC_CLEANUP:
+    if (filedes != -1)
+        close(filedes);
+    if (ret != 0) {
+        if (eafd != -1)
+            close(eafd);
+        eafd = -1;
+    }
+    return eafd;
+}
+
+static int solaris_openat(int fildes, const char *path, int oflag, mode_t mode)
+{
+       int filedes;
+
+       if ((filedes = openat(fildes, path, oflag, mode)) == -1) {
+        switch (errno) {
+        case ENOENT:
+        case EEXIST:
+            break;
+        default:
+            LOG(log_debug, logtype_default, "openat(\"%s\"): %s",
+                path, strerror(errno));
+            errno = ENOATTR;
+            break;
+        }
+       }
+       return filedes;
+}
+
+static int solaris_write_xattr(int attrfd, const char *value, size_t size)
+{
+       if ((ftruncate(attrfd, 0) == 0) && (write(attrfd, value, size) == size)) {
+               return 0;
+       } else {
+               LOG(log_error, logtype_default, "solaris_write_xattr: %s",
+            strerror(errno));
+               return -1;
+       }
+}
+
+#endif /*HAVE_ATTROPEN*/
+
diff --git a/libatalk/vfs/sys_ea.c b/libatalk/vfs/sys_ea.c
deleted file mode 100644 (file)
index 3db20b2..0000000
+++ /dev/null
@@ -1,758 +0,0 @@
-/* 
-   Unix SMB/CIFS implementation.
-   Samba system utilities
-   Copyright (C) Andrew Tridgell 1992-1998
-   Copyright (C) Jeremy Allison  1998-2005
-   Copyright (C) Timur Bakeyev        2005
-   Copyright (C) Bjoern Jacke    2006-2007
-   
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
-   (at your option) any later version.
-   
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
-   
-   You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-   
-   sys_copyxattr modified from LGPL2.1 libattr copyright
-   Copyright (C) 2001-2002 Silicon Graphics, Inc.  All Rights Reserved.
-   Copyright (C) 2001 Andreas Gruenbacher.
-      
-   Samba 3.0.28, modified for netatalk.
-   $Id: sys_ea.c,v 1.6 2009-12-04 10:26:10 franklahm Exp $
-   
-*/
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <errno.h>
-
-#if HAVE_ATTR_XATTR_H
-#include <attr/xattr.h>
-#elif HAVE_SYS_XATTR_H
-#include <sys/xattr.h>
-#endif
-
-#ifdef HAVE_SYS_EA_H
-#include <sys/ea.h>
-#endif
-
-#ifdef HAVE_ATTROPEN
-
-#include <dirent.h>
-#endif
-
-#ifdef HAVE_SYS_EXTATTR_H
-#include <sys/extattr.h>
-#endif
-
-#include <atalk/adouble.h>
-#include <atalk/util.h>
-#include <atalk/logger.h>
-#include <atalk/ea.h>
-
-#ifndef ENOATTR
-#define ENOATTR ENODATA
-#endif
-
-/******** Solaris EA helper function prototypes ********/
-#ifdef HAVE_ATTROPEN
-#define SOLARIS_ATTRMODE S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP
-static int solaris_write_xattr(int attrfd, const char *value, size_t size);
-static ssize_t solaris_read_xattr(int attrfd, void *value, size_t size);
-static ssize_t solaris_list_xattr(int attrdirfd, char *list, size_t size);
-static int solaris_unlinkat(int attrdirfd, const char *name);
-static int solaris_attropen(const char *path, const char *attrpath, int oflag, mode_t mode);
-static int solaris_openat(int fildes, const char *path, int oflag, mode_t mode);
-#endif
-
-/**************************************************************************
- Wrappers for extented attribute calls. Based on the Linux package with
- support for IRIX and (Net|Free)BSD also. Expand as other systems have them.
-****************************************************************************/
-static char attr_name[256 +5] = "user.";
-
-static const char *prefix(const char *uname)
-{
-#if defined(HAVE_ATTROPEN)
-       return uname;
-#else
-       strlcpy(attr_name +5, uname, 256);
-       return attr_name;
-#endif
-}
-
-ssize_t sys_getxattr (const char *path, const char *uname, void *value, size_t size)
-{
-       const char *name = prefix(uname);
-
-#if defined(HAVE_GETXATTR)
-#ifndef XATTR_ADD_OPT
-       return getxattr(path, name, value, size);
-#else
-       int options = 0;
-       return getxattr(path, name, value, size, 0, options);
-#endif
-#elif defined(HAVE_GETEA)
-       return getea(path, name, value, size);
-#elif defined(HAVE_EXTATTR_GET_FILE)
-       ssize_t retval;
-       /*
-        * The BSD implementation has a nasty habit of silently truncating
-        * the returned value to the size of the buffer, so we have to check
-        * that the buffer is large enough to fit the returned value.
-        */
-       if((retval = extattr_get_file(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0)) >= 0) {
-        if (size == 0)
-            /* size == 0 means only return size */
-            return retval;
-               if (retval > size) {
-                       errno = ERANGE;
-                       return -1;
-               }
-               if ((retval = extattr_get_file(path, EXTATTR_NAMESPACE_USER, uname, value, size)) >= 0)
-                       return retval;
-       }
-
-       LOG(log_maxdebug, logtype_default, "sys_getxattr: extattr_get_file() failed with: %s\n", strerror(errno));
-       return -1;
-#elif defined(HAVE_ATTR_GET)
-       int retval, flags = 0;
-       int valuelength = (int)size;
-       char *attrname = strchr(name,'.') + 1;
-       
-       if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
-
-       retval = attr_get(path, attrname, (char *)value, &valuelength, flags);
-
-       return retval ? retval : valuelength;
-#elif defined(HAVE_ATTROPEN)
-       ssize_t ret = -1;
-       int attrfd = solaris_attropen(path, name, O_RDONLY, 0);
-       if (attrfd >= 0) {
-               ret = solaris_read_xattr(attrfd, value, size);
-               close(attrfd);
-       }
-       return ret;
-#else
-       errno = ENOSYS;
-       return -1;
-#endif
-}
-
-ssize_t sys_lgetxattr (const char *path, const char *uname, void *value, size_t size)
-{
-       const char *name = prefix(uname);
-
-#if defined(HAVE_LGETXATTR)
-       return lgetxattr(path, name, value, size);
-#elif defined(HAVE_GETXATTR) && defined(XATTR_ADD_OPT)
-       int options = XATTR_NOFOLLOW;
-       return getxattr(path, name, value, size, 0, options);
-#elif defined(HAVE_LGETEA)
-       return lgetea(path, name, value, size);
-#elif defined(HAVE_EXTATTR_GET_LINK)
-       ssize_t retval;
-       if((retval=extattr_get_link(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0)) >= 0) {
-               if(retval > size) {
-                       errno = ERANGE;
-                       return -1;
-               }
-               if((retval=extattr_get_link(path, EXTATTR_NAMESPACE_USER, uname, value, size)) >= 0)
-                       return retval;
-       }
-       
-       LOG(log_maxdebug, logtype_default, "sys_lgetxattr: extattr_get_link() failed with: %s\n", strerror(errno));
-       return -1;
-#elif defined(HAVE_ATTR_GET)
-       int retval, flags = ATTR_DONTFOLLOW;
-       int valuelength = (int)size;
-       char *attrname = strchr(name,'.') + 1;
-       
-       if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
-
-       retval = attr_get(path, attrname, (char *)value, &valuelength, flags);
-
-       return retval ? retval : valuelength;
-#elif defined(HAVE_ATTROPEN)
-       ssize_t ret = -1;
-       int attrfd = solaris_attropen(path, name, O_RDONLY|AT_SYMLINK_NOFOLLOW, 0);
-       if (attrfd >= 0) {
-               ret = solaris_read_xattr(attrfd, value, size);
-               close(attrfd);
-       }
-       return ret;
-#else
-       errno = ENOSYS;
-       return -1;
-#endif
-}
-
-#if defined(HAVE_EXTATTR_LIST_FILE)
-
-#define EXTATTR_PREFIX(s)      (s), (sizeof((s))-1)
-
-static struct {
-        int space;
-       const char *name;
-       size_t len;
-} 
-extattr[] = {
-       { EXTATTR_NAMESPACE_SYSTEM, EXTATTR_PREFIX("") },
-        { EXTATTR_NAMESPACE_USER, EXTATTR_PREFIX("") },
-};
-
-typedef union {
-       const char *path;
-       int filedes;
-} extattr_arg;
-
-static ssize_t bsd_attr_list (int type, extattr_arg arg, char *list, size_t size)
-{
-       ssize_t list_size;
-       int i, len;
-
-    switch(type) {
-#if defined(HAVE_EXTATTR_LIST_FILE)
-    case 0:
-        list_size = extattr_list_file(arg.path, EXTATTR_NAMESPACE_USER, list, size);
-        break;
-#endif
-#if defined(HAVE_EXTATTR_LIST_LINK)
-    case 1:
-        list_size = extattr_list_link(arg.path, EXTATTR_NAMESPACE_USER, list, size);
-        break;
-#endif
-#if defined(HAVE_EXTATTR_LIST_FD)
-    case 2:
-        list_size = extattr_list_fd(arg.filedes, EXTATTR_NAMESPACE_USER, list, size);
-        break;
-#endif
-    default:
-        errno = ENOSYS;
-        return -1;
-    }
-
-    /* Some error happend. Errno should be set by the previous call */
-    if(list_size < 0)
-        return -1;
-
-    /* No attributes */
-    if(list_size == 0)
-        return 0;
-
-    /* XXX: Call with an empty buffer may be used to calculate
-       necessary buffer size. Unfortunately, we can't say, how
-       many attributes were returned, so here is the potential
-       problem with the emulation.
-    */
-    if(list == NULL)
-        return list_size;
-
-    /* Buffer is too small to fit the results */
-    if(list_size > size) {
-        errno = ERANGE;
-        return -1;
-    }
-
-    /* Convert from pascal strings to C strings */
-    len = list[0];
-    memmove(list, list + 1, list_size);
-
-    for(i = len; i < list_size; ) {
-        LOG(log_maxdebug, logtype_afpd, "len: %d, i: %d", len, i);
-
-        len = list[i];
-        list[i] = '\0';
-        i += len + 1;
-    }
-
-       return list_size;
-}
-
-#endif
-
-#if defined(HAVE_ATTR_LIST) && defined(HAVE_SYS_ATTRIBUTES_H)
-static char attr_buffer[ATTR_MAX_VALUELEN];
-
-static ssize_t irix_attr_list(const char *path, int filedes, char *list, size_t size, int flags)
-{
-       int retval = 0, index;
-       attrlist_cursor_t *cursor = 0;
-       int total_size = 0;
-       attrlist_t * al = (attrlist_t *)attr_buffer;
-       attrlist_ent_t *ae;
-       size_t ent_size, left = size;
-       char *bp = list;
-
-       while (True) {
-           if (filedes)
-               retval = attr_listf(filedes, attr_buffer, ATTR_MAX_VALUELEN, flags, cursor);
-           else
-               retval = attr_list(path, attr_buffer, ATTR_MAX_VALUELEN, flags, cursor);
-           if (retval) break;
-           for (index = 0; index < al->al_count; index++) {
-               ae = ATTR_ENTRY(attr_buffer, index);
-               ent_size = strlen(ae->a_name) + sizeof("user.");
-               if (left >= ent_size) {
-                   strncpy(bp, "user.", sizeof("user."));
-                   strncat(bp, ae->a_name, ent_size - sizeof("user."));
-                   bp += ent_size;
-                   left -= ent_size;
-               } else if (size) {
-                   errno = ERANGE;
-                   retval = -1;
-                   break;
-               }
-               total_size += ent_size;
-           }
-           if (al->al_more == 0) break;
-       }
-       if (retval == 0) {
-           flags |= ATTR_ROOT;
-           cursor = 0;
-           while (True) {
-               if (filedes)
-                   retval = attr_listf(filedes, attr_buffer, ATTR_MAX_VALUELEN, flags, cursor);
-               else
-                   retval = attr_list(path, attr_buffer, ATTR_MAX_VALUELEN, flags, cursor);
-               if (retval) break;
-               for (index = 0; index < al->al_count; index++) {
-                   ae = ATTR_ENTRY(attr_buffer, index);
-                   ent_size = strlen(ae->a_name) + sizeof("system.");
-                   if (left >= ent_size) {
-                       strncpy(bp, "system.", sizeof("system."));
-                       strncat(bp, ae->a_name, ent_size - sizeof("system."));
-                       bp += ent_size;
-                       left -= ent_size;
-                   } else if (size) {
-                       errno = ERANGE;
-                       retval = -1;
-                       break;
-                   }
-                   total_size += ent_size;
-               }
-               if (al->al_more == 0) break;
-           }
-       }
-       return (ssize_t)(retval ? retval : total_size);
-}
-
-#endif
-
-#if defined(HAVE_LISTXATTR)
-static ssize_t remove_user(ssize_t ret, char *list, size_t size)
-{
-       size_t len;
-       char *ptr;
-       char *ptr1;
-       ssize_t ptrsize;
-       
-       if (ret <= 0 || size == 0)
-               return ret;
-       ptrsize = ret;
-       ptr = ptr1 = list;
-       while (ptrsize > 0) {
-               len = strlen(ptr1) +1;
-               ptrsize -= len;
-               if (strncmp(ptr1, "user.",5)) {
-                       ptr1 += len;
-                       continue;
-               }
-               memmove(ptr, ptr1 +5, len -5);
-               ptr += len -5;
-               ptr1 += len;
-       }
-       return ptr -list;
-}
-#endif
-
-ssize_t sys_listxattr (const char *path, char *list, size_t size)
-{
-#if defined(HAVE_LISTXATTR)
-       ssize_t ret;
-
-#ifndef XATTR_ADD_OPT
-       ret = listxattr(path, list, size);
-#else
-       int options = 0;
-       ret = listxattr(path, list, size, options);
-#endif
-       return remove_user(ret, list, size);
-
-#elif defined(HAVE_LISTEA)
-       return listea(path, list, size);
-#elif defined(HAVE_EXTATTR_LIST_FILE)
-       extattr_arg arg;
-       arg.path = path;
-       return bsd_attr_list(0, arg, list, size);
-#elif defined(HAVE_ATTR_LIST) && defined(HAVE_SYS_ATTRIBUTES_H)
-       return irix_attr_list(path, 0, list, size, 0);
-#elif defined(HAVE_ATTROPEN)
-       ssize_t ret = -1;
-       int attrdirfd = solaris_attropen(path, ".", O_RDONLY, 0);
-       if (attrdirfd >= 0) {
-               ret = solaris_list_xattr(attrdirfd, list, size);
-               close(attrdirfd);
-       }
-       return ret;
-#else
-       errno = ENOSYS;
-       return -1;
-#endif
-}
-
-ssize_t sys_llistxattr (const char *path, char *list, size_t size)
-{
-#if defined(HAVE_LLISTXATTR)
-       ssize_t ret;
-
-       ret = llistxattr(path, list, size);
-       return remove_user(ret, list, size);
-#elif defined(HAVE_LISTXATTR) && defined(XATTR_ADD_OPT)
-       ssize_t ret;
-       int options = XATTR_NOFOLLOW;
-
-       ret = listxattr(path, list, size, options);
-       return remove_user(ret, list, size);
-
-#elif defined(HAVE_LLISTEA)
-       return llistea(path, list, size);
-#elif defined(HAVE_EXTATTR_LIST_LINK)
-       extattr_arg arg;
-       arg.path = path;
-       return bsd_attr_list(1, arg, list, size);
-#elif defined(HAVE_ATTR_LIST) && defined(HAVE_SYS_ATTRIBUTES_H)
-       return irix_attr_list(path, 0, list, size, ATTR_DONTFOLLOW);
-#elif defined(HAVE_ATTROPEN)
-       ssize_t ret = -1;
-       int attrdirfd = solaris_attropen(path, ".", O_RDONLY|AT_SYMLINK_NOFOLLOW, 0);
-       if (attrdirfd >= 0) {
-               ret = solaris_list_xattr(attrdirfd, list, size);
-               close(attrdirfd);
-       }
-       return ret;
-#else
-       errno = ENOSYS;
-       return -1;
-#endif
-}
-
-int sys_removexattr (const char *path, const char *uname)
-{
-       const char *name = prefix(uname);
-#if defined(HAVE_REMOVEXATTR)
-#ifndef XATTR_ADD_OPT
-       return removexattr(path, name);
-#else
-       int options = 0;
-       return removexattr(path, name, options);
-#endif
-#elif defined(HAVE_REMOVEEA)
-       return removeea(path, name);
-#elif defined(HAVE_EXTATTR_DELETE_FILE)
-       return extattr_delete_file(path, EXTATTR_NAMESPACE_USER, uname);
-#elif defined(HAVE_ATTR_REMOVE)
-       int flags = 0;
-       char *attrname = strchr(name,'.') + 1;
-       
-       if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
-
-       return attr_remove(path, attrname, flags);
-#elif defined(HAVE_ATTROPEN)
-       int ret = -1;
-       int attrdirfd = solaris_attropen(path, ".", O_RDONLY, 0);
-       if (attrdirfd >= 0) {
-               ret = solaris_unlinkat(attrdirfd, name);
-               close(attrdirfd);
-       }
-       return ret;
-#else
-       errno = ENOSYS;
-       return -1;
-#endif
-}
-
-int sys_lremovexattr (const char *path, const char *uname)
-{
-       const char *name = prefix(uname);
-#if defined(HAVE_LREMOVEXATTR)
-       return lremovexattr(path, name);
-#elif defined(HAVE_REMOVEXATTR) && defined(XATTR_ADD_OPT)
-       int options = XATTR_NOFOLLOW;
-       return removexattr(path, name, options);
-#elif defined(HAVE_LREMOVEEA)
-       return lremoveea(path, name);
-#elif defined(HAVE_EXTATTR_DELETE_LINK)
-       return extattr_delete_link(path, EXTATTR_NAMESPACE_USER, uname);
-#elif defined(HAVE_ATTR_REMOVE)
-       int flags = ATTR_DONTFOLLOW;
-       char *attrname = strchr(name,'.') + 1;
-       
-       if (strncmp(name, "system", 6) == 0) flags |= ATTR_ROOT;
-
-       return attr_remove(path, attrname, flags);
-#elif defined(HAVE_ATTROPEN)
-       int ret = -1;
-       int attrdirfd = solaris_attropen(path, ".", O_RDONLY|AT_SYMLINK_NOFOLLOW, 0);
-       if (attrdirfd >= 0) {
-               ret = solaris_unlinkat(attrdirfd, name);
-               close(attrdirfd);
-       }
-       return ret;
-#else
-       errno = ENOSYS;
-       return -1;
-#endif
-}
-
-int sys_setxattr (const char *path, const char *uname, const void *value, size_t size, int flags)
-{
-       const char *name = prefix(uname);
-#if defined(HAVE_SETXATTR)
-#ifndef XATTR_ADD_OPT
-       return setxattr(path, name, value, size, flags);
-#else
-       int options = 0;
-       return setxattr(path, name, value, size, 0, options);
-#endif
-#elif defined(HAVE_SETEA)
-       return setea(path, name, value, size, flags);
-#elif defined(HAVE_EXTATTR_SET_FILE)
-       int retval = 0;
-       if (flags) {
-               /* Check attribute existence */
-               retval = extattr_get_file(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0);
-               if (retval < 0) {
-                       /* REPLACE attribute, that doesn't exist */
-                       if (flags & XATTR_REPLACE && errno == ENOATTR) {
-                               errno = ENOATTR;
-                               return -1;
-                       }
-                       /* Ignore other errors */
-               }
-               else {
-                       /* CREATE attribute, that already exists */
-                       if (flags & XATTR_CREATE) {
-                               errno = EEXIST;
-                               return -1;
-                       }
-               }
-       }
-       retval = extattr_set_file(path, EXTATTR_NAMESPACE_USER, uname, value, size);
-       return (retval < 0) ? -1 : 0;
-#elif defined(HAVE_ATTR_SET)
-       int myflags = 0;
-       char *attrname = strchr(name,'.') + 1;
-       
-       if (strncmp(name, "system", 6) == 0) myflags |= ATTR_ROOT;
-       if (flags & XATTR_CREATE) myflags |= ATTR_CREATE;
-       if (flags & XATTR_REPLACE) myflags |= ATTR_REPLACE;
-
-       return attr_set(path, attrname, (const char *)value, size, myflags);
-#elif defined(HAVE_ATTROPEN)
-       int ret = -1;
-       int myflags = O_RDWR;
-       int attrfd;
-       if (flags & XATTR_CREATE) myflags |= O_EXCL;
-       if (!(flags & XATTR_REPLACE)) myflags |= O_CREAT;
-       attrfd = solaris_attropen(path, name, myflags, (mode_t) SOLARIS_ATTRMODE);
-       if (attrfd >= 0) {
-               ret = solaris_write_xattr(attrfd, value, size);
-               close(attrfd);
-       }
-       return ret;
-#else
-       errno = ENOSYS;
-       return -1;
-#endif
-}
-
-int sys_lsetxattr (const char *path, const char *uname, const void *value, size_t size, int flags)
-{
-       const char *name = prefix(uname);
-#if defined(HAVE_LSETXATTR)
-       return lsetxattr(path, name, value, size, flags);
-#elif defined(HAVE_SETXATTR) && defined(XATTR_ADD_OPT)
-       int options = XATTR_NOFOLLOW;
-       return setxattr(path, name, value, size, 0, options);
-#elif defined(LSETEA)
-       return lsetea(path, name, value, size, flags);
-#elif defined(HAVE_EXTATTR_SET_LINK)
-       int retval = 0;
-       if (flags) {
-               /* Check attribute existence */
-               retval = extattr_get_link(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0);
-               if (retval < 0) {
-                       /* REPLACE attribute, that doesn't exist */
-                       if (flags & XATTR_REPLACE && errno == ENOATTR) {
-                               errno = ENOATTR;
-                               return -1;
-                       }
-                       /* Ignore other errors */
-               }
-               else {
-                       /* CREATE attribute, that already exists */
-                       if (flags & XATTR_CREATE) {
-                               errno = EEXIST;
-                               return -1;
-                       }
-               }
-       }
-
-       retval = extattr_set_link(path, EXTATTR_NAMESPACE_USER, uname, value, size);
-       return (retval < 0) ? -1 : 0;
-#elif defined(HAVE_ATTR_SET)
-       int myflags = ATTR_DONTFOLLOW;
-       char *attrname = strchr(name,'.') + 1;
-       
-       if (strncmp(name, "system", 6) == 0) myflags |= ATTR_ROOT;
-       if (flags & XATTR_CREATE) myflags |= ATTR_CREATE;
-       if (flags & XATTR_REPLACE) myflags |= ATTR_REPLACE;
-
-       return attr_set(path, attrname, (const char *)value, size, myflags);
-#elif defined(HAVE_ATTROPEN)
-       int ret = -1;
-       int myflags = O_RDWR | AT_SYMLINK_NOFOLLOW;
-       int attrfd;
-       if (flags & XATTR_CREATE) myflags |= O_EXCL;
-       if (!(flags & XATTR_REPLACE)) myflags |= O_CREAT;
-       attrfd = solaris_attropen(path, name, myflags, (mode_t) SOLARIS_ATTRMODE);
-       if (attrfd >= 0) {
-               ret = solaris_write_xattr(attrfd, value, size);
-               close(attrfd);
-       }
-       return ret;
-#else
-       errno = ENOSYS;
-       return -1;
-#endif
-}
-
-/**************************************************************************
- helper functions for Solaris' EA support
-****************************************************************************/
-#ifdef HAVE_ATTROPEN
-static ssize_t solaris_read_xattr(int attrfd, void *value, size_t size)
-{
-       struct stat sbuf;
-
-       if (fstat(attrfd, &sbuf) == -1) {
-               return -1;
-       }
-
-       /* This is to return the current size of the named extended attribute */
-       if (size == 0) {
-               return sbuf.st_size;
-       }
-
-       /* check size and read xattr */
-       if (sbuf.st_size > size) {
-               return -1;
-       }
-
-       return read(attrfd, value, sbuf.st_size);
-}
-
-static ssize_t solaris_list_xattr(int attrdirfd, char *list, size_t size)
-{
-       ssize_t len = 0;
-       DIR *dirp;
-       struct dirent *de;
-       int newfd = dup(attrdirfd);
-       /* CAUTION: The originating file descriptor should not be
-                   used again following the call to fdopendir().
-                   For that reason we dup() the file descriptor
-                   here to make things more clear. */
-       dirp = fdopendir(newfd);
-
-       while ((de = readdir(dirp))) {
-               size_t listlen;
-               if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..") ||
-                    !strcmp(de->d_name, "SUNWattr_ro") || !strcmp(de->d_name, "SUNWattr_rw")) 
-               {
-                       /* we don't want "." and ".." here: */
-                       LOG(log_maxdebug, logtype_default, "skipped EA %s\n",de->d_name);
-                       continue;
-               }
-
-               listlen = strlen(de->d_name);
-               if (size == 0) {
-                       /* return the current size of the list of extended attribute names*/
-                       len += listlen + 1;
-               } else {
-                       /* check size and copy entry + nul into list. */
-                       if ((len + listlen + 1) > size) {
-                               errno = ERANGE;
-                               len = -1;
-                               break;
-                       } else {
-                               strcpy(list + len, de->d_name);
-                               len += listlen;
-                               list[len] = '\0';
-                               ++len;
-                       }
-               }
-       }
-
-       if (closedir(dirp) == -1) {
-               LOG(log_error, logtype_default, "closedir dirp: %s",strerror(errno));
-               return -1;
-       }
-       return len;
-}
-
-static int solaris_unlinkat(int attrdirfd, const char *name)
-{
-       if (unlinkat(attrdirfd, name, 0) == -1) {
-               return -1;
-       }
-       return 0;
-}
-
-static int solaris_attropen(const char *path, const char *attrpath, int oflag, mode_t mode)
-{
-       int filedes = attropen(path, attrpath, oflag, mode);
-       if (filedes == -1) {
-        if (errno != ENOENT)
-            LOG(log_error, logtype_default, "attropen(\"%s\", ea:'%s'): %s",
-                path, attrpath, strerror(errno));
-        errno = ENOATTR;
-       }
-       return filedes;
-}
-
-static int solaris_openat(int fildes, const char *path, int oflag, mode_t mode)
-{
-       int filedes = openat(fildes, path, oflag, mode);
-       if (filedes == -1) {
-               LOG(log_error, logtype_default, "openat(\"%s\"): %s",
-            path, strerror(errno));
-       }
-       return filedes;
-}
-
-static int solaris_write_xattr(int attrfd, const char *value, size_t size)
-{
-       if ((ftruncate(attrfd, 0) == 0) && (write(attrfd, value, size) == size)) {
-               return 0;
-       } else {
-               LOG(log_error, logtype_default, "solaris_write_xattr: %s",
-            strerror(errno));
-               return -1;
-       }
-}
-
-#endif /*HAVE_ATTROPEN*/
-
index ffb524b825d88e7b2444a8e5cf742eaf4d5834d6..1c0556d95e2eebc2e9baeccc34227a112ceeed8a 100644 (file)
 #include <atalk/logger.h>
 #include <atalk/unix.h>
 #include <atalk/acl.h>
-
-/* -----------------------------
-   a dropbox is a folder where w is set but not r eg:
-   rwx-wx-wx or rwx-wx--
-   rwx----wx (is not asked by a Mac with OS >= 8.0 ?)
-*/
-int stickydirmode(const char *name, const mode_t mode, const int dropbox, const mode_t v_umask)
-{
-    int retval = 0;
-
-#ifdef DROPKLUDGE
-    /* Turn on the sticky bit if this is a drop box, also turn off the setgid bit */
-    if ((dropbox & AFPVOL_DROPBOX)) {
-        int uid;
-
-        if ( ( (mode & S_IWOTH) && !(mode & S_IROTH)) ||
-             ( (mode & S_IWGRP) && !(mode & S_IRGRP)) )
-        {
-            uid=geteuid();
-            if ( seteuid(0) < 0) {
-                LOG(log_error, logtype_afpd, "stickydirmode: unable to seteuid root: %s", strerror(errno));
-            }
-            if ( (retval=chmod_acl( name, ( (DIRBITS | mode | S_ISVTX) & ~v_umask) )) < 0) {
-                LOG(log_error, logtype_afpd, "stickydirmode: chmod \"%s\": %s", fullpathname(name), strerror(errno) );
-            } else {
-                LOG(log_debug, logtype_afpd, "stickydirmode: chmod \"%s\": %s", fullpathname(name), strerror(retval) );
-            }
-            seteuid(uid);
-            return retval;
-        }
-    }
-#endif /* DROPKLUDGE */
-
-    /*
-     *  Ignore EPERM errors:  We may be dealing with a directory that is
-     *  group writable, in which case chmod will fail.
-     */
-    if ( (chmod_acl( name, (DIRBITS | mode) & ~v_umask ) < 0) && errno != EPERM &&
-         !(errno == ENOENT && (dropbox & AFPVOL_NOADOUBLE)) )
-    {
-        LOG(log_error, logtype_afpd, "stickydirmode: chmod \"%s\": %s", fullpathname(name), strerror(errno) );
-        retval = -1;
-    }
-
-    return retval;
-}
+#include <atalk/compat.h>
+#include <atalk/errchk.h>
+#include <atalk/ea.h>
 
 /* ------------------------- */
 int dir_rx_set(mode_t mode)
@@ -172,6 +129,38 @@ int netatalk_unlink(const char *name)
  * *at semnatics support functions (like openat, renameat standard funcs)
  **************************************************************************/
 
+/* Copy all file data from one file fd to another */
+int copy_file_fd(int sfd, int dfd)
+{
+    EC_INIT;
+    ssize_t cc;
+    size_t  buflen;
+    char   filebuf[NETATALK_DIOSZ_STACK];
+
+    while ((cc = read(sfd, filebuf, sizeof(filebuf)))) {
+        if (cc < 0) {
+            if (errno == EINTR)
+                continue;
+            LOG(log_error, logtype_afpd, "copy_file_fd: %s", strerror(errno));
+            EC_FAIL;
+        }
+
+        buflen = cc;
+        while (buflen > 0) {
+            if ((cc = write(dfd, filebuf, buflen)) < 0) {
+                if (errno == EINTR)
+                    continue;
+                LOG(log_error, logtype_afpd, "copy_file_fd: %s", strerror(errno));
+                EC_FAIL;
+            }
+            buflen -= cc;
+        }
+    }
+
+EC_CLEANUP:
+    EC_EXIT;
+}
+
 /* 
  * Supports *at semantics if HAVE_ATFUNCS, pass dirfd=-1 to ignore this
  */
@@ -182,7 +171,7 @@ int copy_file(int dirfd, const char *src, const char *dst, mode_t mode)
     int    dfd = -1;
     ssize_t cc;
     size_t  buflen;
-    char   filebuf[8192];
+    char   filebuf[NETATALK_DIOSZ_STACK];
 
 #ifdef HAVE_ATFUNCS
     if (dirfd == -1)
@@ -204,29 +193,7 @@ int copy_file(int dirfd, const char *src, const char *dst, mode_t mode)
         goto exit;
     }
 
-    while ((cc = read(sfd, filebuf, sizeof(filebuf)))) {
-        if (cc < 0) {
-            if (errno == EINTR)
-                continue;
-            LOG(log_error, logtype_afpd, "copy_file('%s'/'%s'): read '%s' error: %s",
-                src, dst, src, strerror(errno));
-            ret = -1;
-            goto exit;
-        }
-
-        buflen = cc;
-        while (buflen > 0) {
-            if ((cc = write(dfd, filebuf, buflen)) < 0) {
-                if (errno == EINTR)
-                    continue;
-                LOG(log_error, logtype_afpd, "copy_file('%s'/'%s'): read '%s' error: %s",
-                    src, dst, dst, strerror(errno));
-                ret = -1;
-                goto exit;
-            }
-            buflen -= cc;
-        }
-    }
+    ret = copy_file_fd(sfd, dfd);
 
 exit:
     if (sfd != -1)
@@ -247,6 +214,43 @@ exit:
     return ret;
 }
 
+/*!
+ * Copy an EA from one file to another
+ *
+ * Supports *at semantics if HAVE_ATFUNCS, pass dirfd=-1 to ignore this
+ */
+int copy_ea(const char *ea, int dirfd, const char *src, const char *dst, mode_t mode)
+{
+    EC_INIT;
+    int    sfd = -1;
+    int    dfd = -1;
+    size_t easize;
+    char   *eabuf = NULL;
+
+#ifdef HAVE_ATFUNCS
+    if (dirfd == -1)
+        dirfd = AT_FDCWD;
+    EC_NEG1_LOG( sfd = openat(dirfd, src, O_RDONLY) );
+#else
+    EC_NEG1_LOG( sfd = open(src, O_RDONLY) );
+#endif
+    EC_NEG1_LOG( dfd = open(dst, O_WRONLY, mode) );
+
+    if ((easize = sys_fgetxattr(sfd, ea, NULL, 0)) > 0) {
+        EC_NULL_LOG( eabuf = malloc(easize));
+        EC_NEG1_LOG( easize = sys_fgetxattr(sfd, ea, eabuf, easize) );
+        EC_NEG1_LOG( easize = sys_fsetxattr(dfd, ea, eabuf, easize, 0) );
+    }
+
+EC_CLEANUP:
+    if (sfd != -1)
+        close(sfd);
+    if (dfd != -1)
+        close(dfd);
+    free(eabuf);
+    EC_EXIT;
+}
+
 /* 
  * at wrapper for netatalk_unlink
  */
index 0999b878a8c37c800660e3ffb6945893e78623fe..8495d8c22fba19dd88789b82c6822bfb4a4fb3d6 100644 (file)
@@ -42,6 +42,7 @@
 #include <atalk/errchk.h>
 #include <atalk/bstrlib.h>
 #include <atalk/bstradd.h>
+#include <atalk/compat.h>
 
 struct perm {
     uid_t uid;
@@ -88,33 +89,28 @@ for_each_adouble(const char *from, const char *name, rf_loop fn, void *data, int
     return ret;
 }
 
-/*******************************************************************************
- * classic adouble format 
- *******************************************************************************/
-
 static int netatalk_name(const char *name)
 {
-    return strcasecmp(name,".AppleDouble") &&
-        strcasecmp(name,".AppleDB") &&
-        strcasecmp(name,".AppleDesktop");
+    return strcmp(name,".AppleDB") && strcmp(name,".AppleDesktop");        
 }
 
+/*******************************************************************************
+ * classic adouble format 
+ *******************************************************************************/
+
 static int validupath_adouble(VFS_FUNC_ARGS_VALIDUPATH)
 {
     if (name[0] != '.')
         return 1;
     
-    if (!(vol->v_flags & AFPVOL_USEDOTS))
-        return 0;
-        
-    return netatalk_name(name) && strcasecmp(name,".Parent");
+    return netatalk_name(name) && strcmp(name,".AppleDouble") && strcasecmp(name,".Parent");
 }                                           
 
 /* ----------------- */
 static int RF_chown_adouble(VFS_FUNC_ARGS_CHOWN)
 {
     struct stat st;
-    char        *ad_p;
+    const char *ad_p;
 
     ad_p = vol->ad_path(path, ADFLAGS_HF );
 
@@ -139,7 +135,7 @@ static int deletecurdir_adouble_loop(struct dirent *de, char *name, void *data _
     /* bail if the file exists in the current directory.
      * note: this will not fail with dangling symlinks */
     
-    if (stat(de->d_name, &st) == 0)
+    if (lstat(de->d_name, &st) == 0)
         return AFPERR_DIRNEMPT;
 
     if ((err = netatalk_unlink(name)))
@@ -173,11 +169,11 @@ static int RF_setfilmode_adouble(VFS_FUNC_ARGS_SETFILEMODE)
 /* ----------------- */
 static int RF_setdirunixmode_adouble(VFS_FUNC_ARGS_SETDIRUNIXMODE)
 {
-    char *adouble = vol->ad_path(name, ADFLAGS_DIR );
+    const char *adouble = vol->ad_path(name, ADFLAGS_DIR );
     int  dropbox = vol->v_flags;
 
     if (dir_rx_set(mode)) {
-        if (stickydirmode(ad_dir(adouble), DIRBITS | mode, dropbox, vol->v_umask) < 0 ) 
+        if (chmod_acl(ad_dir(adouble), (DIRBITS | mode) & ~vol->v_umask) < 0 ) 
             return -1;
     }
 
@@ -185,7 +181,7 @@ static int RF_setdirunixmode_adouble(VFS_FUNC_ARGS_SETDIRUNIXMODE)
         return -1;
 
     if (!dir_rx_set(mode)) {
-        if (stickydirmode(ad_dir(adouble), DIRBITS | mode, dropbox, vol->v_umask) < 0 ) 
+        if (chmod_acl(ad_dir(adouble), (DIRBITS | mode) & ~vol->v_umask) < 0 ) 
             return  -1 ;
     }
     return 0;
@@ -214,65 +210,29 @@ static int RF_setdirmode_adouble(VFS_FUNC_ARGS_SETDIRMODE)
 {
     int   dropbox = vol->v_flags;
     mode_t hf_mode = ad_hf_mode(mode);
-    char  *adouble = vol->ad_path(name, ADFLAGS_DIR );
-    char  *adouble_p = ad_dir(adouble);
+    const char  *adouble = vol->ad_path(name, ADFLAGS_DIR );
+    const char  *adouble_p = ad_dir(adouble);
 
     if (dir_rx_set(mode)) {
-        if (stickydirmode(ad_dir(adouble), DIRBITS | mode, dropbox, vol->v_umask) < 0) 
+        if (chmod_acl(ad_dir(adouble), (DIRBITS | mode) & ~vol->v_umask) < 0) 
             return -1;
     }
 
-    if (for_each_adouble("setdirmode", adouble_p, setdirmode_adouble_loop, &hf_mode, vol_noadouble(vol), vol->v_umask))
+    if (for_each_adouble("setdirmode", adouble_p, setdirmode_adouble_loop, &hf_mode, 0, vol->v_umask))
         return -1;
 
     if (!dir_rx_set(mode)) {
-        if (stickydirmode(ad_dir(adouble), DIRBITS | mode, dropbox, vol->v_umask) < 0) 
+        if (chmod_acl(ad_dir(adouble), (DIRBITS | mode) & ~vol->v_umask) < 0) 
             return  -1 ;
     }
     return 0;
 }
 
-/* ----------------- */
-static int setdirowner_adouble_loop(struct dirent *de _U_, char *name, void *data, int flag _U_, mode_t v_umask _U_)
-{
-    struct perm   *owner  = data;
-
-    if ( chown( name, owner->uid, owner->gid ) < 0 && errno != EPERM ) {
-         LOG(log_debug, logtype_afpd, "setdirowner: chown %d/%d %s: %s",
-                owner->uid, owner->gid, fullpathname(name), strerror(errno) );
-         /* return ( -1 ); Sometimes this is okay */
-    }
-    return 0;
-}
-
 static int RF_setdirowner_adouble(VFS_FUNC_ARGS_SETDIROWNER)
 {
-    int           noadouble = vol_noadouble(vol);
-    char          *adouble_p;
-    struct stat   st;
-    struct perm   owner;
-    
-    owner.uid = uid;
-    owner.gid = gid;
-
-    adouble_p = ad_dir(vol->ad_path(name, ADFLAGS_DIR ));
-
-    if (for_each_adouble("setdirowner", adouble_p, setdirowner_adouble_loop, &owner, noadouble, vol->v_umask)) 
-        return -1;
-
-    /*
-     * We cheat: we know that chown doesn't do anything.
-     */
-    if ( stat( ".AppleDouble", &st ) < 0) {
-        if (errno == ENOENT && noadouble)
-            return 0;
-        LOG(log_error, logtype_afpd, "setdirowner: stat %s: %s", fullpathname(".AppleDouble"), strerror(errno) );
-        return -1;
-    }
-    if ( gid && gid != st.st_gid && chown( ".AppleDouble", uid, gid ) < 0 && errno != EPERM ) {
+    if (lchown(".AppleDouble", uid, gid) < 0 && errno != EPERM ) {
         LOG(log_debug, logtype_afpd, "setdirowner: chown %d/%d %s: %s",
-            uid, gid,fullpathname(".AppleDouble"), strerror(errno) );
-        /* return ( -1 ); Sometimes this is okay */
+            uid, gid,fullpathname(".AppleDouble"), strerror(errno));
     }
     return 0;
 }
@@ -307,8 +267,8 @@ static int RF_renamefile_adouble(VFS_FUNC_ARGS_RENAMEFILE)
              * create .AppleDouble if the file is already opened, so we
              * use a diff one, it's not a pb,ie it's not the same file, yet.
              */
-            ad_init(&ad, vol->v_adouble, vol->v_ad_options); 
-            if (!ad_open(dst, ADFLAGS_HF, O_RDWR | O_CREAT, 0666, &ad)) {
+            ad_init(&ad, vol); 
+            if (ad_open(&ad, dst, ADFLAGS_HF | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) == 0) {
                ad_close(&ad, ADFLAGS_HF);
                if (!unix_rename(dirfd, adsrc, -1, vol->ad_path(dst, 0 )) ) 
                    err = 0;
@@ -374,7 +334,10 @@ static int RF_copyfile_adouble(VFS_FUNC_ARGS_COPYFILE)
         EC_ZERO(bcatcstr(d, name));
     }
 
-    EC_ZERO(copy_file(sfd, cfrombstr(s), cfrombstr(d), 0666));
+    /* ignore errors */
+    if (copy_file(sfd, cfrombstr(s), cfrombstr(d), 0666) != 0)
+        if (errno != ENOENT)
+            EC_FAIL;
 
 EC_CLEANUP:
     bdestroy(s);
@@ -493,412 +456,184 @@ EC_CLEANUP:
 }
 #endif
 
-/*********************************************************************************
- * sfm adouble format
- *********************************************************************************/
-static int ads_chown_loop(struct dirent *de _U_, char *name, void *data, int flag _U_, mode_t v_umask _U_)
-{
-    struct perm   *owner  = data;
-    
-    if (chown( name , owner->uid, owner->gid ) < 0) {
-        return -1;
-    }
-    return 0;
-}
-
-static int RF_chown_ads(VFS_FUNC_ARGS_CHOWN)
-{
-    struct        stat st;
-    char          *ad_p;
-    struct perm   owner;
-    
-    owner.uid = uid;
-    owner.gid = gid;
-
-
-    ad_p = ad_dir(vol->ad_path(path, ADFLAGS_HF ));
-
-    if ( stat( ad_p, &st ) < 0 ) {
-       /* ignore */
-        return 0;
-    }
-    
-    if (chown( ad_p, uid, gid ) < 0) {
-       return -1;
-    }
-    return for_each_adouble("chown_ads", ad_p, ads_chown_loop, &owner, 1, vol->v_umask);
-}
-
-/* --------------------------------- */
-static int deletecurdir_ads1_loop(struct dirent *de _U_, char *name, void *data _U_, int flag _U_, mode_t v_umask _U_)
-{
-    return netatalk_unlink(name);
-}
-
-static int ads_delete_rf(char *name)
-{
-    int err;
-
-    if ((err = for_each_adouble("deletecurdir", name, deletecurdir_ads1_loop, NULL, 1, 0))) 
-        return err;
-    /* FIXME 
-     * it's a problem for a nfs mounted folder, there's .nfsxxx around
-     * for linux the following line solve it.
-     * but it could fail if rm .nfsxxx  create a new .nfsyyy :(
-    */
-    if ((err = for_each_adouble("deletecurdir", name, deletecurdir_ads1_loop, NULL, 1, 0))) 
-        return err;
-    return netatalk_rmdir(-1, name);
-}
-
-static int deletecurdir_ads_loop(struct dirent *de, char *name, void *data _U_, int flag _U_, mode_t v_umask _U_)
+/*************************************************************************
+ * EA adouble format 
+ ************************************************************************/
+static int validupath_ea(VFS_FUNC_ARGS_VALIDUPATH)
 {
-    struct stat st;
-    
-    /* bail if the file exists in the current directory.
-     * note: this will not fail with dangling symlinks */
+    if (name[0] != '.')
+        return 1;
     
-    if (stat(de->d_name, &st) == 0) {
-        return AFPERR_DIRNEMPT;
-    }
-    return ads_delete_rf(name);
-}
-
-static int RF_deletecurdir_ads(VFS_FUNC_ARGS_DELETECURDIR)
-{
-    int err;
-
-    /* delete stray .AppleDouble files. this happens to get .Parent files as well. */
-    if ((err = for_each_adouble("deletecurdir", ".AppleDouble", deletecurdir_ads_loop, NULL, 1, 0))) 
-        return err;
-
-    return netatalk_rmdir(-1, ".AppleDouble" );
-}
-
-/* ------------------- */
-struct set_mode {
-    mode_t mode;
-    struct stat *st;
-};
-
-static int ads_setfilmode_loop(struct dirent *de _U_, char *name, void *data, int flag _U_, mode_t v_umask)
-{
-    struct set_mode *param = data;
-
-    return setfilmode(name, param->mode, param->st, v_umask);
+#ifndef HAVE_EAFD
+    if (name[1] == '_')
+        return ad_valid_header_osx(name);
+#endif
+    return netatalk_name(name);
 }
 
-static int ads_setfilmode(const char * name, mode_t mode, struct stat *st, mode_t v_umask)
+/* ----------------- */
+static int RF_chown_ea(VFS_FUNC_ARGS_CHOWN)
 {
-    mode_t file_mode = ad_hf_mode(mode);
-    mode_t dir_mode = file_mode;
-    struct set_mode param;
-
-    if ((dir_mode & (S_IRUSR | S_IWUSR )))
-        dir_mode |= S_IXUSR;
-    if ((dir_mode & (S_IRGRP | S_IWGRP )))
-        dir_mode |= S_IXGRP;
-    if ((dir_mode & (S_IROTH | S_IWOTH )))
-        dir_mode |= S_IXOTH;
-
-       /* change folder */
-       dir_mode |= DIRBITS;
-    if (dir_rx_set(dir_mode)) {
-        if (chmod_acl( name,  dir_mode ) < 0)
-            return -1;
-    }
-    param.st = st;
-    param.mode = file_mode;
-    if (for_each_adouble("setfilmode_ads", name, ads_setfilmode_loop, &param, 0, v_umask) < 0)
-        return -1;
-
-    if (!dir_rx_set(dir_mode)) {
-        if (chmod_acl( name,  dir_mode ) < 0)
-            return -1;
-    }
-
+#ifndef HAVE_EAFD
+    return chown(vol->ad_path(path, ADFLAGS_HF ), uid, gid);
+#endif
     return 0;
 }
 
-static int RF_setfilmode_ads(VFS_FUNC_ARGS_SETFILEMODE)
+/* ---------------- */
+static int RF_renamedir_ea(VFS_FUNC_ARGS_RENAMEDIR)
 {
-    return ads_setfilmode(ad_dir(vol->ad_path(name, ADFLAGS_HF )), mode, st, vol->v_umask);
+    return 0;
 }
 
-/* ------------------- */
-static int RF_setdirunixmode_ads(VFS_FUNC_ARGS_SETDIRUNIXMODE)
+/* Returns 1 if the entry is NOT an ._ file */
+static int deletecurdir_ea_osx_chkifempty_loop(struct dirent *de, char *name, void *data _U_, int flag _U_, mode_t v_umask _U_)
 {
-    char *adouble = vol->ad_path(name, ADFLAGS_DIR );
-    char   ad_p[ MAXPATHLEN + 1];
-    int dropbox = vol->v_flags;
-
-    strlcpy(ad_p,ad_dir(adouble), MAXPATHLEN + 1);
-
-    if (dir_rx_set(mode)) {
-
-        /* .AppleDouble */
-        if (stickydirmode(ad_dir(ad_p), DIRBITS | mode, dropbox, vol->v_umask) < 0) 
-            return -1;
-
-        /* .AppleDouble/.Parent */
-        if (stickydirmode(ad_p, DIRBITS | mode, dropbox, vol->v_umask) < 0) 
-            return -1;
-    }
-
-    if (ads_setfilmode(ad_dir(vol->ad_path(name, ADFLAGS_DIR)), mode, st, vol->v_umask) < 0)
-        return -1;
+    if (de->d_name[0] != '.' || de->d_name[0] == '_')
+        return 1;
 
-    if (!dir_rx_set(mode)) {
-        if (stickydirmode(ad_p, DIRBITS | mode, dropbox, vol->v_umask) < 0) 
-            return  -1 ;
-        if (stickydirmode(ad_dir(ad_p), DIRBITS | mode, dropbox, vol->v_umask) < 0) 
-            return -1;
-    }
     return 0;
 }
 
-/* ------------------- */
-struct dir_mode {
-    mode_t mode;
-    int    dropbox;
-};
-
-static int setdirmode_ads_loop(struct dirent *de _U_, char *name, void *data, int flag, mode_t v_umask)
+static int deletecurdir_ea_osx_loop(struct dirent *de, char *name, void *data _U_, int flag _U_, mode_t v_umask _U_)
 {
-
-    struct dir_mode *param = data;
-    int    ret = 0; /* 0 ignore error, -1 */
-
-    if (dir_rx_set(param->mode)) {
-        if (stickydirmode(name, DIRBITS | param->mode, param->dropbox, v_umask) < 0) {
-            if (flag) {
-                return 0;
-            }
-            return ret;
-        }
-    }
-    if (ads_setfilmode(name, param->mode, NULL, v_umask) < 0)
+    int ret;
+    
+    if ((ret = netatalk_unlink(name)) != 0)
         return ret;
 
-    if (!dir_rx_set(param->mode)) {
-        if (stickydirmode(name, DIRBITS | param->mode, param->dropbox, v_umask) < 0) {
-            if (flag) {
-                return 0;
-            }
-            return ret;
-        }
-    }
     return 0;
 }
 
-static int RF_setdirmode_ads(VFS_FUNC_ARGS_SETDIRMODE)
+/* ---------------- */
+static int RF_deletecurdir_ea(VFS_FUNC_ARGS_DELETECURDIR)
 {
-    char *adouble = vol->ad_path(name, ADFLAGS_DIR );
-    char   ad_p[ MAXPATHLEN + 1];
-    struct dir_mode param;
-
-    param.mode = mode;
-    param.dropbox = vol->v_flags;
-
-    strlcpy(ad_p,ad_dir(adouble), sizeof(ad_p));
-
-    if (dir_rx_set(mode)) {
-        /* .AppleDouble */
-        if (stickydirmode(ad_dir(ad_p), DIRBITS | mode, param.dropbox, vol->v_umask) < 0) 
-            return -1;
+#ifndef HAVE_EAFD
+    int err;
+    /* delete stray ._AppleDouble files */
+
+    /* first check if there's really no other file besides files starting with ._ */
+    if ((err = for_each_adouble("deletecurdir_ea_osx", ".",
+                                deletecurdir_ea_osx_chkifempty_loop,
+                                NULL, 0, 0)) != 0) {
+        if (err == 1)
+            return AFPERR_DIRNEMPT;
+        return AFPERR_MISC;
     }
 
-    if (for_each_adouble("setdirmode_ads", ad_dir(ad_p), setdirmode_ads_loop, &param, vol_noadouble(vol), vol->v_umask))
-        return -1;
+    /* Now delete orphaned ._ files */
+    if ((err = for_each_adouble("deletecurdir_ea_osx", ".",
+                                deletecurdir_ea_osx_loop,
+                                NULL, 0, 0)) != 0)
+        return err;
 
-    if (!dir_rx_set(mode)) {
-        if (stickydirmode(ad_dir(ad_p), DIRBITS | mode, param.dropbox, vol->v_umask) < 0 ) 
-            return -1;
-    }
+#endif
     return 0;
 }
 
-/* ------------------- */
-static int setdirowner_ads1_loop(struct dirent *de _U_, char *name, void *data, int flag _U_, mode_t v_umask _U_)
+/* ---------------- */
+static int RF_setdirunixmode_ea(VFS_FUNC_ARGS_SETDIRUNIXMODE)
 {
-    struct perm   *owner  = data;
-
-    if ( chown( name, owner->uid, owner->gid ) < 0 && errno != EPERM ) {
-         LOG(log_debug, logtype_afpd, "setdirowner: chown %d/%d %s: %s",
-                owner->uid, owner->gid, fullpathname(name), strerror(errno) );
-         /* return ( -1 ); Sometimes this is okay */
-    }
+#ifndef HAVE_EAFD
+#endif
     return 0;
 }
 
-static int setdirowner_ads_loop(struct dirent *de _U_, char *name, void *data, int flag, mode_t v_umask _U_)
+static int RF_setfilmode_ea(VFS_FUNC_ARGS_SETFILEMODE)
 {
-    struct perm   *owner  = data;
-
-    if (for_each_adouble("setdirowner", name, setdirowner_ads1_loop, data, flag, 0) < 0)
-        return -1;
-
-    if ( chown( name, owner->uid, owner->gid ) < 0 && errno != EPERM ) {
-         LOG(log_debug, logtype_afpd, "setdirowner: chown %d/%d %s: %s",
-                owner->uid, owner->gid, fullpathname(name), strerror(errno) );
-         /* return ( -1 ); Sometimes this is okay */
-    }
+#ifndef HAVE_EAFD
+    return adouble_setfilmode(vol->ad_path(name, ADFLAGS_HF ), mode, st, vol->v_umask);
+#endif
     return 0;
 }
 
-static int RF_setdirowner_ads(VFS_FUNC_ARGS_SETDIROWNER)
+/* ---------------- */
+static int RF_setdirmode_ea(VFS_FUNC_ARGS_SETDIRMODE)
 {
-    int           noadouble = vol_noadouble(vol);
-    char          adouble_p[ MAXPATHLEN + 1];
-    struct stat   st;
-    struct perm   owner;
-    
-    owner.uid = uid;
-    owner.gid = gid;
-
-    strlcpy(adouble_p, ad_dir(vol->ad_path(name, ADFLAGS_DIR )), sizeof(adouble_p));
-
-    if (for_each_adouble("setdirowner", ad_dir(adouble_p), setdirowner_ads_loop, &owner, noadouble, 0)) 
-        return -1;
-
-    /*
-     * We cheat: we know that chown doesn't do anything.
-     */
-    if ( stat( ".AppleDouble", &st ) < 0) {
-        if (errno == ENOENT && noadouble)
-            return 0;
-        LOG(log_error, logtype_afpd, "setdirowner: stat %s: %s", fullpathname(".AppleDouble"), strerror(errno) );
-        return -1;
-    }
-    if ( gid && gid != st.st_gid && chown( ".AppleDouble", uid, gid ) < 0 && errno != EPERM ) {
-        LOG(log_debug, logtype_afpd, "setdirowner: chown %d/%d %s: %s",
-            uid, gid,fullpathname(".AppleDouble"), strerror(errno) );
-        /* return ( -1 ); Sometimes this is okay */
-    }
+#ifndef HAVE_EAFD
+#endif
     return 0;
 }
 
-/* ------------------- */
-static int RF_deletefile_ads(VFS_FUNC_ARGS_DELETEFILE)
-{
-    int ret = 0;
-    int cwd = -1;
-    char *ad_p;
-
-    ad_p = ad_dir(vol->ad_path(file, ADFLAGS_HF ));
-
-    if (dirfd != -1) {
-        if (((cwd = open(".", O_RDONLY)) == -1) || (fchdir(dirfd) != 0)) {
-            ret = AFPERR_MISC;
-            goto exit;
-        }
-    }
-
-    ret = ads_delete_rf(ad_p);
-
-    if (dirfd != -1 && fchdir(cwd) != 0) {
-        LOG(log_error, logtype_afpd, "RF_deletefile_ads: cant chdir back. exit!");
-        exit(EXITERR_SYS);
-    }
-
-exit:
-    if (cwd != -1)
-        close(cwd);
-
-    return ret;
-}
-
-/* --------------------------- */
-static int RF_renamefile_ads(VFS_FUNC_ARGS_RENAMEFILE)
+/* ---------------- */
+static int RF_setdirowner_ea(VFS_FUNC_ARGS_SETDIROWNER)
 {
-    char  adsrc[ MAXPATHLEN + 1];
-    int   err = 0;
-
-    strcpy( adsrc, ad_dir(vol->ad_path(src, 0 )));
-    if (unix_rename(dirfd, adsrc, -1, ad_dir(vol->ad_path(dst, 0 ))) < 0) {
-        struct stat st;
-
-        err = errno;
-        if (errno == ENOENT) {
-               struct adouble    ad;
-
-            if (lstatat(dirfd, adsrc, &st)) /* source has no ressource fork, */
-                return 0;
-            
-            /* We are here  because :
-             * -there's no dest folder. 
-             * -there's no .AppleDouble in the dest folder.
-             * if we use the struct adouble passed in parameter it will not
-             * create .AppleDouble if the file is already opened, so we
-             * use a diff one, it's not a pb,ie it's not the same file, yet.
-             */
-            ad_init(&ad, vol->v_adouble, vol->v_ad_options); 
-            if (!ad_open(dst, ADFLAGS_HF, O_RDWR | O_CREAT, 0666, &ad)) {
-               ad_close(&ad, ADFLAGS_HF);
-
-               /* We must delete it */
-               RF_deletefile_ads(vol, -1, dst );
-               if (!unix_rename(dirfd, adsrc, -1, ad_dir(vol->ad_path(dst, 0 ))) ) 
-                   err = 0;
-                else 
-                   err = errno;
-            }
-            else { /* it's something else, bail out */
-                   err = errno;
-               }
-           }
-       }
-       if (err) {
-               errno = err;
-               return -1;
-       }
+#ifndef HAVE_EAFD
+#endif
        return 0;
 }
 
-/*************************************************************************
- * osx adouble format 
- ************************************************************************/
-static int validupath_osx(VFS_FUNC_ARGS_VALIDUPATH)
-{
-    return strncmp(name,"._", 2) && (
-      (vol->v_flags & AFPVOL_USEDOTS) ? netatalk_name(name): name[0] != '.');
-}             
-
-/* ---------------- */
-static int RF_renamedir_osx(VFS_FUNC_ARGS_RENAMEDIR)
+static int RF_deletefile_ea(VFS_FUNC_ARGS_DELETEFILE)
 {
-    /* We simply move the corresponding ad file as well */
-    char   tempbuf[258]="._";
-    return unix_rename(dirfd, vol->ad_path(oldpath,0), -1, strcat(tempbuf,newpath));
+#ifndef HAVE_EAFD
+       return netatalk_unlinkat(dirfd, vol->ad_path(file, ADFLAGS_HF));
+#endif
+    return 0;
 }
-
-/* ---------------- */
-static int RF_deletecurdir_osx(VFS_FUNC_ARGS_DELETECURDIR)
+static int RF_copyfile_ea(VFS_FUNC_ARGS_COPYFILE)
 {
-    return netatalk_unlink( vol->ad_path(".",0) );
-}
+#ifdef HAVE_EAFD
+    /* the EA VFS module does this all for us */
+    return 0;
+#endif
 
-/* ---------------- */
-static int RF_setdirunixmode_osx(VFS_FUNC_ARGS_SETDIRUNIXMODE)
-{
-    return adouble_setfilmode(vol->ad_path(name, ADFLAGS_DIR ), mode, st, vol->v_umask);
-}
+    EC_INIT;
+    bstring s = NULL, d = NULL;
+    char *dup1 = NULL;
+    char *dup2 = NULL;
+    char *dup3 = NULL;
+    char *dup4 = NULL;
+    const char *name = NULL;
+    const char *dir = NULL;
 
-/* ---------------- */
-static int RF_setdirmode_osx(VFS_FUNC_ARGS_SETDIRMODE)
-{
-    return 0;
-}
+    /* get basename */
+
+    /* build src path to ._ file*/
+    EC_NULL(dup1 = strdup(src));
+    EC_NULL(name = basename(strdup(dup1)));
+
+    EC_NULL(dup2 = strdup(src));
+    EC_NULL(dir = dirname(dup2));
+    EC_NULL(s = bfromcstr(dir));
+    EC_ZERO(bcatcstr(s, "/._"));
+    EC_ZERO(bcatcstr(s, name));
+
+    /* build dst path to ._file*/
+    EC_NULL(dup4 = strdup(dst));
+    EC_NULL(name = basename(strdup(dup4)));
+
+    EC_NULL(dup3 = strdup(dst));
+    EC_NULL(dir = dirname(dup3));
+    EC_NULL(d = bfromcstr(dir));
+    EC_ZERO(bcatcstr(d, "/._"));
+    EC_ZERO(bcatcstr(d, name));
+
+    if (copy_file(sfd, cfrombstr(s), cfrombstr(d), 0666) != 0) {
+        switch (errno) {
+        case ENOENT:
+            break;
+        default:
+            LOG(log_error, logtype_afpd, "[VFS] copyfile(\"%s\" -> \"%s\"): %s",
+                cfrombstr(s), cfrombstr(d), strerror(errno));
+            EC_FAIL;
+                    
+        }
+    }
 
-/* ---------------- */
-static int RF_setdirowner_osx(VFS_FUNC_ARGS_SETDIROWNER)
-{
-       return 0;
+EC_CLEANUP:
+    bdestroy(s);
+    bdestroy(d);
+    free(dup1);
+    free(dup2);
+    free(dup3);
+    free(dup4);
+    EC_EXIT;
 }
 
 /* ---------------- */
-static int RF_renamefile_osx(VFS_FUNC_ARGS_RENAMEFILE)
+static int RF_renamefile_ea(VFS_FUNC_ARGS_RENAMEFILE)
 {
+#ifndef HAVE_EAFD
     char  adsrc[ MAXPATHLEN + 1];
     int   err = 0;
 
@@ -914,6 +649,8 @@ static int RF_renamefile_osx(VFS_FUNC_ARGS_RENAMEFILE)
         return -1;
     }
     return 0;
+#endif
+    return 0;
 }
 
 /********************************************************************************************
@@ -1003,10 +740,10 @@ static struct vfs_ops vfs_master_funcs = {
 };
 
 /* 
- * Primary adouble modules: default, osx, sfm
+ * Primary adouble modules: v2, ea
  */
 
-static struct vfs_ops netatalk_adouble = {
+static struct vfs_ops netatalk_adouble_v2 = {
     /* vfs_validupath:    */ validupath_adouble,
     /* vfs_chown:         */ RF_chown_adouble,
     /* vfs_renamedir:     */ RF_renamedir_adouble,
@@ -1021,34 +758,18 @@ static struct vfs_ops netatalk_adouble = {
     NULL
 };
 
-static struct vfs_ops netatalk_adouble_osx = {
-    /* vfs_validupath:    */ validupath_osx,
-    /* vfs_chown:         */ RF_chown_adouble,
-    /* vfs_renamedir:     */ RF_renamedir_osx,
-    /* vfs_deletecurdir:  */ RF_deletecurdir_osx,
-    /* vfs_setfilmode:    */ RF_setfilmode_adouble,
-    /* vfs_setdirmode:    */ RF_setdirmode_osx,
-    /* vfs_setdirunixmode:*/ RF_setdirunixmode_osx,
-    /* vfs_setdirowner:   */ RF_setdirowner_osx,
-    /* vfs_deletefile:    */ RF_deletefile_adouble,
-    /* vfs_renamefile:    */ RF_renamefile_osx,
-    /* vfs_copyfile:      */ NULL,
-    NULL
-};
-
-/* samba sfm format. ad_path shouldn't be set her */
-static struct vfs_ops netatalk_adouble_sfm = {
-    /* vfs_validupath:    */ validupath_adouble,
-    /* vfs_chown:         */ RF_chown_ads,
-    /* vfs_renamedir:     */ RF_renamedir_adouble,
-    /* vfs_deletecurdir:  */ RF_deletecurdir_ads,
-    /* vfs_setfilmode:    */ RF_setfilmode_ads,
-    /* vfs_setdirmode:    */ RF_setdirmode_ads,
-    /* vfs_setdirunixmode:*/ RF_setdirunixmode_ads,
-    /* vfs_setdirowner:   */ RF_setdirowner_ads,
-    /* vfs_deletefile:    */ RF_deletefile_ads,
-    /* vfs_renamefile:    */ RF_renamefile_ads,
-    /* vfs_copyfile:      */ NULL,
+static struct vfs_ops netatalk_adouble_ea = {
+    /* vfs_validupath:    */ validupath_ea,
+    /* vfs_chown:         */ RF_chown_ea,
+    /* vfs_renamedir:     */ RF_renamedir_ea,
+    /* vfs_deletecurdir:  */ RF_deletecurdir_ea,
+    /* vfs_setfilmode:    */ RF_setfilmode_ea,
+    /* vfs_setdirmode:    */ RF_setdirmode_ea,
+    /* vfs_setdirunixmode:*/ RF_setdirunixmode_ea,
+    /* vfs_setdirowner:   */ RF_setdirowner_ea,
+    /* vfs_deletefile:    */ RF_deletefile_ea,
+    /* vfs_renamefile:    */ RF_renamefile_ea,
+    /* vfs_copyfile:      */ RF_copyfile_ea,
     NULL
 };
 
@@ -1150,17 +871,16 @@ void initvol_vfs(struct vol *vol)
     vol->vfs = &vfs_master_funcs;
 
     /* Default adouble stuff */
-    if (vol->v_adouble == AD_VERSION2_OSX) {
-        vol->vfs_modules[0] = &netatalk_adouble_osx;
-        vol->ad_path = ad_path_osx;
-    }
-    else if (vol->v_adouble == AD_VERSION1_SFM) {
-        vol->vfs_modules[0] = &netatalk_adouble_sfm;
-        vol->ad_path = ad_path_sfm;
-    }
-    else {
-        vol->vfs_modules[0] = &netatalk_adouble;
+    if (vol->v_adouble == AD_VERSION2) {
+        vol->vfs_modules[0] = &netatalk_adouble_v2;
         vol->ad_path = ad_path;
+    } else {
+        vol->vfs_modules[0] = &netatalk_adouble_ea;
+#ifdef HAVE_EAFD
+        vol->ad_path = ad_path_ea;
+#else
+        vol->ad_path = ad_path_osx;
+#endif
     }
 
     /* Extended Attributes */
diff --git a/libevent/.gitignore b/libevent/.gitignore
new file mode 100644 (file)
index 0000000..2dca840
--- /dev/null
@@ -0,0 +1,95 @@
+### These files should get ignored no matter where they appear.
+
+# Editors leave these lying around
+\#*\#
+.#*
+*~
+*.swp
+
+# C stuff
+*.o
+
+# Windows stuff
+*.obj
+*.exe
+*.lib
+
+# Patch leaves these lying arround
+*.orig
+*.rej
+
+# gcov stuff
+*.gcno
+*.gcov
+*.gcda
+
+# Autotools stuff
+.deps
+Makefile
+Makefile.in
+
+# Libtool stuff
+.libs
+*.lo
+*.la
+
+# ctags stuff
+TAGS
+
+# Stuff made by our makefiles
+libevent.pc
+libevent_pthreads.pc
+libevent_openssl.pc
+
+## The initial / makes these files only get ignored in particular directories.
+/autom4te.cache
+
+# Libtool adds these, at least sometimes
+/m4/libtool.m4
+/m4/ltoptions.m4
+/m4/ltsugar.m4
+/m4/ltversion.m4
+/m4/lt~obsolete.m4
+
+/aclocal.m4
+/compile
+/doxygen
+/config.guess
+/config.log
+/config.status
+/config.sub
+/configure
+/depcomp
+/config.h
+/config.h.in
+/install-sh
+/libtool
+/ltmain.sh
+/missing
+/stamp-h1
+
+/include/event2/event-config.h
+
+/sample/dns-example
+/sample/event-test
+/sample/hello-world
+/sample/http-server
+/sample/le-proxy
+/sample/signal-test
+/sample/time-test
+
+/test/bench
+/test/bench_cascade
+/test/bench_http
+/test/bench_httpclient
+/test/regress
+/test/regress.gen.c
+/test/regress.gen.h
+/test/rpcgen-attempted
+/test/test-eof
+/test/test-init
+/test/test-ratelim
+/test/test-time
+/test/test-weof
+/test/test-changelist
+
diff --git a/libevent/ChangeLog b/libevent/ChangeLog
new file mode 100644 (file)
index 0000000..f09e724
--- /dev/null
@@ -0,0 +1,1245 @@
+Changes in version 2.0.18-stable (22 Mar 2012)
+BUGFIXES (core):
+ o Make uses of open() close-on-exec safe by introducing an internal evutil_open_closeonexec. (d2b5f72 Ross Lagerwall, 03dce42)
+
+BUGFIXES (kqueue):
+ o Properly zero the kevent in kq_setup_kevent() (c2c7b39 Sebastian Hahn)
+
+BUILD FIXES:
+ o Added OPENSSL_LDFLAGS env variable which is appended to SSL checks. (9278196 Mark Ellzey)
+ o Changed OPENSSL_LDFLAGS to OPENSSL_LIBADD (2d67b63 Mark Ellzey)
+ o Don't do clang version detection when disabling some flags (083296b Sebastian Hahn)
+
+BUGFIXES (dns):
+ o Stop crashing in evdns when nameserver probes give a weird error (bec5068)
+
+
+Changes in version 2.0.17-stable (10 Feb 2012)
+
+BUGFIXES (core):
+ o Be absolutely sure to clear pncalls before leaving event_signal_closure (11f36a5)
+ o check for sysctl before we use it (358c745 Mike Frysinger)
+ o Remove bogus casts of socket to int before calling ev_callback (f032516)
+ o Make evconnlistener work around bug in older Linux when getting nmapped (ecfc720)
+ o Fix a list corruption bug when using event_reinit() with signals present (6e41cdc)
+ o Fix a fd leak in event_reinit() (3f18ad1)
+ o Do a memberwise comparison of threading function tables (c94a5f2 Nate R)
+ o Use C-style comments in C source files (for compatibility with compilers such as xlc on AIX). (d84d917 Greg Hewgill)
+ o Avoid crash when freeing event_iocp and using event_set_mem_functions (19715a6
+ o In the kqueue backend, do not report EBADF as an EV_READ (5d7bfa1 Nicholas Marriott)
+
+BUGFIXES (evbuffer and bufferevents):
+ o Fix behavior of evbuffer_peek(buf,-1,NULL,NULL,0) (c986f23 Zack Weinberg)
+ o Loop on filtering SSL reads until we are blocked or exhausted. (5b4b812)
+
+BUGFIXES (evhttp):
+ o Force strict validation of HTTP version in response. (790f6b3 Catalin Patulea)
+
+BUGFIXES (evdns):
+ o evdns: fix a bug in circular-queue implementation (d6094b1)
+
+BUILD FIXES:
+ o Fix a silly compilation error with the sun compiler (1927776 Colin Watt)
+ o Suppress a gcc warning from ignoring fwrite return in http-sample.c (7206e8c)
+
+DOCUMENTATION FIXES:
+ o Slightly clarify evbuffer_peek documentation (7bbf6ca)
+ o Update copyright notices to 2012 (e49e289)
+
+NEW APIS:
+ o Backport evhttp_connection_get_bufferevent to Libevent 2.0 (da70fa7 Arno Bakker)
+
+TESTS AND TEST FIXES:
+ o Fix a race condition in the dns/bufferevent_connect_hostname test. (cba48c7)
+ o Add function to check referential integrity of an event_base (27737d5)
+ o Check event_base correctness at end of each unit test (3312b02)
+ o Workaround in the unit tests for an apparent epoll bug in Linux 3.2 (dab9187)
+ o Better workaround for Linux 3.2 edge-triggered epoll bug (9f9e259)
+
+Changes in version 2.0.16-stable (18 Nov 2011)
+BUGFIXES (core):
+ o More detailed message in case of libevent self-debugging failure. (9e6a4ef Leonid Evdokimov)
+ o epoll: close fd on alloc fail at initialization (1aee718 Jamie Iles)
+ o Fix compile warning from saying event2/*.h inside a comment (447b0ba)
+ o Warn when unable to construct base because of failing make_base_notifiable (4e797f3)
+ o Don't try to make notifiable event_base when no threading fns are configured (e787413)
+
+BUGFIXES (evbuffer):
+ o unit test for remove_buffer bug (90bd620 Greg Hazel)
+ o Fix an evbuffer crash in evbuffer_remove_buffer() (c37069c)
+
+BUGFIXES (bufferevent_openssl):
+ o Refactor amount-to-read calculations in buffervent_ssl consider_reading() (a186e73 Mark Ellzey)
+ o Move SSL rate-limit enforcement into bytes_to_read() (96c562f)
+ o Avoid spinning on OpenSSL reads (2aa036f Mark Ellzey)
+
+BUGFIXES (dns)
+ o Empty DNS reply with OK status is another way to say NODATA. (21a08d6 Leonid Evdokimov)
+
+TESTING:
+ o Tests for 94fba5b and f72e8f6 (d58c15e Leonid Evdokimov)
+ o Test for commit aff6ba1 (f7841bf Leonid Evdokimov)
+ o Style and comment tweaks for dns/leak* tests (5e42202)
+ o improve test to remove at least one buffer from src (7eb52eb Greg Hazel)
+
+DOCUMENTATION:
+ o Add note about evhttp_send_reply_end to its doxygen (724bfb5)
+ o Update copyright dates to 2011. (3c824bd)
+ o Fix typo in whatsnew-2.0.txt (674bc6a Mansour Moufid)
+ o Improve win32 behavior of dns-sample.c code (a3f320e Gisle Vanem)
+
+
+
+Changes in version 2.0.15-stable (12 Oct 2011)
+BUGFIXES (DNS):
+ o DNS: add ttl for negative answers using RFC 2308 idea. (f72e8f6 Leonid Evdokimov)
+ o Add DNS_ERR_NODATA error code to handle empty replies. (94fba5b Leonid Evdokimov)
+
+BUFGIXES (bufferevents and evbuffers):
+ o Make evbuffer callbacks get the right n_added value after evbuffer_add (1ef1f68 Alex)
+ o Prefer mmap to sendfile unless a DRAINS_TO_FD flag is set. Allows add_file to work with SSL. (0ba0af9)
+
+BUGFIXES (event loop):
+ o When a signal callback is activated to run multiple times, allow event_base_loopbreak to work even before they all have run. (4e8eb6a)
+
+DOCUMENTATION FIXES:
+ o Fix docstring in dns.h (2b6eae5 Leonid Evdokimov)
+ o refer to non-deprecated evdns functions in comments (ba5c27d Greg Hazel)
+
+BUILD AND TESTING FIXES:
+ o le-proxy and regress depend on openssl directly (9ae061a Sergey Avseyev)
+ o Use _SOURCES, not _sources, in sample/Makefile.am (7f82382)
+ o Fixed compiler warnings for unchecked read/write calls. (c3b62fd Mark Ellzey)
+ o Make write-checking fixes use tt_fail_perror (2b76847)
+ o Fix some "value never used" warnings with gcc 4.6.1 (39c0cf7)
+
+
+
+Changes in version 2.0.14-stable (31 Aug 2011)
+BUGFIXES (bufferevents and evbuffers):
+ o Propagate errors on the underlying bufferevent to the user. (4a34394 Joachim Bauch)
+ o Ignore OpenSSL deprecation warnings on OS X (5d1b255 Sebastian Hahn)
+ o Fix handling of group rate limits under 64 bytes of burst (6d5440e)
+ o Solaris sendfile: correctly detect amount of data sent (643922e Michael Herf)
+ o Make rate limiting work with common_timeout logic (5b18f13)
+ o clear read watermark on underlying bufferevent when creating filtering bev to fix potentially failing fragmented ssl handshakes (54f7e61 Joachim Bauch)
+
+BUGFIXES (IOCP):
+ o IOCP: don't launch reads or writes on an unconnected socket (495c227)
+ o Make IOCP rate-limiting group support stricter and less surprising. (a98da7b)
+ o Have test-ratelim.c support IOCP (0ff2c5a)
+ o Make overlapped reads result in evbuffer callbacks getting invoked (6acfbdd)
+ o Correctly terminate IO on an async bufferevent on bufferevent_free (e6af35d)
+
+BUGFIXES (other):
+ o Fix evsig_dealloc memory leak with debugging turned on. (9b724b2 Leonid Evdokimov)
+ o Fix request_finished memory leak with debugging turned on. (aff6ba1 Leonid Evdokimov)
+
+BUILD AND TESTING FIXES:
+ o Allow OS-neutral builds for platforms where some versions have arc4random_buf (b442302 Mitchell Livingston)
+ o Try to fix 'make distcheck' errors when building out-of-tree (04656ea Dave Hart)
+ o Clean up some problems identified by Coverity. (7c11e51 Harlan Stenn)
+
+
+Changes in version 2.0.13-stable (18 Jul 2011)
+BUGFIXES
+ o Avoid race-condition when initializing global locks (b683cae)
+ o Fix bug in SSL bufferevents backed by a bev with a write high-watermarks (e050703 Joachim Bauch)
+ o Speed up invoke_callbacks on evbuffers when there are no callbacks (f87f568 Mark Ellzey)
+ o Avoid a segfault when all methods are disabled or broken (27ce38b)
+ o Fix incorrect results from evbuffer_search_eol(EOL_LF) (4461f1a)
+ o Add some missing checks for mm_calloc failures (89d5e09)
+ o Replace an assertion for event_base_free(NULL) with a check-and-warn (09fe97d)
+ o Report kqueue ebadf, epipe, and eperm as EV_READ events (1fd34ab)
+ o Check if the `evhttp_new_object' function in `http.c' returns NULL. (446cc7a Mansour Moufid)
+ o Use the correct printf args when formatting size_t (3203f88)
+ o Complain if the caller tries to change threading cbs after setting them (cb6ecee)
+
+DOCUMENTATION FIXES AND IMPROVEMENTS
+ o Revise the event/evbuffer/bufferevent doxygen for clarity and accuracy (2888fac)
+ o Update Doxyfile to produce more useful output (aea0555)
+
+TEST FIXES
+ o Fix up test_evutil_snprintf (caf695a)
+ o Fix tinytest invocation from windows shell (57def34 Ed Day)
+
+BUILD FIXES
+ o Use AM_CPPFLAGS in sample/Makefile.am, not AM_CFLAGS (4a5c82d)
+ o Fix select.c compilation on systems with no NFDBITS (49d1136)
+ o Fix a few warnings on OpenBSD (8ee9f9c Nicholas Marriott)
+ o Don't break when building tests from git without python installed (b031adf)
+ o Don't install event_rpcgen.py when --disable-libevent-install is used (e23cda3 Harlan Stenn)
+ o Fix AIX build issue with TAILQ_FOREACH definition (e934096)
+
+
+Changes in version 2.0.12-stable (4 Jun 2011)
+BUGFIXES
+ o Fix a warn-and-fail bug in kqueue by providing kevent() room to report errors (28317a0)
+ o Fix an assert-inducing fencepost bug in the select backend (d90149d)
+ o Fix failing http assertion introducd in commit 0d6622e (0848814 Kevin Ko)
+ o Fix a bug that prevented us from configuring IPv6 nameservers. (74760f1)
+ o Prevent size_t overflow in evhttp_htmlescape. (06c51cd Mansour Moufid)
+ o Added several checks for under/overflow conditions in evhttp_handle_chunked_read (a279272 Mark Ellzey)
+ o Added overflow checks in evhttp_read_body and evhttp_get_body (84560fc Mark Ellzey)
+
+DOCUMENTATION:
+ o Add missing words to EVLOOP_NONBLOCK documentation (9556a7d)
+
+BUILD FIXES
+ o libssl depends on libcrypto, not the other way around. (274dd03 Peter Rosin)
+ o Libtool brings in the dependencies of libevent_openssl.la automatically (7b819f2 Peter Rosin)
+ o Use OPENSSL_LIBS in Makefile.am (292092e Sebastian Hahn)
+ o Move the win32 detection in configure.in (ceb03b9 Sebastian Hahn)
+ o Correctly detect openssl on windows (6619385 Sebastian Hahn)
+ o Fix a compile warning with zlib 1.2.4 and 1.2.5 (5786b91 Sebastian Hahn)
+ o Fix compilation with GCC 2, which had no __builtin_expect (09d39a1 Dave Hart)
+ o Fix new warnings from GCC 4.6 (06a714f)
+ o Link with -lshell32 and -ladvapi32 on Win32. (86090ee Peter Rosin)
+ o Make the tests build when OpenSSL is not available. (07c41be Peter Rosin)
+ o Bring in the compile script from automake, if needed. (f3c7a4c Peter Rosin)
+ o MSVC does not provide S_ISDIR, so provide it manually. (70be7d1 Peter Rosin)
+ o unistd.h and sys/time.h might not exist. (fe93022 Peter Rosin)
+ o Make sure TINYTEST_LOCAL is defined when building tinytest.c (8fa030c Peter Rosin)
+ o Fix winsock2.h #include issues with MSVC (3d768dc Peter Rosin)
+ o Use evutil_gettimeofday instead of relying on the system gettimeofday. (0de87fe Peter Rosin)
+ o Always use evutil_snprintf, even if OS provides it (d1b2d11 Sebastian Hahn)
+ o InitializeCriticalSectionAndSpinCount requires _WIN32_WINNT >= 0x0403. (816115a Peter Rosin)
+ o cygwin: make it possible to build DLLs (d54d3fc)
+
+
+
+Changes in version 2.0.11-stable (27 Apr 2011)
+  [Autogenerated from the Git log, sorted and cleaned by hand.]
+BUGFIXES:
+ o Fix evport handling of POLLHUP and POLLERR (b42ce4b)
+ o Fix compilation on Windows with NDEBUG (cb8059d)
+ o Check for POLLERR, POLLHUP and POLLNVAL for Solaris event ports (0144886 Trond Norbye)
+ o Detect and handle more allocation failures. (666b096 Jardel Weyrich)
+ o Use event_err() only if the failure is truly unrecoverable. (3f8d22a Jardel Weyrich)
+ o Handle resize failures in the select backend better. (83e805a)
+ o Correctly free selectop fields when select_resize fails in select_init (0c0ec0b)
+ o Make --enable-gcc-warnings a no-op if not using gcc (3267703)
+ o Fix a type error in our (unused) arc4random_stir() (f736198)
+ o Correctly detect and stop non-chunked http requests when the body is too long (63a715e)
+ o Have event_base_gettimeofday_cached() always return wall-clock time (a459ef7)
+ o Workaround for http crash bug 3078187 (5dc5662 Tomash Brechko)
+ o Fix incorrect assertions and possible use-after-free in evrpc_free() (4b8f02f Christophe Fillot)
+ o Reset outgoing http connection when read data in idle state. (272823f Tomash Brechko)
+ o Fix subtle recursion in evhttp_connection_cb_cleanup(). (218cf19 Tomash Brechko)
+ o Fix the case when failed evhttp_make_request() leaved request in the queue. (0d6622e Tomash Brechko)
+ o Fix a crash bug in evdns server circular list code (00e91b3)
+ o Handle calloc failure in evdns. (Found by Dave Hart) (364291e)
+ o Fix a memory leak on win32 socket->event map. (b4f89f0)
+ o Add a forgotten NULL check to evhttp_parse_headers (12311ff Sebastian Hahn)
+ o Fix possible NULL-deref in evdns_cancel_request (5208544 Sebastian Hahn)
+
+PORTABILITY:
+ o Fall back to sscanf if we have no other way to implement strtoll (453317b)
+ o Build correctly on platforms without sockaddr_storage (9184563)
+ o Try to build correctly on platforms with no IPv6 support (713c254)
+ o Build on systems without AI_PASSIVE (cb92113)
+ o Fix http unit test on non-windows platforms without getaddrinfo (6092f12)
+ o Do not check for gethostbyname_r versions if we have getaddrinfo (c1260b0)
+ o Include arpa/inet.h as needed on HPUX (10c834c Harlan Stenn)
+ o Include util-internal.h as needed to build on platforms with no sockaddr_storage (bbf5515 Harlan Stenn)
+ o Check for getservbyname even if not on win32. (af08a94 Harlan Stenn)
+ o Add -D_OSF_SOURCE to fix hpux builds (0b33479 Harlan Stenn)
+ o Check for allocation failures in apply_socktype_protocol_hack (637d17a)
+ o Fix the check for multicast or broadcast addresses in evutil_check_interfaces (1a21d7b)
+ o Avoid a free(NULL) if out-of-memory in evdns_getaddrinfo. Found by Dave Hart (3417f68)
+
+DEFENSIVE PROGRAMMING:
+ o Add compile-time check for AF_UNSPEC==PF_UNSPEC (3c8f4e7)
+
+BUGS IN TESTS:
+ o Fix test.sh output on solaris (b4f89b6 Dave Hart)
+ o Make test-eof fail with a timeout if we never get an eof. (05a2c22 Harlan Stenn)
+ o Use %s with printf in test.sh (039b9bd)
+ o Add an assert to appease clang's static analyzer (b0ff7eb Sebastian Hahn)
+ o Add a forgotten return value check in the unit tests (3819b62 Sebastian Hahn)
+ o Actually send NULL request in http_bad_request_test (b693c32 Sebastian Hahn)
+ o add some (void) casts for unused variables (65707d7 Sebastian Hahn)
+ o Refactor test_getaddrinfo_async_cancel_stress() (48c44a6 Sebastian Hahn)
+ o Be nice and "handle" error return values in sample code (4bac793 Sebastian Hahn)
+ o Check return value of evbuffer_add_cb in tests (93a1abb Sebastian Hahn)
+ o Remote some dead code from dns-example.c (744c745 Sebastian Hahn)
+ o Zero a struct sockaddr_in before using it (646f9fe Sebastian Hahn)
+
+BUILD FIXES:
+ o Fix warnings about AC_LANG_PROGRAM usage (f663112 Sebastian Hahn)
+ o Skip check for zlib if we have no zlib.h (a317c06 Harlan Stenn)
+ o Fix autoconf bracket issues; make check for getaddrinfo include netdb.h (833e5e9 Harlan Stenn)
+ o Correct an AM_CFLAGS to an AM_CPPFLAGS in test/Makefile.am (9c469db Dave Hart)
+ o Fix make distcheck & installation of libevent 1 headers (b5a1f9f Dave Hart)
+ o Fix compilation under LLVM/clang with --enable-gcc-warnings (ad9ff58 Sebastian Hahn)
+
+FEATURES:
+ o Make URI parser able to tolerate nonconformant URIs. (95060b5)
+
+DOCUMENTATION:
+ o Clarify event_set_mem_functions doc (926f816)
+ o Correct evhttp_del_accept_socket documentation on whether socket is closed (f665924)
+ o fix spelling mistake in whatsnew-2.0.txt (deb2f73)
+ o Fix sample/http-server ipv6 fixes (eb692be)
+ o Comment internal headers used in sample code. (4eb281c)
+ o Be explicit about how long event loops run in event.h documentation (f95bafb)
+ o Add comment to configure.in to explain gc-sections test logic (c621359)
+ o Fix a couple of memory leaks in samples/http-server.c. Found by Dave Hart. (2e9f665)
+
+BUILD IMPROVEMENTS:
+ o Use the gcc -ffunction-segments feature to allow gc when linking with static libevent (0965c56 Dave Hart)
+ o Add configure options to disable installation, regression tests (49e9bb7 Dave Hart)
+
+
+
+Changes in version 2.0.10-stable (16 Dec 2010)
+  [Autogenerated from the Git log, sorted and cleaned by hand.]
+BUGFIXES
+ o Minor fix for IOCP shutdown handling fix (2599b2d Kelly Brock)
+ o Correctly notify the main thread when activating an event from a subthread (5beeec9)
+ o Reject overlong http requests early when Expect:100-continue is set (d23839f Constantine Verutin)
+ o EVUTIL_ASSERT: Use sizeof() to avoid "unused variable" warnings with -DNDEBUG. (b63ab17 Evan Jones)
+
+CODE CLEANUPS
+ o bufferevent-internal.h: Use the new event2/util.h header, not evutil.h (ef5e65a Evan Jones)
+ o Use relative includes instead of system includes consistently. (fbe64f2 Evan Jones)
+ o Make whitespace more consistent
+
+TESTING
+ o tests: Use new event2 headers instead of old compatibility headers. (4f33209 Evan Jones)
+
+DOCUMENTATION
+ o Document that the cpu_hint is only used on Windows with IOCP for now (57689c4)
+ o Add stuff to "whats new in 2.0" based on reading include changes since August. (18adc3f)
+
+
+Changes in 2.0.9-rc (30 Nov 2010):
+  [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW AND MODIFIED APIs
+ o Add a function to change a listener's callback. (46ee061)
+ o Make evbuffer_add_file take ev_off_t, not off_t (ac7e52d)
+ o Make rate-limits go up to SIZE_MAX/EV_SSIZE_MAX, not just INT32_MAX (2cbb1a1)
+ o Add a bufferevent_get_base function (aab49b6)
+
+MAJOR BUGFIXES
+ o Disable changelist for epoll by default because of Linux dup() bug; add an option and/or an envvar to reenable it for speed. (9531763)
+ o Fix a 100%-CPU bug where an SSL connection would sometimes never stop trying to write (1213d3d)
+ o Fix a nasty bug related to use of dup() with epoll on Linux (c281aba)
+ o Fix bugs in posix thread-id calculation when sizeof(pthread_t) != sizeof(long) (fbaf077)
+ o Fix some ints to evutil_socket_t; make tests pass on win64. (f817bfa Dimitre Piskyulev)
+ o Set _EVENT_SIZEOF_VOID_P correctly on win32 and win64 (1ae82cd Dimitre Piskyulev)
+ o Avoid double-invocation of user callback with EVUTIL_EAI_CANCEL (abf01ed)
+ o Set SO_UPDATE_ACCEPT_CONTEXT on sockets from AcceptEx so that shutdown() can work (52aa419)
+ o When closing a filtering bufferevent, clear callbacks on the underlying bufferevent (fc7b1b0)
+
+NEW AND MODIFIED HTTP APIs
+ o Add evhttp_parse_query_str to be used with evhttp_uri_parse. (2075fbc)
+ o Add evhttp_response_code to remove one more reason to include http_struct.h (22e0a9b)
+ o Define enumerators for all HTTP methods, including PATCH from RFC5789 (75a7341 Felix Nawothnig)
+ o Functions to actually use evhttp_bound_socket with/as evconnlistener. (006efa7)
+ o Add evhttp_request_get_command so code can tell GET from POST without peeking at the struct. (49f4bf7)
+ o Introduce absolute URI parsing helpers. (86dd720 Pavel Plesov)
+ o Revise evhttp_uri_parse implementation to handle more of RFC3986 (eaa5f1d)
+ o Add evhttp_connection_get_base() to get the event_base from an http connection (cd00079)
+ o Let evhttp_parse_query return -1 on failure (b1756d0)
+ o New evhttp_uri(encode|decode) functions to handle + and NUL characters right (a8148ce)
+ o Add evhttp_response_code to remove one more reason to include http_struct.h (22e0a9b)
+ o Tweak interface for allowed methods (f5b391e)
+ o Add evhttp server alias interface, correct flagging of proxy requests. (aab8c38 Christopher Davis)
+
+HTTP BUGFIXES
+ o Add some comments to http.c and make a few functions static. (90b3ed5)
+ o Fix Content-Length when trying send more than 100GB of data (!) on an evhttp. (525da3e)
+ o Fix a bug where we would read too much data in HTTP bodies or requests. (58a1cc6)
+ o Correctly count req->body_size on http usage without Content-Length (8e342e5)
+ o Avoid missed-request bug when entire http request arrives before data is flushed (74c0e86)
+ o reset "chunked" flag when sending non-chunked reply (aa5f55f Joachim Bauch)
+ o evhttp_encode_uri encodes all reserved characters, including !$'()*+,/:=@ (2e63a60)
+ o Replace exact-version checks for HTTP/1.1 with >= or < checks (647e094)
+ o evhttp: Return 501 when we get an unrecognized method, not 400. (536311a)
+ o Don't disable reading from the HTTP connection after sending the request to be notified of connection-close in time (c76640b Felix Nawothnig)
+ o Never call evhttp_readcb while writing. (0512487)
+ o Try to fix an assertion failure related to close detection (0faaa39)
+ o Correctly detect timeouts during http connects (04861d5)
+ o Preliminary support for Continue expectation in evhttp. (fa9305f Christopher Davis)
+
+OTHER BUGFIXES
+ o Correct logic for realigning a chain in evbuffer_add (e4f34e8)
+ o Fix a minor syntax error that most compilers didn't care about (e56ff65)
+ o Fix some uses of int for socket in regress (5d389dc)
+ o Check return value for ioctlsocket on win32 (f5ad31c Trond Norbye)
+ o Fix som event_warns that should have been event_warnx (19c71e7)
+ o Fix signal handler types for win64. (b81217f)
+ o Try to clear up more size_t vs int/long issues. (598d133)
+ o Make sure IOCP evconnlistener uses virtual events. (7b40a00 Christopher Davis)
+ o Don't free evdns_request handles until after the callback is invoked (9ed30de)
+ o Fix some more cancel-related bugs in getaddrinfo_async (c7cfbcf)
+ o Make evdns_getaddrinfo_cancel threadsafe (d51b2fc)
+ o Only clear underlying callbacks when the user hasn't reset them. (1ac5b23)
+ o Fix bug in bufferevent_connect on an openssl bufferevent that already had an fd (4f228a1)
+ o Resolve an evport bug in the thread/forking test (3a67d0b)
+ o Make sure the CLOEXEC flag is set on fds we open for base notification (3ab578f)
+ o Fix IRIX build.  sa_family collides with a #define in sys/socket.h on IRIX. (e874982 Kevin Bowling)
+ o If not WIN32, include <sys/socket.h> in event2/util.h. (1cd45e5 Kevin Bowling)
+ o Fix some C99-style comments to work with the xlC compiler. (c2e5e22 Kevin Bowling)
+ o Add some checks since lack of TAILQ_FOREACH doesn't imply lack of FIRST, END, NEXT, or INSERT_BEFORE.  Quiet some warnings in XL C. (c4dc335 Kevin Bowling)
+ o Reworked AIX __ss_family workaround to use AC_STRUCT_MEMBER. (2e2a3d7 Kevin Bowling)
+ o Take select from <sys/select.h> when testing in autoconf.  AIX build fix. (a3a9f6b Kevin Bowling)
+ o Fix snprintf related failures on IRIX. (3239073 Kevin Bowling)
+ o Remove _event_initialized(); make event_initialized() a function(); make it consistent on windows and non-windows (652024b)
+ o Do not let EVLOOP_ONCE exit the loop until all deferred callbacks have run (2d5e1bd)
+ o Make EVLOOP_ONCE ignore internal events (0617a81)
+ o Possible crash fix when freeing an underlying bufferevent of an openssl bufferevent (29f7623)
+
+HTTP CLEANUPS
+ o Stop using Libevent-1 headers in regress_http (1f507d7)
+ o Modernize header usage in bench_http.c (e587069)
+ o fix signed/unsigned warnings in http.c (74a91e5)
+ o Update the HTTP regression tests to use Libevent2 apis for non-http stuff (d9ffa89)
+ o Start porting http tests to not use legacy interfaces (8505a74)
+ o Convert the rest of the http tests to be non-legacy unit tests. (9bb8239)
+ o Rename the confusing "base" static variable in regress_http.c (353402a)
+ o Stop accessing http request struct directly from in the unit tests. (0b137f4)
+ o Refactor http version parsing into a single function (a38140b)
+
+TESTING
+ o Improvements to tinytest_macros.h (ad923a1)
+ o Add a huge pile of tests for the new URI functions, and make them pass. (a5a76e6)
+ o Unit tests for evhttp_uri_set* (bc98f5e)
+ o Increase the skew tolerance to 2 seconds in thread/deferred_cb_skew (f806476 Christopher Davis)
+ o Reorder backends in test.sh to match preference order in event.c (ece974f)
+ o Add a stress test for getaddrinfo_cancel (da1bf52)
+ o Units test for unexpected evhttp methods. (75e3320)
+
+DOCUMENTATION
+ o Document behavior of URI parsing more thoroughly. (3a33462)
+ o Document that two bufferevent functions only work on socket bufferevents (70e1b60)
+ o add a requested docstring for event_rpcgen.CommandLine.__init__ (f1250eb)
+ o Fix a mistake in http documentation found by Julien Blache (229714d)
+ o Add a basic example of how to write a static HTTP server. (4e794d5)
+ o Document event_get_assignment (88be27d)
+ o Note that reentrant calls to libevent from logging cbs may fail badly (e431bcd)
+ o Clarify EVLOOP_* documentation to be more precise. (057a514)
+
+CLEANUPS
+ o Simplify the logic for choosing EPOLL_CTL_ADD vs EPOLL_CTL_MOD (2c66983)
+ o Rename "size" variables in win32select that were really fd counts. (b6a158c)
+ o Fix even more win64 warnings (7484df6)
+ o Fix even more win64 warnings: buffer, event_tagging, http, evdns, evrpc (545a611)
+ o Fix more wn64 warnings. (34b84b9 Christopher Davis)
+ o Use the label_len local variable in evdns instead of recalculating it over and over (ba01456)
+ o Fix some irix compilation warnings spotted by Kevin Bowling (7bcace2)
+
+
+
+Changes in 2.0.8-rc (14 Oct 2010):
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW APIS
+ o Add error callback to evconnlistener (c4be8d8 Simon Perreault)
+ o Add a LEV_OPT_THREADSAFE option for threadsafe evconnlisteners (127d4f2)
+
+CHANGED BEHAVIOR
+ o Correct logic on disabling underlying bufferevents when disabling a filter (ac27eb8)
+
+BUGFIXES
+ o Obey enabled status when unsuspending (040a019 Simon Perreault)
+ o Warn when using the error-prone EV_SIGNAL interface in an error-prone way.  Also, fix a couple of race conditions in signal.c (720bd93)
+ O Make default signal backend fully threadsafe (95a7d41)
+ o Put internal events at highest priority (90651b3)
+ o Fix warnings in the main codebase flagged by -Wsigned-compare (9c8db0, 5e4bafb, 5c214a, 6be589a, e06f514)
+ o Fix compile in kqueue.c (b395392 Sebastian Hahn)
+ o Do not search outside of the system directory for windows DLLs (d49b5e3)
+ o Fix a spurious-call bug on epoll.c (0faaee0)
+ o Send a shutdown(SHUT_WR) before closing an http connection (e0fd870 Christopher Davis)
+ o Fix warnings on mingw with gcc 4.5 (5b7a370)
+ o Fix an EINVAL on evbuffer_write_iovec on OpenSolaris. (fdc640b)
+ o Fix allocation error for IOCP listeners. Probably harmless, since struct event is big (481ef92)
+ o Make iocp/listener/error work; don't accept again if lev is disabled. (62b429a Christopher Davis)
+ o Handle rate-limiting for reading on OpenSSL bufferevents correctly. (819b171)
+ o Fix serious bugs in per-bufferevent rate-limiting code (34d64f8)
+ o Avoid spurious reads from just-created open openssl bufferevents (223ee40)
+ o Fix a case where an ssl bufferevent with CLOSE_ON_FREE didn't close its fd (93bb7d8)
+ o The corrected bufferevent filter semantics let us fix our openssl tests (34331e4)
+
+TESTING
+ o Make SSL tests cover enabling/disabling EV_READ. (a5ce9ad)
+ o Bump to the latest version of tinytest (f0bd83e)
+ o Unit tests for listener error callbacks (045eef4)
+ o New unit test for ssl bufferevents starting with connected SSLs. (02f6259)
+
+DEBUGGABILITY
+ o Make debugging output for epoll backend more comprehensive (ec2b05e)
+ o Make event.c debugging messages report fds (e119899)
+ o Make the --enable-gcc-warnings option include signed comparison warnings (d3b096c)
+
+DEADCODE REMOVAL
+ o Remove the now-useless evsig_caught and evsig_process (4858b79)
+ o Remove event_base.evsigbase; nothing used it. (38d0960)
+
+
+
+Changes in 2.0.7-rc (9 Sep 2010):
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW APIS
+ o Expose a evdns_base_nameserver_sockaddr_add() function to add a nameserver by sockaddr (1952143)
+ o Add event_config_set_num_cpus_hint() for tuning win32 IOCP thread pools, etc. (2447fe8 Christopher Davis)
+
+BUGFIXES
+ o Fix a nasty dangling-event bug when using rate-limiting groups (0bffe43)
+ o Clean up syntax on TAILQ_ENTRY() usage to build correctly with recent MSVC (60433a0 Gilad Benjamini)
+ o Make definition of WIN32_LEAN_AND_MEAN in event.h conditional (3920172 Gilad Benjamini)
+ o Correctly detect failure to delete bufferevent read-timeout event (da6e7cd)
+ o Set close-on-exec bit for filedescriptors created by dns subsystem (d0b8843)
+ o Fix kqueue correctness test on x84_64 (6123d12)
+ o Detect events with no ev_base; warn instead of crashing (f1074b7)
+ o Fix an issue with forking and signal socketpairs in select/poll backends (d61b2f3)
+ o Stop using global arrays to implement the EVUTIL_ctype functions (1fdec20)
+ o On windows, make lock/thread function tables static (5de2bcb)
+ o Close th_notify_fds and open a new pair on reinit (495ed66)
+ o Declare signal handler function as "__cdecl" on Windows (f0056d0)
+ o Use the _func() replacements for open, fstat, etc in evutil.c on win32 (e50c0fc)
+ o Only process up to MAX_DEFERRED deferred_cbs at a time (17a14f1 Christopher Davis)
+
+THREADING BUGFIXES
+ o Avoid deadlock when activating signals (970e6ad)
+ o Add a condition variable backend, with implementations for pthreads and win32 (d4977b5)
+ o Use conditions instead of current_event_lock to fix a deadlock (e0972c2)
+ o Fix logic error in win32 TRY_LOCK that caused problems with rate-limiting (4c32b9d)
+ o Avoid needlessly calling evthread_notify_base() when the loop is not running (c7a06bf)
+ o Minimize calls to base_notify implementation functions, thereby avoiding needless syscalls (4632b78)
+
+IOCP BUGFIXES
+ o IOCP-related evbuffer fixes (03afa20 Christopher Davis)
+ o Stop IOCP when freeing the event_base (d844242 Christopher Davis)
+ o Some IOCP bufferevent tweaks (76f7e7a Christopher Davis)
+
+TESTS
+ o Make the regress_pthread.c tests work on windows with current test APIs (d74ae38)
+ o Add a unit test for conditions (5fb1095)
+ o Allow more than one copy of regression tests to run at once (a97320a)
+ o Fix event_del(0) instance in bench.c (b0f284c Shuo Chen)
+ o Fix a few memory leaks in the tests (1115366)
+ o IOCP-related unit test tweaks (499452f Christopher Davis)
+ o Improve testing of when thread-notification occurs (ce85280)
+
+BUILD AND DISTRIBUTION
+ o Add pkgconfig files for libevent_{openssl,pthreads} (ebcb1f0)
+ o Change include order in Makefile.nmake (4022b28)
+ o Make include/event2/event-config.h not included in source dist (a4af9be)
+ o Honor NDEBUG; build without warnings with NDEBUG; make NDEBUG always-off in unit test code (743f866)
+ o Declare evkeyvalq and event_list even if event_struct.h comes before sys/queue.h (d3ceca8)
+ o Move evkeyvalq into a separate header for evhttp_parse_query users (ca9048f)
+ o Prefer autoreconf -ivf to manual autogen.sh (7ea8e89)
+
+CLEANUP
+ o Completely remove the (mostly-removed) obsolete thread functions (3808168)
+ o Rename regress_pthread.c to regress_thread.c (041989f)
+ o Make defer-internal.h use lock macros, not direct calls to lock fns (5218d2a)
+
+DOCUMENTATION
+ o Document that DNS_NO_SEARCH is an obsolete alias for DNS_QUERY_NO_SEARCH (33200e7)
+ o Update the whatsnew-2.0.txt document (4991669)
+
+
+
+Changes in 2.0.6-rc (6 Aug 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Document a change in the semantics of event_get_struct_event_size() (e21f5d1)
+ o Add a comment to describe our plan for library versioning (9659ece)
+ o Fix sentence fragment in docs for event_get_struct_event_size() (7b259b6)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Remove the obsolete evthread interfaces (c5bab56)
+ o Let evhttp_send_error infer the right error reasons (3990669)
+ o Add a function to retrieve the other side of a bufferevent pair (17a8e2d)
+ o Add bufferevent_lock()/bufferevent_unlock() (215e629)
+ o Stop asserting when asked for a (unsupported) TCP dns port. Just return NULL. (7e87a59)
+ o Replace (unused,always 0) is_tcp argument to evdns_add_server_port*() with flags (e1c1167)
+ o Constify a couple of arguments to evdns_server_request_add_*_reply (cc2379d)
+ o Add an interface to expose min_share in ratelimiting groups (6ae53d6)
+
+BUGFIXES
+ o Avoid event_del on uninitialized event in event_base_free (6d19510)
+ o Add some missing includes to fix Linux build again (75701e8)
+ o Avoid close of uninitialized socket in evbuffer unit test (bda21e7)
+ o Correctly recognize .255 addresses as link-local when looking for interfaces (8c3452b)
+ o If no evdns request can be launched, return NULL, not a handle (b14f151)
+ o Use generic win32 interfaces, not ASCII-only ones, where possible. (899b0a3)
+ o Fix the default HTTP error template (06bd056 Felix Nawothnig)
+ o Close the file in evutil_read_file whether there's an error or not. (0798dd1 Pierre Phaneuf)
+ o Fix possible nullptr dereference in evhttp_send_reply_end() (29b2e23 Felix Nawothnig)
+ o never let bufferevent_rlim functions return negative (0859870)
+ o Make sample/hello_world work on windows (d89fdba)
+ o Fix a deadlock related to event-base notification.  Diagnosed by Zhou Li, Avi Bab, and Scott Lamb. (17522d2)
+ o Possible fix to 100% cpu usage with epoll and openssl (cf249e7 Mike Smellie)
+ o Don't race when calling event_active/event_add on a running signal event (fc5e0a2)
+ o Suppress a spurious EPERM warning in epoll.c (e73cbde)
+ o Fix wrong size calculation of iovec buffers when exact=1 (65abdc2 niks)
+ o Change bufferevent_openssl::do_write so it doesn't call SSL_write with a 0 length buffer (c991317 Mike Smellie)
+ o Fixed compilation of sample/le-proxy.c on win32 (13b912e Trond Norbye)
+ o Fix rate-limit calculation on openssl bufferevents. (009f300)
+ o Remember to initialize timeout events for bufferevent_async (de1f5d6 Christopher Davis)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Test the unlocked-deferred callback case of bufferevents (dfb75ab)
+ o Remove the now-unusable EVTHREAD_LOCK/UNLOCK constants (fdfc3fc)
+ o Use -Wlogical-op on gcc 4.5 or higher (d14bb92)
+ o Add the libtool-generated /m4/* stuff to .gitignore (c21c663)
+ o Remove some automake-generated files from version control. (9b14911)
+ o Have autogen.sh pass --force-missing to automake (8a44062)
+ o Set library version for libevent_pthreads correctly (b2d7440)
+ o Really only add libevent_core.la to LIBADD on mingw (1425003 Sebastian Hahn)
+ o Build more cleanly with NetBSDs that dislike toupper(char) (42a8c71)
+ o Fix unit tests with -DUSE_DEBUG enabled (28f31a4)
+ o Fix evdns build with -DUNICODE (5fa30d2)
+ o Move event-config.h to include/event2 (ec347b9)
+
+TESTING
+ o Add options to test-ratelim.c to check its results (2b44dcc)
+ o Make test-ratelim clean up after itself better. (b5bfc44)
+ o Remove the now-obsolete setup_test() and cleanup_test() functions (e73f1d7)
+ o Remove all non-error prints from test/regress.c (8bc1e3d)
+ o Make test.sh exit with nonzero status if tests fail (faf2a04)
+ o Have the unit tests report errors from test.sh (3689bd2)
+ o Fix logic in correcting high values from FIONREAD (3467f2f)
+ o Add test for behavior on remote socket close (44d57ee)
+ o Unit test for event_get_struct_event_size() (7510aac)
+ o Make test/test.sh call test-changelist (7c92691)
+ o Fix badly-behaved subtest of dns/bufferevent_connect_hostname (840a72f Joachim Bauch)
+ o Add option to test-ratelim to test min_share (42f6b62)
+ o Fix an assertion bug in test-ratelim (b2c6202)
+ o Make tests quieter on local dns resolver failure (e996b3d)
+ o Increase the tolerance in our unit tests for sloppy clocks. (170ffd2)
+ o Use AF_INET socketpair to test sendfile on Solaris (9b60209)
+ o Make test-changelist count cpu usage right on win32 (ea1ea3d)
+
+INTERNALS, PERFORMANCE, AND CODE CLEANUPS
+ o Mark the event_err() functions as __attribute__((noreturn)) (33bbbed)
+ o Do not check that event_base is set in EVBASE_ACQUIRE_LOCK (218a3c3)
+ o Replace (safe) use of strcpy with memcpy to appease OpenBSD (caca2f4)
+ o Remove some dead assignments (47c5dfb)
+ o Fix a pedantic gcc 4.4 warning in event2/event.h (276e7ee)
+ o Drain th_notify_fd[0] more bytes at a time. (a5bc15b)
+ o Tidy up the code in evthread_make_base_notifiable a little (61e1eee)
+ o Pass flags to fcntl(F_SETFL) and fcntl(F_SETFD) as int, not long (7c2dea1)
+ o Remove unused variables in test/test-changelist.c (b00d4c0)
+ o Fix whitespace. (cb927a5)
+ o Improve error message for failed epoll to make debugging easier. (9e725f7)
+ o Turn our socketpair() replacement into its own function (57b30cd)
+
+
+
+Changes in 2.0.5-beta (10 May 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Update all our copyright notices to say "2010" (17efc1c)
+ o Add Christopher Clark and Maxim Yegorushkin to the LICENSE file (38b7b57)
+ o Clarify Christopher Clark's status as writer of original ht code. (78772c3)
+ o Try to comment some of the event code more (cdd4c49)
+ o Add a few more evmap/changelist comments (c247adc)
+ o Add a comment to explain why evdns_request is now separte from request (ceefbe8)
+ o Document evutil_secure_rng_init() and evutil_secure_rng_add_bytes() (a5bf43a)
+ o Stop distributing and installing manpages: they were too inaccurate (7731ec8)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Remove signal_assign() and signal_new() macros. (2fac0f7)
+ o Make evdns use the regular logging system by default (b2f2be6)
+ o Allow evbuffer_read() to split across more than 2 iovecs (e470ad3)
+ o Functions to manipulate existing rate limiting groups. (ee41aca)
+ o Functions to track the total bytes sent over a rate limit group. (fb366c1)
+ o Detect and refuse reentrant event_base_loop() calls (b557b17)
+ o Limit the maximum number of events on each socket to 65535 (819f949)
+ o Add evbuffer_copyout to copy data from an evbuffer without draining (eb86c8c)
+ o Expose the request and reply members of rpc_req_generic() (07edf78 Shuo Chen)
+ o Add void* arguments to request_new and reply_new evrpc hooks (755fbf1 Shuo Chen)
+ o Seed the RNG using sysctl() as well as /dev/urandom (71fc3eb)
+ o Make evutil_secure_rng_init() work even with builtin arc4random (f980716)
+ o Report DNS error when lookup fails during bufferevent_socket_connect_hostname. (0ef4070 Christopher Davis)
+ o Release locks on bufferevents while executing callbacks (a5208fe Joachim Bauch) o Make debug mode catch mixed ET and non-ET events on an fd (cb67074)
+ o Catch attempts to enable debug_mode too late (9ecf0d4)
+ o Refuse null keys in evhttp_parse_query() (953e229 Frank Denis)
+
+BUGFIXES
+ o Avoid a spurious close(-1) on Linux (70a44b6)
+ o Do not close(-1) when freeing an uninitialized socket bufferevent (b34abf3)
+ o Free evdns_base->req_heads on evdns_base_free (859af67)
+ o Avoid an (untriggerable so far) crash bug in bufferevent_free() (0cf1431)
+ o Set mem_offset for every bufferevent type (657d1b6)
+ o Fix infrequent memory leak in bufferevent_init_common(). (8398641 Jardel Weyrich)
+ o Make evutil_signal_active() match declaration. (e1e703d Patrick Galbraith)
+ o Fix minheap code to use replacement malloc functions (a527618)
+ o Fix a free(NULL) in minheap-internal.h (6f20492)
+ o Fix critical bug in evbuffer_write when writev is not available (cda56ab)
+ o Make the no_iovecs case of write_atmost compile (8e227b0)
+ o Fix a memory leak when appending/prepending to a buffer with unused space. (45068a3)
+ o Clean up a mistake in pointer manipulation in evbuffer_remove (28bfed4 Christopher Davis)
+ o Always round up when there's a fractional number of msecs. (8f9e60c Christopher Davis)
+ o Fix compiler warnings under WIN32 (d469c50 Giuseppe Scrivano)
+ o Clean up properly when adding a signal handler fails. (b84b598 Gilad Benjamini) o Ensure that evdns_request is a persistent handle. (15bb82d Christopher Davis)
+ o Free search state when finished searching to avoid an infinite loop. (a625840 Christopher Davis)
+ o Assert for valid requests as necessary. (67072f3 Christopher Davis)
+ o do not leak the request object on persistent connections (9d8edf2)
+ o Make evdns logging threadsafe (b1c7950)
+ o Fix a couple of bugs in the BSD sysctl arc4seed logic (a47a4b7)
+ o Remove one last bug in last_with_datap logic. Found with valgrind (d49b92a)
+ o fix a leak when unpausing evrpc requests (94ee125)
+ o Fix a memory leak when unmarshalling RPC object arrays (f6ab2a2)
+ o Fix compilation when openssl support is disabled (40c301b)
+ o Allow empty reason line in HTTP status (739e688 Pierre Phaneuf)
+ o Fix a compile warning introduced in 739e688 (bd1ed5f Sebastian Hahn)
+ o Fix nonstandard TAILQ_FOREACH_REVERSE() definition (71afc52 Frank Denis)
+ o Try /proc on Linux as entropy fallback; use sysctl as last resort (20fda29)
+ o Fix symbol conflict between mm_*() macros and libmm (99e50e9)
+ o Fix some crazy macro mistakes in arc4random.c (90d4225)
+ o Make evbuffer_add_file() work on windows (dcdae6b)
+ o Fix unused-variable warning when building with threads disabled (ad811cd)
+ o Numerous opensolaris compilation fixes (c44de06)
+ o Fix getaddrinfo with protocol unset on Solaris 9. Found by Dagobert Michelsen (2cf2a28)
+ o Fix another nasty solaris getaddrinfo() behavior (3557071)
+ o Define _REENTRANT as needed on Solaris, elsewhere (c1cd32a)
+ o Fix some autoconf issues on OpenBSD (7c519df)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Distribute libevent.pc.in, not libevent.pc (22aff04)
+ o Avoid errors in evutil.c when building with _UNICODE defined (b677032 Brodie Thiesfield)
+ o Avoid errors in http.c when building with VC 2003 .NET (13e4f3b Brodie Thiesfield)
+ o Support the standard 'make check' target in place of 'make verify' (426c8fb)
+ o Remove redundant stuff from EXTRA_DIST (b660edf)
+ o Switch to using AM conditionals in place of AC_LIBOBJ (2e898f5)
+ o Remove an orphaned RELEASE flag in Makefile.am (0794b0d)
+ o Give a better warning for bad automake versions. (77c917d)
+ o Use dist_bin_SCRIPTS, not EXTRA_DIST, to distribute scripts (9eb2fd7)
+ o Never test for select() on windows (3eb044d Trond Norbye)
+ o Do not inhibit automake dependencies generation (10c4c90 Giuseppe Scrivano)
+ o Create shared libraries under Windows (3cbca86 Giuseppe Scrivano)
+ o Add ctags/etags files to .gitignore (0861d17)
+ o Only specify -no-undefined on mingw (25433b9)
+ o Only add libevent_core.la to LIBADD on mingw (fdc6297)
+
+TESTING
+ o Get bench_http to work on Windows; add a switch to enable IOCP. (4ac38a5 Christopher Davis)
+ o VC has no getopt(), so do without in bench_http. (1273d2f Christopher Davis)
+ o Fix an obnoxious typo in the bufferevent_timeout_filter test (0d047c3)
+ o Fix a write of uninitialized RAM in regression tests (68dc742)
+ o Fix some memory leaks in the unit tests (274a7bd)
+ o Make 'main/many_events' test 70 fds, not 64. (33874b0)
+ o Unit-test every evbuffer_add_file() implementation. (06a4443)
+ o Add more unit tests for evbuffer_expand (8c83e99)
+ o Test another case of evbuffer_prepend (1234b95)
+ o Fix a possible double-free bug in SSL bufferevents with CLOSE_ON_FREE (7501895) o Add dns/search_cancel unit test. (39b870b Christopher Davis)
+ o Make http_base_test stop leaking an event_base. (96730d3)
+ o Detect broken unsetenv at unit-test runtime (f37cd4c)
+ o Implement regress_make_tempfile on win32 to test evbuffer_add_file (b4f12a1)
+ o add more (currently skipped) add_file tests on win32 (05de45d)
+ o Fix bench_http build on win32. (384d124)
+ o Make unit test for add_file able to tell "error" from "done" (88a543f)
+ o Make test for bufferevent_connect_hostname system-neutral (f89168e)
+ o Make test.sh support mingw/msys on win32 (0ee6f6c)
+ o Fix test.sh on freebsd (3d9e05b)
+
+INTERNALS, PERFORMANCE, AND AND CODE CLEANUPS
+ o Improve the speed of evbuffer_readln() (cc1600a)
+ o more whitespace normalization (2c2618d)
+ o Revise evbuffer to add last_with_data (2a6d2a1)
+ o Use last_with_data in place of previous_to_last (c8ac57f)
+ o Remove previous_to_last from evbuffer (6f47bd1)
+ o Fix last_with_data compilation on windows (1e7b986)
+ o Add some glass-box tests for the last_with_data code. (17da042)
+ o Improve robustness for refcounting (f1bc125)
+ o Remove a needless min_heap_shift_up_() call (7204b91)
+ o Increase MIN_BUFFER_SIZE to 512 (1024 on 64-bit) (2014ae4)
+ o Do not use evbuffer_expand() to add the first chain to a buffer (5c0ebb3)
+ o Make evbuffer_prepend handle empty buffers better (c87272b)
+ o Replace last_with_data with a slightly smarter version (b7442f8)
+ o Turn the increasingly complex *_CHAIN() macros into functions (96865c4)
+ o Rewrite evbuffer_expand and its users (d5ebcf3)
+ o Add evutil_tv_to_msec for safe conversion of timevals to milliseconds. (850c3ff Christopher Davis)
+ o Initialize last_with_datap correctly in evbuffer_overlapped (a0983b6)
+ o Replace EVUTIL_CLOSESOCKET macro with a function (899c1dc Sebastian Sjöberg)
+ o Move domain search state to evdns_request. (beaa14a Christopher Davis)
+ o Remove redundant checks for lock!=NULL before calling EVLOCK_LOCK (50ec59f)
+ o Rename current_base symbol to event_global_current_base_ (c16e684)
+ o Fix whitespace in evutil.c (935e150)
+ o Replace users of "int fd" with "evutil_socket_t fd" in portable code (c7cf6f0)
+
+
+
+Changes in 2.0.4-alpha (28 Feb 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Add stub header for 2.0.4-alpha changelog. (94d0065)
+ o Improve the README with more information and links. (0b42726)
+ o Add more people who wrote patches to the acknowledgments (0af10d5)
+ o Add a warning about the use of event_initialized. (f32b575)
+ o Add a LICENSE file so people can find our license easily (7067006)
+ o Add a new "hello world" sample program (becb9f9)
+ o Clarify status of example programs (d60a1bd)
+ o Update time-test.c to use event2 (f4190bf)
+ o Add the arc4random.c license to the LICENSE file. (e15e1e9)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Improved optional lock debugging. (0cd3bb9)
+ o Rate-limiting for bufferevents; group and individual limits are supported. (737c9cd)
+ o Testing code for bufferevent rate-limiting. (f0c0124)
+ o Make the initial nameserver probe timeout configurable. (1e56a32)
+ o Revise the locking API: deprecate the old locking callbacks and add trylock. (347952f)
+ o Do not make bufferevent_setfd implicitly disable EV_READ and EV_WRITE. (8274379)
+ o Do not ignore bufferevent_enable(EV_READ) before bufferevent_connect(). (4a5b534)
+ o Introduced evutil_make_socket_closeonexec() to preserve fd flags for F_SETFD. (d0939d2 Jardel Weyrich)
+ o evdns_getaddrinfo() now supports the /etc/hosts file. (72dd666)
+ o Look at the proper /etc/hosts file on windows. (66c02c7)
+ o Allow http connections to use evdns for hostname looksups. (c698b77)
+ o Changelist code to defer event changes until just before dispatch (27308aa)
+ o do not use a function to assign the evdns base; instead assign it via evhttp_connection_base_new() which is a new function introduced in 2.0 (5032e52)
+ o Functions to access more fields of struct event. (0683950)
+ o Make kqueue use changelists. (45e5ae3)
+ o Remove kqueue->pend_changes. (3225dfb)
+ o Minimize epoll_ctl calls by using changelist (c8c6a89)
+ o Add support for a "debug mode" to try to catch common errors. (cd17c3a)
+ o Note a missing ratelim function (361da8f)
+ o Add ev_[u]intptr_t to include/event2/util.h (1fa4c81)
+ o const-ify a few more functions in event.h (d38a7a1)
+ o Deprecate EVENT_FD and EVENT_SIGNAL. (f6b2694)
+ o Remove EVUTIL_CHECK_FMT. (6c21c89)
+ o Add EV_*_MAX macros to event2/util.h to expose limits for ev_* types. (aba1fff) o Functions to view and manipulate rate-limiting buckets. (85047a6)
+ o Add the rest of the integer limits, and add a test for them. (60742d5)
+ o Remove the 'flags' argument from evdns_base_set_option() (1dd7e6d)
+ o Add an arc4random implementation for use by evdns (d4de062)
+ o Use off_t for the length parameter of evbuffer_add_file (3fe60fd)
+ o Construct Windows locks using InitializeCriticalSectionAndSpinCount (32c6f1b)
+ o Expose view of current rate limit as constrained by group limit (162ce8a)
+ o Provide consistent, tested semantics for bufferevent timeouts (d328829)
+
+BUGFIXES AND TESTS
+ o Tolerate code that returns from a fatal_cb. (91fe23f)
+ o Parenthesize macro arguments more aggressively (07e9e9b)
+ o Fix memory-leak of signal handler array with kqueue. (e1ffbb8)
+ o Stop passing EVTHREAD_READ and EVTHREAD_WRITE to non-rw locks. (76cd2b7)
+ o Fix two use-after-free bugs in unit tests spoted by lock debugging (d84d838)
+ o Fix a locking bug in event_base_loop() (da1718b)
+ o Fix an evdns lock violation. (2df1f82 Zhuang Yuyao)
+ o Valgrind fix: Clear struct kevent before checking for OSX bug. (56771a3 William Ahern)
+ o Fix up evthread compilation on windows (bd6f1ba Roman Puls)
+ o Fix regress_iocp.c usage of old lock allocation macros. (31687b4 unknown)
+ o Update nmake makefile to build evthread.c (b62d979 unknown)
+ o Fix a crash when reading badly formatted resolve.conf; from Yasuoka Masahiko (6c7c579 Yasuoka Masahiko)
+ o Fix a snow leopard compile warning in the unit tests. (7ae9445)
+ o Fix compile on Snow Leopard with gcc warnings enabled (70cdfe4 Sebastian Hahn)
+ o Only define _GNU_SOURCE if it is not already defined. (ea6b1df Joachim Bauch)
+ o Update sample/signal-test.c to use newer APIs and not leak. (f6430ac Evan Jones)
+ o Fix a segfault when writing a very fragmented evbuffer onto an SSL (a6adeca Joachim Bauch)
+ o Fix a segfault when freeing SSL bufferevents in an unusual order (a773df5 Joachim Bauch)
+ o Drop install-sh from our git repo: a mismatched version could break "make dist" (6799527)
+ o Set all instances of the version number correctly. (5a112d3)
+ o Fix a few locking issues on windows. (c51bb3c unknown)
+ o Use evutil_socket_t, not int, when logging socket errors. (292467c)
+ o Fix up behavior of never-defered callbacks a little (390e056)
+ o Replace some cases of uint32_t with ev_uint32_t. (a47d88d)
+ o Fix compilation of devpoll.c by adding missing thread includes. (fee2c77 Dagobert Michelsen)
+ o Make evutil_make_socket_nonblocking() leave any other flags alone. (4c8b7cd Jardel Weyrich)
+ o Fix an fd leak in evconnlistener_new_bind(). (24fb502 Jardel Weyrich)
+ o Fix a bogus free in evutil_new_addrinfo() (0d64051 Jardel Weyrich)
+ o Adjusted fcntl() retval comparison on evutil_make_socket_nonblocking(). (4df7dbc Jardel Weyrich)
+ o Fix the code that allowed DNS options to not end with : (ee4953f)
+ o Fix crash bugs when a bufferevent's eventcb is not set. (2e8eeea)
+ o Fix test-ratelim compilation on Linux. (885b427)
+ o Fix compilation of rate-limiting code on win32. (165d30e)
+ o Eradicated the last free() call. Let mm_free() take care of deallocation. (0546ce1 Jardel Weyrich)
+ o Fix byte counts when mixing deferred and non-deferred evbuffer callbacks. (29151e6)
+ o Fixed a memory leak on windows threads implementation. The CRITICAL_SECTION was not being free'd in evthread_win32_lock_free(). (2f33e00 Jardel Weyrich)
+ o Fixed a fd leak in start_accepting(), plus cosmetic changes (4367a33 Jardel Weyrich)
+ o Improved error handling in evconnlistener_new_async(). Also keeping the fd open because it is not opened by this function, so the caller is responsible for closing it. Additionally, since evconnlistener_new_bind() creates a socket and passes it to the function above, it required error checking to close the same socket. (fec66f9 Jardel Weyrich)
+ o Don't use a bind address for nameservers on loopback (8d4aaf9)
+ o Fix compilation of rate-limit code when threading support is disabled (97a8c79)
+ o Detect setenv/unsetenv; skip main/base_environ test if we can't fake them. (7296971)
+ o Check more internal event_add() calls for failure (ff3f6cd)
+ o Fix windows and msvc build (5c7a7bc)
+ o Call event_debug_unassign on internal events (a19b4a0)
+ o Try to fix a warning in hash_debug_entry (137f2c6)
+ o Fix a dumb typo in ev_intptr_t definitions. (27c9a40)
+ o do not fail while sending on http connections the client closed. (93d7369)
+ o make evhttp_send() safe against terminated connections, too (3978180)
+ o Make Libevent 1.4.12 build on win32 with Unicode enabled. (000a33e Brodie Thiesfield)
+ o Fix some additional -DUNICODE issues on win32. (a7a9431)
+ o Add a check to make soure our EVUTIL_AI flags do not conflict with the native ones (c18490e)
+ o Always use our own gai_strerror() replacement. (6810bdb)
+ o Make RNG work when we have arc4random() but not arc4random_buf() (4ec8fea)
+ o validate close cb on server when client connection closes (2f782af)
+ o Fix two unlocked reads in evbuffer. (7116bf2)
+ o When working without a current event base, don't try to use IOCP listeners (cb52838)
+ o Fix getpid() usage on Windows (ff2a134)
+ o Add a unit test for secure rng. (48a29b6)
+ o Add some headers to fix freebsd compilation (b72be50)
+ o When connect() succeeds immediately, don't invoke the callback immediately. (7515de9)
+ o Suspend read/write on bufferevents during hostname lookup (db08f64)
+ o Make bufferevent_free() clear all callbacks immediately. (b2fbeb3)
+ o Fix some race conditions in persistent events and event_reinit (e2642f0)
+ o Fix a bug in resetting timeouts on persistent events when IO triggers. (38ec0a7)
+ o Add a test for timeouts on filtering bufferevents. (c02bfe1)
+ o Add test for periodic timers that get activated for other reasons (8fcb7a1)
+ o Use new timeval diff comparison function in bufferevent test (f3dfe46)
+ o Delete stack-alloced event in new unit test before returning. (7ffd387)
+ o Fix mingw compilation (23170a6)
+ o Try to define a sane _EVENT_SIZEOF_SIZE_T for msvc compilation (1e14f82)
+ o Fix arc4random compilation on MSVC. (98edb89)
+ o deal with connect() failing immediately (7bc48bf)
+ o Small cleanups on freebsd-connect-refused patch. (57b7248)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Remove the contents of WIN32-Prj as unmaintained. (c69d5a5)
+ o Allow the user to redirect the verbose output of test/test.sh to a file (c382de6)
+ o Allow test.sh to be run as ./test/test.sh (7dfbe94)
+ o Never believe that we have pthreads on win32, even if gcc thinks we do. (78ed097)
+ o Make it compile under gcc --std=c89. (e2ca403)
+ o Fix a number of warnings from gcc -pedantic (918e9c5)
+ o Add the msvc-generated .lib files to .gitignore. (e244a2e)
+ o Add the "compile" script to gitignore. (1ba6bed)
+
+INTERNALS AND CODE CLEANUPS
+ o Add a .gitignore file. (ba34071)
+ o New EVTHREAD_TRY_LOCK function to try to grab a lock. (689fc09)
+ o Add the abilitity to mark some buffer callbacks as never-deferred. (438f9ed)
+ o Refactor our 'suspend operation' logic on bufferevents. (0d744aa)
+ o Simplify the read high-watermark checking. (5846bf6)
+ o Improve readability of evutil_unparse_protoname() (5a43df8 Jardel Weyrich)
+ o Expose our cached gettimeofday value with a new interface (47854a8)
+ o Whitespace fixes in test.sh (0b151a9)
+ o Enable branch-prediction hints with EVUTIL_UNLIKELY. (eaaf27f)
+ o Refactor code from evdns into a new internal "read a file" function. (0f7144f)
+ o Comestic changes in evconnlistener_new(), new_accepting_socket(), accepted_socket_invoke_user_cb() and iocp_listener_enable(). (510ab6b Jardel Weyrich)
+ o Add unit-test for bad_request bug fixed in 1.4 recently. (6cc79c6 Pavel Plesov) o Add a comment on evthread_enable_lock_debuging. (b9f43b2)
+ o Fix test.sh on shells without echo -n (94131e9)
+ o More unit tests for getaddrinfo_async: v4timeout and cancel. (a334b31)
+ o Make http use evconnlistener. (ec34533)
+ o move dns utility functions into a separate file so that we can use them for http testing (b822639)
+ o add a test for evhttp_connection_base_new with a dns_base (26714ca)
+ o forgot to add void to test function (78a50fe)
+ o Add a forgotten header (changelist-internal.h) (4b9f307)
+ o Remove some commented-out code in evutil (26e1b6f)
+ o Remove a needless include of rpc_compat.h (70a4a3e)
+ o Use less memory for each entry in a hashtable (a66e947)
+ o Try to untangle the logic in server_port_flush(). (439aea0)
+ o Use ev_[u]intptr_t types in place of [u]intptr_t (cef61a2)
+ o Reduce windows header includes in our own headers. (da6135e)
+ o clean up terminate_chunked test (e8a9782)
+ o Increment the submicro version number. (63e868e)
+ o Update event-config.h version number to match configure.in (aae7db5)
+ o Clean up formatting: Disallow space-before-tab. (8fdf09c)
+ o Clean up formatting: use tabs, not 8-spaces, to indent. (e5bbd40)
+ o Clean up formatting: remove trailing spaces (e5cf987)
+ o Clean up formatting: function/keyword spacing consistency. (4faeaea)
+
+
+
+Changes in 2.0.3-alpha (20 Nov 2009):
+ o Add a new code to support SSL/TLS on bufferevents, using the OpenSSL library (where available).
+ o Fix a bug where we didn't allocate enough memory in event_get_supported_methods().
+ o Avoid segfault during failed allocation of locked evdns_base. (Found by Rocco Carbone.)
+ o Export new evutil_ascii_* functions to perform locale-independent character type operations.
+ o Try to compile better with MSVC: patches from Brodie Thiesfield
+ o New evconnlistener_get_fd function to expose a listener's associated socket.
+ o Expose an ev_socklen_t type for consistent use across platforms.
+ o Make bufferevent_socket_connect() work when the original fd was -1.
+ o Fix a bug in bufferevent_socket_connect() when the connection succeeds too quickly.
+ o Export an evutil_sockaddr_cmp() to compare to sockaddr objects for equality.
+ o Add a bufferevent_get_enabled() to tell what a bufferevent has been configured to do.
+ o Add an evbuffer_search_eol() function to locate the end of a line nondestructively.
+ o Add an evbuffer_search_range() function to search a bounded range of a buffer.
+ o Fix a rare crash bug in evdns.
+ o Have bufferevent_socket_connect() with no arguments put a bufferevent into connecting mode.
+ o Support sendfile on Solaris: patch from Caitlin Mercer.
+ o New functions to explicitly reference a socket used by an evhttp object. Patches from David Reiss.
+ o When we send a BEV_EVENT_CONNECTED to indicate connected status, we no longer invoke the write callback as well unless we actually wrote data too.
+ o If the kernel tells us that there are a negative number of bytes to read from a socket, do not believe it.  Fixes bug 2841177; found by Alexander Pronchenkov.
+ o Do not detect whether we have monotonic clock support every time a new event base is created: instead do it only once.  Patch taken from Chromium.
+ o Do not allocate the maximum event queue for the epoll backend at startup.  Instead, start out accepting 32 events at a time, and double the queue's size when it seems that the OS is generating events faster than we're requesting them.  Saves up to 374K per epoll-based event_base.  Resolves bug 2839240.
+ o Treat an event with a negative fd as valid but untriggerable by Libevent.  This is useful for applications that want to manually activate events.
+ o Fix compilation on Android, which forgot to define fd_mask in its sys/select.h
+ o Do not drop data from evbuffer when out of memory; reported by Jacek Masiulaniec
+ o New event_base_got_exit() and event_base_got_break() functions to tell whether an event loop exited because of an event_base_loopexit() or an event_base_loopbreak().  Patch from Ka-Hing Cheung.
+ o When adding or deleting an event from a non-main thread, only wake up the main thread when its behavior actually needs to change.
+ o Fix some bugs when using the old evdns interfaces to initialize the evdns module.
+ o Detect errors during bufferevent_connect().  Patch from Christopher Davis.
+ o Fix compilation for listener.h for C++ - missing extern "C".  Patch from Ferenc Szalai.
+ o Make the event_base_loop() family of functions respect thread-safety better.  This should clear up a few hard-to-debug race conditions.
+ o Fix a bug when using a specialized memory allocator on win32.
+ o Have the win32 select() backend label TCP-socket-connected events as EV_WRITE, not EV_READ.  This should bring it in line with the other backends, and improve portability.  Patch from Christopher Davis.
+ o Stop using enums as arguments or return values when what we mean is a bitfield of enum values.  C++ doesn't believe that you can OR two enum values together and get another enum, and C++ takes its typing seriously.  Patch from Christopher Davis.
+ o Add an API to replace all fatal calls to exit() with a user-provided panic function.
+ o Replace all assert() calls with a variant that is aware of the user-provided logging and panic functions.
+ o Add a return value to event_assign so that it can fail rather than asserting when the user gives it bad input.  event_set still dies on bad input.
+ o The event_base_new() and event_base_new_with_config() functions now never call exit() on failure.  For backward "compatibility", event_init() still does, but more consistently.
+ o Remove compat/sys/_time.h.  It interfered with system headers on HPUX, and its functionality has been subsumed by event2/util.h and util-internal.h.
+ o Add a new bufferevent_socket_connect_hostname() to encapsulate the resolve-then-connect operation.
+ o Build kqueue.c correctly on GNU/kFreeBSD platforms. Patch pulled upstream from Debian.
+ o Alternative queue-based timeout algorithm for programs that use a large number of timeouts with the same value.
+ o New event_base_config option to disable the timeval cache entirely.
+ o Make EV_PERSIST timeouts more accurate: schedule the next event based on the scheduled time of the previous event, not based on the current time.
+ o Allow http.c to handle cases where getaddrinfo returns an IPv6 address.  Patch from Ryan Phillips.
+ o Fix a problem with excessive memory allocation when using multiple event priorities.
+ o Default to using arc4random for DNS transaction IDs on systems that have it; from OpenBSD.
+ o Never check the environment when we're running setuid or setgid; from OpenBSD.
+ o Options passed to evdns_set_option() no longer need to end with a colon.
+ o Add an evutil_getaddrinfo() function to clone getaddrinfo on platforms that don't have it.
+ o Add an evdns_getaddrinfo() function to provide a nonblocking getaddrinfo using evdns, so programs can perform useful hostname lookup.
+ o Finally expose the IOCP-based bufferevent backend.  It passes its unit tests, but probably still has some bugs remaining.  Code by Nick Mathewson and Christopher Davis.
+ o Numerous other bugfixes.
+ o On FreeBSD and other OSes, connect can return ECONREFUSED immediately; instead of failing the function call, pretend with faileld in the callback.
+ o Fix a race condition in the pthreads test case; found by Nick Mathewson
+ o Remove most calls to event_err() in http and deal with memory errors instead
+
+
+
+Changes in 2.0.2-alpha (25 Jul 2009):
+ o Add a new flag to bufferevents to make all callbacks automatically deferred.
+ o Make evdns functionality locked, and automatically defer dns callbacks.
+ o Fix a possible free(NULL) when freeing an event_base with no signals.
+ o Add a flag to disable checking environment varibles when making an event_base
+ o Disallow setting less than 1 priority.
+ o Fix a bug when removing a timeout from the heap. [Patch from Marko Kreen]
+ o Use signal.h, not sys/signal.h. [Patch from mmadia]
+ o Try harder to build with certain older c99 compilers.
+ o Make sure that an event_config's flags field is always initialized to 0. [Bug report from Victor Goya]
+ o Avoid data corruption when reading data entirely into the second-to-last chain of an evbuffer. [Bug report from Victor Goya]
+ o Make sendfile work on FreeBSD
+ o Do not use vararg macros for accessing evrpc structures; this is not backwards compatible, but we did not promise any backwards compatibility for the rpc code.
+ o Actually define the event_config_set_flag() function.
+ o Try harder to compile with Visual C++.
+ o Move event_set() and its allies to event2/event_compat.h where they belong.
+ o Remove the event_gotsig code, which has long been deprecated and unused.
+ o Add an event_get_base() function to return the base assigned to an event.
+ o New function to automate connecting on a socket-based bufferevent.
+ o New functions to automate listening for incoming TCP connections.
+ o Do case-insensitive checks with a locale-independent comparison function.
+ o Rename the evbuffercb and everrorcb callbacks to bufferevent_data_cb and bufferevent_event_cb respectively.  The old names are available in bufferevent_compat.h.
+ o Rename the EVBUFFER_* codes used by bufferevent event callbacks to BEV_EVENT_*, to avoid namespace collision with evbuffer flags.  The old names are available in bufferevent_compat.h.
+ o Move the EVBUFFER_INPUT and EVBUFFER_OUTPUT macros to bufferevent_compat.h
+ o Add a bufferevent_getfd() function to mirror bufferevent_setfd()
+ o Make bufferevent_setfd() return an error code if the operation is not successful.
+ o Shave 22 bytes off struct event on 32-bit platforms by shrinking and re-ordering fields.  The savings on 64-bit platforms is likely higher.
+ o Cap the maximum number of priorities at 256.
+ o Change the semantics of evbuffer_cb_set_flags() to be set-flag only; add a new evbuffer_cb_clear_flags() to remove set flags.
+ o Change the interface of evbuffer_add_reference so that the cleanup callback gets more information
+ o Revise the new evbuffer_reserve_space/evbuffer_commit_space() interfaces so that you can use them without causing extraneous copies or leaving gaps in the evbuffer.
+ o Add a new evbuffer_peek() interface to inspect data in an evbuffer without removing it.
+ o Fix a deadlock when suspending reads in a bufferevent due to a full buffer. (Spotted by Joachim Bauch.)
+ o Fix a memory error when freeing a thread-enabled event base with registered events. (Spotted by Joachim Bauch.)
+ o Try to contain degree of failure when running on a win32 version so heavily firewalled that we can't fake a socketpair.
+ o Activate fd events in a pseudorandom order with O(N) backends, so that we don't systematically favor low fds (select) or earlier-added fds (poll, win32).
+ o Replace some read()/write() instances with send()/recv() to work properly on win32.
+ o Set truncated flag correctly in evdns server replies.
+ o Raise RpcGenError in event_rpcgen.py; from jmanison and Zack Weinberg
+ o Fix preamble of rpcgen-generated files to rely on event2 includes; based on work by jmansion; patch from Zack Weinberg.
+ o Allow specifying the output filename for rpcgen; based on work by jmansion; patch from Zack Weinberg.
+ o Allow C identifiers as struct names; allow multiple comments in .rpc files; from Zack Weinberg
+ o Mitigate a race condition when using socket bufferevents in multiple threads.
+ o Use AC_SEARCH_LIBS, not AC_CHECK_LIB to avoid needless library use.
+ o Do not allow event_del(ev) to return while that event's callback is executing in another thread.  This fixes a nasty race condition.
+ o event_get_supported_methods() now lists methods that have been disabled with the EVENT_NO* environment options.
+ o Rename encode_int[64] to evtag_encode_int[64] to avoid polluting the global namespace.  The old method names are still available as macros in event2/tag_compat.h.
+
+
+
+Changes in 2.0.1-alpha (17 Apr 2009):
+ o free minheap on event_base_free(); from Christopher Layne
+ o debug cleanups in signal.c; from Christopher Layne
+ o provide event_base_new() that does not set the current_base global
+ o bufferevent_write now uses a const source argument; report from Charles Kerr
+ o improve documentation on event_base_loopexit; patch from Scott Lamb
+ o New function, event_{base_}loopbreak.  Like event_loopexit, it makes an event loop stop executing and return.  Unlike event_loopexit, it keeps subsequent pending events from getting executed.  Patch from Scott Lamb
+ o Check return value of event_add in signal.c
+ o provide event_reinit() to reintialize an event_base after fork
+ o New function event_set_mem_functinons.  It allows the user to give libevent replacement functions to use for memory management in place of malloc(), free(), etc.  This should be generally useful for memory instrumentation, specialized allocators, and so on.
+ o The kqueue implementation now catches signals that are raised after event_add() is called but before the event_loop() call.  This makes it match the other implementations.
+ o The kqueue implementation now restores original signal handlers correctly when its signal events are removed.
+ o Check return value of event_add in signal.c
+ o Add a more powerful evbuffer_readln as a replacement for evbuffer_readline.  The new function handles more newline styles, and is more useful with buffers that may contain a nul characters.
+ o Do not mangle socket handles on 64-bit windows.
+ o The configure script now takes an --enable-gcc-warnigns option that turns on many optional gcc warnings.  (Nick has been building with these for a while, but they might be useful to other developers.)
+ o move EV_PERSIST handling out of the event backends
+ o small improvements to evhttp documentation
+ o always generate Date and Content-Length headers for HTTP/1.1 replies
+ o set the correct event base for HTTP close events
+ o When building with GCC, use the "format" attribute to verify type correctness of calls to printf-like functions.
+ o Rewrite win32.c backend to be O(n lg n) rather than O(n^2).
+ o Removed obsoleted recalc code
+ o support for 32-bit tag numbers in rpc structures; this is wire compatible, but changes the API slightly.
+ o pull setters/getters out of RPC structures into a base class to which we just need to store a pointer; this reduces the memory footprint of these structures.
+ o prefix {encode,decode}_tag functions with evtag to avoid collisions
+ o fix a bug with event_rpcgen for integers
+ o Correctly handle DNS replies with no answers set (Fixes bug 1846282)
+ o add -Wstrict-aliasing to warnings and more cleanup
+ o removed linger from http server socket; reported by Ilya Martynov
+ o event_rpcgen now allows creating integer arrays
+ o support string arrays in event_rpcgen
+ o change evrpc hooking to allow pausing of RPCs; this will make it possible for the hook to do some meaning ful work; this is not backwards compatible.
+ o allow an http request callback to take ownership of a request structure
+ o allow association of meta data with RPC requests for hook processing
+ o associate more context for hooks to query such as the connection object
+ o remove pending timeouts on event_base_free()
+ o also check EAGAIN for Solaris' event ports; from W.C.A. Wijngaards
+ o devpoll and evport need reinit; tested by W.C.A Wijngaards
+ o event_base_get_method; from Springande Ulv
+ o Send CRLF after each chunk in HTTP output, for compliance with RFC2626.  Patch from "propanbutan".  Fixes bug 1894184.
+ o Add a int64_t parsing function, with unit tests, so we can apply Scott Lamb's fix to allow large HTTP values.
+ o Use a 64-bit field to hold HTTP content-lengths.  Patch from Scott Lamb.
+ o Allow regression code to build even without Python installed
+ o remove NDEBUG ifdefs from evdns.c
+ o detect integer types properly on platforms without stdint.h
+ o udpate documentation of event_loop and event_base_loop; from Tani Hosokawa.
+ o simplify evbuffer by removing orig_buffer
+ o do not insert event into list when evsel->add fails
+ o add support for PUT/DELETE requests; from Josh Rotenberg
+ o introduce evhttp_accept_socket() to accept from an already created socket
+ o include Content-Length in reply for HTTP/1.0 requests with keep-alive
+ o increase listen queue for http sockets to 128; if that is not enough the evhttp_accpet_socket() api can be used with a prepared socket.
+ o Patch from Tani Hosokawa: make some functions in http.c threadsafe.
+ o test support for PUT/DELETE requests; from Josh Rotenberg
+ o rewrite of the evbuffer code to reduce memory copies
+ o Some older Solaris versions demand that _REENTRANT be defined to get strtok_r(); do so.
+ o Do not free the kqop file descriptor in other processes, also allow it to be 0; from Andrei Nigmatulin
+ o Provide OpenSSL style support for multiple threads accessing the same event_base
+ o make event_rpcgen.py generate code include event-config.h; reported by Sam Banks.
+ o switch thread support so that locks get allocated as they are needed.
+ o make event methods static so that they are not exported; from Andrei Nigmatulin
+ o make RPC replies use application/octet-stream as mime type
+ o do not delete uninitialized timeout event in evdns
+ o Correct the documentation on buffer printf functions.
+ o Don't warn on unimplemented epoll_create(): this isn't a problem, just a reason to fall back to poll or select.
+ o Correctly handle timeouts larger than 35 minutes on Linux with epoll.c.  This is probably a kernel defect, but we'll have to support old kernels anyway even if it gets fixed.
+ o Make name_from_addr() threadsafe in http.c
+ o Add new thread-safe interfaces to evdns functions.
+ o Make all event_tagging interfaces threadsafe.
+ o Rename internal memory management functions.
+ o New functions (event_assign, event_new, event_free) for use by apps that want to be safely threadsafe, or want to remain ignorant of the contents of struct event.
+ o introduce bufferevent_read_buffer; allows reading without memory copy.
+ o expose bufferevent_setwatermark via header files and fix high watermark on read
+ o fix a bug in buffrevent read water marks and add a test for them
+ o fix a bug in which bufferevent_write_buffer would not schedule a write event
+ o provide bufferevent_input and bufferevent_output without requiring knowledge of the structure
+ o introduce bufferevent_setcb and bufferevent_setfd to allow better manipulation of bufferevents
+ o convert evhttp_connection to use bufferevents.
+ o use libevent's internal timercmp on all platforms, to avoid bugs on old platforms where timercmp(a,b,<=) is buggy.
+ o Remove the never-exported, never-used evhttp_hostportfile function.
+ o Support input/output filters for bufferevents; somewhat similar to libio's model.  This will allow us to implement SSL, compression, etc, transparently to users of bufferevents such as the http layer.
+ o allow connections to be removed from an rpc pool
+ o add new evtimer_assign, signal_assign, evtimer_new, and signal_new functions to manipulate timer and signal events, analagous to the now-recommended event_assign and event_new
+ o switch internal uses of event_set over to use event_assign.
+ o introduce evbuffer_contiguous_space() api that tells a user how much data is available in the first buffer chain
+ o introduce evbuffer_reserve_space() and evbuffer_commit_space() to make processing in filters more efficient.
+ o reduce system calls for getting current time by caching it.
+ o separate signal events from io events; making the code less complex.
+ o support for periodic timeouts
+ o support for virtual HTTP hosts.
+ o turn event_initialized() into a function, and add function equivalents to EVENT_SIGNAL and EVENT_FD so that people don't need to include event_struct.h
+ o Build test directory correctly with CPPFLAGS set.
+ o Provide an API for retrieving the supported event mechanisms.
+ o event_base_new_with_config() and corresponding config APIs.
+ o migrate the evhttp header to event2/ but accessors are still missing.
+ o deprecate timeout_* event functions by moving them to event_compat.h
+ o Move        windows gettimeofday replacement into a new evutil_gettimeofday().
+ o Make configure script work on IRIX.
+ o provide a method for canceling ongoing http requests.
+ o Make vsnprintf() returns consistent on win32.
+ o Fix connection keep-alive behavior for HTTP/1.0
+ o Fix use of freed memory in event_reinit; pointed out by Peter Postma
+ o constify struct timeval * where possible
+ o make event_get_supported_methods obey environment variables
+ o support for edge-triggered events on epoll and kqueue backends: patch from Valery Kholodkov
+ o support for selecting event backends by their features, and for querying the features of a backend.
+ o change failing behavior of event_base_new_with_config: if a config is provided and no backend is selected, return NULL instead of aborting.
+ o deliver partial data to request callbacks when chunked callback is set even if there is no chunking on the http level; allows cancelation of requests from within the chunked callback; from Scott Lamb.
+ o allow min_heap_erase to be called on removed members; from liusifan.
+ o Rename INPUT and OUTPUT to EVRPC_INPUT and EVRPC_OUTPUT.  Retain INPUT/OUTPUT aliases on on-win32 platforms for backwards compatibility.
+ o Do not use SO_REUSEADDR when connecting
+ o Support 64-bit integers in RPC structs
+ o Correct handling of trailing headers in chunked replies; from Scott Lamb.
+ o Support multi-line HTTP headers; based on a patch from Moshe Litvin
+ o Reject negative Content-Length headers; anonymous bug report
+ o Detect CLOCK_MONOTONIC at runtime for evdns; anonymous bug report   
+ o Various HTTP correctness fixes from Scott Lamb
+ o Fix a bug where deleting signals with the kqueue backend would cause subsequent adds to fail
+ o Support multiple events listening on the same signal; make signals regular events that go on the same event queue; problem report by Alexander Drozdov.
+ o Fix a problem with epoll() and reinit; problem report by Alexander Drozdov. 
+ o Fix off-by-one errors in devpoll; from Ian Bell
+ o Make event_add not change any state if it fails; reported by Ian Bell.
+ o Fix a bug where headers arriving in multiple packets were not parsed; fix from Jiang Hong; test by me.
+ o Match the query in DNS replies to the query in the request; from Vsevolod Stakhov.
+ o Add new utility functions to correctly observe and log winsock errors.
+ o Do not remove Accept-Encoding header
+ o Clear the timer cache on entering the event loop; reported by Victor Chang
+ o Only bind the socket on connect when a local address has been provided; reported by Alejo Sanchez
+ o Allow setting of local port for evhttp connections to support millions of connections from a single system; from Richard Jones.
+ o Clear the timer cache when leaving the event loop; reported by Robin Haberkorn
+ o Fix a typo in setting the global event base; reported by lance.
+ o Set the 0x20 bit on outgoing alphabetic characters in DNS requests randomly, and insist on a match in replies.  This helps resist DNS poisoning attacks.
+ o Make the http connection close detection work properly with bufferevents and fix a potential memory leak associated with it.
+ o Restructure the event backends so that they do not need to keep track of events themselves, as a side effect multiple events can use the same fd or signal.
+ o Add generic implementations for parsing and emiting IPv6 addresses on platforms that do not have inet_ntop and/or inet_pton.
+ o Allow DNS servers that have IPv6 addresses.
+ o Add an evbuffer_write_atmost() function to write a limited number of bytes to an fd.
+ o Refactor internal notify-main-thread logic to prefer eventfd to pipe, then pipe to socketpair, and only use socketpairs as a last resort.
+ o Try harder to pack all evbuffer reads into as few chains as possible, using readv/WSARecv as appropriate.
+ o New evthread_use_windows_threads() and evthread_use_pthreads() functions to set up the evthread callbacks with reasonable defaults.
+ o Change the semantics of timeouts in conjunction with EV_PERSIST; timeouts in that case will now repeat until deleted.
+ o sendfile, mmap and memory reference support for evbuffers.
+ o New evutil_make_listen_socket_reuseable() to abstract SO_REUSEADDR.
+ o New bind-to option to allow DNS clients to bind to an arbitrary port for outgoing requests.
+ o evbuffers can now be "frozen" to prevent operations at one or both ends.
+ o Bufferevents now notice external attempts to add data to an inbuf or remove it from an outbuf, and stop them.
+ o Fix parsing of queries where the encoded queries contained \r, \n or +
+ o Do not allow internal events to starve lower-priority events.
+
+Changes in 1.4.0:
+ o allow \r or \n individually to separate HTTP headers instead of the standard "\r\n"; from Charles Kerr.
+ o demote most http warnings to debug messages
+ o Fix Solaris compilation; from Magne Mahre
+ o Add a "Date" header to HTTP responses, as required by HTTP 1.1.
+ o Support specifying the local address of an evhttp_connection using set_local_address
+ o Fix a memory leak in which failed HTTP connections whould not free the request object
+ o Make adding of array members in event_rpcgen more efficient, but doubling memory allocation
+ o Fix a memory leak in the DNS server
+ o Fix compilation when DNS_USE_OPENSSL_FOR_ID is enabled
+ o Fix buffer size and string generation in evdns_resolve_reverse_ipv6().
+ o Respond to nonstandard DNS queries with "NOTIMPL" rather than by ignoring them.
+ o In DNS responses, the CD flag should be preserved, not the TC flag.
+ o Fix http.c to compile properly with USE_DEBUG; from Christopher Layne
+ o Handle NULL timeouts correctly on Solaris; from Trond Norbye
+ o Recalculate pending events properly when reallocating event array on Solaris; from Trond Norbye
+ o Add Doxygen documentation to header files; from Mark Heily
+ o Add a evdns_set_transaction_id_fn() function to override the default
+   transaction ID generation code.
+ o Add an evutil module (with header evutil.h) to implement our standard cross-platform hacks, on the theory that somebody else would like to use them too.
+ o Fix signals implementation on windows.
+ o Fix http module on windows to close sockets properly.
+ o Make autogen.sh script run correctly on systems where /bin/sh isn't bash. (Patch from Trond Norbye, rewritten by Hagne Mahre and then Hannah Schroeter.)
+ o Skip calling gettime() in timeout_process if we are not in fact waiting for any events. (Patch from Trond Norbye)
+ o Make test subdirectory compile under mingw.
+ o Fix win32 buffer.c behavior so that it is correct for sockets (which do not like ReadFile and WriteFile).
+ o Make the test.sh script run unit tests for the evpoll method.
+ o Make the entire evdns.h header enclosed in "extern C" as appropriate.
+ o Fix implementation of strsep on platforms that lack it
+ o Fix implementation of getaddrinfo on platforms that lack it; mainly, this will make Windows http.c work better.  Original patch by Lubomir Marinov.
+ o Fix evport implementation: port_disassociate called on unassociated events resulting in bogus errors; more efficient memory management; from Trond Norbye and Prakash Sangappa
+ o support for hooks on rpc input and output; can be used to implement rpc independent processing such as compression or authentication.
+ o use a min heap instead of a red-black tree for timeouts; as a result finding the min is a O(1) operation now; from Maxim Yegorushkin
+ o associate an event base with an rpc pool
+ o added two additional libraries: libevent_core and libevent_extra in addition to the regular libevent.  libevent_core contains only the event core whereas libevent_extra contains dns, http and rpc support
+ o Begin using libtool's library versioning support correctly.  If we don't mess up, this will more or less guarantee binaries linked against old versions of libevent continue working when we make changes to libevent that do not break backward compatibility.
+ o Fix evhttp.h compilation when TAILQ_ENTRY is not defined.
+ o Small code cleanups in epoll_dispatch().
+ o Increase the maximum number of addresses read from a packet in evdns to 32.
+ o Remove support for the rtsig method: it hasn't compiled for a while, and nobody seems to miss it very much.  Let us know if there's a good reason to put it back in.
+ o Rename the "class" field in evdns_server_request to dns_question_class, so that it won't break compilation under C++.  Use a macro so that old code won't break.  Mark the macro as deprecated.
+ o Fix DNS unit tests so that having a DNS server with broken IPv6 support is no longer cause for aborting the unit tests.
+ o Make event_base_free() succeed even if there are pending non-internal events on a base.  This may still leak memory and fds, but at least it no longer crashes.
+ o Post-process the config.h file into a new, installed event-config.h file that we can install, and whose macros will be safe to include in header files.
+ o Remove the long-deprecated acconfig.h file.
+ o Do not require #include <sys/types.h> before #include <event.h>.
+ o Add new evutil_timer* functions to wrap (or replace) the regular timeval manipulation functions.
+ o Fix many build issues when using the Microsoft C compiler.
+ o Remove a bash-ism in autogen.sh
+ o When calling event_del on a signal, restore the signal handler's previous value rather than setting it to SIG_DFL. Patch from Christopher Layne.
+ o Make the logic for active events work better with internal events; patch from Christopher Layne.
+ o We do not need to specially remove a timeout before calling event_del; patch from Christopher Layne.
diff --git a/libevent/Doxyfile b/libevent/Doxyfile
new file mode 100644 (file)
index 0000000..5d3865e
--- /dev/null
@@ -0,0 +1,257 @@
+# Doxyfile 1.5.1
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+#       TAG = value [value, ...]
+# For lists items can also be appended using:
+#       TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded 
+# by quotes) that should identify the project.
+
+PROJECT_NAME           = libevent
+
+# Place all output under 'doxygen/'
+
+OUTPUT_DIRECTORY        = doxygen/
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen 
+# will interpret the first line (until the first dot) of a JavaDoc-style 
+# comment as the brief description. If set to NO, the JavaDoc 
+# comments will behave just like the Qt-style comments (thus requiring an 
+# explicit @brief command for a brief description.
+
+JAVADOC_AUTOBRIEF      = YES
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C 
+# sources only. Doxygen will then generate output that is more tailored for C. 
+# For instance, some of the names that are used will be different. The list 
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C  = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the 
+# brief documentation of file, namespace and class members alphabetically 
+# by member name. If set to NO (the default) the members will appear in 
+# declaration order.
+
+SORT_BRIEF_DOCS        = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag 
+# can be used to strip a user-defined part of the path. Stripping is 
+# only done if one of the specified strings matches the left-hand part of 
+# the path. The tag can be used to show relative paths in the file list. 
+# If left blank the directory from which doxygen is run is used as the 
+# path to strip.
+
+STRIP_FROM_PATH        = include/
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain 
+# documented source files. You may enter file names like "myfile.cpp" or 
+# directories like "/usr/src/myproject". Separate the files or directories 
+# with spaces.
+
+INPUT                  = \
+        include/event2/buffer.h \
+        include/event2/buffer_compat.h \
+        include/event2/bufferevent.h \
+        include/event2/bufferevent_compat.h \
+        include/event2/bufferevent_ssl.h \
+        include/event2/dns.h \
+        include/event2/dns_compat.h \
+        include/event2/event.h \
+        include/event2/event_compat.h \
+        include/event2/http.h \
+        include/event2/http_compat.h \
+        include/event2/listener.h \
+        include/event2/rpc.h \
+        include/event2/rpc_compat.h \
+        include/event2/tag.h \
+        include/event2/tag_compat.h \
+        include/event2/thread.h \
+        include/event2/util.h
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will 
+# generate HTML output.
+
+GENERATE_HTML          = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will 
+# generate Latex output.
+
+GENERATE_LATEX         = YES
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. 
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be 
+# invoked. If left blank `latex' will be used as the default command name.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to 
+# generate index for LaTeX. If left blank `makeindex' will be used as the 
+# default command name.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact 
+# LaTeX documents. This may be useful for small projects and may help to 
+# save some trees in general.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used 
+# by the printer. Possible values are: a4, a4wide, letter, legal and 
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE             = a4wide
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX 
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES         = 
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for 
+# the generated latex document. The header should contain everything until 
+# the first chapter. If it is left blank doxygen will generate a 
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER           = 
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated 
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will 
+# contain links (just like the HTML output) instead of page references 
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS         = NO
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of 
+# plain latex in the generated Makefile. Set this option to YES to get a 
+# higher quality PDF documentation.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. 
+# command to the generated LaTeX files. This will instruct LaTeX to keep 
+# running if errors occur, instead of asking the user for help. 
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE        = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not 
+# include the index chapters (such as File Index, Compound Index, etc.) 
+# in the output.
+
+LATEX_HIDE_INDICES     = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will 
+# generate man pages
+
+GENERATE_MAN           = NO
+
+# The MAN_EXTENSION tag determines the extension that is added to 
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output, 
+# then it will generate one additional man file for each entity 
+# documented in the real man page(s). These additional files 
+# only source the real man page, but without them the man command 
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS              = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor   
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will 
+# evaluate all C-preprocessor directives found in the sources and include 
+# files.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro 
+# names in the source code. If set to NO (the default) only conditional 
+# compilation will be performed. Macro expansion can be done in a controlled 
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES 
+# then the macro expansion is limited to the macros specified with the 
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files 
+# in the INCLUDE_PATH (see below) will be search if a #include is found.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that 
+# contain include files that are not input files but should be processed by 
+# the preprocessor.
+
+INCLUDE_PATH           = 
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard 
+# patterns (like *.h and *.hpp) to filter out the header-files in the 
+# directories. If left blank, the patterns specified with FILE_PATTERNS will 
+# be used.
+
+INCLUDE_FILE_PATTERNS  = 
+
+# The PREDEFINED tag can be used to specify one or more macro names that 
+# are defined before the preprocessor is started (similar to the -D option of 
+# gcc). The argument of the tag is a list of macros of the form: name 
+# or name=definition (no spaces). If the definition and the = are 
+# omitted =1 is assumed. To prevent a macro definition from being 
+# undefined via #undef or recursively expanded use the := operator 
+# instead of the = operator.
+
+PREDEFINED             = TAILQ_ENTRY RB_ENTRY _EVENT_DEFINED_TQENTRY _EVENT_IN_DOXYGEN
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then 
+# this tag can be used to specify a list of macro names that should be expanded. 
+# The macro definition that is found in the sources will be used. 
+# Use the PREDEFINED tag if you want to use a different macro definition.
+
+EXPAND_AS_DEFINED      = 
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then 
+# doxygen's preprocessor will remove all function-like macros that are alone 
+# on a line, have an all uppercase name, and do not end with a semicolon. Such 
+# function macros are typically used for boiler-plate code, and will confuse 
+# the parser if not removed.
+
+SKIP_FUNCTION_MACROS   = YES
diff --git a/libevent/LICENSE b/libevent/LICENSE
new file mode 100644 (file)
index 0000000..70d76b3
--- /dev/null
@@ -0,0 +1,74 @@
+Libevent is available for use under the following license, commonly known
+as the 3-clause (or "modified") BSD license:
+
+==============================
+Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. The name of the author may not be used to endorse or promote products
+   derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+==============================
+
+Portions of Libevent are based on works by others, also made available by
+them under the three-clause BSD license above.  The copyright notices are
+available in the corresponding source files; the license is as above.  Here's
+a list:
+
+log.c:
+   Copyright (c) 2000 Dug Song <dugsong@monkey.org>
+   Copyright (c) 1993 The Regents of the University of California.
+
+strlcpy.c:
+   Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+
+win32select.c:
+   Copyright (c) 2003 Michael A. Davis <mike@datanerds.net>
+
+evport.c:
+   Copyright (c) 2007 Sun Microsystems
+
+ht-internal.h:
+   Copyright (c) 2002 Christopher Clark
+
+minheap-internal.h:
+   Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com>
+
+==============================
+
+The arc4module is available under the following, sometimes called the
+"OpenBSD" license:
+
+   Copyright (c) 1996, David Mazieres <dm@uun.org>
+   Copyright (c) 2008, Damien Miller <djm@openbsd.org>
+
+   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.
+
diff --git a/libevent/Makefile.am b/libevent/Makefile.am
new file mode 100644 (file)
index 0000000..09505bd
--- /dev/null
@@ -0,0 +1,253 @@
+# Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+# 'foreign' means that we're not enforcing GNU package rules strictly.
+# '1.7' means that we need automake 1.7 or later (and we do).
+AUTOMAKE_OPTIONS = foreign 1.7
+
+ACLOCAL_AMFLAGS = -I m4
+
+# This is the "Release" of the Libevent ABI.  It takes precedence over
+# the VERSION_INFO, so that two versions of Libevent with the same
+# "Release" are never binary-compatible.
+#
+# This number incremented once for the 2.0 release candidate, and
+# will increment for each series until we revise our interfaces enough
+# that we can seriously expect ABI compatibility between series.
+#
+RELEASE = -release 2.0
+
+# This is the version info for the libevent binary API.  It has three
+# numbers:
+#   Current  -- the number of the binary API that we're implementing
+#   Revision -- which iteration of the implementation of the binary
+#               API are we supplying?
+#   Age      -- How many previous binary API versions do we also
+#               support?
+#
+# To increment a VERSION_INFO (current:revision:age):
+#    If the ABI didn't change:
+#        Return (current:revision+1:age)
+#    If the ABI changed, but it's backward-compatible:
+#        Return (current+1:0:age+1)
+#    If the ABI changed and it isn't backward-compatible:
+#        Return (current+1:0:0)
+#
+# Once an RC is out, DO NOT MAKE ANY ABI-BREAKING CHANGES IN THAT SERIES
+# UNLESS YOU REALLY REALLY HAVE TO.
+VERSION_INFO = 6:6:1
+
+# History:          RELEASE    VERSION_INFO
+#  2.0.1-alpha --     2.0        1:0:0
+#  2.0.2-alpha --                2:0:0
+#  2.0.3-alpha --                2:0:0  (should have incremented; didn't.)
+#  2.0.4-alpha --                3:0:0
+#  2.0.5-beta  --                4:0:0
+#  2.0.6-rc    --     2.0        2:0:0
+#  2.0.7-rc    --     2.0        3:0:1
+#  2.0.8-rc    --     2.0        4:0:2
+#  2.0.9-rc    --     2.0        5:0:0 (ABI changed slightly)
+#  2.0.10-stable--    2.0        5:1:0 (No ABI change)
+#  2.0.11-stable--    2.0        6:0:1 (ABI changed, backward-compatible)
+#  2.0.12-stable--    2.0        6:1:1 (No ABI change)
+#  2.0.13-stable--    2.0        6:2:1 (No ABI change)
+#  2.0.14-stable--    2.0        6:3:1 (No ABI change)
+#  2.0.15-stable--    2.0        6:3:1 (Forgot to update :( )
+#  2.0.16-stable--    2.0        6:4:1 (No ABI change)
+#  2.0.17-stable--    2.0        6:5:1 (No ABI change)
+#  2.0.18-stable--    2.0        6:6:1 (No ABI change)
+#
+# For Libevent 2.1:
+#  2.1.1-alpha --     2.1        1:0:0
+
+
+# ABI version history for this package effectively restarts every time
+# we change RELEASE.  Version 1.4.x had RELEASE of 1.4.
+#
+# Ideally, we would not be using RELEASE at all; instead we could just
+# use the VERSION_INFO field to label our backward-incompatible ABI
+# changes, and those would be few and far between.  Unfortunately,
+# Libevent still exposes far too many volatile structures in its
+# headers, so we pretty much have to assume that most development
+# series will break ABI compatibility.  For now, it's simplest just to
+# keep incrementing the RELEASE between series and resetting VERSION_INFO.
+#
+# Eventually, when we get to the point where the structures in the
+# headers are all non-changing (or not there at all!), we can shift to
+# a more normal worldview where backward-incompatible ABI changes are
+# nice and rare.  For the next couple of years, though, 'struct event'
+# is user-visible, and so we can pretty much guarantee that release
+# series won't be binary-compatible.
+
+if INSTALL_LIBEVENT
+dist_bin_SCRIPTS = event_rpcgen.py
+endif
+
+pkgconfigdir=$(libdir)/pkgconfig
+LIBEVENT_PKGCONFIG=libevent.pc
+
+# These sources are conditionally added by configure.in or conditionally
+# included from other files.
+PLATFORM_DEPENDENT_SRC = \
+       epoll_sub.c \
+       arc4random.c
+
+EXTRA_DIST = \
+       LICENSE \
+       autogen.sh \
+       event_rpcgen.py \
+       libevent.pc.in \
+       Doxyfile \
+       whatsnew-2.0.txt \
+       Makefile.nmake test/Makefile.nmake \
+       $(PLATFORM_DEPENDENT_SRC)
+
+LIBEVENT_LIBS_LA = libevent.la libevent_core.la libevent_extra.la
+if PTHREADS
+LIBEVENT_LIBS_LA += libevent_pthreads.la
+LIBEVENT_PKGCONFIG += libevent_pthreads.pc
+endif
+if OPENSSL
+LIBEVENT_LIBS_LA += libevent_openssl.la
+LIBEVENT_PKGCONFIG += libevent_openssl.pc
+endif
+
+if INSTALL_LIBEVENT
+lib_LTLIBRARIES = $(LIBEVENT_LIBS_LA)
+pkgconfig_DATA = $(LIBEVENT_PKGCONFIG)
+else
+noinst_LTLIBRARIES =  $(LIBEVENT_LIBS_LA)
+endif
+
+SUBDIRS = . include sample test
+
+if BUILD_WIN32
+
+SYS_LIBS = -lws2_32 -lshell32 -ladvapi32
+SYS_SRC = win32select.c evthread_win32.c buffer_iocp.c event_iocp.c \
+       bufferevent_async.c
+SYS_INCLUDES = -IWIN32-Code
+
+else
+
+SYS_LIBS =
+SYS_SRC =
+SYS_INCLUDES =
+
+endif
+
+if SELECT_BACKEND
+SYS_SRC += select.c
+endif
+if POLL_BACKEND
+SYS_SRC += poll.c
+endif
+if DEVPOLL_BACKEND
+SYS_SRC += devpoll.c
+endif
+if KQUEUE_BACKEND
+SYS_SRC += kqueue.c
+endif
+if EPOLL_BACKEND
+SYS_SRC += epoll.c
+endif
+if EVPORT_BACKEND
+SYS_SRC += evport.c
+endif
+if SIGNAL_SUPPORT
+SYS_SRC += signal.c
+endif
+
+BUILT_SOURCES = ./include/event2/event-config.h
+
+./include/event2/event-config.h: config.h
+       @MKDIR_P@ ./include/event2
+       echo '/* event2/event-config.h' > $@
+       echo ' *' >> $@
+       echo ' * This file was generated by autoconf when libevent was built, and post-' >> $@
+       echo ' * processed by Libevent so that its macros would have a uniform prefix.' >> $@
+       echo ' *' >> $@
+       echo ' * DO NOT EDIT THIS FILE.' >> $@
+       echo ' *' >> $@
+       echo ' * Do not rely on macros in this file existing in later versions.'>> $@
+       echo ' */' >> $@
+       echo '#ifndef _EVENT2_EVENT_CONFIG_H_' >> $@
+       echo '#define _EVENT2_EVENT_CONFIG_H_' >> $@
+
+       sed -e 's/#define /#define _EVENT_/' \
+           -e 's/#undef /#undef _EVENT_/' \
+           -e 's/#ifndef /#ifndef _EVENT_/' < config.h >> $@
+       echo "#endif" >> $@
+
+CORE_SRC = event.c evthread.c buffer.c \
+       bufferevent.c bufferevent_sock.c bufferevent_filter.c \
+       bufferevent_pair.c listener.c bufferevent_ratelim.c \
+       evmap.c log.c evutil.c evutil_rand.c strlcpy.c $(SYS_SRC)
+EXTRA_SRC = event_tagging.c http.c evdns.c evrpc.c
+
+if BUILD_WITH_NO_UNDEFINED
+NO_UNDEFINED = -no-undefined
+MAYBE_CORE = libevent_core.la
+else
+NO_UNDEFINED =
+MAYBE_CORE =
+endif
+
+GENERIC_LDFLAGS = -version-info $(VERSION_INFO) $(RELEASE) $(NO_UNDEFINED)
+
+libevent_la_SOURCES = $(CORE_SRC) $(EXTRA_SRC)
+libevent_la_LIBADD = @LTLIBOBJS@ $(SYS_LIBS)
+libevent_la_LDFLAGS = $(GENERIC_LDFLAGS)
+
+libevent_core_la_SOURCES = $(CORE_SRC)
+libevent_core_la_LIBADD = @LTLIBOBJS@ $(SYS_LIBS)
+libevent_core_la_LDFLAGS = $(GENERIC_LDFLAGS)
+
+if PTHREADS
+libevent_pthreads_la_SOURCES = evthread_pthread.c
+libevent_pthreads_la_LIBADD = $(MAYBE_CORE)
+libevent_pthreads_la_LDFLAGS = $(GENERIC_LDFLAGS)
+endif
+
+libevent_extra_la_SOURCES = $(EXTRA_SRC)
+libevent_extra_la_LIBADD = $(MAYBE_CORE) $(SYS_LIBS)
+libevent_extra_la_LDFLAGS = $(GENERIC_LDFLAGS)
+
+if OPENSSL
+libevent_openssl_la_SOURCES = bufferevent_openssl.c
+libevent_openssl_la_LIBADD = $(MAYBE_CORE) $(OPENSSL_LIBS)
+libevent_openssl_la_LDFLAGS = $(GENERIC_LDFLAGS)
+endif
+
+noinst_HEADERS = util-internal.h mm-internal.h ipv6-internal.h \
+       evrpc-internal.h strlcpy-internal.h evbuffer-internal.h \
+       bufferevent-internal.h http-internal.h event-internal.h \
+       evthread-internal.h ht-internal.h defer-internal.h \
+       minheap-internal.h log-internal.h evsignal-internal.h evmap-internal.h \
+       changelist-internal.h iocp-internal.h \
+       ratelim-internal.h \
+       WIN32-Code/event2/event-config.h \
+       WIN32-Code/tree.h \
+       compat/sys/queue.h
+
+EVENT1_HDRS = event.h evhttp.h evdns.h evrpc.h evutil.h
+
+if INSTALL_LIBEVENT
+include_HEADERS = $(EVENT1_HDRS)
+else
+noinst_HEADERS += $(EVENT1_HDRS)
+endif
+
+AM_CPPFLAGS = -I$(srcdir)/compat -I$(srcdir)/include -I./include $(SYS_INCLUDES)
+
+verify: check
+
+doxygen: FORCE
+       doxygen $(srcdir)/Doxyfile
+FORCE:
+
+DISTCLEANFILES = *~ libevent.pc ./include/event2/event-config.h
+
diff --git a/libevent/Makefile.nmake b/libevent/Makefile.nmake
new file mode 100644 (file)
index 0000000..4cd04c1
--- /dev/null
@@ -0,0 +1,47 @@
+# WATCH OUT!  This makefile is a work in progress.  It is probably missing
+# tons of important things.  DO NOT RELY ON IT TO BUILD A GOOD LIBEVENT.
+
+# Needed for correctness
+CFLAGS=/IWIN32-Code /Iinclude /Icompat /DWIN32 /DHAVE_CONFIG_H /I.
+
+# For optimization and warnings
+CFLAGS=$(CFLAGS) /Ox /W3 /wd4996 /nologo
+
+# XXXX have a debug mode
+
+LIBFLAGS=/nologo
+
+CORE_OBJS=event.obj buffer.obj bufferevent.obj bufferevent_sock.obj \
+       bufferevent_pair.obj listener.obj evmap.obj log.obj evutil.obj \
+       strlcpy.obj signal.obj bufferevent_filter.obj evthread.obj \
+       bufferevent_ratelim.obj evutil_rand.obj
+WIN_OBJS=win32select.obj evthread_win32.obj buffer_iocp.obj \
+       event_iocp.obj bufferevent_async.obj
+EXTRA_OBJS=event_tagging.obj http.obj evdns.obj evrpc.obj
+
+ALL_OBJS=$(CORE_OBJS) $(WIN_OBJS) $(EXTRA_OBJS)
+STATIC_LIBS=libevent_core.lib libevent_extras.lib libevent.lib
+
+
+all: static_libs tests
+
+static_libs: $(STATIC_LIBS)
+
+libevent_core.lib: $(CORE_OBJS) $(WIN_OBJS)
+       lib $(LIBFLAGS) $(CORE_OBJS) $(WIN_OBJS) /out:libevent_core.lib 
+
+libevent_extras.lib: $(EXTRA_OBJS)
+       lib $(LIBFLAGS) $(EXTRA_OBJS) /out:libevent_extras.lib
+
+libevent.lib: $(CORE_OBJS) $(WIN_OBJS) $(EXTRA_OBJS)
+       lib $(LIBFLAGS) $(CORE_OBJS) $(EXTRA_OBJS) $(WIN_OBJS) /out:libevent.lib
+
+clean:
+       del $(ALL_OBJS)
+       del $(STATIC_LIBS)
+       cd test
+       $(MAKE) /F Makefile.nmake clean
+
+tests:
+       cd test
+       $(MAKE) /F Makefile.nmake
diff --git a/libevent/README b/libevent/README
new file mode 100644 (file)
index 0000000..9d695bb
--- /dev/null
@@ -0,0 +1,188 @@
+0. BUILDING AND INSTALLATION (Briefly)
+
+$ ./configure
+$ make
+$ make verify   # (optional)
+$ sudo make install
+
+1. BUILDING AND INSTALLATION (In Depth)
+
+To build libevent, type
+
+$ ./configure && make
+
+     (If you got libevent from the git repository, you will
+      first need to run the included "autogen.sh" script in order to
+      generate the configure script.)
+
+You can run the regression tests by running
+
+$ make verify
+
+Install as root via
+
+# make install
+
+Before, reporting any problems, please run the regression tests.
+
+To enable the low-level tracing build the library as:
+
+   CFLAGS=-DUSE_DEBUG ./configure [...]
+
+Standard configure flags should work.  In particular, see:
+
+   --disable-shared          Only build static libraries
+   --prefix                  Install all files relative to this directory.
+
+
+The configure script also supports the following flags:
+
+   --enable-gcc-warnings     Enable extra compiler checking with GCC.
+   --disable-malloc-replacement
+                             Don't let applications replace our memory
+                             management functions
+   --disable-openssl         Disable support for OpenSSL encryption.
+   --disable-thread-support  Don't support multithreaded environments.
+
+2. USEFUL LINKS:
+
+For the latest released version of Libevent, see the official website at
+http://monkey.org/~provos/libevent/ .
+
+There's a pretty good work-in-progress manual up at
+   http://www.wangafu.net/~nickm/libevent-book/ .
+
+For the latest development versions of Libevent, access our Git repository
+via
+   "git clone git://levent.git.sourceforge.net/gitroot/levent/libevent"
+
+You can browse the git repository online at
+http://levent.git.sourceforge.net/git/gitweb-index.cgi .
+
+To report bugs, request features, or submit patches to Libevent,
+use the Sourceforge trackers at
+https://sourceforge.net/tracker/?group_id=50884 .
+
+There's also a libevent-users mailing list for talking about Libevent
+use and development: http://archives.seul.org/libevent/users/
+
+3. ACKNOWLEDGMENTS
+
+The following people have helped with suggestions, ideas, code or
+fixing bugs:
+
+  Arno Bakker
+  Alejo
+  Weston Andros Adamson
+  William Ahern
+  Ivan Andropov
+  Sergey Avseyev
+  Avi Bab
+  Gilad Benjamini
+  Stas Bekman
+  Joachim Bauch
+  Denis Bilenko
+  Julien Blache
+  Kevin Bowling
+  Tomash Brechko
+  Kelly Brock
+  Ralph Castain
+  Adrian Chadd
+  Lawnstein Chan
+  Shuo Chen
+  Ka-Hing Cheung
+  Andrew Danforth
+  Ed Day
+  Christopher Davis
+  Mike Davis
+  Mihai Draghicioiu
+  Mark Ellzey
+  Shie Erlich
+  Leonid Evdokimov
+  Christophe Fillot
+  Mike Frysinger
+  Remi Gacogne
+  Alexander von Gernler
+  Artur Grabowski
+  Dave Hart
+  Greg Hazel
+  Michael Herf
+  Sebastian Hahn
+  Mark Heily
+  Greg Hewgill
+  Aaron Hopkins
+  Tani Hosokawa
+  Jamie Iles
+  Claudio Jeker
+  Evan Jones
+  George Kadianakis
+  Phua Keat
+  Kevin Ko
+  Brian Koehmstedt
+  Marko Kreen
+  Valery Kyholodov
+  Ross Lagerwall
+  Scott Lamb
+  Christopher Layne
+  Adam Langley
+  Philip Lewis
+  Zhou Li
+  David Libenzi
+  Yan Lin
+  Moshe Litvin
+  Mitchell Livingston
+  Hagne Mahre
+  Lubomir Marinov
+  Abilio Marques
+  Nick Mathewson
+  James Mansion
+  Nicholas Marriott
+  Andrey Matveev
+  Caitlin Mercer
+  Dagobert Michelsen
+  Mansour Moufid
+  Felix Nawothnig
+  Trond Norbye
+  Linus Nordberg
+  Richard Nyberg
+  Jon Oberheide
+  Phil Oleson
+  Dave Pacheco
+  Tassilo von Parseval
+  Catalin Patulea
+  Simon Perreault
+  Pierre Phaneuf
+  Ryan Phillips
+  Dimitre Piskyulev
+  Pavel Plesov
+  Jon Poland
+  Nate R
+  Robert Ransom
+  Bert JW Regeer
+  Peter Rosin
+  Maseeb Abdul Qadir
+  Wang Qin
+  Hanna Schroeter
+  Ralf Schmitt
+  Mike Smellie
+  Kevin Springborn
+  Harlan Stenn
+  Steve Snyder
+  Dug Song
+  Dongsheng Song
+  Hannes Sowa
+  Ferenc Szalai
+  Brodie Thiesfield
+  Jason Toffaletti
+  Gisle Vanem
+  Bas Verhoeven
+  Constantine Verutin
+  Colin Watt
+  Zack Weinberg
+  Jardel Weyrich
+  Alex
+  Taral
+  propanbutan
+  mmadia
+
+If we have forgotten your name, please contact us.
diff --git a/libevent/WIN32-Code/event2/event-config.h b/libevent/WIN32-Code/event2/event-config.h
new file mode 100644 (file)
index 0000000..67aaf60
--- /dev/null
@@ -0,0 +1,363 @@
+/* event2/event-config.h
+ *
+ * This file was generated by autoconf when libevent was built, and post-
+ * processed by Libevent so that its macros would have a uniform prefix.
+ *
+ * DO NOT EDIT THIS FILE.
+ *
+ * Do not rely on macros in this file existing in later versions.
+ */
+#ifndef _EVENT_CONFIG_H_
+#define _EVENT_CONFIG_H_
+/* config.h.  Generated by configure.  */
+/* config.h.in.  Generated from configure.in by autoheader.  */
+
+/* Define if libevent should not allow replacing the mm functions */
+/* #undef _EVENT_DISABLE_MM_REPLACEMENT */
+
+/* Define if libevent should not be compiled with thread support */
+/* #undef _EVENT_DISABLE_THREAD_SUPPORT */
+
+/* Define if clock_gettime is available in libc */
+/* #undef _EVENT_DNS_USE_CPU_CLOCK_FOR_ID */
+
+/* Define is no secure id variant is available */
+/* #define _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID 1 */
+#define _EVENT_DNS_USE_FTIME_FOR_ID 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+/* #undef _EVENT_HAVE_ARPA_INET_H */
+
+/* Define to 1 if you have the `clock_gettime' function. */
+/* #undef _EVENT_HAVE_CLOCK_GETTIME */
+
+/* Define if /dev/poll is available */
+/* #undef _EVENT_HAVE_DEVPOLL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+/* #undef _EVENT_HAVE_DLFCN_H */
+
+/* Define if your system supports the epoll system calls */
+/* #undef _EVENT_HAVE_EPOLL */
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+/* #undef _EVENT_HAVE_EPOLL_CTL */
+
+/* Define to 1 if you have the `eventfd' function. */
+/* #undef _EVENT_HAVE_EVENTFD */
+
+/* Define if your system supports event ports */
+/* #undef _EVENT_HAVE_EVENT_PORTS */
+
+/* Define to 1 if you have the `fcntl' function. */
+/* #undef _EVENT_HAVE_FCNTL */
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define _EVENT_HAVE_FCNTL_H 1
+
+/* Define to 1 if you have the `getaddrinfo' function. */
+#define _EVENT_HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define _EVENT_HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getprotobynumber' function. */
+#define _EVENT_HAVE_GETPROTOBYNUMBER 1
+
+/* Define to 1 if you have the `getservbyname' function. */
+#define _EVENT_HAVE_GETSERVBYNAME 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+/* #define _EVENT_HAVE_GETTIMEOFDAY 1 */
+
+/* Define to 1 if you have the `inet_aton' function. */
+/* #undef _EVENT_HAVE_INET_ATON */
+
+/* Define to 1 if you have the `inet_ntop' function. */
+/* #undef _EVENT_HAVE_INET_NTOP */
+
+/* Define to 1 if you have the `inet_pton' function. */
+/* #undef _EVENT_HAVE_INET_PTON */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+/* #define _EVENT_HAVE_INTTYPES_H 1 */
+
+/* Define to 1 if you have the `kqueue' function. */
+/* #undef _EVENT_HAVE_KQUEUE */
+
+/* Define if the system has zlib */
+/* #undef _EVENT_HAVE_LIBZ */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define _EVENT_HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+/* #undef _EVENT_HAVE_MMAP */
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+/* #undef _EVENT_HAVE_NETINET_IN6_H */
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+/* #undef _EVENT_HAVE_NETINET_IN_H */
+
+/* Define to 1 if you have the `pipe' function. */
+/* #undef _EVENT_HAVE_PIPE */
+
+/* Define to 1 if you have the `poll' function. */
+/* #undef _EVENT_HAVE_POLL */
+
+/* Define to 1 if you have the <poll.h> header file. */
+/* #undef _EVENT_HAVE_POLL_H */
+
+/* Define to 1 if you have the `port_create' function. */
+/* #undef _EVENT_HAVE_PORT_CREATE */
+
+/* Define to 1 if you have the <port.h> header file. */
+/* #undef _EVENT_HAVE_PORT_H */
+
+/* Define if you have POSIX threads libraries and header files. */
+/* #undef _EVENT_HAVE_PTHREAD */
+
+/* Define if we have pthreads on this system */
+/* #undef _EVENT_HAVE_PTHREADS */
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+/* #undef _EVENT_HAVE_SA_FAMILY_T */
+
+/* Define to 1 if you have the `select' function. */
+/* #undef _EVENT_HAVE_SELECT */
+
+/* Define to 1 if you have the `sendfile' function. */
+/* #undef _EVENT_HAVE_SENDFILE */
+
+/* Define if F_SETFD is defined in <fcntl.h> */
+/* #undef _EVENT_HAVE_SETFD */
+
+/* Define to 1 if you have the `sigaction' function. */
+/* #undef _EVENT_HAVE_SIGACTION */
+
+/* Define to 1 if you have the `signal' function. */
+#define _EVENT_HAVE_SIGNAL 1
+
+/* Define to 1 if you have the `splice' function. */
+/* #undef _EVENT_HAVE_SPLICE */
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#define _EVENT_HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define _EVENT_HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+/* #define _EVENT_HAVE_STDINT_H 1 */
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define _EVENT_HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define _EVENT_HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define _EVENT_HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+/* #undef _EVENT_HAVE_STRLCPY */
+
+/* Define to 1 if you have the `strsep' function. */
+/* #undef _EVENT_HAVE_STRSEP */
+
+/* Define to 1 if you have the `strtok_r' function. */
+/* #undef _EVENT_HAVE_STRTOK_R */
+
+/* Define to 1 if you have the `strtoll' function. */
+/* #define _EVENT_HAVE_STRTOLL 1 */
+
+#define _EVENT_HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct in6_addr'. */
+#define _EVENT_HAVE_STRUCT_IN6_ADDR 1
+
+/* Define to 1 if `s6_addr16' is member of `struct in6_addr'. */
+#define _EVENT_HAVE_STRUCT_IN6_ADDR_S6_ADDR16 1
+
+/* Define to 1 if `s6_addr32' is member of `struct in6_addr'. */
+#define _EVENT_HAVE_STRUCT_IN6_ADDR_S6_ADDR32 1
+
+/* Define to 1 if the system has the type `struct sockaddr_in6'. */
+#define _EVENT_HAVE_STRUCT_SOCKADDR_IN6 1
+
+/* Define to 1 if `sin6_len' is member of `struct sockaddr_in6'. */
+/* #undef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */
+
+/* Define to 1 if `sin_len' is member of `struct sockaddr_in'. */
+/* #undef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define _EVENT_HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if you have the <sys/devpoll.h> header file. */
+/* #undef _EVENT_HAVE_SYS_DEVPOLL_H */
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+/* #undef _EVENT_HAVE_SYS_EPOLL_H */
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+/* #undef _EVENT_HAVE_SYS_EVENTFD_H */
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+/* #undef _EVENT_HAVE_SYS_EVENT_H */
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+/* #undef _EVENT_HAVE_SYS_IOCTL_H */
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+/* #undef _EVENT_HAVE_SYS_MMAN_H */
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+/* #define _EVENT_HAVE_SYS_PARAM_H 1 */
+
+/* Define to 1 if you have the <sys/queue.h> header file. */
+/* #undef _EVENT_HAVE_SYS_QUEUE_H */
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+/* #undef _EVENT_HAVE_SYS_SELECT_H */
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+/* #undef _EVENT_HAVE_SYS_SENDFILE_H */
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+/* #undef _EVENT_HAVE_SYS_SOCKET_H */
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define _EVENT_HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+/* #define _EVENT_HAVE_SYS_TIME_H 1 */
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define _EVENT_HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+/* #undef _EVENT_HAVE_SYS_UIO_H */
+
+/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
+/* #undef _EVENT_HAVE_TAILQFOREACH */
+
+/* Define if timeradd is defined in <sys/time.h> */
+/* #undef _EVENT_HAVE_TIMERADD */
+
+/* Define if timerclear is defined in <sys/time.h> */
+#define _EVENT_HAVE_TIMERCLEAR 1
+
+/* Define if timercmp is defined in <sys/time.h> */
+#define _EVENT_HAVE_TIMERCMP 1
+
+/* Define if timerisset is defined in <sys/time.h> */
+#define _EVENT_HAVE_TIMERISSET 1
+
+/* Define to 1 if the system has the type `uint16_t'. */
+/* #define _EVENT_HAVE_UINT16_T 1 */
+
+/* Define to 1 if the system has the type `uint32_t'. */
+/* #define _EVENT_HAVE_UINT32_T 1 */
+
+/* Define to 1 if the system has the type `uint64_t'. */
+/* #define _EVENT_HAVE_UINT64_T 1 */
+
+/* Define to 1 if the system has the type `uint8_t'. */
+/* #define _EVENT_HAVE_UINT8_T 1 */
+
+/* Define to 1 if you have the <unistd.h> header file. */
+/* #define _EVENT_HAVE_UNISTD_H 1 */
+
+/* Define to 1 if you have the `vasprintf' function. */
+/* #undef _EVENT_HAVE_VASPRINTF */
+
+/* Define if kqueue works correctly with pipes */
+/* #undef _EVENT_HAVE_WORKING_KQUEUE */
+
+/* Numeric representation of the version */
+#define _EVENT_NUMERIC_VERSION 0x02001200
+
+/* Name of package */
+#define _EVENT_PACKAGE "libevent"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define _EVENT_PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define _EVENT_PACKAGE_NAME ""
+
+/* Define to the full name and version of this package. */
+#define _EVENT_PACKAGE_STRING ""
+
+/* Define to the one symbol short name of this package. */
+#define _EVENT_PACKAGE_TARNAME ""
+
+/* Define to the version of this package. */
+#define _EVENT_PACKAGE_VERSION ""
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+   your system. */
+/* #undef _EVENT_PTHREAD_CREATE_JOINABLE */
+
+/* The size of a `int', as computed by sizeof. */
+#define _EVENT_SIZEOF_INT 4
+
+/* The size of a `long', as computed by sizeof. */
+#define _EVENT_SIZEOF_LONG 4
+
+/* The size of a `long long', as computed by sizeof. */
+#define _EVENT_SIZEOF_LONG_LONG 8
+
+/* The size of a `short', as computed by sizeof. */
+#define _EVENT_SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#ifdef _WIN64
+#define _EVENT_SIZEOF_SIZE_T 8
+#else
+#define _EVENT_SIZEOF_SIZE_T 4
+#endif
+
+/* The size of `void *', as computed by sizeof. */
+#ifdef _WIN64
+#define _EVENT_SIZEOF_VOID_P 8
+#else
+#define _EVENT_SIZEOF_VOID_P 4
+#endif
+
+/* Define to 1 if you have the ANSI C header files. */
+#define _EVENT_STDC_HEADERS 1
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define _EVENT_TIME_WITH_SYS_TIME 1
+
+/* Version number of package */
+#define _EVENT_VERSION "2.0.18-stable"
+
+/* Define to appropriate substitue if compiler doesnt have __func__ */
+#define _EVENT___func__ __FUNCTION__
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef _EVENT_const */
+
+/* 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 _EVENT___cplusplus
+#define _EVENT_inline __inline
+#endif
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef _EVENT_pid_t */
+
+/* Define to `unsigned' if <sys/types.h> does not define. */
+/* #undef _EVENT_size_t */
+
+/* Define to unsigned int if you dont have it */
+#define _EVENT_socklen_t unsigned int
+
+/* Define to `int' if <sys/types.h> does not define. */
+#define _EVENT_ssize_t SSIZE_T
+
+#endif
diff --git a/libevent/WIN32-Code/tree.h b/libevent/WIN32-Code/tree.h
new file mode 100644 (file)
index 0000000..585618d
--- /dev/null
@@ -0,0 +1,1354 @@
+/*     $OpenBSD: tree.h,v 1.7 2002/10/17 21:51:54 art Exp $    */
+/*
+ * Copyright 2002 Niels Provos <provos@citi.umich.edu>
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef        _SYS_TREE_H_
+#define        _SYS_TREE_H_
+
+/*
+ * This file defines data structures for different types of trees:
+ * splay trees and red-black trees.
+ *
+ * A splay tree is a self-organizing data structure.  Every operation
+ * on the tree causes a splay to happen.  The splay moves the requested
+ * node to the root of the tree and partly rebalances it.
+ *
+ * This has the benefit that request locality causes faster lookups as
+ * the requested nodes move to the top of the tree.  On the other hand,
+ * every lookup causes memory writes.
+ *
+ * The Balance Theorem bounds the total access time for m operations
+ * and n inserts on an initially empty tree as O((m + n)lg n).  The
+ * amortized cost for a sequence of m accesses to a splay tree is O(lg n);
+ *
+ * A red-black tree is a binary search tree with the node color as an
+ * extra attribute.  It fulfills a set of conditions:
+ *     - every search path from the root to a leaf consists of the
+ *       same number of black nodes,
+ *     - each red node (except for the root) has a black parent,
+ *     - each leaf node is black.
+ *
+ * Every operation on a red-black tree is bounded as O(lg n).
+ * The maximum height of a red-black tree is 2lg (n+1).
+ */
+
+#define SPLAY_HEAD(name, type)                                         \
+struct name {                                                          \
+       struct type *sph_root; /* root of the tree */                   \
+}
+
+#define SPLAY_INITIALIZER(root)                                                \
+       { NULL }
+
+#define SPLAY_INIT(root) do {                                          \
+       (root)->sph_root = NULL;                                        \
+} while (0)
+
+#define SPLAY_ENTRY(type)                                              \
+struct {                                                               \
+       struct type *spe_left; /* left element */                       \
+       struct type *spe_right; /* right element */                     \
+}
+
+#define SPLAY_LEFT(elm, field)         (elm)->field.spe_left
+#define SPLAY_RIGHT(elm, field)                (elm)->field.spe_right
+#define SPLAY_ROOT(head)               (head)->sph_root
+#define SPLAY_EMPTY(head)              (SPLAY_ROOT(head) == NULL)
+
+/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
+#define SPLAY_ROTATE_RIGHT(head, tmp, field) do {                      \
+       SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field);  \
+       SPLAY_RIGHT(tmp, field) = (head)->sph_root;                     \
+       (head)->sph_root = tmp;                                         \
+} while (0)
+
+#define SPLAY_ROTATE_LEFT(head, tmp, field) do {                       \
+       SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field);  \
+       SPLAY_LEFT(tmp, field) = (head)->sph_root;                      \
+       (head)->sph_root = tmp;                                         \
+} while (0)
+
+#define SPLAY_LINKLEFT(head, tmp, field) do {                          \
+       SPLAY_LEFT(tmp, field) = (head)->sph_root;                      \
+       tmp = (head)->sph_root;                                         \
+       (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);         \
+} while (0)
+
+#define SPLAY_LINKRIGHT(head, tmp, field) do {                         \
+       SPLAY_RIGHT(tmp, field) = (head)->sph_root;                     \
+       tmp = (head)->sph_root;                                         \
+       (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);        \
+} while (0)
+
+#define SPLAY_ASSEMBLE(head, node, left, right, field) do {            \
+       SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \
+       SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\
+       SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \
+       SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \
+} while (0)
+
+/* Generates prototypes and inline functions */
+
+#define SPLAY_PROTOTYPE(name, type, field, cmp)                                \
+void name##_SPLAY(struct name *, struct type *);                       \
+void name##_SPLAY_MINMAX(struct name *, int);                          \
+struct type *name##_SPLAY_INSERT(struct name *, struct type *);                \
+struct type *name##_SPLAY_REMOVE(struct name *, struct type *);                \
+                                                                       \
+/* Finds the node with the same key as elm */                          \
+static __inline struct type *                                          \
+name##_SPLAY_FIND(struct name *head, struct type *elm)                 \
+{                                                                      \
+       if (SPLAY_EMPTY(head))                                          \
+               return(NULL);                                           \
+       name##_SPLAY(head, elm);                                        \
+       if ((cmp)(elm, (head)->sph_root) == 0)                          \
+               return (head->sph_root);                                \
+       return (NULL);                                                  \
+}                                                                      \
+                                                                       \
+static __inline struct type *                                          \
+name##_SPLAY_NEXT(struct name *head, struct type *elm)                 \
+{                                                                      \
+       name##_SPLAY(head, elm);                                        \
+       if (SPLAY_RIGHT(elm, field) != NULL) {                          \
+               elm = SPLAY_RIGHT(elm, field);                          \
+               while (SPLAY_LEFT(elm, field) != NULL) {                \
+                       elm = SPLAY_LEFT(elm, field);                   \
+               }                                                       \
+       } else                                                          \
+               elm = NULL;                                             \
+       return (elm);                                                   \
+}                                                                      \
+                                                                       \
+static __inline struct type *                                          \
+name##_SPLAY_MIN_MAX(struct name *head, int val)                       \
+{                                                                      \
+       name##_SPLAY_MINMAX(head, val);                                 \
+       return (SPLAY_ROOT(head));                                      \
+}
+
+/* Main splay operation.
+ * Moves node close to the key of elm to top
+ */
+#define SPLAY_GENERATE(name, type, field, cmp)                         \
+struct type *                                                          \
+name##_SPLAY_INSERT(struct name *head, struct type *elm)               \
+{                                                                      \
+    if (SPLAY_EMPTY(head)) {                                           \
+           SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL;    \
+    } else {                                                           \
+           int __comp;                                                 \
+           name##_SPLAY(head, elm);                                    \
+           __comp = (cmp)(elm, (head)->sph_root);                      \
+           if(__comp < 0) {                                            \
+                   SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\
+                   SPLAY_RIGHT(elm, field) = (head)->sph_root;         \
+                   SPLAY_LEFT((head)->sph_root, field) = NULL;         \
+           } else if (__comp > 0) {                                    \
+                   SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\
+                   SPLAY_LEFT(elm, field) = (head)->sph_root;          \
+                   SPLAY_RIGHT((head)->sph_root, field) = NULL;        \
+           } else                                                      \
+                   return ((head)->sph_root);                          \
+    }                                                                  \
+    (head)->sph_root = (elm);                                          \
+    return (NULL);                                                     \
+}                                                                      \
+                                                                       \
+struct type *                                                          \
+name##_SPLAY_REMOVE(struct name *head, struct type *elm)               \
+{                                                                      \
+       struct type *__tmp;                                             \
+       if (SPLAY_EMPTY(head))                                          \
+               return (NULL);                                          \
+       name##_SPLAY(head, elm);                                        \
+       if ((cmp)(elm, (head)->sph_root) == 0) {                        \
+               if (SPLAY_LEFT((head)->sph_root, field) == NULL) {      \
+                       (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\
+               } else {                                                \
+                       __tmp = SPLAY_RIGHT((head)->sph_root, field);   \
+                       (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\
+                       name##_SPLAY(head, elm);                        \
+                       SPLAY_RIGHT((head)->sph_root, field) = __tmp;   \
+               }                                                       \
+               return (elm);                                           \
+       }                                                               \
+       return (NULL);                                                  \
+}                                                                      \
+                                                                       \
+void                                                                   \
+name##_SPLAY(struct name *head, struct type *elm)                      \
+{                                                                      \
+       struct type __node, *__left, *__right, *__tmp;                  \
+       int __comp;                                                     \
+\
+       SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+       __left = __right = &__node;                                     \
+\
+       while ((__comp = (cmp)(elm, (head)->sph_root))) {               \
+               if (__comp < 0) {                                       \
+                       __tmp = SPLAY_LEFT((head)->sph_root, field);    \
+                       if (__tmp == NULL)                              \
+                               break;                                  \
+                       if ((cmp)(elm, __tmp) < 0){                     \
+                               SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+                               if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+                                       break;                          \
+                       }                                               \
+                       SPLAY_LINKLEFT(head, __right, field);           \
+               } else if (__comp > 0) {                                \
+                       __tmp = SPLAY_RIGHT((head)->sph_root, field);   \
+                       if (__tmp == NULL)                              \
+                               break;                                  \
+                       if ((cmp)(elm, __tmp) > 0){                     \
+                               SPLAY_ROTATE_LEFT(head, __tmp, field);  \
+                               if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+                                       break;                          \
+                       }                                               \
+                       SPLAY_LINKRIGHT(head, __left, field);           \
+               }                                                       \
+       }                                                               \
+       SPLAY_ASSEMBLE(head, &__node, __left, __right, field);          \
+}                                                                      \
+                                                                       \
+/* Splay with either the minimum or the maximum element                        \
+ * Used to find minimum or maximum element in tree.                    \
+ */                                                                    \
+void name##_SPLAY_MINMAX(struct name *head, int __comp) \
+{                                                                      \
+       struct type __node, *__left, *__right, *__tmp;                  \
+\
+       SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+       __left = __right = &__node;                                     \
+\
+       while (1) {                                                     \
+               if (__comp < 0) {                                       \
+                       __tmp = SPLAY_LEFT((head)->sph_root, field);    \
+                       if (__tmp == NULL)                              \
+                               break;                                  \
+                       if (__comp < 0){                                \
+                               SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+                               if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+                                       break;                          \
+                       }                                               \
+                       SPLAY_LINKLEFT(head, __right, field);           \
+               } else if (__comp > 0) {                                \
+                       __tmp = SPLAY_RIGHT((head)->sph_root, field);   \
+                       if (__tmp == NULL)                              \
+                               break;                                  \
+                       if (__comp > 0) {                               \
+                               SPLAY_ROTATE_LEFT(head, __tmp, field);  \
+                               if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+                                       break;                          \
+                       }                                               \
+                       SPLAY_LINKRIGHT(head, __left, field);           \
+               }                                                       \
+       }                                                               \
+       SPLAY_ASSEMBLE(head, &__node, __left, __right, field);          \
+}
+
+#define SPLAY_NEGINF   -1
+#define SPLAY_INF      1
+
+#define SPLAY_INSERT(name, x, y)       name##_SPLAY_INSERT(x, y)
+#define SPLAY_REMOVE(name, x, y)       name##_SPLAY_REMOVE(x, y)
+#define SPLAY_FIND(name, x, y)         name##_SPLAY_FIND(x, y)
+#define SPLAY_NEXT(name, x, y)         name##_SPLAY_NEXT(x, y)
+#define SPLAY_MIN(name, x)             (SPLAY_EMPTY(x) ? NULL  \
+                                       : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
+#define SPLAY_MAX(name, x)             (SPLAY_EMPTY(x) ? NULL  \
+                                       : name##_SPLAY_MIN_MAX(x, SPLAY_INF))
+
+#define SPLAY_FOREACH(x, name, head)                                   \
+       for ((x) = SPLAY_MIN(name, head);                               \
+            (x) != NULL;                                               \
+            (x) = SPLAY_NEXT(name, head, x))
+
+/* Macros that define a red-back tree */
+#define RB_HEAD(name, type)                                            \
+struct name {                                                          \
+       struct type *rbh_root; /* root of the tree */                   \
+}
+
+#define RB_INITIALIZER(root)                                           \
+       { NULL }
+
+#define RB_INIT(root) do {                                             \
+       (root)->rbh_root = NULL;                                        \
+} while (0)
+
+#define RB_BLACK       0
+#define RB_RED         1
+#define RB_ENTRY(type)                                                 \
+struct {                                                               \
+       struct type *rbe_left;          /* left element */              \
+       struct type *rbe_right;         /* right element */             \
+       struct type *rbe_parent;        /* parent element */            \
+       int rbe_color;                  /* node color */                \
+}
+
+#define RB_LEFT(elm, field)            (elm)->field.rbe_left
+#define RB_RIGHT(elm, field)           (elm)->field.rbe_right
+#define RB_PARENT(elm, field)          (elm)->field.rbe_parent
+#define RB_COLOR(elm, field)           (elm)->field.rbe_color
+#define RB_ROOT(head)                  (head)->rbh_root
+#define RB_EMPTY(head)                 (RB_ROOT(head) == NULL)
+
+#define RB_SET(elm, parent, field) do {                                        \
+       RB_PARENT(elm, field) = parent;                                 \
+       RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL;              \
+       RB_COLOR(elm, field) = RB_RED;                                  \
+} while (0)
+
+#define RB_SET_BLACKRED(black, red, field) do {                                \
+       RB_COLOR(black, field) = RB_BLACK;                              \
+       RB_COLOR(red, field) = RB_RED;                                  \
+} while (0)
+
+#ifndef RB_AUGMENT
+#define RB_AUGMENT(x)
+#endif
+
+#define RB_ROTATE_LEFT(head, elm, tmp, field) do {                     \
+       (tmp) = RB_RIGHT(elm, field);                                   \
+       if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) {             \
+               RB_PARENT(RB_LEFT(tmp, field), field) = (elm);          \
+       }                                                               \
+       RB_AUGMENT(elm);                                                \
+       if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {          \
+               if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))     \
+                       RB_LEFT(RB_PARENT(elm, field), field) = (tmp);  \
+               else                                                    \
+                       RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+       } else                                                          \
+               (head)->rbh_root = (tmp);                               \
+       RB_LEFT(tmp, field) = (elm);                                    \
+       RB_PARENT(elm, field) = (tmp);                                  \
+       RB_AUGMENT(tmp);                                                \
+       if ((RB_PARENT(tmp, field)))                                    \
+               RB_AUGMENT(RB_PARENT(tmp, field));                      \
+} while (0)
+
+#define RB_ROTATE_RIGHT(head, elm, tmp, field) do {                    \
+       (tmp) = RB_LEFT(elm, field);                                    \
+       if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) {             \
+               RB_PARENT(RB_RIGHT(tmp, field), field) = (elm);         \
+       }                                                               \
+       RB_AUGMENT(elm);                                                \
+       if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {          \
+               if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))     \
+                       RB_LEFT(RB_PARENT(elm, field), field) = (tmp);  \
+               else                                                    \
+                       RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+       } else                                                          \
+               (head)->rbh_root = (tmp);                               \
+       RB_RIGHT(tmp, field) = (elm);                                   \
+       RB_PARENT(elm, field) = (tmp);                                  \
+       RB_AUGMENT(tmp);                                                \
+       if ((RB_PARENT(tmp, field)))                                    \
+               RB_AUGMENT(RB_PARENT(tmp, field));                      \
+} while (0)
+
+/* Generates prototypes and inline functions */
+#define RB_PROTOTYPE(name, type, field, cmp)                           \
+void name##_RB_INSERT_COLOR(struct name *, struct type *);     \
+void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
+struct type *name##_RB_REMOVE(struct name *, struct type *);           \
+struct type *name##_RB_INSERT(struct name *, struct type *);           \
+struct type *name##_RB_FIND(struct name *, struct type *);             \
+struct type *name##_RB_NEXT(struct type *);                            \
+struct type *name##_RB_MINMAX(struct name *, int);                     \
+                                                                       \
+
+/* Main rb operation.
+ * Moves node close to the key of elm to top
+ */
+#define RB_GENERATE(name, type, field, cmp)                            \
+void                                                                   \
+name##_RB_INSERT_COLOR(struct name *head, struct type *elm)            \
+{                                                                      \
+       struct type *parent, *gparent, *tmp;                            \
+       while ((parent = RB_PARENT(elm, field)) &&                      \
+           RB_COLOR(parent, field) == RB_RED) {                        \
+               gparent = RB_PARENT(parent, field);                     \
+               if (parent == RB_LEFT(gparent, field)) {                \
+                       tmp = RB_RIGHT(gparent, field);                 \
+                       if (tmp && RB_COLOR(tmp, field) == RB_RED) {    \
+                               RB_COLOR(tmp, field) = RB_BLACK;        \
+                               RB_SET_BLACKRED(parent, gparent, field);\
+                               elm = gparent;                          \
+                               continue;                               \
+                       }                                               \
+                       if (RB_RIGHT(parent, field) == elm) {           \
+                               RB_ROTATE_LEFT(head, parent, tmp, field);\
+                               tmp = parent;                           \
+                               parent = elm;                           \
+                               elm = tmp;                              \
+                       }                                               \
+                       RB_SET_BLACKRED(parent, gparent, field);        \
+                       RB_ROTATE_RIGHT(head, gparent, tmp, field);     \
+               } else {                                                \
+                       tmp = RB_LEFT(gparent, field);                  \
+                       if (tmp && RB_COLOR(tmp, field) == RB_RED) {    \
+                               RB_COLOR(tmp, field) = RB_BLACK;        \
+                               RB_SET_BLACKRED(parent, gparent, field);\
+                               elm = gparent;                          \
+                               continue;                               \
+                       }                                               \
+                       if (RB_LEFT(parent, field) == elm) {            \
+                               RB_ROTATE_RIGHT(head, parent, tmp, field);\
+                               tmp = parent;                           \
+                               parent = elm;                           \
+                               elm = tmp;                              \
+                       }                                               \
+                       RB_SET_BLACKRED(parent, gparent, field);        \
+                       RB_ROTATE_LEFT(head, gparent, tmp, field);      \
+               }                                                       \
+       }                                                               \
+       RB_COLOR(head->rbh_root, field) = RB_BLACK;                     \
+}                                                                      \
+                                                                       \
+void                                                                   \
+name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \
+{                                                                      \
+       struct type *tmp;                                               \
+       while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) &&     \
+           elm != RB_ROOT(head)) {                                     \
+               if (RB_LEFT(parent, field) == elm) {                    \
+                       tmp = RB_RIGHT(parent, field);                  \
+                       if (RB_COLOR(tmp, field) == RB_RED) {           \
+                               RB_SET_BLACKRED(tmp, parent, field);    \
+                               RB_ROTATE_LEFT(head, parent, tmp, field);\
+                               tmp = RB_RIGHT(parent, field);          \
+                       }                                               \
+                       if ((RB_LEFT(tmp, field) == NULL ||             \
+                           RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+                           (RB_RIGHT(tmp, field) == NULL ||            \
+                           RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+                               RB_COLOR(tmp, field) = RB_RED;          \
+                               elm = parent;                           \
+                               parent = RB_PARENT(elm, field);         \
+                       } else {                                        \
+                               if (RB_RIGHT(tmp, field) == NULL ||     \
+                                   RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\
+                                       struct type *oleft;             \
+                                       if ((oleft = RB_LEFT(tmp, field)))\
+                                               RB_COLOR(oleft, field) = RB_BLACK;\
+                                       RB_COLOR(tmp, field) = RB_RED;  \
+                                       RB_ROTATE_RIGHT(head, tmp, oleft, field);\
+                                       tmp = RB_RIGHT(parent, field);  \
+                               }                                       \
+                               RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+                               RB_COLOR(parent, field) = RB_BLACK;     \
+                               if (RB_RIGHT(tmp, field))               \
+                                       RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\
+                               RB_ROTATE_LEFT(head, parent, tmp, field);\
+                               elm = RB_ROOT(head);                    \
+                               break;                                  \
+                       }                                               \
+               } else {                                                \
+                       tmp = RB_LEFT(parent, field);                   \
+                       if (RB_COLOR(tmp, field) == RB_RED) {           \
+                               RB_SET_BLACKRED(tmp, parent, field);    \
+                               RB_ROTATE_RIGHT(head, parent, tmp, field);\
+                               tmp = RB_LEFT(parent, field);           \
+                       }                                               \
+                       if ((RB_LEFT(tmp, field) == NULL ||             \
+                           RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+                           (RB_RIGHT(tmp, field) == NULL ||            \
+                           RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+                               RB_COLOR(tmp, field) = RB_RED;          \
+                               elm = parent;                           \
+                               parent = RB_PARENT(elm, field);         \
+                       } else {                                        \
+                               if (RB_LEFT(tmp, field) == NULL ||      \
+                                   RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\
+                                       struct type *oright;            \
+                                       if ((oright = RB_RIGHT(tmp, field)))\
+                                               RB_COLOR(oright, field) = RB_BLACK;\
+                                       RB_COLOR(tmp, field) = RB_RED;  \
+                                       RB_ROTATE_LEFT(head, tmp, oright, field);\
+                                       tmp = RB_LEFT(parent, field);   \
+                               }                                       \
+                               RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+                               RB_COLOR(parent, field) = RB_BLACK;     \
+                               if (RB_LEFT(tmp, field))                \
+                                       RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\
+                               RB_ROTATE_RIGHT(head, parent, tmp, field);\
+                               elm = RB_ROOT(head);                    \
+                               break;                                  \
+                       }                                               \
+               }                                                       \
+       }                                                               \
+       if (elm)                                                        \
+               RB_COLOR(elm, field) = RB_BLACK;                        \
+}                                                                      \
+                                                                       \
+struct type *                                                          \
+name##_RB_REMOVE(struct name *head, struct type *elm)                  \
+{                                                                      \
+       struct type *child, *parent, *old = elm;                        \
+       int color;                                                      \
+       if (RB_LEFT(elm, field) == NULL)                                \
+               child = RB_RIGHT(elm, field);                           \
+       else if (RB_RIGHT(elm, field) == NULL)                          \
+               child = RB_LEFT(elm, field);                            \
+       else {                                                          \
+               struct type *left;                                      \
+               elm = RB_RIGHT(elm, field);                             \
+               while ((left = RB_LEFT(elm, field)))                    \
+                       elm = left;                                     \
+               child = RB_RIGHT(elm, field);                           \
+               parent = RB_PARENT(elm, field);                         \
+               color = RB_COLOR(elm, field);                           \
+               if (child)                                              \
+                       RB_PARENT(child, field) = parent;               \
+               if (parent) {                                           \
+                       if (RB_LEFT(parent, field) == elm)              \
+                               RB_LEFT(parent, field) = child;         \
+                       else                                            \
+                               RB_RIGHT(parent, field) = child;        \
+                       RB_AUGMENT(parent);                             \
+               } else                                                  \
+                       RB_ROOT(head) = child;                          \
+               if (RB_PARENT(elm, field) == old)                       \
+                       parent = elm;                                   \
+               (elm)->field = (old)->field;                            \
+               if (RB_PARENT(old, field)) {                            \
+                       if (RB_LEFT(RB_PARENT(old, field), field) == old)\
+                               RB_LEFT(RB_PARENT(old, field), field) = elm;\
+                       else                                            \
+                               RB_RIGHT(RB_PARENT(old, field), field) = elm;\
+                       RB_AUGMENT(RB_PARENT(old, field));              \
+               } else                                                  \
+                       RB_ROOT(head) = elm;                            \
+               RB_PARENT(RB_LEFT(old, field), field) = elm;            \
+               if (RB_RIGHT(old, field))                               \
+                       RB_PARENT(RB_RIGHT(old, field), field) = elm;   \
+               if (parent) {                                           \
+                       left = parent;                                  \
+                       do {                                            \
+                               RB_AUGMENT(left);                       \
+                       } while ((left = RB_PARENT(left, field)));      \
+               }                                                       \
+               goto color;                                             \
+       }                                                               \
+       parent = RB_PARENT(elm, field);                                 \
+       color = RB_COLOR(elm, field);                                   \
+       if (child)                                                      \
+               RB_PARENT(child, field) = parent;                       \
+       if (parent) {                                                   \
+               if (RB_LEFT(parent, field) == elm)                      \
+                       RB_LEFT(parent, field) = child;                 \
+               else                                                    \
+                       RB_RIGHT(parent, field) = child;                \
+               RB_AUGMENT(parent);                                     \
+       } else                                                          \
+               RB_ROOT(head) = child;                                  \
+color:                                                                 \
+       if (color == RB_BLACK)                                          \
+               name##_RB_REMOVE_COLOR(head, parent, child);            \
+       return (old);                                                   \
+}                                                                      \
+                                                                       \
+/* Inserts a node into the RB tree */                                  \
+struct type *                                                          \
+name##_RB_INSERT(struct name *head, struct type *elm)                  \
+{                                                                      \
+       struct type *tmp;                                               \
+       struct type *parent = NULL;                                     \
+       int comp = 0;                                                   \
+       tmp = RB_ROOT(head);                                            \
+       while (tmp) {                                                   \
+               parent = tmp;                                           \
+               comp = (cmp)(elm, parent);                              \
+               if (comp < 0)                                           \
+                       tmp = RB_LEFT(tmp, field);                      \
+               else if (comp > 0)                                      \
+                       tmp = RB_RIGHT(tmp, field);                     \
+               else                                                    \
+                       return (tmp);                                   \
+       }                                                               \
+       RB_SET(elm, parent, field);                                     \
+       if (parent != NULL) {                                           \
+               if (comp < 0)                                           \
+                       RB_LEFT(parent, field) = elm;                   \
+               else                                                    \
+                       RB_RIGHT(parent, field) = elm;                  \
+               RB_AUGMENT(parent);                                     \
+       } else                                                          \
+               RB_ROOT(head) = elm;                                    \
+       name##_RB_INSERT_COLOR(head, elm);                              \
+       return (NULL);                                                  \
+}                                                                      \
+                                                                       \
+/* Finds the node with the same key as elm */                          \
+struct type *                                                          \
+name##_RB_FIND(struct name *head, struct type *elm)                    \
+{                                                                      \
+       struct type *tmp = RB_ROOT(head);                               \
+       int comp;                                                       \
+       while (tmp) {                                                   \
+               comp = cmp(elm, tmp);                                   \
+               if (comp < 0)                                           \
+                       tmp = RB_LEFT(tmp, field);                      \
+               else if (comp > 0)                                      \
+                       tmp = RB_RIGHT(tmp, field);                     \
+               else                                                    \
+                       return (tmp);                                   \
+       }                                                               \
+       return (NULL);                                                  \
+}                                                                      \
+                                                                       \
+struct type *                                                          \
+name##_RB_NEXT(struct type *elm)                                       \
+{                                                                      \
+       if (RB_RIGHT(elm, field)) {                                     \
+               elm = RB_RIGHT(elm, field);                             \
+               while (RB_LEFT(elm, field))                             \
+                       elm = RB_LEFT(elm, field);                      \
+       } else {                                                        \
+               if (RB_PARENT(elm, field) &&                            \
+                   (elm == RB_LEFT(RB_PARENT(elm, field), field)))     \
+                       elm = RB_PARENT(elm, field);                    \
+               else {                                                  \
+                       while (RB_PARENT(elm, field) &&                 \
+                           (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\
+                               elm = RB_PARENT(elm, field);            \
+                       elm = RB_PARENT(elm, field);                    \
+               }                                                       \
+       }                                                               \
+       return (elm);                                                   \
+}                                                                      \
+                                                                       \
+struct type *                                                          \
+name##_RB_MINMAX(struct name *head, int val)                           \
+{                                                                      \
+       struct type *tmp = RB_ROOT(head);                               \
+       struct type *parent = NULL;                                     \
+       while (tmp) {                                                   \
+               parent = tmp;                                           \
+               if (val < 0)                                            \
+                       tmp = RB_LEFT(tmp, field);                      \
+               else                                                    \
+                       tmp = RB_RIGHT(tmp, field);                     \
+       }                                                               \
+       return (parent);                                                \
+}
+
+#define RB_NEGINF      -1
+#define RB_INF 1
+
+#define RB_INSERT(name, x, y)  name##_RB_INSERT(x, y)
+#define RB_REMOVE(name, x, y)  name##_RB_REMOVE(x, y)
+#define RB_FIND(name, x, y)    name##_RB_FIND(x, y)
+#define RB_NEXT(name, x, y)    name##_RB_NEXT(y)
+#define RB_MIN(name, x)                name##_RB_MINMAX(x, RB_NEGINF)
+#define RB_MAX(name, x)                name##_RB_MINMAX(x, RB_INF)
+
+#define RB_FOREACH(x, name, head)                                      \
+       for ((x) = RB_MIN(name, head);                                  \
+            (x) != NULL;                                               \
+            (x) = name##_RB_NEXT(x))
+
+#endif /* _SYS_TREE_H_ */
+/*     $OpenBSD: tree.h,v 1.7 2002/10/17 21:51:54 art Exp $    */
+/*
+ * Copyright 2002 Niels Provos <provos@citi.umich.edu>
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef        _SYS_TREE_H_
+#define        _SYS_TREE_H_
+
+/*
+ * This file defines data structures for different types of trees:
+ * splay trees and red-black trees.
+ *
+ * A splay tree is a self-organizing data structure.  Every operation
+ * on the tree causes a splay to happen.  The splay moves the requested
+ * node to the root of the tree and partly rebalances it.
+ *
+ * This has the benefit that request locality causes faster lookups as
+ * the requested nodes move to the top of the tree.  On the other hand,
+ * every lookup causes memory writes.
+ *
+ * The Balance Theorem bounds the total access time for m operations
+ * and n inserts on an initially empty tree as O((m + n)lg n).  The
+ * amortized cost for a sequence of m accesses to a splay tree is O(lg n);
+ *
+ * A red-black tree is a binary search tree with the node color as an
+ * extra attribute.  It fulfills a set of conditions:
+ *     - every search path from the root to a leaf consists of the
+ *       same number of black nodes,
+ *     - each red node (except for the root) has a black parent,
+ *     - each leaf node is black.
+ *
+ * Every operation on a red-black tree is bounded as O(lg n).
+ * The maximum height of a red-black tree is 2lg (n+1).
+ */
+
+#define SPLAY_HEAD(name, type)                                         \
+struct name {                                                          \
+       struct type *sph_root; /* root of the tree */                   \
+}
+
+#define SPLAY_INITIALIZER(root)                                                \
+       { NULL }
+
+#define SPLAY_INIT(root) do {                                          \
+       (root)->sph_root = NULL;                                        \
+} while (0)
+
+#define SPLAY_ENTRY(type)                                              \
+struct {                                                               \
+       struct type *spe_left; /* left element */                       \
+       struct type *spe_right; /* right element */                     \
+}
+
+#define SPLAY_LEFT(elm, field)         (elm)->field.spe_left
+#define SPLAY_RIGHT(elm, field)                (elm)->field.spe_right
+#define SPLAY_ROOT(head)               (head)->sph_root
+#define SPLAY_EMPTY(head)              (SPLAY_ROOT(head) == NULL)
+
+/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
+#define SPLAY_ROTATE_RIGHT(head, tmp, field) do {                      \
+       SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field);  \
+       SPLAY_RIGHT(tmp, field) = (head)->sph_root;                     \
+       (head)->sph_root = tmp;                                         \
+} while (0)
+
+#define SPLAY_ROTATE_LEFT(head, tmp, field) do {                       \
+       SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field);  \
+       SPLAY_LEFT(tmp, field) = (head)->sph_root;                      \
+       (head)->sph_root = tmp;                                         \
+} while (0)
+
+#define SPLAY_LINKLEFT(head, tmp, field) do {                          \
+       SPLAY_LEFT(tmp, field) = (head)->sph_root;                      \
+       tmp = (head)->sph_root;                                         \
+       (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);         \
+} while (0)
+
+#define SPLAY_LINKRIGHT(head, tmp, field) do {                         \
+       SPLAY_RIGHT(tmp, field) = (head)->sph_root;                     \
+       tmp = (head)->sph_root;                                         \
+       (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);        \
+} while (0)
+
+#define SPLAY_ASSEMBLE(head, node, left, right, field) do {            \
+       SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \
+       SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\
+       SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \
+       SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \
+} while (0)
+
+/* Generates prototypes and inline functions */
+
+#define SPLAY_PROTOTYPE(name, type, field, cmp)                                \
+void name##_SPLAY(struct name *, struct type *);                       \
+void name##_SPLAY_MINMAX(struct name *, int);                          \
+struct type *name##_SPLAY_INSERT(struct name *, struct type *);                \
+struct type *name##_SPLAY_REMOVE(struct name *, struct type *);                \
+                                                                       \
+/* Finds the node with the same key as elm */                          \
+static __inline struct type *                                          \
+name##_SPLAY_FIND(struct name *head, struct type *elm)                 \
+{                                                                      \
+       if (SPLAY_EMPTY(head))                                          \
+               return(NULL);                                           \
+       name##_SPLAY(head, elm);                                        \
+       if ((cmp)(elm, (head)->sph_root) == 0)                          \
+               return (head->sph_root);                                \
+       return (NULL);                                                  \
+}                                                                      \
+                                                                       \
+static __inline struct type *                                          \
+name##_SPLAY_NEXT(struct name *head, struct type *elm)                 \
+{                                                                      \
+       name##_SPLAY(head, elm);                                        \
+       if (SPLAY_RIGHT(elm, field) != NULL) {                          \
+               elm = SPLAY_RIGHT(elm, field);                          \
+               while (SPLAY_LEFT(elm, field) != NULL) {                \
+                       elm = SPLAY_LEFT(elm, field);                   \
+               }                                                       \
+       } else                                                          \
+               elm = NULL;                                             \
+       return (elm);                                                   \
+}                                                                      \
+                                                                       \
+static __inline struct type *                                          \
+name##_SPLAY_MIN_MAX(struct name *head, int val)                       \
+{                                                                      \
+       name##_SPLAY_MINMAX(head, val);                                 \
+       return (SPLAY_ROOT(head));                                      \
+}
+
+/* Main splay operation.
+ * Moves node close to the key of elm to top
+ */
+#define SPLAY_GENERATE(name, type, field, cmp)                         \
+struct type *                                                          \
+name##_SPLAY_INSERT(struct name *head, struct type *elm)               \
+{                                                                      \
+    if (SPLAY_EMPTY(head)) {                                           \
+           SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL;    \
+    } else {                                                           \
+           int __comp;                                                 \
+           name##_SPLAY(head, elm);                                    \
+           __comp = (cmp)(elm, (head)->sph_root);                      \
+           if(__comp < 0) {                                            \
+                   SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\
+                   SPLAY_RIGHT(elm, field) = (head)->sph_root;         \
+                   SPLAY_LEFT((head)->sph_root, field) = NULL;         \
+           } else if (__comp > 0) {                                    \
+                   SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\
+                   SPLAY_LEFT(elm, field) = (head)->sph_root;          \
+                   SPLAY_RIGHT((head)->sph_root, field) = NULL;        \
+           } else                                                      \
+                   return ((head)->sph_root);                          \
+    }                                                                  \
+    (head)->sph_root = (elm);                                          \
+    return (NULL);                                                     \
+}                                                                      \
+                                                                       \
+struct type *                                                          \
+name##_SPLAY_REMOVE(struct name *head, struct type *elm)               \
+{                                                                      \
+       struct type *__tmp;                                             \
+       if (SPLAY_EMPTY(head))                                          \
+               return (NULL);                                          \
+       name##_SPLAY(head, elm);                                        \
+       if ((cmp)(elm, (head)->sph_root) == 0) {                        \
+               if (SPLAY_LEFT((head)->sph_root, field) == NULL) {      \
+                       (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\
+               } else {                                                \
+                       __tmp = SPLAY_RIGHT((head)->sph_root, field);   \
+                       (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\
+                       name##_SPLAY(head, elm);                        \
+                       SPLAY_RIGHT((head)->sph_root, field) = __tmp;   \
+               }                                                       \
+               return (elm);                                           \
+       }                                                               \
+       return (NULL);                                                  \
+}                                                                      \
+                                                                       \
+void                                                                   \
+name##_SPLAY(struct name *head, struct type *elm)                      \
+{                                                                      \
+       struct type __node, *__left, *__right, *__tmp;                  \
+       int __comp;                                                     \
+\
+       SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+       __left = __right = &__node;                                     \
+\
+       while ((__comp = (cmp)(elm, (head)->sph_root))) {               \
+               if (__comp < 0) {                                       \
+                       __tmp = SPLAY_LEFT((head)->sph_root, field);    \
+                       if (__tmp == NULL)                              \
+                               break;                                  \
+                       if ((cmp)(elm, __tmp) < 0){                     \
+                               SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+                               if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+                                       break;                          \
+                       }                                               \
+                       SPLAY_LINKLEFT(head, __right, field);           \
+               } else if (__comp > 0) {                                \
+                       __tmp = SPLAY_RIGHT((head)->sph_root, field);   \
+                       if (__tmp == NULL)                              \
+                               break;                                  \
+                       if ((cmp)(elm, __tmp) > 0){                     \
+                               SPLAY_ROTATE_LEFT(head, __tmp, field);  \
+                               if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+                                       break;                          \
+                       }                                               \
+                       SPLAY_LINKRIGHT(head, __left, field);           \
+               }                                                       \
+       }                                                               \
+       SPLAY_ASSEMBLE(head, &__node, __left, __right, field);          \
+}                                                                      \
+                                                                       \
+/* Splay with either the minimum or the maximum element                        \
+ * Used to find minimum or maximum element in tree.                    \
+ */                                                                    \
+void name##_SPLAY_MINMAX(struct name *head, int __comp) \
+{                                                                      \
+       struct type __node, *__left, *__right, *__tmp;                  \
+\
+       SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+       __left = __right = &__node;                                     \
+\
+       while (1) {                                                     \
+               if (__comp < 0) {                                       \
+                       __tmp = SPLAY_LEFT((head)->sph_root, field);    \
+                       if (__tmp == NULL)                              \
+                               break;                                  \
+                       if (__comp < 0){                                \
+                               SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+                               if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+                                       break;                          \
+                       }                                               \
+                       SPLAY_LINKLEFT(head, __right, field);           \
+               } else if (__comp > 0) {                                \
+                       __tmp = SPLAY_RIGHT((head)->sph_root, field);   \
+                       if (__tmp == NULL)                              \
+                               break;                                  \
+                       if (__comp > 0) {                               \
+                               SPLAY_ROTATE_LEFT(head, __tmp, field);  \
+                               if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+                                       break;                          \
+                       }                                               \
+                       SPLAY_LINKRIGHT(head, __left, field);           \
+               }                                                       \
+       }                                                               \
+       SPLAY_ASSEMBLE(head, &__node, __left, __right, field);          \
+}
+
+#define SPLAY_NEGINF   -1
+#define SPLAY_INF      1
+
+#define SPLAY_INSERT(name, x, y)       name##_SPLAY_INSERT(x, y)
+#define SPLAY_REMOVE(name, x, y)       name##_SPLAY_REMOVE(x, y)
+#define SPLAY_FIND(name, x, y)         name##_SPLAY_FIND(x, y)
+#define SPLAY_NEXT(name, x, y)         name##_SPLAY_NEXT(x, y)
+#define SPLAY_MIN(name, x)             (SPLAY_EMPTY(x) ? NULL  \
+                                       : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
+#define SPLAY_MAX(name, x)             (SPLAY_EMPTY(x) ? NULL  \
+                                       : name##_SPLAY_MIN_MAX(x, SPLAY_INF))
+
+#define SPLAY_FOREACH(x, name, head)                                   \
+       for ((x) = SPLAY_MIN(name, head);                               \
+            (x) != NULL;                                               \
+            (x) = SPLAY_NEXT(name, head, x))
+
+/* Macros that define a red-back tree */
+#define RB_HEAD(name, type)                                            \
+struct name {                                                          \
+       struct type *rbh_root; /* root of the tree */                   \
+}
+
+#define RB_INITIALIZER(root)                                           \
+       { NULL }
+
+#define RB_INIT(root) do {                                             \
+       (root)->rbh_root = NULL;                                        \
+} while (0)
+
+#define RB_BLACK       0
+#define RB_RED         1
+#define RB_ENTRY(type)                                                 \
+struct {                                                               \
+       struct type *rbe_left;          /* left element */              \
+       struct type *rbe_right;         /* right element */             \
+       struct type *rbe_parent;        /* parent element */            \
+       int rbe_color;                  /* node color */                \
+}
+
+#define RB_LEFT(elm, field)            (elm)->field.rbe_left
+#define RB_RIGHT(elm, field)           (elm)->field.rbe_right
+#define RB_PARENT(elm, field)          (elm)->field.rbe_parent
+#define RB_COLOR(elm, field)           (elm)->field.rbe_color
+#define RB_ROOT(head)                  (head)->rbh_root
+#define RB_EMPTY(head)                 (RB_ROOT(head) == NULL)
+
+#define RB_SET(elm, parent, field) do {                                        \
+       RB_PARENT(elm, field) = parent;                                 \
+       RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL;              \
+       RB_COLOR(elm, field) = RB_RED;                                  \
+} while (0)
+
+#define RB_SET_BLACKRED(black, red, field) do {                                \
+       RB_COLOR(black, field) = RB_BLACK;                              \
+       RB_COLOR(red, field) = RB_RED;                                  \
+} while (0)
+
+#ifndef RB_AUGMENT
+#define RB_AUGMENT(x)
+#endif
+
+#define RB_ROTATE_LEFT(head, elm, tmp, field) do {                     \
+       (tmp) = RB_RIGHT(elm, field);                                   \
+       if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) {             \
+               RB_PARENT(RB_LEFT(tmp, field), field) = (elm);          \
+       }                                                               \
+       RB_AUGMENT(elm);                                                \
+       if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {          \
+               if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))     \
+                       RB_LEFT(RB_PARENT(elm, field), field) = (tmp);  \
+               else                                                    \
+                       RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+       } else                                                          \
+               (head)->rbh_root = (tmp);                               \
+       RB_LEFT(tmp, field) = (elm);                                    \
+       RB_PARENT(elm, field) = (tmp);                                  \
+       RB_AUGMENT(tmp);                                                \
+       if ((RB_PARENT(tmp, field)))                                    \
+               RB_AUGMENT(RB_PARENT(tmp, field));                      \
+} while (0)
+
+#define RB_ROTATE_RIGHT(head, elm, tmp, field) do {                    \
+       (tmp) = RB_LEFT(elm, field);                                    \
+       if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) {             \
+               RB_PARENT(RB_RIGHT(tmp, field), field) = (elm);         \
+       }                                                               \
+       RB_AUGMENT(elm);                                                \
+       if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {          \
+               if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))     \
+                       RB_LEFT(RB_PARENT(elm, field), field) = (tmp);  \
+               else                                                    \
+                       RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+       } else                                                          \
+               (head)->rbh_root = (tmp);                               \
+       RB_RIGHT(tmp, field) = (elm);                                   \
+       RB_PARENT(elm, field) = (tmp);                                  \
+       RB_AUGMENT(tmp);                                                \
+       if ((RB_PARENT(tmp, field)))                                    \
+               RB_AUGMENT(RB_PARENT(tmp, field));                      \
+} while (0)
+
+/* Generates prototypes and inline functions */
+#define RB_PROTOTYPE(name, type, field, cmp)                           \
+void name##_RB_INSERT_COLOR(struct name *, struct type *);     \
+void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
+struct type *name##_RB_REMOVE(struct name *, struct type *);           \
+struct type *name##_RB_INSERT(struct name *, struct type *);           \
+struct type *name##_RB_FIND(struct name *, struct type *);             \
+struct type *name##_RB_NEXT(struct type *);                            \
+struct type *name##_RB_MINMAX(struct name *, int);                     \
+                                                                       \
+
+/* Main rb operation.
+ * Moves node close to the key of elm to top
+ */
+#define RB_GENERATE(name, type, field, cmp)                            \
+void                                                                   \
+name##_RB_INSERT_COLOR(struct name *head, struct type *elm)            \
+{                                                                      \
+       struct type *parent, *gparent, *tmp;                            \
+       while ((parent = RB_PARENT(elm, field)) &&                      \
+           RB_COLOR(parent, field) == RB_RED) {                        \
+               gparent = RB_PARENT(parent, field);                     \
+               if (parent == RB_LEFT(gparent, field)) {                \
+                       tmp = RB_RIGHT(gparent, field);                 \
+                       if (tmp && RB_COLOR(tmp, field) == RB_RED) {    \
+                               RB_COLOR(tmp, field) = RB_BLACK;        \
+                               RB_SET_BLACKRED(parent, gparent, field);\
+                               elm = gparent;                          \
+                               continue;                               \
+                       }                                               \
+                       if (RB_RIGHT(parent, field) == elm) {           \
+                               RB_ROTATE_LEFT(head, parent, tmp, field);\
+                               tmp = parent;                           \
+                               parent = elm;                           \
+                               elm = tmp;                              \
+                       }                                               \
+                       RB_SET_BLACKRED(parent, gparent, field);        \
+                       RB_ROTATE_RIGHT(head, gparent, tmp, field);     \
+               } else {                                                \
+                       tmp = RB_LEFT(gparent, field);                  \
+                       if (tmp && RB_COLOR(tmp, field) == RB_RED) {    \
+                               RB_COLOR(tmp, field) = RB_BLACK;        \
+                               RB_SET_BLACKRED(parent, gparent, field);\
+                               elm = gparent;                          \
+                               continue;                               \
+                       }                                               \
+                       if (RB_LEFT(parent, field) == elm) {            \
+                               RB_ROTATE_RIGHT(head, parent, tmp, field);\
+                               tmp = parent;                           \
+                               parent = elm;                           \
+                               elm = tmp;                              \
+                       }                                               \
+                       RB_SET_BLACKRED(parent, gparent, field);        \
+                       RB_ROTATE_LEFT(head, gparent, tmp, field);      \
+               }                                                       \
+       }                                                               \
+       RB_COLOR(head->rbh_root, field) = RB_BLACK;                     \
+}                                                                      \
+                                                                       \
+void                                                                   \
+name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \
+{                                                                      \
+       struct type *tmp;                                               \
+       while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) &&     \
+           elm != RB_ROOT(head)) {                                     \
+               if (RB_LEFT(parent, field) == elm) {                    \
+                       tmp = RB_RIGHT(parent, field);                  \
+                       if (RB_COLOR(tmp, field) == RB_RED) {           \
+                               RB_SET_BLACKRED(tmp, parent, field);    \
+                               RB_ROTATE_LEFT(head, parent, tmp, field);\
+                               tmp = RB_RIGHT(parent, field);          \
+                       }                                               \
+                       if ((RB_LEFT(tmp, field) == NULL ||             \
+                           RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+                           (RB_RIGHT(tmp, field) == NULL ||            \
+                           RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+                               RB_COLOR(tmp, field) = RB_RED;          \
+                               elm = parent;                           \
+                               parent = RB_PARENT(elm, field);         \
+                       } else {                                        \
+                               if (RB_RIGHT(tmp, field) == NULL ||     \
+                                   RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\
+                                       struct type *oleft;             \
+                                       if ((oleft = RB_LEFT(tmp, field)))\
+                                               RB_COLOR(oleft, field) = RB_BLACK;\
+                                       RB_COLOR(tmp, field) = RB_RED;  \
+                                       RB_ROTATE_RIGHT(head, tmp, oleft, field);\
+                                       tmp = RB_RIGHT(parent, field);  \
+                               }                                       \
+                               RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+                               RB_COLOR(parent, field) = RB_BLACK;     \
+                               if (RB_RIGHT(tmp, field))               \
+                                       RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\
+                               RB_ROTATE_LEFT(head, parent, tmp, field);\
+                               elm = RB_ROOT(head);                    \
+                               break;                                  \
+                       }                                               \
+               } else {                                                \
+                       tmp = RB_LEFT(parent, field);                   \
+                       if (RB_COLOR(tmp, field) == RB_RED) {           \
+                               RB_SET_BLACKRED(tmp, parent, field);    \
+                               RB_ROTATE_RIGHT(head, parent, tmp, field);\
+                               tmp = RB_LEFT(parent, field);           \
+                       }                                               \
+                       if ((RB_LEFT(tmp, field) == NULL ||             \
+                           RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+                           (RB_RIGHT(tmp, field) == NULL ||            \
+                           RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+                               RB_COLOR(tmp, field) = RB_RED;          \
+                               elm = parent;                           \
+                               parent = RB_PARENT(elm, field);         \
+                       } else {                                        \
+                               if (RB_LEFT(tmp, field) == NULL ||      \
+                                   RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\
+                                       struct type *oright;            \
+                                       if ((oright = RB_RIGHT(tmp, field)))\
+                                               RB_COLOR(oright, field) = RB_BLACK;\
+                                       RB_COLOR(tmp, field) = RB_RED;  \
+                                       RB_ROTATE_LEFT(head, tmp, oright, field);\
+                                       tmp = RB_LEFT(parent, field);   \
+                               }                                       \
+                               RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+                               RB_COLOR(parent, field) = RB_BLACK;     \
+                               if (RB_LEFT(tmp, field))                \
+                                       RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\
+                               RB_ROTATE_RIGHT(head, parent, tmp, field);\
+                               elm = RB_ROOT(head);                    \
+                               break;                                  \
+                       }                                               \
+               }                                                       \
+       }                                                               \
+       if (elm)                                                        \
+               RB_COLOR(elm, field) = RB_BLACK;                        \
+}                                                                      \
+                                                                       \
+struct type *                                                          \
+name##_RB_REMOVE(struct name *head, struct type *elm)                  \
+{                                                                      \
+       struct type *child, *parent, *old = elm;                        \
+       int color;                                                      \
+       if (RB_LEFT(elm, field) == NULL)                                \
+               child = RB_RIGHT(elm, field);                           \
+       else if (RB_RIGHT(elm, field) == NULL)                          \
+               child = RB_LEFT(elm, field);                            \
+       else {                                                          \
+               struct type *left;                                      \
+               elm = RB_RIGHT(elm, field);                             \
+               while ((left = RB_LEFT(elm, field)))                    \
+                       elm = left;                                     \
+               child = RB_RIGHT(elm, field);                           \
+               parent = RB_PARENT(elm, field);                         \
+               color = RB_COLOR(elm, field);                           \
+               if (child)                                              \
+                       RB_PARENT(child, field) = parent;               \
+               if (parent) {                                           \
+                       if (RB_LEFT(parent, field) == elm)              \
+                               RB_LEFT(parent, field) = child;         \
+                       else                                            \
+                               RB_RIGHT(parent, field) = child;        \
+                       RB_AUGMENT(parent);                             \
+               } else                                                  \
+                       RB_ROOT(head) = child;                          \
+               if (RB_PARENT(elm, field) == old)                       \
+                       parent = elm;                                   \
+               (elm)->field = (old)->field;                            \
+               if (RB_PARENT(old, field)) {                            \
+                       if (RB_LEFT(RB_PARENT(old, field), field) == old)\
+                               RB_LEFT(RB_PARENT(old, field), field) = elm;\
+                       else                                            \
+                               RB_RIGHT(RB_PARENT(old, field), field) = elm;\
+                       RB_AUGMENT(RB_PARENT(old, field));              \
+               } else                                                  \
+                       RB_ROOT(head) = elm;                            \
+               RB_PARENT(RB_LEFT(old, field), field) = elm;            \
+               if (RB_RIGHT(old, field))                               \
+                       RB_PARENT(RB_RIGHT(old, field), field) = elm;   \
+               if (parent) {                                           \
+                       left = parent;                                  \
+                       do {                                            \
+                               RB_AUGMENT(left);                       \
+                       } while ((left = RB_PARENT(left, field)));      \
+               }                                                       \
+               goto color;                                             \
+       }                                                               \
+       parent = RB_PARENT(elm, field);                                 \
+       color = RB_COLOR(elm, field);                                   \
+       if (child)                                                      \
+               RB_PARENT(child, field) = parent;                       \
+       if (parent) {                                                   \
+               if (RB_LEFT(parent, field) == elm)                      \
+                       RB_LEFT(parent, field) = child;                 \
+               else                                                    \
+                       RB_RIGHT(parent, field) = child;                \
+               RB_AUGMENT(parent);                                     \
+       } else                                                          \
+               RB_ROOT(head) = child;                                  \
+color:                                                                 \
+       if (color == RB_BLACK)                                          \
+               name##_RB_REMOVE_COLOR(head, parent, child);            \
+       return (old);                                                   \
+}                                                                      \
+                                                                       \
+/* Inserts a node into the RB tree */                                  \
+struct type *                                                          \
+name##_RB_INSERT(struct name *head, struct type *elm)                  \
+{                                                                      \
+       struct type *tmp;                                               \
+       struct type *parent = NULL;                                     \
+       int comp = 0;                                                   \
+       tmp = RB_ROOT(head);                                            \
+       while (tmp) {                                                   \
+               parent = tmp;                                           \
+               comp = (cmp)(elm, parent);                              \
+               if (comp < 0)                                           \
+                       tmp = RB_LEFT(tmp, field);                      \
+               else if (comp > 0)                                      \
+                       tmp = RB_RIGHT(tmp, field);                     \
+               else                                                    \
+                       return (tmp);                                   \
+       }                                                               \
+       RB_SET(elm, parent, field);                                     \
+       if (parent != NULL) {                                           \
+               if (comp < 0)                                           \
+                       RB_LEFT(parent, field) = elm;                   \
+               else                                                    \
+                       RB_RIGHT(parent, field) = elm;                  \
+               RB_AUGMENT(parent);                                     \
+       } else                                                          \
+               RB_ROOT(head) = elm;                                    \
+       name##_RB_INSERT_COLOR(head, elm);                              \
+       return (NULL);                                                  \
+}                                                                      \
+                                                                       \
+/* Finds the node with the same key as elm */                          \
+struct type *                                                          \
+name##_RB_FIND(struct name *head, struct type *elm)                    \
+{                                                                      \
+       struct type *tmp = RB_ROOT(head);                               \
+       int comp;                                                       \
+       while (tmp) {                                                   \
+               comp = cmp(elm, tmp);                                   \
+               if (comp < 0)                                           \
+                       tmp = RB_LEFT(tmp, field);                      \
+               else if (comp > 0)                                      \
+                       tmp = RB_RIGHT(tmp, field);                     \
+               else                                                    \
+                       return (tmp);                                   \
+       }                                                               \
+       return (NULL);                                                  \
+}                                                                      \
+                                                                       \
+struct type *                                                          \
+name##_RB_NEXT(struct type *elm)                                       \
+{                                                                      \
+       if (RB_RIGHT(elm, field)) {                                     \
+               elm = RB_RIGHT(elm, field);                             \
+               while (RB_LEFT(elm, field))                             \
+                       elm = RB_LEFT(elm, field);                      \
+       } else {                                                        \
+               if (RB_PARENT(elm, field) &&                            \
+                   (elm == RB_LEFT(RB_PARENT(elm, field), field)))     \
+                       elm = RB_PARENT(elm, field);                    \
+               else {                                                  \
+                       while (RB_PARENT(elm, field) &&                 \
+                           (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\
+                               elm = RB_PARENT(elm, field);            \
+                       elm = RB_PARENT(elm, field);                    \
+               }                                                       \
+       }                                                               \
+       return (elm);                                                   \
+}                                                                      \
+                                                                       \
+struct type *                                                          \
+name##_RB_MINMAX(struct name *head, int val)                           \
+{                                                                      \
+       struct type *tmp = RB_ROOT(head);                               \
+       struct type *parent = NULL;                                     \
+       while (tmp) {                                                   \
+               parent = tmp;                                           \
+               if (val < 0)                                            \
+                       tmp = RB_LEFT(tmp, field);                      \
+               else                                                    \
+                       tmp = RB_RIGHT(tmp, field);                     \
+       }                                                               \
+       return (parent);                                                \
+}
+
+#define RB_NEGINF      -1
+#define RB_INF 1
+
+#define RB_INSERT(name, x, y)  name##_RB_INSERT(x, y)
+#define RB_REMOVE(name, x, y)  name##_RB_REMOVE(x, y)
+#define RB_FIND(name, x, y)    name##_RB_FIND(x, y)
+#define RB_NEXT(name, x, y)    name##_RB_NEXT(y)
+#define RB_MIN(name, x)                name##_RB_MINMAX(x, RB_NEGINF)
+#define RB_MAX(name, x)                name##_RB_MINMAX(x, RB_INF)
+
+#define RB_FOREACH(x, name, head)                                      \
+       for ((x) = RB_MIN(name, head);                                  \
+            (x) != NULL;                                               \
+            (x) = name##_RB_NEXT(x))
+
+#endif /* _SYS_TREE_H_ */
diff --git a/libevent/arc4random.c b/libevent/arc4random.c
new file mode 100644 (file)
index 0000000..cabc46f
--- /dev/null
@@ -0,0 +1,539 @@
+/* Portable arc4random.c based on arc4random.c from OpenBSD.
+ * Portable version by Chris Davis, adapted for Libevent by Nick Mathewson
+ * Copyright (c) 2010 Chris Davis, Niels Provos, and Nick Mathewson
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Note that in Libevent, this file isn't compiled directly.  Instead,
+ * it's included from evutil_rand.c
+ */
+
+/*
+ * Copyright (c) 1996, David Mazieres <dm@uun.org>
+ * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
+ *
+ * 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.
+ */
+
+/*
+ * Arc4 random number generator for OpenBSD.
+ *
+ * This code is derived from section 17.1 of Applied Cryptography,
+ * second edition, which describes a stream cipher allegedly
+ * compatible with RSA Labs "RC4" cipher (the actual description of
+ * which is a trade secret).  The same algorithm is used as a stream
+ * cipher called "arcfour" in Tatu Ylonen's ssh package.
+ *
+ * Here the stream cipher has been modified always to include the time
+ * when initializing the state.  That makes it impossible to
+ * regenerate the same random sequence twice, so this can't be used
+ * for encryption, but will generate good random numbers.
+ *
+ * RC4 is a registered trademark of RSA Laboratories.
+ */
+
+#ifndef ARC4RANDOM_EXPORT
+#define ARC4RANDOM_EXPORT
+#endif
+
+#ifndef ARC4RANDOM_UINT32
+#define ARC4RANDOM_UINT32 uint32_t
+#endif
+
+#ifndef ARC4RANDOM_NO_INCLUDES
+#ifdef WIN32
+#include <wincrypt.h>
+#include <process.h>
+#else
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#ifdef _EVENT_HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif
+#endif
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
+/* Add platform entropy 32 bytes (256 bits) at a time. */
+#define ADD_ENTROPY 32
+
+/* Re-seed from the platform RNG after generating this many bytes. */
+#define BYTES_BEFORE_RESEED 1600000
+
+struct arc4_stream {
+       unsigned char i;
+       unsigned char j;
+       unsigned char s[256];
+};
+
+#ifdef WIN32
+#define getpid _getpid
+#define pid_t int
+#endif
+
+static int rs_initialized;
+static struct arc4_stream rs;
+static pid_t arc4_stir_pid;
+static int arc4_count;
+static int arc4_seeded_ok;
+
+static inline unsigned char arc4_getbyte(void);
+
+static inline void
+arc4_init(void)
+{
+       int     n;
+
+       for (n = 0; n < 256; n++)
+               rs.s[n] = n;
+       rs.i = 0;
+       rs.j = 0;
+}
+
+static inline void
+arc4_addrandom(const unsigned char *dat, int datlen)
+{
+       int     n;
+       unsigned char si;
+
+       rs.i--;
+       for (n = 0; n < 256; n++) {
+               rs.i = (rs.i + 1);
+               si = rs.s[rs.i];
+               rs.j = (rs.j + si + dat[n % datlen]);
+               rs.s[rs.i] = rs.s[rs.j];
+               rs.s[rs.j] = si;
+       }
+       rs.j = rs.i;
+}
+
+#ifndef WIN32
+static ssize_t
+read_all(int fd, unsigned char *buf, size_t count)
+{
+       size_t numread = 0;
+       ssize_t result;
+
+       while (numread < count) {
+               result = read(fd, buf+numread, count-numread);
+               if (result<0)
+                       return -1;
+               else if (result == 0)
+                       break;
+               numread += result;
+       }
+
+       return (ssize_t)numread;
+}
+#endif
+
+#ifdef WIN32
+#define TRY_SEED_WIN32
+static int
+arc4_seed_win32(void)
+{
+       /* This is adapted from Tor's crypto_seed_rng() */
+       static int provider_set = 0;
+       static HCRYPTPROV provider;
+       unsigned char buf[ADD_ENTROPY];
+
+       if (!provider_set) {
+               if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
+                   CRYPT_VERIFYCONTEXT)) {
+                       if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
+                               return -1;
+               }
+               provider_set = 1;
+       }
+       if (!CryptGenRandom(provider, sizeof(buf), buf))
+               return -1;
+       arc4_addrandom(buf, sizeof(buf));
+       memset(buf, 0, sizeof(buf));
+       arc4_seeded_ok = 1;
+       return 0;
+}
+#endif
+
+#if defined(_EVENT_HAVE_SYS_SYSCTL_H) && defined(_EVENT_HAVE_SYSCTL)
+#if _EVENT_HAVE_DECL_CTL_KERN && _EVENT_HAVE_DECL_KERN_RANDOM && _EVENT_HAVE_DECL_RANDOM_UUID
+#define TRY_SEED_SYSCTL_LINUX
+static int
+arc4_seed_sysctl_linux(void)
+{
+       /* Based on code by William Ahern, this function tries to use the
+        * RANDOM_UUID sysctl to get entropy from the kernel.  This can work
+        * even if /dev/urandom is inaccessible for some reason (e.g., we're
+        * running in a chroot). */
+       int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
+       unsigned char buf[ADD_ENTROPY];
+       size_t len, n;
+       unsigned i;
+       int any_set;
+
+       memset(buf, 0, sizeof(buf));
+
+       for (len = 0; len < sizeof(buf); len += n) {
+               n = sizeof(buf) - len;
+
+               if (0 != sysctl(mib, 3, &buf[len], &n, NULL, 0))
+                       return -1;
+       }
+       /* make sure that the buffer actually got set. */
+       for (i=0,any_set=0; i<sizeof(buf); ++i) {
+               any_set |= buf[i];
+       }
+       if (!any_set)
+               return -1;
+
+       arc4_addrandom(buf, sizeof(buf));
+       memset(buf, 0, sizeof(buf));
+       arc4_seeded_ok = 1;
+       return 0;
+}
+#endif
+
+#if _EVENT_HAVE_DECL_CTL_KERN && _EVENT_HAVE_DECL_KERN_ARND
+#define TRY_SEED_SYSCTL_BSD
+static int
+arc4_seed_sysctl_bsd(void)
+{
+       /* Based on code from William Ahern and from OpenBSD, this function
+        * tries to use the KERN_ARND syscall to get entropy from the kernel.
+        * This can work even if /dev/urandom is inaccessible for some reason
+        * (e.g., we're running in a chroot). */
+       int mib[] = { CTL_KERN, KERN_ARND };
+       unsigned char buf[ADD_ENTROPY];
+       size_t len, n;
+       int i, any_set;
+
+       memset(buf, 0, sizeof(buf));
+
+       len = sizeof(buf);
+       if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
+               for (len = 0; len < sizeof(buf); len += sizeof(unsigned)) {
+                       n = sizeof(unsigned);
+                       if (n + len > sizeof(buf))
+                           n = len - sizeof(buf);
+                       if (sysctl(mib, 2, &buf[len], &n, NULL, 0) == -1)
+                               return -1;
+               }
+       }
+       /* make sure that the buffer actually got set. */
+       for (i=any_set=0; i<sizeof(buf); ++i) {
+               any_set |= buf[i];
+       }
+       if (!any_set)
+               return -1;
+
+       arc4_addrandom(buf, sizeof(buf));
+       memset(buf, 0, sizeof(buf));
+       arc4_seeded_ok = 1;
+       return 0;
+}
+#endif
+#endif /* defined(_EVENT_HAVE_SYS_SYSCTL_H) */
+
+#ifdef __linux__
+#define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
+static int
+arc4_seed_proc_sys_kernel_random_uuid(void)
+{
+       /* Occasionally, somebody will make /proc/sys accessible in a chroot,
+        * but not /dev/urandom.  Let's try /proc/sys/kernel/random/uuid.
+        * Its format is stupid, so we need to decode it from hex.
+        */
+       int fd;
+       char buf[128];
+       unsigned char entropy[64];
+       int bytes, n, i, nybbles;
+       for (bytes = 0; bytes<ADD_ENTROPY; ) {
+               fd = evutil_open_closeonexec("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
+               if (fd < 0)
+                       return -1;
+               n = read(fd, buf, sizeof(buf));
+               close(fd);
+               if (n<=0)
+                       return -1;
+               memset(entropy, 0, sizeof(entropy));
+               for (i=nybbles=0; i<n; ++i) {
+                       if (EVUTIL_ISXDIGIT(buf[i])) {
+                               int nyb = evutil_hex_char_to_int(buf[i]);
+                               if (nybbles & 1) {
+                                       entropy[nybbles/2] |= nyb;
+                               } else {
+                                       entropy[nybbles/2] |= nyb<<4;
+                               }
+                               ++nybbles;
+                       }
+               }
+               if (nybbles < 2)
+                       return -1;
+               arc4_addrandom(entropy, nybbles/2);
+               bytes += nybbles/2;
+       }
+       memset(entropy, 0, sizeof(entropy));
+       memset(buf, 0, sizeof(buf));
+       return 0;
+}
+#endif
+
+#ifndef WIN32
+#define TRY_SEED_URANDOM
+static int
+arc4_seed_urandom(void)
+{
+       /* This is adapted from Tor's crypto_seed_rng() */
+       static const char *filenames[] = {
+               "/dev/srandom", "/dev/urandom", "/dev/random", NULL
+       };
+       unsigned char buf[ADD_ENTROPY];
+       int fd, i;
+       size_t n;
+
+       for (i = 0; filenames[i]; ++i) {
+               fd = evutil_open_closeonexec(filenames[i], O_RDONLY, 0);
+               if (fd<0)
+                       continue;
+               n = read_all(fd, buf, sizeof(buf));
+               close(fd);
+               if (n != sizeof(buf))
+                       return -1;
+               arc4_addrandom(buf, sizeof(buf));
+               memset(buf, 0, sizeof(buf));
+               arc4_seeded_ok = 1;
+               return 0;
+       }
+
+       return -1;
+}
+#endif
+
+static int
+arc4_seed(void)
+{
+       int ok = 0;
+       /* We try every method that might work, and don't give up even if one
+        * does seem to work.  There's no real harm in over-seeding, and if
+        * one of these sources turns out to be broken, that would be bad. */
+#ifdef TRY_SEED_WIN32
+       if (0 == arc4_seed_win32())
+               ok = 1;
+#endif
+#ifdef TRY_SEED_URANDOM
+       if (0 == arc4_seed_urandom())
+               ok = 1;
+#endif
+#ifdef TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
+       if (0 == arc4_seed_proc_sys_kernel_random_uuid())
+               ok = 1;
+#endif
+#ifdef TRY_SEED_SYSCTL_LINUX
+       /* Apparently Linux is deprecating sysctl, and spewing warning
+        * messages when you try to use it. */
+       if (!ok && 0 == arc4_seed_sysctl_linux())
+               ok = 1;
+#endif
+#ifdef TRY_SEED_SYSCTL_BSD
+       if (0 == arc4_seed_sysctl_bsd())
+               ok = 1;
+#endif
+       return ok ? 0 : -1;
+}
+
+static int
+arc4_stir(void)
+{
+       int     i;
+
+       if (!rs_initialized) {
+               arc4_init();
+               rs_initialized = 1;
+       }
+
+       arc4_seed();
+       if (!arc4_seeded_ok)
+               return -1;
+
+       /*
+        * Discard early keystream, as per recommendations in
+        * "Weaknesses in the Key Scheduling Algorithm of RC4" by
+        * Scott Fluhrer, Itsik Mantin, and Adi Shamir.
+        * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
+        *
+        * Ilya Mironov's "(Not So) Random Shuffles of RC4" suggests that
+        * we drop at least 2*256 bytes, with 12*256 as a conservative
+        * value.
+        *
+        * RFC4345 says to drop 6*256.
+        *
+        * At least some versions of this code drop 4*256, in a mistaken
+        * belief that "words" in the Fluhrer/Mantin/Shamir paper refers
+        * to processor words.
+        *
+        * We add another sect to the cargo cult, and choose 12*256.
+        */
+       for (i = 0; i < 12*256; i++)
+               (void)arc4_getbyte();
+       arc4_count = BYTES_BEFORE_RESEED;
+
+       return 0;
+}
+
+
+static void
+arc4_stir_if_needed(void)
+{
+       pid_t pid = getpid();
+
+       if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
+       {
+               arc4_stir_pid = pid;
+               arc4_stir();
+       }
+}
+
+static inline unsigned char
+arc4_getbyte(void)
+{
+       unsigned char si, sj;
+
+       rs.i = (rs.i + 1);
+       si = rs.s[rs.i];
+       rs.j = (rs.j + si);
+       sj = rs.s[rs.j];
+       rs.s[rs.i] = sj;
+       rs.s[rs.j] = si;
+       return (rs.s[(si + sj) & 0xff]);
+}
+
+static inline unsigned int
+arc4_getword(void)
+{
+       unsigned int val;
+
+       val = arc4_getbyte() << 24;
+       val |= arc4_getbyte() << 16;
+       val |= arc4_getbyte() << 8;
+       val |= arc4_getbyte();
+
+       return val;
+}
+
+#ifndef ARC4RANDOM_NOSTIR
+ARC4RANDOM_EXPORT int
+arc4random_stir(void)
+{
+       int val;
+       _ARC4_LOCK();
+       val = arc4_stir();
+       _ARC4_UNLOCK();
+       return val;
+}
+#endif
+
+#ifndef ARC4RANDOM_NOADDRANDOM
+ARC4RANDOM_EXPORT void
+arc4random_addrandom(const unsigned char *dat, int datlen)
+{
+       int j;
+       _ARC4_LOCK();
+       if (!rs_initialized)
+               arc4_stir();
+       for (j = 0; j < datlen; j += 256) {
+               /* arc4_addrandom() ignores all but the first 256 bytes of
+                * its input.  We want to make sure to look at ALL the
+                * data in 'dat', just in case the user is doing something
+                * crazy like passing us all the files in /var/log. */
+               arc4_addrandom(dat + j, datlen - j);
+       }
+       _ARC4_UNLOCK();
+}
+#endif
+
+#ifndef ARC4RANDOM_NORANDOM
+ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
+arc4random(void)
+{
+       ARC4RANDOM_UINT32 val;
+       _ARC4_LOCK();
+       arc4_count -= 4;
+       arc4_stir_if_needed();
+       val = arc4_getword();
+       _ARC4_UNLOCK();
+       return val;
+}
+#endif
+
+ARC4RANDOM_EXPORT void
+arc4random_buf(void *_buf, size_t n)
+{
+       unsigned char *buf = _buf;
+       _ARC4_LOCK();
+       arc4_stir_if_needed();
+       while (n--) {
+               if (--arc4_count <= 0)
+                       arc4_stir();
+               buf[n] = arc4_getbyte();
+       }
+       _ARC4_UNLOCK();
+}
+
+#ifndef ARC4RANDOM_NOUNIFORM
+/*
+ * Calculate a uniformly distributed random number less than upper_bound
+ * avoiding "modulo bias".
+ *
+ * Uniformity is achieved by generating new random numbers until the one
+ * returned is outside the range [0, 2**32 % upper_bound).  This
+ * guarantees the selected random number will be inside
+ * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
+ * after reduction modulo upper_bound.
+ */
+ARC4RANDOM_EXPORT unsigned int
+arc4random_uniform(unsigned int upper_bound)
+{
+       ARC4RANDOM_UINT32 r, min;
+
+       if (upper_bound < 2)
+               return 0;
+
+#if (UINT_MAX > 0xffffffffUL)
+       min = 0x100000000UL % upper_bound;
+#else
+       /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
+       if (upper_bound > 0x80000000)
+               min = 1 + ~upper_bound;         /* 2**32 - upper_bound */
+       else {
+               /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
+               min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
+       }
+#endif
+
+       /*
+        * This could theoretically loop forever but each retry has
+        * p > 0.5 (worst case, usually far better) of selecting a
+        * number inside the range we need, so it should rarely need
+        * to re-roll.
+        */
+       for (;;) {
+               r = arc4random();
+               if (r >= min)
+                       break;
+       }
+
+       return r % upper_bound;
+}
+#endif
diff --git a/libevent/autogen.sh b/libevent/autogen.sh
new file mode 100755 (executable)
index 0000000..57eeb94
--- /dev/null
@@ -0,0 +1,15 @@
+#!/bin/sh
+if [ -x "`which autoreconf 2>/dev/null`" ] ; then
+   exec autoreconf -ivf
+fi
+
+LIBTOOLIZE=libtoolize
+SYSNAME=`uname`
+if [ "x$SYSNAME" = "xDarwin" ] ; then
+  LIBTOOLIZE=glibtoolize
+fi
+aclocal -I m4 && \
+       autoheader && \
+       $LIBTOOLIZE && \
+       autoconf && \
+       automake --add-missing --force-missing --copy
diff --git a/libevent/buffer.c b/libevent/buffer.c
new file mode 100644 (file)
index 0000000..ff64aed
--- /dev/null
@@ -0,0 +1,3062 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <io.h>
+#endif
+
+#ifdef _EVENT_HAVE_VASPRINTF
+/* If we have vasprintf, we need to define this before we include stdio.h. */
+#define _GNU_SOURCE
+#endif
+
+#include <sys/types.h>
+
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+
+#ifdef _EVENT_HAVE_SYS_UIO_H
+#include <sys/uio.h>
+#endif
+
+#ifdef _EVENT_HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+
+#ifdef _EVENT_HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+
+#ifdef _EVENT_HAVE_SYS_SENDFILE_H
+#include <sys/sendfile.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <limits.h>
+
+#include "event2/event.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/thread.h"
+#include "event2/event-config.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+#include "evthread-internal.h"
+#include "evbuffer-internal.h"
+#include "bufferevent-internal.h"
+
+/* some systems do not have MAP_FAILED */
+#ifndef MAP_FAILED
+#define MAP_FAILED     ((void *)-1)
+#endif
+
+/* send file support */
+#if defined(_EVENT_HAVE_SYS_SENDFILE_H) && defined(_EVENT_HAVE_SENDFILE) && defined(__linux__)
+#define USE_SENDFILE           1
+#define SENDFILE_IS_LINUX      1
+#elif defined(_EVENT_HAVE_SENDFILE) && defined(__FreeBSD__)
+#define USE_SENDFILE           1
+#define SENDFILE_IS_FREEBSD    1
+#elif defined(_EVENT_HAVE_SENDFILE) && defined(__APPLE__)
+#define USE_SENDFILE           1
+#define SENDFILE_IS_MACOSX     1
+#elif defined(_EVENT_HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
+#define USE_SENDFILE           1
+#define SENDFILE_IS_SOLARIS    1
+#endif
+
+#ifdef USE_SENDFILE
+static int use_sendfile = 1;
+#endif
+#ifdef _EVENT_HAVE_MMAP
+static int use_mmap = 1;
+#endif
+
+
+/* Mask of user-selectable callback flags. */
+#define EVBUFFER_CB_USER_FLAGS     0xffff
+/* Mask of all internal-use-only flags. */
+#define EVBUFFER_CB_INTERNAL_FLAGS  0xffff0000
+
+/* Flag set if the callback is using the cb_obsolete function pointer  */
+#define EVBUFFER_CB_OBSOLETE          0x00040000
+
+/* evbuffer_chain support */
+#define CHAIN_SPACE_PTR(ch) ((ch)->buffer + (ch)->misalign + (ch)->off)
+#define CHAIN_SPACE_LEN(ch) ((ch)->flags & EVBUFFER_IMMUTABLE ? \
+           0 : (ch)->buffer_len - ((ch)->misalign + (ch)->off))
+
+#define CHAIN_PINNED(ch)  (((ch)->flags & EVBUFFER_MEM_PINNED_ANY) != 0)
+#define CHAIN_PINNED_R(ch)  (((ch)->flags & EVBUFFER_MEM_PINNED_R) != 0)
+
+static void evbuffer_chain_align(struct evbuffer_chain *chain);
+static int evbuffer_chain_should_realign(struct evbuffer_chain *chain,
+    size_t datalen);
+static void evbuffer_deferred_callback(struct deferred_cb *cb, void *arg);
+static int evbuffer_ptr_memcmp(const struct evbuffer *buf,
+    const struct evbuffer_ptr *pos, const char *mem, size_t len);
+static struct evbuffer_chain *evbuffer_expand_singlechain(struct evbuffer *buf,
+    size_t datlen);
+
+#ifdef WIN32
+static int evbuffer_readfile(struct evbuffer *buf, evutil_socket_t fd,
+    ev_ssize_t howmuch);
+#else
+#define evbuffer_readfile evbuffer_read
+#endif
+
+static struct evbuffer_chain *
+evbuffer_chain_new(size_t size)
+{
+       struct evbuffer_chain *chain;
+       size_t to_alloc;
+
+       size += EVBUFFER_CHAIN_SIZE;
+
+       /* get the next largest memory that can hold the buffer */
+       to_alloc = MIN_BUFFER_SIZE;
+       while (to_alloc < size)
+               to_alloc <<= 1;
+
+       /* we get everything in one chunk */
+       if ((chain = mm_malloc(to_alloc)) == NULL)
+               return (NULL);
+
+       memset(chain, 0, EVBUFFER_CHAIN_SIZE);
+
+       chain->buffer_len = to_alloc - EVBUFFER_CHAIN_SIZE;
+
+       /* this way we can manipulate the buffer to different addresses,
+        * which is required for mmap for example.
+        */
+       chain->buffer = EVBUFFER_CHAIN_EXTRA(u_char, chain);
+
+       return (chain);
+}
+
+static inline void
+evbuffer_chain_free(struct evbuffer_chain *chain)
+{
+       if (CHAIN_PINNED(chain)) {
+               chain->flags |= EVBUFFER_DANGLING;
+               return;
+       }
+       if (chain->flags & (EVBUFFER_MMAP|EVBUFFER_SENDFILE|
+               EVBUFFER_REFERENCE)) {
+               if (chain->flags & EVBUFFER_REFERENCE) {
+                       struct evbuffer_chain_reference *info =
+                           EVBUFFER_CHAIN_EXTRA(
+                                   struct evbuffer_chain_reference,
+                                   chain);
+                       if (info->cleanupfn)
+                               (*info->cleanupfn)(chain->buffer,
+                                   chain->buffer_len,
+                                   info->extra);
+               }
+#ifdef _EVENT_HAVE_MMAP
+               if (chain->flags & EVBUFFER_MMAP) {
+                       struct evbuffer_chain_fd *info =
+                           EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd,
+                               chain);
+                       if (munmap(chain->buffer, chain->buffer_len) == -1)
+                               event_warn("%s: munmap failed", __func__);
+                       if (close(info->fd) == -1)
+                               event_warn("%s: close(%d) failed",
+                                   __func__, info->fd);
+               }
+#endif
+#ifdef USE_SENDFILE
+               if (chain->flags & EVBUFFER_SENDFILE) {
+                       struct evbuffer_chain_fd *info =
+                           EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd,
+                               chain);
+                       if (close(info->fd) == -1)
+                               event_warn("%s: close(%d) failed",
+                                   __func__, info->fd);
+               }
+#endif
+       }
+
+       mm_free(chain);
+}
+
+static void
+evbuffer_free_all_chains(struct evbuffer_chain *chain)
+{
+       struct evbuffer_chain *next;
+       for (; chain; chain = next) {
+               next = chain->next;
+               evbuffer_chain_free(chain);
+       }
+}
+
+#ifndef NDEBUG
+static int
+evbuffer_chains_all_empty(struct evbuffer_chain *chain)
+{
+       for (; chain; chain = chain->next) {
+               if (chain->off)
+                       return 0;
+       }
+       return 1;
+}
+#else
+/* The definition is needed for EVUTIL_ASSERT, which uses sizeof to avoid
+"unused variable" warnings. */
+static inline int evbuffer_chains_all_empty(struct evbuffer_chain *chain) {
+       return 1;
+}
+#endif
+
+/* Free all trailing chains in 'buf' that are neither pinned nor empty, prior
+ * to replacing them all with a new chain.  Return a pointer to the place
+ * where the new chain will go.
+ *
+ * Internal; requires lock.  The caller must fix up buf->last and buf->first
+ * as needed; they might have been freed.
+ */
+static struct evbuffer_chain **
+evbuffer_free_trailing_empty_chains(struct evbuffer *buf)
+{
+       struct evbuffer_chain **ch = buf->last_with_datap;
+       /* Find the first victim chain.  It might be *last_with_datap */
+       while ((*ch) && ((*ch)->off != 0 || CHAIN_PINNED(*ch)))
+               ch = &(*ch)->next;
+       if (*ch) {
+               EVUTIL_ASSERT(evbuffer_chains_all_empty(*ch));
+               evbuffer_free_all_chains(*ch);
+               *ch = NULL;
+       }
+       return ch;
+}
+
+/* Add a single chain 'chain' to the end of 'buf', freeing trailing empty
+ * chains as necessary.  Requires lock.  Does not schedule callbacks.
+ */
+static void
+evbuffer_chain_insert(struct evbuffer *buf,
+    struct evbuffer_chain *chain)
+{
+       ASSERT_EVBUFFER_LOCKED(buf);
+       if (*buf->last_with_datap == NULL) {
+               /* There are no chains data on the buffer at all. */
+               EVUTIL_ASSERT(buf->last_with_datap == &buf->first);
+               EVUTIL_ASSERT(buf->first == NULL);
+               buf->first = buf->last = chain;
+       } else {
+               struct evbuffer_chain **ch = buf->last_with_datap;
+               /* Find the first victim chain.  It might be *last_with_datap */
+               while ((*ch) && ((*ch)->off != 0 || CHAIN_PINNED(*ch)))
+                       ch = &(*ch)->next;
+               if (*ch == NULL) {
+                       /* There is no victim; just append this new chain. */
+                       buf->last->next = chain;
+                       if (chain->off)
+                               buf->last_with_datap = &buf->last->next;
+               } else {
+                       /* Replace all victim chains with this chain. */
+                       EVUTIL_ASSERT(evbuffer_chains_all_empty(*ch));
+                       evbuffer_free_all_chains(*ch);
+                       *ch = chain;
+               }
+               buf->last = chain;
+       }
+       buf->total_len += chain->off;
+}
+
+static inline struct evbuffer_chain *
+evbuffer_chain_insert_new(struct evbuffer *buf, size_t datlen)
+{
+       struct evbuffer_chain *chain;
+       if ((chain = evbuffer_chain_new(datlen)) == NULL)
+               return NULL;
+       evbuffer_chain_insert(buf, chain);
+       return chain;
+}
+
+void
+_evbuffer_chain_pin(struct evbuffer_chain *chain, unsigned flag)
+{
+       EVUTIL_ASSERT((chain->flags & flag) == 0);
+       chain->flags |= flag;
+}
+
+void
+_evbuffer_chain_unpin(struct evbuffer_chain *chain, unsigned flag)
+{
+       EVUTIL_ASSERT((chain->flags & flag) != 0);
+       chain->flags &= ~flag;
+       if (chain->flags & EVBUFFER_DANGLING)
+               evbuffer_chain_free(chain);
+}
+
+struct evbuffer *
+evbuffer_new(void)
+{
+       struct evbuffer *buffer;
+
+       buffer = mm_calloc(1, sizeof(struct evbuffer));
+       if (buffer == NULL)
+               return (NULL);
+
+       TAILQ_INIT(&buffer->callbacks);
+       buffer->refcnt = 1;
+       buffer->last_with_datap = &buffer->first;
+
+       return (buffer);
+}
+
+int
+evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags)
+{
+       EVBUFFER_LOCK(buf);
+       buf->flags |= (ev_uint32_t)flags;
+       EVBUFFER_UNLOCK(buf);
+       return 0;
+}
+
+int
+evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags)
+{
+       EVBUFFER_LOCK(buf);
+       buf->flags &= ~(ev_uint32_t)flags;
+       EVBUFFER_UNLOCK(buf);
+       return 0;
+}
+
+void
+_evbuffer_incref(struct evbuffer *buf)
+{
+       EVBUFFER_LOCK(buf);
+       ++buf->refcnt;
+       EVBUFFER_UNLOCK(buf);
+}
+
+void
+_evbuffer_incref_and_lock(struct evbuffer *buf)
+{
+       EVBUFFER_LOCK(buf);
+       ++buf->refcnt;
+}
+
+int
+evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base)
+{
+       EVBUFFER_LOCK(buffer);
+       buffer->cb_queue = event_base_get_deferred_cb_queue(base);
+       buffer->deferred_cbs = 1;
+       event_deferred_cb_init(&buffer->deferred,
+           evbuffer_deferred_callback, buffer);
+       EVBUFFER_UNLOCK(buffer);
+       return 0;
+}
+
+int
+evbuffer_enable_locking(struct evbuffer *buf, void *lock)
+{
+#ifdef _EVENT_DISABLE_THREAD_SUPPORT
+       return -1;
+#else
+       if (buf->lock)
+               return -1;
+
+       if (!lock) {
+               EVTHREAD_ALLOC_LOCK(lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+               if (!lock)
+                       return -1;
+               buf->lock = lock;
+               buf->own_lock = 1;
+       } else {
+               buf->lock = lock;
+               buf->own_lock = 0;
+       }
+
+       return 0;
+#endif
+}
+
+void
+evbuffer_set_parent(struct evbuffer *buf, struct bufferevent *bev)
+{
+       EVBUFFER_LOCK(buf);
+       buf->parent = bev;
+       EVBUFFER_UNLOCK(buf);
+}
+
+static void
+evbuffer_run_callbacks(struct evbuffer *buffer, int running_deferred)
+{
+       struct evbuffer_cb_entry *cbent, *next;
+       struct evbuffer_cb_info info;
+       size_t new_size;
+       ev_uint32_t mask, masked_val;
+       int clear = 1;
+
+       if (running_deferred) {
+               mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
+               masked_val = EVBUFFER_CB_ENABLED;
+       } else if (buffer->deferred_cbs) {
+               mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
+               masked_val = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
+               /* Don't zero-out n_add/n_del, since the deferred callbacks
+                  will want to see them. */
+               clear = 0;
+       } else {
+               mask = EVBUFFER_CB_ENABLED;
+               masked_val = EVBUFFER_CB_ENABLED;
+       }
+
+       ASSERT_EVBUFFER_LOCKED(buffer);
+
+       if (TAILQ_EMPTY(&buffer->callbacks)) {
+               buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
+               return;
+       }
+       if (buffer->n_add_for_cb == 0 && buffer->n_del_for_cb == 0)
+               return;
+
+       new_size = buffer->total_len;
+       info.orig_size = new_size + buffer->n_del_for_cb - buffer->n_add_for_cb;
+       info.n_added = buffer->n_add_for_cb;
+       info.n_deleted = buffer->n_del_for_cb;
+       if (clear) {
+               buffer->n_add_for_cb = 0;
+               buffer->n_del_for_cb = 0;
+       }
+       for (cbent = TAILQ_FIRST(&buffer->callbacks);
+            cbent != TAILQ_END(&buffer->callbacks);
+            cbent = next) {
+               /* Get the 'next' pointer now in case this callback decides
+                * to remove itself or something. */
+               next = TAILQ_NEXT(cbent, next);
+
+               if ((cbent->flags & mask) != masked_val)
+                       continue;
+
+               if ((cbent->flags & EVBUFFER_CB_OBSOLETE))
+                       cbent->cb.cb_obsolete(buffer,
+                           info.orig_size, new_size, cbent->cbarg);
+               else
+                       cbent->cb.cb_func(buffer, &info, cbent->cbarg);
+       }
+}
+
+void
+evbuffer_invoke_callbacks(struct evbuffer *buffer)
+{
+       if (TAILQ_EMPTY(&buffer->callbacks)) {
+               buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
+               return;
+       }
+
+       if (buffer->deferred_cbs) {
+               if (buffer->deferred.queued)
+                       return;
+               _evbuffer_incref_and_lock(buffer);
+               if (buffer->parent)
+                       bufferevent_incref(buffer->parent);
+               EVBUFFER_UNLOCK(buffer);
+               event_deferred_cb_schedule(buffer->cb_queue, &buffer->deferred);
+       }
+
+       evbuffer_run_callbacks(buffer, 0);
+}
+
+static void
+evbuffer_deferred_callback(struct deferred_cb *cb, void *arg)
+{
+       struct bufferevent *parent = NULL;
+       struct evbuffer *buffer = arg;
+
+       /* XXXX It would be better to run these callbacks without holding the
+        * lock */
+       EVBUFFER_LOCK(buffer);
+       parent = buffer->parent;
+       evbuffer_run_callbacks(buffer, 1);
+       _evbuffer_decref_and_unlock(buffer);
+       if (parent)
+               bufferevent_decref(parent);
+}
+
+static void
+evbuffer_remove_all_callbacks(struct evbuffer *buffer)
+{
+       struct evbuffer_cb_entry *cbent;
+
+       while ((cbent = TAILQ_FIRST(&buffer->callbacks))) {
+           TAILQ_REMOVE(&buffer->callbacks, cbent, next);
+           mm_free(cbent);
+       }
+}
+
+void
+_evbuffer_decref_and_unlock(struct evbuffer *buffer)
+{
+       struct evbuffer_chain *chain, *next;
+       ASSERT_EVBUFFER_LOCKED(buffer);
+
+       EVUTIL_ASSERT(buffer->refcnt > 0);
+
+       if (--buffer->refcnt > 0) {
+               EVBUFFER_UNLOCK(buffer);
+               return;
+       }
+
+       for (chain = buffer->first; chain != NULL; chain = next) {
+               next = chain->next;
+               evbuffer_chain_free(chain);
+       }
+       evbuffer_remove_all_callbacks(buffer);
+       if (buffer->deferred_cbs)
+               event_deferred_cb_cancel(buffer->cb_queue, &buffer->deferred);
+
+       EVBUFFER_UNLOCK(buffer);
+       if (buffer->own_lock)
+               EVTHREAD_FREE_LOCK(buffer->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       mm_free(buffer);
+}
+
+void
+evbuffer_free(struct evbuffer *buffer)
+{
+       EVBUFFER_LOCK(buffer);
+       _evbuffer_decref_and_unlock(buffer);
+}
+
+void
+evbuffer_lock(struct evbuffer *buf)
+{
+       EVBUFFER_LOCK(buf);
+}
+
+void
+evbuffer_unlock(struct evbuffer *buf)
+{
+       EVBUFFER_UNLOCK(buf);
+}
+
+size_t
+evbuffer_get_length(const struct evbuffer *buffer)
+{
+       size_t result;
+
+       EVBUFFER_LOCK(buffer);
+
+       result = (buffer->total_len);
+
+       EVBUFFER_UNLOCK(buffer);
+
+       return result;
+}
+
+size_t
+evbuffer_get_contiguous_space(const struct evbuffer *buf)
+{
+       struct evbuffer_chain *chain;
+       size_t result;
+
+       EVBUFFER_LOCK(buf);
+       chain = buf->first;
+       result = (chain != NULL ? chain->off : 0);
+       EVBUFFER_UNLOCK(buf);
+
+       return result;
+}
+
+int
+evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
+    struct evbuffer_iovec *vec, int n_vecs)
+{
+       struct evbuffer_chain *chain, **chainp;
+       int n = -1;
+
+       EVBUFFER_LOCK(buf);
+       if (buf->freeze_end)
+               goto done;
+       if (n_vecs < 1)
+               goto done;
+       if (n_vecs == 1) {
+               if ((chain = evbuffer_expand_singlechain(buf, size)) == NULL)
+                       goto done;
+
+               vec[0].iov_base = CHAIN_SPACE_PTR(chain);
+               vec[0].iov_len = (size_t) CHAIN_SPACE_LEN(chain);
+               EVUTIL_ASSERT(size<0 || (size_t)vec[0].iov_len >= (size_t)size);
+               n = 1;
+       } else {
+               if (_evbuffer_expand_fast(buf, size, n_vecs)<0)
+                       goto done;
+               n = _evbuffer_read_setup_vecs(buf, size, vec, n_vecs,
+                               &chainp, 0);
+       }
+
+done:
+       EVBUFFER_UNLOCK(buf);
+       return n;
+
+}
+
+static int
+advance_last_with_data(struct evbuffer *buf)
+{
+       int n = 0;
+       ASSERT_EVBUFFER_LOCKED(buf);
+
+       if (!*buf->last_with_datap)
+               return 0;
+
+       while ((*buf->last_with_datap)->next && (*buf->last_with_datap)->next->off) {
+               buf->last_with_datap = &(*buf->last_with_datap)->next;
+               ++n;
+       }
+       return n;
+}
+
+int
+evbuffer_commit_space(struct evbuffer *buf,
+    struct evbuffer_iovec *vec, int n_vecs)
+{
+       struct evbuffer_chain *chain, **firstchainp, **chainp;
+       int result = -1;
+       size_t added = 0;
+       int i;
+
+       EVBUFFER_LOCK(buf);
+
+       if (buf->freeze_end)
+               goto done;
+       if (n_vecs == 0) {
+               result = 0;
+               goto done;
+       } else if (n_vecs == 1 &&
+           (buf->last && vec[0].iov_base == (void*)CHAIN_SPACE_PTR(buf->last))) {
+               /* The user only got or used one chain; it might not
+                * be the first one with space in it. */
+               if ((size_t)vec[0].iov_len > (size_t)CHAIN_SPACE_LEN(buf->last))
+                       goto done;
+               buf->last->off += vec[0].iov_len;
+               added = vec[0].iov_len;
+               if (added)
+                       advance_last_with_data(buf);
+               goto okay;
+       }
+
+       /* Advance 'firstchain' to the first chain with space in it. */
+       firstchainp = buf->last_with_datap;
+       if (!*firstchainp)
+               goto done;
+       if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
+               firstchainp = &(*firstchainp)->next;
+       }
+
+       chain = *firstchainp;
+       /* pass 1: make sure that the pointers and lengths of vecs[] are in
+        * bounds before we try to commit anything. */
+       for (i=0; i<n_vecs; ++i) {
+               if (!chain)
+                       goto done;
+               if (vec[i].iov_base != (void*)CHAIN_SPACE_PTR(chain) ||
+                   (size_t)vec[i].iov_len > CHAIN_SPACE_LEN(chain))
+                       goto done;
+               chain = chain->next;
+       }
+       /* pass 2: actually adjust all the chains. */
+       chainp = firstchainp;
+       for (i=0; i<n_vecs; ++i) {
+               (*chainp)->off += vec[i].iov_len;
+               added += vec[i].iov_len;
+               if (vec[i].iov_len) {
+                       buf->last_with_datap = chainp;
+               }
+               chainp = &(*chainp)->next;
+       }
+
+okay:
+       buf->total_len += added;
+       buf->n_add_for_cb += added;
+       result = 0;
+       evbuffer_invoke_callbacks(buf);
+
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+
+static inline int
+HAS_PINNED_R(struct evbuffer *buf)
+{
+       return (buf->last && CHAIN_PINNED_R(buf->last));
+}
+
+static inline void
+ZERO_CHAIN(struct evbuffer *dst)
+{
+       ASSERT_EVBUFFER_LOCKED(dst);
+       dst->first = NULL;
+       dst->last = NULL;
+       dst->last_with_datap = &(dst)->first;
+       dst->total_len = 0;
+}
+
+/* Prepares the contents of src to be moved to another buffer by removing
+ * read-pinned chains. The first pinned chain is saved in first, and the
+ * last in last. If src has no read-pinned chains, first and last are set
+ * to NULL. */
+static int
+PRESERVE_PINNED(struct evbuffer *src, struct evbuffer_chain **first,
+               struct evbuffer_chain **last)
+{
+       struct evbuffer_chain *chain, **pinned;
+
+       ASSERT_EVBUFFER_LOCKED(src);
+
+       if (!HAS_PINNED_R(src)) {
+               *first = *last = NULL;
+               return 0;
+       }
+
+       pinned = src->last_with_datap;
+       if (!CHAIN_PINNED_R(*pinned))
+               pinned = &(*pinned)->next;
+       EVUTIL_ASSERT(CHAIN_PINNED_R(*pinned));
+       chain = *first = *pinned;
+       *last = src->last;
+
+       /* If there's data in the first pinned chain, we need to allocate
+        * a new chain and copy the data over. */
+       if (chain->off) {
+               struct evbuffer_chain *tmp;
+
+               EVUTIL_ASSERT(pinned == src->last_with_datap);
+               tmp = evbuffer_chain_new(chain->off);
+               if (!tmp)
+                       return -1;
+               memcpy(tmp->buffer, chain->buffer + chain->misalign,
+                       chain->off);
+               tmp->off = chain->off;
+               *src->last_with_datap = tmp;
+               src->last = tmp;
+               chain->misalign += chain->off;
+               chain->off = 0;
+       } else {
+               src->last = *src->last_with_datap;
+               *pinned = NULL;
+       }
+
+       return 0;
+}
+
+static inline void
+RESTORE_PINNED(struct evbuffer *src, struct evbuffer_chain *pinned,
+               struct evbuffer_chain *last)
+{
+       ASSERT_EVBUFFER_LOCKED(src);
+
+       if (!pinned) {
+               ZERO_CHAIN(src);
+               return;
+       }
+
+       src->first = pinned;
+       src->last = last;
+       src->last_with_datap = &src->first;
+       src->total_len = 0;
+}
+
+static inline void
+COPY_CHAIN(struct evbuffer *dst, struct evbuffer *src)
+{
+       ASSERT_EVBUFFER_LOCKED(dst);
+       ASSERT_EVBUFFER_LOCKED(src);
+       dst->first = src->first;
+       if (src->last_with_datap == &src->first)
+               dst->last_with_datap = &dst->first;
+       else
+               dst->last_with_datap = src->last_with_datap;
+       dst->last = src->last;
+       dst->total_len = src->total_len;
+}
+
+static void
+APPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
+{
+       ASSERT_EVBUFFER_LOCKED(dst);
+       ASSERT_EVBUFFER_LOCKED(src);
+       dst->last->next = src->first;
+       if (src->last_with_datap == &src->first)
+               dst->last_with_datap = &dst->last->next;
+       else
+               dst->last_with_datap = src->last_with_datap;
+       dst->last = src->last;
+       dst->total_len += src->total_len;
+}
+
+static void
+PREPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
+{
+       ASSERT_EVBUFFER_LOCKED(dst);
+       ASSERT_EVBUFFER_LOCKED(src);
+       src->last->next = dst->first;
+       dst->first = src->first;
+       dst->total_len += src->total_len;
+       if (*dst->last_with_datap == NULL) {
+               if (src->last_with_datap == &(src)->first)
+                       dst->last_with_datap = &dst->first;
+               else
+                       dst->last_with_datap = src->last_with_datap;
+       } else if (dst->last_with_datap == &dst->first) {
+               dst->last_with_datap = &src->last->next;
+       }
+}
+
+int
+evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
+{
+       struct evbuffer_chain *pinned, *last;
+       size_t in_total_len, out_total_len;
+       int result = 0;
+
+       EVBUFFER_LOCK2(inbuf, outbuf);
+       in_total_len = inbuf->total_len;
+       out_total_len = outbuf->total_len;
+
+       if (in_total_len == 0 || outbuf == inbuf)
+               goto done;
+
+       if (outbuf->freeze_end || inbuf->freeze_start) {
+               result = -1;
+               goto done;
+       }
+
+       if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
+               result = -1;
+               goto done;
+       }
+
+       if (out_total_len == 0) {
+               /* There might be an empty chain at the start of outbuf; free
+                * it. */
+               evbuffer_free_all_chains(outbuf->first);
+               COPY_CHAIN(outbuf, inbuf);
+       } else {
+               APPEND_CHAIN(outbuf, inbuf);
+       }
+
+       RESTORE_PINNED(inbuf, pinned, last);
+
+       inbuf->n_del_for_cb += in_total_len;
+       outbuf->n_add_for_cb += in_total_len;
+
+       evbuffer_invoke_callbacks(inbuf);
+       evbuffer_invoke_callbacks(outbuf);
+
+done:
+       EVBUFFER_UNLOCK2(inbuf, outbuf);
+       return result;
+}
+
+int
+evbuffer_prepend_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
+{
+       struct evbuffer_chain *pinned, *last;
+       size_t in_total_len, out_total_len;
+       int result = 0;
+
+       EVBUFFER_LOCK2(inbuf, outbuf);
+
+       in_total_len = inbuf->total_len;
+       out_total_len = outbuf->total_len;
+
+       if (!in_total_len || inbuf == outbuf)
+               goto done;
+
+       if (outbuf->freeze_start || inbuf->freeze_start) {
+               result = -1;
+               goto done;
+       }
+
+       if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
+               result = -1;
+               goto done;
+       }
+
+       if (out_total_len == 0) {
+               /* There might be an empty chain at the start of outbuf; free
+                * it. */
+               evbuffer_free_all_chains(outbuf->first);
+               COPY_CHAIN(outbuf, inbuf);
+       } else {
+               PREPEND_CHAIN(outbuf, inbuf);
+       }
+
+       RESTORE_PINNED(inbuf, pinned, last);
+
+       inbuf->n_del_for_cb += in_total_len;
+       outbuf->n_add_for_cb += in_total_len;
+
+       evbuffer_invoke_callbacks(inbuf);
+       evbuffer_invoke_callbacks(outbuf);
+done:
+       EVBUFFER_UNLOCK2(inbuf, outbuf);
+       return result;
+}
+
+int
+evbuffer_drain(struct evbuffer *buf, size_t len)
+{
+       struct evbuffer_chain *chain, *next;
+       size_t remaining, old_len;
+       int result = 0;
+
+       EVBUFFER_LOCK(buf);
+       old_len = buf->total_len;
+
+       if (old_len == 0)
+               goto done;
+
+       if (buf->freeze_start) {
+               result = -1;
+               goto done;
+       }
+
+       if (len >= old_len && !HAS_PINNED_R(buf)) {
+               len = old_len;
+               for (chain = buf->first; chain != NULL; chain = next) {
+                       next = chain->next;
+                       evbuffer_chain_free(chain);
+               }
+
+               ZERO_CHAIN(buf);
+       } else {
+               if (len >= old_len)
+                       len = old_len;
+
+               buf->total_len -= len;
+               remaining = len;
+               for (chain = buf->first;
+                    remaining >= chain->off;
+                    chain = next) {
+                       next = chain->next;
+                       remaining -= chain->off;
+
+                       if (chain == *buf->last_with_datap) {
+                               buf->last_with_datap = &buf->first;
+                       }
+                       if (&chain->next == buf->last_with_datap)
+                               buf->last_with_datap = &buf->first;
+
+                       if (CHAIN_PINNED_R(chain)) {
+                               EVUTIL_ASSERT(remaining == 0);
+                               chain->misalign += chain->off;
+                               chain->off = 0;
+                               break;
+                       } else
+                               evbuffer_chain_free(chain);
+               }
+
+               buf->first = chain;
+               if (chain) {
+                       chain->misalign += remaining;
+                       chain->off -= remaining;
+               }
+       }
+
+       buf->n_del_for_cb += len;
+       /* Tell someone about changes in this buffer */
+       evbuffer_invoke_callbacks(buf);
+
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+
+/* Reads data from an event buffer and drains the bytes read */
+int
+evbuffer_remove(struct evbuffer *buf, void *data_out, size_t datlen)
+{
+       ev_ssize_t n;
+       EVBUFFER_LOCK(buf);
+       n = evbuffer_copyout(buf, data_out, datlen);
+       if (n > 0) {
+               if (evbuffer_drain(buf, n)<0)
+                       n = -1;
+       }
+       EVBUFFER_UNLOCK(buf);
+       return (int)n;
+}
+
+ev_ssize_t
+evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen)
+{
+       /*XXX fails badly on sendfile case. */
+       struct evbuffer_chain *chain;
+       char *data = data_out;
+       size_t nread;
+       ev_ssize_t result = 0;
+
+       EVBUFFER_LOCK(buf);
+
+       chain = buf->first;
+
+       if (datlen >= buf->total_len)
+               datlen = buf->total_len;
+
+       if (datlen == 0)
+               goto done;
+
+       if (buf->freeze_start) {
+               result = -1;
+               goto done;
+       }
+
+       nread = datlen;
+
+       while (datlen && datlen >= chain->off) {
+               memcpy(data, chain->buffer + chain->misalign, chain->off);
+               data += chain->off;
+               datlen -= chain->off;
+
+               chain = chain->next;
+               EVUTIL_ASSERT(chain || datlen==0);
+       }
+
+       if (datlen) {
+               EVUTIL_ASSERT(chain);
+               memcpy(data, chain->buffer + chain->misalign, datlen);
+       }
+
+       result = nread;
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+
+/* reads data from the src buffer to the dst buffer, avoids memcpy as
+ * possible. */
+/*  XXXX should return ev_ssize_t */
+int
+evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
+    size_t datlen)
+{
+       /*XXX We should have an option to force this to be zero-copy.*/
+
+       /*XXX can fail badly on sendfile case. */
+       struct evbuffer_chain *chain, *previous;
+       size_t nread = 0;
+       int result;
+
+       EVBUFFER_LOCK2(src, dst);
+
+       chain = previous = src->first;
+
+       if (datlen == 0 || dst == src) {
+               result = 0;
+               goto done;
+       }
+
+       if (dst->freeze_end || src->freeze_start) {
+               result = -1;
+               goto done;
+       }
+
+       /* short-cut if there is no more data buffered */
+       if (datlen >= src->total_len) {
+               datlen = src->total_len;
+               evbuffer_add_buffer(dst, src);
+               result = (int)datlen; /*XXXX should return ev_ssize_t*/
+               goto done;
+       }
+
+       /* removes chains if possible */
+       while (chain->off <= datlen) {
+               /* We can't remove the last with data from src unless we
+                * remove all chains, in which case we would have done the if
+                * block above */
+               EVUTIL_ASSERT(chain != *src->last_with_datap);
+               nread += chain->off;
+               datlen -= chain->off;
+               previous = chain;
+               if (src->last_with_datap == &chain->next)
+                       src->last_with_datap = &src->first;
+               chain = chain->next;
+       }
+
+       if (nread) {
+               /* we can remove the chain */
+               struct evbuffer_chain **chp;
+               chp = evbuffer_free_trailing_empty_chains(dst);
+
+               if (dst->first == NULL) {
+                       dst->first = src->first;
+               } else {
+                       *chp = src->first;
+               }
+               dst->last = previous;
+               previous->next = NULL;
+               src->first = chain;
+               advance_last_with_data(dst);
+
+               dst->total_len += nread;
+               dst->n_add_for_cb += nread;
+       }
+
+       /* we know that there is more data in the src buffer than
+        * we want to read, so we manually drain the chain */
+       evbuffer_add(dst, chain->buffer + chain->misalign, datlen);
+       chain->misalign += datlen;
+       chain->off -= datlen;
+       nread += datlen;
+
+       /* You might think we would want to increment dst->n_add_for_cb
+        * here too.  But evbuffer_add above already took care of that.
+        */
+       src->total_len -= nread;
+       src->n_del_for_cb += nread;
+
+       if (nread) {
+               evbuffer_invoke_callbacks(dst);
+               evbuffer_invoke_callbacks(src);
+       }
+       result = (int)nread;/*XXXX should change return type */
+
+done:
+       EVBUFFER_UNLOCK2(src, dst);
+       return result;
+}
+
+unsigned char *
+evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size)
+{
+       struct evbuffer_chain *chain, *next, *tmp, *last_with_data;
+       unsigned char *buffer, *result = NULL;
+       ev_ssize_t remaining;
+       int removed_last_with_data = 0;
+       int removed_last_with_datap = 0;
+
+       EVBUFFER_LOCK(buf);
+
+       chain = buf->first;
+
+       if (size < 0)
+               size = buf->total_len;
+       /* if size > buf->total_len, we cannot guarantee to the user that she
+        * is going to have a long enough buffer afterwards; so we return
+        * NULL */
+       if (size == 0 || (size_t)size > buf->total_len)
+               goto done;
+
+       /* No need to pull up anything; the first size bytes are
+        * already here. */
+       if (chain->off >= (size_t)size) {
+               result = chain->buffer + chain->misalign;
+               goto done;
+       }
+
+       /* Make sure that none of the chains we need to copy from is pinned. */
+       remaining = size - chain->off;
+       EVUTIL_ASSERT(remaining >= 0);
+       for (tmp=chain->next; tmp; tmp=tmp->next) {
+               if (CHAIN_PINNED(tmp))
+                       goto done;
+               if (tmp->off >= (size_t)remaining)
+                       break;
+               remaining -= tmp->off;
+       }
+
+       if (CHAIN_PINNED(chain)) {
+               size_t old_off = chain->off;
+               if (CHAIN_SPACE_LEN(chain) < size - chain->off) {
+                       /* not enough room at end of chunk. */
+                       goto done;
+               }
+               buffer = CHAIN_SPACE_PTR(chain);
+               tmp = chain;
+               tmp->off = size;
+               size -= old_off;
+               chain = chain->next;
+       } else if (chain->buffer_len - chain->misalign >= (size_t)size) {
+               /* already have enough space in the first chain */
+               size_t old_off = chain->off;
+               buffer = chain->buffer + chain->misalign + chain->off;
+               tmp = chain;
+               tmp->off = size;
+               size -= old_off;
+               chain = chain->next;
+       } else {
+               if ((tmp = evbuffer_chain_new(size)) == NULL) {
+                       event_warn("%s: out of memory", __func__);
+                       goto done;
+               }
+               buffer = tmp->buffer;
+               tmp->off = size;
+               buf->first = tmp;
+       }
+
+       /* TODO(niels): deal with buffers that point to NULL like sendfile */
+
+       /* Copy and free every chunk that will be entirely pulled into tmp */
+       last_with_data = *buf->last_with_datap;
+       for (; chain != NULL && (size_t)size >= chain->off; chain = next) {
+               next = chain->next;
+
+               memcpy(buffer, chain->buffer + chain->misalign, chain->off);
+               size -= chain->off;
+               buffer += chain->off;
+               if (chain == last_with_data)
+                       removed_last_with_data = 1;
+               if (&chain->next == buf->last_with_datap)
+                       removed_last_with_datap = 1;
+
+               evbuffer_chain_free(chain);
+       }
+
+       if (chain != NULL) {
+               memcpy(buffer, chain->buffer + chain->misalign, size);
+               chain->misalign += size;
+               chain->off -= size;
+       } else {
+               buf->last = tmp;
+       }
+
+       tmp->next = chain;
+
+       if (removed_last_with_data) {
+               buf->last_with_datap = &buf->first;
+       } else if (removed_last_with_datap) {
+               if (buf->first->next && buf->first->next->off)
+                       buf->last_with_datap = &buf->first->next;
+               else
+                       buf->last_with_datap = &buf->first;
+       }
+
+       result = (tmp->buffer + tmp->misalign);
+
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+
+/*
+ * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
+ * The returned buffer needs to be freed by the called.
+ */
+char *
+evbuffer_readline(struct evbuffer *buffer)
+{
+       return evbuffer_readln(buffer, NULL, EVBUFFER_EOL_ANY);
+}
+
+static inline ev_ssize_t
+evbuffer_strchr(struct evbuffer_ptr *it, const char chr)
+{
+       struct evbuffer_chain *chain = it->_internal.chain;
+       size_t i = it->_internal.pos_in_chain;
+       while (chain != NULL) {
+               char *buffer = (char *)chain->buffer + chain->misalign;
+               char *cp = memchr(buffer+i, chr, chain->off-i);
+               if (cp) {
+                       it->_internal.chain = chain;
+                       it->_internal.pos_in_chain = cp - buffer;
+                       it->pos += (cp - buffer - i);
+                       return it->pos;
+               }
+               it->pos += chain->off - i;
+               i = 0;
+               chain = chain->next;
+       }
+
+       return (-1);
+}
+
+static inline char *
+find_eol_char(char *s, size_t len)
+{
+#define CHUNK_SZ 128
+       /* Lots of benchmarking found this approach to be faster in practice
+        * than doing two memchrs over the whole buffer, doin a memchr on each
+        * char of the buffer, or trying to emulate memchr by hand. */
+       char *s_end, *cr, *lf;
+       s_end = s+len;
+       while (s < s_end) {
+               size_t chunk = (s + CHUNK_SZ < s_end) ? CHUNK_SZ : (s_end - s);
+               cr = memchr(s, '\r', chunk);
+               lf = memchr(s, '\n', chunk);
+               if (cr) {
+                       if (lf && lf < cr)
+                               return lf;
+                       return cr;
+               } else if (lf) {
+                       return lf;
+               }
+               s += CHUNK_SZ;
+       }
+
+       return NULL;
+#undef CHUNK_SZ
+}
+
+static ev_ssize_t
+evbuffer_find_eol_char(struct evbuffer_ptr *it)
+{
+       struct evbuffer_chain *chain = it->_internal.chain;
+       size_t i = it->_internal.pos_in_chain;
+       while (chain != NULL) {
+               char *buffer = (char *)chain->buffer + chain->misalign;
+               char *cp = find_eol_char(buffer+i, chain->off-i);
+               if (cp) {
+                       it->_internal.chain = chain;
+                       it->_internal.pos_in_chain = cp - buffer;
+                       it->pos += (cp - buffer) - i;
+                       return it->pos;
+               }
+               it->pos += chain->off - i;
+               i = 0;
+               chain = chain->next;
+       }
+
+       return (-1);
+}
+
+static inline int
+evbuffer_strspn(
+       struct evbuffer_ptr *ptr, const char *chrset)
+{
+       int count = 0;
+       struct evbuffer_chain *chain = ptr->_internal.chain;
+       size_t i = ptr->_internal.pos_in_chain;
+
+       if (!chain)
+               return -1;
+
+       while (1) {
+               char *buffer = (char *)chain->buffer + chain->misalign;
+               for (; i < chain->off; ++i) {
+                       const char *p = chrset;
+                       while (*p) {
+                               if (buffer[i] == *p++)
+                                       goto next;
+                       }
+                       ptr->_internal.chain = chain;
+                       ptr->_internal.pos_in_chain = i;
+                       ptr->pos += count;
+                       return count;
+               next:
+                       ++count;
+               }
+               i = 0;
+
+               if (! chain->next) {
+                       ptr->_internal.chain = chain;
+                       ptr->_internal.pos_in_chain = i;
+                       ptr->pos += count;
+                       return count;
+               }
+
+               chain = chain->next;
+       }
+}
+
+
+static inline char
+evbuffer_getchr(struct evbuffer_ptr *it)
+{
+       struct evbuffer_chain *chain = it->_internal.chain;
+       size_t off = it->_internal.pos_in_chain;
+
+       return chain->buffer[chain->misalign + off];
+}
+
+struct evbuffer_ptr
+evbuffer_search_eol(struct evbuffer *buffer,
+    struct evbuffer_ptr *start, size_t *eol_len_out,
+    enum evbuffer_eol_style eol_style)
+{
+       struct evbuffer_ptr it, it2;
+       size_t extra_drain = 0;
+       int ok = 0;
+
+       EVBUFFER_LOCK(buffer);
+
+       if (start) {
+               memcpy(&it, start, sizeof(it));
+       } else {
+               it.pos = 0;
+               it._internal.chain = buffer->first;
+               it._internal.pos_in_chain = 0;
+       }
+
+       /* the eol_style determines our first stop character and how many
+        * characters we are going to drain afterwards. */
+       switch (eol_style) {
+       case EVBUFFER_EOL_ANY:
+               if (evbuffer_find_eol_char(&it) < 0)
+                       goto done;
+               memcpy(&it2, &it, sizeof(it));
+               extra_drain = evbuffer_strspn(&it2, "\r\n");
+               break;
+       case EVBUFFER_EOL_CRLF_STRICT: {
+               it = evbuffer_search(buffer, "\r\n", 2, &it);
+               if (it.pos < 0)
+                       goto done;
+               extra_drain = 2;
+               break;
+       }
+       case EVBUFFER_EOL_CRLF:
+               while (1) {
+                       if (evbuffer_find_eol_char(&it) < 0)
+                               goto done;
+                       if (evbuffer_getchr(&it) == '\n') {
+                               extra_drain = 1;
+                               break;
+                       } else if (!evbuffer_ptr_memcmp(
+                                   buffer, &it, "\r\n", 2)) {
+                               extra_drain = 2;
+                               break;
+                       } else {
+                               if (evbuffer_ptr_set(buffer, &it, 1,
+                                       EVBUFFER_PTR_ADD)<0)
+                                       goto done;
+                       }
+               }
+               break;
+       case EVBUFFER_EOL_LF:
+               if (evbuffer_strchr(&it, '\n') < 0)
+                       goto done;
+               extra_drain = 1;
+               break;
+       default:
+               goto done;
+       }
+
+       ok = 1;
+done:
+       EVBUFFER_UNLOCK(buffer);
+
+       if (!ok) {
+               it.pos = -1;
+       }
+       if (eol_len_out)
+               *eol_len_out = extra_drain;
+
+       return it;
+}
+
+char *
+evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
+               enum evbuffer_eol_style eol_style)
+{
+       struct evbuffer_ptr it;
+       char *line;
+       size_t n_to_copy=0, extra_drain=0;
+       char *result = NULL;
+
+       EVBUFFER_LOCK(buffer);
+
+       if (buffer->freeze_start) {
+               goto done;
+       }
+
+       it = evbuffer_search_eol(buffer, NULL, &extra_drain, eol_style);
+       if (it.pos < 0)
+               goto done;
+       n_to_copy = it.pos;
+
+       if ((line = mm_malloc(n_to_copy+1)) == NULL) {
+               event_warn("%s: out of memory", __func__);
+               goto done;
+       }
+
+       evbuffer_remove(buffer, line, n_to_copy);
+       line[n_to_copy] = '\0';
+
+       evbuffer_drain(buffer, extra_drain);
+       result = line;
+done:
+       EVBUFFER_UNLOCK(buffer);
+
+       if (n_read_out)
+               *n_read_out = result ? n_to_copy : 0;
+
+       return result;
+}
+
+#define EVBUFFER_CHAIN_MAX_AUTO_SIZE 4096
+
+/* Adds data to an event buffer */
+
+int
+evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)
+{
+       struct evbuffer_chain *chain, *tmp;
+       const unsigned char *data = data_in;
+       size_t remain, to_alloc;
+       int result = -1;
+
+       EVBUFFER_LOCK(buf);
+
+       if (buf->freeze_end) {
+               goto done;
+       }
+
+       chain = buf->last;
+
+       /* If there are no chains allocated for this buffer, allocate one
+        * big enough to hold all the data. */
+       if (chain == NULL) {
+               chain = evbuffer_chain_new(datlen);
+               if (!chain)
+                       goto done;
+               evbuffer_chain_insert(buf, chain);
+       }
+
+       if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
+               remain = (size_t)(chain->buffer_len - chain->misalign - chain->off);
+               if (remain >= datlen) {
+                       /* there's enough space to hold all the data in the
+                        * current last chain */
+                       memcpy(chain->buffer + chain->misalign + chain->off,
+                           data, datlen);
+                       chain->off += datlen;
+                       buf->total_len += datlen;
+                       buf->n_add_for_cb += datlen;
+                       goto out;
+               } else if (!CHAIN_PINNED(chain) &&
+                   evbuffer_chain_should_realign(chain, datlen)) {
+                       /* we can fit the data into the misalignment */
+                       evbuffer_chain_align(chain);
+
+                       memcpy(chain->buffer + chain->off, data, datlen);
+                       chain->off += datlen;
+                       buf->total_len += datlen;
+                       buf->n_add_for_cb += datlen;
+                       goto out;
+               }
+       } else {
+               /* we cannot write any data to the last chain */
+               remain = 0;
+       }
+
+       /* we need to add another chain */
+       to_alloc = chain->buffer_len;
+       if (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)
+               to_alloc <<= 1;
+       if (datlen > to_alloc)
+               to_alloc = datlen;
+       tmp = evbuffer_chain_new(to_alloc);
+       if (tmp == NULL)
+               goto done;
+
+       if (remain) {
+               memcpy(chain->buffer + chain->misalign + chain->off,
+                   data, remain);
+               chain->off += remain;
+               buf->total_len += remain;
+               buf->n_add_for_cb += remain;
+       }
+
+       data += remain;
+       datlen -= remain;
+
+       memcpy(tmp->buffer, data, datlen);
+       tmp->off = datlen;
+       evbuffer_chain_insert(buf, tmp);
+       buf->n_add_for_cb += datlen;
+
+out:
+       evbuffer_invoke_callbacks(buf);
+       result = 0;
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+
+int
+evbuffer_prepend(struct evbuffer *buf, const void *data, size_t datlen)
+{
+       struct evbuffer_chain *chain, *tmp;
+       int result = -1;
+
+       EVBUFFER_LOCK(buf);
+
+       if (buf->freeze_start) {
+               goto done;
+       }
+
+       chain = buf->first;
+
+       if (chain == NULL) {
+               chain = evbuffer_chain_new(datlen);
+               if (!chain)
+                       goto done;
+               evbuffer_chain_insert(buf, chain);
+       }
+
+       /* we cannot touch immutable buffers */
+       if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
+               /* If this chain is empty, we can treat it as
+                * 'empty at the beginning' rather than 'empty at the end' */
+               if (chain->off == 0)
+                       chain->misalign = chain->buffer_len;
+
+               if ((size_t)chain->misalign >= datlen) {
+                       /* we have enough space to fit everything */
+                       memcpy(chain->buffer + chain->misalign - datlen,
+                           data, datlen);
+                       chain->off += datlen;
+                       chain->misalign -= datlen;
+                       buf->total_len += datlen;
+                       buf->n_add_for_cb += datlen;
+                       goto out;
+               } else if (chain->misalign) {
+                       /* we can only fit some of the data. */
+                       memcpy(chain->buffer,
+                           (char*)data + datlen - chain->misalign,
+                           (size_t)chain->misalign);
+                       chain->off += (size_t)chain->misalign;
+                       buf->total_len += (size_t)chain->misalign;
+                       buf->n_add_for_cb += (size_t)chain->misalign;
+                       datlen -= (size_t)chain->misalign;
+                       chain->misalign = 0;
+               }
+       }
+
+       /* we need to add another chain */
+       if ((tmp = evbuffer_chain_new(datlen)) == NULL)
+               goto done;
+       buf->first = tmp;
+       if (buf->last_with_datap == &buf->first)
+               buf->last_with_datap = &tmp->next;
+
+       tmp->next = chain;
+
+       tmp->off = datlen;
+       tmp->misalign = tmp->buffer_len - datlen;
+
+       memcpy(tmp->buffer + tmp->misalign, data, datlen);
+       buf->total_len += datlen;
+       buf->n_add_for_cb += (size_t)chain->misalign;
+
+out:
+       evbuffer_invoke_callbacks(buf);
+       result = 0;
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+
+/** Helper: realigns the memory in chain->buffer so that misalign is 0. */
+static void
+evbuffer_chain_align(struct evbuffer_chain *chain)
+{
+       EVUTIL_ASSERT(!(chain->flags & EVBUFFER_IMMUTABLE));
+       EVUTIL_ASSERT(!(chain->flags & EVBUFFER_MEM_PINNED_ANY));
+       memmove(chain->buffer, chain->buffer + chain->misalign, chain->off);
+       chain->misalign = 0;
+}
+
+#define MAX_TO_COPY_IN_EXPAND 4096
+#define MAX_TO_REALIGN_IN_EXPAND 2048
+
+/** Helper: return true iff we should realign chain to fit datalen bytes of
+    data in it. */
+static int
+evbuffer_chain_should_realign(struct evbuffer_chain *chain,
+    size_t datlen)
+{
+       return chain->buffer_len - chain->off >= datlen &&
+           (chain->off < chain->buffer_len / 2) &&
+           (chain->off <= MAX_TO_REALIGN_IN_EXPAND);
+}
+
+/* Expands the available space in the event buffer to at least datlen, all in
+ * a single chunk.  Return that chunk. */
+static struct evbuffer_chain *
+evbuffer_expand_singlechain(struct evbuffer *buf, size_t datlen)
+{
+       struct evbuffer_chain *chain, **chainp;
+       struct evbuffer_chain *result = NULL;
+       ASSERT_EVBUFFER_LOCKED(buf);
+
+       chainp = buf->last_with_datap;
+
+       /* XXX If *chainp is no longer writeable, but has enough space in its
+        * misalign, this might be a bad idea: we could still use *chainp, not
+        * (*chainp)->next. */
+       if (*chainp && CHAIN_SPACE_LEN(*chainp) == 0)
+               chainp = &(*chainp)->next;
+
+       /* 'chain' now points to the first chain with writable space (if any)
+        * We will either use it, realign it, replace it, or resize it. */
+       chain = *chainp;
+
+       if (chain == NULL ||
+           (chain->flags & (EVBUFFER_IMMUTABLE|EVBUFFER_MEM_PINNED_ANY))) {
+               /* We can't use the last_with_data chain at all.  Just add a
+                * new one that's big enough. */
+               goto insert_new;
+       }
+
+       /* If we can fit all the data, then we don't have to do anything */
+       if (CHAIN_SPACE_LEN(chain) >= datlen) {
+               result = chain;
+               goto ok;
+       }
+
+       /* If the chain is completely empty, just replace it by adding a new
+        * empty chain. */
+       if (chain->off == 0) {
+               goto insert_new;
+       }
+
+       /* If the misalignment plus the remaining space fulfills our data
+        * needs, we could just force an alignment to happen.  Afterwards, we
+        * have enough space.  But only do this if we're saving a lot of space
+        * and not moving too much data.  Otherwise the space savings are
+        * probably offset by the time lost in copying.
+        */
+       if (evbuffer_chain_should_realign(chain, datlen)) {
+               evbuffer_chain_align(chain);
+               result = chain;
+               goto ok;
+       }
+
+       /* At this point, we can either resize the last chunk with space in
+        * it, use the next chunk after it, or   If we add a new chunk, we waste
+        * CHAIN_SPACE_LEN(chain) bytes in the former last chunk.  If we
+        * resize, we have to copy chain->off bytes.
+        */
+
+       /* Would expanding this chunk be affordable and worthwhile? */
+       if (CHAIN_SPACE_LEN(chain) < chain->buffer_len / 8 ||
+           chain->off > MAX_TO_COPY_IN_EXPAND) {
+               /* It's not worth resizing this chain. Can the next one be
+                * used? */
+               if (chain->next && CHAIN_SPACE_LEN(chain->next) >= datlen) {
+                       /* Yes, we can just use the next chain (which should
+                        * be empty. */
+                       result = chain->next;
+                       goto ok;
+               } else {
+                       /* No; append a new chain (which will free all
+                        * terminal empty chains.) */
+                       goto insert_new;
+               }
+       } else {
+               /* Okay, we're going to try to resize this chain: Not doing so
+                * would waste at least 1/8 of its current allocation, and we
+                * can do so without having to copy more than
+                * MAX_TO_COPY_IN_EXPAND bytes. */
+               /* figure out how much space we need */
+               size_t length = chain->off + datlen;
+               struct evbuffer_chain *tmp = evbuffer_chain_new(length);
+               if (tmp == NULL)
+                       goto err;
+
+               /* copy the data over that we had so far */
+               tmp->off = chain->off;
+               memcpy(tmp->buffer, chain->buffer + chain->misalign,
+                   chain->off);
+               /* fix up the list */
+               EVUTIL_ASSERT(*chainp == chain);
+               result = *chainp = tmp;
+
+               if (buf->last == chain)
+                       buf->last = tmp;
+
+               tmp->next = chain->next;
+               evbuffer_chain_free(chain);
+               goto ok;
+       }
+
+insert_new:
+       result = evbuffer_chain_insert_new(buf, datlen);
+       if (!result)
+               goto err;
+ok:
+       EVUTIL_ASSERT(result);
+       EVUTIL_ASSERT(CHAIN_SPACE_LEN(result) >= datlen);
+err:
+       return result;
+}
+
+/* Make sure that datlen bytes are available for writing in the last n
+ * chains.  Never copies or moves data. */
+int
+_evbuffer_expand_fast(struct evbuffer *buf, size_t datlen, int n)
+{
+       struct evbuffer_chain *chain = buf->last, *tmp, *next;
+       size_t avail;
+       int used;
+
+       ASSERT_EVBUFFER_LOCKED(buf);
+       EVUTIL_ASSERT(n >= 2);
+
+       if (chain == NULL || (chain->flags & EVBUFFER_IMMUTABLE)) {
+               /* There is no last chunk, or we can't touch the last chunk.
+                * Just add a new chunk. */
+               chain = evbuffer_chain_new(datlen);
+               if (chain == NULL)
+                       return (-1);
+
+               evbuffer_chain_insert(buf, chain);
+               return (0);
+       }
+
+       used = 0; /* number of chains we're using space in. */
+       avail = 0; /* how much space they have. */
+       /* How many bytes can we stick at the end of buffer as it is?  Iterate
+        * over the chains at the end of the buffer, tring to see how much
+        * space we have in the first n. */
+       for (chain = *buf->last_with_datap; chain; chain = chain->next) {
+               if (chain->off) {
+                       size_t space = (size_t) CHAIN_SPACE_LEN(chain);
+                       EVUTIL_ASSERT(chain == *buf->last_with_datap);
+                       if (space) {
+                               avail += space;
+                               ++used;
+                       }
+               } else {
+                       /* No data in chain; realign it. */
+                       chain->misalign = 0;
+                       avail += chain->buffer_len;
+                       ++used;
+               }
+               if (avail >= datlen) {
+                       /* There is already enough space.  Just return */
+                       return (0);
+               }
+               if (used == n)
+                       break;
+       }
+
+       /* There wasn't enough space in the first n chains with space in
+        * them. Either add a new chain with enough space, or replace all
+        * empty chains with one that has enough space, depending on n. */
+       if (used < n) {
+               /* The loop ran off the end of the chains before it hit n
+                * chains; we can add another. */
+               EVUTIL_ASSERT(chain == NULL);
+
+               tmp = evbuffer_chain_new(datlen - avail);
+               if (tmp == NULL)
+                       return (-1);
+
+               buf->last->next = tmp;
+               buf->last = tmp;
+               /* (we would only set last_with_data if we added the first
+                * chain. But if the buffer had no chains, we would have
+                * just allocated a new chain earlier) */
+               return (0);
+       } else {
+               /* Nuke _all_ the empty chains. */
+               int rmv_all = 0; /* True iff we removed last_with_data. */
+               chain = *buf->last_with_datap;
+               if (!chain->off) {
+                       EVUTIL_ASSERT(chain == buf->first);
+                       rmv_all = 1;
+                       avail = 0;
+               } else {
+                       avail = (size_t) CHAIN_SPACE_LEN(chain);
+                       chain = chain->next;
+               }
+
+
+               for (; chain; chain = next) {
+                       next = chain->next;
+                       EVUTIL_ASSERT(chain->off == 0);
+                       evbuffer_chain_free(chain);
+               }
+               tmp = evbuffer_chain_new(datlen - avail);
+               if (tmp == NULL) {
+                       if (rmv_all) {
+                               ZERO_CHAIN(buf);
+                       } else {
+                               buf->last = *buf->last_with_datap;
+                               (*buf->last_with_datap)->next = NULL;
+                       }
+                       return (-1);
+               }
+
+               if (rmv_all) {
+                       buf->first = buf->last = tmp;
+                       buf->last_with_datap = &buf->first;
+               } else {
+                       (*buf->last_with_datap)->next = tmp;
+                       buf->last = tmp;
+               }
+               return (0);
+       }
+}
+
+int
+evbuffer_expand(struct evbuffer *buf, size_t datlen)
+{
+       struct evbuffer_chain *chain;
+
+       EVBUFFER_LOCK(buf);
+       chain = evbuffer_expand_singlechain(buf, datlen);
+       EVBUFFER_UNLOCK(buf);
+       return chain ? 0 : -1;
+}
+
+/*
+ * Reads data from a file descriptor into a buffer.
+ */
+
+#if defined(_EVENT_HAVE_SYS_UIO_H) || defined(WIN32)
+#define USE_IOVEC_IMPL
+#endif
+
+#ifdef USE_IOVEC_IMPL
+
+#ifdef _EVENT_HAVE_SYS_UIO_H
+/* number of iovec we use for writev, fragmentation is going to determine
+ * how much we end up writing */
+
+#define DEFAULT_WRITE_IOVEC 128
+
+#if defined(UIO_MAXIOV) && UIO_MAXIOV < DEFAULT_WRITE_IOVEC
+#define NUM_WRITE_IOVEC UIO_MAXIOV
+#elif defined(IOV_MAX) && IOV_MAX < DEFAULT_WRITE_IOVEC
+#define NUM_WRITE_IOVEC IOV_MAX
+#else
+#define NUM_WRITE_IOVEC DEFAULT_WRITE_IOVEC
+#endif
+
+#define IOV_TYPE struct iovec
+#define IOV_PTR_FIELD iov_base
+#define IOV_LEN_FIELD iov_len
+#define IOV_LEN_TYPE size_t
+#else
+#define NUM_WRITE_IOVEC 16
+#define IOV_TYPE WSABUF
+#define IOV_PTR_FIELD buf
+#define IOV_LEN_FIELD len
+#define IOV_LEN_TYPE unsigned long
+#endif
+#endif
+#define NUM_READ_IOVEC 4
+
+#define EVBUFFER_MAX_READ      4096
+
+/** Helper function to figure out which space to use for reading data into
+    an evbuffer.  Internal use only.
+
+    @param buf The buffer to read into
+    @param howmuch How much we want to read.
+    @param vecs An array of two or more iovecs or WSABUFs.
+    @param n_vecs_avail The length of vecs
+    @param chainp A pointer to a variable to hold the first chain we're
+      reading into.
+    @param exact Boolean: if true, we do not provide more than 'howmuch'
+      space in the vectors, even if more space is available.
+    @return The number of buffers we're using.
+ */
+int
+_evbuffer_read_setup_vecs(struct evbuffer *buf, ev_ssize_t howmuch,
+    struct evbuffer_iovec *vecs, int n_vecs_avail,
+    struct evbuffer_chain ***chainp, int exact)
+{
+       struct evbuffer_chain *chain;
+       struct evbuffer_chain **firstchainp;
+       size_t so_far;
+       int i;
+       ASSERT_EVBUFFER_LOCKED(buf);
+
+       if (howmuch < 0)
+               return -1;
+
+       so_far = 0;
+       /* Let firstchain be the first chain with any space on it */
+       firstchainp = buf->last_with_datap;
+       if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
+               firstchainp = &(*firstchainp)->next;
+       }
+
+       chain = *firstchainp;
+       for (i = 0; i < n_vecs_avail && so_far < (size_t)howmuch; ++i) {
+               size_t avail = (size_t) CHAIN_SPACE_LEN(chain);
+               if (avail > (howmuch - so_far) && exact)
+                       avail = howmuch - so_far;
+               vecs[i].iov_base = CHAIN_SPACE_PTR(chain);
+               vecs[i].iov_len = avail;
+               so_far += avail;
+               chain = chain->next;
+       }
+
+       *chainp = firstchainp;
+       return i;
+}
+
+static int
+get_n_bytes_readable_on_socket(evutil_socket_t fd)
+{
+#if defined(FIONREAD) && defined(WIN32)
+       unsigned long lng = EVBUFFER_MAX_READ;
+       if (ioctlsocket(fd, FIONREAD, &lng) < 0)
+               return -1;
+       return (int)lng;
+#elif defined(FIONREAD)
+       int n = EVBUFFER_MAX_READ;
+       if (ioctl(fd, FIONREAD, &n) < 0)
+               return -1;
+       return n;
+#else
+       return EVBUFFER_MAX_READ;
+#endif
+}
+
+/* TODO(niels): should this function return ev_ssize_t and take ev_ssize_t
+ * as howmuch? */
+int
+evbuffer_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch)
+{
+       struct evbuffer_chain **chainp;
+       int n;
+       int result;
+
+#ifdef USE_IOVEC_IMPL
+       int nvecs, i, remaining;
+#else
+       struct evbuffer_chain *chain;
+       unsigned char *p;
+#endif
+
+       EVBUFFER_LOCK(buf);
+
+       if (buf->freeze_end) {
+               result = -1;
+               goto done;
+       }
+
+       n = get_n_bytes_readable_on_socket(fd);
+       if (n <= 0 || n > EVBUFFER_MAX_READ)
+               n = EVBUFFER_MAX_READ;
+       if (howmuch < 0 || howmuch > n)
+               howmuch = n;
+
+#ifdef USE_IOVEC_IMPL
+       /* Since we can use iovecs, we're willing to use the last
+        * NUM_READ_IOVEC chains. */
+       if (_evbuffer_expand_fast(buf, howmuch, NUM_READ_IOVEC) == -1) {
+               result = -1;
+               goto done;
+       } else {
+               IOV_TYPE vecs[NUM_READ_IOVEC];
+#ifdef _EVBUFFER_IOVEC_IS_NATIVE
+               nvecs = _evbuffer_read_setup_vecs(buf, howmuch, vecs,
+                   NUM_READ_IOVEC, &chainp, 1);
+#else
+               /* We aren't using the native struct iovec.  Therefore,
+                  we are on win32. */
+               struct evbuffer_iovec ev_vecs[NUM_READ_IOVEC];
+               nvecs = _evbuffer_read_setup_vecs(buf, howmuch, ev_vecs, 2,
+                   &chainp, 1);
+
+               for (i=0; i < nvecs; ++i)
+                       WSABUF_FROM_EVBUFFER_IOV(&vecs[i], &ev_vecs[i]);
+#endif
+
+#ifdef WIN32
+               {
+                       DWORD bytesRead;
+                       DWORD flags=0;
+                       if (WSARecv(fd, vecs, nvecs, &bytesRead, &flags, NULL, NULL)) {
+                               /* The read failed. It might be a close,
+                                * or it might be an error. */
+                               if (WSAGetLastError() == WSAECONNABORTED)
+                                       n = 0;
+                               else
+                                       n = -1;
+                       } else
+                               n = bytesRead;
+               }
+#else
+               n = readv(fd, vecs, nvecs);
+#endif
+       }
+
+#else /*!USE_IOVEC_IMPL*/
+       /* If we don't have FIONREAD, we might waste some space here */
+       /* XXX we _will_ waste some space here if there is any space left
+        * over on buf->last. */
+       if ((chain = evbuffer_expand_singlechain(buf, howmuch)) == NULL) {
+               result = -1;
+               goto done;
+       }
+
+       /* We can append new data at this point */
+       p = chain->buffer + chain->misalign + chain->off;
+
+#ifndef WIN32
+       n = read(fd, p, howmuch);
+#else
+       n = recv(fd, p, howmuch, 0);
+#endif
+#endif /* USE_IOVEC_IMPL */
+
+       if (n == -1) {
+               result = -1;
+               goto done;
+       }
+       if (n == 0) {
+               result = 0;
+               goto done;
+       }
+
+#ifdef USE_IOVEC_IMPL
+       remaining = n;
+       for (i=0; i < nvecs; ++i) {
+               ev_ssize_t space = (ev_ssize_t) CHAIN_SPACE_LEN(*chainp);
+               if (space < remaining) {
+                       (*chainp)->off += space;
+                       remaining -= (int)space;
+               } else {
+                       (*chainp)->off += remaining;
+                       buf->last_with_datap = chainp;
+                       break;
+               }
+               chainp = &(*chainp)->next;
+       }
+#else
+       chain->off += n;
+       advance_last_with_data(buf);
+#endif
+       buf->total_len += n;
+       buf->n_add_for_cb += n;
+
+       /* Tell someone about changes in this buffer */
+       evbuffer_invoke_callbacks(buf);
+       result = n;
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+
+#ifdef WIN32
+static int
+evbuffer_readfile(struct evbuffer *buf, evutil_socket_t fd, ev_ssize_t howmuch)
+{
+       int result;
+       int nchains, n;
+       struct evbuffer_iovec v[2];
+
+       EVBUFFER_LOCK(buf);
+
+       if (buf->freeze_end) {
+               result = -1;
+               goto done;
+       }
+
+       if (howmuch < 0)
+               howmuch = 16384;
+
+
+       /* XXX we _will_ waste some space here if there is any space left
+        * over on buf->last. */
+       nchains = evbuffer_reserve_space(buf, howmuch, v, 2);
+       if (nchains < 1 || nchains > 2) {
+               result = -1;
+               goto done;
+       }
+       n = read((int)fd, v[0].iov_base, (unsigned int)v[0].iov_len);
+       if (n <= 0) {
+               result = n;
+               goto done;
+       }
+       v[0].iov_len = (IOV_LEN_TYPE) n; /* XXXX another problem with big n.*/
+       if (nchains > 1) {
+               n = read((int)fd, v[1].iov_base, (unsigned int)v[1].iov_len);
+               if (n <= 0) {
+                       result = (unsigned long) v[0].iov_len;
+                       evbuffer_commit_space(buf, v, 1);
+                       goto done;
+               }
+               v[1].iov_len = n;
+       }
+       evbuffer_commit_space(buf, v, nchains);
+
+       result = n;
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+#endif
+
+#ifdef USE_IOVEC_IMPL
+static inline int
+evbuffer_write_iovec(struct evbuffer *buffer, evutil_socket_t fd,
+    ev_ssize_t howmuch)
+{
+       IOV_TYPE iov[NUM_WRITE_IOVEC];
+       struct evbuffer_chain *chain = buffer->first;
+       int n, i = 0;
+
+       if (howmuch < 0)
+               return -1;
+
+       ASSERT_EVBUFFER_LOCKED(buffer);
+       /* XXX make this top out at some maximal data length?  if the
+        * buffer has (say) 1MB in it, split over 128 chains, there's
+        * no way it all gets written in one go. */
+       while (chain != NULL && i < NUM_WRITE_IOVEC && howmuch) {
+#ifdef USE_SENDFILE
+               /* we cannot write the file info via writev */
+               if (chain->flags & EVBUFFER_SENDFILE)
+                       break;
+#endif
+               iov[i].IOV_PTR_FIELD = (void *) (chain->buffer + chain->misalign);
+               if ((size_t)howmuch >= chain->off) {
+                       /* XXXcould be problematic when windows supports mmap*/
+                       iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)chain->off;
+                       howmuch -= chain->off;
+               } else {
+                       /* XXXcould be problematic when windows supports mmap*/
+                       iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)howmuch;
+                       break;
+               }
+               chain = chain->next;
+       }
+#ifdef WIN32
+       {
+               DWORD bytesSent;
+               if (WSASend(fd, iov, i, &bytesSent, 0, NULL, NULL))
+                       n = -1;
+               else
+                       n = bytesSent;
+       }
+#else
+       n = writev(fd, iov, i);
+#endif
+       return (n);
+}
+#endif
+
+#ifdef USE_SENDFILE
+static inline int
+evbuffer_write_sendfile(struct evbuffer *buffer, evutil_socket_t fd,
+    ev_ssize_t howmuch)
+{
+       struct evbuffer_chain *chain = buffer->first;
+       struct evbuffer_chain_fd *info =
+           EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd, chain);
+#if defined(SENDFILE_IS_MACOSX) || defined(SENDFILE_IS_FREEBSD)
+       int res;
+       off_t len = chain->off;
+#elif defined(SENDFILE_IS_LINUX) || defined(SENDFILE_IS_SOLARIS)
+       ev_ssize_t res;
+       off_t offset = chain->misalign;
+#endif
+
+       ASSERT_EVBUFFER_LOCKED(buffer);
+
+#if defined(SENDFILE_IS_MACOSX)
+       res = sendfile(info->fd, fd, chain->misalign, &len, NULL, 0);
+       if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
+               return (-1);
+
+       return (len);
+#elif defined(SENDFILE_IS_FREEBSD)
+       res = sendfile(info->fd, fd, chain->misalign, chain->off, NULL, &len, 0);
+       if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
+               return (-1);
+
+       return (len);
+#elif defined(SENDFILE_IS_LINUX)
+       /* TODO(niels): implement splice */
+       res = sendfile(fd, info->fd, &offset, chain->off);
+       if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
+               /* if this is EAGAIN or EINTR return 0; otherwise, -1 */
+               return (0);
+       }
+       return (res);
+#elif defined(SENDFILE_IS_SOLARIS)
+       {
+               const off_t offset_orig = offset;
+               res = sendfile(fd, info->fd, &offset, chain->off);
+               if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
+                       if (offset - offset_orig)
+                               return offset - offset_orig;
+                       /* if this is EAGAIN or EINTR and no bytes were
+                        * written, return 0 */
+                       return (0);
+               }
+               return (res);
+       }
+#endif
+}
+#endif
+
+int
+evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
+    ev_ssize_t howmuch)
+{
+       int n = -1;
+
+       EVBUFFER_LOCK(buffer);
+
+       if (buffer->freeze_start) {
+               goto done;
+       }
+
+       if (howmuch < 0 || (size_t)howmuch > buffer->total_len)
+               howmuch = buffer->total_len;
+
+       if (howmuch > 0) {
+#ifdef USE_SENDFILE
+               struct evbuffer_chain *chain = buffer->first;
+               if (chain != NULL && (chain->flags & EVBUFFER_SENDFILE))
+                       n = evbuffer_write_sendfile(buffer, fd, howmuch);
+               else {
+#endif
+#ifdef USE_IOVEC_IMPL
+               n = evbuffer_write_iovec(buffer, fd, howmuch);
+#elif defined(WIN32)
+               /* XXX(nickm) Don't disable this code until we know if
+                * the WSARecv code above works. */
+               void *p = evbuffer_pullup(buffer, howmuch);
+               n = send(fd, p, howmuch, 0);
+#else
+               void *p = evbuffer_pullup(buffer, howmuch);
+               n = write(fd, p, howmuch);
+#endif
+#ifdef USE_SENDFILE
+               }
+#endif
+       }
+
+       if (n > 0)
+               evbuffer_drain(buffer, n);
+
+done:
+       EVBUFFER_UNLOCK(buffer);
+       return (n);
+}
+
+int
+evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd)
+{
+       return evbuffer_write_atmost(buffer, fd, -1);
+}
+
+unsigned char *
+evbuffer_find(struct evbuffer *buffer, const unsigned char *what, size_t len)
+{
+       unsigned char *search;
+       struct evbuffer_ptr ptr;
+
+       EVBUFFER_LOCK(buffer);
+
+       ptr = evbuffer_search(buffer, (const char *)what, len, NULL);
+       if (ptr.pos < 0) {
+               search = NULL;
+       } else {
+               search = evbuffer_pullup(buffer, ptr.pos + len);
+               if (search)
+                       search += ptr.pos;
+       }
+       EVBUFFER_UNLOCK(buffer);
+       return search;
+}
+
+int
+evbuffer_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos,
+    size_t position, enum evbuffer_ptr_how how)
+{
+       size_t left = position;
+       struct evbuffer_chain *chain = NULL;
+
+       EVBUFFER_LOCK(buf);
+
+       switch (how) {
+       case EVBUFFER_PTR_SET:
+               chain = buf->first;
+               pos->pos = position;
+               position = 0;
+               break;
+       case EVBUFFER_PTR_ADD:
+               /* this avoids iterating over all previous chains if
+                  we just want to advance the position */
+               chain = pos->_internal.chain;
+               pos->pos += position;
+               position = pos->_internal.pos_in_chain;
+               break;
+       }
+
+       while (chain && position + left >= chain->off) {
+               left -= chain->off - position;
+               chain = chain->next;
+               position = 0;
+       }
+       if (chain) {
+               pos->_internal.chain = chain;
+               pos->_internal.pos_in_chain = position + left;
+       } else {
+               pos->_internal.chain = NULL;
+               pos->pos = -1;
+       }
+
+       EVBUFFER_UNLOCK(buf);
+
+       return chain != NULL ? 0 : -1;
+}
+
+/**
+   Compare the bytes in buf at position pos to the len bytes in mem.  Return
+   less than 0, 0, or greater than 0 as memcmp.
+ */
+static int
+evbuffer_ptr_memcmp(const struct evbuffer *buf, const struct evbuffer_ptr *pos,
+    const char *mem, size_t len)
+{
+       struct evbuffer_chain *chain;
+       size_t position;
+       int r;
+
+       ASSERT_EVBUFFER_LOCKED(buf);
+
+       if (pos->pos + len > buf->total_len)
+               return -1;
+
+       chain = pos->_internal.chain;
+       position = pos->_internal.pos_in_chain;
+       while (len && chain) {
+               size_t n_comparable;
+               if (len + position > chain->off)
+                       n_comparable = chain->off - position;
+               else
+                       n_comparable = len;
+               r = memcmp(chain->buffer + chain->misalign + position, mem,
+                   n_comparable);
+               if (r)
+                       return r;
+               mem += n_comparable;
+               len -= n_comparable;
+               position = 0;
+               chain = chain->next;
+       }
+
+       return 0;
+}
+
+struct evbuffer_ptr
+evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start)
+{
+       return evbuffer_search_range(buffer, what, len, start, NULL);
+}
+
+struct evbuffer_ptr
+evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start, const struct evbuffer_ptr *end)
+{
+       struct evbuffer_ptr pos;
+       struct evbuffer_chain *chain, *last_chain = NULL;
+       const unsigned char *p;
+       char first;
+
+       EVBUFFER_LOCK(buffer);
+
+       if (start) {
+               memcpy(&pos, start, sizeof(pos));
+               chain = pos._internal.chain;
+       } else {
+               pos.pos = 0;
+               chain = pos._internal.chain = buffer->first;
+               pos._internal.pos_in_chain = 0;
+       }
+
+       if (end)
+               last_chain = end->_internal.chain;
+
+       if (!len || len > EV_SSIZE_MAX)
+               goto done;
+
+       first = what[0];
+
+       while (chain) {
+               const unsigned char *start_at =
+                   chain->buffer + chain->misalign +
+                   pos._internal.pos_in_chain;
+               p = memchr(start_at, first,
+                   chain->off - pos._internal.pos_in_chain);
+               if (p) {
+                       pos.pos += p - start_at;
+                       pos._internal.pos_in_chain += p - start_at;
+                       if (!evbuffer_ptr_memcmp(buffer, &pos, what, len)) {
+                               if (end && pos.pos + (ev_ssize_t)len > end->pos)
+                                       goto not_found;
+                               else
+                                       goto done;
+                       }
+                       ++pos.pos;
+                       ++pos._internal.pos_in_chain;
+                       if (pos._internal.pos_in_chain == chain->off) {
+                               chain = pos._internal.chain = chain->next;
+                               pos._internal.pos_in_chain = 0;
+                       }
+               } else {
+                       if (chain == last_chain)
+                               goto not_found;
+                       pos.pos += chain->off - pos._internal.pos_in_chain;
+                       chain = pos._internal.chain = chain->next;
+                       pos._internal.pos_in_chain = 0;
+               }
+       }
+
+not_found:
+       pos.pos = -1;
+       pos._internal.chain = NULL;
+done:
+       EVBUFFER_UNLOCK(buffer);
+       return pos;
+}
+
+int
+evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
+    struct evbuffer_ptr *start_at,
+    struct evbuffer_iovec *vec, int n_vec)
+{
+       struct evbuffer_chain *chain;
+       int idx = 0;
+       ev_ssize_t len_so_far = 0;
+
+       EVBUFFER_LOCK(buffer);
+
+       if (start_at) {
+               chain = start_at->_internal.chain;
+               len_so_far = chain->off
+                   - start_at->_internal.pos_in_chain;
+               idx = 1;
+               if (n_vec > 0) {
+                       vec[0].iov_base = chain->buffer + chain->misalign
+                           + start_at->_internal.pos_in_chain;
+                       vec[0].iov_len = len_so_far;
+               }
+               chain = chain->next;
+       } else {
+               chain = buffer->first;
+       }
+
+       if (n_vec == 0 && len < 0) {
+               /* If no vectors are provided and they asked for "everything",
+                * pretend they asked for the actual available amount. */
+               len = buffer->total_len - len_so_far;
+       }
+
+       while (chain) {
+               if (len >= 0 && len_so_far >= len)
+                       break;
+               if (idx<n_vec) {
+                       vec[idx].iov_base = chain->buffer + chain->misalign;
+                       vec[idx].iov_len = chain->off;
+               } else if (len<0) {
+                       break;
+               }
+               ++idx;
+               len_so_far += chain->off;
+               chain = chain->next;
+       }
+
+       EVBUFFER_UNLOCK(buffer);
+
+       return idx;
+}
+
+
+int
+evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
+{
+       char *buffer;
+       size_t space;
+       int sz, result = -1;
+       va_list aq;
+       struct evbuffer_chain *chain;
+
+
+       EVBUFFER_LOCK(buf);
+
+       if (buf->freeze_end) {
+               goto done;
+       }
+
+       /* make sure that at least some space is available */
+       if ((chain = evbuffer_expand_singlechain(buf, 64)) == NULL)
+               goto done;
+
+       for (;;) {
+#if 0
+               size_t used = chain->misalign + chain->off;
+               buffer = (char *)chain->buffer + chain->misalign + chain->off;
+               EVUTIL_ASSERT(chain->buffer_len >= used);
+               space = chain->buffer_len - used;
+#endif
+               buffer = (char*) CHAIN_SPACE_PTR(chain);
+               space = (size_t) CHAIN_SPACE_LEN(chain);
+
+#ifndef va_copy
+#define        va_copy(dst, src)       memcpy(&(dst), &(src), sizeof(va_list))
+#endif
+               va_copy(aq, ap);
+
+               sz = evutil_vsnprintf(buffer, space, fmt, aq);
+
+               va_end(aq);
+
+               if (sz < 0)
+                       goto done;
+               if ((size_t)sz < space) {
+                       chain->off += sz;
+                       buf->total_len += sz;
+                       buf->n_add_for_cb += sz;
+
+                       advance_last_with_data(buf);
+                       evbuffer_invoke_callbacks(buf);
+                       result = sz;
+                       goto done;
+               }
+               if ((chain = evbuffer_expand_singlechain(buf, sz + 1)) == NULL)
+                       goto done;
+       }
+       /* NOTREACHED */
+
+done:
+       EVBUFFER_UNLOCK(buf);
+       return result;
+}
+
+int
+evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
+{
+       int res = -1;
+       va_list ap;
+
+       va_start(ap, fmt);
+       res = evbuffer_add_vprintf(buf, fmt, ap);
+       va_end(ap);
+
+       return (res);
+}
+
+int
+evbuffer_add_reference(struct evbuffer *outbuf,
+    const void *data, size_t datlen,
+    evbuffer_ref_cleanup_cb cleanupfn, void *extra)
+{
+       struct evbuffer_chain *chain;
+       struct evbuffer_chain_reference *info;
+       int result = -1;
+
+       chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_reference));
+       if (!chain)
+               return (-1);
+       chain->flags |= EVBUFFER_REFERENCE | EVBUFFER_IMMUTABLE;
+       chain->buffer = (u_char *)data;
+       chain->buffer_len = datlen;
+       chain->off = datlen;
+
+       info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_reference, chain);
+       info->cleanupfn = cleanupfn;
+       info->extra = extra;
+
+       EVBUFFER_LOCK(outbuf);
+       if (outbuf->freeze_end) {
+               /* don't call chain_free; we do not want to actually invoke
+                * the cleanup function */
+               mm_free(chain);
+               goto done;
+       }
+       evbuffer_chain_insert(outbuf, chain);
+       outbuf->n_add_for_cb += datlen;
+
+       evbuffer_invoke_callbacks(outbuf);
+
+       result = 0;
+done:
+       EVBUFFER_UNLOCK(outbuf);
+
+       return result;
+}
+
+/* TODO(niels): maybe we don't want to own the fd, however, in that
+ * case, we should dup it - dup is cheap.  Perhaps, we should use a
+ * callback instead?
+ */
+/* TODO(niels): we may want to add to automagically convert to mmap, in
+ * case evbuffer_remove() or evbuffer_pullup() are being used.
+ */
+int
+evbuffer_add_file(struct evbuffer *outbuf, int fd,
+    ev_off_t offset, ev_off_t length)
+{
+#if defined(USE_SENDFILE) || defined(_EVENT_HAVE_MMAP)
+       struct evbuffer_chain *chain;
+       struct evbuffer_chain_fd *info;
+#endif
+#if defined(USE_SENDFILE)
+       int sendfile_okay = 1;
+#endif
+       int ok = 1;
+
+#if defined(USE_SENDFILE)
+       if (use_sendfile) {
+               EVBUFFER_LOCK(outbuf);
+               sendfile_okay = outbuf->flags & EVBUFFER_FLAG_DRAINS_TO_FD;
+               EVBUFFER_UNLOCK(outbuf);
+       }
+
+       if (use_sendfile && sendfile_okay) {
+               chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_fd));
+               if (chain == NULL) {
+                       event_warn("%s: out of memory", __func__);
+                       return (-1);
+               }
+
+               chain->flags |= EVBUFFER_SENDFILE | EVBUFFER_IMMUTABLE;
+               chain->buffer = NULL;   /* no reading possible */
+               chain->buffer_len = length + offset;
+               chain->off = length;
+               chain->misalign = offset;
+
+               info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd, chain);
+               info->fd = fd;
+
+               EVBUFFER_LOCK(outbuf);
+               if (outbuf->freeze_end) {
+                       mm_free(chain);
+                       ok = 0;
+               } else {
+                       outbuf->n_add_for_cb += length;
+                       evbuffer_chain_insert(outbuf, chain);
+               }
+       } else
+#endif
+#if defined(_EVENT_HAVE_MMAP)
+       if (use_mmap) {
+               void *mapped = mmap(NULL, length + offset, PROT_READ,
+#ifdef MAP_NOCACHE
+                   MAP_NOCACHE |
+#endif
+#ifdef MAP_FILE
+                   MAP_FILE |
+#endif
+                   MAP_PRIVATE,
+                   fd, 0);
+               /* some mmap implementations require offset to be a multiple of
+                * the page size.  most users of this api, are likely to use 0
+                * so mapping everything is not likely to be a problem.
+                * TODO(niels): determine page size and round offset to that
+                * page size to avoid mapping too much memory.
+                */
+               if (mapped == MAP_FAILED) {
+                       event_warn("%s: mmap(%d, %d, %zu) failed",
+                           __func__, fd, 0, (size_t)(offset + length));
+                       return (-1);
+               }
+               chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_fd));
+               if (chain == NULL) {
+                       event_warn("%s: out of memory", __func__);
+                       munmap(mapped, length);
+                       return (-1);
+               }
+
+               chain->flags |= EVBUFFER_MMAP | EVBUFFER_IMMUTABLE;
+               chain->buffer = mapped;
+               chain->buffer_len = length + offset;
+               chain->off = length + offset;
+
+               info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd, chain);
+               info->fd = fd;
+
+               EVBUFFER_LOCK(outbuf);
+               if (outbuf->freeze_end) {
+                       info->fd = -1;
+                       evbuffer_chain_free(chain);
+                       ok = 0;
+               } else {
+                       outbuf->n_add_for_cb += length;
+
+                       evbuffer_chain_insert(outbuf, chain);
+
+                       /* we need to subtract whatever we don't need */
+                       evbuffer_drain(outbuf, offset);
+               }
+       } else
+#endif
+       {
+               /* the default implementation */
+               struct evbuffer *tmp = evbuffer_new();
+               ev_ssize_t read;
+
+               if (tmp == NULL)
+                       return (-1);
+
+#ifdef WIN32
+#define lseek _lseeki64
+#endif
+               if (lseek(fd, offset, SEEK_SET) == -1) {
+                       evbuffer_free(tmp);
+                       return (-1);
+               }
+
+               /* we add everything to a temporary buffer, so that we
+                * can abort without side effects if the read fails.
+                */
+               while (length) {
+                       read = evbuffer_readfile(tmp, fd, (ev_ssize_t)length);
+                       if (read == -1) {
+                               evbuffer_free(tmp);
+                               return (-1);
+                       }
+
+                       length -= read;
+               }
+
+               EVBUFFER_LOCK(outbuf);
+               if (outbuf->freeze_end) {
+                       evbuffer_free(tmp);
+                       ok = 0;
+               } else {
+                       evbuffer_add_buffer(outbuf, tmp);
+                       evbuffer_free(tmp);
+
+#ifdef WIN32
+#define close _close
+#endif
+                       close(fd);
+               }
+       }
+
+       if (ok)
+               evbuffer_invoke_callbacks(outbuf);
+       EVBUFFER_UNLOCK(outbuf);
+
+       return ok ? 0 : -1;
+}
+
+
+void
+evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg)
+{
+       EVBUFFER_LOCK(buffer);
+
+       if (!TAILQ_EMPTY(&buffer->callbacks))
+               evbuffer_remove_all_callbacks(buffer);
+
+       if (cb) {
+               struct evbuffer_cb_entry *ent =
+                   evbuffer_add_cb(buffer, NULL, cbarg);
+               ent->cb.cb_obsolete = cb;
+               ent->flags |= EVBUFFER_CB_OBSOLETE;
+       }
+       EVBUFFER_UNLOCK(buffer);
+}
+
+struct evbuffer_cb_entry *
+evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
+{
+       struct evbuffer_cb_entry *e;
+       if (! (e = mm_calloc(1, sizeof(struct evbuffer_cb_entry))))
+               return NULL;
+       EVBUFFER_LOCK(buffer);
+       e->cb.cb_func = cb;
+       e->cbarg = cbarg;
+       e->flags = EVBUFFER_CB_ENABLED;
+       TAILQ_INSERT_HEAD(&buffer->callbacks, e, next);
+       EVBUFFER_UNLOCK(buffer);
+       return e;
+}
+
+int
+evbuffer_remove_cb_entry(struct evbuffer *buffer,
+                        struct evbuffer_cb_entry *ent)
+{
+       EVBUFFER_LOCK(buffer);
+       TAILQ_REMOVE(&buffer->callbacks, ent, next);
+       EVBUFFER_UNLOCK(buffer);
+       mm_free(ent);
+       return 0;
+}
+
+int
+evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
+{
+       struct evbuffer_cb_entry *cbent;
+       int result = -1;
+       EVBUFFER_LOCK(buffer);
+       TAILQ_FOREACH(cbent, &buffer->callbacks, next) {
+               if (cb == cbent->cb.cb_func && cbarg == cbent->cbarg) {
+                       result = evbuffer_remove_cb_entry(buffer, cbent);
+                       goto done;
+               }
+       }
+done:
+       EVBUFFER_UNLOCK(buffer);
+       return result;
+}
+
+int
+evbuffer_cb_set_flags(struct evbuffer *buffer,
+                     struct evbuffer_cb_entry *cb, ev_uint32_t flags)
+{
+       /* the user isn't allowed to mess with these. */
+       flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
+       EVBUFFER_LOCK(buffer);
+       cb->flags |= flags;
+       EVBUFFER_UNLOCK(buffer);
+       return 0;
+}
+
+int
+evbuffer_cb_clear_flags(struct evbuffer *buffer,
+                     struct evbuffer_cb_entry *cb, ev_uint32_t flags)
+{
+       /* the user isn't allowed to mess with these. */
+       flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
+       EVBUFFER_LOCK(buffer);
+       cb->flags &= ~flags;
+       EVBUFFER_UNLOCK(buffer);
+       return 0;
+}
+
+int
+evbuffer_freeze(struct evbuffer *buffer, int start)
+{
+       EVBUFFER_LOCK(buffer);
+       if (start)
+               buffer->freeze_start = 1;
+       else
+               buffer->freeze_end = 1;
+       EVBUFFER_UNLOCK(buffer);
+       return 0;
+}
+
+int
+evbuffer_unfreeze(struct evbuffer *buffer, int start)
+{
+       EVBUFFER_LOCK(buffer);
+       if (start)
+               buffer->freeze_start = 0;
+       else
+               buffer->freeze_end = 0;
+       EVBUFFER_UNLOCK(buffer);
+       return 0;
+}
+
+#if 0
+void
+evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
+{
+       if (!(cb->flags & EVBUFFER_CB_SUSPENDED)) {
+               cb->size_before_suspend = evbuffer_get_length(buffer);
+               cb->flags |= EVBUFFER_CB_SUSPENDED;
+       }
+}
+
+void
+evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
+{
+       if ((cb->flags & EVBUFFER_CB_SUSPENDED)) {
+               unsigned call = (cb->flags & EVBUFFER_CB_CALL_ON_UNSUSPEND);
+               size_t sz = cb->size_before_suspend;
+               cb->flags &= ~(EVBUFFER_CB_SUSPENDED|
+                              EVBUFFER_CB_CALL_ON_UNSUSPEND);
+               cb->size_before_suspend = 0;
+               if (call && (cb->flags & EVBUFFER_CB_ENABLED)) {
+                       cb->cb(buffer, sz, evbuffer_get_length(buffer), cb->cbarg);
+               }
+       }
+}
+#endif
+
+/* These hooks are exposed so that the unit tests can temporarily disable
+ * sendfile support in order to test mmap, or both to test linear
+ * access. Don't use it; if we need to add a way to disable sendfile support
+ * in the future, it will probably be via an alternate version of
+ * evbuffer_add_file() with a 'flags' argument.
+ */
+int _evbuffer_testing_use_sendfile(void);
+int _evbuffer_testing_use_mmap(void);
+int _evbuffer_testing_use_linear_file_access(void);
+
+int
+_evbuffer_testing_use_sendfile(void)
+{
+       int ok = 0;
+#ifdef USE_SENDFILE
+       use_sendfile = 1;
+       ok = 1;
+#endif
+#ifdef _EVENT_HAVE_MMAP
+       use_mmap = 0;
+#endif
+       return ok;
+}
+int
+_evbuffer_testing_use_mmap(void)
+{
+       int ok = 0;
+#ifdef USE_SENDFILE
+       use_sendfile = 0;
+#endif
+#ifdef _EVENT_HAVE_MMAP
+       use_mmap = 1;
+       ok = 1;
+#endif
+       return ok;
+}
+int
+_evbuffer_testing_use_linear_file_access(void)
+{
+#ifdef USE_SENDFILE
+       use_sendfile = 0;
+#endif
+#ifdef _EVENT_HAVE_MMAP
+       use_mmap = 0;
+#endif
+       return 1;
+}
diff --git a/libevent/buffer_iocp.c b/libevent/buffer_iocp.c
new file mode 100644 (file)
index 0000000..5d5303e
--- /dev/null
@@ -0,0 +1,325 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+/**
+   @file buffer_iocp.c
+
+   This module implements overlapped read and write functions for evbuffer
+   objects on Windows.
+*/
+
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/util.h"
+#include "event2/thread.h"
+#include "event2/event-config.h"
+#include "util-internal.h"
+#include "evthread-internal.h"
+#include "evbuffer-internal.h"
+#include "iocp-internal.h"
+#include "mm-internal.h"
+
+#include <winsock2.h>
+#include <windows.h>
+#include <stdio.h>
+
+#define MAX_WSABUFS 16
+
+/** An evbuffer that can handle overlapped IO. */
+struct evbuffer_overlapped {
+       struct evbuffer buffer;
+       /** The socket that we're doing overlapped IO on. */
+       evutil_socket_t fd;
+
+       /** pending I/O type */
+       unsigned read_in_progress : 1;
+       unsigned write_in_progress : 1;
+
+       /** The first pinned chain in the buffer. */
+       struct evbuffer_chain *first_pinned;
+
+       /** How many chains are pinned; how many of the fields in buffers
+        * are we using. */
+       int n_buffers;
+       WSABUF buffers[MAX_WSABUFS];
+};
+
+/** Given an evbuffer, return the correponding evbuffer structure, or NULL if
+ * the evbuffer isn't overlapped. */
+static inline struct evbuffer_overlapped *
+upcast_evbuffer(struct evbuffer *buf)
+{
+       if (!buf || !buf->is_overlapped)
+               return NULL;
+       return EVUTIL_UPCAST(buf, struct evbuffer_overlapped, buffer);
+}
+
+/** Unpin all the chains noted as pinned in 'eo'. */
+static void
+pin_release(struct evbuffer_overlapped *eo, unsigned flag)
+{
+       int i;
+       struct evbuffer_chain *next, *chain = eo->first_pinned;
+
+       for (i = 0; i < eo->n_buffers; ++i) {
+               EVUTIL_ASSERT(chain);
+               next = chain->next;
+               _evbuffer_chain_unpin(chain, flag);
+               chain = next;
+       }
+}
+
+void
+evbuffer_commit_read(struct evbuffer *evbuf, ev_ssize_t nBytes)
+{
+       struct evbuffer_overlapped *buf = upcast_evbuffer(evbuf);
+       struct evbuffer_chain **chainp;
+       size_t remaining, len;
+       unsigned i;
+
+       EVBUFFER_LOCK(evbuf);
+       EVUTIL_ASSERT(buf->read_in_progress && !buf->write_in_progress);
+       EVUTIL_ASSERT(nBytes >= 0); /* XXXX Can this be false? */
+
+       evbuffer_unfreeze(evbuf, 0);
+
+       chainp = evbuf->last_with_datap;
+       if (!((*chainp)->flags & EVBUFFER_MEM_PINNED_R))
+               chainp = &(*chainp)->next;
+       remaining = nBytes;
+       for (i = 0; remaining > 0 && i < (unsigned)buf->n_buffers; ++i) {
+               EVUTIL_ASSERT(*chainp);
+               len = buf->buffers[i].len;
+               if (remaining < len)
+                       len = remaining;
+               (*chainp)->off += len;
+               evbuf->last_with_datap = chainp;
+               remaining -= len;
+               chainp = &(*chainp)->next;
+       }
+
+       pin_release(buf, EVBUFFER_MEM_PINNED_R);
+
+       buf->read_in_progress = 0;
+
+       evbuf->total_len += nBytes;
+       evbuf->n_add_for_cb += nBytes;
+
+       evbuffer_invoke_callbacks(evbuf);
+
+       _evbuffer_decref_and_unlock(evbuf);
+}
+
+void
+evbuffer_commit_write(struct evbuffer *evbuf, ev_ssize_t nBytes)
+{
+       struct evbuffer_overlapped *buf = upcast_evbuffer(evbuf);
+
+       EVBUFFER_LOCK(evbuf);
+       EVUTIL_ASSERT(buf->write_in_progress && !buf->read_in_progress);
+       evbuffer_unfreeze(evbuf, 1);
+       evbuffer_drain(evbuf, nBytes);
+       pin_release(buf,EVBUFFER_MEM_PINNED_W);
+       buf->write_in_progress = 0;
+       _evbuffer_decref_and_unlock(evbuf);
+}
+
+struct evbuffer *
+evbuffer_overlapped_new(evutil_socket_t fd)
+{
+       struct evbuffer_overlapped *evo;
+
+       evo = mm_calloc(1, sizeof(struct evbuffer_overlapped));
+       if (!evo)
+               return NULL;
+
+       TAILQ_INIT(&evo->buffer.callbacks);
+       evo->buffer.refcnt = 1;
+       evo->buffer.last_with_datap = &evo->buffer.first;
+
+       evo->buffer.is_overlapped = 1;
+       evo->fd = fd;
+
+       return &evo->buffer;
+}
+
+int
+evbuffer_launch_write(struct evbuffer *buf, ev_ssize_t at_most,
+               struct event_overlapped *ol)
+{
+       struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
+       int r = -1;
+       int i;
+       struct evbuffer_chain *chain;
+       DWORD bytesSent;
+
+       if (!buf) {
+               /* No buffer, or it isn't overlapped */
+               return -1;
+       }
+
+       EVBUFFER_LOCK(buf);
+       EVUTIL_ASSERT(!buf_o->read_in_progress);
+       if (buf->freeze_start || buf_o->write_in_progress)
+               goto done;
+       if (!buf->total_len) {
+               /* Nothing to write */
+               r = 0;
+               goto done;
+       } else if (at_most < 0 || (size_t)at_most > buf->total_len) {
+               at_most = buf->total_len;
+       }
+       evbuffer_freeze(buf, 1);
+
+       buf_o->first_pinned = NULL;
+       buf_o->n_buffers = 0;
+       memset(buf_o->buffers, 0, sizeof(buf_o->buffers));
+
+       chain = buf_o->first_pinned = buf->first;
+
+       for (i=0; i < MAX_WSABUFS && chain; ++i, chain=chain->next) {
+               WSABUF *b = &buf_o->buffers[i];
+               b->buf = (char*)( chain->buffer + chain->misalign );
+               _evbuffer_chain_pin(chain, EVBUFFER_MEM_PINNED_W);
+
+               if ((size_t)at_most > chain->off) {
+                       /* XXXX Cast is safe for now, since win32 has no
+                          mmaped chains.  But later, we need to have this
+                          add more WSAbufs if chain->off is greater than
+                          ULONG_MAX */
+                       b->len = (unsigned long)chain->off;
+                       at_most -= chain->off;
+               } else {
+                       b->len = (unsigned long)at_most;
+                       ++i;
+                       break;
+               }
+       }
+
+       buf_o->n_buffers = i;
+       _evbuffer_incref(buf);
+       if (WSASend(buf_o->fd, buf_o->buffers, i, &bytesSent, 0,
+               &ol->overlapped, NULL)) {
+               int error = WSAGetLastError();
+               if (error != WSA_IO_PENDING) {
+                       /* An actual error. */
+                       pin_release(buf_o, EVBUFFER_MEM_PINNED_W);
+                       evbuffer_unfreeze(buf, 1);
+                       evbuffer_free(buf); /* decref */
+                       goto done;
+               }
+       }
+
+       buf_o->write_in_progress = 1;
+       r = 0;
+done:
+       EVBUFFER_UNLOCK(buf);
+       return r;
+}
+
+int
+evbuffer_launch_read(struct evbuffer *buf, size_t at_most,
+               struct event_overlapped *ol)
+{
+       struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
+       int r = -1, i;
+       int nvecs;
+       int npin=0;
+       struct evbuffer_chain *chain=NULL, **chainp;
+       DWORD bytesRead;
+       DWORD flags = 0;
+       struct evbuffer_iovec vecs[MAX_WSABUFS];
+
+       if (!buf_o)
+               return -1;
+       EVBUFFER_LOCK(buf);
+       EVUTIL_ASSERT(!buf_o->write_in_progress);
+       if (buf->freeze_end || buf_o->read_in_progress)
+               goto done;
+
+       buf_o->first_pinned = NULL;
+       buf_o->n_buffers = 0;
+       memset(buf_o->buffers, 0, sizeof(buf_o->buffers));
+
+       if (_evbuffer_expand_fast(buf, at_most, MAX_WSABUFS) == -1)
+               goto done;
+       evbuffer_freeze(buf, 0);
+
+       nvecs = _evbuffer_read_setup_vecs(buf, at_most,
+           vecs, MAX_WSABUFS, &chainp, 1);
+       for (i=0;i<nvecs;++i) {
+               WSABUF_FROM_EVBUFFER_IOV(
+                       &buf_o->buffers[i],
+                       &vecs[i]);
+       }
+
+       buf_o->n_buffers = nvecs;
+       buf_o->first_pinned = chain = *chainp;
+
+       npin=0;
+       for ( ; chain; chain = chain->next) {
+               _evbuffer_chain_pin(chain, EVBUFFER_MEM_PINNED_R);
+               ++npin;
+       }
+       EVUTIL_ASSERT(npin == nvecs);
+
+       _evbuffer_incref(buf);
+       if (WSARecv(buf_o->fd, buf_o->buffers, nvecs, &bytesRead, &flags,
+                   &ol->overlapped, NULL)) {
+               int error = WSAGetLastError();
+               if (error != WSA_IO_PENDING) {
+                       /* An actual error. */
+                       pin_release(buf_o, EVBUFFER_MEM_PINNED_R);
+                       evbuffer_unfreeze(buf, 0);
+                       evbuffer_free(buf); /* decref */
+                       goto done;
+               }
+       }
+
+       buf_o->read_in_progress = 1;
+       r = 0;
+done:
+       EVBUFFER_UNLOCK(buf);
+       return r;
+}
+
+evutil_socket_t
+_evbuffer_overlapped_get_fd(struct evbuffer *buf)
+{
+       struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
+       return buf_o ? buf_o->fd : -1;
+}
+
+void
+_evbuffer_overlapped_set_fd(struct evbuffer *buf, evutil_socket_t fd)
+{
+       struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
+       EVBUFFER_LOCK(buf);
+       /* XXX is this right?, should it cancel current I/O operations? */
+       if (buf_o)
+               buf_o->fd = fd;
+       EVBUFFER_UNLOCK(buf);
+}
diff --git a/libevent/bufferevent-internal.h b/libevent/bufferevent-internal.h
new file mode 100644 (file)
index 0000000..8348ab7
--- /dev/null
@@ -0,0 +1,410 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _BUFFEREVENT_INTERNAL_H_
+#define _BUFFEREVENT_INTERNAL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include "event2/util.h"
+#include "defer-internal.h"
+#include "evthread-internal.h"
+#include "event2/thread.h"
+#include "ratelim-internal.h"
+#include "event2/bufferevent_struct.h"
+
+/* These flags are reasons that we might be declining to actually enable
+   reading or writing on a bufferevent.
+ */
+
+/* On a all bufferevents, for reading: used when we have read up to the
+   watermark value.
+
+   On a filtering bufferevent, for writing: used when the underlying
+   bufferevent's write buffer has been filled up to its watermark
+   value.
+*/
+#define BEV_SUSPEND_WM 0x01
+/* On a base bufferevent: when we have emptied a bandwidth buckets */
+#define BEV_SUSPEND_BW 0x02
+/* On a base bufferevent: when we have emptied the group's bandwidth bucket. */
+#define BEV_SUSPEND_BW_GROUP 0x04
+/* On a socket bufferevent: can't do any operations while we're waiting for
+ * name lookup to finish. */
+#define BEV_SUSPEND_LOOKUP 0x08
+/* On a base bufferevent, for reading: used when a filter has choked this
+ * (underlying) bufferevent because it has stopped reading from it. */
+#define BEV_SUSPEND_FILT_READ 0x10
+
+typedef ev_uint16_t bufferevent_suspend_flags;
+
+struct bufferevent_rate_limit_group {
+       /** List of all members in the group */
+       TAILQ_HEAD(rlim_group_member_list, bufferevent_private) members;
+       /** Current limits for the group. */
+       struct ev_token_bucket rate_limit;
+       struct ev_token_bucket_cfg rate_limit_cfg;
+
+       /** True iff we don't want to read from any member of the group.until
+        * the token bucket refills.  */
+       unsigned read_suspended : 1;
+       /** True iff we don't want to write from any member of the group.until
+        * the token bucket refills.  */
+       unsigned write_suspended : 1;
+       /** True iff we were unable to suspend one of the bufferevents in the
+        * group for reading the last time we tried, and we should try
+        * again. */
+       unsigned pending_unsuspend_read : 1;
+       /** True iff we were unable to suspend one of the bufferevents in the
+        * group for writing the last time we tried, and we should try
+        * again. */
+       unsigned pending_unsuspend_write : 1;
+
+       /*@{*/
+       /** Total number of bytes read or written in this group since last
+        * reset. */
+       ev_uint64_t total_read;
+       ev_uint64_t total_written;
+       /*@}*/
+
+       /** The number of bufferevents in the group. */
+       int n_members;
+
+       /** The smallest number of bytes that any member of the group should
+        * be limited to read or write at a time. */
+       ev_ssize_t min_share;
+       ev_ssize_t configured_min_share;
+
+       /** Timeout event that goes off once a tick, when the bucket is ready
+        * to refill. */
+       struct event master_refill_event;
+       /** Lock to protect the members of this group.  This lock should nest
+        * within every bufferevent lock: if you are holding this lock, do
+        * not assume you can lock another bufferevent. */
+       void *lock;
+};
+
+/** Fields for rate-limiting a single bufferevent. */
+struct bufferevent_rate_limit {
+       /* Linked-list elements for storing this bufferevent_private in a
+        * group.
+        *
+        * Note that this field is supposed to be protected by the group
+        * lock */
+       TAILQ_ENTRY(bufferevent_private) next_in_group;
+       /** The rate-limiting group for this bufferevent, or NULL if it is
+        * only rate-limited on its own. */
+       struct bufferevent_rate_limit_group *group;
+
+       /* This bufferevent's current limits. */
+       struct ev_token_bucket limit;
+       /* Pointer to the rate-limit configuration for this bufferevent.
+        * Can be shared.  XXX reference-count this? */
+       struct ev_token_bucket_cfg *cfg;
+
+       /* Timeout event used when one this bufferevent's buckets are
+        * empty. */
+       struct event refill_bucket_event;
+};
+
+/** Parts of the bufferevent structure that are shared among all bufferevent
+ * types, but not exposed in bufferevent_struct.h. */
+struct bufferevent_private {
+       /** The underlying bufferevent structure. */
+       struct bufferevent bev;
+
+       /** Evbuffer callback to enforce watermarks on input. */
+       struct evbuffer_cb_entry *read_watermarks_cb;
+
+       /** If set, we should free the lock when we free the bufferevent. */
+       unsigned own_lock : 1;
+
+       /** Flag: set if we have deferred callbacks and a read callback is
+        * pending. */
+       unsigned readcb_pending : 1;
+       /** Flag: set if we have deferred callbacks and a write callback is
+        * pending. */
+       unsigned writecb_pending : 1;
+       /** Flag: set if we are currently busy connecting. */
+       unsigned connecting : 1;
+       /** Flag: set if a connect failed prematurely; this is a hack for
+        * getting around the bufferevent abstraction. */
+       unsigned connection_refused : 1;
+       /** Set to the events pending if we have deferred callbacks and
+        * an events callback is pending. */
+       short eventcb_pending;
+
+       /** If set, read is suspended until one or more conditions are over.
+        * The actual value here is a bitfield of those conditions; see the
+        * BEV_SUSPEND_* flags above. */
+       bufferevent_suspend_flags read_suspended;
+
+       /** If set, writing is suspended until one or more conditions are over.
+        * The actual value here is a bitfield of those conditions; see the
+        * BEV_SUSPEND_* flags above. */
+       bufferevent_suspend_flags write_suspended;
+
+       /** Set to the current socket errno if we have deferred callbacks and
+        * an events callback is pending. */
+       int errno_pending;
+
+       /** The DNS error code for bufferevent_socket_connect_hostname */
+       int dns_error;
+
+       /** Used to implement deferred callbacks */
+       struct deferred_cb deferred;
+
+       /** The options this bufferevent was constructed with */
+       enum bufferevent_options options;
+
+       /** Current reference count for this bufferevent. */
+       int refcnt;
+
+       /** Lock for this bufferevent.  Shared by the inbuf and the outbuf.
+        * If NULL, locking is disabled. */
+       void *lock;
+
+       /** Rate-limiting information for this bufferevent */
+       struct bufferevent_rate_limit *rate_limiting;
+};
+
+/** Possible operations for a control callback. */
+enum bufferevent_ctrl_op {
+       BEV_CTRL_SET_FD,
+       BEV_CTRL_GET_FD,
+       BEV_CTRL_GET_UNDERLYING,
+       BEV_CTRL_CANCEL_ALL
+};
+
+/** Possible data types for a control callback */
+union bufferevent_ctrl_data {
+       void *ptr;
+       evutil_socket_t fd;
+};
+
+/**
+   Implementation table for a bufferevent: holds function pointers and other
+   information to make the various bufferevent types work.
+*/
+struct bufferevent_ops {
+       /** The name of the bufferevent's type. */
+       const char *type;
+       /** At what offset into the implementation type will we find a
+           bufferevent structure?
+
+           Example: if the type is implemented as
+           struct bufferevent_x {
+              int extra_data;
+              struct bufferevent bev;
+           }
+           then mem_offset should be offsetof(struct bufferevent_x, bev)
+       */
+       off_t mem_offset;
+
+       /** Enables one or more of EV_READ|EV_WRITE on a bufferevent.  Does
+           not need to adjust the 'enabled' field.  Returns 0 on success, -1
+           on failure.
+        */
+       int (*enable)(struct bufferevent *, short);
+
+       /** Disables one or more of EV_READ|EV_WRITE on a bufferevent.  Does
+           not need to adjust the 'enabled' field.  Returns 0 on success, -1
+           on failure.
+        */
+       int (*disable)(struct bufferevent *, short);
+
+       /** Free any storage and deallocate any extra data or structures used
+           in this implementation.
+        */
+       void (*destruct)(struct bufferevent *);
+
+       /** Called when the timeouts on the bufferevent have changed.*/
+       int (*adj_timeouts)(struct bufferevent *);
+
+       /** Called to flush data. */
+       int (*flush)(struct bufferevent *, short, enum bufferevent_flush_mode);
+
+       /** Called to access miscellaneous fields. */
+       int (*ctrl)(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+};
+
+extern const struct bufferevent_ops bufferevent_ops_socket;
+extern const struct bufferevent_ops bufferevent_ops_filter;
+extern const struct bufferevent_ops bufferevent_ops_pair;
+
+#define BEV_IS_SOCKET(bevp) ((bevp)->be_ops == &bufferevent_ops_socket)
+#define BEV_IS_FILTER(bevp) ((bevp)->be_ops == &bufferevent_ops_filter)
+#define BEV_IS_PAIR(bevp) ((bevp)->be_ops == &bufferevent_ops_pair)
+
+#ifdef WIN32
+extern const struct bufferevent_ops bufferevent_ops_async;
+#define BEV_IS_ASYNC(bevp) ((bevp)->be_ops == &bufferevent_ops_async)
+#else
+#define BEV_IS_ASYNC(bevp) 0
+#endif
+
+/** Initialize the shared parts of a bufferevent. */
+int bufferevent_init_common(struct bufferevent_private *, struct event_base *, const struct bufferevent_ops *, enum bufferevent_options options);
+
+/** For internal use: temporarily stop all reads on bufev, until the conditions
+ * in 'what' are over. */
+void bufferevent_suspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what);
+/** For internal use: clear the conditions 'what' on bufev, and re-enable
+ * reading if there are no conditions left. */
+void bufferevent_unsuspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what);
+
+/** For internal use: temporarily stop all writes on bufev, until the conditions
+ * in 'what' are over. */
+void bufferevent_suspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what);
+/** For internal use: clear the conditions 'what' on bufev, and re-enable
+ * writing if there are no conditions left. */
+void bufferevent_unsuspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what);
+
+#define bufferevent_wm_suspend_read(b) \
+       bufferevent_suspend_read((b), BEV_SUSPEND_WM)
+#define bufferevent_wm_unsuspend_read(b) \
+       bufferevent_unsuspend_read((b), BEV_SUSPEND_WM)
+
+/*
+  Disable a bufferevent.  Equivalent to bufferevent_disable(), but
+  first resets 'connecting' flag to force EV_WRITE down for sure.
+
+  XXXX this method will go away in the future; try not to add new users.
+    See comment in evhttp_connection_reset() for discussion.
+
+  @param bufev the bufferevent to be disabled
+  @param event any combination of EV_READ | EV_WRITE.
+  @return 0 if successful, or -1 if an error occurred
+  @see bufferevent_disable()
+ */
+int bufferevent_disable_hard(struct bufferevent *bufev, short event);
+
+/** Internal: Set up locking on a bufferevent.  If lock is set, use it.
+ * Otherwise, use a new lock. */
+int bufferevent_enable_locking(struct bufferevent *bufev, void *lock);
+/** Internal: Increment the reference count on bufev. */
+void bufferevent_incref(struct bufferevent *bufev);
+/** Internal: Lock bufev and increase its reference count.
+ * unlocking it otherwise. */
+void _bufferevent_incref_and_lock(struct bufferevent *bufev);
+/** Internal: Decrement the reference count on bufev.  Returns 1 if it freed
+ * the bufferevent.*/
+int bufferevent_decref(struct bufferevent *bufev);
+/** Internal: Drop the reference count on bufev, freeing as necessary, and
+ * unlocking it otherwise.  Returns 1 if it freed the bufferevent. */
+int _bufferevent_decref_and_unlock(struct bufferevent *bufev);
+
+/** Internal: If callbacks are deferred and we have a read callback, schedule
+ * a readcb.  Otherwise just run the readcb. */
+void _bufferevent_run_readcb(struct bufferevent *bufev);
+/** Internal: If callbacks are deferred and we have a write callback, schedule
+ * a writecb.  Otherwise just run the writecb. */
+void _bufferevent_run_writecb(struct bufferevent *bufev);
+/** Internal: If callbacks are deferred and we have an eventcb, schedule
+ * it to run with events "what".  Otherwise just run the eventcb. */
+void _bufferevent_run_eventcb(struct bufferevent *bufev, short what);
+
+/** Internal: Add the event 'ev' with timeout tv, unless tv is set to 0, in
+ * which case add ev with no timeout. */
+int _bufferevent_add_event(struct event *ev, const struct timeval *tv);
+
+/* =========
+ * These next functions implement timeouts for bufferevents that aren't doing
+ * anything else with ev_read and ev_write, to handle timeouts.
+ * ========= */
+/** Internal use: Set up the ev_read and ev_write callbacks so that
+ * the other "generic_timeout" functions will work on it.  Call this from
+ * the constructor function. */
+void _bufferevent_init_generic_timeout_cbs(struct bufferevent *bev);
+/** Internal use: Delete the ev_read and ev_write callbacks if they're pending.
+ * Call this from the destructor function. */
+int _bufferevent_del_generic_timeout_cbs(struct bufferevent *bev);
+/** Internal use: Add or delete the generic timeout events as appropriate.
+ * (If an event is enabled and a timeout is set, we add the event.  Otherwise
+ * we delete it.)  Call this from anything that changes the timeout values,
+ * that enabled EV_READ or EV_WRITE, or that disables EV_READ or EV_WRITE. */
+int _bufferevent_generic_adj_timeouts(struct bufferevent *bev);
+
+/** Internal use: We have just successfully read data into an inbuf, so
+ * reset the read timeout (if any). */
+#define BEV_RESET_GENERIC_READ_TIMEOUT(bev)                            \
+       do {                                                            \
+               if (evutil_timerisset(&(bev)->timeout_read))            \
+                       event_add(&(bev)->ev_read, &(bev)->timeout_read); \
+       } while (0)
+/** Internal use: We have just successfully written data from an inbuf, so
+ * reset the read timeout (if any). */
+#define BEV_RESET_GENERIC_WRITE_TIMEOUT(bev)                           \
+       do {                                                            \
+               if (evutil_timerisset(&(bev)->timeout_write))           \
+                       event_add(&(bev)->ev_write, &(bev)->timeout_write); \
+       } while (0)
+#define BEV_DEL_GENERIC_READ_TIMEOUT(bev)      \
+               event_del(&(bev)->ev_read)
+#define BEV_DEL_GENERIC_WRITE_TIMEOUT(bev)     \
+               event_del(&(bev)->ev_write)
+
+
+/** Internal: Given a bufferevent, return its corresponding
+ * bufferevent_private. */
+#define BEV_UPCAST(b) EVUTIL_UPCAST((b), struct bufferevent_private, bev)
+
+#ifdef _EVENT_DISABLE_THREAD_SUPPORT
+#define BEV_LOCK(b) _EVUTIL_NIL_STMT
+#define BEV_UNLOCK(b) _EVUTIL_NIL_STMT
+#else
+/** Internal: Grab the lock (if any) on a bufferevent */
+#define BEV_LOCK(b) do {                                               \
+               struct bufferevent_private *locking =  BEV_UPCAST(b);   \
+               EVLOCK_LOCK(locking->lock, 0);                          \
+       } while (0)
+
+/** Internal: Release the lock (if any) on a bufferevent */
+#define BEV_UNLOCK(b) do {                                             \
+               struct bufferevent_private *locking =  BEV_UPCAST(b);   \
+               EVLOCK_UNLOCK(locking->lock, 0);                        \
+       } while (0)
+#endif
+
+
+/* ==== For rate-limiting. */
+
+int _bufferevent_decrement_write_buckets(struct bufferevent_private *bev,
+    ev_ssize_t bytes);
+int _bufferevent_decrement_read_buckets(struct bufferevent_private *bev,
+    ev_ssize_t bytes);
+ev_ssize_t _bufferevent_get_read_max(struct bufferevent_private *bev);
+ev_ssize_t _bufferevent_get_write_max(struct bufferevent_private *bev);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _BUFFEREVENT_INTERNAL_H_ */
diff --git a/libevent/bufferevent.c b/libevent/bufferevent.c
new file mode 100644 (file)
index 0000000..45a1437
--- /dev/null
@@ -0,0 +1,875 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+
+#include "event2/event-config.h"
+
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+#include <errno.h>
+
+#include "event2/util.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/event.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "evbuffer-internal.h"
+#include "util-internal.h"
+
+static void _bufferevent_cancel_all(struct bufferevent *bev);
+
+
+void
+bufferevent_suspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what)
+{
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       BEV_LOCK(bufev);
+       if (!bufev_private->read_suspended)
+               bufev->be_ops->disable(bufev, EV_READ);
+       bufev_private->read_suspended |= what;
+       BEV_UNLOCK(bufev);
+}
+
+void
+bufferevent_unsuspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what)
+{
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       BEV_LOCK(bufev);
+       bufev_private->read_suspended &= ~what;
+       if (!bufev_private->read_suspended && (bufev->enabled & EV_READ))
+               bufev->be_ops->enable(bufev, EV_READ);
+       BEV_UNLOCK(bufev);
+}
+
+void
+bufferevent_suspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what)
+{
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       BEV_LOCK(bufev);
+       if (!bufev_private->write_suspended)
+               bufev->be_ops->disable(bufev, EV_WRITE);
+       bufev_private->write_suspended |= what;
+       BEV_UNLOCK(bufev);
+}
+
+void
+bufferevent_unsuspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what)
+{
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       BEV_LOCK(bufev);
+       bufev_private->write_suspended &= ~what;
+       if (!bufev_private->write_suspended && (bufev->enabled & EV_WRITE))
+               bufev->be_ops->enable(bufev, EV_WRITE);
+       BEV_UNLOCK(bufev);
+}
+
+
+/* Callback to implement watermarks on the input buffer.  Only enabled
+ * if the watermark is set. */
+static void
+bufferevent_inbuf_wm_cb(struct evbuffer *buf,
+    const struct evbuffer_cb_info *cbinfo,
+    void *arg)
+{
+       struct bufferevent *bufev = arg;
+       size_t size;
+
+       size = evbuffer_get_length(buf);
+
+       if (size >= bufev->wm_read.high)
+               bufferevent_wm_suspend_read(bufev);
+       else
+               bufferevent_wm_unsuspend_read(bufev);
+}
+
+static void
+bufferevent_run_deferred_callbacks_locked(struct deferred_cb *_, void *arg)
+{
+       struct bufferevent_private *bufev_private = arg;
+       struct bufferevent *bufev = &bufev_private->bev;
+
+       BEV_LOCK(bufev);
+       if ((bufev_private->eventcb_pending & BEV_EVENT_CONNECTED) &&
+           bufev->errorcb) {
+               /* The "connected" happened before any reads or writes, so
+                  send it first. */
+               bufev_private->eventcb_pending &= ~BEV_EVENT_CONNECTED;
+               bufev->errorcb(bufev, BEV_EVENT_CONNECTED, bufev->cbarg);
+       }
+       if (bufev_private->readcb_pending && bufev->readcb) {
+               bufev_private->readcb_pending = 0;
+               bufev->readcb(bufev, bufev->cbarg);
+       }
+       if (bufev_private->writecb_pending && bufev->writecb) {
+               bufev_private->writecb_pending = 0;
+               bufev->writecb(bufev, bufev->cbarg);
+       }
+       if (bufev_private->eventcb_pending && bufev->errorcb) {
+               short what = bufev_private->eventcb_pending;
+               int err = bufev_private->errno_pending;
+               bufev_private->eventcb_pending = 0;
+               bufev_private->errno_pending = 0;
+               EVUTIL_SET_SOCKET_ERROR(err);
+               bufev->errorcb(bufev, what, bufev->cbarg);
+       }
+       _bufferevent_decref_and_unlock(bufev);
+}
+
+static void
+bufferevent_run_deferred_callbacks_unlocked(struct deferred_cb *_, void *arg)
+{
+       struct bufferevent_private *bufev_private = arg;
+       struct bufferevent *bufev = &bufev_private->bev;
+
+       BEV_LOCK(bufev);
+#define UNLOCKED(stmt) \
+       do { BEV_UNLOCK(bufev); stmt; BEV_LOCK(bufev); } while(0)
+
+       if ((bufev_private->eventcb_pending & BEV_EVENT_CONNECTED) &&
+           bufev->errorcb) {
+               /* The "connected" happened before any reads or writes, so
+                  send it first. */
+               bufferevent_event_cb errorcb = bufev->errorcb;
+               void *cbarg = bufev->cbarg;
+               bufev_private->eventcb_pending &= ~BEV_EVENT_CONNECTED;
+               UNLOCKED(errorcb(bufev, BEV_EVENT_CONNECTED, cbarg));
+       }
+       if (bufev_private->readcb_pending && bufev->readcb) {
+               bufferevent_data_cb readcb = bufev->readcb;
+               void *cbarg = bufev->cbarg;
+               bufev_private->readcb_pending = 0;
+               UNLOCKED(readcb(bufev, cbarg));
+       }
+       if (bufev_private->writecb_pending && bufev->writecb) {
+               bufferevent_data_cb writecb = bufev->writecb;
+               void *cbarg = bufev->cbarg;
+               bufev_private->writecb_pending = 0;
+               UNLOCKED(writecb(bufev, cbarg));
+       }
+       if (bufev_private->eventcb_pending && bufev->errorcb) {
+               bufferevent_event_cb errorcb = bufev->errorcb;
+               void *cbarg = bufev->cbarg;
+               short what = bufev_private->eventcb_pending;
+               int err = bufev_private->errno_pending;
+               bufev_private->eventcb_pending = 0;
+               bufev_private->errno_pending = 0;
+               EVUTIL_SET_SOCKET_ERROR(err);
+               UNLOCKED(errorcb(bufev,what,cbarg));
+       }
+       _bufferevent_decref_and_unlock(bufev);
+#undef UNLOCKED
+}
+
+#define SCHEDULE_DEFERRED(bevp)                                                \
+       do {                                                            \
+               bufferevent_incref(&(bevp)->bev);                       \
+               event_deferred_cb_schedule(                             \
+                       event_base_get_deferred_cb_queue((bevp)->bev.ev_base), \
+                       &(bevp)->deferred);                             \
+       } while (0)
+
+
+void
+_bufferevent_run_readcb(struct bufferevent *bufev)
+{
+       /* Requires that we hold the lock and a reference */
+       struct bufferevent_private *p =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       if (bufev->readcb == NULL)
+               return;
+       if (p->options & BEV_OPT_DEFER_CALLBACKS) {
+               p->readcb_pending = 1;
+               if (!p->deferred.queued)
+                       SCHEDULE_DEFERRED(p);
+       } else {
+               bufev->readcb(bufev, bufev->cbarg);
+       }
+}
+
+void
+_bufferevent_run_writecb(struct bufferevent *bufev)
+{
+       /* Requires that we hold the lock and a reference */
+       struct bufferevent_private *p =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       if (bufev->writecb == NULL)
+               return;
+       if (p->options & BEV_OPT_DEFER_CALLBACKS) {
+               p->writecb_pending = 1;
+               if (!p->deferred.queued)
+                       SCHEDULE_DEFERRED(p);
+       } else {
+               bufev->writecb(bufev, bufev->cbarg);
+       }
+}
+
+void
+_bufferevent_run_eventcb(struct bufferevent *bufev, short what)
+{
+       /* Requires that we hold the lock and a reference */
+       struct bufferevent_private *p =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       if (bufev->errorcb == NULL)
+               return;
+       if (p->options & BEV_OPT_DEFER_CALLBACKS) {
+               p->eventcb_pending |= what;
+               p->errno_pending = EVUTIL_SOCKET_ERROR();
+               if (!p->deferred.queued)
+                       SCHEDULE_DEFERRED(p);
+       } else {
+               bufev->errorcb(bufev, what, bufev->cbarg);
+       }
+}
+
+int
+bufferevent_init_common(struct bufferevent_private *bufev_private,
+    struct event_base *base,
+    const struct bufferevent_ops *ops,
+    enum bufferevent_options options)
+{
+       struct bufferevent *bufev = &bufev_private->bev;
+
+       if (!bufev->input) {
+               if ((bufev->input = evbuffer_new()) == NULL)
+                       return -1;
+       }
+
+       if (!bufev->output) {
+               if ((bufev->output = evbuffer_new()) == NULL) {
+                       evbuffer_free(bufev->input);
+                       return -1;
+               }
+       }
+
+       bufev_private->refcnt = 1;
+       bufev->ev_base = base;
+
+       /* Disable timeouts. */
+       evutil_timerclear(&bufev->timeout_read);
+       evutil_timerclear(&bufev->timeout_write);
+
+       bufev->be_ops = ops;
+
+       /*
+        * Set to EV_WRITE so that using bufferevent_write is going to
+        * trigger a callback.  Reading needs to be explicitly enabled
+        * because otherwise no data will be available.
+        */
+       bufev->enabled = EV_WRITE;
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       if (options & BEV_OPT_THREADSAFE) {
+               if (bufferevent_enable_locking(bufev, NULL) < 0) {
+                       /* cleanup */
+                       evbuffer_free(bufev->input);
+                       evbuffer_free(bufev->output);
+                       bufev->input = NULL;
+                       bufev->output = NULL;
+                       return -1;
+               }
+       }
+#endif
+       if ((options & (BEV_OPT_DEFER_CALLBACKS|BEV_OPT_UNLOCK_CALLBACKS))
+           == BEV_OPT_UNLOCK_CALLBACKS) {
+               event_warnx("UNLOCK_CALLBACKS requires DEFER_CALLBACKS");
+               return -1;
+       }
+       if (options & BEV_OPT_DEFER_CALLBACKS) {
+               if (options & BEV_OPT_UNLOCK_CALLBACKS)
+                       event_deferred_cb_init(&bufev_private->deferred,
+                           bufferevent_run_deferred_callbacks_unlocked,
+                           bufev_private);
+               else
+                       event_deferred_cb_init(&bufev_private->deferred,
+                           bufferevent_run_deferred_callbacks_locked,
+                           bufev_private);
+       }
+
+       bufev_private->options = options;
+
+       evbuffer_set_parent(bufev->input, bufev);
+       evbuffer_set_parent(bufev->output, bufev);
+
+       return 0;
+}
+
+void
+bufferevent_setcb(struct bufferevent *bufev,
+    bufferevent_data_cb readcb, bufferevent_data_cb writecb,
+    bufferevent_event_cb eventcb, void *cbarg)
+{
+       BEV_LOCK(bufev);
+
+       bufev->readcb = readcb;
+       bufev->writecb = writecb;
+       bufev->errorcb = eventcb;
+
+       bufev->cbarg = cbarg;
+       BEV_UNLOCK(bufev);
+}
+
+struct evbuffer *
+bufferevent_get_input(struct bufferevent *bufev)
+{
+       return bufev->input;
+}
+
+struct evbuffer *
+bufferevent_get_output(struct bufferevent *bufev)
+{
+       return bufev->output;
+}
+
+struct event_base *
+bufferevent_get_base(struct bufferevent *bufev)
+{
+       return bufev->ev_base;
+}
+
+int
+bufferevent_write(struct bufferevent *bufev, const void *data, size_t size)
+{
+       if (evbuffer_add(bufev->output, data, size) == -1)
+               return (-1);
+
+       return 0;
+}
+
+int
+bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf)
+{
+       if (evbuffer_add_buffer(bufev->output, buf) == -1)
+               return (-1);
+
+       return 0;
+}
+
+size_t
+bufferevent_read(struct bufferevent *bufev, void *data, size_t size)
+{
+       return (evbuffer_remove(bufev->input, data, size));
+}
+
+int
+bufferevent_read_buffer(struct bufferevent *bufev, struct evbuffer *buf)
+{
+       return (evbuffer_add_buffer(buf, bufev->input));
+}
+
+int
+bufferevent_enable(struct bufferevent *bufev, short event)
+{
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       short impl_events = event;
+       int r = 0;
+
+       _bufferevent_incref_and_lock(bufev);
+       if (bufev_private->read_suspended)
+               impl_events &= ~EV_READ;
+       if (bufev_private->write_suspended)
+               impl_events &= ~EV_WRITE;
+
+       bufev->enabled |= event;
+
+       if (impl_events && bufev->be_ops->enable(bufev, impl_events) < 0)
+               r = -1;
+
+       _bufferevent_decref_and_unlock(bufev);
+       return r;
+}
+
+int
+bufferevent_set_timeouts(struct bufferevent *bufev,
+                        const struct timeval *tv_read,
+                        const struct timeval *tv_write)
+{
+       int r = 0;
+       BEV_LOCK(bufev);
+       if (tv_read) {
+               bufev->timeout_read = *tv_read;
+       } else {
+               evutil_timerclear(&bufev->timeout_read);
+       }
+       if (tv_write) {
+               bufev->timeout_write = *tv_write;
+       } else {
+               evutil_timerclear(&bufev->timeout_write);
+       }
+
+       if (bufev->be_ops->adj_timeouts)
+               r = bufev->be_ops->adj_timeouts(bufev);
+       BEV_UNLOCK(bufev);
+
+       return r;
+}
+
+
+/* Obsolete; use bufferevent_set_timeouts */
+void
+bufferevent_settimeout(struct bufferevent *bufev,
+                      int timeout_read, int timeout_write)
+{
+       struct timeval tv_read, tv_write;
+       struct timeval *ptv_read = NULL, *ptv_write = NULL;
+
+       memset(&tv_read, 0, sizeof(tv_read));
+       memset(&tv_write, 0, sizeof(tv_write));
+
+       if (timeout_read) {
+               tv_read.tv_sec = timeout_read;
+               ptv_read = &tv_read;
+       }
+       if (timeout_write) {
+               tv_write.tv_sec = timeout_write;
+               ptv_write = &tv_write;
+       }
+
+       bufferevent_set_timeouts(bufev, ptv_read, ptv_write);
+}
+
+
+int
+bufferevent_disable_hard(struct bufferevent *bufev, short event)
+{
+       int r = 0;
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+
+       BEV_LOCK(bufev);
+       bufev->enabled &= ~event;
+
+       bufev_private->connecting = 0;
+       if (bufev->be_ops->disable(bufev, event) < 0)
+               r = -1;
+
+       BEV_UNLOCK(bufev);
+       return r;
+}
+
+int
+bufferevent_disable(struct bufferevent *bufev, short event)
+{
+       int r = 0;
+
+       BEV_LOCK(bufev);
+       bufev->enabled &= ~event;
+
+       if (bufev->be_ops->disable(bufev, event) < 0)
+               r = -1;
+
+       BEV_UNLOCK(bufev);
+       return r;
+}
+
+/*
+ * Sets the water marks
+ */
+
+void
+bufferevent_setwatermark(struct bufferevent *bufev, short events,
+    size_t lowmark, size_t highmark)
+{
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+
+       BEV_LOCK(bufev);
+       if (events & EV_WRITE) {
+               bufev->wm_write.low = lowmark;
+               bufev->wm_write.high = highmark;
+       }
+
+       if (events & EV_READ) {
+               bufev->wm_read.low = lowmark;
+               bufev->wm_read.high = highmark;
+
+               if (highmark) {
+                       /* There is now a new high-water mark for read.
+                          enable the callback if needed, and see if we should
+                          suspend/bufferevent_wm_unsuspend. */
+
+                       if (bufev_private->read_watermarks_cb == NULL) {
+                               bufev_private->read_watermarks_cb =
+                                   evbuffer_add_cb(bufev->input,
+                                                   bufferevent_inbuf_wm_cb,
+                                                   bufev);
+                       }
+                       evbuffer_cb_set_flags(bufev->input,
+                                     bufev_private->read_watermarks_cb,
+                                     EVBUFFER_CB_ENABLED|EVBUFFER_CB_NODEFER);
+
+                       if (evbuffer_get_length(bufev->input) > highmark)
+                               bufferevent_wm_suspend_read(bufev);
+                       else if (evbuffer_get_length(bufev->input) < highmark)
+                               bufferevent_wm_unsuspend_read(bufev);
+               } else {
+                       /* There is now no high-water mark for read. */
+                       if (bufev_private->read_watermarks_cb)
+                               evbuffer_cb_clear_flags(bufev->input,
+                                   bufev_private->read_watermarks_cb,
+                                   EVBUFFER_CB_ENABLED);
+                       bufferevent_wm_unsuspend_read(bufev);
+               }
+       }
+       BEV_UNLOCK(bufev);
+}
+
+int
+bufferevent_flush(struct bufferevent *bufev,
+    short iotype,
+    enum bufferevent_flush_mode mode)
+{
+       int r = -1;
+       BEV_LOCK(bufev);
+       if (bufev->be_ops->flush)
+               r = bufev->be_ops->flush(bufev, iotype, mode);
+       BEV_UNLOCK(bufev);
+       return r;
+}
+
+void
+_bufferevent_incref_and_lock(struct bufferevent *bufev)
+{
+       struct bufferevent_private *bufev_private =
+           BEV_UPCAST(bufev);
+       BEV_LOCK(bufev);
+       ++bufev_private->refcnt;
+}
+
+#if 0
+static void
+_bufferevent_transfer_lock_ownership(struct bufferevent *donor,
+    struct bufferevent *recipient)
+{
+       struct bufferevent_private *d = BEV_UPCAST(donor);
+       struct bufferevent_private *r = BEV_UPCAST(recipient);
+       if (d->lock != r->lock)
+               return;
+       if (r->own_lock)
+               return;
+       if (d->own_lock) {
+               d->own_lock = 0;
+               r->own_lock = 1;
+       }
+}
+#endif
+
+int
+_bufferevent_decref_and_unlock(struct bufferevent *bufev)
+{
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       struct bufferevent *underlying;
+
+       EVUTIL_ASSERT(bufev_private->refcnt > 0);
+
+       if (--bufev_private->refcnt) {
+               BEV_UNLOCK(bufev);
+               return 0;
+       }
+
+       underlying = bufferevent_get_underlying(bufev);
+
+       /* Clean up the shared info */
+       if (bufev->be_ops->destruct)
+               bufev->be_ops->destruct(bufev);
+
+       /* XXX what happens if refcnt for these buffers is > 1?
+        * The buffers can share a lock with this bufferevent object,
+        * but the lock might be destroyed below. */
+       /* evbuffer will free the callbacks */
+       evbuffer_free(bufev->input);
+       evbuffer_free(bufev->output);
+
+       if (bufev_private->rate_limiting) {
+               if (bufev_private->rate_limiting->group)
+                       bufferevent_remove_from_rate_limit_group_internal(bufev,0);
+               if (event_initialized(&bufev_private->rate_limiting->refill_bucket_event))
+                       event_del(&bufev_private->rate_limiting->refill_bucket_event);
+               event_debug_unassign(&bufev_private->rate_limiting->refill_bucket_event);
+               mm_free(bufev_private->rate_limiting);
+               bufev_private->rate_limiting = NULL;
+       }
+
+       event_debug_unassign(&bufev->ev_read);
+       event_debug_unassign(&bufev->ev_write);
+
+       BEV_UNLOCK(bufev);
+       if (bufev_private->own_lock)
+               EVTHREAD_FREE_LOCK(bufev_private->lock,
+                   EVTHREAD_LOCKTYPE_RECURSIVE);
+
+       /* Free the actual allocated memory. */
+       mm_free(((char*)bufev) - bufev->be_ops->mem_offset);
+
+       /* Release the reference to underlying now that we no longer need the
+        * reference to it.  We wait this long mainly in case our lock is
+        * shared with underlying.
+        *
+        * The 'destruct' function will also drop a reference to underlying
+        * if BEV_OPT_CLOSE_ON_FREE is set.
+        *
+        * XXX Should we/can we just refcount evbuffer/bufferevent locks?
+        * It would probably save us some headaches.
+        */
+       if (underlying)
+               bufferevent_decref(underlying);
+
+       return 1;
+}
+
+int
+bufferevent_decref(struct bufferevent *bufev)
+{
+       BEV_LOCK(bufev);
+       return _bufferevent_decref_and_unlock(bufev);
+}
+
+void
+bufferevent_free(struct bufferevent *bufev)
+{
+       BEV_LOCK(bufev);
+       bufferevent_setcb(bufev, NULL, NULL, NULL, NULL);
+       _bufferevent_cancel_all(bufev);
+       _bufferevent_decref_and_unlock(bufev);
+}
+
+void
+bufferevent_incref(struct bufferevent *bufev)
+{
+       struct bufferevent_private *bufev_private =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+
+       BEV_LOCK(bufev);
+       ++bufev_private->refcnt;
+       BEV_UNLOCK(bufev);
+}
+
+int
+bufferevent_enable_locking(struct bufferevent *bufev, void *lock)
+{
+#ifdef _EVENT_DISABLE_THREAD_SUPPORT
+       return -1;
+#else
+       struct bufferevent *underlying;
+
+       if (BEV_UPCAST(bufev)->lock)
+               return -1;
+       underlying = bufferevent_get_underlying(bufev);
+
+       if (!lock && underlying && BEV_UPCAST(underlying)->lock) {
+               lock = BEV_UPCAST(underlying)->lock;
+               BEV_UPCAST(bufev)->lock = lock;
+               BEV_UPCAST(bufev)->own_lock = 0;
+       } else if (!lock) {
+               EVTHREAD_ALLOC_LOCK(lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+               if (!lock)
+                       return -1;
+               BEV_UPCAST(bufev)->lock = lock;
+               BEV_UPCAST(bufev)->own_lock = 1;
+       } else {
+               BEV_UPCAST(bufev)->lock = lock;
+               BEV_UPCAST(bufev)->own_lock = 0;
+       }
+       evbuffer_enable_locking(bufev->input, lock);
+       evbuffer_enable_locking(bufev->output, lock);
+
+       if (underlying && !BEV_UPCAST(underlying)->lock)
+               bufferevent_enable_locking(underlying, lock);
+
+       return 0;
+#endif
+}
+
+int
+bufferevent_setfd(struct bufferevent *bev, evutil_socket_t fd)
+{
+       union bufferevent_ctrl_data d;
+       int res = -1;
+       d.fd = fd;
+       BEV_LOCK(bev);
+       if (bev->be_ops->ctrl)
+               res = bev->be_ops->ctrl(bev, BEV_CTRL_SET_FD, &d);
+       BEV_UNLOCK(bev);
+       return res;
+}
+
+evutil_socket_t
+bufferevent_getfd(struct bufferevent *bev)
+{
+       union bufferevent_ctrl_data d;
+       int res = -1;
+       d.fd = -1;
+       BEV_LOCK(bev);
+       if (bev->be_ops->ctrl)
+               res = bev->be_ops->ctrl(bev, BEV_CTRL_GET_FD, &d);
+       BEV_UNLOCK(bev);
+       return (res<0) ? -1 : d.fd;
+}
+
+static void
+_bufferevent_cancel_all(struct bufferevent *bev)
+{
+       union bufferevent_ctrl_data d;
+       memset(&d, 0, sizeof(d));
+       BEV_LOCK(bev);
+       if (bev->be_ops->ctrl)
+               bev->be_ops->ctrl(bev, BEV_CTRL_CANCEL_ALL, &d);
+       BEV_UNLOCK(bev);
+}
+
+short
+bufferevent_get_enabled(struct bufferevent *bufev)
+{
+       short r;
+       BEV_LOCK(bufev);
+       r = bufev->enabled;
+       BEV_UNLOCK(bufev);
+       return r;
+}
+
+struct bufferevent *
+bufferevent_get_underlying(struct bufferevent *bev)
+{
+       union bufferevent_ctrl_data d;
+       int res = -1;
+       d.ptr = NULL;
+       BEV_LOCK(bev);
+       if (bev->be_ops->ctrl)
+               res = bev->be_ops->ctrl(bev, BEV_CTRL_GET_UNDERLYING, &d);
+       BEV_UNLOCK(bev);
+       return (res<0) ? NULL : d.ptr;
+}
+
+static void
+bufferevent_generic_read_timeout_cb(evutil_socket_t fd, short event, void *ctx)
+{
+       struct bufferevent *bev = ctx;
+       _bufferevent_incref_and_lock(bev);
+       bufferevent_disable(bev, EV_READ);
+       _bufferevent_run_eventcb(bev, BEV_EVENT_TIMEOUT|BEV_EVENT_READING);
+       _bufferevent_decref_and_unlock(bev);
+}
+static void
+bufferevent_generic_write_timeout_cb(evutil_socket_t fd, short event, void *ctx)
+{
+       struct bufferevent *bev = ctx;
+       _bufferevent_incref_and_lock(bev);
+       bufferevent_disable(bev, EV_WRITE);
+       _bufferevent_run_eventcb(bev, BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING);
+       _bufferevent_decref_and_unlock(bev);
+}
+
+void
+_bufferevent_init_generic_timeout_cbs(struct bufferevent *bev)
+{
+       evtimer_assign(&bev->ev_read, bev->ev_base,
+           bufferevent_generic_read_timeout_cb, bev);
+       evtimer_assign(&bev->ev_write, bev->ev_base,
+           bufferevent_generic_write_timeout_cb, bev);
+}
+
+int
+_bufferevent_del_generic_timeout_cbs(struct bufferevent *bev)
+{
+       int r1,r2;
+       r1 = event_del(&bev->ev_read);
+       r2 = event_del(&bev->ev_write);
+       if (r1<0 || r2<0)
+               return -1;
+       return 0;
+}
+
+int
+_bufferevent_generic_adj_timeouts(struct bufferevent *bev)
+{
+       const short enabled = bev->enabled;
+       struct bufferevent_private *bev_p =
+           EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
+       int r1=0, r2=0;
+       if ((enabled & EV_READ) && !bev_p->read_suspended &&
+           evutil_timerisset(&bev->timeout_read))
+               r1 = event_add(&bev->ev_read, &bev->timeout_read);
+       else
+               r1 = event_del(&bev->ev_read);
+
+       if ((enabled & EV_WRITE) && !bev_p->write_suspended &&
+           evutil_timerisset(&bev->timeout_write) &&
+           evbuffer_get_length(bev->output))
+               r2 = event_add(&bev->ev_write, &bev->timeout_write);
+       else
+               r2 = event_del(&bev->ev_write);
+       if (r1 < 0 || r2 < 0)
+               return -1;
+       return 0;
+}
+
+int
+_bufferevent_add_event(struct event *ev, const struct timeval *tv)
+{
+       if (tv->tv_sec == 0 && tv->tv_usec == 0)
+               return event_add(ev, NULL);
+       else
+               return event_add(ev, tv);
+}
+
+/* For use by user programs only; internally, we should be calling
+   either _bufferevent_incref_and_lock(), or BEV_LOCK. */
+void
+bufferevent_lock(struct bufferevent *bev)
+{
+       _bufferevent_incref_and_lock(bev);
+}
+
+void
+bufferevent_unlock(struct bufferevent *bev)
+{
+       _bufferevent_decref_and_unlock(bev);
+}
diff --git a/libevent/bufferevent_async.c b/libevent/bufferevent_async.c
new file mode 100644 (file)
index 0000000..f34ca5f
--- /dev/null
@@ -0,0 +1,690 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+
+#include <sys/queue.h>
+
+#include "event2/util.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/event.h"
+#include "event2/util.h"
+#include "event-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "util-internal.h"
+#include "iocp-internal.h"
+
+#ifndef SO_UPDATE_CONNECT_CONTEXT
+/* Mingw is sometimes missing this */
+#define SO_UPDATE_CONNECT_CONTEXT 0x7010
+#endif
+
+/* prototypes */
+static int be_async_enable(struct bufferevent *, short);
+static int be_async_disable(struct bufferevent *, short);
+static void be_async_destruct(struct bufferevent *);
+static int be_async_flush(struct bufferevent *, short, enum bufferevent_flush_mode);
+static int be_async_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+struct bufferevent_async {
+       struct bufferevent_private bev;
+       struct event_overlapped connect_overlapped;
+       struct event_overlapped read_overlapped;
+       struct event_overlapped write_overlapped;
+       size_t read_in_progress;
+       size_t write_in_progress;
+       unsigned ok : 1;
+       unsigned read_added : 1;
+       unsigned write_added : 1;
+};
+
+const struct bufferevent_ops bufferevent_ops_async = {
+       "socket_async",
+       evutil_offsetof(struct bufferevent_async, bev.bev),
+       be_async_enable,
+       be_async_disable,
+       be_async_destruct,
+       _bufferevent_generic_adj_timeouts,
+       be_async_flush,
+       be_async_ctrl,
+};
+
+static inline struct bufferevent_async *
+upcast(struct bufferevent *bev)
+{
+       struct bufferevent_async *bev_a;
+       if (bev->be_ops != &bufferevent_ops_async)
+               return NULL;
+       bev_a = EVUTIL_UPCAST(bev, struct bufferevent_async, bev.bev);
+       return bev_a;
+}
+
+static inline struct bufferevent_async *
+upcast_connect(struct event_overlapped *eo)
+{
+       struct bufferevent_async *bev_a;
+       bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, connect_overlapped);
+       EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));
+       return bev_a;
+}
+
+static inline struct bufferevent_async *
+upcast_read(struct event_overlapped *eo)
+{
+       struct bufferevent_async *bev_a;
+       bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, read_overlapped);
+       EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));
+       return bev_a;
+}
+
+static inline struct bufferevent_async *
+upcast_write(struct event_overlapped *eo)
+{
+       struct bufferevent_async *bev_a;
+       bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, write_overlapped);
+       EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));
+       return bev_a;
+}
+
+static void
+bev_async_del_write(struct bufferevent_async *beva)
+{
+       struct bufferevent *bev = &beva->bev.bev;
+
+       if (beva->write_added) {
+               beva->write_added = 0;
+               event_base_del_virtual(bev->ev_base);
+       }
+}
+
+static void
+bev_async_del_read(struct bufferevent_async *beva)
+{
+       struct bufferevent *bev = &beva->bev.bev;
+
+       if (beva->read_added) {
+               beva->read_added = 0;
+               event_base_del_virtual(bev->ev_base);
+       }
+}
+
+static void
+bev_async_add_write(struct bufferevent_async *beva)
+{
+       struct bufferevent *bev = &beva->bev.bev;
+
+       if (!beva->write_added) {
+               beva->write_added = 1;
+               event_base_add_virtual(bev->ev_base);
+       }
+}
+
+static void
+bev_async_add_read(struct bufferevent_async *beva)
+{
+       struct bufferevent *bev = &beva->bev.bev;
+
+       if (!beva->read_added) {
+               beva->read_added = 1;
+               event_base_add_virtual(bev->ev_base);
+       }
+}
+
+static void
+bev_async_consider_writing(struct bufferevent_async *beva)
+{
+       size_t at_most;
+       int limit;
+       struct bufferevent *bev = &beva->bev.bev;
+
+       /* Don't write if there's a write in progress, or we do not
+        * want to write, or when there's nothing left to write. */
+       if (beva->write_in_progress || beva->bev.connecting)
+               return;
+       if (!beva->ok || !(bev->enabled&EV_WRITE) ||
+           !evbuffer_get_length(bev->output)) {
+               bev_async_del_write(beva);
+               return;
+       }
+
+       at_most = evbuffer_get_length(bev->output);
+
+       /* This is safe so long as bufferevent_get_write_max never returns
+        * more than INT_MAX.  That's true for now. XXXX */
+       limit = (int)_bufferevent_get_write_max(&beva->bev);
+       if (at_most >= (size_t)limit && limit >= 0)
+               at_most = limit;
+
+       if (beva->bev.write_suspended) {
+               bev_async_del_write(beva);
+               return;
+       }
+
+       /*  XXXX doesn't respect low-water mark very well. */
+       bufferevent_incref(bev);
+       if (evbuffer_launch_write(bev->output, at_most,
+           &beva->write_overlapped)) {
+               bufferevent_decref(bev);
+               beva->ok = 0;
+               _bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
+       } else {
+               beva->write_in_progress = at_most;
+               _bufferevent_decrement_write_buckets(&beva->bev, at_most);
+               bev_async_add_write(beva);
+       }
+}
+
+static void
+bev_async_consider_reading(struct bufferevent_async *beva)
+{
+       size_t cur_size;
+       size_t read_high;
+       size_t at_most;
+       int limit;
+       struct bufferevent *bev = &beva->bev.bev;
+
+       /* Don't read if there is a read in progress, or we do not
+        * want to read. */
+       if (beva->read_in_progress || beva->bev.connecting)
+               return;
+       if (!beva->ok || !(bev->enabled&EV_READ)) {
+               bev_async_del_read(beva);
+               return;
+       }
+
+       /* Don't read if we're full */
+       cur_size = evbuffer_get_length(bev->input);
+       read_high = bev->wm_read.high;
+       if (read_high) {
+               if (cur_size >= read_high) {
+                       bev_async_del_read(beva);
+                       return;
+               }
+               at_most = read_high - cur_size;
+       } else {
+               at_most = 16384; /* FIXME totally magic. */
+       }
+
+       /* XXXX This over-commits. */
+       /* XXXX see also not above on cast on _bufferevent_get_write_max() */
+       limit = (int)_bufferevent_get_read_max(&beva->bev);
+       if (at_most >= (size_t)limit && limit >= 0)
+               at_most = limit;
+
+       if (beva->bev.read_suspended) {
+               bev_async_del_read(beva);
+               return;
+       }
+
+       bufferevent_incref(bev);
+       if (evbuffer_launch_read(bev->input, at_most, &beva->read_overlapped)) {
+               beva->ok = 0;
+               _bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
+               bufferevent_decref(bev);
+       } else {
+               beva->read_in_progress = at_most;
+               _bufferevent_decrement_read_buckets(&beva->bev, at_most);
+               bev_async_add_read(beva);
+       }
+
+       return;
+}
+
+static void
+be_async_outbuf_callback(struct evbuffer *buf,
+    const struct evbuffer_cb_info *cbinfo,
+    void *arg)
+{
+       struct bufferevent *bev = arg;
+       struct bufferevent_async *bev_async = upcast(bev);
+
+       /* If we added data to the outbuf and were not writing before,
+        * we may want to write now. */
+
+       _bufferevent_incref_and_lock(bev);
+
+       if (cbinfo->n_added)
+               bev_async_consider_writing(bev_async);
+
+       _bufferevent_decref_and_unlock(bev);
+}
+
+static void
+be_async_inbuf_callback(struct evbuffer *buf,
+    const struct evbuffer_cb_info *cbinfo,
+    void *arg)
+{
+       struct bufferevent *bev = arg;
+       struct bufferevent_async *bev_async = upcast(bev);
+
+       /* If we drained data from the inbuf and were not reading before,
+        * we may want to read now */
+
+       _bufferevent_incref_and_lock(bev);
+
+       if (cbinfo->n_deleted)
+               bev_async_consider_reading(bev_async);
+
+       _bufferevent_decref_and_unlock(bev);
+}
+
+static int
+be_async_enable(struct bufferevent *buf, short what)
+{
+       struct bufferevent_async *bev_async = upcast(buf);
+
+       if (!bev_async->ok)
+               return -1;
+
+       if (bev_async->bev.connecting) {
+               /* Don't launch anything during connection attempts. */
+               return 0;
+       }
+
+       if (what & EV_READ)
+               BEV_RESET_GENERIC_READ_TIMEOUT(buf);
+       if (what & EV_WRITE)
+               BEV_RESET_GENERIC_WRITE_TIMEOUT(buf);
+
+       /* If we newly enable reading or writing, and we aren't reading or
+          writing already, consider launching a new read or write. */
+
+       if (what & EV_READ)
+               bev_async_consider_reading(bev_async);
+       if (what & EV_WRITE)
+               bev_async_consider_writing(bev_async);
+       return 0;
+}
+
+static int
+be_async_disable(struct bufferevent *bev, short what)
+{
+       struct bufferevent_async *bev_async = upcast(bev);
+       /* XXXX If we disable reading or writing, we may want to consider
+        * canceling any in-progress read or write operation, though it might
+        * not work. */
+
+       if (what & EV_READ) {
+               BEV_DEL_GENERIC_READ_TIMEOUT(bev);
+               bev_async_del_read(bev_async);
+       }
+       if (what & EV_WRITE) {
+               BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
+               bev_async_del_write(bev_async);
+       }
+
+       return 0;
+}
+
+static void
+be_async_destruct(struct bufferevent *bev)
+{
+       struct bufferevent_async *bev_async = upcast(bev);
+       struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+       evutil_socket_t fd;
+
+       EVUTIL_ASSERT(!upcast(bev)->write_in_progress &&
+                       !upcast(bev)->read_in_progress);
+
+       bev_async_del_read(bev_async);
+       bev_async_del_write(bev_async);
+
+       fd = _evbuffer_overlapped_get_fd(bev->input);
+       if (bev_p->options & BEV_OPT_CLOSE_ON_FREE) {
+               /* XXXX possible double-close */
+               evutil_closesocket(fd);
+       }
+       /* delete this in case non-blocking connect was used */
+       if (event_initialized(&bev->ev_write)) {
+               event_del(&bev->ev_write);
+               _bufferevent_del_generic_timeout_cbs(bev);
+       }
+}
+
+/* GetQueuedCompletionStatus doesn't reliably yield WSA error codes, so
+ * we use WSAGetOverlappedResult to translate. */
+static void
+bev_async_set_wsa_error(struct bufferevent *bev, struct event_overlapped *eo)
+{
+       DWORD bytes, flags;
+       evutil_socket_t fd;
+
+       fd = _evbuffer_overlapped_get_fd(bev->input);
+       WSAGetOverlappedResult(fd, &eo->overlapped, &bytes, FALSE, &flags);
+}
+
+static int
+be_async_flush(struct bufferevent *bev, short what,
+    enum bufferevent_flush_mode mode)
+{
+       return 0;
+}
+
+static void
+connect_complete(struct event_overlapped *eo, ev_uintptr_t key,
+    ev_ssize_t nbytes, int ok)
+{
+       struct bufferevent_async *bev_a = upcast_connect(eo);
+       struct bufferevent *bev = &bev_a->bev.bev;
+       evutil_socket_t sock;
+
+       BEV_LOCK(bev);
+
+       EVUTIL_ASSERT(bev_a->bev.connecting);
+       bev_a->bev.connecting = 0;
+       sock = _evbuffer_overlapped_get_fd(bev_a->bev.bev.input);
+       /* XXXX Handle error? */
+       setsockopt(sock, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
+
+       if (ok)
+               bufferevent_async_set_connected(bev);
+       else
+               bev_async_set_wsa_error(bev, eo);
+
+       _bufferevent_run_eventcb(bev,
+                       ok? BEV_EVENT_CONNECTED : BEV_EVENT_ERROR);
+
+       event_base_del_virtual(bev->ev_base);
+
+       _bufferevent_decref_and_unlock(bev);
+}
+
+static void
+read_complete(struct event_overlapped *eo, ev_uintptr_t key,
+    ev_ssize_t nbytes, int ok)
+{
+       struct bufferevent_async *bev_a = upcast_read(eo);
+       struct bufferevent *bev = &bev_a->bev.bev;
+       short what = BEV_EVENT_READING;
+       ev_ssize_t amount_unread;
+       BEV_LOCK(bev);
+       EVUTIL_ASSERT(bev_a->read_in_progress);
+
+       amount_unread = bev_a->read_in_progress - nbytes;
+       evbuffer_commit_read(bev->input, nbytes);
+       bev_a->read_in_progress = 0;
+       if (amount_unread)
+               _bufferevent_decrement_read_buckets(&bev_a->bev, -amount_unread);
+
+       if (!ok)
+               bev_async_set_wsa_error(bev, eo);
+
+       if (bev_a->ok) {
+               if (ok && nbytes) {
+                       BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+                       if (evbuffer_get_length(bev->input) >= bev->wm_read.low)
+                               _bufferevent_run_readcb(bev);
+                       bev_async_consider_reading(bev_a);
+               } else if (!ok) {
+                       what |= BEV_EVENT_ERROR;
+                       bev_a->ok = 0;
+                       _bufferevent_run_eventcb(bev, what);
+               } else if (!nbytes) {
+                       what |= BEV_EVENT_EOF;
+                       bev_a->ok = 0;
+                       _bufferevent_run_eventcb(bev, what);
+               }
+       }
+
+       _bufferevent_decref_and_unlock(bev);
+}
+
+static void
+write_complete(struct event_overlapped *eo, ev_uintptr_t key,
+    ev_ssize_t nbytes, int ok)
+{
+       struct bufferevent_async *bev_a = upcast_write(eo);
+       struct bufferevent *bev = &bev_a->bev.bev;
+       short what = BEV_EVENT_WRITING;
+       ev_ssize_t amount_unwritten;
+
+       BEV_LOCK(bev);
+       EVUTIL_ASSERT(bev_a->write_in_progress);
+
+       amount_unwritten = bev_a->write_in_progress - nbytes;
+       evbuffer_commit_write(bev->output, nbytes);
+       bev_a->write_in_progress = 0;
+
+       if (amount_unwritten)
+               _bufferevent_decrement_write_buckets(&bev_a->bev,
+                                                    -amount_unwritten);
+
+
+       if (!ok)
+               bev_async_set_wsa_error(bev, eo);
+
+       if (bev_a->ok) {
+               if (ok && nbytes) {
+                       BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
+                       if (evbuffer_get_length(bev->output) <=
+                           bev->wm_write.low)
+                               _bufferevent_run_writecb(bev);
+                       bev_async_consider_writing(bev_a);
+               } else if (!ok) {
+                       what |= BEV_EVENT_ERROR;
+                       bev_a->ok = 0;
+                       _bufferevent_run_eventcb(bev, what);
+               } else if (!nbytes) {
+                       what |= BEV_EVENT_EOF;
+                       bev_a->ok = 0;
+                       _bufferevent_run_eventcb(bev, what);
+               }
+       }
+
+       _bufferevent_decref_and_unlock(bev);
+}
+
+struct bufferevent *
+bufferevent_async_new(struct event_base *base,
+    evutil_socket_t fd, int options)
+{
+       struct bufferevent_async *bev_a;
+       struct bufferevent *bev;
+       struct event_iocp_port *iocp;
+
+       options |= BEV_OPT_THREADSAFE;
+
+       if (!(iocp = event_base_get_iocp(base)))
+               return NULL;
+
+       if (fd >= 0 && event_iocp_port_associate(iocp, fd, 1)<0) {
+               int err = GetLastError();
+               /* We may have alrady associated this fd with a port.
+                * Let's hope it's this port, and that the error code
+                * for doing this neer changes. */
+               if (err != ERROR_INVALID_PARAMETER)
+                       return NULL;
+       }
+
+       if (!(bev_a = mm_calloc(1, sizeof(struct bufferevent_async))))
+               return NULL;
+
+       bev = &bev_a->bev.bev;
+       if (!(bev->input = evbuffer_overlapped_new(fd))) {
+               mm_free(bev_a);
+               return NULL;
+       }
+       if (!(bev->output = evbuffer_overlapped_new(fd))) {
+               evbuffer_free(bev->input);
+               mm_free(bev_a);
+               return NULL;
+       }
+
+       if (bufferevent_init_common(&bev_a->bev, base, &bufferevent_ops_async,
+               options)<0)
+               goto err;
+
+       evbuffer_add_cb(bev->input, be_async_inbuf_callback, bev);
+       evbuffer_add_cb(bev->output, be_async_outbuf_callback, bev);
+
+       event_overlapped_init(&bev_a->connect_overlapped, connect_complete);
+       event_overlapped_init(&bev_a->read_overlapped, read_complete);
+       event_overlapped_init(&bev_a->write_overlapped, write_complete);
+
+       bev_a->ok = fd >= 0;
+       if (bev_a->ok)
+               _bufferevent_init_generic_timeout_cbs(bev);
+
+       return bev;
+err:
+       bufferevent_free(&bev_a->bev.bev);
+       return NULL;
+}
+
+void
+bufferevent_async_set_connected(struct bufferevent *bev)
+{
+       struct bufferevent_async *bev_async = upcast(bev);
+       bev_async->ok = 1;
+       _bufferevent_init_generic_timeout_cbs(bev);
+       /* Now's a good time to consider reading/writing */
+       be_async_enable(bev, bev->enabled);
+}
+
+int
+bufferevent_async_can_connect(struct bufferevent *bev)
+{
+       const struct win32_extension_fns *ext =
+           event_get_win32_extension_fns();
+
+       if (BEV_IS_ASYNC(bev) &&
+           event_base_get_iocp(bev->ev_base) &&
+           ext && ext->ConnectEx)
+               return 1;
+
+       return 0;
+}
+
+int
+bufferevent_async_connect(struct bufferevent *bev, evutil_socket_t fd,
+       const struct sockaddr *sa, int socklen)
+{
+       BOOL rc;
+       struct bufferevent_async *bev_async = upcast(bev);
+       struct sockaddr_storage ss;
+       const struct win32_extension_fns *ext =
+           event_get_win32_extension_fns();
+
+       EVUTIL_ASSERT(ext && ext->ConnectEx && fd >= 0 && sa != NULL);
+
+       /* ConnectEx() requires that the socket be bound to an address
+        * with bind() before using, otherwise it will fail. We attempt
+        * to issue a bind() here, taking into account that the error
+        * code is set to WSAEINVAL when the socket is already bound. */
+       memset(&ss, 0, sizeof(ss));
+       if (sa->sa_family == AF_INET) {
+               struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
+               sin->sin_family = AF_INET;
+               sin->sin_addr.s_addr = INADDR_ANY;
+       } else if (sa->sa_family == AF_INET6) {
+               struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
+               sin6->sin6_family = AF_INET6;
+               sin6->sin6_addr = in6addr_any;
+       } else {
+               /* Well, the user will have to bind() */
+               return -1;
+       }
+       if (bind(fd, (struct sockaddr *)&ss, sizeof(ss)) < 0 &&
+           WSAGetLastError() != WSAEINVAL)
+               return -1;
+
+       event_base_add_virtual(bev->ev_base);
+       bufferevent_incref(bev);
+       rc = ext->ConnectEx(fd, sa, socklen, NULL, 0, NULL,
+                           &bev_async->connect_overlapped.overlapped);
+       if (rc || WSAGetLastError() == ERROR_IO_PENDING)
+               return 0;
+
+       event_base_del_virtual(bev->ev_base);
+       bufferevent_decref(bev);
+
+       return -1;
+}
+
+static int
+be_async_ctrl(struct bufferevent *bev, enum bufferevent_ctrl_op op,
+    union bufferevent_ctrl_data *data)
+{
+       switch (op) {
+       case BEV_CTRL_GET_FD:
+               data->fd = _evbuffer_overlapped_get_fd(bev->input);
+               return 0;
+       case BEV_CTRL_SET_FD: {
+               struct event_iocp_port *iocp;
+
+               if (data->fd == _evbuffer_overlapped_get_fd(bev->input))
+                       return 0;
+               if (!(iocp = event_base_get_iocp(bev->ev_base)))
+                       return -1;
+               if (event_iocp_port_associate(iocp, data->fd, 1) < 0)
+                       return -1;
+               _evbuffer_overlapped_set_fd(bev->input, data->fd);
+               _evbuffer_overlapped_set_fd(bev->output, data->fd);
+               return 0;
+       }
+       case BEV_CTRL_CANCEL_ALL: {
+               struct bufferevent_async *bev_a = upcast(bev);
+               evutil_socket_t fd = _evbuffer_overlapped_get_fd(bev->input);
+               if (fd != (evutil_socket_t)INVALID_SOCKET &&
+                   (bev_a->bev.options & BEV_OPT_CLOSE_ON_FREE)) {
+                       closesocket(fd);
+               }
+               bev_a->ok = 0;
+               return 0;
+       }
+       case BEV_CTRL_GET_UNDERLYING:
+       default:
+               return -1;
+       }
+}
+
+
diff --git a/libevent/bufferevent_filter.c b/libevent/bufferevent_filter.c
new file mode 100644 (file)
index 0000000..557f8cc
--- /dev/null
@@ -0,0 +1,511 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+
+#include "event2/event-config.h"
+
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/util.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/event.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "util-internal.h"
+
+/* prototypes */
+static int be_filter_enable(struct bufferevent *, short);
+static int be_filter_disable(struct bufferevent *, short);
+static void be_filter_destruct(struct bufferevent *);
+
+static void be_filter_readcb(struct bufferevent *, void *);
+static void be_filter_writecb(struct bufferevent *, void *);
+static void be_filter_eventcb(struct bufferevent *, short, void *);
+static int be_filter_flush(struct bufferevent *bufev,
+    short iotype, enum bufferevent_flush_mode mode);
+static int be_filter_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+static void bufferevent_filtered_outbuf_cb(struct evbuffer *buf,
+    const struct evbuffer_cb_info *info, void *arg);
+
+struct bufferevent_filtered {
+       struct bufferevent_private bev;
+
+       /** The bufferevent that we read/write filtered data from/to. */
+       struct bufferevent *underlying;
+       /** A callback on our outbuf to notice when somebody adds data */
+       struct evbuffer_cb_entry *outbuf_cb;
+       /** True iff we have received an EOF callback from the underlying
+        * bufferevent. */
+       unsigned got_eof;
+
+       /** Function to free context when we're done. */
+       void (*free_context)(void *);
+       /** Input filter */
+       bufferevent_filter_cb process_in;
+       /** Output filter */
+       bufferevent_filter_cb process_out;
+       /** User-supplied argument to the filters. */
+       void *context;
+};
+
+const struct bufferevent_ops bufferevent_ops_filter = {
+       "filter",
+       evutil_offsetof(struct bufferevent_filtered, bev.bev),
+       be_filter_enable,
+       be_filter_disable,
+       be_filter_destruct,
+       _bufferevent_generic_adj_timeouts,
+       be_filter_flush,
+       be_filter_ctrl,
+};
+
+/* Given a bufferevent that's really the bev filter of a bufferevent_filtered,
+ * return that bufferevent_filtered. Returns NULL otherwise.*/
+static inline struct bufferevent_filtered *
+upcast(struct bufferevent *bev)
+{
+       struct bufferevent_filtered *bev_f;
+       if (bev->be_ops != &bufferevent_ops_filter)
+               return NULL;
+       bev_f = (void*)( ((char*)bev) -
+                        evutil_offsetof(struct bufferevent_filtered, bev.bev));
+       EVUTIL_ASSERT(bev_f->bev.bev.be_ops == &bufferevent_ops_filter);
+       return bev_f;
+}
+
+#define downcast(bev_f) (&(bev_f)->bev.bev)
+
+/** Return 1 iff bevf's underlying bufferevent's output buffer is at or
+ * over its high watermark such that we should not write to it in a given
+ * flush mode. */
+static int
+be_underlying_writebuf_full(struct bufferevent_filtered *bevf,
+    enum bufferevent_flush_mode state)
+{
+       struct bufferevent *u = bevf->underlying;
+       return state == BEV_NORMAL &&
+           u->wm_write.high &&
+           evbuffer_get_length(u->output) >= u->wm_write.high;
+}
+
+/** Return 1 if our input buffer is at or over its high watermark such that we
+ * should not write to it in a given flush mode. */
+static int
+be_readbuf_full(struct bufferevent_filtered *bevf,
+    enum bufferevent_flush_mode state)
+{
+       struct bufferevent *bufev = downcast(bevf);
+       return state == BEV_NORMAL &&
+           bufev->wm_read.high &&
+           evbuffer_get_length(bufev->input) >= bufev->wm_read.high;
+}
+
+
+/* Filter to use when we're created with a NULL filter. */
+static enum bufferevent_filter_result
+be_null_filter(struct evbuffer *src, struct evbuffer *dst, ev_ssize_t lim,
+              enum bufferevent_flush_mode state, void *ctx)
+{
+       (void)state;
+       if (evbuffer_remove_buffer(src, dst, lim) == 0)
+               return BEV_OK;
+       else
+               return BEV_ERROR;
+}
+
+struct bufferevent *
+bufferevent_filter_new(struct bufferevent *underlying,
+                      bufferevent_filter_cb input_filter,
+                      bufferevent_filter_cb output_filter,
+                      int options,
+                      void (*free_context)(void *),
+                      void *ctx)
+{
+       struct bufferevent_filtered *bufev_f;
+       int tmp_options = options & ~BEV_OPT_THREADSAFE;
+
+       if (!underlying)
+               return NULL;
+
+       if (!input_filter)
+               input_filter = be_null_filter;
+       if (!output_filter)
+               output_filter = be_null_filter;
+
+       bufev_f = mm_calloc(1, sizeof(struct bufferevent_filtered));
+       if (!bufev_f)
+               return NULL;
+
+       if (bufferevent_init_common(&bufev_f->bev, underlying->ev_base,
+                                   &bufferevent_ops_filter, tmp_options) < 0) {
+               mm_free(bufev_f);
+               return NULL;
+       }
+       if (options & BEV_OPT_THREADSAFE) {
+               bufferevent_enable_locking(downcast(bufev_f), NULL);
+       }
+
+       bufev_f->underlying = underlying;
+
+       bufev_f->process_in = input_filter;
+       bufev_f->process_out = output_filter;
+       bufev_f->free_context = free_context;
+       bufev_f->context = ctx;
+
+       bufferevent_setcb(bufev_f->underlying,
+           be_filter_readcb, be_filter_writecb, be_filter_eventcb, bufev_f);
+
+       bufev_f->outbuf_cb = evbuffer_add_cb(downcast(bufev_f)->output,
+          bufferevent_filtered_outbuf_cb, bufev_f);
+
+       _bufferevent_init_generic_timeout_cbs(downcast(bufev_f));
+       bufferevent_incref(underlying);
+
+       bufferevent_enable(underlying, EV_READ|EV_WRITE);
+       bufferevent_suspend_read(underlying, BEV_SUSPEND_FILT_READ);
+
+       return downcast(bufev_f);
+}
+
+static void
+be_filter_destruct(struct bufferevent *bev)
+{
+       struct bufferevent_filtered *bevf = upcast(bev);
+       EVUTIL_ASSERT(bevf);
+       if (bevf->free_context)
+               bevf->free_context(bevf->context);
+
+       if (bevf->bev.options & BEV_OPT_CLOSE_ON_FREE) {
+               /* Yes, there is also a decref in bufferevent_decref.
+                * That decref corresponds to the incref when we set
+                * underlying for the first time.  This decref is an
+                * extra one to remove the last reference.
+                */
+               if (BEV_UPCAST(bevf->underlying)->refcnt < 2) {
+                       event_warnx("BEV_OPT_CLOSE_ON_FREE set on an "
+                           "bufferevent with too few references");
+               } else {
+                       bufferevent_free(bevf->underlying);
+               }
+       } else {
+               if (bevf->underlying) {
+                       if (bevf->underlying->errorcb == be_filter_eventcb)
+                               bufferevent_setcb(bevf->underlying,
+                                   NULL, NULL, NULL, NULL);
+                       bufferevent_unsuspend_read(bevf->underlying,
+                           BEV_SUSPEND_FILT_READ);
+               }
+       }
+
+       _bufferevent_del_generic_timeout_cbs(bev);
+}
+
+static int
+be_filter_enable(struct bufferevent *bev, short event)
+{
+       struct bufferevent_filtered *bevf = upcast(bev);
+       if (event & EV_WRITE)
+               BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
+
+       if (event & EV_READ) {
+               BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+               bufferevent_unsuspend_read(bevf->underlying,
+                   BEV_SUSPEND_FILT_READ);
+       }
+       return 0;
+}
+
+static int
+be_filter_disable(struct bufferevent *bev, short event)
+{
+       struct bufferevent_filtered *bevf = upcast(bev);
+       if (event & EV_WRITE)
+               BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
+       if (event & EV_READ) {
+               BEV_DEL_GENERIC_READ_TIMEOUT(bev);
+               bufferevent_suspend_read(bevf->underlying,
+                   BEV_SUSPEND_FILT_READ);
+       }
+       return 0;
+}
+
+static enum bufferevent_filter_result
+be_filter_process_input(struct bufferevent_filtered *bevf,
+                       enum bufferevent_flush_mode state,
+                       int *processed_out)
+{
+       enum bufferevent_filter_result res;
+       struct bufferevent *bev = downcast(bevf);
+
+       if (state == BEV_NORMAL) {
+               /* If we're in 'normal' mode, don't urge data on the filter
+                * unless we're reading data and under our high-water mark.*/
+               if (!(bev->enabled & EV_READ) ||
+                   be_readbuf_full(bevf, state))
+                       return BEV_OK;
+       }
+
+       do {
+               ev_ssize_t limit = -1;
+               if (state == BEV_NORMAL && bev->wm_read.high)
+                       limit = bev->wm_read.high -
+                           evbuffer_get_length(bev->input);
+
+               res = bevf->process_in(bevf->underlying->input,
+                   bev->input, limit, state, bevf->context);
+
+               if (res == BEV_OK)
+                       *processed_out = 1;
+       } while (res == BEV_OK &&
+                (bev->enabled & EV_READ) &&
+                evbuffer_get_length(bevf->underlying->input) &&
+                !be_readbuf_full(bevf, state));
+
+       if (*processed_out)
+               BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+
+       return res;
+}
+
+
+static enum bufferevent_filter_result
+be_filter_process_output(struct bufferevent_filtered *bevf,
+                        enum bufferevent_flush_mode state,
+                        int *processed_out)
+{
+       /* Requires references and lock: might call writecb */
+       enum bufferevent_filter_result res = BEV_OK;
+       struct bufferevent *bufev = downcast(bevf);
+       int again = 0;
+
+       if (state == BEV_NORMAL) {
+               /* If we're in 'normal' mode, don't urge data on the
+                * filter unless we're writing data, and the underlying
+                * bufferevent is accepting data, and we have data to
+                * give the filter.  If we're in 'flush' or 'finish',
+                * call the filter no matter what. */
+               if (!(bufev->enabled & EV_WRITE) ||
+                   be_underlying_writebuf_full(bevf, state) ||
+                   !evbuffer_get_length(bufev->output))
+                       return BEV_OK;
+       }
+
+       /* disable the callback that calls this function
+          when the user adds to the output buffer. */
+       evbuffer_cb_set_flags(bufev->output, bevf->outbuf_cb, 0);
+
+       do {
+               int processed = 0;
+               again = 0;
+
+               do {
+                       ev_ssize_t limit = -1;
+                       if (state == BEV_NORMAL &&
+                           bevf->underlying->wm_write.high)
+                               limit = bevf->underlying->wm_write.high -
+                                   evbuffer_get_length(bevf->underlying->output);
+
+                       res = bevf->process_out(downcast(bevf)->output,
+                           bevf->underlying->output,
+                           limit,
+                           state,
+                           bevf->context);
+
+                       if (res == BEV_OK)
+                               processed = *processed_out = 1;
+               } while (/* Stop if the filter wasn't successful...*/
+                       res == BEV_OK &&
+                       /* Or if we aren't writing any more. */
+                       (bufev->enabled & EV_WRITE) &&
+                       /* Of if we have nothing more to write and we are
+                        * not flushing. */
+                       evbuffer_get_length(bufev->output) &&
+                       /* Or if we have filled the underlying output buffer. */
+                       !be_underlying_writebuf_full(bevf,state));
+
+               if (processed &&
+                   evbuffer_get_length(bufev->output) <= bufev->wm_write.low) {
+                       /* call the write callback.*/
+                       _bufferevent_run_writecb(bufev);
+
+                       if (res == BEV_OK &&
+                           (bufev->enabled & EV_WRITE) &&
+                           evbuffer_get_length(bufev->output) &&
+                           !be_underlying_writebuf_full(bevf, state)) {
+                               again = 1;
+                       }
+               }
+       } while (again);
+
+       /* reenable the outbuf_cb */
+       evbuffer_cb_set_flags(bufev->output,bevf->outbuf_cb,
+           EVBUFFER_CB_ENABLED);
+
+       if (*processed_out)
+               BEV_RESET_GENERIC_WRITE_TIMEOUT(bufev);
+
+       return res;
+}
+
+/* Called when the size of our outbuf changes. */
+static void
+bufferevent_filtered_outbuf_cb(struct evbuffer *buf,
+    const struct evbuffer_cb_info *cbinfo, void *arg)
+{
+       struct bufferevent_filtered *bevf = arg;
+       struct bufferevent *bev = downcast(bevf);
+
+       if (cbinfo->n_added) {
+               int processed_any = 0;
+               /* Somebody added more data to the output buffer. Try to
+                * process it, if we should. */
+               _bufferevent_incref_and_lock(bev);
+               be_filter_process_output(bevf, BEV_NORMAL, &processed_any);
+               _bufferevent_decref_and_unlock(bev);
+       }
+}
+
+/* Called when the underlying socket has read. */
+static void
+be_filter_readcb(struct bufferevent *underlying, void *_me)
+{
+       struct bufferevent_filtered *bevf = _me;
+       enum bufferevent_filter_result res;
+       enum bufferevent_flush_mode state;
+       struct bufferevent *bufev = downcast(bevf);
+       int processed_any = 0;
+
+       _bufferevent_incref_and_lock(bufev);
+
+       if (bevf->got_eof)
+               state = BEV_FINISHED;
+       else
+               state = BEV_NORMAL;
+
+       /* XXXX use return value */
+       res = be_filter_process_input(bevf, state, &processed_any);
+       (void)res;
+
+       /* XXX This should be in process_input, not here.  There are
+        * other places that can call process-input, and they should
+        * force readcb calls as needed. */
+       if (processed_any &&
+           evbuffer_get_length(bufev->input) >= bufev->wm_read.low)
+               _bufferevent_run_readcb(bufev);
+
+       _bufferevent_decref_and_unlock(bufev);
+}
+
+/* Called when the underlying socket has drained enough that we can write to
+   it. */
+static void
+be_filter_writecb(struct bufferevent *underlying, void *_me)
+{
+       struct bufferevent_filtered *bevf = _me;
+       struct bufferevent *bev = downcast(bevf);
+       int processed_any = 0;
+
+       _bufferevent_incref_and_lock(bev);
+       be_filter_process_output(bevf, BEV_NORMAL, &processed_any);
+       _bufferevent_decref_and_unlock(bev);
+}
+
+/* Called when the underlying socket has given us an error */
+static void
+be_filter_eventcb(struct bufferevent *underlying, short what, void *_me)
+{
+       struct bufferevent_filtered *bevf = _me;
+       struct bufferevent *bev = downcast(bevf);
+
+       _bufferevent_incref_and_lock(bev);
+       /* All we can really to is tell our own eventcb. */
+       _bufferevent_run_eventcb(bev, what);
+       _bufferevent_decref_and_unlock(bev);
+}
+
+static int
+be_filter_flush(struct bufferevent *bufev,
+    short iotype, enum bufferevent_flush_mode mode)
+{
+       struct bufferevent_filtered *bevf = upcast(bufev);
+       int processed_any = 0;
+       EVUTIL_ASSERT(bevf);
+
+       _bufferevent_incref_and_lock(bufev);
+
+       if (iotype & EV_READ) {
+               be_filter_process_input(bevf, mode, &processed_any);
+       }
+       if (iotype & EV_WRITE) {
+               be_filter_process_output(bevf, mode, &processed_any);
+       }
+       /* XXX check the return value? */
+       /* XXX does this want to recursively call lower-level flushes? */
+       bufferevent_flush(bevf->underlying, iotype, mode);
+
+       _bufferevent_decref_and_unlock(bufev);
+
+       return processed_any;
+}
+
+static int
+be_filter_ctrl(struct bufferevent *bev, enum bufferevent_ctrl_op op,
+    union bufferevent_ctrl_data *data)
+{
+       struct bufferevent_filtered *bevf;
+       switch (op) {
+       case BEV_CTRL_GET_UNDERLYING:
+               bevf = upcast(bev);
+               data->ptr = bevf->underlying;
+               return 0;
+       case BEV_CTRL_GET_FD:
+       case BEV_CTRL_SET_FD:
+       case BEV_CTRL_CANCEL_ALL:
+       default:
+               return -1;
+       }
+}
diff --git a/libevent/bufferevent_openssl.c b/libevent/bufferevent_openssl.c
new file mode 100644 (file)
index 0000000..412c08e
--- /dev/null
@@ -0,0 +1,1418 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+
+#include "event2/event-config.h"
+
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/bufferevent_ssl.h"
+#include "event2/buffer.h"
+#include "event2/event.h"
+
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "log-internal.h"
+
+#include <openssl/bio.h>
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+
+/*
+ * Define an OpenSSL bio that targets a bufferevent.
+ */
+
+/* --------------------
+   A BIO is an OpenSSL abstraction that handles reading and writing data.  The
+   library will happily speak SSL over anything that implements a BIO
+   interface.
+
+   Here we define a BIO implementation that directs its output to a
+   bufferevent.  We'll want to use this only when none of OpenSSL's built-in
+   IO mechanisms work for us.
+   -------------------- */
+
+/* every BIO type needs its own integer type value. */
+#define BIO_TYPE_LIBEVENT 57
+/* ???? Arguably, we should set BIO_TYPE_FILTER or BIO_TYPE_SOURCE_SINK on
+ * this. */
+
+#if 0
+static void
+print_err(int val)
+{
+       int err;
+       printf("Error was %d\n", val);
+
+       while ((err = ERR_get_error()))x {
+               const char *msg = (const char*)ERR_reason_error_string(err);
+               const char *lib = (const char*)ERR_lib_error_string(err);
+               const char *func = (const char*)ERR_func_error_string(err);
+
+               printf("%s in %s %s\n", msg, lib, func);
+       }
+}
+#else
+#define print_err(v) ((void)0)
+#endif
+
+/* Called to initialize a new BIO */
+static int
+bio_bufferevent_new(BIO *b)
+{
+       b->init = 0;
+       b->num = -1;
+       b->ptr = NULL; /* We'll be putting the bufferevent in this field.*/
+       b->flags = 0;
+       return 1;
+}
+
+/* Called to uninitialize the BIO. */
+static int
+bio_bufferevent_free(BIO *b)
+{
+       if (!b)
+               return 0;
+       if (b->shutdown) {
+               if (b->init && b->ptr)
+                       bufferevent_free(b->ptr);
+               b->init = 0;
+               b->flags = 0;
+               b->ptr = NULL;
+       }
+       return 1;
+}
+
+/* Called to extract data from the BIO. */
+static int
+bio_bufferevent_read(BIO *b, char *out, int outlen)
+{
+       int r = 0;
+       struct evbuffer *input;
+
+       BIO_clear_retry_flags(b);
+
+       if (!out)
+               return 0;
+       if (!b->ptr)
+               return -1;
+
+       input = bufferevent_get_input(b->ptr);
+       if (evbuffer_get_length(input) == 0) {
+               /* If there's no data to read, say so. */
+               BIO_set_retry_read(b);
+               return -1;
+       } else {
+               r = evbuffer_remove(input, out, outlen);
+       }
+
+       return r;
+}
+
+/* Called to write data info the BIO */
+static int
+bio_bufferevent_write(BIO *b, const char *in, int inlen)
+{
+       struct bufferevent *bufev = b->ptr;
+       struct evbuffer *output;
+       size_t outlen;
+
+       BIO_clear_retry_flags(b);
+
+       if (!b->ptr)
+               return -1;
+
+       output = bufferevent_get_output(bufev);
+       outlen = evbuffer_get_length(output);
+
+       /* Copy only as much data onto the output buffer as can fit under the
+        * high-water mark. */
+       if (bufev->wm_write.high && bufev->wm_write.high <= (outlen+inlen)) {
+               if (bufev->wm_write.high <= outlen) {
+                       /* If no data can fit, we'll need to retry later. */
+                       BIO_set_retry_write(b);
+                       return -1;
+               }
+               inlen = bufev->wm_write.high - outlen;
+       }
+
+       EVUTIL_ASSERT(inlen > 0);
+       evbuffer_add(output, in, inlen);
+       return inlen;
+}
+
+/* Called to handle various requests */
+static long
+bio_bufferevent_ctrl(BIO *b, int cmd, long num, void *ptr)
+{
+       struct bufferevent *bufev = b->ptr;
+       long ret = 1;
+
+       switch (cmd) {
+       case BIO_CTRL_GET_CLOSE:
+               ret = b->shutdown;
+               break;
+       case BIO_CTRL_SET_CLOSE:
+               b->shutdown = (int)num;
+               break;
+       case BIO_CTRL_PENDING:
+               ret = evbuffer_get_length(bufferevent_get_input(bufev)) != 0;
+               break;
+       case BIO_CTRL_WPENDING:
+               ret = evbuffer_get_length(bufferevent_get_output(bufev)) != 0;
+               break;
+       /* XXXX These two are given a special-case treatment because
+        * of cargo-cultism.  I should come up with a better reason. */
+       case BIO_CTRL_DUP:
+       case BIO_CTRL_FLUSH:
+               ret = 1;
+               break;
+       default:
+               ret = 0;
+               break;
+       }
+       return ret;
+}
+
+/* Called to write a string to the BIO */
+static int
+bio_bufferevent_puts(BIO *b, const char *s)
+{
+       return bio_bufferevent_write(b, s, strlen(s));
+}
+
+/* Method table for the bufferevent BIO */
+static BIO_METHOD methods_bufferevent = {
+       BIO_TYPE_LIBEVENT, "bufferevent",
+       bio_bufferevent_write,
+       bio_bufferevent_read,
+       bio_bufferevent_puts,
+       NULL /* bio_bufferevent_gets */,
+       bio_bufferevent_ctrl,
+       bio_bufferevent_new,
+       bio_bufferevent_free,
+       NULL /* callback_ctrl */,
+};
+
+/* Return the method table for the bufferevents BIO */
+static BIO_METHOD *
+BIO_s_bufferevent(void)
+{
+       return &methods_bufferevent;
+}
+
+/* Create a new BIO to wrap communication around a bufferevent.  If close_flag
+ * is true, the bufferevent will be freed when the BIO is closed. */
+static BIO *
+BIO_new_bufferevent(struct bufferevent *bufferevent, int close_flag)
+{
+       BIO *result;
+       if (!bufferevent)
+               return NULL;
+       if (!(result = BIO_new(BIO_s_bufferevent())))
+               return NULL;
+       result->init = 1;
+       result->ptr = bufferevent;
+       result->shutdown = close_flag ? 1 : 0;
+       return result;
+}
+
+/* --------------------
+   Now, here's the OpenSSL-based implementation of bufferevent.
+
+   The implementation comes in two flavors: one that connects its SSL object
+   to an underlying bufferevent using a BIO_bufferevent, and one that has the
+   SSL object connect to a socket directly.  The latter should generally be
+   faster, except on Windows, where your best bet is using a
+   bufferevent_async.
+
+   (OpenSSL supports many other BIO types, too.  But we can't use any unless
+   we have a good way to get notified when they become readable/writable.)
+   -------------------- */
+
+struct bio_data_counts {
+       unsigned long n_written;
+       unsigned long n_read;
+};
+
+struct bufferevent_openssl {
+       /* Shared fields with common bufferevent implementation code.
+          If we were set up with an underlying bufferevent, we use the
+          events here as timers only.  If we have an SSL, then we use
+          the events as socket events.
+        */
+       struct bufferevent_private bev;
+       /* An underlying bufferevent that we're directing our output to.
+          If it's NULL, then we're connected to an fd, not an evbuffer. */
+       struct bufferevent *underlying;
+       /* The SSL object doing our encryption. */
+       SSL *ssl;
+
+       /* A callback that's invoked when data arrives on our outbuf so we
+          know to write data to the SSL. */
+       struct evbuffer_cb_entry *outbuf_cb;
+
+       /* A count of how much data the bios have read/written total.  Used
+          for rate-limiting. */
+       struct bio_data_counts counts;
+
+       /* If this value is greater than 0, then the last SSL_write blocked,
+        * and we need to try it again with this many bytes. */
+       ev_ssize_t last_write;
+
+#define NUM_ERRORS 3
+       ev_uint32_t errors[NUM_ERRORS];
+
+       /* When we next get available space, we should say "read" instead of
+          "write". This can happen if there's a renegotiation during a read
+          operation. */
+       unsigned read_blocked_on_write : 1;
+       /* When we next get data, we should say "write" instead of "read". */
+       unsigned write_blocked_on_read : 1;
+       /* XXX */
+       unsigned allow_dirty_shutdown : 1;
+       /* XXXX */
+       unsigned fd_is_set : 1;
+       /* XXX */
+       unsigned n_errors : 2;
+
+       /* Are we currently connecting, accepting, or doing IO? */
+       unsigned state : 2;
+};
+
+static int be_openssl_enable(struct bufferevent *, short);
+static int be_openssl_disable(struct bufferevent *, short);
+static void be_openssl_destruct(struct bufferevent *);
+static int be_openssl_adj_timeouts(struct bufferevent *);
+static int be_openssl_flush(struct bufferevent *bufev,
+    short iotype, enum bufferevent_flush_mode mode);
+static int be_openssl_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+const struct bufferevent_ops bufferevent_ops_openssl = {
+       "ssl",
+       evutil_offsetof(struct bufferevent_openssl, bev.bev),
+       be_openssl_enable,
+       be_openssl_disable,
+       be_openssl_destruct,
+       be_openssl_adj_timeouts,
+       be_openssl_flush,
+       be_openssl_ctrl,
+};
+
+/* Given a bufferevent, return a pointer to the bufferevent_openssl that
+ * contains it, if any. */
+static inline struct bufferevent_openssl *
+upcast(struct bufferevent *bev)
+{
+       struct bufferevent_openssl *bev_o;
+       if (bev->be_ops != &bufferevent_ops_openssl)
+               return NULL;
+       bev_o = (void*)( ((char*)bev) -
+                        evutil_offsetof(struct bufferevent_openssl, bev.bev));
+       EVUTIL_ASSERT(bev_o->bev.bev.be_ops == &bufferevent_ops_openssl);
+       return bev_o;
+}
+
+static inline void
+put_error(struct bufferevent_openssl *bev_ssl, unsigned long err)
+{
+       if (bev_ssl->n_errors == NUM_ERRORS)
+               return;
+       /* The error type according to openssl is "unsigned long", but
+          openssl never uses more than 32 bits of it.  It _can't_ use more
+          than 32 bits of it, since it needs to report errors on systems
+          where long is only 32 bits.
+        */
+       bev_ssl->errors[bev_ssl->n_errors++] = (ev_uint32_t) err;
+}
+
+/* Have the base communications channel (either the underlying bufferevent or
+ * ev_read and ev_write) start reading.  Take the read-blocked-on-write flag
+ * into account. */
+static int
+start_reading(struct bufferevent_openssl *bev_ssl)
+{
+       if (bev_ssl->underlying) {
+               bufferevent_unsuspend_read(bev_ssl->underlying,
+                   BEV_SUSPEND_FILT_READ);
+               return 0;
+       } else {
+               struct bufferevent *bev = &bev_ssl->bev.bev;
+               int r;
+               r = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
+               if (r == 0 && bev_ssl->read_blocked_on_write)
+                       r = _bufferevent_add_event(&bev->ev_write,
+                           &bev->timeout_write);
+               return r;
+       }
+}
+
+/* Have the base communications channel (either the underlying bufferevent or
+ * ev_read and ev_write) start writing.  Take the write-blocked-on-read flag
+ * into account. */
+static int
+start_writing(struct bufferevent_openssl *bev_ssl)
+{
+       int r = 0;
+       if (bev_ssl->underlying) {
+               ;
+       } else {
+               struct bufferevent *bev = &bev_ssl->bev.bev;
+               r = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
+               if (!r && bev_ssl->write_blocked_on_read)
+                       r = _bufferevent_add_event(&bev->ev_read,
+                           &bev->timeout_read);
+       }
+       return r;
+}
+
+static void
+stop_reading(struct bufferevent_openssl *bev_ssl)
+{
+       if (bev_ssl->write_blocked_on_read)
+               return;
+       if (bev_ssl->underlying) {
+               bufferevent_suspend_read(bev_ssl->underlying,
+                   BEV_SUSPEND_FILT_READ);
+       } else {
+               struct bufferevent *bev = &bev_ssl->bev.bev;
+               event_del(&bev->ev_read);
+       }
+}
+
+static void
+stop_writing(struct bufferevent_openssl *bev_ssl)
+{
+       if (bev_ssl->read_blocked_on_write)
+               return;
+       if (bev_ssl->underlying) {
+               ;
+       } else {
+               struct bufferevent *bev = &bev_ssl->bev.bev;
+               event_del(&bev->ev_write);
+       }
+}
+
+static int
+set_rbow(struct bufferevent_openssl *bev_ssl)
+{
+       if (!bev_ssl->underlying)
+               stop_reading(bev_ssl);
+       bev_ssl->read_blocked_on_write = 1;
+       return start_writing(bev_ssl);
+}
+
+static int
+set_wbor(struct bufferevent_openssl *bev_ssl)
+{
+       if (!bev_ssl->underlying)
+               stop_writing(bev_ssl);
+       bev_ssl->write_blocked_on_read = 1;
+       return start_reading(bev_ssl);
+}
+
+static int
+clear_rbow(struct bufferevent_openssl *bev_ssl)
+{
+       struct bufferevent *bev = &bev_ssl->bev.bev;
+       int r = 0;
+       bev_ssl->read_blocked_on_write = 0;
+       if (!(bev->enabled & EV_WRITE))
+               stop_writing(bev_ssl);
+       if (bev->enabled & EV_READ)
+               r = start_reading(bev_ssl);
+       return r;
+}
+
+
+static int
+clear_wbor(struct bufferevent_openssl *bev_ssl)
+{
+       struct bufferevent *bev = &bev_ssl->bev.bev;
+       int r = 0;
+       bev_ssl->write_blocked_on_read = 0;
+       if (!(bev->enabled & EV_READ))
+               stop_reading(bev_ssl);
+       if (bev->enabled & EV_WRITE)
+               r = start_writing(bev_ssl);
+       return r;
+}
+
+static void
+conn_closed(struct bufferevent_openssl *bev_ssl, int errcode, int ret)
+{
+       int event = BEV_EVENT_ERROR;
+       int dirty_shutdown = 0;
+       unsigned long err;
+
+       switch (errcode) {
+       case SSL_ERROR_ZERO_RETURN:
+               /* Possibly a clean shutdown. */
+               if (SSL_get_shutdown(bev_ssl->ssl) & SSL_RECEIVED_SHUTDOWN)
+                       event = BEV_EVENT_EOF;
+               else
+                       dirty_shutdown = 1;
+               break;
+       case SSL_ERROR_SYSCALL:
+               /* IO error; possibly a dirty shutdown. */
+               if (ret == 0 && ERR_peek_error() == 0)
+                       dirty_shutdown = 1;
+               break;
+       case SSL_ERROR_SSL:
+               /* Protocol error. */
+               break;
+       case SSL_ERROR_WANT_X509_LOOKUP:
+               /* XXXX handle this. */
+               break;
+       case SSL_ERROR_NONE:
+       case SSL_ERROR_WANT_READ:
+       case SSL_ERROR_WANT_WRITE:
+       case SSL_ERROR_WANT_CONNECT:
+       case SSL_ERROR_WANT_ACCEPT:
+       default:
+               /* should be impossible; treat as normal error. */
+               event_warnx("BUG: Unexpected OpenSSL error code %d", errcode);
+               break;
+       }
+
+       while ((err = ERR_get_error())) {
+               put_error(bev_ssl, err);
+       }
+
+       if (dirty_shutdown && bev_ssl->allow_dirty_shutdown)
+               event = BEV_EVENT_EOF;
+
+       stop_reading(bev_ssl);
+       stop_writing(bev_ssl);
+
+       _bufferevent_run_eventcb(&bev_ssl->bev.bev, event);
+}
+
+static void
+init_bio_counts(struct bufferevent_openssl *bev_ssl)
+{
+       bev_ssl->counts.n_written =
+           BIO_number_written(SSL_get_wbio(bev_ssl->ssl));
+       bev_ssl->counts.n_read =
+           BIO_number_read(SSL_get_rbio(bev_ssl->ssl));
+}
+
+static inline void
+decrement_buckets(struct bufferevent_openssl *bev_ssl)
+{
+       unsigned long num_w = BIO_number_written(SSL_get_wbio(bev_ssl->ssl));
+       unsigned long num_r = BIO_number_read(SSL_get_rbio(bev_ssl->ssl));
+       /* These next two subtractions can wrap around. That's okay. */
+       unsigned long w = num_w - bev_ssl->counts.n_written;
+       unsigned long r = num_r - bev_ssl->counts.n_read;
+       if (w)
+               _bufferevent_decrement_write_buckets(&bev_ssl->bev, w);
+       if (r)
+               _bufferevent_decrement_read_buckets(&bev_ssl->bev, r);
+       bev_ssl->counts.n_written = num_w;
+       bev_ssl->counts.n_read = num_r;
+}
+
+/* returns -1 on internal error, 0 on stall, 1 on progress */
+static int
+do_read(struct bufferevent_openssl *bev_ssl, int n_to_read)
+{
+       /* Requires lock */
+       struct bufferevent *bev = &bev_ssl->bev.bev;
+       struct evbuffer *input = bev->input;
+       int r, n, i, n_used = 0, blocked = 0, atmost;
+       struct evbuffer_iovec space[2];
+
+       atmost = _bufferevent_get_read_max(&bev_ssl->bev);
+       if (n_to_read > atmost)
+               n_to_read = atmost;
+
+       n = evbuffer_reserve_space(input, n_to_read, space, 2);
+       if (n < 0)
+               return -1;
+
+       for (i=0; i<n; ++i) {
+               if (bev_ssl->bev.read_suspended)
+                       break;
+               r = SSL_read(bev_ssl->ssl, space[i].iov_base, space[i].iov_len);
+               if (r>0) {
+                       if (bev_ssl->read_blocked_on_write)
+                               if (clear_rbow(bev_ssl) < 0)
+                                       return -1;
+                       ++n_used;
+                       space[i].iov_len = r;
+                       decrement_buckets(bev_ssl);
+               } else {
+                       int err = SSL_get_error(bev_ssl->ssl, r);
+                       print_err(err);
+                       switch (err) {
+                       case SSL_ERROR_WANT_READ:
+                               /* Can't read until underlying has more data. */
+                               if (bev_ssl->read_blocked_on_write)
+                                       if (clear_rbow(bev_ssl) < 0)
+                                               return -1;
+                               break;
+                       case SSL_ERROR_WANT_WRITE:
+                               /* This read operation requires a write, and the
+                                * underlying is full */
+                               if (!bev_ssl->read_blocked_on_write)
+                                       if (set_rbow(bev_ssl) < 0)
+                                               return -1;
+                               break;
+                       default:
+                               conn_closed(bev_ssl, err, r);
+                               break;
+                       }
+                       blocked = 1;
+                       break; /* out of the loop */
+               }
+       }
+
+       if (n_used) {
+               evbuffer_commit_space(input, space, n_used);
+               if (bev_ssl->underlying)
+                       BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+
+               if (evbuffer_get_length(input) >= bev->wm_read.low)
+                       _bufferevent_run_readcb(bev);
+       }
+
+       return blocked ? 0 : 1;
+}
+
+static int
+do_write(struct bufferevent_openssl *bev_ssl, int atmost)
+{
+       int i, r, n, n_written = 0, blocked=0;
+       struct bufferevent *bev = &bev_ssl->bev.bev;
+       struct evbuffer *output = bev->output;
+       struct evbuffer_iovec space[8];
+
+       if (bev_ssl->last_write > 0)
+               atmost = bev_ssl->last_write;
+       else
+               atmost = _bufferevent_get_write_max(&bev_ssl->bev);
+
+       n = evbuffer_peek(output, atmost, NULL, space, 8);
+       if (n < 0)
+               return -1;
+
+       if (n > 8)
+               n = 8;
+       for (i=0; i < n; ++i) {
+               if (bev_ssl->bev.write_suspended)
+                       break;
+
+               /* SSL_write will (reasonably) return 0 if we tell it to
+                  send 0 data.  Skip this case so we don't interpret the
+                  result as an error */
+               if (space[i].iov_len == 0)
+                       continue;
+
+               r = SSL_write(bev_ssl->ssl, space[i].iov_base,
+                   space[i].iov_len);
+               if (r > 0) {
+                       if (bev_ssl->write_blocked_on_read)
+                               if (clear_wbor(bev_ssl) < 0)
+                                       return -1;
+                       n_written += r;
+                       bev_ssl->last_write = -1;
+                       decrement_buckets(bev_ssl);
+               } else {
+                       int err = SSL_get_error(bev_ssl->ssl, r);
+                       print_err(err);
+                       switch (err) {
+                       case SSL_ERROR_WANT_WRITE:
+                               /* Can't read until underlying has more data. */
+                               if (bev_ssl->write_blocked_on_read)
+                                       if (clear_wbor(bev_ssl) < 0)
+                                               return -1;
+                               bev_ssl->last_write = space[i].iov_len;
+                               break;
+                       case SSL_ERROR_WANT_READ:
+                               /* This read operation requires a write, and the
+                                * underlying is full */
+                               if (!bev_ssl->write_blocked_on_read)
+                                       if (set_wbor(bev_ssl) < 0)
+                                               return -1;
+                               bev_ssl->last_write = space[i].iov_len;
+                               break;
+                       default:
+                               conn_closed(bev_ssl, err, r);
+                               bev_ssl->last_write = -1;
+                               break;
+                       }
+                       blocked = 1;
+                       break;
+               }
+       }
+       if (n_written) {
+               evbuffer_drain(output, n_written);
+               if (bev_ssl->underlying)
+                       BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
+
+               if (evbuffer_get_length(output) <= bev->wm_write.low)
+                       _bufferevent_run_writecb(bev);
+       }
+       return blocked ? 0 : 1;
+}
+
+#define WRITE_FRAME 15000
+
+#define READ_DEFAULT 4096
+
+/* Try to figure out how many bytes to read; return 0 if we shouldn't be
+ * reading. */
+static int
+bytes_to_read(struct bufferevent_openssl *bev)
+{
+       struct evbuffer *input = bev->bev.bev.input;
+       struct event_watermark *wm = &bev->bev.bev.wm_read;
+       int result = READ_DEFAULT;
+       ev_ssize_t limit;
+       /* XXX 99% of this is generic code that nearly all bufferevents will
+        * want. */
+
+       if (bev->write_blocked_on_read) {
+               return 0;
+       }
+
+       if (! (bev->bev.bev.enabled & EV_READ)) {
+               return 0;
+       }
+
+       if (bev->bev.read_suspended) {
+               return 0;
+       }
+
+       if (wm->high) {
+               if (evbuffer_get_length(input) >= wm->high) {
+                       return 0;
+               }
+
+               result = wm->high - evbuffer_get_length(input);
+       } else {
+               result = READ_DEFAULT;
+       }
+
+       /* Respect the rate limit */
+       limit = _bufferevent_get_read_max(&bev->bev);
+       if (result > limit) {
+               result = limit;
+       }
+
+       return result;
+}
+
+
+/* Things look readable.  If write is blocked on read, write till it isn't.
+ * Read from the underlying buffer until we block or we hit our high-water
+ * mark.
+ */
+static void
+consider_reading(struct bufferevent_openssl *bev_ssl)
+{
+       int r;
+       int n_to_read;
+
+       while (bev_ssl->write_blocked_on_read) {
+               r = do_write(bev_ssl, WRITE_FRAME);
+               if (r <= 0)
+                       break;
+       }
+       if (bev_ssl->write_blocked_on_read)
+               return;
+
+       n_to_read = bytes_to_read(bev_ssl);
+
+       while (n_to_read) {
+               if (do_read(bev_ssl, n_to_read) <= 0)
+                       break;
+
+               /* Read all pending data.  This won't hit the network
+                * again, and will (most importantly) put us in a state
+                * where we don't need to read anything else until the
+                * socket is readable again.  It'll potentially make us
+                * overrun our read high-watermark (somewhat
+                * regrettable).  The damage to the rate-limit has
+                * already been done, since OpenSSL went and read a
+                * whole SSL record anyway. */
+               n_to_read = SSL_pending(bev_ssl->ssl);
+
+               /* XXX This if statement is actually a bad bug, added to avoid
+                * XXX a worse bug.
+                *
+                * The bad bug: It can potentially cause resource unfairness
+                * by reading too much data from the underlying bufferevent;
+                * it can potentially cause read looping if the underlying
+                * bufferevent is a bufferevent_pair and deferred callbacks
+                * aren't used.
+                *
+                * The worse bug: If we didn't do this, then we would
+                * potentially not read any more from bev_ssl->underlying
+                * until more data arrived there, which could lead to us
+                * waiting forever.
+                */
+               if (!n_to_read && bev_ssl->underlying)
+                       n_to_read = bytes_to_read(bev_ssl);
+       }
+
+       if (!bev_ssl->underlying) {
+               /* Should be redundant, but let's avoid busy-looping */
+               if (bev_ssl->bev.read_suspended ||
+                   !(bev_ssl->bev.bev.enabled & EV_READ)) {
+                       event_del(&bev_ssl->bev.bev.ev_read);
+               }
+       }
+}
+
+static void
+consider_writing(struct bufferevent_openssl *bev_ssl)
+{
+       int r;
+       struct evbuffer *output = bev_ssl->bev.bev.output;
+       struct evbuffer *target = NULL;
+       struct event_watermark *wm = NULL;
+
+       while (bev_ssl->read_blocked_on_write) {
+               r = do_read(bev_ssl, 1024); /* XXXX 1024 is a hack */
+               if (r <= 0)
+                       break;
+       }
+       if (bev_ssl->read_blocked_on_write)
+               return;
+       if (bev_ssl->underlying) {
+               target = bev_ssl->underlying->output;
+               wm = &bev_ssl->underlying->wm_write;
+       }
+       while ((bev_ssl->bev.bev.enabled & EV_WRITE) &&
+           (! bev_ssl->bev.write_suspended) &&
+           evbuffer_get_length(output) &&
+           (!target || (! wm->high || evbuffer_get_length(target) < wm->high))) {
+               int n_to_write;
+               if (wm && wm->high)
+                       n_to_write = wm->high - evbuffer_get_length(target);
+               else
+                       n_to_write = WRITE_FRAME;
+               r = do_write(bev_ssl, n_to_write);
+               if (r <= 0)
+                       break;
+       }
+
+       if (!bev_ssl->underlying) {
+               if (evbuffer_get_length(output) == 0) {
+                       event_del(&bev_ssl->bev.bev.ev_write);
+               } else if (bev_ssl->bev.write_suspended ||
+                   !(bev_ssl->bev.bev.enabled & EV_WRITE)) {
+                       /* Should be redundant, but let's avoid busy-looping */
+                       event_del(&bev_ssl->bev.bev.ev_write);
+               }
+       }
+}
+
+static void
+be_openssl_readcb(struct bufferevent *bev_base, void *ctx)
+{
+       struct bufferevent_openssl *bev_ssl = ctx;
+       consider_reading(bev_ssl);
+}
+
+static void
+be_openssl_writecb(struct bufferevent *bev_base, void *ctx)
+{
+       struct bufferevent_openssl *bev_ssl = ctx;
+       consider_writing(bev_ssl);
+}
+
+static void
+be_openssl_eventcb(struct bufferevent *bev_base, short what, void *ctx)
+{
+       struct bufferevent_openssl *bev_ssl = ctx;
+       int event = 0;
+
+       if (what & BEV_EVENT_EOF) {
+               if (bev_ssl->allow_dirty_shutdown)
+                       event = BEV_EVENT_EOF;
+               else
+                       event = BEV_EVENT_ERROR;
+       } else if (what & BEV_EVENT_TIMEOUT) {
+               /* We sure didn't set this.  Propagate it to the user. */
+               event = what;
+       } else if (what & BEV_EVENT_ERROR) {
+               /* An error occurred on the connection.  Propagate it to the user. */
+               event = what;
+       } else if (what & BEV_EVENT_CONNECTED) {
+               /* Ignore it.  We're saying SSL_connect() already, which will
+                  eat it. */
+       }
+       if (event)
+               _bufferevent_run_eventcb(&bev_ssl->bev.bev, event);
+}
+
+static void
+be_openssl_readeventcb(evutil_socket_t fd, short what, void *ptr)
+{
+       struct bufferevent_openssl *bev_ssl = ptr;
+       _bufferevent_incref_and_lock(&bev_ssl->bev.bev);
+       if (what & EV_TIMEOUT) {
+               _bufferevent_run_eventcb(&bev_ssl->bev.bev,
+                   BEV_EVENT_TIMEOUT|BEV_EVENT_READING);
+       } else
+               consider_reading(bev_ssl);
+       _bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
+}
+
+static void
+be_openssl_writeeventcb(evutil_socket_t fd, short what, void *ptr)
+{
+       struct bufferevent_openssl *bev_ssl = ptr;
+       _bufferevent_incref_and_lock(&bev_ssl->bev.bev);
+       if (what & EV_TIMEOUT) {
+               _bufferevent_run_eventcb(&bev_ssl->bev.bev,
+                   BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING);
+       }
+       consider_writing(bev_ssl);
+       _bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
+}
+
+static int
+set_open_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
+{
+       if (bev_ssl->underlying) {
+               bufferevent_setcb(bev_ssl->underlying,
+                   be_openssl_readcb, be_openssl_writecb, be_openssl_eventcb,
+                   bev_ssl);
+               return 0;
+       } else {
+               struct bufferevent *bev = &bev_ssl->bev.bev;
+               int rpending=0, wpending=0, r1=0, r2=0;
+               if (fd < 0 && bev_ssl->fd_is_set)
+                       fd = event_get_fd(&bev->ev_read);
+               if (bev_ssl->fd_is_set) {
+                       rpending = event_pending(&bev->ev_read, EV_READ, NULL);
+                       wpending = event_pending(&bev->ev_write, EV_WRITE, NULL);
+                       event_del(&bev->ev_read);
+                       event_del(&bev->ev_write);
+               }
+               event_assign(&bev->ev_read, bev->ev_base, fd,
+                   EV_READ|EV_PERSIST, be_openssl_readeventcb, bev_ssl);
+               event_assign(&bev->ev_write, bev->ev_base, fd,
+                   EV_WRITE|EV_PERSIST, be_openssl_writeeventcb, bev_ssl);
+               if (rpending)
+                       r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
+               if (wpending)
+                       r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
+               if (fd >= 0) {
+                       bev_ssl->fd_is_set = 1;
+               }
+               return (r1<0 || r2<0) ? -1 : 0;
+       }
+}
+
+static int
+do_handshake(struct bufferevent_openssl *bev_ssl)
+{
+       int r;
+
+       switch (bev_ssl->state) {
+       default:
+       case BUFFEREVENT_SSL_OPEN:
+               EVUTIL_ASSERT(0);
+               return -1;
+       case BUFFEREVENT_SSL_CONNECTING:
+       case BUFFEREVENT_SSL_ACCEPTING:
+               r = SSL_do_handshake(bev_ssl->ssl);
+               break;
+       }
+       decrement_buckets(bev_ssl);
+
+       if (r==1) {
+               /* We're done! */
+               bev_ssl->state = BUFFEREVENT_SSL_OPEN;
+               set_open_callbacks(bev_ssl, -1); /* XXXX handle failure */
+               /* Call do_read and do_write as needed */
+               bufferevent_enable(&bev_ssl->bev.bev, bev_ssl->bev.bev.enabled);
+               _bufferevent_run_eventcb(&bev_ssl->bev.bev,
+                   BEV_EVENT_CONNECTED);
+               return 1;
+       } else {
+               int err = SSL_get_error(bev_ssl->ssl, r);
+               print_err(err);
+               switch (err) {
+               case SSL_ERROR_WANT_WRITE:
+                       if (!bev_ssl->underlying) {
+                               stop_reading(bev_ssl);
+                               return start_writing(bev_ssl);
+                       }
+                       return 0;
+               case SSL_ERROR_WANT_READ:
+                       if (!bev_ssl->underlying) {
+                               stop_writing(bev_ssl);
+                               return start_reading(bev_ssl);
+                       }
+                       return 0;
+               default:
+                       conn_closed(bev_ssl, err, r);
+                       return -1;
+               }
+       }
+}
+
+static void
+be_openssl_handshakecb(struct bufferevent *bev_base, void *ctx)
+{
+       struct bufferevent_openssl *bev_ssl = ctx;
+       do_handshake(bev_ssl);/* XXX handle failure */
+}
+
+static void
+be_openssl_handshakeeventcb(evutil_socket_t fd, short what, void *ptr)
+{
+       struct bufferevent_openssl *bev_ssl = ptr;
+
+       _bufferevent_incref_and_lock(&bev_ssl->bev.bev);
+       if (what & EV_TIMEOUT) {
+               _bufferevent_run_eventcb(&bev_ssl->bev.bev, BEV_EVENT_TIMEOUT);
+       } else
+               do_handshake(bev_ssl);/* XXX handle failure */
+       _bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
+}
+
+static int
+set_handshake_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
+{
+       if (bev_ssl->underlying) {
+               bufferevent_setcb(bev_ssl->underlying,
+                   be_openssl_handshakecb, be_openssl_handshakecb,
+                   be_openssl_eventcb,
+                   bev_ssl);
+               return do_handshake(bev_ssl);
+       } else {
+               struct bufferevent *bev = &bev_ssl->bev.bev;
+               int r1=0, r2=0;
+               if (fd < 0 && bev_ssl->fd_is_set)
+                       fd = event_get_fd(&bev->ev_read);
+               if (bev_ssl->fd_is_set) {
+                       event_del(&bev->ev_read);
+                       event_del(&bev->ev_write);
+               }
+               event_assign(&bev->ev_read, bev->ev_base, fd,
+                   EV_READ|EV_PERSIST, be_openssl_handshakeeventcb, bev_ssl);
+               event_assign(&bev->ev_write, bev->ev_base, fd,
+                   EV_WRITE|EV_PERSIST, be_openssl_handshakeeventcb, bev_ssl);
+               if (fd >= 0) {
+                       r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
+                       r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
+                       bev_ssl->fd_is_set = 1;
+               }
+               return (r1<0 || r2<0) ? -1 : 0;
+       }
+}
+
+int
+bufferevent_ssl_renegotiate(struct bufferevent *bev)
+{
+       struct bufferevent_openssl *bev_ssl = upcast(bev);
+       if (!bev_ssl)
+               return -1;
+       if (SSL_renegotiate(bev_ssl->ssl) < 0)
+               return -1;
+       bev_ssl->state = BUFFEREVENT_SSL_CONNECTING;
+       if (set_handshake_callbacks(bev_ssl, -1) < 0)
+               return -1;
+       if (!bev_ssl->underlying)
+               return do_handshake(bev_ssl);
+       return 0;
+}
+
+static void
+be_openssl_outbuf_cb(struct evbuffer *buf,
+    const struct evbuffer_cb_info *cbinfo, void *arg)
+{
+       struct bufferevent_openssl *bev_ssl = arg;
+       int r = 0;
+       /* XXX need to hold a reference here. */
+
+       if (cbinfo->n_added && bev_ssl->state == BUFFEREVENT_SSL_OPEN) {
+               if (cbinfo->orig_size == 0)
+                       r = _bufferevent_add_event(&bev_ssl->bev.bev.ev_write,
+                           &bev_ssl->bev.bev.timeout_write);
+               consider_writing(bev_ssl);
+       }
+       /* XXX Handle r < 0 */
+        (void)r;
+}
+
+
+static int
+be_openssl_enable(struct bufferevent *bev, short events)
+{
+       struct bufferevent_openssl *bev_ssl = upcast(bev);
+       int r1 = 0, r2 = 0;
+
+       if (bev_ssl->state != BUFFEREVENT_SSL_OPEN)
+               return 0;
+
+       if (events & EV_READ)
+               r1 = start_reading(bev_ssl);
+       if (events & EV_WRITE)
+               r2 = start_writing(bev_ssl);
+
+       if (bev_ssl->underlying) {
+               if (events & EV_READ)
+                       BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+               if (events & EV_WRITE)
+                       BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
+
+               if (events & EV_READ)
+                       consider_reading(bev_ssl);
+               if (events & EV_WRITE)
+                       consider_writing(bev_ssl);
+       }
+       return (r1 < 0 || r2 < 0) ? -1 : 0;
+}
+
+static int
+be_openssl_disable(struct bufferevent *bev, short events)
+{
+       struct bufferevent_openssl *bev_ssl = upcast(bev);
+       if (bev_ssl->state != BUFFEREVENT_SSL_OPEN)
+               return 0;
+
+       if (events & EV_READ)
+               stop_reading(bev_ssl);
+       if (events & EV_WRITE)
+               stop_writing(bev_ssl);
+
+       if (bev_ssl->underlying) {
+               if (events & EV_READ)
+                       BEV_DEL_GENERIC_READ_TIMEOUT(bev);
+               if (events & EV_WRITE)
+                       BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
+       }
+       return 0;
+}
+
+static void
+be_openssl_destruct(struct bufferevent *bev)
+{
+       struct bufferevent_openssl *bev_ssl = upcast(bev);
+
+       if (bev_ssl->underlying) {
+               _bufferevent_del_generic_timeout_cbs(bev);
+       } else {
+               event_del(&bev->ev_read);
+               event_del(&bev->ev_write);
+       }
+
+       if (bev_ssl->bev.options & BEV_OPT_CLOSE_ON_FREE) {
+               if (bev_ssl->underlying) {
+                       if (BEV_UPCAST(bev_ssl->underlying)->refcnt < 2) {
+                               event_warnx("BEV_OPT_CLOSE_ON_FREE set on an "
+                                   "bufferevent with too few references");
+                       } else {
+                               bufferevent_free(bev_ssl->underlying);
+                               bev_ssl->underlying = NULL;
+                       }
+               } else {
+                       evutil_socket_t fd = -1;
+                       BIO *bio = SSL_get_wbio(bev_ssl->ssl);
+                       if (bio)
+                               fd = BIO_get_fd(bio, NULL);
+                       if (fd >= 0)
+                               evutil_closesocket(fd);
+               }
+               SSL_free(bev_ssl->ssl);
+       } else {
+               if (bev_ssl->underlying) {
+                       if (bev_ssl->underlying->errorcb == be_openssl_eventcb)
+                               bufferevent_setcb(bev_ssl->underlying,
+                                   NULL,NULL,NULL,NULL);
+                       bufferevent_unsuspend_read(bev_ssl->underlying,
+                           BEV_SUSPEND_FILT_READ);
+               }
+       }
+}
+
+static int
+be_openssl_adj_timeouts(struct bufferevent *bev)
+{
+       struct bufferevent_openssl *bev_ssl = upcast(bev);
+
+       if (bev_ssl->underlying)
+               return _bufferevent_generic_adj_timeouts(bev);
+       else {
+               int r1=0, r2=0;
+               if (event_pending(&bev->ev_read, EV_READ, NULL))
+                       r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
+               if (event_pending(&bev->ev_write, EV_WRITE, NULL))
+                       r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
+               return (r1<0 || r2<0) ? -1 : 0;
+       }
+}
+
+static int
+be_openssl_flush(struct bufferevent *bufev,
+    short iotype, enum bufferevent_flush_mode mode)
+{
+       /* XXXX Implement this. */
+       return 0;
+}
+
+static int
+be_openssl_ctrl(struct bufferevent *bev,
+    enum bufferevent_ctrl_op op, union bufferevent_ctrl_data *data)
+{
+       struct bufferevent_openssl *bev_ssl = upcast(bev);
+       switch (op) {
+       case BEV_CTRL_SET_FD:
+               if (bev_ssl->underlying)
+                       return -1;
+               {
+                       BIO *bio;
+                       bio = BIO_new_socket(data->fd, 0);
+                       SSL_set_bio(bev_ssl->ssl, bio, bio);
+                       bev_ssl->fd_is_set = 1;
+               }
+               if (bev_ssl->state == BUFFEREVENT_SSL_OPEN)
+                       return set_open_callbacks(bev_ssl, data->fd);
+               else {
+                       return set_handshake_callbacks(bev_ssl, data->fd);
+               }
+       case BEV_CTRL_GET_FD:
+               if (bev_ssl->underlying)
+                       return -1;
+               if (!bev_ssl->fd_is_set)
+                       return -1;
+               data->fd = event_get_fd(&bev->ev_read);
+               return 0;
+       case BEV_CTRL_GET_UNDERLYING:
+               if (!bev_ssl->underlying)
+                       return -1;
+               data->ptr = bev_ssl->underlying;
+               return 0;
+       case BEV_CTRL_CANCEL_ALL:
+       default:
+               return -1;
+       }
+}
+
+SSL *
+bufferevent_openssl_get_ssl(struct bufferevent *bufev)
+{
+       struct bufferevent_openssl *bev_ssl = upcast(bufev);
+       if (!bev_ssl)
+               return NULL;
+       return bev_ssl->ssl;
+}
+
+static struct bufferevent *
+bufferevent_openssl_new_impl(struct event_base *base,
+    struct bufferevent *underlying,
+    evutil_socket_t fd,
+    SSL *ssl,
+    enum bufferevent_ssl_state state,
+    int options)
+{
+       struct bufferevent_openssl *bev_ssl = NULL;
+       struct bufferevent_private *bev_p = NULL;
+       int tmp_options = options & ~BEV_OPT_THREADSAFE;
+
+       if (underlying != NULL && fd >= 0)
+               return NULL; /* Only one can be set. */
+
+       if (!(bev_ssl = mm_calloc(1, sizeof(struct bufferevent_openssl))))
+               goto err;
+
+       bev_p = &bev_ssl->bev;
+
+       if (bufferevent_init_common(bev_p, base,
+               &bufferevent_ops_openssl, tmp_options) < 0)
+               goto err;
+
+       /* Don't explode if we decide to realloc a chunk we're writing from in
+        * the output buffer. */
+       SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
+
+       bev_ssl->underlying = underlying;
+       bev_ssl->ssl = ssl;
+
+       bev_ssl->outbuf_cb = evbuffer_add_cb(bev_p->bev.output,
+           be_openssl_outbuf_cb, bev_ssl);
+
+       if (options & BEV_OPT_THREADSAFE)
+               bufferevent_enable_locking(&bev_ssl->bev.bev, NULL);
+
+       if (underlying) {
+               _bufferevent_init_generic_timeout_cbs(&bev_ssl->bev.bev);
+               bufferevent_incref(underlying);
+       }
+
+       bev_ssl->state = state;
+       bev_ssl->last_write = -1;
+
+       init_bio_counts(bev_ssl);
+
+       switch (state) {
+       case BUFFEREVENT_SSL_ACCEPTING:
+               SSL_set_accept_state(bev_ssl->ssl);
+               if (set_handshake_callbacks(bev_ssl, fd) < 0)
+                       goto err;
+               break;
+       case BUFFEREVENT_SSL_CONNECTING:
+               SSL_set_connect_state(bev_ssl->ssl);
+               if (set_handshake_callbacks(bev_ssl, fd) < 0)
+                       goto err;
+               break;
+       case BUFFEREVENT_SSL_OPEN:
+               if (set_open_callbacks(bev_ssl, fd) < 0)
+                       goto err;
+               break;
+       default:
+               goto err;
+       }
+
+       if (underlying) {
+               bufferevent_setwatermark(underlying, EV_READ, 0, 0);
+               bufferevent_enable(underlying, EV_READ|EV_WRITE);
+               if (state == BUFFEREVENT_SSL_OPEN)
+                       bufferevent_suspend_read(underlying,
+                           BEV_SUSPEND_FILT_READ);
+       } else {
+               bev_ssl->bev.bev.enabled = EV_READ|EV_WRITE;
+               if (bev_ssl->fd_is_set) {
+                       if (state != BUFFEREVENT_SSL_OPEN)
+                               if (event_add(&bev_ssl->bev.bev.ev_read, NULL) < 0)
+                                       goto err;
+                       if (event_add(&bev_ssl->bev.bev.ev_write, NULL) < 0)
+                               goto err;
+               }
+       }
+
+       return &bev_ssl->bev.bev;
+err:
+       if (bev_ssl)
+               bufferevent_free(&bev_ssl->bev.bev);
+       return NULL;
+}
+
+struct bufferevent *
+bufferevent_openssl_filter_new(struct event_base *base,
+    struct bufferevent *underlying,
+    SSL *ssl,
+    enum bufferevent_ssl_state state,
+    int options)
+{
+       /* We don't tell the BIO to close the bufferevent; we do it ourselves
+        * on be_openssl_destruct */
+       int close_flag = 0; /* options & BEV_OPT_CLOSE_ON_FREE; */
+       BIO *bio;
+       if (!underlying)
+               return NULL;
+       if (!(bio = BIO_new_bufferevent(underlying, close_flag)))
+               return NULL;
+
+       SSL_set_bio(ssl, bio, bio);
+
+       return bufferevent_openssl_new_impl(
+               base, underlying, -1, ssl, state, options);
+}
+
+struct bufferevent *
+bufferevent_openssl_socket_new(struct event_base *base,
+    evutil_socket_t fd,
+    SSL *ssl,
+    enum bufferevent_ssl_state state,
+    int options)
+{
+       /* Does the SSL already have an fd? */
+       BIO *bio = SSL_get_wbio(ssl);
+       long have_fd = -1;
+
+       if (bio)
+               have_fd = BIO_get_fd(bio, NULL);
+
+       if (have_fd >= 0) {
+               /* The SSL is already configured with an fd. */
+               if (fd < 0) {
+                       /* We should learn the fd from the SSL. */
+                       fd = (evutil_socket_t) have_fd;
+               } else if (have_fd == (long)fd) {
+                       /* We already know the fd from the SSL; do nothing */
+               } else {
+                       /* We specified an fd different from that of the SSL.
+                          This is probably an error on our part.  Fail. */
+                       return NULL;
+               }
+               (void) BIO_set_close(bio, 0);
+       } else {
+               /* The SSL isn't configured with a BIO with an fd. */
+               if (fd >= 0) {
+                       /* ... and we have an fd we want to use. */
+                       bio = BIO_new_socket(fd, 0);
+                       SSL_set_bio(ssl, bio, bio);
+               } else {
+                       /* Leave the fd unset. */
+               }
+       }
+
+       return bufferevent_openssl_new_impl(
+               base, NULL, fd, ssl, state, options);
+}
+
+unsigned long
+bufferevent_get_openssl_error(struct bufferevent *bev)
+{
+       unsigned long err = 0;
+       struct bufferevent_openssl *bev_ssl;
+       BEV_LOCK(bev);
+       bev_ssl = upcast(bev);
+       if (bev_ssl && bev_ssl->n_errors) {
+               err = bev_ssl->errors[--bev_ssl->n_errors];
+       }
+       BEV_UNLOCK(bev);
+       return err;
+}
diff --git a/libevent/bufferevent_pair.c b/libevent/bufferevent_pair.c
new file mode 100644 (file)
index 0000000..6ec5cac
--- /dev/null
@@ -0,0 +1,333 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include "event2/util.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/event.h"
+#include "defer-internal.h"
+#include "bufferevent-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+
+struct bufferevent_pair {
+       struct bufferevent_private bev;
+       struct bufferevent_pair *partner;
+};
+
+
+/* Given a bufferevent that's really a bev part of a bufferevent_pair,
+ * return that bufferevent_filtered. Returns NULL otherwise.*/
+static inline struct bufferevent_pair *
+upcast(struct bufferevent *bev)
+{
+       struct bufferevent_pair *bev_p;
+       if (bev->be_ops != &bufferevent_ops_pair)
+               return NULL;
+       bev_p = EVUTIL_UPCAST(bev, struct bufferevent_pair, bev.bev);
+       EVUTIL_ASSERT(bev_p->bev.bev.be_ops == &bufferevent_ops_pair);
+       return bev_p;
+}
+
+#define downcast(bev_pair) (&(bev_pair)->bev.bev)
+
+static inline void
+incref_and_lock(struct bufferevent *b)
+{
+       struct bufferevent_pair *bevp;
+       _bufferevent_incref_and_lock(b);
+       bevp = upcast(b);
+       if (bevp->partner)
+               _bufferevent_incref_and_lock(downcast(bevp->partner));
+}
+
+static inline void
+decref_and_unlock(struct bufferevent *b)
+{
+       struct bufferevent_pair *bevp = upcast(b);
+       if (bevp->partner)
+               _bufferevent_decref_and_unlock(downcast(bevp->partner));
+       _bufferevent_decref_and_unlock(b);
+}
+
+/* XXX Handle close */
+
+static void be_pair_outbuf_cb(struct evbuffer *,
+    const struct evbuffer_cb_info *, void *);
+
+static struct bufferevent_pair *
+bufferevent_pair_elt_new(struct event_base *base,
+    int options)
+{
+       struct bufferevent_pair *bufev;
+       if (! (bufev = mm_calloc(1, sizeof(struct bufferevent_pair))))
+               return NULL;
+       if (bufferevent_init_common(&bufev->bev, base, &bufferevent_ops_pair,
+               options)) {
+               mm_free(bufev);
+               return NULL;
+       }
+       if (!evbuffer_add_cb(bufev->bev.bev.output, be_pair_outbuf_cb, bufev)) {
+               bufferevent_free(downcast(bufev));
+               return NULL;
+       }
+
+       _bufferevent_init_generic_timeout_cbs(&bufev->bev.bev);
+
+       return bufev;
+}
+
+int
+bufferevent_pair_new(struct event_base *base, int options,
+    struct bufferevent *pair[2])
+{
+       struct bufferevent_pair *bufev1 = NULL, *bufev2 = NULL;
+       int tmp_options;
+
+       options |= BEV_OPT_DEFER_CALLBACKS;
+       tmp_options = options & ~BEV_OPT_THREADSAFE;
+
+       bufev1 = bufferevent_pair_elt_new(base, options);
+       if (!bufev1)
+               return -1;
+       bufev2 = bufferevent_pair_elt_new(base, tmp_options);
+       if (!bufev2) {
+               bufferevent_free(downcast(bufev1));
+               return -1;
+       }
+
+       if (options & BEV_OPT_THREADSAFE) {
+               /*XXXX check return */
+               bufferevent_enable_locking(downcast(bufev2), bufev1->bev.lock);
+       }
+
+       bufev1->partner = bufev2;
+       bufev2->partner = bufev1;
+
+       evbuffer_freeze(downcast(bufev1)->input, 0);
+       evbuffer_freeze(downcast(bufev1)->output, 1);
+       evbuffer_freeze(downcast(bufev2)->input, 0);
+       evbuffer_freeze(downcast(bufev2)->output, 1);
+
+       pair[0] = downcast(bufev1);
+       pair[1] = downcast(bufev2);
+
+       return 0;
+}
+
+static void
+be_pair_transfer(struct bufferevent *src, struct bufferevent *dst,
+    int ignore_wm)
+{
+       size_t src_size, dst_size;
+       size_t n;
+
+       evbuffer_unfreeze(src->output, 1);
+       evbuffer_unfreeze(dst->input, 0);
+
+       if (dst->wm_read.high) {
+               dst_size = evbuffer_get_length(dst->input);
+               if (dst_size < dst->wm_read.high) {
+                       n = dst->wm_read.high - dst_size;
+                       evbuffer_remove_buffer(src->output, dst->input, n);
+               } else {
+                       if (!ignore_wm)
+                               goto done;
+                       n = evbuffer_get_length(src->output);
+                       evbuffer_add_buffer(dst->input, src->output);
+               }
+       } else {
+               n = evbuffer_get_length(src->output);
+               evbuffer_add_buffer(dst->input, src->output);
+       }
+
+       if (n) {
+               BEV_RESET_GENERIC_READ_TIMEOUT(dst);
+
+               if (evbuffer_get_length(dst->output))
+                       BEV_RESET_GENERIC_WRITE_TIMEOUT(dst);
+               else
+                       BEV_DEL_GENERIC_WRITE_TIMEOUT(dst);
+       }
+
+       src_size = evbuffer_get_length(src->output);
+       dst_size = evbuffer_get_length(dst->input);
+
+       if (dst_size >= dst->wm_read.low) {
+               _bufferevent_run_readcb(dst);
+       }
+       if (src_size <= src->wm_write.low) {
+               _bufferevent_run_writecb(src);
+       }
+done:
+       evbuffer_freeze(src->output, 1);
+       evbuffer_freeze(dst->input, 0);
+}
+
+static inline int
+be_pair_wants_to_talk(struct bufferevent_pair *src,
+    struct bufferevent_pair *dst)
+{
+       return (downcast(src)->enabled & EV_WRITE) &&
+           (downcast(dst)->enabled & EV_READ) &&
+           !dst->bev.read_suspended &&
+           evbuffer_get_length(downcast(src)->output);
+}
+
+static void
+be_pair_outbuf_cb(struct evbuffer *outbuf,
+    const struct evbuffer_cb_info *info, void *arg)
+{
+       struct bufferevent_pair *bev_pair = arg;
+       struct bufferevent_pair *partner = bev_pair->partner;
+
+       incref_and_lock(downcast(bev_pair));
+
+       if (info->n_added > info->n_deleted && partner) {
+               /* We got more data.  If the other side's reading, then
+                  hand it over. */
+               if (be_pair_wants_to_talk(bev_pair, partner)) {
+                       be_pair_transfer(downcast(bev_pair), downcast(partner), 0);
+               }
+       }
+
+       decref_and_unlock(downcast(bev_pair));
+}
+
+static int
+be_pair_enable(struct bufferevent *bufev, short events)
+{
+       struct bufferevent_pair *bev_p = upcast(bufev);
+       struct bufferevent_pair *partner = bev_p->partner;
+
+       incref_and_lock(bufev);
+
+       if (events & EV_READ) {
+               BEV_RESET_GENERIC_READ_TIMEOUT(bufev);
+       }
+       if ((events & EV_WRITE) && evbuffer_get_length(bufev->output))
+               BEV_RESET_GENERIC_WRITE_TIMEOUT(bufev);
+
+       /* We're starting to read! Does the other side have anything to write?*/
+       if ((events & EV_READ) && partner &&
+           be_pair_wants_to_talk(partner, bev_p)) {
+               be_pair_transfer(downcast(partner), bufev, 0);
+       }
+       /* We're starting to write! Does the other side want to read? */
+       if ((events & EV_WRITE) && partner &&
+           be_pair_wants_to_talk(bev_p, partner)) {
+               be_pair_transfer(bufev, downcast(partner), 0);
+       }
+       decref_and_unlock(bufev);
+       return 0;
+}
+
+static int
+be_pair_disable(struct bufferevent *bev, short events)
+{
+       if (events & EV_READ) {
+               BEV_DEL_GENERIC_READ_TIMEOUT(bev);
+       }
+       if (events & EV_WRITE)
+               BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
+       return 0;
+}
+
+static void
+be_pair_destruct(struct bufferevent *bev)
+{
+       struct bufferevent_pair *bev_p = upcast(bev);
+
+       if (bev_p->partner) {
+               bev_p->partner->partner = NULL;
+               bev_p->partner = NULL;
+       }
+
+       _bufferevent_del_generic_timeout_cbs(bev);
+}
+
+static int
+be_pair_flush(struct bufferevent *bev, short iotype,
+    enum bufferevent_flush_mode mode)
+{
+       struct bufferevent_pair *bev_p = upcast(bev);
+       struct bufferevent *partner;
+       incref_and_lock(bev);
+       if (!bev_p->partner)
+               return -1;
+
+       partner = downcast(bev_p->partner);
+
+       if (mode == BEV_NORMAL)
+               return 0;
+
+       if ((iotype & EV_READ) != 0)
+               be_pair_transfer(partner, bev, 1);
+
+       if ((iotype & EV_WRITE) != 0)
+               be_pair_transfer(bev, partner, 1);
+
+       if (mode == BEV_FINISHED) {
+               _bufferevent_run_eventcb(partner, iotype|BEV_EVENT_EOF);
+       }
+       decref_and_unlock(bev);
+       return 0;
+}
+
+struct bufferevent *
+bufferevent_pair_get_partner(struct bufferevent *bev)
+{
+       struct bufferevent_pair *bev_p;
+       struct bufferevent *partner;
+       bev_p = upcast(bev);
+       if (! bev_p)
+               return NULL;
+
+       incref_and_lock(bev);
+       partner = downcast(bev_p->partner);
+       decref_and_unlock(bev);
+       return partner;
+}
+
+const struct bufferevent_ops bufferevent_ops_pair = {
+       "pair_elt",
+       evutil_offsetof(struct bufferevent_pair, bev.bev),
+       be_pair_enable,
+       be_pair_disable,
+       be_pair_destruct,
+       _bufferevent_generic_adj_timeouts,
+       be_pair_flush,
+       NULL, /* ctrl */
+};
diff --git a/libevent/bufferevent_ratelim.c b/libevent/bufferevent_ratelim.c
new file mode 100644 (file)
index 0000000..7965390
--- /dev/null
@@ -0,0 +1,1011 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+#include <limits.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/util.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/buffer.h"
+
+#include "ratelim-internal.h"
+
+#include "bufferevent-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+#include "event-internal.h"
+
+int
+ev_token_bucket_init(struct ev_token_bucket *bucket,
+    const struct ev_token_bucket_cfg *cfg,
+    ev_uint32_t current_tick,
+    int reinitialize)
+{
+       if (reinitialize) {
+               /* on reinitialization, we only clip downwards, since we've
+                  already used who-knows-how-much bandwidth this tick.  We
+                  leave "last_updated" as it is; the next update will add the
+                  appropriate amount of bandwidth to the bucket.
+               */
+               if (bucket->read_limit > (ev_int64_t) cfg->read_maximum)
+                       bucket->read_limit = cfg->read_maximum;
+               if (bucket->write_limit > (ev_int64_t) cfg->write_maximum)
+                       bucket->write_limit = cfg->write_maximum;
+       } else {
+               bucket->read_limit = cfg->read_rate;
+               bucket->write_limit = cfg->write_rate;
+               bucket->last_updated = current_tick;
+       }
+       return 0;
+}
+
+int
+ev_token_bucket_update(struct ev_token_bucket *bucket,
+    const struct ev_token_bucket_cfg *cfg,
+    ev_uint32_t current_tick)
+{
+       /* It's okay if the tick number overflows, since we'll just
+        * wrap around when we do the unsigned substraction. */
+       unsigned n_ticks = current_tick - bucket->last_updated;
+
+       /* Make sure some ticks actually happened, and that time didn't
+        * roll back. */
+       if (n_ticks == 0 || n_ticks > INT_MAX)
+               return 0;
+
+       /* Naively, we would say
+               bucket->limit += n_ticks * cfg->rate;
+
+               if (bucket->limit > cfg->maximum)
+                       bucket->limit = cfg->maximum;
+
+          But we're worried about overflow, so we do it like this:
+       */
+
+       if ((cfg->read_maximum - bucket->read_limit) / n_ticks < cfg->read_rate)
+               bucket->read_limit = cfg->read_maximum;
+       else
+               bucket->read_limit += n_ticks * cfg->read_rate;
+
+
+       if ((cfg->write_maximum - bucket->write_limit) / n_ticks < cfg->write_rate)
+               bucket->write_limit = cfg->write_maximum;
+       else
+               bucket->write_limit += n_ticks * cfg->write_rate;
+
+
+       bucket->last_updated = current_tick;
+
+       return 1;
+}
+
+static inline void
+bufferevent_update_buckets(struct bufferevent_private *bev)
+{
+       /* Must hold lock on bev. */
+       struct timeval now;
+       unsigned tick;
+       event_base_gettimeofday_cached(bev->bev.ev_base, &now);
+       tick = ev_token_bucket_get_tick(&now, bev->rate_limiting->cfg);
+       if (tick != bev->rate_limiting->limit.last_updated)
+               ev_token_bucket_update(&bev->rate_limiting->limit,
+                   bev->rate_limiting->cfg, tick);
+}
+
+ev_uint32_t
+ev_token_bucket_get_tick(const struct timeval *tv,
+    const struct ev_token_bucket_cfg *cfg)
+{
+       /* This computation uses two multiplies and a divide.  We could do
+        * fewer if we knew that the tick length was an integer number of
+        * seconds, or if we knew it divided evenly into a second.  We should
+        * investigate that more.
+        */
+
+       /* We cast to an ev_uint64_t first, since we don't want to overflow
+        * before we do the final divide. */
+       ev_uint64_t msec = (ev_uint64_t)tv->tv_sec * 1000 + tv->tv_usec / 1000;
+       return (unsigned)(msec / cfg->msec_per_tick);
+}
+
+struct ev_token_bucket_cfg *
+ev_token_bucket_cfg_new(size_t read_rate, size_t read_burst,
+    size_t write_rate, size_t write_burst,
+    const struct timeval *tick_len)
+{
+       struct ev_token_bucket_cfg *r;
+       struct timeval g;
+       if (! tick_len) {
+               g.tv_sec = 1;
+               g.tv_usec = 0;
+               tick_len = &g;
+       }
+       if (read_rate > read_burst || write_rate > write_burst ||
+           read_rate < 1 || write_rate < 1)
+               return NULL;
+       if (read_rate > EV_RATE_LIMIT_MAX ||
+           write_rate > EV_RATE_LIMIT_MAX ||
+           read_burst > EV_RATE_LIMIT_MAX ||
+           write_burst > EV_RATE_LIMIT_MAX)
+               return NULL;
+       r = mm_calloc(1, sizeof(struct ev_token_bucket_cfg));
+       if (!r)
+               return NULL;
+       r->read_rate = read_rate;
+       r->write_rate = write_rate;
+       r->read_maximum = read_burst;
+       r->write_maximum = write_burst;
+       memcpy(&r->tick_timeout, tick_len, sizeof(struct timeval));
+       r->msec_per_tick = (tick_len->tv_sec * 1000) +
+           (tick_len->tv_usec & COMMON_TIMEOUT_MICROSECONDS_MASK)/1000;
+       return r;
+}
+
+void
+ev_token_bucket_cfg_free(struct ev_token_bucket_cfg *cfg)
+{
+       mm_free(cfg);
+}
+
+/* No matter how big our bucket gets, don't try to read more than this
+ * much in a single read operation. */
+#define MAX_TO_READ_EVER 16384
+/* No matter how big our bucket gets, don't try to write more than this
+ * much in a single write operation. */
+#define MAX_TO_WRITE_EVER 16384
+
+#define LOCK_GROUP(g) EVLOCK_LOCK((g)->lock, 0)
+#define UNLOCK_GROUP(g) EVLOCK_UNLOCK((g)->lock, 0)
+
+static int _bev_group_suspend_reading(struct bufferevent_rate_limit_group *g);
+static int _bev_group_suspend_writing(struct bufferevent_rate_limit_group *g);
+static void _bev_group_unsuspend_reading(struct bufferevent_rate_limit_group *g);
+static void _bev_group_unsuspend_writing(struct bufferevent_rate_limit_group *g);
+
+/** Helper: figure out the maximum amount we should write if is_write, or
+    the maximum amount we should read if is_read.  Return that maximum, or
+    0 if our bucket is wholly exhausted.
+ */
+static inline ev_ssize_t
+_bufferevent_get_rlim_max(struct bufferevent_private *bev, int is_write)
+{
+       /* needs lock on bev. */
+       ev_ssize_t max_so_far = is_write?MAX_TO_WRITE_EVER:MAX_TO_READ_EVER;
+
+#define LIM(x)                                         \
+       (is_write ? (x).write_limit : (x).read_limit)
+
+#define GROUP_SUSPENDED(g)                     \
+       (is_write ? (g)->write_suspended : (g)->read_suspended)
+
+       /* Sets max_so_far to MIN(x, max_so_far) */
+#define CLAMPTO(x)                             \
+       do {                                    \
+               if (max_so_far > (x))           \
+                       max_so_far = (x);       \
+       } while (0);
+
+       if (!bev->rate_limiting)
+               return max_so_far;
+
+       /* If rate-limiting is enabled at all, update the appropriate
+          bucket, and take the smaller of our rate limit and the group
+          rate limit.
+        */
+
+       if (bev->rate_limiting->cfg) {
+               bufferevent_update_buckets(bev);
+               max_so_far = LIM(bev->rate_limiting->limit);
+       }
+       if (bev->rate_limiting->group) {
+               struct bufferevent_rate_limit_group *g =
+                   bev->rate_limiting->group;
+               ev_ssize_t share;
+               LOCK_GROUP(g);
+               if (GROUP_SUSPENDED(g)) {
+                       /* We can get here if we failed to lock this
+                        * particular bufferevent while suspending the whole
+                        * group. */
+                       if (is_write)
+                               bufferevent_suspend_write(&bev->bev,
+                                   BEV_SUSPEND_BW_GROUP);
+                       else
+                               bufferevent_suspend_read(&bev->bev,
+                                   BEV_SUSPEND_BW_GROUP);
+                       share = 0;
+               } else {
+                       /* XXXX probably we should divide among the active
+                        * members, not the total members. */
+                       share = LIM(g->rate_limit) / g->n_members;
+                       if (share < g->min_share)
+                               share = g->min_share;
+               }
+               UNLOCK_GROUP(g);
+               CLAMPTO(share);
+       }
+
+       if (max_so_far < 0)
+               max_so_far = 0;
+       return max_so_far;
+}
+
+ev_ssize_t
+_bufferevent_get_read_max(struct bufferevent_private *bev)
+{
+       return _bufferevent_get_rlim_max(bev, 0);
+}
+
+ev_ssize_t
+_bufferevent_get_write_max(struct bufferevent_private *bev)
+{
+       return _bufferevent_get_rlim_max(bev, 1);
+}
+
+int
+_bufferevent_decrement_read_buckets(struct bufferevent_private *bev, ev_ssize_t bytes)
+{
+       /* XXXXX Make sure all users of this function check its return value */
+       int r = 0;
+       /* need to hold lock on bev */
+       if (!bev->rate_limiting)
+               return 0;
+
+       if (bev->rate_limiting->cfg) {
+               bev->rate_limiting->limit.read_limit -= bytes;
+               if (bev->rate_limiting->limit.read_limit <= 0) {
+                       bufferevent_suspend_read(&bev->bev, BEV_SUSPEND_BW);
+                       if (event_add(&bev->rate_limiting->refill_bucket_event,
+                               &bev->rate_limiting->cfg->tick_timeout) < 0)
+                               r = -1;
+               } else if (bev->read_suspended & BEV_SUSPEND_BW) {
+                       if (!(bev->write_suspended & BEV_SUSPEND_BW))
+                               event_del(&bev->rate_limiting->refill_bucket_event);
+                       bufferevent_unsuspend_read(&bev->bev, BEV_SUSPEND_BW);
+               }
+       }
+
+       if (bev->rate_limiting->group) {
+               LOCK_GROUP(bev->rate_limiting->group);
+               bev->rate_limiting->group->rate_limit.read_limit -= bytes;
+               bev->rate_limiting->group->total_read += bytes;
+               if (bev->rate_limiting->group->rate_limit.read_limit <= 0) {
+                       _bev_group_suspend_reading(bev->rate_limiting->group);
+               } else if (bev->rate_limiting->group->read_suspended) {
+                       _bev_group_unsuspend_reading(bev->rate_limiting->group);
+               }
+               UNLOCK_GROUP(bev->rate_limiting->group);
+       }
+
+       return r;
+}
+
+int
+_bufferevent_decrement_write_buckets(struct bufferevent_private *bev, ev_ssize_t bytes)
+{
+       /* XXXXX Make sure all users of this function check its return value */
+       int r = 0;
+       /* need to hold lock */
+       if (!bev->rate_limiting)
+               return 0;
+
+       if (bev->rate_limiting->cfg) {
+               bev->rate_limiting->limit.write_limit -= bytes;
+               if (bev->rate_limiting->limit.write_limit <= 0) {
+                       bufferevent_suspend_write(&bev->bev, BEV_SUSPEND_BW);
+                       if (event_add(&bev->rate_limiting->refill_bucket_event,
+                               &bev->rate_limiting->cfg->tick_timeout) < 0)
+                               r = -1;
+               } else if (bev->write_suspended & BEV_SUSPEND_BW) {
+                       if (!(bev->read_suspended & BEV_SUSPEND_BW))
+                               event_del(&bev->rate_limiting->refill_bucket_event);
+                       bufferevent_unsuspend_write(&bev->bev, BEV_SUSPEND_BW);
+               }
+       }
+
+       if (bev->rate_limiting->group) {
+               LOCK_GROUP(bev->rate_limiting->group);
+               bev->rate_limiting->group->rate_limit.write_limit -= bytes;
+               bev->rate_limiting->group->total_written += bytes;
+               if (bev->rate_limiting->group->rate_limit.write_limit <= 0) {
+                       _bev_group_suspend_writing(bev->rate_limiting->group);
+               } else if (bev->rate_limiting->group->write_suspended) {
+                       _bev_group_unsuspend_writing(bev->rate_limiting->group);
+               }
+               UNLOCK_GROUP(bev->rate_limiting->group);
+       }
+
+       return r;
+}
+
+/** Stop reading on every bufferevent in <b>g</b> */
+static int
+_bev_group_suspend_reading(struct bufferevent_rate_limit_group *g)
+{
+       /* Needs group lock */
+       struct bufferevent_private *bev;
+       g->read_suspended = 1;
+       g->pending_unsuspend_read = 0;
+
+       /* Note that in this loop we call EVLOCK_TRY_LOCK instead of BEV_LOCK,
+          to prevent a deadlock.  (Ordinarily, the group lock nests inside
+          the bufferevent locks.  If we are unable to lock any individual
+          bufferevent, it will find out later when it looks at its limit
+          and sees that its group is suspended.
+       */
+       TAILQ_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
+               if (EVLOCK_TRY_LOCK(bev->lock)) {
+                       bufferevent_suspend_read(&bev->bev,
+                           BEV_SUSPEND_BW_GROUP);
+                       EVLOCK_UNLOCK(bev->lock, 0);
+               }
+       }
+       return 0;
+}
+
+/** Stop writing on every bufferevent in <b>g</b> */
+static int
+_bev_group_suspend_writing(struct bufferevent_rate_limit_group *g)
+{
+       /* Needs group lock */
+       struct bufferevent_private *bev;
+       g->write_suspended = 1;
+       g->pending_unsuspend_write = 0;
+       TAILQ_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
+               if (EVLOCK_TRY_LOCK(bev->lock)) {
+                       bufferevent_suspend_write(&bev->bev,
+                           BEV_SUSPEND_BW_GROUP);
+                       EVLOCK_UNLOCK(bev->lock, 0);
+               }
+       }
+       return 0;
+}
+
+/** Timer callback invoked on a single bufferevent with one or more exhausted
+    buckets when they are ready to refill. */
+static void
+_bev_refill_callback(evutil_socket_t fd, short what, void *arg)
+{
+       unsigned tick;
+       struct timeval now;
+       struct bufferevent_private *bev = arg;
+       int again = 0;
+       BEV_LOCK(&bev->bev);
+       if (!bev->rate_limiting || !bev->rate_limiting->cfg) {
+               BEV_UNLOCK(&bev->bev);
+               return;
+       }
+
+       /* First, update the bucket */
+       event_base_gettimeofday_cached(bev->bev.ev_base, &now);
+       tick = ev_token_bucket_get_tick(&now,
+           bev->rate_limiting->cfg);
+       ev_token_bucket_update(&bev->rate_limiting->limit,
+           bev->rate_limiting->cfg,
+           tick);
+
+       /* Now unsuspend any read/write operations as appropriate. */
+       if ((bev->read_suspended & BEV_SUSPEND_BW)) {
+               if (bev->rate_limiting->limit.read_limit > 0)
+                       bufferevent_unsuspend_read(&bev->bev, BEV_SUSPEND_BW);
+               else
+                       again = 1;
+       }
+       if ((bev->write_suspended & BEV_SUSPEND_BW)) {
+               if (bev->rate_limiting->limit.write_limit > 0)
+                       bufferevent_unsuspend_write(&bev->bev, BEV_SUSPEND_BW);
+               else
+                       again = 1;
+       }
+       if (again) {
+               /* One or more of the buckets may need another refill if they
+                  started negative.
+
+                  XXXX if we need to be quiet for more ticks, we should
+                  maybe figure out what timeout we really want.
+               */
+               /* XXXX Handle event_add failure somehow */
+               event_add(&bev->rate_limiting->refill_bucket_event,
+                   &bev->rate_limiting->cfg->tick_timeout);
+       }
+       BEV_UNLOCK(&bev->bev);
+}
+
+/** Helper: grab a random element from a bufferevent group. */
+static struct bufferevent_private *
+_bev_group_random_element(struct bufferevent_rate_limit_group *group)
+{
+       int which;
+       struct bufferevent_private *bev;
+
+       /* requires group lock */
+
+       if (!group->n_members)
+               return NULL;
+
+       EVUTIL_ASSERT(! TAILQ_EMPTY(&group->members));
+
+       which = _evutil_weakrand() % group->n_members;
+
+       bev = TAILQ_FIRST(&group->members);
+       while (which--)
+               bev = TAILQ_NEXT(bev, rate_limiting->next_in_group);
+
+       return bev;
+}
+
+/** Iterate over the elements of a rate-limiting group 'g' with a random
+    starting point, assigning each to the variable 'bev', and executing the
+    block 'block'.
+
+    We do this in a half-baked effort to get fairness among group members.
+    XXX Round-robin or some kind of priority queue would be even more fair.
+ */
+#define FOREACH_RANDOM_ORDER(block)                    \
+       do {                                            \
+               first = _bev_group_random_element(g);   \
+               for (bev = first; bev != TAILQ_END(&g->members); \
+                   bev = TAILQ_NEXT(bev, rate_limiting->next_in_group)) { \
+                       block ;                                  \
+               }                                                \
+               for (bev = TAILQ_FIRST(&g->members); bev && bev != first; \
+                   bev = TAILQ_NEXT(bev, rate_limiting->next_in_group)) { \
+                       block ;                                         \
+               }                                                       \
+       } while (0)
+
+static void
+_bev_group_unsuspend_reading(struct bufferevent_rate_limit_group *g)
+{
+       int again = 0;
+       struct bufferevent_private *bev, *first;
+
+       g->read_suspended = 0;
+       FOREACH_RANDOM_ORDER({
+               if (EVLOCK_TRY_LOCK(bev->lock)) {
+                       bufferevent_unsuspend_read(&bev->bev,
+                           BEV_SUSPEND_BW_GROUP);
+                       EVLOCK_UNLOCK(bev->lock, 0);
+               } else {
+                       again = 1;
+               }
+       });
+       g->pending_unsuspend_read = again;
+}
+
+static void
+_bev_group_unsuspend_writing(struct bufferevent_rate_limit_group *g)
+{
+       int again = 0;
+       struct bufferevent_private *bev, *first;
+       g->write_suspended = 0;
+
+       FOREACH_RANDOM_ORDER({
+               if (EVLOCK_TRY_LOCK(bev->lock)) {
+                       bufferevent_unsuspend_write(&bev->bev,
+                           BEV_SUSPEND_BW_GROUP);
+                       EVLOCK_UNLOCK(bev->lock, 0);
+               } else {
+                       again = 1;
+               }
+       });
+       g->pending_unsuspend_write = again;
+}
+
+/** Callback invoked every tick to add more elements to the group bucket
+    and unsuspend group members as needed.
+ */
+static void
+_bev_group_refill_callback(evutil_socket_t fd, short what, void *arg)
+{
+       struct bufferevent_rate_limit_group *g = arg;
+       unsigned tick;
+       struct timeval now;
+
+       event_base_gettimeofday_cached(event_get_base(&g->master_refill_event), &now);
+
+       LOCK_GROUP(g);
+
+       tick = ev_token_bucket_get_tick(&now, &g->rate_limit_cfg);
+       ev_token_bucket_update(&g->rate_limit, &g->rate_limit_cfg, tick);
+
+       if (g->pending_unsuspend_read ||
+           (g->read_suspended && (g->rate_limit.read_limit >= g->min_share))) {
+               _bev_group_unsuspend_reading(g);
+       }
+       if (g->pending_unsuspend_write ||
+           (g->write_suspended && (g->rate_limit.write_limit >= g->min_share))){
+               _bev_group_unsuspend_writing(g);
+       }
+
+       /* XXXX Rather than waiting to the next tick to unsuspend stuff
+        * with pending_unsuspend_write/read, we should do it on the
+        * next iteration of the mainloop.
+        */
+
+       UNLOCK_GROUP(g);
+}
+
+int
+bufferevent_set_rate_limit(struct bufferevent *bev,
+    struct ev_token_bucket_cfg *cfg)
+{
+       struct bufferevent_private *bevp =
+           EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
+       int r = -1;
+       struct bufferevent_rate_limit *rlim;
+       struct timeval now;
+       ev_uint32_t tick;
+       int reinit = 0, suspended = 0;
+       /* XXX reference-count cfg */
+
+       BEV_LOCK(bev);
+
+       if (cfg == NULL) {
+               if (bevp->rate_limiting) {
+                       rlim = bevp->rate_limiting;
+                       rlim->cfg = NULL;
+                       bufferevent_unsuspend_read(bev, BEV_SUSPEND_BW);
+                       bufferevent_unsuspend_write(bev, BEV_SUSPEND_BW);
+                       if (event_initialized(&rlim->refill_bucket_event))
+                               event_del(&rlim->refill_bucket_event);
+               }
+               r = 0;
+               goto done;
+       }
+
+       event_base_gettimeofday_cached(bev->ev_base, &now);
+       tick = ev_token_bucket_get_tick(&now, cfg);
+
+       if (bevp->rate_limiting && bevp->rate_limiting->cfg == cfg) {
+               /* no-op */
+               r = 0;
+               goto done;
+       }
+       if (bevp->rate_limiting == NULL) {
+               rlim = mm_calloc(1, sizeof(struct bufferevent_rate_limit));
+               if (!rlim)
+                       goto done;
+               bevp->rate_limiting = rlim;
+       } else {
+               rlim = bevp->rate_limiting;
+       }
+       reinit = rlim->cfg != NULL;
+
+       rlim->cfg = cfg;
+       ev_token_bucket_init(&rlim->limit, cfg, tick, reinit);
+
+       if (reinit) {
+               EVUTIL_ASSERT(event_initialized(&rlim->refill_bucket_event));
+               event_del(&rlim->refill_bucket_event);
+       }
+       evtimer_assign(&rlim->refill_bucket_event, bev->ev_base,
+           _bev_refill_callback, bevp);
+
+       if (rlim->limit.read_limit > 0) {
+               bufferevent_unsuspend_read(bev, BEV_SUSPEND_BW);
+       } else {
+               bufferevent_suspend_read(bev, BEV_SUSPEND_BW);
+               suspended=1;
+       }
+       if (rlim->limit.write_limit > 0) {
+               bufferevent_unsuspend_write(bev, BEV_SUSPEND_BW);
+       } else {
+               bufferevent_suspend_write(bev, BEV_SUSPEND_BW);
+               suspended = 1;
+       }
+
+       if (suspended)
+               event_add(&rlim->refill_bucket_event, &cfg->tick_timeout);
+
+       r = 0;
+
+done:
+       BEV_UNLOCK(bev);
+       return r;
+}
+
+struct bufferevent_rate_limit_group *
+bufferevent_rate_limit_group_new(struct event_base *base,
+    const struct ev_token_bucket_cfg *cfg)
+{
+       struct bufferevent_rate_limit_group *g;
+       struct timeval now;
+       ev_uint32_t tick;
+
+       event_base_gettimeofday_cached(base, &now);
+       tick = ev_token_bucket_get_tick(&now, cfg);
+
+       g = mm_calloc(1, sizeof(struct bufferevent_rate_limit_group));
+       if (!g)
+               return NULL;
+       memcpy(&g->rate_limit_cfg, cfg, sizeof(g->rate_limit_cfg));
+       TAILQ_INIT(&g->members);
+
+       ev_token_bucket_init(&g->rate_limit, cfg, tick, 0);
+
+       event_assign(&g->master_refill_event, base, -1, EV_PERSIST,
+           _bev_group_refill_callback, g);
+       /*XXXX handle event_add failure */
+       event_add(&g->master_refill_event, &cfg->tick_timeout);
+
+       EVTHREAD_ALLOC_LOCK(g->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+
+       bufferevent_rate_limit_group_set_min_share(g, 64);
+
+       return g;
+}
+
+int
+bufferevent_rate_limit_group_set_cfg(
+       struct bufferevent_rate_limit_group *g,
+       const struct ev_token_bucket_cfg *cfg)
+{
+       int same_tick;
+       if (!g || !cfg)
+               return -1;
+
+       LOCK_GROUP(g);
+       same_tick = evutil_timercmp(
+               &g->rate_limit_cfg.tick_timeout, &cfg->tick_timeout, ==);
+       memcpy(&g->rate_limit_cfg, cfg, sizeof(g->rate_limit_cfg));
+
+       if (g->rate_limit.read_limit > (ev_ssize_t)cfg->read_maximum)
+               g->rate_limit.read_limit = cfg->read_maximum;
+       if (g->rate_limit.write_limit > (ev_ssize_t)cfg->write_maximum)
+               g->rate_limit.write_limit = cfg->write_maximum;
+
+       if (!same_tick) {
+               /* This can cause a hiccup in the schedule */
+               event_add(&g->master_refill_event, &cfg->tick_timeout);
+       }
+
+       /* The new limits might force us to adjust min_share differently. */
+       bufferevent_rate_limit_group_set_min_share(g, g->configured_min_share);
+
+       UNLOCK_GROUP(g);
+       return 0;
+}
+
+int
+bufferevent_rate_limit_group_set_min_share(
+       struct bufferevent_rate_limit_group *g,
+       size_t share)
+{
+       if (share > EV_SSIZE_MAX)
+               return -1;
+
+       g->configured_min_share = share;
+
+       /* Can't set share to less than the one-tick maximum.  IOW, at steady
+        * state, at least one connection can go per tick. */
+       if (share > g->rate_limit_cfg.read_rate)
+               share = g->rate_limit_cfg.read_rate;
+       if (share > g->rate_limit_cfg.write_rate)
+               share = g->rate_limit_cfg.write_rate;
+
+       g->min_share = share;
+       return 0;
+}
+
+void
+bufferevent_rate_limit_group_free(struct bufferevent_rate_limit_group *g)
+{
+       LOCK_GROUP(g);
+       EVUTIL_ASSERT(0 == g->n_members);
+       event_del(&g->master_refill_event);
+       UNLOCK_GROUP(g);
+       EVTHREAD_FREE_LOCK(g->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       mm_free(g);
+}
+
+int
+bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
+    struct bufferevent_rate_limit_group *g)
+{
+       int wsuspend, rsuspend;
+       struct bufferevent_private *bevp =
+           EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
+       BEV_LOCK(bev);
+
+       if (!bevp->rate_limiting) {
+               struct bufferevent_rate_limit *rlim;
+               rlim = mm_calloc(1, sizeof(struct bufferevent_rate_limit));
+               if (!rlim) {
+                       BEV_UNLOCK(bev);
+                       return -1;
+               }
+               evtimer_assign(&rlim->refill_bucket_event, bev->ev_base,
+                   _bev_refill_callback, bevp);
+               bevp->rate_limiting = rlim;
+       }
+
+       if (bevp->rate_limiting->group == g) {
+               BEV_UNLOCK(bev);
+               return 0;
+       }
+       if (bevp->rate_limiting->group)
+               bufferevent_remove_from_rate_limit_group(bev);
+
+       LOCK_GROUP(g);
+       bevp->rate_limiting->group = g;
+       ++g->n_members;
+       TAILQ_INSERT_TAIL(&g->members, bevp, rate_limiting->next_in_group);
+
+       rsuspend = g->read_suspended;
+       wsuspend = g->write_suspended;
+
+       UNLOCK_GROUP(g);
+
+       if (rsuspend)
+               bufferevent_suspend_read(bev, BEV_SUSPEND_BW_GROUP);
+       if (wsuspend)
+               bufferevent_suspend_write(bev, BEV_SUSPEND_BW_GROUP);
+
+       BEV_UNLOCK(bev);
+       return 0;
+}
+
+int
+bufferevent_remove_from_rate_limit_group(struct bufferevent *bev)
+{
+       return bufferevent_remove_from_rate_limit_group_internal(bev, 1);
+}
+
+int
+bufferevent_remove_from_rate_limit_group_internal(struct bufferevent *bev,
+    int unsuspend)
+{
+       struct bufferevent_private *bevp =
+           EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
+       BEV_LOCK(bev);
+       if (bevp->rate_limiting && bevp->rate_limiting->group) {
+               struct bufferevent_rate_limit_group *g =
+                   bevp->rate_limiting->group;
+               LOCK_GROUP(g);
+               bevp->rate_limiting->group = NULL;
+               --g->n_members;
+               TAILQ_REMOVE(&g->members, bevp, rate_limiting->next_in_group);
+               UNLOCK_GROUP(g);
+       }
+       if (unsuspend) {
+               bufferevent_unsuspend_read(bev, BEV_SUSPEND_BW_GROUP);
+               bufferevent_unsuspend_write(bev, BEV_SUSPEND_BW_GROUP);
+       }
+       BEV_UNLOCK(bev);
+       return 0;
+}
+
+/* ===
+ * API functions to expose rate limits.
+ *
+ * Don't use these from inside Libevent; they're meant to be for use by
+ * the program.
+ * === */
+
+/* Mostly you don't want to use this function from inside libevent;
+ * _bufferevent_get_read_max() is more likely what you want*/
+ev_ssize_t
+bufferevent_get_read_limit(struct bufferevent *bev)
+{
+       ev_ssize_t r;
+       struct bufferevent_private *bevp;
+       BEV_LOCK(bev);
+       bevp = BEV_UPCAST(bev);
+       if (bevp->rate_limiting && bevp->rate_limiting->cfg) {
+               bufferevent_update_buckets(bevp);
+               r = bevp->rate_limiting->limit.read_limit;
+       } else {
+               r = EV_SSIZE_MAX;
+       }
+       BEV_UNLOCK(bev);
+       return r;
+}
+
+/* Mostly you don't want to use this function from inside libevent;
+ * _bufferevent_get_write_max() is more likely what you want*/
+ev_ssize_t
+bufferevent_get_write_limit(struct bufferevent *bev)
+{
+       ev_ssize_t r;
+       struct bufferevent_private *bevp;
+       BEV_LOCK(bev);
+       bevp = BEV_UPCAST(bev);
+       if (bevp->rate_limiting && bevp->rate_limiting->cfg) {
+               bufferevent_update_buckets(bevp);
+               r = bevp->rate_limiting->limit.write_limit;
+       } else {
+               r = EV_SSIZE_MAX;
+       }
+       BEV_UNLOCK(bev);
+       return r;
+}
+
+ev_ssize_t
+bufferevent_get_max_to_read(struct bufferevent *bev)
+{
+       ev_ssize_t r;
+       BEV_LOCK(bev);
+       r = _bufferevent_get_read_max(BEV_UPCAST(bev));
+       BEV_UNLOCK(bev);
+       return r;
+}
+
+ev_ssize_t
+bufferevent_get_max_to_write(struct bufferevent *bev)
+{
+       ev_ssize_t r;
+       BEV_LOCK(bev);
+       r = _bufferevent_get_write_max(BEV_UPCAST(bev));
+       BEV_UNLOCK(bev);
+       return r;
+}
+
+
+/* Mostly you don't want to use this function from inside libevent;
+ * _bufferevent_get_read_max() is more likely what you want*/
+ev_ssize_t
+bufferevent_rate_limit_group_get_read_limit(
+       struct bufferevent_rate_limit_group *grp)
+{
+       ev_ssize_t r;
+       LOCK_GROUP(grp);
+       r = grp->rate_limit.read_limit;
+       UNLOCK_GROUP(grp);
+       return r;
+}
+
+/* Mostly you don't want to use this function from inside libevent;
+ * _bufferevent_get_write_max() is more likely what you want. */
+ev_ssize_t
+bufferevent_rate_limit_group_get_write_limit(
+       struct bufferevent_rate_limit_group *grp)
+{
+       ev_ssize_t r;
+       LOCK_GROUP(grp);
+       r = grp->rate_limit.write_limit;
+       UNLOCK_GROUP(grp);
+       return r;
+}
+
+int
+bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr)
+{
+       int r = 0;
+       ev_ssize_t old_limit, new_limit;
+       struct bufferevent_private *bevp;
+       BEV_LOCK(bev);
+       bevp = BEV_UPCAST(bev);
+       EVUTIL_ASSERT(bevp->rate_limiting && bevp->rate_limiting->cfg);
+       old_limit = bevp->rate_limiting->limit.read_limit;
+
+       new_limit = (bevp->rate_limiting->limit.read_limit -= decr);
+       if (old_limit > 0 && new_limit <= 0) {
+               bufferevent_suspend_read(bev, BEV_SUSPEND_BW);
+               if (event_add(&bevp->rate_limiting->refill_bucket_event,
+                       &bevp->rate_limiting->cfg->tick_timeout) < 0)
+                       r = -1;
+       } else if (old_limit <= 0 && new_limit > 0) {
+               if (!(bevp->write_suspended & BEV_SUSPEND_BW))
+                       event_del(&bevp->rate_limiting->refill_bucket_event);
+               bufferevent_unsuspend_read(bev, BEV_SUSPEND_BW);
+       }
+
+       BEV_UNLOCK(bev);
+       return r;
+}
+
+int
+bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr)
+{
+       /* XXXX this is mostly copy-and-paste from
+        * bufferevent_decrement_read_limit */
+       int r = 0;
+       ev_ssize_t old_limit, new_limit;
+       struct bufferevent_private *bevp;
+       BEV_LOCK(bev);
+       bevp = BEV_UPCAST(bev);
+       EVUTIL_ASSERT(bevp->rate_limiting && bevp->rate_limiting->cfg);
+       old_limit = bevp->rate_limiting->limit.write_limit;
+
+       new_limit = (bevp->rate_limiting->limit.write_limit -= decr);
+       if (old_limit > 0 && new_limit <= 0) {
+               bufferevent_suspend_write(bev, BEV_SUSPEND_BW);
+               if (event_add(&bevp->rate_limiting->refill_bucket_event,
+                       &bevp->rate_limiting->cfg->tick_timeout) < 0)
+                       r = -1;
+       } else if (old_limit <= 0 && new_limit > 0) {
+               if (!(bevp->read_suspended & BEV_SUSPEND_BW))
+                       event_del(&bevp->rate_limiting->refill_bucket_event);
+               bufferevent_unsuspend_write(bev, BEV_SUSPEND_BW);
+       }
+
+       BEV_UNLOCK(bev);
+       return r;
+}
+
+int
+bufferevent_rate_limit_group_decrement_read(
+       struct bufferevent_rate_limit_group *grp, ev_ssize_t decr)
+{
+       int r = 0;
+       ev_ssize_t old_limit, new_limit;
+       LOCK_GROUP(grp);
+       old_limit = grp->rate_limit.read_limit;
+       new_limit = (grp->rate_limit.read_limit -= decr);
+
+       if (old_limit > 0 && new_limit <= 0) {
+               _bev_group_suspend_reading(grp);
+       } else if (old_limit <= 0 && new_limit > 0) {
+               _bev_group_unsuspend_reading(grp);
+       }
+
+       UNLOCK_GROUP(grp);
+       return r;
+}
+
+int
+bufferevent_rate_limit_group_decrement_write(
+       struct bufferevent_rate_limit_group *grp, ev_ssize_t decr)
+{
+       int r = 0;
+       ev_ssize_t old_limit, new_limit;
+       LOCK_GROUP(grp);
+       old_limit = grp->rate_limit.write_limit;
+       new_limit = (grp->rate_limit.write_limit -= decr);
+
+       if (old_limit > 0 && new_limit <= 0) {
+               _bev_group_suspend_writing(grp);
+       } else if (old_limit <= 0 && new_limit > 0) {
+               _bev_group_unsuspend_writing(grp);
+       }
+
+       UNLOCK_GROUP(grp);
+       return r;
+}
+
+void
+bufferevent_rate_limit_group_get_totals(struct bufferevent_rate_limit_group *grp,
+    ev_uint64_t *total_read_out, ev_uint64_t *total_written_out)
+{
+       EVUTIL_ASSERT(grp != NULL);
+       if (total_read_out)
+               *total_read_out = grp->total_read;
+       if (total_written_out)
+               *total_written_out = grp->total_written;
+}
+
+void
+bufferevent_rate_limit_group_reset_totals(struct bufferevent_rate_limit_group *grp)
+{
+       grp->total_read = grp->total_written = 0;
+}
diff --git a/libevent/bufferevent_sock.c b/libevent/bufferevent_sock.c
new file mode 100644 (file)
index 0000000..9050eda
--- /dev/null
@@ -0,0 +1,693 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+
+#include "event2/event-config.h"
+
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef _EVENT_HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef _EVENT_HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+
+#include "event2/util.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/event.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "util-internal.h"
+#ifdef WIN32
+#include "iocp-internal.h"
+#endif
+
+/* prototypes */
+static int be_socket_enable(struct bufferevent *, short);
+static int be_socket_disable(struct bufferevent *, short);
+static void be_socket_destruct(struct bufferevent *);
+static int be_socket_adj_timeouts(struct bufferevent *);
+static int be_socket_flush(struct bufferevent *, short, enum bufferevent_flush_mode);
+static int be_socket_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+static void be_socket_setfd(struct bufferevent *, evutil_socket_t);
+
+const struct bufferevent_ops bufferevent_ops_socket = {
+       "socket",
+       evutil_offsetof(struct bufferevent_private, bev),
+       be_socket_enable,
+       be_socket_disable,
+       be_socket_destruct,
+       be_socket_adj_timeouts,
+       be_socket_flush,
+       be_socket_ctrl,
+};
+
+#define be_socket_add(ev, t)                   \
+       _bufferevent_add_event((ev), (t))
+
+static void
+bufferevent_socket_outbuf_cb(struct evbuffer *buf,
+    const struct evbuffer_cb_info *cbinfo,
+    void *arg)
+{
+       struct bufferevent *bufev = arg;
+       struct bufferevent_private *bufev_p =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+
+       if (cbinfo->n_added &&
+           (bufev->enabled & EV_WRITE) &&
+           !event_pending(&bufev->ev_write, EV_WRITE, NULL) &&
+           !bufev_p->write_suspended) {
+               /* Somebody added data to the buffer, and we would like to
+                * write, and we were not writing.  So, start writing. */
+               if (be_socket_add(&bufev->ev_write, &bufev->timeout_write) == -1) {
+                   /* Should we log this? */
+               }
+       }
+}
+
+static void
+bufferevent_readcb(evutil_socket_t fd, short event, void *arg)
+{
+       struct bufferevent *bufev = arg;
+       struct bufferevent_private *bufev_p =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       struct evbuffer *input;
+       int res = 0;
+       short what = BEV_EVENT_READING;
+       ev_ssize_t howmuch = -1, readmax=-1;
+
+       _bufferevent_incref_and_lock(bufev);
+
+       if (event == EV_TIMEOUT) {
+               what |= BEV_EVENT_TIMEOUT;
+               goto error;
+       }
+
+       input = bufev->input;
+
+       /*
+        * If we have a high watermark configured then we don't want to
+        * read more data than would make us reach the watermark.
+        */
+       if (bufev->wm_read.high != 0) {
+               howmuch = bufev->wm_read.high - evbuffer_get_length(input);
+               /* we somehow lowered the watermark, stop reading */
+               if (howmuch <= 0) {
+                       bufferevent_wm_suspend_read(bufev);
+                       goto done;
+               }
+       }
+       readmax = _bufferevent_get_read_max(bufev_p);
+       if (howmuch < 0 || howmuch > readmax) /* The use of -1 for "unlimited"
+                                              * uglifies this code. XXXX */
+               howmuch = readmax;
+       if (bufev_p->read_suspended)
+               goto done;
+
+       evbuffer_unfreeze(input, 0);
+       res = evbuffer_read(input, fd, (int)howmuch); /* XXXX evbuffer_read would do better to take and return ev_ssize_t */
+       evbuffer_freeze(input, 0);
+
+       if (res == -1) {
+               int err = evutil_socket_geterror(fd);
+               if (EVUTIL_ERR_RW_RETRIABLE(err))
+                       goto reschedule;
+               /* error case */
+               what |= BEV_EVENT_ERROR;
+       } else if (res == 0) {
+               /* eof case */
+               what |= BEV_EVENT_EOF;
+       }
+
+       if (res <= 0)
+               goto error;
+
+       _bufferevent_decrement_read_buckets(bufev_p, res);
+
+       /* Invoke the user callback - must always be called last */
+       if (evbuffer_get_length(input) >= bufev->wm_read.low)
+               _bufferevent_run_readcb(bufev);
+
+       goto done;
+
+ reschedule:
+       goto done;
+
+ error:
+       bufferevent_disable(bufev, EV_READ);
+       _bufferevent_run_eventcb(bufev, what);
+
+ done:
+       _bufferevent_decref_and_unlock(bufev);
+}
+
+static void
+bufferevent_writecb(evutil_socket_t fd, short event, void *arg)
+{
+       struct bufferevent *bufev = arg;
+       struct bufferevent_private *bufev_p =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       int res = 0;
+       short what = BEV_EVENT_WRITING;
+       int connected = 0;
+       ev_ssize_t atmost = -1;
+
+       _bufferevent_incref_and_lock(bufev);
+
+       if (event == EV_TIMEOUT) {
+               what |= BEV_EVENT_TIMEOUT;
+               goto error;
+       }
+       if (bufev_p->connecting) {
+               int c = evutil_socket_finished_connecting(fd);
+               /* we need to fake the error if the connection was refused
+                * immediately - usually connection to localhost on BSD */
+               if (bufev_p->connection_refused) {
+                 bufev_p->connection_refused = 0;
+                 c = -1;
+               }
+
+               if (c == 0)
+                       goto done;
+
+               bufev_p->connecting = 0;
+               if (c < 0) {
+                       event_del(&bufev->ev_write);
+                       event_del(&bufev->ev_read);
+                       _bufferevent_run_eventcb(bufev, BEV_EVENT_ERROR);
+                       goto done;
+               } else {
+                       connected = 1;
+#ifdef WIN32
+                       if (BEV_IS_ASYNC(bufev)) {
+                               event_del(&bufev->ev_write);
+                               bufferevent_async_set_connected(bufev);
+                               _bufferevent_run_eventcb(bufev,
+                                               BEV_EVENT_CONNECTED);
+                               goto done;
+                       }
+#endif
+                       _bufferevent_run_eventcb(bufev,
+                                       BEV_EVENT_CONNECTED);
+                       if (!(bufev->enabled & EV_WRITE) ||
+                           bufev_p->write_suspended) {
+                               event_del(&bufev->ev_write);
+                               goto done;
+                       }
+               }
+       }
+
+       atmost = _bufferevent_get_write_max(bufev_p);
+
+       if (bufev_p->write_suspended)
+               goto done;
+
+       if (evbuffer_get_length(bufev->output)) {
+               evbuffer_unfreeze(bufev->output, 1);
+               res = evbuffer_write_atmost(bufev->output, fd, atmost);
+               evbuffer_freeze(bufev->output, 1);
+               if (res == -1) {
+                       int err = evutil_socket_geterror(fd);
+                       if (EVUTIL_ERR_RW_RETRIABLE(err))
+                               goto reschedule;
+                       what |= BEV_EVENT_ERROR;
+               } else if (res == 0) {
+                       /* eof case
+                          XXXX Actually, a 0 on write doesn't indicate
+                          an EOF. An ECONNRESET might be more typical.
+                        */
+                       what |= BEV_EVENT_EOF;
+               }
+               if (res <= 0)
+                       goto error;
+
+               _bufferevent_decrement_write_buckets(bufev_p, res);
+       }
+
+       if (evbuffer_get_length(bufev->output) == 0) {
+               event_del(&bufev->ev_write);
+       }
+
+       /*
+        * Invoke the user callback if our buffer is drained or below the
+        * low watermark.
+        */
+       if ((res || !connected) &&
+           evbuffer_get_length(bufev->output) <= bufev->wm_write.low) {
+               _bufferevent_run_writecb(bufev);
+       }
+
+       goto done;
+
+ reschedule:
+       if (evbuffer_get_length(bufev->output) == 0) {
+               event_del(&bufev->ev_write);
+       }
+       goto done;
+
+ error:
+       bufferevent_disable(bufev, EV_WRITE);
+       _bufferevent_run_eventcb(bufev, what);
+
+ done:
+       _bufferevent_decref_and_unlock(bufev);
+}
+
+struct bufferevent *
+bufferevent_socket_new(struct event_base *base, evutil_socket_t fd,
+    int options)
+{
+       struct bufferevent_private *bufev_p;
+       struct bufferevent *bufev;
+
+#ifdef WIN32
+       if (base && event_base_get_iocp(base))
+               return bufferevent_async_new(base, fd, options);
+#endif
+
+       if ((bufev_p = mm_calloc(1, sizeof(struct bufferevent_private)))== NULL)
+               return NULL;
+
+       if (bufferevent_init_common(bufev_p, base, &bufferevent_ops_socket,
+                                   options) < 0) {
+               mm_free(bufev_p);
+               return NULL;
+       }
+       bufev = &bufev_p->bev;
+       evbuffer_set_flags(bufev->output, EVBUFFER_FLAG_DRAINS_TO_FD);
+
+       event_assign(&bufev->ev_read, bufev->ev_base, fd,
+           EV_READ|EV_PERSIST, bufferevent_readcb, bufev);
+       event_assign(&bufev->ev_write, bufev->ev_base, fd,
+           EV_WRITE|EV_PERSIST, bufferevent_writecb, bufev);
+
+       evbuffer_add_cb(bufev->output, bufferevent_socket_outbuf_cb, bufev);
+
+       evbuffer_freeze(bufev->input, 0);
+       evbuffer_freeze(bufev->output, 1);
+
+       return bufev;
+}
+
+int
+bufferevent_socket_connect(struct bufferevent *bev,
+    struct sockaddr *sa, int socklen)
+{
+       struct bufferevent_private *bufev_p =
+           EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
+
+       evutil_socket_t fd;
+       int r = 0;
+       int result=-1;
+       int ownfd = 0;
+
+       _bufferevent_incref_and_lock(bev);
+
+       if (!bufev_p)
+               goto done;
+
+       fd = bufferevent_getfd(bev);
+       if (fd < 0) {
+               if (!sa)
+                       goto done;
+               fd = socket(sa->sa_family, SOCK_STREAM, 0);
+               if (fd < 0)
+                       goto done;
+               if (evutil_make_socket_nonblocking(fd)<0)
+                       goto done;
+               ownfd = 1;
+       }
+       if (sa) {
+#ifdef WIN32
+               if (bufferevent_async_can_connect(bev)) {
+                       bufferevent_setfd(bev, fd);
+                       r = bufferevent_async_connect(bev, fd, sa, socklen);
+                       if (r < 0)
+                               goto freesock;
+                       bufev_p->connecting = 1;
+                       result = 0;
+                       goto done;
+               } else
+#endif
+               r = evutil_socket_connect(&fd, sa, socklen);
+               if (r < 0)
+                       goto freesock;
+       }
+#ifdef WIN32
+       /* ConnectEx() isn't always around, even when IOCP is enabled.
+        * Here, we borrow the socket object's write handler to fall back
+        * on a non-blocking connect() when ConnectEx() is unavailable. */
+       if (BEV_IS_ASYNC(bev)) {
+               event_assign(&bev->ev_write, bev->ev_base, fd,
+                   EV_WRITE|EV_PERSIST, bufferevent_writecb, bev);
+       }
+#endif
+       bufferevent_setfd(bev, fd);
+       if (r == 0) {
+               if (! be_socket_enable(bev, EV_WRITE)) {
+                       bufev_p->connecting = 1;
+                       result = 0;
+                       goto done;
+               }
+       } else if (r == 1) {
+               /* The connect succeeded already. How very BSD of it. */
+               result = 0;
+               bufev_p->connecting = 1;
+               event_active(&bev->ev_write, EV_WRITE, 1);
+       } else {
+               /* The connect failed already.  How very BSD of it. */
+               bufev_p->connection_refused = 1;
+               bufev_p->connecting = 1;
+               result = 0;
+               event_active(&bev->ev_write, EV_WRITE, 1);
+       }
+
+       goto done;
+
+freesock:
+       _bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
+       if (ownfd)
+               evutil_closesocket(fd);
+       /* do something about the error? */
+done:
+       _bufferevent_decref_and_unlock(bev);
+       return result;
+}
+
+static void
+bufferevent_connect_getaddrinfo_cb(int result, struct evutil_addrinfo *ai,
+    void *arg)
+{
+       struct bufferevent *bev = arg;
+       struct bufferevent_private *bev_p =
+           EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
+       int r;
+       BEV_LOCK(bev);
+
+       bufferevent_unsuspend_write(bev, BEV_SUSPEND_LOOKUP);
+       bufferevent_unsuspend_read(bev, BEV_SUSPEND_LOOKUP);
+
+       if (result != 0) {
+               bev_p->dns_error = result;
+               _bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
+               _bufferevent_decref_and_unlock(bev);
+               if (ai)
+                       evutil_freeaddrinfo(ai);
+               return;
+       }
+
+       /* XXX use the other addrinfos? */
+       /* XXX use this return value */
+       r = bufferevent_socket_connect(bev, ai->ai_addr, (int)ai->ai_addrlen);
+       (void)r;
+       _bufferevent_decref_and_unlock(bev);
+       evutil_freeaddrinfo(ai);
+}
+
+int
+bufferevent_socket_connect_hostname(struct bufferevent *bev,
+    struct evdns_base *evdns_base, int family, const char *hostname, int port)
+{
+       char portbuf[10];
+       struct evutil_addrinfo hint;
+       int err;
+       struct bufferevent_private *bev_p =
+           EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
+
+       if (family != AF_INET && family != AF_INET6 && family != AF_UNSPEC)
+               return -1;
+       if (port < 1 || port > 65535)
+               return -1;
+
+       BEV_LOCK(bev);
+       bev_p->dns_error = 0;
+       BEV_UNLOCK(bev);
+
+       evutil_snprintf(portbuf, sizeof(portbuf), "%d", port);
+
+       memset(&hint, 0, sizeof(hint));
+       hint.ai_family = family;
+       hint.ai_protocol = IPPROTO_TCP;
+       hint.ai_socktype = SOCK_STREAM;
+
+       bufferevent_suspend_write(bev, BEV_SUSPEND_LOOKUP);
+       bufferevent_suspend_read(bev, BEV_SUSPEND_LOOKUP);
+
+       bufferevent_incref(bev);
+       err = evutil_getaddrinfo_async(evdns_base, hostname, portbuf,
+           &hint, bufferevent_connect_getaddrinfo_cb, bev);
+
+       if (err == 0) {
+               return 0;
+       } else {
+               bufferevent_unsuspend_write(bev, BEV_SUSPEND_LOOKUP);
+               bufferevent_unsuspend_read(bev, BEV_SUSPEND_LOOKUP);
+               return -1;
+       }
+}
+
+int
+bufferevent_socket_get_dns_error(struct bufferevent *bev)
+{
+       int rv;
+       struct bufferevent_private *bev_p =
+           EVUTIL_UPCAST(bev, struct bufferevent_private, bev);
+
+       BEV_LOCK(bev);
+       rv = bev_p->dns_error;
+       BEV_LOCK(bev);
+
+       return rv;
+}
+
+/*
+ * Create a new buffered event object.
+ *
+ * The read callback is invoked whenever we read new data.
+ * The write callback is invoked whenever the output buffer is drained.
+ * The error callback is invoked on a write/read error or on EOF.
+ *
+ * Both read and write callbacks maybe NULL.  The error callback is not
+ * allowed to be NULL and have to be provided always.
+ */
+
+struct bufferevent *
+bufferevent_new(evutil_socket_t fd,
+    bufferevent_data_cb readcb, bufferevent_data_cb writecb,
+    bufferevent_event_cb eventcb, void *cbarg)
+{
+       struct bufferevent *bufev;
+
+       if (!(bufev = bufferevent_socket_new(NULL, fd, 0)))
+               return NULL;
+
+       bufferevent_setcb(bufev, readcb, writecb, eventcb, cbarg);
+
+       return bufev;
+}
+
+
+static int
+be_socket_enable(struct bufferevent *bufev, short event)
+{
+       if (event & EV_READ) {
+               if (be_socket_add(&bufev->ev_read,&bufev->timeout_read) == -1)
+                       return -1;
+       }
+       if (event & EV_WRITE) {
+               if (be_socket_add(&bufev->ev_write,&bufev->timeout_write) == -1)
+                       return -1;
+       }
+       return 0;
+}
+
+static int
+be_socket_disable(struct bufferevent *bufev, short event)
+{
+       struct bufferevent_private *bufev_p =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       if (event & EV_READ) {
+               if (event_del(&bufev->ev_read) == -1)
+                       return -1;
+       }
+       /* Don't actually disable the write if we are trying to connect. */
+       if ((event & EV_WRITE) && ! bufev_p->connecting) {
+               if (event_del(&bufev->ev_write) == -1)
+                       return -1;
+       }
+       return 0;
+}
+
+static void
+be_socket_destruct(struct bufferevent *bufev)
+{
+       struct bufferevent_private *bufev_p =
+           EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
+       evutil_socket_t fd;
+       EVUTIL_ASSERT(bufev->be_ops == &bufferevent_ops_socket);
+
+       fd = event_get_fd(&bufev->ev_read);
+
+       event_del(&bufev->ev_read);
+       event_del(&bufev->ev_write);
+
+       if ((bufev_p->options & BEV_OPT_CLOSE_ON_FREE) && fd >= 0)
+               EVUTIL_CLOSESOCKET(fd);
+}
+
+static int
+be_socket_adj_timeouts(struct bufferevent *bufev)
+{
+       int r = 0;
+       if (event_pending(&bufev->ev_read, EV_READ, NULL))
+               if (be_socket_add(&bufev->ev_read, &bufev->timeout_read) < 0)
+                       r = -1;
+       if (event_pending(&bufev->ev_write, EV_WRITE, NULL)) {
+               if (be_socket_add(&bufev->ev_write, &bufev->timeout_write) < 0)
+                       r = -1;
+       }
+       return r;
+}
+
+static int
+be_socket_flush(struct bufferevent *bev, short iotype,
+    enum bufferevent_flush_mode mode)
+{
+       return 0;
+}
+
+
+static void
+be_socket_setfd(struct bufferevent *bufev, evutil_socket_t fd)
+{
+       BEV_LOCK(bufev);
+       EVUTIL_ASSERT(bufev->be_ops == &bufferevent_ops_socket);
+
+       event_del(&bufev->ev_read);
+       event_del(&bufev->ev_write);
+
+       event_assign(&bufev->ev_read, bufev->ev_base, fd,
+           EV_READ|EV_PERSIST, bufferevent_readcb, bufev);
+       event_assign(&bufev->ev_write, bufev->ev_base, fd,
+           EV_WRITE|EV_PERSIST, bufferevent_writecb, bufev);
+
+       if (fd >= 0)
+               bufferevent_enable(bufev, bufev->enabled);
+
+       BEV_UNLOCK(bufev);
+}
+
+/* XXXX Should non-socket bufferevents support this? */
+int
+bufferevent_priority_set(struct bufferevent *bufev, int priority)
+{
+       int r = -1;
+
+       BEV_LOCK(bufev);
+       if (bufev->be_ops != &bufferevent_ops_socket)
+               goto done;
+
+       if (event_priority_set(&bufev->ev_read, priority) == -1)
+               goto done;
+       if (event_priority_set(&bufev->ev_write, priority) == -1)
+               goto done;
+
+       r = 0;
+done:
+       BEV_UNLOCK(bufev);
+       return r;
+}
+
+/* XXXX Should non-socket bufferevents support this? */
+int
+bufferevent_base_set(struct event_base *base, struct bufferevent *bufev)
+{
+       int res = -1;
+
+       BEV_LOCK(bufev);
+       if (bufev->be_ops != &bufferevent_ops_socket)
+               goto done;
+
+       bufev->ev_base = base;
+
+       res = event_base_set(base, &bufev->ev_read);
+       if (res == -1)
+               goto done;
+
+       res = event_base_set(base, &bufev->ev_write);
+done:
+       BEV_UNLOCK(bufev);
+       return res;
+}
+
+static int
+be_socket_ctrl(struct bufferevent *bev, enum bufferevent_ctrl_op op,
+    union bufferevent_ctrl_data *data)
+{
+       switch (op) {
+       case BEV_CTRL_SET_FD:
+               be_socket_setfd(bev, data->fd);
+               return 0;
+       case BEV_CTRL_GET_FD:
+               data->fd = event_get_fd(&bev->ev_read);
+               return 0;
+       case BEV_CTRL_GET_UNDERLYING:
+       case BEV_CTRL_CANCEL_ALL:
+       default:
+               return -1;
+       }
+}
diff --git a/libevent/changelist-internal.h b/libevent/changelist-internal.h
new file mode 100644 (file)
index 0000000..6ed432a
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _CHANGELIST_H_
+#define _CHANGELIST_H_
+
+/*
+  A "changelist" is a list of all the fd status changes that should be made
+  between calls to the backend's dispatch function.  There are a few reasons
+  that a backend would want to queue changes like this rather than processing
+  them immediately.
+
+    1) Sometimes applications will add and delete the same event more than
+       once between calls to dispatch.  Processing these changes immediately
+       is needless, and potentially expensive (especially if we're on a system
+       that makes one syscall per changed event).
+
+    2) Sometimes we can coalesce multiple changes on the same fd into a single
+       syscall if we know about them in advance.  For example, epoll can do an
+       add and a delete at the same time, but only if we have found out about
+       both of them before we tell epoll.
+
+    3) Sometimes adding an event that we immediately delete can cause
+       unintended consequences: in kqueue, this makes pending events get
+       reported spuriously.
+ */
+
+#include "event2/util.h"
+
+/** Represents a */
+struct event_change {
+       /** The fd or signal whose events are to be changed */
+       evutil_socket_t fd;
+       /* The events that were enabled on the fd before any of these changes
+          were made.  May include EV_READ or EV_WRITE. */
+       short old_events;
+
+       /* The changes that we want to make in reading and writing on this fd.
+        * If this is a signal, then read_change has EV_CHANGE_SIGNAL set,
+        * and write_change is unused. */
+       ev_uint8_t read_change;
+       ev_uint8_t write_change;
+};
+
+/* Flags for read_change and write_change. */
+
+/* If set, add the event. */
+#define EV_CHANGE_ADD     0x01
+/* If set, delete the event.  Exclusive with EV_CHANGE_ADD */
+#define EV_CHANGE_DEL     0x02
+/* If set, this event refers a signal, not an fd. */
+#define EV_CHANGE_SIGNAL  EV_SIGNAL
+/* Set for persistent events.  Currently not used. */
+#define EV_CHANGE_PERSIST EV_PERSIST
+/* Set for adding edge-triggered events. */
+#define EV_CHANGE_ET      EV_ET
+
+/* The value of fdinfo_size that a backend should use if it is letting
+ * changelist handle its add and delete functions. */
+#define EVENT_CHANGELIST_FDINFO_SIZE sizeof(int)
+
+/** Set up the data fields in a changelist. */
+void event_changelist_init(struct event_changelist *changelist);
+/** Remove every change in the changelist, and make corresponding changes
+ * in the event maps in the base.  This function is generally used right
+ * after making all the changes in the changelist. */
+void event_changelist_remove_all(struct event_changelist *changelist,
+    struct event_base *base);
+/** Free all memory held in a changelist. */
+void event_changelist_freemem(struct event_changelist *changelist);
+
+/** Implementation of eventop_add that queues the event in a changelist. */
+int event_changelist_add(struct event_base *base, evutil_socket_t fd, short old, short events,
+    void *p);
+/** Implementation of eventop_del that queues the event in a changelist. */
+int event_changelist_del(struct event_base *base, evutil_socket_t fd, short old, short events,
+    void *p);
+
+#endif
diff --git a/libevent/compat/sys/queue.h b/libevent/compat/sys/queue.h
new file mode 100644 (file)
index 0000000..53dd10d
--- /dev/null
@@ -0,0 +1,488 @@
+/*     $OpenBSD: queue.h,v 1.16 2000/09/07 19:47:59 art Exp $  */
+/*     $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $       */
+
+/*
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. 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.
+ *
+ *     @(#)queue.h     8.5 (Berkeley) 8/20/94
+ */
+
+#ifndef        _SYS_QUEUE_H_
+#define        _SYS_QUEUE_H_
+
+/*
+ * This file defines five types of data structures: singly-linked lists,
+ * lists, simple queues, tail queues, and circular queues.
+ *
+ *
+ * A singly-linked list is headed by a single forward pointer. The elements
+ * are singly linked for minimum space and pointer manipulation overhead at
+ * the expense of O(n) removal for arbitrary elements. New elements can be
+ * added to the list after an existing element or at the head of the list.
+ * Elements being removed from the head of the list should use the explicit
+ * macro for this purpose for optimum efficiency. A singly-linked list may
+ * only be traversed in the forward direction.  Singly-linked lists are ideal
+ * for applications with large datasets and few or no removals or for
+ * implementing a LIFO queue.
+ *
+ * A list is headed by a single forward pointer (or an array of forward
+ * pointers for a hash table header). The elements are doubly linked
+ * so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before
+ * or after an existing element or at the head of the list. A list
+ * may only be traversed in the forward direction.
+ *
+ * A simple queue is headed by a pair of pointers, one the head of the
+ * list and the other to the tail of the list. The elements are singly
+ * linked to save space, so elements can only be removed from the
+ * head of the list. New elements can be added to the list before or after
+ * an existing element, at the head of the list, or at the end of the
+ * list. A simple queue may only be traversed in the forward direction.
+ *
+ * A tail queue is headed by a pair of pointers, one to the head of the
+ * list and the other to the tail of the list. The elements are doubly
+ * linked so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before or
+ * after an existing element, at the head of the list, or at the end of
+ * the list. A tail queue may be traversed in either direction.
+ *
+ * A circle queue is headed by a pair of pointers, one to the head of the
+ * list and the other to the tail of the list. The elements are doubly
+ * linked so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before or after
+ * an existing element, at the head of the list, or at the end of the list.
+ * A circle queue may be traversed in either direction, but has a more
+ * complex end of list detection.
+ *
+ * For details on the use of these macros, see the queue(3) manual page.
+ */
+
+/*
+ * Singly-linked List definitions.
+ */
+#define SLIST_HEAD(name, type)                                         \
+struct name {                                                          \
+       struct type *slh_first; /* first element */                     \
+}
+
+#define        SLIST_HEAD_INITIALIZER(head)                                    \
+       { NULL }
+
+#ifndef WIN32
+#define SLIST_ENTRY(type)                                              \
+struct {                                                               \
+       struct type *sle_next;  /* next element */                      \
+}
+#endif
+
+/*
+ * Singly-linked List access methods.
+ */
+#define        SLIST_FIRST(head)       ((head)->slh_first)
+#define        SLIST_END(head)         NULL
+#define        SLIST_EMPTY(head)       (SLIST_FIRST(head) == SLIST_END(head))
+#define        SLIST_NEXT(elm, field)  ((elm)->field.sle_next)
+
+#define        SLIST_FOREACH(var, head, field)                                 \
+       for((var) = SLIST_FIRST(head);                                  \
+           (var) != SLIST_END(head);                                   \
+           (var) = SLIST_NEXT(var, field))
+
+/*
+ * Singly-linked List functions.
+ */
+#define        SLIST_INIT(head) {                                              \
+       SLIST_FIRST(head) = SLIST_END(head);                            \
+}
+
+#define        SLIST_INSERT_AFTER(slistelm, elm, field) do {                   \
+       (elm)->field.sle_next = (slistelm)->field.sle_next;             \
+       (slistelm)->field.sle_next = (elm);                             \
+} while (0)
+
+#define        SLIST_INSERT_HEAD(head, elm, field) do {                        \
+       (elm)->field.sle_next = (head)->slh_first;                      \
+       (head)->slh_first = (elm);                                      \
+} while (0)
+
+#define        SLIST_REMOVE_HEAD(head, field) do {                             \
+       (head)->slh_first = (head)->slh_first->field.sle_next;          \
+} while (0)
+
+/*
+ * List definitions.
+ */
+#define LIST_HEAD(name, type)                                          \
+struct name {                                                          \
+       struct type *lh_first;  /* first element */                     \
+}
+
+#define LIST_HEAD_INITIALIZER(head)                                    \
+       { NULL }
+
+#define LIST_ENTRY(type)                                               \
+struct {                                                               \
+       struct type *le_next;   /* next element */                      \
+       struct type **le_prev;  /* address of previous next element */  \
+}
+
+/*
+ * List access methods
+ */
+#define        LIST_FIRST(head)                ((head)->lh_first)
+#define        LIST_END(head)                  NULL
+#define        LIST_EMPTY(head)                (LIST_FIRST(head) == LIST_END(head))
+#define        LIST_NEXT(elm, field)           ((elm)->field.le_next)
+
+#define LIST_FOREACH(var, head, field)                                 \
+       for((var) = LIST_FIRST(head);                                   \
+           (var)!= LIST_END(head);                                     \
+           (var) = LIST_NEXT(var, field))
+
+/*
+ * List functions.
+ */
+#define        LIST_INIT(head) do {                                            \
+       LIST_FIRST(head) = LIST_END(head);                              \
+} while (0)
+
+#define LIST_INSERT_AFTER(listelm, elm, field) do {                    \
+       if (((elm)->field.le_next = (listelm)->field.le_next) != NULL)  \
+               (listelm)->field.le_next->field.le_prev =               \
+                   &(elm)->field.le_next;                              \
+       (listelm)->field.le_next = (elm);                               \
+       (elm)->field.le_prev = &(listelm)->field.le_next;               \
+} while (0)
+
+#define        LIST_INSERT_BEFORE(listelm, elm, field) do {                    \
+       (elm)->field.le_prev = (listelm)->field.le_prev;                \
+       (elm)->field.le_next = (listelm);                               \
+       *(listelm)->field.le_prev = (elm);                              \
+       (listelm)->field.le_prev = &(elm)->field.le_next;               \
+} while (0)
+
+#define LIST_INSERT_HEAD(head, elm, field) do {                                \
+       if (((elm)->field.le_next = (head)->lh_first) != NULL)          \
+               (head)->lh_first->field.le_prev = &(elm)->field.le_next;\
+       (head)->lh_first = (elm);                                       \
+       (elm)->field.le_prev = &(head)->lh_first;                       \
+} while (0)
+
+#define LIST_REMOVE(elm, field) do {                                   \
+       if ((elm)->field.le_next != NULL)                               \
+               (elm)->field.le_next->field.le_prev =                   \
+                   (elm)->field.le_prev;                               \
+       *(elm)->field.le_prev = (elm)->field.le_next;                   \
+} while (0)
+
+#define LIST_REPLACE(elm, elm2, field) do {                            \
+       if (((elm2)->field.le_next = (elm)->field.le_next) != NULL)     \
+               (elm2)->field.le_next->field.le_prev =                  \
+                   &(elm2)->field.le_next;                             \
+       (elm2)->field.le_prev = (elm)->field.le_prev;                   \
+       *(elm2)->field.le_prev = (elm2);                                \
+} while (0)
+
+/*
+ * Simple queue definitions.
+ */
+#define SIMPLEQ_HEAD(name, type)                                       \
+struct name {                                                          \
+       struct type *sqh_first; /* first element */                     \
+       struct type **sqh_last; /* addr of last next element */         \
+}
+
+#define SIMPLEQ_HEAD_INITIALIZER(head)                                 \
+       { NULL, &(head).sqh_first }
+
+#define SIMPLEQ_ENTRY(type)                                            \
+struct {                                                               \
+       struct type *sqe_next;  /* next element */                      \
+}
+
+/*
+ * Simple queue access methods.
+ */
+#define        SIMPLEQ_FIRST(head)         ((head)->sqh_first)
+#define        SIMPLEQ_END(head)           NULL
+#define        SIMPLEQ_EMPTY(head)         (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head))
+#define        SIMPLEQ_NEXT(elm, field)    ((elm)->field.sqe_next)
+
+#define SIMPLEQ_FOREACH(var, head, field)                              \
+       for((var) = SIMPLEQ_FIRST(head);                                \
+           (var) != SIMPLEQ_END(head);                                 \
+           (var) = SIMPLEQ_NEXT(var, field))
+
+/*
+ * Simple queue functions.
+ */
+#define        SIMPLEQ_INIT(head) do {                                         \
+       (head)->sqh_first = NULL;                                       \
+       (head)->sqh_last = &(head)->sqh_first;                          \
+} while (0)
+
+#define SIMPLEQ_INSERT_HEAD(head, elm, field) do {                     \
+       if (((elm)->field.sqe_next = (head)->sqh_first) == NULL)        \
+               (head)->sqh_last = &(elm)->field.sqe_next;              \
+       (head)->sqh_first = (elm);                                      \
+} while (0)
+
+#define SIMPLEQ_INSERT_TAIL(head, elm, field) do {                     \
+       (elm)->field.sqe_next = NULL;                                   \
+       *(head)->sqh_last = (elm);                                      \
+       (head)->sqh_last = &(elm)->field.sqe_next;                      \
+} while (0)
+
+#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do {           \
+       if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\
+               (head)->sqh_last = &(elm)->field.sqe_next;              \
+       (listelm)->field.sqe_next = (elm);                              \
+} while (0)
+
+#define SIMPLEQ_REMOVE_HEAD(head, elm, field) do {                     \
+       if (((head)->sqh_first = (elm)->field.sqe_next) == NULL)        \
+               (head)->sqh_last = &(head)->sqh_first;                  \
+} while (0)
+
+/*
+ * Tail queue definitions.
+ */
+#define TAILQ_HEAD(name, type)                                         \
+struct name {                                                          \
+       struct type *tqh_first; /* first element */                     \
+       struct type **tqh_last; /* addr of last next element */         \
+}
+
+#define TAILQ_HEAD_INITIALIZER(head)                                   \
+       { NULL, &(head).tqh_first }
+
+#define TAILQ_ENTRY(type)                                              \
+struct {                                                               \
+       struct type *tqe_next;  /* next element */                      \
+       struct type **tqe_prev; /* address of previous next element */  \
+}
+
+/*
+ * tail queue access methods
+ */
+#define        TAILQ_FIRST(head)               ((head)->tqh_first)
+#define        TAILQ_END(head)                 NULL
+#define        TAILQ_NEXT(elm, field)          ((elm)->field.tqe_next)
+#define TAILQ_LAST(head, headname)                                     \
+       (*(((struct headname *)((head)->tqh_last))->tqh_last))
+/* XXX */
+#define TAILQ_PREV(elm, headname, field)                               \
+       (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
+#define        TAILQ_EMPTY(head)                                               \
+       (TAILQ_FIRST(head) == TAILQ_END(head))
+
+#define TAILQ_FOREACH(var, head, field)                                        \
+       for((var) = TAILQ_FIRST(head);                                  \
+           (var) != TAILQ_END(head);                                   \
+           (var) = TAILQ_NEXT(var, field))
+
+#define TAILQ_FOREACH_REVERSE(var, head, headname, field)              \
+       for((var) = TAILQ_LAST(head, headname);                         \
+           (var) != TAILQ_END(head);                                   \
+           (var) = TAILQ_PREV(var, headname, field))
+
+/*
+ * Tail queue functions.
+ */
+#define        TAILQ_INIT(head) do {                                           \
+       (head)->tqh_first = NULL;                                       \
+       (head)->tqh_last = &(head)->tqh_first;                          \
+} while (0)
+
+#define TAILQ_INSERT_HEAD(head, elm, field) do {                       \
+       if (((elm)->field.tqe_next = (head)->tqh_first) != NULL)        \
+               (head)->tqh_first->field.tqe_prev =                     \
+                   &(elm)->field.tqe_next;                             \
+       else                                                            \
+               (head)->tqh_last = &(elm)->field.tqe_next;              \
+       (head)->tqh_first = (elm);                                      \
+       (elm)->field.tqe_prev = &(head)->tqh_first;                     \
+} while (0)
+
+#define TAILQ_INSERT_TAIL(head, elm, field) do {                       \
+       (elm)->field.tqe_next = NULL;                                   \
+       (elm)->field.tqe_prev = (head)->tqh_last;                       \
+       *(head)->tqh_last = (elm);                                      \
+       (head)->tqh_last = &(elm)->field.tqe_next;                      \
+} while (0)
+
+#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do {             \
+       if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\
+               (elm)->field.tqe_next->field.tqe_prev =                 \
+                   &(elm)->field.tqe_next;                             \
+       else                                                            \
+               (head)->tqh_last = &(elm)->field.tqe_next;              \
+       (listelm)->field.tqe_next = (elm);                              \
+       (elm)->field.tqe_prev = &(listelm)->field.tqe_next;             \
+} while (0)
+
+#define        TAILQ_INSERT_BEFORE(listelm, elm, field) do {                   \
+       (elm)->field.tqe_prev = (listelm)->field.tqe_prev;              \
+       (elm)->field.tqe_next = (listelm);                              \
+       *(listelm)->field.tqe_prev = (elm);                             \
+       (listelm)->field.tqe_prev = &(elm)->field.tqe_next;             \
+} while (0)
+
+#define TAILQ_REMOVE(head, elm, field) do {                            \
+       if (((elm)->field.tqe_next) != NULL)                            \
+               (elm)->field.tqe_next->field.tqe_prev =                 \
+                   (elm)->field.tqe_prev;                              \
+       else                                                            \
+               (head)->tqh_last = (elm)->field.tqe_prev;               \
+       *(elm)->field.tqe_prev = (elm)->field.tqe_next;                 \
+} while (0)
+
+#define TAILQ_REPLACE(head, elm, elm2, field) do {                     \
+       if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL)   \
+               (elm2)->field.tqe_next->field.tqe_prev =                \
+                   &(elm2)->field.tqe_next;                            \
+       else                                                            \
+               (head)->tqh_last = &(elm2)->field.tqe_next;             \
+       (elm2)->field.tqe_prev = (elm)->field.tqe_prev;                 \
+       *(elm2)->field.tqe_prev = (elm2);                               \
+} while (0)
+
+/*
+ * Circular queue definitions.
+ */
+#define CIRCLEQ_HEAD(name, type)                                       \
+struct name {                                                          \
+       struct type *cqh_first;         /* first element */             \
+       struct type *cqh_last;          /* last element */              \
+}
+
+#define CIRCLEQ_HEAD_INITIALIZER(head)                                 \
+       { CIRCLEQ_END(&head), CIRCLEQ_END(&head) }
+
+#define CIRCLEQ_ENTRY(type)                                            \
+struct {                                                               \
+       struct type *cqe_next;          /* next element */              \
+       struct type *cqe_prev;          /* previous element */          \
+}
+
+/*
+ * Circular queue access methods
+ */
+#define        CIRCLEQ_FIRST(head)             ((head)->cqh_first)
+#define        CIRCLEQ_LAST(head)              ((head)->cqh_last)
+#define        CIRCLEQ_END(head)               ((void *)(head))
+#define        CIRCLEQ_NEXT(elm, field)        ((elm)->field.cqe_next)
+#define        CIRCLEQ_PREV(elm, field)        ((elm)->field.cqe_prev)
+#define        CIRCLEQ_EMPTY(head)                                             \
+       (CIRCLEQ_FIRST(head) == CIRCLEQ_END(head))
+
+#define CIRCLEQ_FOREACH(var, head, field)                              \
+       for((var) = CIRCLEQ_FIRST(head);                                \
+           (var) != CIRCLEQ_END(head);                                 \
+           (var) = CIRCLEQ_NEXT(var, field))
+
+#define CIRCLEQ_FOREACH_REVERSE(var, head, field)                      \
+       for((var) = CIRCLEQ_LAST(head);                                 \
+           (var) != CIRCLEQ_END(head);                                 \
+           (var) = CIRCLEQ_PREV(var, field))
+
+/*
+ * Circular queue functions.
+ */
+#define        CIRCLEQ_INIT(head) do {                                         \
+       (head)->cqh_first = CIRCLEQ_END(head);                          \
+       (head)->cqh_last = CIRCLEQ_END(head);                           \
+} while (0)
+
+#define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do {           \
+       (elm)->field.cqe_next = (listelm)->field.cqe_next;              \
+       (elm)->field.cqe_prev = (listelm);                              \
+       if ((listelm)->field.cqe_next == CIRCLEQ_END(head))             \
+               (head)->cqh_last = (elm);                               \
+       else                                                            \
+               (listelm)->field.cqe_next->field.cqe_prev = (elm);      \
+       (listelm)->field.cqe_next = (elm);                              \
+} while (0)
+
+#define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do {          \
+       (elm)->field.cqe_next = (listelm);                              \
+       (elm)->field.cqe_prev = (listelm)->field.cqe_prev;              \
+       if ((listelm)->field.cqe_prev == CIRCLEQ_END(head))             \
+               (head)->cqh_first = (elm);                              \
+       else                                                            \
+               (listelm)->field.cqe_prev->field.cqe_next = (elm);      \
+       (listelm)->field.cqe_prev = (elm);                              \
+} while (0)
+
+#define CIRCLEQ_INSERT_HEAD(head, elm, field) do {                     \
+       (elm)->field.cqe_next = (head)->cqh_first;                      \
+       (elm)->field.cqe_prev = CIRCLEQ_END(head);                      \
+       if ((head)->cqh_last == CIRCLEQ_END(head))                      \
+               (head)->cqh_last = (elm);                               \
+       else                                                            \
+               (head)->cqh_first->field.cqe_prev = (elm);              \
+       (head)->cqh_first = (elm);                                      \
+} while (0)
+
+#define CIRCLEQ_INSERT_TAIL(head, elm, field) do {                     \
+       (elm)->field.cqe_next = CIRCLEQ_END(head);                      \
+       (elm)->field.cqe_prev = (head)->cqh_last;                       \
+       if ((head)->cqh_first == CIRCLEQ_END(head))                     \
+               (head)->cqh_first = (elm);                              \
+       else                                                            \
+               (head)->cqh_last->field.cqe_next = (elm);               \
+       (head)->cqh_last = (elm);                                       \
+} while (0)
+
+#define        CIRCLEQ_REMOVE(head, elm, field) do {                           \
+       if ((elm)->field.cqe_next == CIRCLEQ_END(head))                 \
+               (head)->cqh_last = (elm)->field.cqe_prev;               \
+       else                                                            \
+               (elm)->field.cqe_next->field.cqe_prev =                 \
+                   (elm)->field.cqe_prev;                              \
+       if ((elm)->field.cqe_prev == CIRCLEQ_END(head))                 \
+               (head)->cqh_first = (elm)->field.cqe_next;              \
+       else                                                            \
+               (elm)->field.cqe_prev->field.cqe_next =                 \
+                   (elm)->field.cqe_next;                              \
+} while (0)
+
+#define CIRCLEQ_REPLACE(head, elm, elm2, field) do {                   \
+       if (((elm2)->field.cqe_next = (elm)->field.cqe_next) ==         \
+           CIRCLEQ_END(head))                                          \
+               (head).cqh_last = (elm2);                               \
+       else                                                            \
+               (elm2)->field.cqe_next->field.cqe_prev = (elm2);        \
+       if (((elm2)->field.cqe_prev = (elm)->field.cqe_prev) ==         \
+           CIRCLEQ_END(head))                                          \
+               (head).cqh_first = (elm2);                              \
+       else                                                            \
+               (elm2)->field.cqe_prev->field.cqe_next = (elm2);        \
+} while (0)
+
+#endif /* !_SYS_QUEUE_H_ */
diff --git a/libevent/configure.in b/libevent/configure.in
new file mode 100644 (file)
index 0000000..285637b
--- /dev/null
@@ -0,0 +1,796 @@
+dnl configure.in for libevent
+dnl Copyright 2000-2007 Niels Provos
+dnl Copyright 2007-2012 Niels Provos and Nick Mathewson
+dnl
+dnl See LICENSE for copying information.
+dnl
+dnl Original version Dug Song <dugsong@monkey.org>
+
+AC_PREREQ(2.59c)
+AC_INIT(event.c)
+
+AC_CONFIG_MACRO_DIR([m4])
+
+AM_INIT_AUTOMAKE(libevent,2.0.18-stable)
+dnl Enable silent Automake rules if present                                                                           
+m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])])
+AM_CONFIG_HEADER(config.h)
+AC_DEFINE(NUMERIC_VERSION, 0x02001200, [Numeric representation of the version])
+
+dnl Initialize prefix.
+if test "$prefix" = "NONE"; then
+   prefix="/usr/local"
+fi
+
+AC_CANONICAL_BUILD
+AC_CANONICAL_HOST
+dnl the 'build' machine is where we run configure and compile
+dnl the 'host' machine is where the resulting stuff runs.
+
+case "$host_os" in
+
+ osf5*)
+    CFLAGS="$CFLAGS -D_OSF_SOURCE"
+    ;;
+esac
+
+dnl Checks for programs.
+AC_PROG_CC
+AM_PROG_CC_C_O
+AC_PROG_INSTALL
+AC_PROG_LN_S
+AC_PROG_MKDIR_P
+
+AC_PROG_GCC_TRADITIONAL
+
+if test "$GCC" = "yes" ; then
+        # Enable many gcc warnings by default...
+        CFLAGS="$CFLAGS -Wall"
+       # And disable the strict-aliasing optimization, since it breaks
+       # our sockaddr-handling code in strange ways.
+       CFLAGS="$CFLAGS -fno-strict-aliasing"
+fi
+
+# OS X Lion started deprecating the system openssl. Let's just disable
+# all deprecation warnings on OS X.
+case "$host_os" in
+
+ darwin*)
+    CFLAGS="$CFLAGS -Wno-deprecated-declarations"
+    ;;
+esac
+
+AC_ARG_ENABLE(gcc-warnings,
+     AS_HELP_STRING(--enable-gcc-warnings, enable verbose warnings with GCC))
+AC_ARG_ENABLE(thread-support,
+     AS_HELP_STRING(--disable-thread-support, disable support for threading),
+       [], [enable_thread_support=yes])
+AC_ARG_ENABLE(malloc-replacement,
+     AS_HELP_STRING(--disable-malloc-replacement, disable support for replacing the memory mgt functions),
+        [], [enable_malloc_replacement=yes])
+AC_ARG_ENABLE(openssl,
+     AS_HELP_STRING(--disable-openssl, disable support for openssl encryption),
+        [], [enable_openssl=yes])
+AC_ARG_ENABLE(debug-mode,
+     AS_HELP_STRING(--disable-debug-mode, disable support for running in debug mode),
+        [], [enable_debug_mode=yes])
+AC_ARG_ENABLE([libevent-install],
+     AS_HELP_STRING([--disable-libevent-install, disable installation of libevent]),
+       [], [enable_libevent_install=yes])
+AC_ARG_ENABLE([libevent-regress],
+     AS_HELP_STRING([--disable-libevent-regress, skip regress in make check]),
+       [], [enable_libevent_regress=yes])
+AC_ARG_ENABLE([function-sections],
+     AS_HELP_STRING([--enable-function-sections, make static library allow smaller binaries with --gc-sections]),
+       [], [enable_function_sections=no])
+
+
+AC_PROG_LIBTOOL
+
+dnl   Uncomment "AC_DISABLE_SHARED" to make shared librraries not get
+dnl   built by default.  You can also turn shared libs on and off from
+dnl   the command line with --enable-shared and --disable-shared.
+dnl AC_DISABLE_SHARED
+AC_SUBST(LIBTOOL_DEPS)
+
+AM_CONDITIONAL([BUILD_REGRESS], [test "$enable_libevent_regress" = "yes"])
+
+dnl Checks for libraries.
+AC_SEARCH_LIBS([inet_ntoa], [nsl])
+AC_SEARCH_LIBS([socket], [socket])
+AC_SEARCH_LIBS([inet_aton], [resolv])
+AC_SEARCH_LIBS([clock_gettime], [rt])
+AC_SEARCH_LIBS([sendfile], [sendfile])
+
+dnl - check if the macro WIN32 is defined on this compiler.
+dnl - (this is how we check for a windows version of GCC)
+AC_MSG_CHECKING(for WIN32)
+AC_TRY_COMPILE(,
+       [
+#ifndef WIN32
+die horribly
+#endif
+       ],
+       bwin32=true; AC_MSG_RESULT(yes),
+       bwin32=false; AC_MSG_RESULT(no),
+)
+
+dnl - check if the macro __CYGWIN__ is defined on this compiler.
+dnl - (this is how we check for a cygwin version of GCC)
+AC_MSG_CHECKING(for CYGWIN)
+AC_TRY_COMPILE(,
+       [
+#ifndef __CYGWIN__
+die horribly
+#endif
+       ],
+       cygwin=true; AC_MSG_RESULT(yes),
+       cygwin=false; AC_MSG_RESULT(no),
+)
+
+AC_CHECK_HEADERS([zlib.h])
+
+if test "x$ac_cv_header_zlib_h" = "xyes"; then
+dnl Determine if we have zlib for regression tests
+dnl Don't put this one in LIBS
+save_LIBS="$LIBS"
+LIBS=""
+ZLIB_LIBS=""
+have_zlib=no
+AC_SEARCH_LIBS([inflateEnd], [z],
+       [have_zlib=yes
+       ZLIB_LIBS="$LIBS"
+       AC_DEFINE(HAVE_LIBZ, 1, [Define if the system has zlib])])
+LIBS="$save_LIBS"
+AC_SUBST(ZLIB_LIBS)
+fi
+AM_CONDITIONAL(ZLIB_REGRESS, [test "$have_zlib" = "yes"])
+
+dnl See if we have openssl.  This doesn't go in LIBS either.
+if test "$bwin32" = true; then
+  EV_LIB_WS32=-lws2_32
+  EV_LIB_GDI=-lgdi32
+else
+  EV_LIB_WS32=
+  EV_LIB_GDI=
+fi
+AC_SUBST(EV_LIB_WS32)
+AC_SUBST(EV_LIB_GDI)
+AC_SUBST(OPENSSL_LIBADD)
+
+AC_CHECK_HEADERS([openssl/bio.h])
+
+if test "$enable_openssl" = "yes"; then
+save_LIBS="$LIBS"
+LIBS=""
+OPENSSL_LIBS=""
+have_openssl=no
+AC_SEARCH_LIBS([SSL_new], [ssl],
+       [have_openssl=yes
+       OPENSSL_LIBS="$LIBS -lcrypto $EV_LIB_GDI $EV_LIB_WS32 $OPENSSL_LIBADD"
+       AC_DEFINE(HAVE_OPENSSL, 1, [Define if the system has openssl])],
+       [have_openssl=no],
+       [-lcrypto $EV_LIB_GDI $EV_LIB_WS32 $OPENSSL_LIBADD])
+LIBS="$save_LIBS"
+AC_SUBST(OPENSSL_LIBS)
+fi
+
+dnl Checks for header files.
+AC_HEADER_STDC
+AC_CHECK_HEADERS([fcntl.h stdarg.h inttypes.h stdint.h stddef.h poll.h unistd.h sys/epoll.h sys/time.h sys/queue.h sys/event.h sys/param.h sys/ioctl.h sys/select.h sys/devpoll.h port.h netinet/in.h netinet/in6.h sys/socket.h sys/uio.h arpa/inet.h sys/eventfd.h sys/mman.h sys/sendfile.h sys/wait.h netdb.h])
+AC_CHECK_HEADERS(sys/sysctl.h, [], [], [
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+])
+if test "x$ac_cv_header_sys_queue_h" = "xyes"; then
+       AC_MSG_CHECKING(for TAILQ_FOREACH in sys/queue.h)
+       AC_EGREP_CPP(yes,
+[
+#include <sys/queue.h>
+#ifdef TAILQ_FOREACH
+ yes
+#endif
+],     [AC_MSG_RESULT(yes)
+        AC_DEFINE(HAVE_TAILQFOREACH, 1,
+               [Define if TAILQ_FOREACH is defined in <sys/queue.h>])],
+       AC_MSG_RESULT(no)
+       )
+fi
+
+if test "x$ac_cv_header_sys_time_h" = "xyes"; then
+       AC_MSG_CHECKING(for timeradd in sys/time.h)
+       AC_EGREP_CPP(yes,
+[
+#include <sys/time.h>
+#ifdef timeradd
+ yes
+#endif
+],     [ AC_DEFINE(HAVE_TIMERADD, 1,
+               [Define if timeradd is defined in <sys/time.h>])
+         AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
+)
+fi
+
+if test "x$ac_cv_header_sys_time_h" = "xyes"; then
+       AC_MSG_CHECKING(for timercmp in sys/time.h)
+       AC_EGREP_CPP(yes,
+[
+#include <sys/time.h>
+#ifdef timercmp
+ yes
+#endif
+],     [ AC_DEFINE(HAVE_TIMERCMP, 1,
+               [Define if timercmp is defined in <sys/time.h>])
+         AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
+)
+fi
+
+if test "x$ac_cv_header_sys_time_h" = "xyes"; then
+       AC_MSG_CHECKING(for timerclear in sys/time.h)
+       AC_EGREP_CPP(yes,
+[
+#include <sys/time.h>
+#ifdef timerclear
+ yes
+#endif
+],     [ AC_DEFINE(HAVE_TIMERCLEAR, 1,
+               [Define if timerclear is defined in <sys/time.h>])
+         AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
+)
+fi
+
+if test "x$ac_cv_header_sys_time_h" = "xyes"; then
+       AC_MSG_CHECKING(for timerisset in sys/time.h)
+       AC_EGREP_CPP(yes,
+[
+#include <sys/time.h>
+#ifdef timerisset
+ yes
+#endif
+],     [ AC_DEFINE(HAVE_TIMERISSET, 1,
+               [Define if timerisset is defined in <sys/time.h>])
+         AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
+)
+fi
+
+if test "x$ac_cv_header_sys_sysctl_h" = "xyes"; then
+       AC_CHECK_DECLS([CTL_KERN, KERN_RANDOM, RANDOM_UUID, KERN_ARND], [], [],
+          [[#include <sys/types.h>
+            #include <sys/sysctl.h>]]
+       )
+fi
+
+AM_CONDITIONAL(BUILD_WIN32, test x$bwin32 = xtrue)
+AM_CONDITIONAL(BUILD_CYGWIN, test x$cygwin = xtrue)
+AM_CONDITIONAL(BUILD_WITH_NO_UNDEFINED, test x$bwin32 = xtrue || test x$cygwin = xtrue)
+
+if test x$bwin32 = xtrue; then
+   AC_SEARCH_LIBS([getservbyname],[ws2_32])
+fi
+
+dnl Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_C_INLINE
+AC_HEADER_TIME
+
+dnl Checks for library functions.
+AC_CHECK_FUNCS([gettimeofday vasprintf fcntl clock_gettime strtok_r strsep])
+AC_CHECK_FUNCS([getnameinfo strlcpy inet_ntop inet_pton signal sigaction strtoll inet_aton pipe eventfd sendfile mmap splice arc4random arc4random_buf issetugid geteuid getegid getprotobynumber setenv unsetenv putenv sysctl])
+
+AC_CACHE_CHECK(
+    [for getaddrinfo],
+    [libevent_cv_getaddrinfo],
+    [AC_LINK_IFELSE(
+       [AC_LANG_PROGRAM(
+           [[
+               #ifdef HAVE_NETDB_H
+               #include <netdb.h>
+               #endif
+           ]],
+           [[
+               getaddrinfo;
+           ]]
+       )],
+       [libevent_cv_getaddrinfo=yes],
+       [libevent_cv_getaddrinfo=no]
+    )]
+)
+if test "$libevent_cv_getaddrinfo" = "yes" ; then
+    AC_DEFINE([HAVE_GETADDRINFO], [1], [Do we have getaddrinfo()?])
+else
+
+AC_CHECK_FUNCS([getservbyname])
+# Check for gethostbyname_r in all its glorious incompatible versions.
+#   (This is cut-and-pasted from Tor, which based its logic on
+#   Python's configure.in.)
+AH_TEMPLATE(HAVE_GETHOSTBYNAME_R,
+  [Define this if you have any gethostbyname_r()])
+
+AC_CHECK_FUNC(gethostbyname_r, [
+  AC_MSG_CHECKING([how many arguments gethostbyname_r() wants])
+  OLD_CFLAGS=$CFLAGS
+  CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS"
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
+#include <netdb.h>
+  ], [[
+    char *cp1, *cp2;
+    struct hostent *h1, *h2;
+    int i1, i2;
+    (void)gethostbyname_r(cp1,h1,cp2,i1,&h2,&i2);
+  ]])],[
+    AC_DEFINE(HAVE_GETHOSTBYNAME_R)
+    AC_DEFINE(HAVE_GETHOSTBYNAME_R_6_ARG, 1,
+     [Define this if gethostbyname_r takes 6 arguments])
+    AC_MSG_RESULT(6)
+  ], [
+    AC_TRY_COMPILE([
+#include <netdb.h>
+    ], [
+      char *cp1, *cp2;
+      struct hostent *h1;
+      int i1, i2;
+      (void)gethostbyname_r(cp1,h1,cp2,i1,&i2);
+    ], [
+      AC_DEFINE(HAVE_GETHOSTBYNAME_R)
+      AC_DEFINE(HAVE_GETHOSTBYNAME_R_5_ARG, 1,
+        [Define this if gethostbyname_r takes 5 arguments])
+      AC_MSG_RESULT(5)
+   ], [
+      AC_TRY_COMPILE([
+#include <netdb.h>
+     ], [
+       char *cp1;
+       struct hostent *h1;
+       struct hostent_data hd;
+       (void) gethostbyname_r(cp1,h1,&hd);
+     ], [
+       AC_DEFINE(HAVE_GETHOSTBYNAME_R)
+       AC_DEFINE(HAVE_GETHOSTBYNAME_R_3_ARG, 1,
+         [Define this if gethostbyname_r takes 3 arguments])
+       AC_MSG_RESULT(3)
+     ], [
+       AC_MSG_RESULT(0)
+     ])
+  ])
+ ])
+ CFLAGS=$OLD_CFLAGS
+])
+
+fi
+
+AC_CHECK_SIZEOF(long)
+
+AC_MSG_CHECKING(for F_SETFD in fcntl.h)
+AC_EGREP_CPP(yes,
+[
+#define _GNU_SOURCE
+#include <fcntl.h>
+#ifdef F_SETFD
+yes
+#endif
+],     [ AC_DEFINE(HAVE_SETFD, 1,
+             [Define if F_SETFD is defined in <fcntl.h>])
+         AC_MSG_RESULT(yes) ], AC_MSG_RESULT(no))
+
+needsignal=no
+haveselect=no
+if test x$bwin32 != xtrue; then
+    AC_CHECK_FUNCS(select, [haveselect=yes], )
+    if test "x$haveselect" = "xyes" ; then
+       needsignal=yes
+    fi
+fi
+AM_CONDITIONAL(SELECT_BACKEND, [test "x$haveselect" = "xyes"])
+
+havepoll=no
+AC_CHECK_FUNCS(poll, [havepoll=yes], )
+if test "x$havepoll" = "xyes" ; then
+       needsignal=yes
+fi
+AM_CONDITIONAL(POLL_BACKEND, [test "x$havepoll" = "xyes"])
+
+havedevpoll=no
+if test "x$ac_cv_header_sys_devpoll_h" = "xyes"; then
+       AC_DEFINE(HAVE_DEVPOLL, 1,
+                   [Define if /dev/poll is available])
+fi
+AM_CONDITIONAL(DEVPOLL_BACKEND, [test "x$ac_cv_header_sys_devpoll_h" = "xyes"])
+
+havekqueue=no
+if test "x$ac_cv_header_sys_event_h" = "xyes"; then
+       AC_CHECK_FUNCS(kqueue, [havekqueue=yes], )
+       if test "x$havekqueue" = "xyes" ; then
+               AC_MSG_CHECKING(for working kqueue)
+               AC_TRY_RUN(
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/event.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+int
+main(int argc, char **argv)
+{
+       int kq;
+       int n;
+       int fd[[2]];
+       struct kevent ev;
+       struct timespec ts;
+       char buf[[8000]];
+
+       if (pipe(fd) == -1)
+               exit(1);
+       if (fcntl(fd[[1]], F_SETFL, O_NONBLOCK) == -1)
+               exit(1);
+
+       while ((n = write(fd[[1]], buf, sizeof(buf))) == sizeof(buf))
+               ;
+
+        if ((kq = kqueue()) == -1)
+               exit(1);
+
+       memset(&ev, 0, sizeof(ev));
+       ev.ident = fd[[1]];
+       ev.filter = EVFILT_WRITE;
+       ev.flags = EV_ADD | EV_ENABLE;
+       n = kevent(kq, &ev, 1, NULL, 0, NULL);
+       if (n == -1)
+               exit(1);
+
+       read(fd[[0]], buf, sizeof(buf));
+
+       ts.tv_sec = 0;
+       ts.tv_nsec = 0;
+       n = kevent(kq, NULL, 0, &ev, 1, &ts);
+       if (n == -1 || n == 0)
+               exit(1);
+
+       exit(0);
+}, [AC_MSG_RESULT(yes)
+    AC_DEFINE(HAVE_WORKING_KQUEUE, 1,
+               [Define if kqueue works correctly with pipes])
+    havekqueue=yes
+    ], AC_MSG_RESULT(no), AC_MSG_RESULT(no))
+       fi
+fi
+AM_CONDITIONAL(KQUEUE_BACKEND, [test "x$havekqueue" = "xyes"])
+
+haveepollsyscall=no
+haveepoll=no
+AC_CHECK_FUNCS(epoll_ctl, [haveepoll=yes], )
+if test "x$haveepoll" = "xyes" ; then
+       AC_DEFINE(HAVE_EPOLL, 1,
+               [Define if your system supports the epoll system calls])
+       needsignal=yes
+fi
+if test "x$ac_cv_header_sys_epoll_h" = "xyes"; then
+       if test "x$haveepoll" = "xno" ; then
+               AC_MSG_CHECKING(for epoll system call)
+               AC_TRY_RUN(
+#include <stdint.h>
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <sys/epoll.h>
+#include <unistd.h>
+
+int
+epoll_create(int size)
+{
+       return (syscall(__NR_epoll_create, size));
+}
+
+int
+main(int argc, char **argv)
+{
+       int epfd;
+
+       epfd = epoll_create(256);
+       exit (epfd == -1 ? 1 : 0);
+}, [AC_MSG_RESULT(yes)
+    AC_DEFINE(HAVE_EPOLL, 1,
+       [Define if your system supports the epoll system calls])
+    needsignal=yes
+    have_epoll=yes
+    AC_LIBOBJ(epoll_sub)
+    ], AC_MSG_RESULT(no), AC_MSG_RESULT(no))
+       fi
+fi
+AM_CONDITIONAL(EPOLL_BACKEND, [test "x$haveepoll" = "xyes"])
+
+haveeventports=no
+AC_CHECK_FUNCS(port_create, [haveeventports=yes], )
+if test "x$haveeventports" = "xyes" ; then
+       AC_DEFINE(HAVE_EVENT_PORTS, 1,
+               [Define if your system supports event ports])
+       needsignal=yes
+fi
+AM_CONDITIONAL(EVPORT_BACKEND, [test "x$haveeventports" = "xyes"])
+
+if test "x$bwin32" = "xtrue"; then
+       needsignal=yes
+fi
+
+AM_CONDITIONAL(SIGNAL_SUPPORT, [test "x$needsignal" = "xyes"])
+
+AC_TYPE_PID_T
+AC_TYPE_SIZE_T
+AC_TYPE_SSIZE_T
+
+AC_CHECK_TYPES([uint64_t, uint32_t, uint16_t, uint8_t, uintptr_t], , ,
+[#ifdef HAVE_STDINT_H
+#include <stdint.h>
+#elif defined(HAVE_INTTYPES_H)
+#include <inttypes.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif])
+
+AC_CHECK_TYPES([fd_mask], , ,
+[#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif])
+
+AC_CHECK_SIZEOF(long long)
+AC_CHECK_SIZEOF(long)
+AC_CHECK_SIZEOF(int)
+AC_CHECK_SIZEOF(short)
+AC_CHECK_SIZEOF(size_t)
+AC_CHECK_SIZEOF(void *)
+
+AC_CHECK_TYPES([struct in6_addr, struct sockaddr_in6, sa_family_t, struct addrinfo, struct sockaddr_storage], , ,
+[#define _GNU_SOURCE
+#include <sys/types.h>
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef WIN32
+#define WIN32_WINNT 0x400
+#define _WIN32_WINNT 0x400
+#define WIN32_LEAN_AND_MEAN
+#if defined(_MSC_VER) && (_MSC_VER < 1300)
+#include <winsock.h>
+#else
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#endif
+])
+AC_CHECK_MEMBERS([struct in6_addr.s6_addr32, struct in6_addr.s6_addr16, struct sockaddr_in.sin_len, struct sockaddr_in6.sin6_len, struct sockaddr_storage.ss_family, struct sockaddr_storage.__ss_family], , ,
+[#include <sys/types.h>
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef WIN32
+#define WIN32_WINNT 0x400
+#define _WIN32_WINNT 0x400
+#define WIN32_LEAN_AND_MEAN
+#if defined(_MSC_VER) && (_MSC_VER < 1300)
+#include <winsock.h>
+#else
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#endif
+])
+
+AC_MSG_CHECKING([for socklen_t])
+AC_TRY_COMPILE([
+ #include <sys/types.h>
+ #include <sys/socket.h>],
+  [socklen_t x;],
+  AC_MSG_RESULT([yes]),
+  [AC_MSG_RESULT([no])
+  AC_DEFINE(socklen_t, unsigned int,
+       [Define to unsigned int if you dont have it])]
+)
+
+AC_MSG_CHECKING([whether our compiler supports __func__])
+AC_TRY_COMPILE([],
+ [ const char *cp = __func__; ],
+ AC_MSG_RESULT([yes]),
+ AC_MSG_RESULT([no])
+ AC_MSG_CHECKING([whether our compiler supports __FUNCTION__])
+ AC_TRY_COMPILE([],
+   [ const char *cp = __FUNCTION__; ],
+   AC_MSG_RESULT([yes])
+   AC_DEFINE(__func__, __FUNCTION__,
+         [Define to appropriate substitue if compiler doesnt have __func__]),
+   AC_MSG_RESULT([no])
+   AC_DEFINE(__func__, __FILE__,
+         [Define to appropriate substitue if compiler doesnt have __func__])))
+
+
+# check if we can compile with pthreads
+have_pthreads=no
+if test x$bwin32 != xtrue && test "$enable_thread_support" != "no"; then
+  ACX_PTHREAD([
+       AC_DEFINE(HAVE_PTHREADS, 1,
+               [Define if we have pthreads on this system])
+       have_pthreads=yes])
+  CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+  AC_CHECK_SIZEOF(pthread_t, ,
+     [AC_INCLUDES_DEFAULT()
+      #include <pthread.h> ]
+  )
+fi
+AM_CONDITIONAL(PTHREADS, [test "$have_pthreads" != "no" && test "$enable_thread_support" != "no"])
+
+# check if we should compile locking into the library
+if test x$enable_thread_support = xno; then
+   AC_DEFINE(DISABLE_THREAD_SUPPORT, 1,
+       [Define if libevent should not be compiled with thread support])
+fi
+
+# check if we should hard-code the mm functions.
+if test x$enable_malloc_replacement = xno; then
+  AC_DEFINE(DISABLE_MM_REPLACEMENT, 1,
+        [Define if libevent should not allow replacing the mm functions])
+fi
+
+# check if we should hard-code debugging out
+if test x$enable_debug_mode = xno; then
+  AC_DEFINE(DISABLE_DEBUG_MODE, 1,
+        [Define if libevent should build without support for a debug mode])
+fi
+
+# check if we have and should use openssl
+AM_CONDITIONAL(OPENSSL, [test "$enable_openssl" != "no" && test "$have_openssl" = "yes"])
+
+# Add some more warnings which we use in development but not in the
+# released versions.  (Some relevant gcc versions can't handle these.)
+if test x$enable_gcc_warnings = xyes && test "$GCC" = "yes"; then
+
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__GNUC__) || (__GNUC__ < 4)
+#error
+#endif])], have_gcc4=yes, have_gcc4=no)
+
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__GNUC__) || (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)
+#error
+#endif])], have_gcc42=yes, have_gcc42=no)
+
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__GNUC__) || (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)
+#error
+#endif])], have_gcc45=yes, have_gcc45=no)
+
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__clang__)
+#error
+#endif])], have_clang=yes, have_clang=no)
+
+  CFLAGS="$CFLAGS -W -Wfloat-equal -Wundef -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes -Wwrite-strings -Wredundant-decls -Wchar-subscripts -Wcomment -Wformat -Wwrite-strings -Wmissing-declarations -Wredundant-decls -Wnested-externs -Wbad-function-cast -Wswitch-enum -Werror"
+  CFLAGS="$CFLAGS -Wno-unused-parameter -Wstrict-aliasing"
+
+  if test x$have_gcc4 = xyes ; then
+    # These warnings break gcc 3.3.5 and work on gcc 4.0.2
+    CFLAGS="$CFLAGS -Winit-self -Wmissing-field-initializers -Wdeclaration-after-statement"
+    #CFLAGS="$CFLAGS -Wold-style-definition"
+  fi
+
+  if test x$have_gcc42 = xyes ; then
+    # These warnings break gcc 4.0.2 and work on gcc 4.2
+    CFLAGS="$CFLAGS -Waddress"
+  fi
+
+  if test x$have_gcc42 = xyes && test x$have_clang = xno; then
+    # These warnings break gcc 4.0.2 and clang, but work on gcc 4.2
+    CFLAGS="$CFLAGS -Wnormalized=id -Woverride-init"
+  fi
+
+  if test x$have_gcc45 = xyes ; then
+    # These warnings work on gcc 4.5
+    CFLAGS="$CFLAGS -Wlogical-op"
+  fi
+
+  if test x$have_clang = xyes; then
+    # Disable the unused-function warnings, because these trigger
+    # for minheap-internal.h related code.
+    CFLAGS="$CFLAGS -Wno-unused-function"
+  fi
+
+##This will break the world on some 64-bit architectures
+# CFLAGS="$CFLAGS -Winline"
+
+fi
+
+LIBEVENT_GC_SECTIONS=
+if test "$GCC" = yes && test "$enable_function_sections" = yes ; then
+    AC_CACHE_CHECK(
+       [if linker supports omitting unused code and data],
+       [libevent_cv_gc_sections_runs],
+       [
+           dnl  NetBSD will link but likely not run with --gc-sections
+           dnl  http://bugs.ntp.org/1844
+           dnl  http://gnats.netbsd.org/40401
+           dnl  --gc-sections causes attempt to load as linux elf, with
+           dnl  wrong syscalls in place.  Test a little gauntlet of
+           dnl  simple stdio read code checking for errors, expecting
+           dnl  enough syscall differences that the NetBSD code will
+           dnl  fail even with Linux emulation working as designed.
+           dnl  A shorter test could be refined by someone with access
+           dnl  to a NetBSD host with Linux emulation working.
+           origCFLAGS="$CFLAGS"
+           CFLAGS="$CFLAGS -Wl,--gc-sections"
+           AC_LINK_IFELSE(
+               [AC_LANG_PROGRAM(
+                   [[
+                       #include <stdlib.h>
+                       #include <stdio.h>
+                   ]],
+                   [[
+                       FILE *  fpC;
+                       char    buf[32];
+                       size_t  cch;
+                       int     read_success_once;
+
+                       fpC = fopen("conftest.c", "r");
+                       if (NULL == fpC)
+                               exit(1);
+                       do {
+                               cch = fread(buf, sizeof(buf), 1, fpC);
+                               read_success_once |= (0 != cch);
+                       } while (0 != cch);
+                       if (!read_success_once)
+                               exit(2);
+                       if (!feof(fpC))
+                               exit(3);
+                       if (0 != fclose(fpC))
+                               exit(4);
+
+                       exit(EXIT_SUCCESS);
+                   ]]
+               )],
+               [
+                    dnl We have to do this invocation manually so that we can
+                    dnl get the output of conftest.err to make sure it doesn't
+                    dnl mention gc-sections.
+                   if test "X$cross_compiling" = "Xyes" || grep gc-sections conftest.err ; then
+                       libevent_cv_gc_sections_runs=no
+                   else
+                       libevent_cv_gc_sections_runs=no
+                       ./conftest >/dev/null 2>&1 && libevent_cv_gc_sections_runs=yes
+                   fi
+               ],
+               [libevent_cv_gc_sections_runs=no]
+           )
+           CFLAGS="$origCFLAGS"
+           AS_UNSET([origCFLAGS])
+       ]
+    )
+    case "$libevent_cv_gc_sections_runs" in
+     yes)
+       CFLAGS="-ffunction-sections -fdata-sections $CFLAGS"
+       LIBEVENT_GC_SECTIONS="-Wl,--gc-sections"
+       ;;
+    esac
+fi
+AC_SUBST([LIBEVENT_GC_SECTIONS])
+
+AM_CONDITIONAL([INSTALL_LIBEVENT], [test "$enable_libevent_install" = "yes"])
+
+AC_CONFIG_FILES( [libevent.pc libevent_openssl.pc libevent_pthreads.pc] )
+AC_OUTPUT(Makefile include/Makefile test/Makefile sample/Makefile)
diff --git a/libevent/defer-internal.h b/libevent/defer-internal.h
new file mode 100644 (file)
index 0000000..96a5cac
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _DEFER_INTERNAL_H_
+#define _DEFER_INTERNAL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include <sys/queue.h>
+
+struct deferred_cb;
+
+typedef void (*deferred_cb_fn)(struct deferred_cb *, void *);
+
+/** A deferred_cb is a callback that can be scheduled to run as part of
+ * an event_base's event_loop, rather than running immediately. */
+struct deferred_cb {
+       /** Links to the adjacent active (pending) deferred_cb objects. */
+       TAILQ_ENTRY (deferred_cb) cb_next;
+       /** True iff this deferred_cb is pending in an event_base. */
+       unsigned queued : 1;
+       /** The function to execute when the callback runs. */
+       deferred_cb_fn cb;
+       /** The function's second argument. */
+       void *arg;
+};
+
+/** A deferred_cb_queue is a list of deferred_cb that we can add to and run. */
+struct deferred_cb_queue {
+       /** Lock used to protect the queue. */
+       void *lock;
+
+       /** How many entries are in the queue? */
+       int active_count;
+
+       /** Function called when adding to the queue from another thread. */
+       void (*notify_fn)(struct deferred_cb_queue *, void *);
+       void *notify_arg;
+
+       /** Deferred callback management: a list of deferred callbacks to
+        * run active the active events. */
+       TAILQ_HEAD (deferred_cb_list, deferred_cb) deferred_cb_list;
+};
+
+/**
+   Initialize an empty, non-pending deferred_cb.
+
+   @param deferred The deferred_cb structure to initialize.
+   @param cb The function to run when the deferred_cb executes.
+   @param arg The function's second argument.
+ */
+void event_deferred_cb_init(struct deferred_cb *, deferred_cb_fn, void *);
+/**
+   Cancel a deferred_cb if it is currently scheduled in an event_base.
+ */
+void event_deferred_cb_cancel(struct deferred_cb_queue *, struct deferred_cb *);
+/**
+   Activate a deferred_cb if it is not currently scheduled in an event_base.
+ */
+void event_deferred_cb_schedule(struct deferred_cb_queue *, struct deferred_cb *);
+
+#define LOCK_DEFERRED_QUEUE(q)                                         \
+       EVLOCK_LOCK((q)->lock, 0)
+#define UNLOCK_DEFERRED_QUEUE(q)                                       \
+       EVLOCK_UNLOCK((q)->lock, 0)
+
+#ifdef __cplusplus
+}
+#endif
+
+void event_deferred_cb_queue_init(struct deferred_cb_queue *);
+struct deferred_cb_queue *event_base_get_deferred_cb_queue(struct event_base *);
+
+#endif /* _EVENT_INTERNAL_H_ */
+
diff --git a/libevent/devpoll.c b/libevent/devpoll.c
new file mode 100644 (file)
index 0000000..f99cc01
--- /dev/null
@@ -0,0 +1,306 @@
+/*
+ * Copyright 2000-2009 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/resource.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <sys/devpoll.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/thread.h"
+#include "event-internal.h"
+#include "evsignal-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "evthread-internal.h"
+
+struct devpollop {
+       struct pollfd *events;
+       int nevents;
+       int dpfd;
+       struct pollfd *changes;
+       int nchanges;
+};
+
+static void *devpoll_init(struct event_base *);
+static int devpoll_add(struct event_base *, int fd, short old, short events, void *);
+static int devpoll_del(struct event_base *, int fd, short old, short events, void *);
+static int devpoll_dispatch(struct event_base *, struct timeval *);
+static void devpoll_dealloc(struct event_base *);
+
+const struct eventop devpollops = {
+       "devpoll",
+       devpoll_init,
+       devpoll_add,
+       devpoll_del,
+       devpoll_dispatch,
+       devpoll_dealloc,
+       1, /* need reinit */
+       EV_FEATURE_FDS|EV_FEATURE_O1,
+       0
+};
+
+#define NEVENT 32000
+
+static int
+devpoll_commit(struct devpollop *devpollop)
+{
+       /*
+        * Due to a bug in Solaris, we have to use pwrite with an offset of 0.
+        * Write is limited to 2GB of data, until it will fail.
+        */
+       if (pwrite(devpollop->dpfd, devpollop->changes,
+               sizeof(struct pollfd) * devpollop->nchanges, 0) == -1)
+               return (-1);
+
+       devpollop->nchanges = 0;
+       return (0);
+}
+
+static int
+devpoll_queue(struct devpollop *devpollop, int fd, int events) {
+       struct pollfd *pfd;
+
+       if (devpollop->nchanges >= devpollop->nevents) {
+               /*
+                * Change buffer is full, must commit it to /dev/poll before
+                * adding more
+                */
+               if (devpoll_commit(devpollop) != 0)
+                       return (-1);
+       }
+
+       pfd = &devpollop->changes[devpollop->nchanges++];
+       pfd->fd = fd;
+       pfd->events = events;
+       pfd->revents = 0;
+
+       return (0);
+}
+
+static void *
+devpoll_init(struct event_base *base)
+{
+       int dpfd, nfiles = NEVENT;
+       struct rlimit rl;
+       struct devpollop *devpollop;
+
+       if (!(devpollop = mm_calloc(1, sizeof(struct devpollop))))
+               return (NULL);
+
+       if (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&
+           rl.rlim_cur != RLIM_INFINITY)
+               nfiles = rl.rlim_cur;
+
+       /* Initialize the kernel queue */
+       if ((dpfd = evutil_open_closeonexec("/dev/poll", O_RDWR, 0)) == -1) {
+               event_warn("open: /dev/poll");
+               mm_free(devpollop);
+               return (NULL);
+       }
+
+       devpollop->dpfd = dpfd;
+
+       /* Initialize fields */
+       /* FIXME: allocating 'nfiles' worth of space here can be
+        * expensive and unnecessary.  See how epoll.c does it instead. */
+       devpollop->events = mm_calloc(nfiles, sizeof(struct pollfd));
+       if (devpollop->events == NULL) {
+               mm_free(devpollop);
+               close(dpfd);
+               return (NULL);
+       }
+       devpollop->nevents = nfiles;
+
+       devpollop->changes = mm_calloc(nfiles, sizeof(struct pollfd));
+       if (devpollop->changes == NULL) {
+               mm_free(devpollop->events);
+               mm_free(devpollop);
+               close(dpfd);
+               return (NULL);
+       }
+
+       evsig_init(base);
+
+       return (devpollop);
+}
+
+static int
+devpoll_dispatch(struct event_base *base, struct timeval *tv)
+{
+       struct devpollop *devpollop = base->evbase;
+       struct pollfd *events = devpollop->events;
+       struct dvpoll dvp;
+       int i, res, timeout = -1;
+
+       if (devpollop->nchanges)
+               devpoll_commit(devpollop);
+
+       if (tv != NULL)
+               timeout = tv->tv_sec * 1000 + (tv->tv_usec + 999) / 1000;
+
+       dvp.dp_fds = devpollop->events;
+       dvp.dp_nfds = devpollop->nevents;
+       dvp.dp_timeout = timeout;
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+       res = ioctl(devpollop->dpfd, DP_POLL, &dvp);
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       if (res == -1) {
+               if (errno != EINTR) {
+                       event_warn("ioctl: DP_POLL");
+                       return (-1);
+               }
+
+               return (0);
+       }
+
+       event_debug(("%s: devpoll_wait reports %d", __func__, res));
+
+       for (i = 0; i < res; i++) {
+               int which = 0;
+               int what = events[i].revents;
+
+               if (what & POLLHUP)
+                       what |= POLLIN | POLLOUT;
+               else if (what & POLLERR)
+                       what |= POLLIN | POLLOUT;
+
+               if (what & POLLIN)
+                       which |= EV_READ;
+               if (what & POLLOUT)
+                       which |= EV_WRITE;
+
+               if (!which)
+                       continue;
+
+               /* XXX(niels): not sure if this works for devpoll */
+               evmap_io_active(base, events[i].fd, which);
+       }
+
+       return (0);
+}
+
+
+static int
+devpoll_add(struct event_base *base, int fd, short old, short events, void *p)
+{
+       struct devpollop *devpollop = base->evbase;
+       int res;
+       (void)p;
+
+       /*
+        * It's not necessary to OR the existing read/write events that we
+        * are currently interested in with the new event we are adding.
+        * The /dev/poll driver ORs any new events with the existing events
+        * that it has cached for the fd.
+        */
+
+       res = 0;
+       if (events & EV_READ)
+               res |= POLLIN;
+       if (events & EV_WRITE)
+               res |= POLLOUT;
+
+       if (devpoll_queue(devpollop, fd, res) != 0)
+               return (-1);
+
+       return (0);
+}
+
+static int
+devpoll_del(struct event_base *base, int fd, short old, short events, void *p)
+{
+       struct devpollop *devpollop = base->evbase;
+       int res;
+       (void)p;
+
+       res = 0;
+       if (events & EV_READ)
+               res |= POLLIN;
+       if (events & EV_WRITE)
+               res |= POLLOUT;
+
+       /*
+        * The only way to remove an fd from the /dev/poll monitored set is
+        * to use POLLREMOVE by itself.  This removes ALL events for the fd
+        * provided so if we care about two events and are only removing one
+        * we must re-add the other event after POLLREMOVE.
+        */
+
+       if (devpoll_queue(devpollop, fd, POLLREMOVE) != 0)
+               return (-1);
+
+       if ((res & (POLLIN|POLLOUT)) != (POLLIN|POLLOUT)) {
+               /*
+                * We're not deleting all events, so we must resubmit the
+                * event that we are still interested in if one exists.
+                */
+
+               if ((res & POLLIN) && (old & EV_WRITE)) {
+                       /* Deleting read, still care about write */
+                       devpoll_queue(devpollop, fd, POLLOUT);
+               } else if ((res & POLLOUT) && (old & EV_READ)) {
+                       /* Deleting write, still care about read */
+                       devpoll_queue(devpollop, fd, POLLIN);
+               }
+       }
+
+       return (0);
+}
+
+static void
+devpoll_dealloc(struct event_base *base)
+{
+       struct devpollop *devpollop = base->evbase;
+
+       evsig_dealloc(base);
+       if (devpollop->events)
+               mm_free(devpollop->events);
+       if (devpollop->changes)
+               mm_free(devpollop->changes);
+       if (devpollop->dpfd >= 0)
+               close(devpollop->dpfd);
+
+       memset(devpollop, 0, sizeof(struct devpollop));
+       mm_free(devpollop);
+}
diff --git a/libevent/epoll.c b/libevent/epoll.c
new file mode 100644 (file)
index 0000000..4c5c3da
--- /dev/null
@@ -0,0 +1,473 @@
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <sys/resource.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <sys/epoll.h>
+#include <signal.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#ifdef _EVENT_HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#include "event-internal.h"
+#include "evsignal-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "changelist-internal.h"
+
+struct epollop {
+       struct epoll_event *events;
+       int nevents;
+       int epfd;
+};
+
+static void *epoll_init(struct event_base *);
+static int epoll_dispatch(struct event_base *, struct timeval *);
+static void epoll_dealloc(struct event_base *);
+
+static const struct eventop epollops_changelist = {
+       "epoll (with changelist)",
+       epoll_init,
+       event_changelist_add,
+       event_changelist_del,
+       epoll_dispatch,
+       epoll_dealloc,
+       1, /* need reinit */
+       EV_FEATURE_ET|EV_FEATURE_O1,
+       EVENT_CHANGELIST_FDINFO_SIZE
+};
+
+
+static int epoll_nochangelist_add(struct event_base *base, evutil_socket_t fd,
+    short old, short events, void *p);
+static int epoll_nochangelist_del(struct event_base *base, evutil_socket_t fd,
+    short old, short events, void *p);
+
+const struct eventop epollops = {
+       "epoll",
+       epoll_init,
+       epoll_nochangelist_add,
+       epoll_nochangelist_del,
+       epoll_dispatch,
+       epoll_dealloc,
+       1, /* need reinit */
+       EV_FEATURE_ET|EV_FEATURE_O1,
+       0
+};
+
+#define INITIAL_NEVENT 32
+#define MAX_NEVENT 4096
+
+/* On Linux kernels at least up to 2.6.24.4, epoll can't handle timeout
+ * values bigger than (LONG_MAX - 999ULL)/HZ.  HZ in the wild can be
+ * as big as 1000, and LONG_MAX can be as small as (1<<31)-1, so the
+ * largest number of msec we can support here is 2147482.  Let's
+ * round that down by 47 seconds.
+ */
+#define MAX_EPOLL_TIMEOUT_MSEC (35*60*1000)
+
+static void *
+epoll_init(struct event_base *base)
+{
+       int epfd;
+       struct epollop *epollop;
+
+       /* Initialize the kernel queue.  (The size field is ignored since
+        * 2.6.8.) */
+       if ((epfd = epoll_create(32000)) == -1) {
+               if (errno != ENOSYS)
+                       event_warn("epoll_create");
+               return (NULL);
+       }
+
+       evutil_make_socket_closeonexec(epfd);
+
+       if (!(epollop = mm_calloc(1, sizeof(struct epollop)))) {
+               close(epfd);
+               return (NULL);
+       }
+
+       epollop->epfd = epfd;
+
+       /* Initialize fields */
+       epollop->events = mm_calloc(INITIAL_NEVENT, sizeof(struct epoll_event));
+       if (epollop->events == NULL) {
+               mm_free(epollop);
+               close(epfd);
+               return (NULL);
+       }
+       epollop->nevents = INITIAL_NEVENT;
+
+       if ((base->flags & EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST) != 0 ||
+           ((base->flags & EVENT_BASE_FLAG_IGNORE_ENV) == 0 &&
+               evutil_getenv("EVENT_EPOLL_USE_CHANGELIST") != NULL))
+               base->evsel = &epollops_changelist;
+
+       evsig_init(base);
+
+       return (epollop);
+}
+
+static const char *
+change_to_string(int change)
+{
+       change &= (EV_CHANGE_ADD|EV_CHANGE_DEL);
+       if (change == EV_CHANGE_ADD) {
+               return "add";
+       } else if (change == EV_CHANGE_DEL) {
+               return "del";
+       } else if (change == 0) {
+               return "none";
+       } else {
+               return "???";
+       }
+}
+
+static const char *
+epoll_op_to_string(int op)
+{
+       return op == EPOLL_CTL_ADD?"ADD":
+           op == EPOLL_CTL_DEL?"DEL":
+           op == EPOLL_CTL_MOD?"MOD":
+           "???";
+}
+
+static int
+epoll_apply_one_change(struct event_base *base,
+    struct epollop *epollop,
+    const struct event_change *ch)
+{
+       struct epoll_event epev;
+       int op, events = 0;
+
+       if (1) {
+               /* The logic here is a little tricky.  If we had no events set
+                  on the fd before, we need to set op="ADD" and set
+                  events=the events we want to add.  If we had any events set
+                  on the fd before, and we want any events to remain on the
+                  fd, we need to say op="MOD" and set events=the events we
+                  want to remain.  But if we want to delete the last event,
+                  we say op="DEL" and set events=the remaining events.  What
+                  fun!
+               */
+
+               /* TODO: Turn this into a switch or a table lookup. */
+
+               if ((ch->read_change & EV_CHANGE_ADD) ||
+                   (ch->write_change & EV_CHANGE_ADD)) {
+                       /* If we are adding anything at all, we'll want to do
+                        * either an ADD or a MOD. */
+                       events = 0;
+                       op = EPOLL_CTL_ADD;
+                       if (ch->read_change & EV_CHANGE_ADD) {
+                               events |= EPOLLIN;
+                       } else if (ch->read_change & EV_CHANGE_DEL) {
+                               ;
+                       } else if (ch->old_events & EV_READ) {
+                               events |= EPOLLIN;
+                       }
+                       if (ch->write_change & EV_CHANGE_ADD) {
+                               events |= EPOLLOUT;
+                       } else if (ch->write_change & EV_CHANGE_DEL) {
+                               ;
+                       } else if (ch->old_events & EV_WRITE) {
+                               events |= EPOLLOUT;
+                       }
+                       if ((ch->read_change|ch->write_change) & EV_ET)
+                               events |= EPOLLET;
+
+                       if (ch->old_events) {
+                               /* If MOD fails, we retry as an ADD, and if
+                                * ADD fails we will retry as a MOD.  So the
+                                * only hard part here is to guess which one
+                                * will work.  As a heuristic, we'll try
+                                * MOD first if we think there were old
+                                * events and ADD if we think there were none.
+                                *
+                                * We can be wrong about the MOD if the file
+                                * has in fact been closed and re-opened.
+                                *
+                                * We can be wrong about the ADD if the
+                                * the fd has been re-created with a dup()
+                                * of the same file that it was before.
+                                */
+                               op = EPOLL_CTL_MOD;
+                       }
+               } else if ((ch->read_change & EV_CHANGE_DEL) ||
+                   (ch->write_change & EV_CHANGE_DEL)) {
+                       /* If we're deleting anything, we'll want to do a MOD
+                        * or a DEL. */
+                       op = EPOLL_CTL_DEL;
+
+                       if (ch->read_change & EV_CHANGE_DEL) {
+                               if (ch->write_change & EV_CHANGE_DEL) {
+                                       events = EPOLLIN|EPOLLOUT;
+                               } else if (ch->old_events & EV_WRITE) {
+                                       events = EPOLLOUT;
+                                       op = EPOLL_CTL_MOD;
+                               } else {
+                                       events = EPOLLIN;
+                               }
+                       } else if (ch->write_change & EV_CHANGE_DEL) {
+                               if (ch->old_events & EV_READ) {
+                                       events = EPOLLIN;
+                                       op = EPOLL_CTL_MOD;
+                               } else {
+                                       events = EPOLLOUT;
+                               }
+                       }
+               }
+
+               if (!events)
+                       return 0;
+
+               memset(&epev, 0, sizeof(epev));
+               epev.data.fd = ch->fd;
+               epev.events = events;
+               if (epoll_ctl(epollop->epfd, op, ch->fd, &epev) == -1) {
+                       if (op == EPOLL_CTL_MOD && errno == ENOENT) {
+                               /* If a MOD operation fails with ENOENT, the
+                                * fd was probably closed and re-opened.  We
+                                * should retry the operation as an ADD.
+                                */
+                               if (epoll_ctl(epollop->epfd, EPOLL_CTL_ADD, ch->fd, &epev) == -1) {
+                                       event_warn("Epoll MOD(%d) on %d retried as ADD; that failed too",
+                                           (int)epev.events, ch->fd);
+                                       return -1;
+                               } else {
+                                       event_debug(("Epoll MOD(%d) on %d retried as ADD; succeeded.",
+                                               (int)epev.events,
+                                               ch->fd));
+                               }
+                       } else if (op == EPOLL_CTL_ADD && errno == EEXIST) {
+                               /* If an ADD operation fails with EEXIST,
+                                * either the operation was redundant (as with a
+                                * precautionary add), or we ran into a fun
+                                * kernel bug where using dup*() to duplicate the
+                                * same file into the same fd gives you the same epitem
+                                * rather than a fresh one.  For the second case,
+                                * we must retry with MOD. */
+                               if (epoll_ctl(epollop->epfd, EPOLL_CTL_MOD, ch->fd, &epev) == -1) {
+                                       event_warn("Epoll ADD(%d) on %d retried as MOD; that failed too",
+                                           (int)epev.events, ch->fd);
+                                       return -1;
+                               } else {
+                                       event_debug(("Epoll ADD(%d) on %d retried as MOD; succeeded.",
+                                               (int)epev.events,
+                                               ch->fd));
+                               }
+                       } else if (op == EPOLL_CTL_DEL &&
+                           (errno == ENOENT || errno == EBADF ||
+                               errno == EPERM)) {
+                               /* If a delete fails with one of these errors,
+                                * that's fine too: we closed the fd before we
+                                * got around to calling epoll_dispatch. */
+                               event_debug(("Epoll DEL(%d) on fd %d gave %s: DEL was unnecessary.",
+                                       (int)epev.events,
+                                       ch->fd,
+                                       strerror(errno)));
+                       } else {
+                               event_warn("Epoll %s(%d) on fd %d failed.  Old events were %d; read change was %d (%s); write change was %d (%s)",
+                                   epoll_op_to_string(op),
+                                   (int)epev.events,
+                                   ch->fd,
+                                   ch->old_events,
+                                   ch->read_change,
+                                   change_to_string(ch->read_change),
+                                   ch->write_change,
+                                   change_to_string(ch->write_change));
+                               return -1;
+                       }
+               } else {
+                       event_debug(("Epoll %s(%d) on fd %d okay. [old events were %d; read change was %d; write change was %d]",
+                               epoll_op_to_string(op),
+                               (int)epev.events,
+                               (int)ch->fd,
+                               ch->old_events,
+                               ch->read_change,
+                               ch->write_change));
+               }
+       }
+       return 0;
+}
+
+static int
+epoll_apply_changes(struct event_base *base)
+{
+       struct event_changelist *changelist = &base->changelist;
+       struct epollop *epollop = base->evbase;
+       struct event_change *ch;
+
+       int r = 0;
+       int i;
+
+       for (i = 0; i < changelist->n_changes; ++i) {
+               ch = &changelist->changes[i];
+               if (epoll_apply_one_change(base, epollop, ch) < 0)
+                       r = -1;
+       }
+
+       return (r);
+}
+
+static int
+epoll_nochangelist_add(struct event_base *base, evutil_socket_t fd,
+    short old, short events, void *p)
+{
+       struct event_change ch;
+       ch.fd = fd;
+       ch.old_events = old;
+       ch.read_change = ch.write_change = 0;
+       if (events & EV_WRITE)
+               ch.write_change = EV_CHANGE_ADD |
+                   (events & EV_ET);
+       if (events & EV_READ)
+               ch.read_change = EV_CHANGE_ADD |
+                   (events & EV_ET);
+
+       return epoll_apply_one_change(base, base->evbase, &ch);
+}
+
+static int
+epoll_nochangelist_del(struct event_base *base, evutil_socket_t fd,
+    short old, short events, void *p)
+{
+       struct event_change ch;
+       ch.fd = fd;
+       ch.old_events = old;
+       ch.read_change = ch.write_change = 0;
+       if (events & EV_WRITE)
+               ch.write_change = EV_CHANGE_DEL;
+       if (events & EV_READ)
+               ch.read_change = EV_CHANGE_DEL;
+
+       return epoll_apply_one_change(base, base->evbase, &ch);
+}
+
+static int
+epoll_dispatch(struct event_base *base, struct timeval *tv)
+{
+       struct epollop *epollop = base->evbase;
+       struct epoll_event *events = epollop->events;
+       int i, res;
+       long timeout = -1;
+
+       if (tv != NULL) {
+               timeout = evutil_tv_to_msec(tv);
+               if (timeout < 0 || timeout > MAX_EPOLL_TIMEOUT_MSEC) {
+                       /* Linux kernels can wait forever if the timeout is
+                        * too big; see comment on MAX_EPOLL_TIMEOUT_MSEC. */
+                       timeout = MAX_EPOLL_TIMEOUT_MSEC;
+               }
+       }
+
+       epoll_apply_changes(base);
+       event_changelist_remove_all(&base->changelist, base);
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+       res = epoll_wait(epollop->epfd, events, epollop->nevents, timeout);
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       if (res == -1) {
+               if (errno != EINTR) {
+                       event_warn("epoll_wait");
+                       return (-1);
+               }
+
+               return (0);
+       }
+
+       event_debug(("%s: epoll_wait reports %d", __func__, res));
+       EVUTIL_ASSERT(res <= epollop->nevents);
+
+       for (i = 0; i < res; i++) {
+               int what = events[i].events;
+               short ev = 0;
+
+               if (what & (EPOLLHUP|EPOLLERR)) {
+                       ev = EV_READ | EV_WRITE;
+               } else {
+                       if (what & EPOLLIN)
+                               ev |= EV_READ;
+                       if (what & EPOLLOUT)
+                               ev |= EV_WRITE;
+               }
+
+               if (!ev)
+                       continue;
+
+               evmap_io_active(base, events[i].data.fd, ev | EV_ET);
+       }
+
+       if (res == epollop->nevents && epollop->nevents < MAX_NEVENT) {
+               /* We used all of the event space this time.  We should
+                  be ready for more events next time. */
+               int new_nevents = epollop->nevents * 2;
+               struct epoll_event *new_events;
+
+               new_events = mm_realloc(epollop->events,
+                   new_nevents * sizeof(struct epoll_event));
+               if (new_events) {
+                       epollop->events = new_events;
+                       epollop->nevents = new_nevents;
+               }
+       }
+
+       return (0);
+}
+
+
+static void
+epoll_dealloc(struct event_base *base)
+{
+       struct epollop *epollop = base->evbase;
+
+       evsig_dealloc(base);
+       if (epollop->events)
+               mm_free(epollop->events);
+       if (epollop->epfd >= 0)
+               close(epollop->epfd);
+
+       memset(epollop, 0, sizeof(struct epollop));
+       mm_free(epollop);
+}
diff --git a/libevent/epoll_sub.c b/libevent/epoll_sub.c
new file mode 100644 (file)
index 0000000..3738b26
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2003-2009 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <stdint.h>
+
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <sys/epoll.h>
+#include <unistd.h>
+
+int
+epoll_create(int size)
+{
+       return (syscall(__NR_epoll_create, size));
+}
+
+int
+epoll_ctl(int epfd, int op, int fd, struct epoll_event *event)
+{
+
+       return (syscall(__NR_epoll_ctl, epfd, op, fd, event));
+}
+
+int
+epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout)
+{
+       return (syscall(__NR_epoll_wait, epfd, events, maxevents, timeout));
+}
diff --git a/libevent/evbuffer-internal.h b/libevent/evbuffer-internal.h
new file mode 100644 (file)
index 0000000..e68a59d
--- /dev/null
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVBUFFER_INTERNAL_H_
+#define _EVBUFFER_INTERNAL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include "event2/util.h"
+#include "util-internal.h"
+#include "defer-internal.h"
+
+/* Experimental cb flag: "never deferred."  Implementation note:
+ * these callbacks may get an inaccurate view of n_del/n_added in their
+ * arguments. */
+#define EVBUFFER_CB_NODEFER 2
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+#include <sys/queue.h>
+
+/* Minimum allocation for a chain.  We define this so that we're burning no
+ * more than 5% of each allocation on overhead.  It would be nice to lose even
+ * less space, though. */
+#if _EVENT_SIZEOF_VOID_P < 8
+#define MIN_BUFFER_SIZE        512
+#else
+#define MIN_BUFFER_SIZE        1024
+#endif
+
+/** A single evbuffer callback for an evbuffer. This function will be invoked
+ * when bytes are added to or removed from the evbuffer. */
+struct evbuffer_cb_entry {
+       /** Structures to implement a doubly-linked queue of callbacks */
+       TAILQ_ENTRY(evbuffer_cb_entry) next;
+       /** The callback function to invoke when this callback is called.
+           If EVBUFFER_CB_OBSOLETE is set in flags, the cb_obsolete field is
+           valid; otherwise, cb_func is valid. */
+       union {
+               evbuffer_cb_func cb_func;
+               evbuffer_cb cb_obsolete;
+       } cb;
+       /** Argument to pass to cb. */
+       void *cbarg;
+       /** Currently set flags on this callback. */
+       ev_uint32_t flags;
+};
+
+struct bufferevent;
+struct evbuffer_chain;
+struct evbuffer {
+       /** The first chain in this buffer's linked list of chains. */
+       struct evbuffer_chain *first;
+       /** The last chain in this buffer's linked list of chains. */
+       struct evbuffer_chain *last;
+
+       /** Pointer to the next pointer pointing at the 'last_with_data' chain.
+        *
+        * To unpack:
+        *
+        * The last_with_data chain is the last chain that has any data in it.
+        * If all chains in the buffer are empty, it is the first chain.
+        * If the buffer has no chains, it is NULL.
+        *
+        * The last_with_datap pointer points at _whatever 'next' pointer_
+        * points at the last_with_datap chain.  If the last_with_data chain
+        * is the first chain, or it is NULL, then the last_with_datap pointer
+        * is &buf->first.
+        */
+       struct evbuffer_chain **last_with_datap;
+
+       /** Total amount of bytes stored in all chains.*/
+       size_t total_len;
+
+       /** Number of bytes we have added to the buffer since we last tried to
+        * invoke callbacks. */
+       size_t n_add_for_cb;
+       /** Number of bytes we have removed from the buffer since we last
+        * tried to invoke callbacks. */
+       size_t n_del_for_cb;
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       /** A lock used to mediate access to this buffer. */
+       void *lock;
+#endif
+       /** True iff we should free the lock field when we free this
+        * evbuffer. */
+       unsigned own_lock : 1;
+       /** True iff we should not allow changes to the front of the buffer
+        * (drains or prepends). */
+       unsigned freeze_start : 1;
+       /** True iff we should not allow changes to the end of the buffer
+        * (appends) */
+       unsigned freeze_end : 1;
+       /** True iff this evbuffer's callbacks are not invoked immediately
+        * upon a change in the buffer, but instead are deferred to be invoked
+        * from the event_base's loop.  Useful for preventing enormous stack
+        * overflows when we have mutually recursive callbacks, and for
+        * serializing callbacks in a single thread. */
+       unsigned deferred_cbs : 1;
+#ifdef WIN32
+       /** True iff this buffer is set up for overlapped IO. */
+       unsigned is_overlapped : 1;
+#endif
+       /** Zero or more EVBUFFER_FLAG_* bits */
+       ev_uint32_t flags;
+
+       /** Used to implement deferred callbacks. */
+       struct deferred_cb_queue *cb_queue;
+
+       /** A reference count on this evbuffer.  When the reference count
+        * reaches 0, the buffer is destroyed.  Manipulated with
+        * evbuffer_incref and evbuffer_decref_and_unlock and
+        * evbuffer_free. */
+       int refcnt;
+
+       /** A deferred_cb handle to make all of this buffer's callbacks
+        * invoked from the event loop. */
+       struct deferred_cb deferred;
+
+       /** A doubly-linked-list of callback functions */
+       TAILQ_HEAD(evbuffer_cb_queue, evbuffer_cb_entry) callbacks;
+
+       /** The parent bufferevent object this evbuffer belongs to.
+        * NULL if the evbuffer stands alone. */
+       struct bufferevent *parent;
+};
+
+/** A single item in an evbuffer. */
+struct evbuffer_chain {
+       /** points to next buffer in the chain */
+       struct evbuffer_chain *next;
+
+       /** total allocation available in the buffer field. */
+       size_t buffer_len;
+
+       /** unused space at the beginning of buffer or an offset into a
+        * file for sendfile buffers. */
+       ev_off_t misalign;
+
+       /** Offset into buffer + misalign at which to start writing.
+        * In other words, the total number of bytes actually stored
+        * in buffer. */
+       size_t off;
+
+       /** Set if special handling is required for this chain */
+       unsigned flags;
+#define EVBUFFER_MMAP          0x0001  /**< memory in buffer is mmaped */
+#define EVBUFFER_SENDFILE      0x0002  /**< a chain used for sendfile */
+#define EVBUFFER_REFERENCE     0x0004  /**< a chain with a mem reference */
+#define EVBUFFER_IMMUTABLE     0x0008  /**< read-only chain */
+       /** a chain that mustn't be reallocated or freed, or have its contents
+        * memmoved, until the chain is un-pinned. */
+#define EVBUFFER_MEM_PINNED_R  0x0010
+#define EVBUFFER_MEM_PINNED_W  0x0020
+#define EVBUFFER_MEM_PINNED_ANY (EVBUFFER_MEM_PINNED_R|EVBUFFER_MEM_PINNED_W)
+       /** a chain that should be freed, but can't be freed until it is
+        * un-pinned. */
+#define EVBUFFER_DANGLING      0x0040
+
+       /** Usually points to the read-write memory belonging to this
+        * buffer allocated as part of the evbuffer_chain allocation.
+        * For mmap, this can be a read-only buffer and
+        * EVBUFFER_IMMUTABLE will be set in flags.  For sendfile, it
+        * may point to NULL.
+        */
+       unsigned char *buffer;
+};
+
+/* this is currently used by both mmap and sendfile */
+/* TODO(niels): something strange needs to happen for Windows here, I am not
+ * sure what that is, but it needs to get looked into.
+ */
+struct evbuffer_chain_fd {
+       int fd; /**< the fd associated with this chain */
+};
+
+/** callback for a reference buffer; lets us know what to do with it when
+ * we're done with it. */
+struct evbuffer_chain_reference {
+       evbuffer_ref_cleanup_cb cleanupfn;
+       void *extra;
+};
+
+#define EVBUFFER_CHAIN_SIZE sizeof(struct evbuffer_chain)
+/** Return a pointer to extra data allocated along with an evbuffer. */
+#define EVBUFFER_CHAIN_EXTRA(t, c) (t *)((struct evbuffer_chain *)(c) + 1)
+
+/** Assert that we are holding the lock on an evbuffer */
+#define ASSERT_EVBUFFER_LOCKED(buffer)                 \
+       EVLOCK_ASSERT_LOCKED((buffer)->lock)
+
+#define EVBUFFER_LOCK(buffer)                                          \
+       do {                                                            \
+               EVLOCK_LOCK((buffer)->lock, 0);                         \
+       } while (0)
+#define EVBUFFER_UNLOCK(buffer)                                                \
+       do {                                                            \
+               EVLOCK_UNLOCK((buffer)->lock, 0);                       \
+       } while (0)
+#define EVBUFFER_LOCK2(buffer1, buffer2)                               \
+       do {                                                            \
+               EVLOCK_LOCK2((buffer1)->lock, (buffer2)->lock, 0, 0);   \
+       } while (0)
+#define EVBUFFER_UNLOCK2(buffer1, buffer2)                             \
+       do {                                                            \
+               EVLOCK_UNLOCK2((buffer1)->lock, (buffer2)->lock, 0, 0); \
+       } while (0)
+
+/** Increase the reference count of buf by one. */
+void _evbuffer_incref(struct evbuffer *buf);
+/** Increase the reference count of buf by one and acquire the lock. */
+void _evbuffer_incref_and_lock(struct evbuffer *buf);
+/** Pin a single buffer chain using a given flag. A pinned chunk may not be
+ * moved or freed until it is unpinned. */
+void _evbuffer_chain_pin(struct evbuffer_chain *chain, unsigned flag);
+/** Unpin a single buffer chain using a given flag. */
+void _evbuffer_chain_unpin(struct evbuffer_chain *chain, unsigned flag);
+/** As evbuffer_free, but requires that we hold a lock on the buffer, and
+ * releases the lock before freeing it and the buffer. */
+void _evbuffer_decref_and_unlock(struct evbuffer *buffer);
+
+/** As evbuffer_expand, but does not guarantee that the newly allocated memory
+ * is contiguous.  Instead, it may be split across two or more chunks. */
+int _evbuffer_expand_fast(struct evbuffer *, size_t, int);
+
+/** Helper: prepares for a readv/WSARecv call by expanding the buffer to
+ * hold enough memory to read 'howmuch' bytes in possibly noncontiguous memory.
+ * Sets up the one or two iovecs in 'vecs' to point to the free memory and its
+ * extent, and *chainp to point to the first chain that we'll try to read into.
+ * Returns the number of vecs used.
+ */
+int _evbuffer_read_setup_vecs(struct evbuffer *buf, ev_ssize_t howmuch,
+    struct evbuffer_iovec *vecs, int n_vecs, struct evbuffer_chain ***chainp,
+    int exact);
+
+/* Helper macro: copies an evbuffer_iovec in ei to a win32 WSABUF in i. */
+#define WSABUF_FROM_EVBUFFER_IOV(i,ei) do {            \
+               (i)->buf = (ei)->iov_base;              \
+               (i)->len = (unsigned long)(ei)->iov_len;        \
+       } while (0)
+/* XXXX the cast above is safe for now, but not if we allow mmaps on win64.
+ * See note in buffer_iocp's launch_write function */
+
+/** Set the parent bufferevent object for buf to bev */
+void evbuffer_set_parent(struct evbuffer *buf, struct bufferevent *bev);
+
+void evbuffer_invoke_callbacks(struct evbuffer *buf);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVBUFFER_INTERNAL_H_ */
diff --git a/libevent/evdns.3 b/libevent/evdns.3
new file mode 100644 (file)
index 0000000..10414fa
--- /dev/null
@@ -0,0 +1,322 @@
+.\"
+.\" Copyright (c) 2006 Niels Provos <provos@citi.umich.edu>
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
+.\" 3. The name of the author may not be used to endorse or promote products
+.\"    derived from this software without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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.
+.\"
+.Dd October 7, 2006
+.Dt EVDNS 3
+.Os
+.Sh NAME
+.Nm evdns_init
+.Nm evdns_shutdown
+.Nm evdns_err_to_string
+.Nm evdns_nameserver_add
+.Nm evdns_count_nameservers
+.Nm evdns_clear_nameservers_and_suspend
+.Nm evdns_resume
+.Nm evdns_nameserver_ip_add
+.Nm evdns_resolve_ipv4
+.Nm evdns_resolve_reverse
+.Nm evdns_resolv_conf_parse
+.Nm evdns_config_windows_nameservers
+.Nm evdns_search_clear
+.Nm evdns_search_add
+.Nm evdns_search_ndots_set
+.Nm evdns_set_log_fn
+.Nd asynchronous functions for DNS resolution.
+.Sh SYNOPSIS
+.Fd #include <sys/time.h>
+.Fd #include <event.h>
+.Fd #include <evdns.h>
+.Ft int
+.Fn evdns_init
+.Ft void
+.Fn evdns_shutdown "int fail_requests"
+.Ft "const char *"
+.Fn evdns_err_to_string "int err"
+.Ft int
+.Fn evdns_nameserver_add "unsigned long int address"
+.Ft int
+.Fn evdns_count_nameservers
+.Ft int
+.Fn evdns_clear_nameservers_and_suspend
+.Ft int
+.Fn evdns_resume
+.Ft int
+.Fn evdns_nameserver_ip_add(const char *ip_as_string);
+.Ft int
+.Fn evdns_resolve_ipv4 "const char *name" "int flags" "evdns_callback_type callback" "void *ptr"
+.Ft int
+.Fn evdns_resolve_reverse "struct in_addr *in" "int flags" "evdns_callback_type callback" "void *ptr"
+.Ft int
+.Fn evdns_resolv_conf_parse "int flags" "const char *"
+.Ft void
+.Fn evdns_search_clear
+.Ft void
+.Fn evdns_search_add "const char *domain"
+.Ft void
+.Fn evdns_search_ndots_set "const int ndots"
+.Ft void
+.Fn evdns_set_log_fn "evdns_debug_log_fn_type fn"
+.Ft int
+.Fn evdns_config_windows_nameservers
+.Sh DESCRIPTION
+Welcome, gentle reader
+.Pp
+Async DNS lookups are really a whole lot harder than they should be,
+mostly stemming from the fact that the libc resolver has never been
+very good at them. Before you use this library you should see if libc
+can do the job for you with the modern async call getaddrinfo_a
+(see http://www.imperialviolet.org/page25.html#e498). Otherwise,
+please continue.
+.Pp
+This code is based on libevent and you must call event_init before
+any of the APIs in this file. You must also seed the OpenSSL random
+source if you are using OpenSSL for ids (see below).
+.Pp
+This library is designed to be included and shipped with your source
+code. You statically link with it. You should also test for the
+existence of strtok_r and define HAVE_STRTOK_R if you have it.
+.Pp
+The DNS protocol requires a good source of id numbers and these
+numbers should be unpredictable for spoofing reasons. There are
+three methods for generating them here and you must define exactly
+one of them. In increasing order of preference:
+.Pp
+.Bl -tag -width "DNS_USE_GETTIMEOFDAY_FOR_ID" -compact -offset indent
+.It DNS_USE_GETTIMEOFDAY_FOR_ID
+Using the bottom 16 bits of the usec result from gettimeofday. This
+is a pretty poor solution but should work anywhere.
+.It DNS_USE_CPU_CLOCK_FOR_ID
+Using the bottom 16 bits of the nsec result from the CPU's time
+counter. This is better, but may not work everywhere. Requires
+POSIX realtime support and you'll need to link against -lrt on
+glibc systems at least.
+.It DNS_USE_OPENSSL_FOR_ID
+Uses the OpenSSL RAND_bytes call to generate the data. You must
+have seeded the pool before making any calls to this library.
+.El
+.Pp
+The library keeps track of the state of nameservers and will avoid
+them when they go down. Otherwise it will round robin between them.
+.Pp
+Quick start guide:
+  #include "evdns.h"
+  void callback(int result, char type, int count, int ttl,
+        void *addresses, void *arg);
+  evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
+  evdns_resolve("www.hostname.com", 0, callback, NULL);
+.Pp
+When the lookup is complete the callback function is called. The
+first argument will be one of the DNS_ERR_* defines in evdns.h.
+Hopefully it will be DNS_ERR_NONE, in which case type will be
+DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
+which the data can be cached for (in seconds), addresses will point
+to an array of uint32_t's and arg will be whatever you passed to
+evdns_resolve.
+.Pp
+Searching:
+.Pp
+In order for this library to be a good replacement for glibc's resolver it
+supports searching. This involves setting a list of default domains, in
+which names will be queried for. The number of dots in the query name
+determines the order in which this list is used.
+.Pp
+Searching appears to be a single lookup from the point of view of the API,
+although many DNS queries may be generated from a single call to
+evdns_resolve. Searching can also drastically slow down the resolution
+of names.
+.Pp
+To disable searching:
+.Bl -enum -compact -offset indent
+.It
+Never set it up. If you never call
+.Fn evdns_resolv_conf_parse,
+.Fn evdns_init,
+or
+.Fn evdns_search_add
+then no searching will occur.
+.It
+If you do call
+.Fn evdns_resolv_conf_parse
+then don't pass
+.Va DNS_OPTION_SEARCH
+(or
+.Va DNS_OPTIONS_ALL,
+which implies it).
+.It
+When calling
+.Fn evdns_resolve,
+pass the
+.Va DNS_QUERY_NO_SEARCH
+flag.
+.El
+.Pp
+The order of searches depends on the number of dots in the name. If the
+number is greater than the ndots setting then the names is first tried
+globally. Otherwise each search domain is appended in turn.
+.Pp
+The ndots setting can either be set from a resolv.conf, or by calling
+evdns_search_ndots_set.
+.Pp
+For example, with ndots set to 1 (the default) and a search domain list of
+["myhome.net"]:
+ Query: www
+ Order: www.myhome.net, www.
+.Pp
+ Query: www.abc
+ Order: www.abc., www.abc.myhome.net
+.Pp
+.Sh API reference
+.Pp
+.Bl -tag -width 0123456
+.It Ft int Fn evdns_init
+Initializes support for non-blocking name resolution by calling
+.Fn evdns_resolv_conf_parse
+on UNIX and
+.Fn evdns_config_windows_nameservers
+on Windows.
+.It Ft int Fn evdns_nameserver_add "unsigned long int address"
+Add a nameserver. The address should be an IP address in
+network byte order. The type of address is chosen so that
+it matches in_addr.s_addr.
+Returns non-zero on error.
+.It Ft int Fn evdns_nameserver_ip_add "const char *ip_as_string"
+This wraps the above function by parsing a string as an IP
+address and adds it as a nameserver.
+Returns non-zero on error
+.It Ft int Fn evdns_resolve "const char *name" "int flags" "evdns_callback_type callback" "void *ptr"
+Resolve a name. The name parameter should be a DNS name.
+The flags parameter should be 0, or DNS_QUERY_NO_SEARCH
+which disables searching for this query. (see defn of
+searching above).
+.Pp
+The callback argument is a function which is called when
+this query completes and ptr is an argument which is passed
+to that callback function.
+.Pp
+Returns non-zero on error
+.It Ft void Fn evdns_search_clear
+Clears the list of search domains
+.It Ft void Fn evdns_search_add "const char *domain"
+Add a domain to the list of search domains
+.It Ft void Fn evdns_search_ndots_set "int ndots"
+Set the number of dots which, when found in a name, causes
+the first query to be without any search domain.
+.It Ft int Fn evdns_count_nameservers "void"
+Return the number of configured nameservers (not necessarily the
+number of running nameservers).  This is useful for double-checking
+whether our calls to the various nameserver configuration functions
+have been successful.
+.It Ft int Fn evdns_clear_nameservers_and_suspend "void"
+Remove all currently configured nameservers, and suspend all pending
+resolves.  Resolves will not necessarily be re-attempted until
+evdns_resume() is called.
+.It Ft int Fn evdns_resume "void"
+Re-attempt resolves left in limbo after an earlier call to
+evdns_clear_nameservers_and_suspend().
+.It Ft int Fn evdns_config_windows_nameservers "void"
+Attempt to configure a set of nameservers based on platform settings on
+a win32 host.  Preferentially tries to use GetNetworkParams; if that fails,
+looks in the registry.  Returns 0 on success, nonzero on failure.
+.It Ft int Fn evdns_resolv_conf_parse "int flags" "const char *filename"
+Parse a resolv.conf like file from the given filename.
+.Pp
+See the man page for resolv.conf for the format of this file.
+The flags argument determines what information is parsed from
+this file:
+.Bl -tag -width "DNS_OPTION_NAMESERVERS" -offset indent -compact -nested
+.It DNS_OPTION_SEARCH
+domain, search and ndots options
+.It DNS_OPTION_NAMESERVERS
+nameserver lines
+.It DNS_OPTION_MISC
+timeout and attempts options
+.It DNS_OPTIONS_ALL
+all of the above
+.El
+.Pp
+The following directives are not parsed from the file:
+  sortlist, rotate, no-check-names, inet6, debug
+.Pp
+Returns non-zero on error:
+.Bl -tag -width "0" -offset indent -compact -nested
+.It 0
+no errors
+.It 1
+failed to open file
+.It 2
+failed to stat file
+.It 3
+file too large
+.It 4
+out of memory
+.It 5
+short read from file
+.El
+.El
+.Sh Internals:
+Requests are kept in two queues. The first is the inflight queue. In
+this queue requests have an allocated transaction id and nameserver.
+They will soon be transmitted if they haven't already been.
+.Pp
+The second is the waiting queue. The size of the inflight ring is
+limited and all other requests wait in waiting queue for space. This
+bounds the number of concurrent requests so that we don't flood the
+nameserver. Several algorithms require a full walk of the inflight
+queue and so bounding its size keeps thing going nicely under huge
+(many thousands of requests) loads.
+.Pp
+If a nameserver loses too many requests it is considered down and we
+try not to use it. After a while we send a probe to that nameserver
+(a lookup for google.com) and, if it replies, we consider it working
+again. If the nameserver fails a probe we wait longer to try again
+with the next probe.
+.Sh SEE ALSO
+.Xr event 3 ,
+.Xr gethostbyname 3 ,
+.Xr resolv.conf 5
+.Sh HISTORY
+The
+.Nm evdns
+API was developed by Adam Langley on top of the
+.Nm libevent
+API.
+The code was integrate into
+.Nm Tor
+by Nick Mathewson and finally put into
+.Nm libevent
+itself by Niels Provos.
+.Sh AUTHORS
+The
+.Nm evdns
+API and code was written by Adam Langley with significant
+contributions by Nick Mathewson.
+.Sh BUGS
+This documentation is neither complete nor authoritative.
+If you are in doubt about the usage of this API then
+check the source code to find out how it works, write
+up the missing piece of documentation and send it to
+me for inclusion in this man page.
diff --git a/libevent/evdns.c b/libevent/evdns.c
new file mode 100644 (file)
index 0000000..02f5dff
--- /dev/null
@@ -0,0 +1,4620 @@
+/* Copyright 2006-2007 Niels Provos
+ * Copyright 2007-2012 Nick Mathewson and Niels Provos
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+/* Based on software by Adam Langly. Adam's original message:
+ *
+ * Async DNS Library
+ * Adam Langley <agl@imperialviolet.org>
+ * http://www.imperialviolet.org/eventdns.html
+ * Public Domain code
+ *
+ * This software is Public Domain. To view a copy of the public domain dedication,
+ * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
+ * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
+ *
+ * I ask and expect, but do not require, that all derivative works contain an
+ * attribution similar to:
+ *     Parts developed by Adam Langley <agl@imperialviolet.org>
+ *
+ * You may wish to replace the word "Parts" with something else depending on
+ * the amount of original code.
+ *
+ * (Derivative works does not include programs which link against, run or include
+ * the source verbatim in their source distributions)
+ *
+ * Version: 0.1b
+ */
+
+#include <sys/types.h>
+#include "event2/event-config.h"
+
+#ifndef _FORTIFY_SOURCE
+#define _FORTIFY_SOURCE 3
+#endif
+
+#include <string.h>
+#include <fcntl.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _EVENT_HAVE_STDINT_H
+#include <stdint.h>
+#endif
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <limits.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include <stdarg.h>
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#ifndef _WIN32_IE
+#define _WIN32_IE 0x400
+#endif
+#include <shlobj.h>
+#endif
+
+#include "event2/dns.h"
+#include "event2/dns_struct.h"
+#include "event2/dns_compat.h"
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/thread.h"
+
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "bufferevent-internal.h"
+
+#include "defer-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "strlcpy-internal.h"
+#include "ipv6-internal.h"
+#include "util-internal.h"
+#include "evthread-internal.h"
+#ifdef WIN32
+#include <ctype.h>
+#include <winsock2.h>
+#include <windows.h>
+#include <iphlpapi.h>
+#include <io.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#endif
+
+#ifdef _EVENT_HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+
+#define EVDNS_LOG_DEBUG 0
+#define EVDNS_LOG_WARN 1
+#define EVDNS_LOG_MSG 2
+
+#ifndef HOST_NAME_MAX
+#define HOST_NAME_MAX 255
+#endif
+
+#include <stdio.h>
+
+#undef MIN
+#define MIN(a,b) ((a)<(b)?(a):(b))
+
+#define ASSERT_VALID_REQUEST(req) \
+       EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
+
+#define u64 ev_uint64_t
+#define u32 ev_uint32_t
+#define u16 ev_uint16_t
+#define u8  ev_uint8_t
+
+/* maximum number of addresses from a single packet */
+/* that we bother recording */
+#define MAX_V4_ADDRS 32
+#define MAX_V6_ADDRS 32
+
+
+#define TYPE_A        EVDNS_TYPE_A
+#define TYPE_CNAME     5
+#define TYPE_PTR       EVDNS_TYPE_PTR
+#define TYPE_SOA       EVDNS_TYPE_SOA
+#define TYPE_AAAA      EVDNS_TYPE_AAAA
+
+#define CLASS_INET     EVDNS_CLASS_INET
+
+/* Persistent handle.  We keep this separate from 'struct request' since we
+ * need some object to last for as long as an evdns_request is outstanding so
+ * that it can be canceled, whereas a search request can lead to multiple
+ * 'struct request' instances being created over its lifetime. */
+struct evdns_request {
+       struct request *current_req;
+       struct evdns_base *base;
+
+       int pending_cb; /* Waiting for its callback to be invoked; not
+                        * owned by event base any more. */
+
+       /* elements used by the searching code */
+       int search_index;
+       struct search_state *search_state;
+       char *search_origname;  /* needs to be free()ed */
+       int search_flags;
+};
+
+struct request {
+       u8 *request;  /* the dns packet data */
+       u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
+       unsigned int request_len;
+       int reissue_count;
+       int tx_count;  /* the number of times that this packet has been sent */
+       void *user_pointer;  /* the pointer given to us for this request */
+       evdns_callback_type user_callback;
+       struct nameserver *ns;  /* the server which we last sent it */
+
+       /* these objects are kept in a circular list */
+       /* XXX We could turn this into a CIRCLEQ. */
+       struct request *next, *prev;
+
+       struct event timeout_event;
+
+       u16 trans_id;  /* the transaction id */
+       unsigned request_appended :1;   /* true if the request pointer is data which follows this struct */
+       unsigned transmit_me :1;  /* needs to be transmitted */
+
+       /* XXXX This is a horrible hack. */
+       char **put_cname_in_ptr; /* store the cname here if we get one. */
+
+       struct evdns_base *base;
+
+       struct evdns_request *handle;
+};
+
+struct reply {
+       unsigned int type;
+       unsigned int have_answer : 1;
+       union {
+               struct {
+                       u32 addrcount;
+                       u32 addresses[MAX_V4_ADDRS];
+               } a;
+               struct {
+                       u32 addrcount;
+                       struct in6_addr addresses[MAX_V6_ADDRS];
+               } aaaa;
+               struct {
+                       char name[HOST_NAME_MAX];
+               } ptr;
+       } data;
+};
+
+struct nameserver {
+       evutil_socket_t socket;  /* a connected UDP socket */
+       struct sockaddr_storage address;
+       ev_socklen_t addrlen;
+       int failed_times;  /* number of times which we have given this server a chance */
+       int timedout;  /* number of times in a row a request has timed out */
+       struct event event;
+       /* these objects are kept in a circular list */
+       struct nameserver *next, *prev;
+       struct event timeout_event;  /* used to keep the timeout for */
+                                    /* when we next probe this server. */
+                                    /* Valid if state == 0 */
+       /* Outstanding probe request for this nameserver, if any */
+       struct evdns_request *probe_request;
+       char state;  /* zero if we think that this server is down */
+       char choked;  /* true if we have an EAGAIN from this server's socket */
+       char write_waiting;  /* true if we are waiting for EV_WRITE events */
+       struct evdns_base *base;
+};
+
+
+/* Represents a local port where we're listening for DNS requests. Right now, */
+/* only UDP is supported. */
+struct evdns_server_port {
+       evutil_socket_t socket; /* socket we use to read queries and write replies. */
+       int refcnt; /* reference count. */
+       char choked; /* Are we currently blocked from writing? */
+       char closing; /* Are we trying to close this port, pending writes? */
+       evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
+       void *user_data; /* Opaque pointer passed to user_callback */
+       struct event event; /* Read/write event */
+       /* circular list of replies that we want to write. */
+       struct server_request *pending_replies;
+       struct event_base *event_base;
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       void *lock;
+#endif
+};
+
+/* Represents part of a reply being built.     (That is, a single RR.) */
+struct server_reply_item {
+       struct server_reply_item *next; /* next item in sequence. */
+       char *name; /* name part of the RR */
+       u16 type; /* The RR type */
+       u16 class; /* The RR class (usually CLASS_INET) */
+       u32 ttl; /* The RR TTL */
+       char is_name; /* True iff data is a label */
+       u16 datalen; /* Length of data; -1 if data is a label */
+       void *data; /* The contents of the RR */
+};
+
+/* Represents a request that we've received as a DNS server, and holds */
+/* the components of the reply as we're constructing it. */
+struct server_request {
+       /* Pointers to the next and previous entries on the list of replies */
+       /* that we're waiting to write.  Only set if we have tried to respond */
+       /* and gotten EAGAIN. */
+       struct server_request *next_pending;
+       struct server_request *prev_pending;
+
+       u16 trans_id; /* Transaction id. */
+       struct evdns_server_port *port; /* Which port received this request on? */
+       struct sockaddr_storage addr; /* Where to send the response */
+       ev_socklen_t addrlen; /* length of addr */
+
+       int n_answer; /* how many answer RRs have been set? */
+       int n_authority; /* how many authority RRs have been set? */
+       int n_additional; /* how many additional RRs have been set? */
+
+       struct server_reply_item *answer; /* linked list of answer RRs */
+       struct server_reply_item *authority; /* linked list of authority RRs */
+       struct server_reply_item *additional; /* linked list of additional RRs */
+
+       /* Constructed response.  Only set once we're ready to send a reply. */
+       /* Once this is set, the RR fields are cleared, and no more should be set. */
+       char *response;
+       size_t response_len;
+
+       /* Caller-visible fields: flags, questions. */
+       struct evdns_server_request base;
+};
+
+struct evdns_base {
+       /* An array of n_req_heads circular lists for inflight requests.
+        * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
+        */
+       struct request **req_heads;
+       /* A circular list of requests that we're waiting to send, but haven't
+        * sent yet because there are too many requests inflight */
+       struct request *req_waiting_head;
+       /* A circular list of nameservers. */
+       struct nameserver *server_head;
+       int n_req_heads;
+
+       struct event_base *event_base;
+
+       /* The number of good nameservers that we have */
+       int global_good_nameservers;
+
+       /* inflight requests are contained in the req_head list */
+       /* and are actually going out across the network */
+       int global_requests_inflight;
+       /* requests which aren't inflight are in the waiting list */
+       /* and are counted here */
+       int global_requests_waiting;
+
+       int global_max_requests_inflight;
+
+       struct timeval global_timeout;  /* 5 seconds by default */
+       int global_max_reissues;  /* a reissue occurs when we get some errors from the server */
+       int global_max_retransmits;  /* number of times we'll retransmit a request which timed out */
+       /* number of timeouts in a row before we consider this server to be down */
+       int global_max_nameserver_timeout;
+       /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
+       int global_randomize_case;
+
+       /* The first time that a nameserver fails, how long do we wait before
+        * probing to see if it has returned?  */
+       struct timeval global_nameserver_probe_initial_timeout;
+
+       /** Port to bind to for outgoing DNS packets. */
+       struct sockaddr_storage global_outgoing_address;
+       /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
+       ev_socklen_t global_outgoing_addrlen;
+
+       struct timeval global_getaddrinfo_allow_skew;
+
+       int getaddrinfo_ipv4_timeouts;
+       int getaddrinfo_ipv6_timeouts;
+       int getaddrinfo_ipv4_answered;
+       int getaddrinfo_ipv6_answered;
+
+       struct search_state *global_search_state;
+
+       TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       void *lock;
+#endif
+};
+
+struct hosts_entry {
+       TAILQ_ENTRY(hosts_entry) next;
+       union {
+               struct sockaddr sa;
+               struct sockaddr_in sin;
+               struct sockaddr_in6 sin6;
+       } addr;
+       int addrlen;
+       char hostname[1];
+};
+
+static struct evdns_base *current_base = NULL;
+
+struct evdns_base *
+evdns_get_global_base(void)
+{
+       return current_base;
+}
+
+/* Given a pointer to an evdns_server_request, get the corresponding */
+/* server_request. */
+#define TO_SERVER_REQUEST(base_ptr)                                    \
+       ((struct server_request*)                                       \
+         (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
+
+#define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
+
+static struct nameserver *nameserver_pick(struct evdns_base *base);
+static void evdns_request_insert(struct request *req, struct request **head);
+static void evdns_request_remove(struct request *req, struct request **head);
+static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg);
+static int evdns_transmit(struct evdns_base *base);
+static int evdns_request_transmit(struct request *req);
+static void nameserver_send_probe(struct nameserver *const ns);
+static void search_request_finished(struct evdns_request *const);
+static int search_try_next(struct evdns_request *const req);
+static struct request *search_request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
+static void evdns_requests_pump_waiting_queue(struct evdns_base *base);
+static u16 transaction_id_pick(struct evdns_base *base);
+static struct request *request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
+static void request_submit(struct request *const req);
+
+static int server_request_free(struct server_request *req);
+static void server_request_free_answers(struct server_request *req);
+static void server_port_free(struct evdns_server_port *port);
+static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg);
+static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename);
+static int evdns_base_set_option_impl(struct evdns_base *base,
+    const char *option, const char *val, int flags);
+static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests);
+
+static int strtoint(const char *const str);
+
+#ifdef _EVENT_DISABLE_THREAD_SUPPORT
+#define EVDNS_LOCK(base)  _EVUTIL_NIL_STMT
+#define EVDNS_UNLOCK(base) _EVUTIL_NIL_STMT
+#define ASSERT_LOCKED(base) _EVUTIL_NIL_STMT
+#else
+#define EVDNS_LOCK(base)                       \
+       EVLOCK_LOCK((base)->lock, 0)
+#define EVDNS_UNLOCK(base)                     \
+       EVLOCK_UNLOCK((base)->lock, 0)
+#define ASSERT_LOCKED(base)                    \
+       EVLOCK_ASSERT_LOCKED((base)->lock)
+#endif
+
+static void
+default_evdns_log_fn(int warning, const char *buf)
+{
+       if (warning == EVDNS_LOG_WARN)
+               event_warnx("[evdns] %s", buf);
+       else if (warning == EVDNS_LOG_MSG)
+               event_msgx("[evdns] %s", buf);
+       else
+               event_debug(("[evdns] %s", buf));
+}
+
+static evdns_debug_log_fn_type evdns_log_fn = NULL;
+
+void
+evdns_set_log_fn(evdns_debug_log_fn_type fn)
+{
+       evdns_log_fn = fn;
+}
+
+#ifdef __GNUC__
+#define EVDNS_LOG_CHECK         __attribute__ ((format(printf, 2, 3)))
+#else
+#define EVDNS_LOG_CHECK
+#endif
+
+static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
+static void
+_evdns_log(int warn, const char *fmt, ...)
+{
+       va_list args;
+       char buf[512];
+       if (!evdns_log_fn)
+               return;
+       va_start(args,fmt);
+       evutil_vsnprintf(buf, sizeof(buf), fmt, args);
+       va_end(args);
+       if (evdns_log_fn) {
+               if (warn == EVDNS_LOG_MSG)
+                       warn = EVDNS_LOG_WARN;
+               evdns_log_fn(warn, buf);
+       } else {
+               default_evdns_log_fn(warn, buf);
+       }
+
+}
+
+#define log _evdns_log
+
+/* This walks the list of inflight requests to find the */
+/* one with a matching transaction id. Returns NULL on */
+/* failure */
+static struct request *
+request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
+       struct request *req = REQ_HEAD(base, trans_id);
+       struct request *const started_at = req;
+
+       ASSERT_LOCKED(base);
+
+       if (req) {
+               do {
+                       if (req->trans_id == trans_id) return req;
+                       req = req->next;
+               } while (req != started_at);
+       }
+
+       return NULL;
+}
+
+/* a libevent callback function which is called when a nameserver */
+/* has gone down and we want to test if it has came back to life yet */
+static void
+nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) {
+       struct nameserver *const ns = (struct nameserver *) arg;
+       (void)fd;
+       (void)events;
+
+       EVDNS_LOCK(ns->base);
+       nameserver_send_probe(ns);
+       EVDNS_UNLOCK(ns->base);
+}
+
+/* a libevent callback which is called when a nameserver probe (to see if */
+/* it has come back to life) times out. We increment the count of failed_times */
+/* and wait longer to send the next probe packet. */
+static void
+nameserver_probe_failed(struct nameserver *const ns) {
+       struct timeval timeout;
+       int i;
+
+       ASSERT_LOCKED(ns->base);
+       (void) evtimer_del(&ns->timeout_event);
+       if (ns->state == 1) {
+               /* This can happen if the nameserver acts in a way which makes us mark */
+               /* it as bad and then starts sending good replies. */
+               return;
+       }
+
+#define MAX_PROBE_TIMEOUT 3600
+#define TIMEOUT_BACKOFF_FACTOR 3
+
+       memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout,
+           sizeof(struct timeval));
+       for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) {
+               timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR;
+               timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR;
+               if (timeout.tv_usec > 1000000) {
+                       timeout.tv_sec += timeout.tv_usec / 1000000;
+                       timeout.tv_usec %= 1000000;
+               }
+       }
+       if (timeout.tv_sec > MAX_PROBE_TIMEOUT) {
+               timeout.tv_sec = MAX_PROBE_TIMEOUT;
+               timeout.tv_usec = 0;
+       }
+
+       ns->failed_times++;
+
+       if (evtimer_add(&ns->timeout_event, &timeout) < 0) {
+               char addrbuf[128];
+               log(EVDNS_LOG_WARN,
+                   "Error from libevent when adding timer event for %s",
+                   evutil_format_sockaddr_port(
+                           (struct sockaddr *)&ns->address,
+                           addrbuf, sizeof(addrbuf)));
+       }
+}
+
+/* called when a nameserver has been deemed to have failed. For example, too */
+/* many packets have timed out etc */
+static void
+nameserver_failed(struct nameserver *const ns, const char *msg) {
+       struct request *req, *started_at;
+       struct evdns_base *base = ns->base;
+       int i;
+       char addrbuf[128];
+
+       ASSERT_LOCKED(base);
+       /* if this nameserver has already been marked as failed */
+       /* then don't do anything */
+       if (!ns->state) return;
+
+       log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
+           evutil_format_sockaddr_port(
+                   (struct sockaddr *)&ns->address,
+                   addrbuf, sizeof(addrbuf)),
+           msg);
+
+       base->global_good_nameservers--;
+       EVUTIL_ASSERT(base->global_good_nameservers >= 0);
+       if (base->global_good_nameservers == 0) {
+               log(EVDNS_LOG_MSG, "All nameservers have failed");
+       }
+
+       ns->state = 0;
+       ns->failed_times = 1;
+
+       if (evtimer_add(&ns->timeout_event,
+               &base->global_nameserver_probe_initial_timeout) < 0) {
+               log(EVDNS_LOG_WARN,
+                   "Error from libevent when adding timer event for %s",
+                   evutil_format_sockaddr_port(
+                           (struct sockaddr *)&ns->address,
+                           addrbuf, sizeof(addrbuf)));
+               /* ???? Do more? */
+       }
+
+       /* walk the list of inflight requests to see if any can be reassigned to */
+       /* a different server. Requests in the waiting queue don't have a */
+       /* nameserver assigned yet */
+
+       /* if we don't have *any* good nameservers then there's no point */
+       /* trying to reassign requests to one */
+       if (!base->global_good_nameservers) return;
+
+       for (i = 0; i < base->n_req_heads; ++i) {
+               req = started_at = base->req_heads[i];
+               if (req) {
+                       do {
+                               if (req->tx_count == 0 && req->ns == ns) {
+                                       /* still waiting to go out, can be moved */
+                                       /* to another server */
+                                       req->ns = nameserver_pick(base);
+                               }
+                               req = req->next;
+                       } while (req != started_at);
+               }
+       }
+}
+
+static void
+nameserver_up(struct nameserver *const ns)
+{
+       char addrbuf[128];
+       ASSERT_LOCKED(ns->base);
+       if (ns->state) return;
+       log(EVDNS_LOG_MSG, "Nameserver %s is back up",
+           evutil_format_sockaddr_port(
+                   (struct sockaddr *)&ns->address,
+                   addrbuf, sizeof(addrbuf)));
+       evtimer_del(&ns->timeout_event);
+       if (ns->probe_request) {
+               evdns_cancel_request(ns->base, ns->probe_request);
+               ns->probe_request = NULL;
+       }
+       ns->state = 1;
+       ns->failed_times = 0;
+       ns->timedout = 0;
+       ns->base->global_good_nameservers++;
+}
+
+static void
+request_trans_id_set(struct request *const req, const u16 trans_id) {
+       req->trans_id = trans_id;
+       *((u16 *) req->request) = htons(trans_id);
+}
+
+/* Called to remove a request from a list and dealloc it. */
+/* head is a pointer to the head of the list it should be */
+/* removed from or NULL if the request isn't in a list. */
+/* when free_handle is one, free the handle as well. */
+static void
+request_finished(struct request *const req, struct request **head, int free_handle) {
+       struct evdns_base *base = req->base;
+       int was_inflight = (head != &base->req_waiting_head);
+       EVDNS_LOCK(base);
+       ASSERT_VALID_REQUEST(req);
+
+       if (head)
+               evdns_request_remove(req, head);
+
+       log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req);
+       if (was_inflight) {
+               evtimer_del(&req->timeout_event);
+               base->global_requests_inflight--;
+       } else {
+               base->global_requests_waiting--;
+       }
+       /* it was initialized during request_new / evtimer_assign */
+       event_debug_unassign(&req->timeout_event);
+
+       if (!req->request_appended) {
+               /* need to free the request data on it's own */
+               mm_free(req->request);
+       } else {
+               /* the request data is appended onto the header */
+               /* so everything gets free()ed when we: */
+       }
+
+       if (req->handle) {
+               EVUTIL_ASSERT(req->handle->current_req == req);
+
+               if (free_handle) {
+                       search_request_finished(req->handle);
+                       req->handle->current_req = NULL;
+                       if (! req->handle->pending_cb) {
+                               /* If we're planning to run the callback,
+                                * don't free the handle until later. */
+                               mm_free(req->handle);
+                       }
+                       req->handle = NULL; /* If we have a bug, let's crash
+                                            * early */
+               } else {
+                       req->handle->current_req = NULL;
+               }
+       }
+
+       mm_free(req);
+
+       evdns_requests_pump_waiting_queue(base);
+       EVDNS_UNLOCK(base);
+}
+
+/* This is called when a server returns a funny error code. */
+/* We try the request again with another server. */
+/* */
+/* return: */
+/*   0 ok */
+/*   1 failed/reissue is pointless */
+static int
+request_reissue(struct request *req) {
+       const struct nameserver *const last_ns = req->ns;
+       ASSERT_LOCKED(req->base);
+       ASSERT_VALID_REQUEST(req);
+       /* the last nameserver should have been marked as failing */
+       /* by the caller of this function, therefore pick will try */
+       /* not to return it */
+       req->ns = nameserver_pick(req->base);
+       if (req->ns == last_ns) {
+               /* ... but pick did return it */
+               /* not a lot of point in trying again with the */
+               /* same server */
+               return 1;
+       }
+
+       req->reissue_count++;
+       req->tx_count = 0;
+       req->transmit_me = 1;
+
+       return 0;
+}
+
+/* this function looks for space on the inflight queue and promotes */
+/* requests from the waiting queue if it can. */
+static void
+evdns_requests_pump_waiting_queue(struct evdns_base *base) {
+       ASSERT_LOCKED(base);
+       while (base->global_requests_inflight < base->global_max_requests_inflight &&
+                  base->global_requests_waiting) {
+               struct request *req;
+               /* move a request from the waiting queue to the inflight queue */
+               EVUTIL_ASSERT(base->req_waiting_head);
+               req = base->req_waiting_head;
+               evdns_request_remove(req, &base->req_waiting_head);
+
+               base->global_requests_waiting--;
+               base->global_requests_inflight++;
+
+               req->ns = nameserver_pick(base);
+               request_trans_id_set(req, transaction_id_pick(base));
+
+               evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
+               evdns_request_transmit(req);
+               evdns_transmit(base);
+       }
+}
+
+/* TODO(nickm) document */
+struct deferred_reply_callback {
+       struct deferred_cb deferred;
+       struct evdns_request *handle;
+       u8 request_type;
+       u8 have_reply;
+       u32 ttl;
+       u32 err;
+       evdns_callback_type user_callback;
+       struct reply reply;
+};
+
+static void
+reply_run_callback(struct deferred_cb *d, void *user_pointer)
+{
+       struct deferred_reply_callback *cb =
+           EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred);
+
+       switch (cb->request_type) {
+       case TYPE_A:
+               if (cb->have_reply)
+                       cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
+                           cb->reply.data.a.addrcount, cb->ttl,
+                           cb->reply.data.a.addresses,
+                           user_pointer);
+               else
+                       cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
+               break;
+       case TYPE_PTR:
+               if (cb->have_reply) {
+                       char *name = cb->reply.data.ptr.name;
+                       cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
+                           &name, user_pointer);
+               } else {
+                       cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
+               }
+               break;
+       case TYPE_AAAA:
+               if (cb->have_reply)
+                       cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
+                           cb->reply.data.aaaa.addrcount, cb->ttl,
+                           cb->reply.data.aaaa.addresses,
+                           user_pointer);
+               else
+                       cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
+               break;
+       default:
+               EVUTIL_ASSERT(0);
+       }
+
+       if (cb->handle && cb->handle->pending_cb) {
+               mm_free(cb->handle);
+       }
+
+       mm_free(cb);
+}
+
+static void
+reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply)
+{
+       struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d));
+
+       if (!d) {
+               event_warn("%s: Couldn't allocate space for deferred callback.",
+                   __func__);
+               return;
+       }
+
+       ASSERT_LOCKED(req->base);
+
+       d->request_type = req->request_type;
+       d->user_callback = req->user_callback;
+       d->ttl = ttl;
+       d->err = err;
+       if (reply) {
+               d->have_reply = 1;
+               memcpy(&d->reply, reply, sizeof(struct reply));
+       }
+
+       if (req->handle) {
+               req->handle->pending_cb = 1;
+               d->handle = req->handle;
+       }
+
+       event_deferred_cb_init(&d->deferred, reply_run_callback,
+           req->user_pointer);
+       event_deferred_cb_schedule(
+               event_base_get_deferred_cb_queue(req->base->event_base),
+               &d->deferred);
+}
+
+/* this processes a parsed reply packet */
+static void
+reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
+       int error;
+       char addrbuf[128];
+       static const int error_codes[] = {
+               DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
+               DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
+       };
+
+       ASSERT_LOCKED(req->base);
+       ASSERT_VALID_REQUEST(req);
+
+       if (flags & 0x020f || !reply || !reply->have_answer) {
+               /* there was an error */
+               if (flags & 0x0200) {
+                       error = DNS_ERR_TRUNCATED;
+               } else if (flags & 0x000f) {
+                       u16 error_code = (flags & 0x000f) - 1;
+                       if (error_code > 4) {
+                               error = DNS_ERR_UNKNOWN;
+                       } else {
+                               error = error_codes[error_code];
+                       }
+               } else if (reply && !reply->have_answer) {
+                       error = DNS_ERR_NODATA;
+               } else {
+                       error = DNS_ERR_UNKNOWN;
+               }
+
+               switch (error) {
+               case DNS_ERR_NOTIMPL:
+               case DNS_ERR_REFUSED:
+                       /* we regard these errors as marking a bad nameserver */
+                       if (req->reissue_count < req->base->global_max_reissues) {
+                               char msg[64];
+                               evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
+                                        error, evdns_err_to_string(error));
+                               nameserver_failed(req->ns, msg);
+                               if (!request_reissue(req)) return;
+                       }
+                       break;
+               case DNS_ERR_SERVERFAILED:
+                       /* rcode 2 (servfailed) sometimes means "we
+                        * are broken" and sometimes (with some binds)
+                        * means "that request was very confusing."
+                        * Treat this as a timeout, not a failure.
+                        */
+                       log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
+                               "at %s; will allow the request to time out.",
+                           evutil_format_sockaddr_port(
+                                   (struct sockaddr *)&req->ns->address,
+                                   addrbuf, sizeof(addrbuf)));
+                       break;
+               default:
+                       /* we got a good reply from the nameserver: it is up. */
+                       if (req->handle == req->ns->probe_request) {
+                               /* Avoid double-free */
+                               req->ns->probe_request = NULL;
+                       }
+
+                       nameserver_up(req->ns);
+               }
+
+               if (req->handle->search_state &&
+                   req->request_type != TYPE_PTR) {
+                       /* if we have a list of domains to search in,
+                        * try the next one */
+                       if (!search_try_next(req->handle)) {
+                               /* a new request was issued so this
+                                * request is finished and */
+                               /* the user callback will be made when
+                                * that request (or a */
+                               /* child of it) finishes. */
+                               return;
+                       }
+               }
+
+               /* all else failed. Pass the failure up */
+               reply_schedule_callback(req, ttl, error, NULL);
+               request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
+       } else {
+               /* all ok, tell the user */
+               reply_schedule_callback(req, ttl, 0, reply);
+               if (req->handle == req->ns->probe_request)
+                       req->ns->probe_request = NULL; /* Avoid double-free */
+               nameserver_up(req->ns);
+               request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
+       }
+}
+
+static int
+name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
+       int name_end = -1;
+       int j = *idx;
+       int ptr_count = 0;
+#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while (0)
+#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while (0)
+#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
+
+       char *cp = name_out;
+       const char *const end = name_out + name_out_len;
+
+       /* Normally, names are a series of length prefixed strings terminated */
+       /* with a length of 0 (the lengths are u8's < 63). */
+       /* However, the length can start with a pair of 1 bits and that */
+       /* means that the next 14 bits are a pointer within the current */
+       /* packet. */
+
+       for (;;) {
+               u8 label_len;
+               if (j >= length) return -1;
+               GET8(label_len);
+               if (!label_len) break;
+               if (label_len & 0xc0) {
+                       u8 ptr_low;
+                       GET8(ptr_low);
+                       if (name_end < 0) name_end = j;
+                       j = (((int)label_len & 0x3f) << 8) + ptr_low;
+                       /* Make sure that the target offset is in-bounds. */
+                       if (j < 0 || j >= length) return -1;
+                       /* If we've jumped more times than there are characters in the
+                        * message, we must have a loop. */
+                       if (++ptr_count > length) return -1;
+                       continue;
+               }
+               if (label_len > 63) return -1;
+               if (cp != name_out) {
+                       if (cp + 1 >= end) return -1;
+                       *cp++ = '.';
+               }
+               if (cp + label_len >= end) return -1;
+               memcpy(cp, packet + j, label_len);
+               cp += label_len;
+               j += label_len;
+       }
+       if (cp >= end) return -1;
+       *cp = '\0';
+       if (name_end < 0)
+               *idx = j;
+       else
+               *idx = name_end;
+       return 0;
+ err:
+       return -1;
+}
+
+/* parses a raw request from a nameserver */
+static int
+reply_parse(struct evdns_base *base, u8 *packet, int length) {
+       int j = 0, k = 0;  /* index into packet */
+       u16 _t;  /* used by the macros */
+       u32 _t32;  /* used by the macros */
+       char tmp_name[256], cmp_name[256]; /* used by the macros */
+       int name_matches = 0;
+
+       u16 trans_id, questions, answers, authority, additional, datalength;
+       u16 flags = 0;
+       u32 ttl, ttl_r = 0xffffffff;
+       struct reply reply;
+       struct request *req = NULL;
+       unsigned int i;
+
+       ASSERT_LOCKED(base);
+
+       GET16(trans_id);
+       GET16(flags);
+       GET16(questions);
+       GET16(answers);
+       GET16(authority);
+       GET16(additional);
+       (void) authority; /* suppress "unused variable" warnings. */
+       (void) additional; /* suppress "unused variable" warnings. */
+
+       req = request_find_from_trans_id(base, trans_id);
+       if (!req) return -1;
+       EVUTIL_ASSERT(req->base == base);
+
+       memset(&reply, 0, sizeof(reply));
+
+       /* If it's not an answer, it doesn't correspond to any request. */
+       if (!(flags & 0x8000)) return -1;  /* must be an answer */
+       if ((flags & 0x020f) && (flags & 0x020f) != DNS_ERR_NOTEXIST) {
+               /* there was an error and it's not NXDOMAIN */
+               goto err;
+       }
+       /* if (!answers) return; */  /* must have an answer of some form */
+
+       /* This macro skips a name in the DNS reply. */
+#define SKIP_NAME                                              \
+       do { tmp_name[0] = '\0';                                \
+               if (name_parse(packet, length, &j, tmp_name,    \
+                       sizeof(tmp_name))<0)                    \
+                       goto err;                               \
+       } while (0)
+#define TEST_NAME                                                      \
+       do { tmp_name[0] = '\0';                                        \
+               cmp_name[0] = '\0';                                     \
+               k = j;                                                  \
+               if (name_parse(packet, length, &j, tmp_name,            \
+                       sizeof(tmp_name))<0)                            \
+                       goto err;                                       \
+               if (name_parse(req->request, req->request_len, &k,      \
+                       cmp_name, sizeof(cmp_name))<0)                  \
+                       goto err;                                       \
+               if (base->global_randomize_case) {                      \
+                       if (strcmp(tmp_name, cmp_name) == 0)            \
+                               name_matches = 1;                       \
+               } else {                                                \
+                       if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0) \
+                               name_matches = 1;                       \
+               }                                                       \
+       } while (0)
+
+       reply.type = req->request_type;
+
+       /* skip over each question in the reply */
+       for (i = 0; i < questions; ++i) {
+               /* the question looks like
+                *   <label:name><u16:type><u16:class>
+                */
+               TEST_NAME;
+               j += 4;
+               if (j > length) goto err;
+       }
+
+       if (!name_matches)
+               goto err;
+
+       /* now we have the answer section which looks like
+        * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
+        */
+
+       for (i = 0; i < answers; ++i) {
+               u16 type, class;
+
+               SKIP_NAME;
+               GET16(type);
+               GET16(class);
+               GET32(ttl);
+               GET16(datalength);
+
+               if (type == TYPE_A && class == CLASS_INET) {
+                       int addrcount, addrtocopy;
+                       if (req->request_type != TYPE_A) {
+                               j += datalength; continue;
+                       }
+                       if ((datalength & 3) != 0) /* not an even number of As. */
+                           goto err;
+                       addrcount = datalength >> 2;
+                       addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
+
+                       ttl_r = MIN(ttl_r, ttl);
+                       /* we only bother with the first four addresses. */
+                       if (j + 4*addrtocopy > length) goto err;
+                       memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
+                                  packet + j, 4*addrtocopy);
+                       j += 4*addrtocopy;
+                       reply.data.a.addrcount += addrtocopy;
+                       reply.have_answer = 1;
+                       if (reply.data.a.addrcount == MAX_V4_ADDRS) break;
+               } else if (type == TYPE_PTR && class == CLASS_INET) {
+                       if (req->request_type != TYPE_PTR) {
+                               j += datalength; continue;
+                       }
+                       if (name_parse(packet, length, &j, reply.data.ptr.name,
+                                                  sizeof(reply.data.ptr.name))<0)
+                               goto err;
+                       ttl_r = MIN(ttl_r, ttl);
+                       reply.have_answer = 1;
+                       break;
+               } else if (type == TYPE_CNAME) {
+                       char cname[HOST_NAME_MAX];
+                       if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) {
+                               j += datalength; continue;
+                       }
+                       if (name_parse(packet, length, &j, cname,
+                               sizeof(cname))<0)
+                               goto err;
+                       *req->put_cname_in_ptr = mm_strdup(cname);
+               } else if (type == TYPE_AAAA && class == CLASS_INET) {
+                       int addrcount, addrtocopy;
+                       if (req->request_type != TYPE_AAAA) {
+                               j += datalength; continue;
+                       }
+                       if ((datalength & 15) != 0) /* not an even number of AAAAs. */
+                               goto err;
+                       addrcount = datalength >> 4;  /* each address is 16 bytes long */
+                       addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
+                       ttl_r = MIN(ttl_r, ttl);
+
+                       /* we only bother with the first four addresses. */
+                       if (j + 16*addrtocopy > length) goto err;
+                       memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
+                                  packet + j, 16*addrtocopy);
+                       reply.data.aaaa.addrcount += addrtocopy;
+                       j += 16*addrtocopy;
+                       reply.have_answer = 1;
+                       if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break;
+               } else {
+                       /* skip over any other type of resource */
+                       j += datalength;
+               }
+       }
+
+       if (!reply.have_answer) {
+               for (i = 0; i < authority; ++i) {
+                       u16 type, class;
+                       SKIP_NAME;
+                       GET16(type);
+                       GET16(class);
+                       GET32(ttl);
+                       GET16(datalength);
+                       if (type == TYPE_SOA && class == CLASS_INET) {
+                               u32 serial, refresh, retry, expire, minimum;
+                               SKIP_NAME;
+                               SKIP_NAME;
+                               GET32(serial);
+                               GET32(refresh);
+                               GET32(retry);
+                               GET32(expire);
+                               GET32(minimum);
+                               (void)expire;
+                               (void)retry;
+                               (void)refresh;
+                               (void)serial;
+                               ttl_r = MIN(ttl_r, ttl);
+                               ttl_r = MIN(ttl_r, minimum);
+                       } else {
+                               /* skip over any other type of resource */
+                               j += datalength;
+                       }
+               }
+       }
+
+       if (ttl_r == 0xffffffff)
+               ttl_r = 0;
+
+       reply_handle(req, flags, ttl_r, &reply);
+       return 0;
+ err:
+       if (req)
+               reply_handle(req, flags, 0, NULL);
+       return -1;
+}
+
+/* Parse a raw request (packet,length) sent to a nameserver port (port) from */
+/* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
+/* callback. */
+static int
+request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
+{
+       int j = 0;      /* index into packet */
+       u16 _t;  /* used by the macros */
+       char tmp_name[256]; /* used by the macros */
+
+       int i;
+       u16 trans_id, flags, questions, answers, authority, additional;
+       struct server_request *server_req = NULL;
+
+       ASSERT_LOCKED(port);
+
+       /* Get the header fields */
+       GET16(trans_id);
+       GET16(flags);
+       GET16(questions);
+       GET16(answers);
+       GET16(authority);
+       GET16(additional);
+       (void)answers;
+       (void)additional;
+       (void)authority;
+
+       if (flags & 0x8000) return -1; /* Must not be an answer. */
+       flags &= 0x0110; /* Only RD and CD get preserved. */
+
+       server_req = mm_malloc(sizeof(struct server_request));
+       if (server_req == NULL) return -1;
+       memset(server_req, 0, sizeof(struct server_request));
+
+       server_req->trans_id = trans_id;
+       memcpy(&server_req->addr, addr, addrlen);
+       server_req->addrlen = addrlen;
+
+       server_req->base.flags = flags;
+       server_req->base.nquestions = 0;
+       server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions);
+       if (server_req->base.questions == NULL)
+               goto err;
+
+       for (i = 0; i < questions; ++i) {
+               u16 type, class;
+               struct evdns_server_question *q;
+               int namelen;
+               if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
+                       goto err;
+               GET16(type);
+               GET16(class);
+               namelen = (int)strlen(tmp_name);
+               q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
+               if (!q)
+                       goto err;
+               q->type = type;
+               q->dns_question_class = class;
+               memcpy(q->name, tmp_name, namelen+1);
+               server_req->base.questions[server_req->base.nquestions++] = q;
+       }
+
+       /* Ignore answers, authority, and additional. */
+
+       server_req->port = port;
+       port->refcnt++;
+
+       /* Only standard queries are supported. */
+       if (flags & 0x7800) {
+               evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
+               return -1;
+       }
+
+       port->user_callback(&(server_req->base), port->user_data);
+
+       return 0;
+err:
+       if (server_req) {
+               if (server_req->base.questions) {
+                       for (i = 0; i < server_req->base.nquestions; ++i)
+                               mm_free(server_req->base.questions[i]);
+                       mm_free(server_req->base.questions);
+               }
+               mm_free(server_req);
+       }
+       return -1;
+
+#undef SKIP_NAME
+#undef GET32
+#undef GET16
+#undef GET8
+}
+
+
+void
+evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
+{
+}
+
+void
+evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
+{
+}
+
+/* Try to choose a strong transaction id which isn't already in flight */
+static u16
+transaction_id_pick(struct evdns_base *base) {
+       ASSERT_LOCKED(base);
+       for (;;) {
+               u16 trans_id;
+               evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id));
+
+               if (trans_id == 0xffff) continue;
+               /* now check to see if that id is already inflight */
+               if (request_find_from_trans_id(base, trans_id) == NULL)
+                       return trans_id;
+       }
+}
+
+/* choose a namesever to use. This function will try to ignore */
+/* nameservers which we think are down and load balance across the rest */
+/* by updating the server_head global each time. */
+static struct nameserver *
+nameserver_pick(struct evdns_base *base) {
+       struct nameserver *started_at = base->server_head, *picked;
+       ASSERT_LOCKED(base);
+       if (!base->server_head) return NULL;
+
+       /* if we don't have any good nameservers then there's no */
+       /* point in trying to find one. */
+       if (!base->global_good_nameservers) {
+               base->server_head = base->server_head->next;
+               return base->server_head;
+       }
+
+       /* remember that nameservers are in a circular list */
+       for (;;) {
+               if (base->server_head->state) {
+                       /* we think this server is currently good */
+                       picked = base->server_head;
+                       base->server_head = base->server_head->next;
+                       return picked;
+               }
+
+               base->server_head = base->server_head->next;
+               if (base->server_head == started_at) {
+                       /* all the nameservers seem to be down */
+                       /* so we just return this one and hope for the */
+                       /* best */
+                       EVUTIL_ASSERT(base->global_good_nameservers == 0);
+                       picked = base->server_head;
+                       base->server_head = base->server_head->next;
+                       return picked;
+               }
+       }
+}
+
+/* this is called when a namesever socket is ready for reading */
+static void
+nameserver_read(struct nameserver *ns) {
+       struct sockaddr_storage ss;
+       ev_socklen_t addrlen = sizeof(ss);
+       u8 packet[1500];
+       char addrbuf[128];
+       ASSERT_LOCKED(ns->base);
+
+       for (;;) {
+               const int r = recvfrom(ns->socket, (void*)packet,
+                   sizeof(packet), 0,
+                   (struct sockaddr*)&ss, &addrlen);
+               if (r < 0) {
+                       int err = evutil_socket_geterror(ns->socket);
+                       if (EVUTIL_ERR_RW_RETRIABLE(err))
+                               return;
+                       nameserver_failed(ns,
+                           evutil_socket_error_to_string(err));
+                       return;
+               }
+               if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
+                       (struct sockaddr*)&ns->address, 0)) {
+                       log(EVDNS_LOG_WARN, "Address mismatch on received "
+                           "DNS packet.  Apparent source was %s",
+                           evutil_format_sockaddr_port(
+                                   (struct sockaddr *)&ss,
+                                   addrbuf, sizeof(addrbuf)));
+                       return;
+               }
+
+               ns->timedout = 0;
+               reply_parse(ns->base, packet, r);
+       }
+}
+
+/* Read a packet from a DNS client on a server port s, parse it, and */
+/* act accordingly. */
+static void
+server_port_read(struct evdns_server_port *s) {
+       u8 packet[1500];
+       struct sockaddr_storage addr;
+       ev_socklen_t addrlen;
+       int r;
+       ASSERT_LOCKED(s);
+
+       for (;;) {
+               addrlen = sizeof(struct sockaddr_storage);
+               r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
+                                        (struct sockaddr*) &addr, &addrlen);
+               if (r < 0) {
+                       int err = evutil_socket_geterror(s->socket);
+                       if (EVUTIL_ERR_RW_RETRIABLE(err))
+                               return;
+                       log(EVDNS_LOG_WARN,
+                           "Error %s (%d) while reading request.",
+                           evutil_socket_error_to_string(err), err);
+                       return;
+               }
+               request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
+       }
+}
+
+/* Try to write all pending replies on a given DNS server port. */
+static void
+server_port_flush(struct evdns_server_port *port)
+{
+       struct server_request *req = port->pending_replies;
+       ASSERT_LOCKED(port);
+       while (req) {
+               int r = sendto(port->socket, req->response, (int)req->response_len, 0,
+                          (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
+               if (r < 0) {
+                       int err = evutil_socket_geterror(port->socket);
+                       if (EVUTIL_ERR_RW_RETRIABLE(err))
+                               return;
+                       log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err);
+               }
+               if (server_request_free(req)) {
+                       /* we released the last reference to req->port. */
+                       return;
+               } else {
+                       EVUTIL_ASSERT(req != port->pending_replies);
+                       req = port->pending_replies;
+               }
+       }
+
+       /* We have no more pending requests; stop listening for 'writeable' events. */
+       (void) event_del(&port->event);
+       event_assign(&port->event, port->event_base,
+                                port->socket, EV_READ | EV_PERSIST,
+                                server_port_ready_callback, port);
+
+       if (event_add(&port->event, NULL) < 0) {
+               log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
+               /* ???? Do more? */
+       }
+}
+
+/* set if we are waiting for the ability to write to this server. */
+/* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
+/* we stop these events. */
+static void
+nameserver_write_waiting(struct nameserver *ns, char waiting) {
+       ASSERT_LOCKED(ns->base);
+       if (ns->write_waiting == waiting) return;
+
+       ns->write_waiting = waiting;
+       (void) event_del(&ns->event);
+       event_assign(&ns->event, ns->base->event_base,
+           ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
+           nameserver_ready_callback, ns);
+       if (event_add(&ns->event, NULL) < 0) {
+               char addrbuf[128];
+               log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
+                   evutil_format_sockaddr_port(
+                           (struct sockaddr *)&ns->address,
+                           addrbuf, sizeof(addrbuf)));
+               /* ???? Do more? */
+       }
+}
+
+/* a callback function. Called by libevent when the kernel says that */
+/* a nameserver socket is ready for writing or reading */
+static void
+nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) {
+       struct nameserver *ns = (struct nameserver *) arg;
+       (void)fd;
+
+       EVDNS_LOCK(ns->base);
+       if (events & EV_WRITE) {
+               ns->choked = 0;
+               if (!evdns_transmit(ns->base)) {
+                       nameserver_write_waiting(ns, 0);
+               }
+       }
+       if (events & EV_READ) {
+               nameserver_read(ns);
+       }
+       EVDNS_UNLOCK(ns->base);
+}
+
+/* a callback function. Called by libevent when the kernel says that */
+/* a server socket is ready for writing or reading. */
+static void
+server_port_ready_callback(evutil_socket_t fd, short events, void *arg) {
+       struct evdns_server_port *port = (struct evdns_server_port *) arg;
+       (void) fd;
+
+       EVDNS_LOCK(port);
+       if (events & EV_WRITE) {
+               port->choked = 0;
+               server_port_flush(port);
+       }
+       if (events & EV_READ) {
+               server_port_read(port);
+       }
+       EVDNS_UNLOCK(port);
+}
+
+/* This is an inefficient representation; only use it via the dnslabel_table_*
+ * functions, so that is can be safely replaced with something smarter later. */
+#define MAX_LABELS 128
+/* Structures used to implement name compression */
+struct dnslabel_entry { char *v; off_t pos; };
+struct dnslabel_table {
+       int n_labels; /* number of current entries */
+       /* map from name to position in message */
+       struct dnslabel_entry labels[MAX_LABELS];
+};
+
+/* Initialize dnslabel_table. */
+static void
+dnslabel_table_init(struct dnslabel_table *table)
+{
+       table->n_labels = 0;
+}
+
+/* Free all storage held by table, but not the table itself. */
+static void
+dnslabel_clear(struct dnslabel_table *table)
+{
+       int i;
+       for (i = 0; i < table->n_labels; ++i)
+               mm_free(table->labels[i].v);
+       table->n_labels = 0;
+}
+
+/* return the position of the label in the current message, or -1 if the label */
+/* hasn't been used yet. */
+static int
+dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
+{
+       int i;
+       for (i = 0; i < table->n_labels; ++i) {
+               if (!strcmp(label, table->labels[i].v))
+                       return table->labels[i].pos;
+       }
+       return -1;
+}
+
+/* remember that we've used the label at position pos */
+static int
+dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
+{
+       char *v;
+       int p;
+       if (table->n_labels == MAX_LABELS)
+               return (-1);
+       v = mm_strdup(label);
+       if (v == NULL)
+               return (-1);
+       p = table->n_labels++;
+       table->labels[p].v = v;
+       table->labels[p].pos = pos;
+
+       return (0);
+}
+
+/* Converts a string to a length-prefixed set of DNS labels, starting */
+/* at buf[j]. name and buf must not overlap. name_len should be the length */
+/* of name.     table is optional, and is used for compression. */
+/* */
+/* Input: abc.def */
+/* Output: <3>abc<3>def<0> */
+/* */
+/* Returns the first index after the encoded name, or negative on error. */
+/*      -1      label was > 63 bytes */
+/*      -2      name too long to fit in buffer. */
+/* */
+static off_t
+dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
+                                 const char *name, const size_t name_len,
+                                 struct dnslabel_table *table) {
+       const char *end = name + name_len;
+       int ref = 0;
+       u16 _t;
+
+#define APPEND16(x) do {                                               \
+               if (j + 2 > (off_t)buf_len)                             \
+                       goto overflow;                                  \
+               _t = htons(x);                                          \
+               memcpy(buf + j, &_t, 2);                                \
+               j += 2;                                                 \
+       } while (0)
+#define APPEND32(x) do {                                               \
+               if (j + 4 > (off_t)buf_len)                             \
+                       goto overflow;                                  \
+               _t32 = htonl(x);                                        \
+               memcpy(buf + j, &_t32, 4);                              \
+               j += 4;                                                 \
+       } while (0)
+
+       if (name_len > 255) return -2;
+
+       for (;;) {
+               const char *const start = name;
+               if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
+                       APPEND16(ref | 0xc000);
+                       return j;
+               }
+               name = strchr(name, '.');
+               if (!name) {
+                       const size_t label_len = end - start;
+                       if (label_len > 63) return -1;
+                       if ((size_t)(j+label_len+1) > buf_len) return -2;
+                       if (table) dnslabel_table_add(table, start, j);
+                       buf[j++] = (ev_uint8_t)label_len;
+
+                       memcpy(buf + j, start, label_len);
+                       j += (int) label_len;
+                       break;
+               } else {
+                       /* append length of the label. */
+                       const size_t label_len = name - start;
+                       if (label_len > 63) return -1;
+                       if ((size_t)(j+label_len+1) > buf_len) return -2;
+                       if (table) dnslabel_table_add(table, start, j);
+                       buf[j++] = (ev_uint8_t)label_len;
+
+                       memcpy(buf + j, start, label_len);
+                       j += (int) label_len;
+                       /* hop over the '.' */
+                       name++;
+               }
+       }
+
+       /* the labels must be terminated by a 0. */
+       /* It's possible that the name ended in a . */
+       /* in which case the zero is already there */
+       if (!j || buf[j-1]) buf[j++] = 0;
+       return j;
+ overflow:
+       return (-2);
+}
+
+/* Finds the length of a dns request for a DNS name of the given */
+/* length. The actual request may be smaller than the value returned */
+/* here */
+static size_t
+evdns_request_len(const size_t name_len) {
+       return 96 + /* length of the DNS standard header */
+               name_len + 2 +
+               4;  /* space for the resource type */
+}
+
+/* build a dns request packet into buf. buf should be at least as long */
+/* as evdns_request_len told you it should be. */
+/* */
+/* Returns the amount of space used. Negative on error. */
+static int
+evdns_request_data_build(const char *const name, const size_t name_len,
+    const u16 trans_id, const u16 type, const u16 class,
+    u8 *const buf, size_t buf_len) {
+       off_t j = 0;  /* current offset into buf */
+       u16 _t;  /* used by the macros */
+
+       APPEND16(trans_id);
+       APPEND16(0x0100);  /* standard query, recusion needed */
+       APPEND16(1);  /* one question */
+       APPEND16(0);  /* no answers */
+       APPEND16(0);  /* no authority */
+       APPEND16(0);  /* no additional */
+
+       j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
+       if (j < 0) {
+               return (int)j;
+       }
+
+       APPEND16(type);
+       APPEND16(class);
+
+       return (int)j;
+ overflow:
+       return (-1);
+}
+
+/* exported function */
+struct evdns_server_port *
+evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
+{
+       struct evdns_server_port *port;
+       if (flags)
+               return NULL; /* flags not yet implemented */
+       if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
+               return NULL;
+       memset(port, 0, sizeof(struct evdns_server_port));
+
+
+       port->socket = socket;
+       port->refcnt = 1;
+       port->choked = 0;
+       port->closing = 0;
+       port->user_callback = cb;
+       port->user_data = user_data;
+       port->pending_replies = NULL;
+       port->event_base = base;
+
+       event_assign(&port->event, port->event_base,
+                                port->socket, EV_READ | EV_PERSIST,
+                                server_port_ready_callback, port);
+       if (event_add(&port->event, NULL) < 0) {
+               mm_free(port);
+               return NULL;
+       }
+       EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       return port;
+}
+
+struct evdns_server_port *
+evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
+{
+       return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data);
+}
+
+/* exported function */
+void
+evdns_close_server_port(struct evdns_server_port *port)
+{
+       EVDNS_LOCK(port);
+       if (--port->refcnt == 0) {
+               EVDNS_UNLOCK(port);
+               server_port_free(port);
+       } else {
+               port->closing = 1;
+       }
+}
+
+/* exported function */
+int
+evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
+{
+       struct server_request *req = TO_SERVER_REQUEST(_req);
+       struct server_reply_item **itemp, *item;
+       int *countp;
+       int result = -1;
+
+       EVDNS_LOCK(req->port);
+       if (req->response) /* have we already answered? */
+               goto done;
+
+       switch (section) {
+       case EVDNS_ANSWER_SECTION:
+               itemp = &req->answer;
+               countp = &req->n_answer;
+               break;
+       case EVDNS_AUTHORITY_SECTION:
+               itemp = &req->authority;
+               countp = &req->n_authority;
+               break;
+       case EVDNS_ADDITIONAL_SECTION:
+               itemp = &req->additional;
+               countp = &req->n_additional;
+               break;
+       default:
+               goto done;
+       }
+       while (*itemp) {
+               itemp = &((*itemp)->next);
+       }
+       item = mm_malloc(sizeof(struct server_reply_item));
+       if (!item)
+               goto done;
+       item->next = NULL;
+       if (!(item->name = mm_strdup(name))) {
+               mm_free(item);
+               goto done;
+       }
+       item->type = type;
+       item->dns_question_class = class;
+       item->ttl = ttl;
+       item->is_name = is_name != 0;
+       item->datalen = 0;
+       item->data = NULL;
+       if (data) {
+               if (item->is_name) {
+                       if (!(item->data = mm_strdup(data))) {
+                               mm_free(item->name);
+                               mm_free(item);
+                               goto done;
+                       }
+                       item->datalen = (u16)-1;
+               } else {
+                       if (!(item->data = mm_malloc(datalen))) {
+                               mm_free(item->name);
+                               mm_free(item);
+                               goto done;
+                       }
+                       item->datalen = datalen;
+                       memcpy(item->data, data, datalen);
+               }
+       }
+
+       *itemp = item;
+       ++(*countp);
+       result = 0;
+done:
+       EVDNS_UNLOCK(req->port);
+       return result;
+}
+
+/* exported function */
+int
+evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
+{
+       return evdns_server_request_add_reply(
+                 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
+                 ttl, n*4, 0, addrs);
+}
+
+/* exported function */
+int
+evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
+{
+       return evdns_server_request_add_reply(
+                 req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
+                 ttl, n*16, 0, addrs);
+}
+
+/* exported function */
+int
+evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
+{
+       u32 a;
+       char buf[32];
+       if (in && inaddr_name)
+               return -1;
+       else if (!in && !inaddr_name)
+               return -1;
+       if (in) {
+               a = ntohl(in->s_addr);
+               evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
+                               (int)(u8)((a    )&0xff),
+                               (int)(u8)((a>>8 )&0xff),
+                               (int)(u8)((a>>16)&0xff),
+                               (int)(u8)((a>>24)&0xff));
+               inaddr_name = buf;
+       }
+       return evdns_server_request_add_reply(
+                 req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
+                 ttl, -1, 1, hostname);
+}
+
+/* exported function */
+int
+evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
+{
+       return evdns_server_request_add_reply(
+                 req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
+                 ttl, -1, 1, cname);
+}
+
+/* exported function */
+void
+evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags)
+{
+       struct server_request *req = TO_SERVER_REQUEST(exreq);
+       req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD);
+       req->base.flags |= flags;
+}
+
+static int
+evdns_server_request_format_response(struct server_request *req, int err)
+{
+       unsigned char buf[1500];
+       size_t buf_len = sizeof(buf);
+       off_t j = 0, r;
+       u16 _t;
+       u32 _t32;
+       int i;
+       u16 flags;
+       struct dnslabel_table table;
+
+       if (err < 0 || err > 15) return -1;
+
+       /* Set response bit and error code; copy OPCODE and RD fields from
+        * question; copy RA and AA if set by caller. */
+       flags = req->base.flags;
+       flags |= (0x8000 | err);
+
+       dnslabel_table_init(&table);
+       APPEND16(req->trans_id);
+       APPEND16(flags);
+       APPEND16(req->base.nquestions);
+       APPEND16(req->n_answer);
+       APPEND16(req->n_authority);
+       APPEND16(req->n_additional);
+
+       /* Add questions. */
+       for (i=0; i < req->base.nquestions; ++i) {
+               const char *s = req->base.questions[i]->name;
+               j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
+               if (j < 0) {
+                       dnslabel_clear(&table);
+                       return (int) j;
+               }
+               APPEND16(req->base.questions[i]->type);
+               APPEND16(req->base.questions[i]->dns_question_class);
+       }
+
+       /* Add answer, authority, and additional sections. */
+       for (i=0; i<3; ++i) {
+               struct server_reply_item *item;
+               if (i==0)
+                       item = req->answer;
+               else if (i==1)
+                       item = req->authority;
+               else
+                       item = req->additional;
+               while (item) {
+                       r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
+                       if (r < 0)
+                               goto overflow;
+                       j = r;
+
+                       APPEND16(item->type);
+                       APPEND16(item->dns_question_class);
+                       APPEND32(item->ttl);
+                       if (item->is_name) {
+                               off_t len_idx = j, name_start;
+                               j += 2;
+                               name_start = j;
+                               r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
+                               if (r < 0)
+                                       goto overflow;
+                               j = r;
+                               _t = htons( (short) (j-name_start) );
+                               memcpy(buf+len_idx, &_t, 2);
+                       } else {
+                               APPEND16(item->datalen);
+                               if (j+item->datalen > (off_t)buf_len)
+                                       goto overflow;
+                               memcpy(buf+j, item->data, item->datalen);
+                               j += item->datalen;
+                       }
+                       item = item->next;
+               }
+       }
+
+       if (j > 512) {
+overflow:
+               j = 512;
+               buf[2] |= 0x02; /* set the truncated bit. */
+       }
+
+       req->response_len = j;
+
+       if (!(req->response = mm_malloc(req->response_len))) {
+               server_request_free_answers(req);
+               dnslabel_clear(&table);
+               return (-1);
+       }
+       memcpy(req->response, buf, req->response_len);
+       server_request_free_answers(req);
+       dnslabel_clear(&table);
+       return (0);
+}
+
+/* exported function */
+int
+evdns_server_request_respond(struct evdns_server_request *_req, int err)
+{
+       struct server_request *req = TO_SERVER_REQUEST(_req);
+       struct evdns_server_port *port = req->port;
+       int r = -1;
+
+       EVDNS_LOCK(port);
+       if (!req->response) {
+               if ((r = evdns_server_request_format_response(req, err))<0)
+                       goto done;
+       }
+
+       r = sendto(port->socket, req->response, (int)req->response_len, 0,
+                          (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
+       if (r<0) {
+               int sock_err = evutil_socket_geterror(port->socket);
+               if (EVUTIL_ERR_RW_RETRIABLE(sock_err))
+                       goto done;
+
+               if (port->pending_replies) {
+                       req->prev_pending = port->pending_replies->prev_pending;
+                       req->next_pending = port->pending_replies;
+                       req->prev_pending->next_pending =
+                               req->next_pending->prev_pending = req;
+               } else {
+                       req->prev_pending = req->next_pending = req;
+                       port->pending_replies = req;
+                       port->choked = 1;
+
+                       (void) event_del(&port->event);
+                       event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
+
+                       if (event_add(&port->event, NULL) < 0) {
+                               log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
+                       }
+
+               }
+
+               r = 1;
+               goto done;
+       }
+       if (server_request_free(req)) {
+               r = 0;
+               goto done;
+       }
+
+       if (port->pending_replies)
+               server_port_flush(port);
+
+       r = 0;
+done:
+       EVDNS_UNLOCK(port);
+       return r;
+}
+
+/* Free all storage held by RRs in req. */
+static void
+server_request_free_answers(struct server_request *req)
+{
+       struct server_reply_item *victim, *next, **list;
+       int i;
+       for (i = 0; i < 3; ++i) {
+               if (i==0)
+                       list = &req->answer;
+               else if (i==1)
+                       list = &req->authority;
+               else
+                       list = &req->additional;
+
+               victim = *list;
+               while (victim) {
+                       next = victim->next;
+                       mm_free(victim->name);
+                       if (victim->data)
+                               mm_free(victim->data);
+                       mm_free(victim);
+                       victim = next;
+               }
+               *list = NULL;
+       }
+}
+
+/* Free all storage held by req, and remove links to it. */
+/* return true iff we just wound up freeing the server_port. */
+static int
+server_request_free(struct server_request *req)
+{
+       int i, rc=1, lock=0;
+       if (req->base.questions) {
+               for (i = 0; i < req->base.nquestions; ++i)
+                       mm_free(req->base.questions[i]);
+               mm_free(req->base.questions);
+       }
+
+       if (req->port) {
+               EVDNS_LOCK(req->port);
+               lock=1;
+               if (req->port->pending_replies == req) {
+                       if (req->next_pending && req->next_pending != req)
+                               req->port->pending_replies = req->next_pending;
+                       else
+                               req->port->pending_replies = NULL;
+               }
+               rc = --req->port->refcnt;
+       }
+
+       if (req->response) {
+               mm_free(req->response);
+       }
+
+       server_request_free_answers(req);
+
+       if (req->next_pending && req->next_pending != req) {
+               req->next_pending->prev_pending = req->prev_pending;
+               req->prev_pending->next_pending = req->next_pending;
+       }
+
+       if (rc == 0) {
+               EVDNS_UNLOCK(req->port); /* ????? nickm */
+               server_port_free(req->port);
+               mm_free(req);
+               return (1);
+       }
+       if (lock)
+               EVDNS_UNLOCK(req->port);
+       mm_free(req);
+       return (0);
+}
+
+/* Free all storage held by an evdns_server_port.  Only called when  */
+static void
+server_port_free(struct evdns_server_port *port)
+{
+       EVUTIL_ASSERT(port);
+       EVUTIL_ASSERT(!port->refcnt);
+       EVUTIL_ASSERT(!port->pending_replies);
+       if (port->socket > 0) {
+               evutil_closesocket(port->socket);
+               port->socket = -1;
+       }
+       (void) event_del(&port->event);
+       event_debug_unassign(&port->event);
+       EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       mm_free(port);
+}
+
+/* exported function */
+int
+evdns_server_request_drop(struct evdns_server_request *_req)
+{
+       struct server_request *req = TO_SERVER_REQUEST(_req);
+       server_request_free(req);
+       return 0;
+}
+
+/* exported function */
+int
+evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
+{
+       struct server_request *req = TO_SERVER_REQUEST(_req);
+       if (addr_len < (int)req->addrlen)
+               return -1;
+       memcpy(sa, &(req->addr), req->addrlen);
+       return req->addrlen;
+}
+
+#undef APPEND16
+#undef APPEND32
+
+/* this is a libevent callback function which is called when a request */
+/* has timed out. */
+static void
+evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
+       struct request *const req = (struct request *) arg;
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       struct evdns_base *base = req->base;
+#endif
+       (void) fd;
+       (void) events;
+
+       log(EVDNS_LOG_DEBUG, "Request %p timed out", arg);
+       EVDNS_LOCK(base);
+
+       req->ns->timedout++;
+       if (req->ns->timedout > req->base->global_max_nameserver_timeout) {
+               req->ns->timedout = 0;
+               nameserver_failed(req->ns, "request timed out.");
+       }
+
+       if (req->tx_count >= req->base->global_max_retransmits) {
+               /* this request has failed */
+               reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
+               request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
+       } else {
+               /* retransmit it */
+               (void) evtimer_del(&req->timeout_event);
+               evdns_request_transmit(req);
+       }
+       EVDNS_UNLOCK(base);
+}
+
+/* try to send a request to a given server. */
+/* */
+/* return: */
+/*   0 ok */
+/*   1 temporary failure */
+/*   2 other failure */
+static int
+evdns_request_transmit_to(struct request *req, struct nameserver *server) {
+       int r;
+       ASSERT_LOCKED(req->base);
+       ASSERT_VALID_REQUEST(req);
+       r = sendto(server->socket, (void*)req->request, req->request_len, 0,
+           (struct sockaddr *)&server->address, server->addrlen);
+       if (r < 0) {
+               int err = evutil_socket_geterror(server->socket);
+               if (EVUTIL_ERR_RW_RETRIABLE(err))
+                       return 1;
+               nameserver_failed(req->ns, evutil_socket_error_to_string(err));
+               return 2;
+       } else if (r != (int)req->request_len) {
+               return 1;  /* short write */
+       } else {
+               return 0;
+       }
+}
+
+/* try to send a request, updating the fields of the request */
+/* as needed */
+/* */
+/* return: */
+/*   0 ok */
+/*   1 failed */
+static int
+evdns_request_transmit(struct request *req) {
+       int retcode = 0, r;
+
+       ASSERT_LOCKED(req->base);
+       ASSERT_VALID_REQUEST(req);
+       /* if we fail to send this packet then this flag marks it */
+       /* for evdns_transmit */
+       req->transmit_me = 1;
+       EVUTIL_ASSERT(req->trans_id != 0xffff);
+
+       if (req->ns->choked) {
+               /* don't bother trying to write to a socket */
+               /* which we have had EAGAIN from */
+               return 1;
+       }
+
+       r = evdns_request_transmit_to(req, req->ns);
+       switch (r) {
+       case 1:
+               /* temp failure */
+               req->ns->choked = 1;
+               nameserver_write_waiting(req->ns, 1);
+               return 1;
+       case 2:
+               /* failed to transmit the request entirely. */
+               retcode = 1;
+               /* fall through: we'll set a timeout, which will time out,
+                * and make us retransmit the request anyway. */
+       default:
+               /* all ok */
+               log(EVDNS_LOG_DEBUG,
+                   "Setting timeout for request %p", req);
+               if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
+                       log(EVDNS_LOG_WARN,
+                     "Error from libevent when adding timer for request %p",
+                           req);
+                       /* ???? Do more? */
+               }
+               req->tx_count++;
+               req->transmit_me = 0;
+               return retcode;
+       }
+}
+
+static void
+nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
+       struct nameserver *const ns = (struct nameserver *) arg;
+       (void) type;
+       (void) count;
+       (void) ttl;
+       (void) addresses;
+
+       EVDNS_LOCK(ns->base);
+       ns->probe_request = NULL;
+       if (result == DNS_ERR_CANCEL) {
+               /* We canceled this request because the nameserver came up
+                * for some other reason.  Do not change our opinion about
+                * the nameserver. */
+       } else if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
+               /* this is a good reply */
+               nameserver_up(ns);
+       } else {
+               nameserver_probe_failed(ns);
+       }
+       EVDNS_UNLOCK(ns->base);
+}
+
+static void
+nameserver_send_probe(struct nameserver *const ns) {
+       struct evdns_request *handle;
+       struct request *req;
+       char addrbuf[128];
+       /* here we need to send a probe to a given nameserver */
+       /* in the hope that it is up now. */
+
+       ASSERT_LOCKED(ns->base);
+       log(EVDNS_LOG_DEBUG, "Sending probe to %s",
+           evutil_format_sockaddr_port(
+                   (struct sockaddr *)&ns->address,
+                   addrbuf, sizeof(addrbuf)));
+       handle = mm_calloc(1, sizeof(*handle));
+       if (!handle) return;
+       req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
+       if (!req) return;
+       ns->probe_request = handle;
+       /* we force this into the inflight queue no matter what */
+       request_trans_id_set(req, transaction_id_pick(ns->base));
+       req->ns = ns;
+       request_submit(req);
+}
+
+/* returns: */
+/*   0 didn't try to transmit anything */
+/*   1 tried to transmit something */
+static int
+evdns_transmit(struct evdns_base *base) {
+       char did_try_to_transmit = 0;
+       int i;
+
+       ASSERT_LOCKED(base);
+       for (i = 0; i < base->n_req_heads; ++i) {
+               if (base->req_heads[i]) {
+                       struct request *const started_at = base->req_heads[i], *req = started_at;
+                       /* first transmit all the requests which are currently waiting */
+                       do {
+                               if (req->transmit_me) {
+                                       did_try_to_transmit = 1;
+                                       evdns_request_transmit(req);
+                               }
+
+                               req = req->next;
+                       } while (req != started_at);
+               }
+       }
+
+       return did_try_to_transmit;
+}
+
+/* exported function */
+int
+evdns_base_count_nameservers(struct evdns_base *base)
+{
+       const struct nameserver *server;
+       int n = 0;
+
+       EVDNS_LOCK(base);
+       server = base->server_head;
+       if (!server)
+               goto done;
+       do {
+               ++n;
+               server = server->next;
+       } while (server != base->server_head);
+done:
+       EVDNS_UNLOCK(base);
+       return n;
+}
+
+int
+evdns_count_nameservers(void)
+{
+       return evdns_base_count_nameservers(current_base);
+}
+
+/* exported function */
+int
+evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
+{
+       struct nameserver *server, *started_at;
+       int i;
+
+       EVDNS_LOCK(base);
+       server = base->server_head;
+       started_at = base->server_head;
+       if (!server) {
+               EVDNS_UNLOCK(base);
+               return 0;
+       }
+       while (1) {
+               struct nameserver *next = server->next;
+               (void) event_del(&server->event);
+               if (evtimer_initialized(&server->timeout_event))
+                       (void) evtimer_del(&server->timeout_event);
+               if (server->socket >= 0)
+                       evutil_closesocket(server->socket);
+               mm_free(server);
+               if (next == started_at)
+                       break;
+               server = next;
+       }
+       base->server_head = NULL;
+       base->global_good_nameservers = 0;
+
+       for (i = 0; i < base->n_req_heads; ++i) {
+               struct request *req, *req_started_at;
+               req = req_started_at = base->req_heads[i];
+               while (req) {
+                       struct request *next = req->next;
+                       req->tx_count = req->reissue_count = 0;
+                       req->ns = NULL;
+                       /* ???? What to do about searches? */
+                       (void) evtimer_del(&req->timeout_event);
+                       req->trans_id = 0;
+                       req->transmit_me = 0;
+
+                       base->global_requests_waiting++;
+                       evdns_request_insert(req, &base->req_waiting_head);
+                       /* We want to insert these suspended elements at the front of
+                        * the waiting queue, since they were pending before any of
+                        * the waiting entries were added.  This is a circular list,
+                        * so we can just shift the start back by one.*/
+                       base->req_waiting_head = base->req_waiting_head->prev;
+
+                       if (next == req_started_at)
+                               break;
+                       req = next;
+               }
+               base->req_heads[i] = NULL;
+       }
+
+       base->global_requests_inflight = 0;
+
+       EVDNS_UNLOCK(base);
+       return 0;
+}
+
+int
+evdns_clear_nameservers_and_suspend(void)
+{
+       return evdns_base_clear_nameservers_and_suspend(current_base);
+}
+
+
+/* exported function */
+int
+evdns_base_resume(struct evdns_base *base)
+{
+       EVDNS_LOCK(base);
+       evdns_requests_pump_waiting_queue(base);
+       EVDNS_UNLOCK(base);
+       return 0;
+}
+
+int
+evdns_resume(void)
+{
+       return evdns_base_resume(current_base);
+}
+
+static int
+_evdns_nameserver_add_impl(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
+       /* first check to see if we already have this nameserver */
+
+       const struct nameserver *server = base->server_head, *const started_at = base->server_head;
+       struct nameserver *ns;
+       int err = 0;
+       char addrbuf[128];
+
+       ASSERT_LOCKED(base);
+       if (server) {
+               do {
+                       if (!evutil_sockaddr_cmp((struct sockaddr*)&server->address, address, 1)) return 3;
+                       server = server->next;
+               } while (server != started_at);
+       }
+       if (addrlen > (int)sizeof(ns->address)) {
+               log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
+               return 2;
+       }
+
+       ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
+       if (!ns) return -1;
+
+       memset(ns, 0, sizeof(struct nameserver));
+       ns->base = base;
+
+       evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
+
+       ns->socket = socket(address->sa_family, SOCK_DGRAM, 0);
+       if (ns->socket < 0) { err = 1; goto out1; }
+       evutil_make_socket_closeonexec(ns->socket);
+       evutil_make_socket_nonblocking(ns->socket);
+
+       if (base->global_outgoing_addrlen &&
+           !evutil_sockaddr_is_loopback(address)) {
+               if (bind(ns->socket,
+                       (struct sockaddr*)&base->global_outgoing_address,
+                       base->global_outgoing_addrlen) < 0) {
+                       log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address");
+                       err = 2;
+                       goto out2;
+               }
+       }
+
+       memcpy(&ns->address, address, addrlen);
+       ns->addrlen = addrlen;
+       ns->state = 1;
+       event_assign(&ns->event, ns->base->event_base, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
+       if (event_add(&ns->event, NULL) < 0) {
+               err = 2;
+               goto out2;
+       }
+
+       log(EVDNS_LOG_DEBUG, "Added nameserver %s",
+           evutil_format_sockaddr_port(address, addrbuf, sizeof(addrbuf)));
+
+       /* insert this nameserver into the list of them */
+       if (!base->server_head) {
+               ns->next = ns->prev = ns;
+               base->server_head = ns;
+       } else {
+               ns->next = base->server_head->next;
+               ns->prev = base->server_head;
+               base->server_head->next = ns;
+               ns->next->prev = ns;
+       }
+
+       base->global_good_nameservers++;
+
+       return 0;
+
+out2:
+       evutil_closesocket(ns->socket);
+out1:
+       event_debug_unassign(&ns->event);
+       mm_free(ns);
+       log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
+           evutil_format_sockaddr_port(address, addrbuf, sizeof(addrbuf)), err);
+       return err;
+}
+
+/* exported function */
+int
+evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
+{
+       struct sockaddr_in sin;
+       int res;
+       sin.sin_addr.s_addr = address;
+       sin.sin_port = htons(53);
+       sin.sin_family = AF_INET;
+       EVDNS_LOCK(base);
+       res = _evdns_nameserver_add_impl(base, (struct sockaddr*)&sin, sizeof(sin));
+       EVDNS_UNLOCK(base);
+       return res;
+}
+
+int
+evdns_nameserver_add(unsigned long int address) {
+       if (!current_base)
+               current_base = evdns_base_new(NULL, 0);
+       return evdns_base_nameserver_add(current_base, address);
+}
+
+static void
+sockaddr_setport(struct sockaddr *sa, ev_uint16_t port)
+{
+       if (sa->sa_family == AF_INET) {
+               ((struct sockaddr_in *)sa)->sin_port = htons(port);
+       } else if (sa->sa_family == AF_INET6) {
+               ((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
+       }
+}
+
+static ev_uint16_t
+sockaddr_getport(struct sockaddr *sa)
+{
+       if (sa->sa_family == AF_INET) {
+               return ntohs(((struct sockaddr_in *)sa)->sin_port);
+       } else if (sa->sa_family == AF_INET6) {
+               return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
+       } else {
+               return 0;
+       }
+}
+
+/* exported function */
+int
+evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) {
+       struct sockaddr_storage ss;
+       struct sockaddr *sa;
+       int len = sizeof(ss);
+       int res;
+       if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss,
+               &len)) {
+               log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s",
+                       ip_as_string);
+               return 4;
+       }
+       sa = (struct sockaddr *) &ss;
+       if (sockaddr_getport(sa) == 0)
+               sockaddr_setport(sa, 53);
+
+       EVDNS_LOCK(base);
+       res = _evdns_nameserver_add_impl(base, sa, len);
+       EVDNS_UNLOCK(base);
+       return res;
+}
+
+int
+evdns_nameserver_ip_add(const char *ip_as_string) {
+       if (!current_base)
+               current_base = evdns_base_new(NULL, 0);
+       return evdns_base_nameserver_ip_add(current_base, ip_as_string);
+}
+
+int
+evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
+    const struct sockaddr *sa, ev_socklen_t len, unsigned flags)
+{
+       int res;
+       EVUTIL_ASSERT(base);
+       EVDNS_LOCK(base);
+       res = _evdns_nameserver_add_impl(base, sa, len);
+       EVDNS_UNLOCK(base);
+       return res;
+}
+
+/* remove from the queue */
+static void
+evdns_request_remove(struct request *req, struct request **head)
+{
+       ASSERT_LOCKED(req->base);
+       ASSERT_VALID_REQUEST(req);
+
+#if 0
+       {
+               struct request *ptr;
+               int found = 0;
+               EVUTIL_ASSERT(*head != NULL);
+
+               ptr = *head;
+               do {
+                       if (ptr == req) {
+                               found = 1;
+                               break;
+                       }
+                       ptr = ptr->next;
+               } while (ptr != *head);
+               EVUTIL_ASSERT(found);
+
+               EVUTIL_ASSERT(req->next);
+       }
+#endif
+
+       if (req->next == req) {
+               /* only item in the list */
+               *head = NULL;
+       } else {
+               req->next->prev = req->prev;
+               req->prev->next = req->next;
+               if (*head == req) *head = req->next;
+       }
+       req->next = req->prev = NULL;
+}
+
+/* insert into the tail of the queue */
+static void
+evdns_request_insert(struct request *req, struct request **head) {
+       ASSERT_LOCKED(req->base);
+       ASSERT_VALID_REQUEST(req);
+       if (!*head) {
+               *head = req;
+               req->next = req->prev = req;
+               return;
+       }
+
+       req->prev = (*head)->prev;
+       req->prev->next = req;
+       req->next = *head;
+       (*head)->prev = req;
+}
+
+static int
+string_num_dots(const char *s) {
+       int count = 0;
+       while ((s = strchr(s, '.'))) {
+               s++;
+               count++;
+       }
+       return count;
+}
+
+static struct request *
+request_new(struct evdns_base *base, struct evdns_request *handle, int type,
+           const char *name, int flags, evdns_callback_type callback,
+           void *user_ptr) {
+
+       const char issuing_now =
+           (base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0;
+
+       const size_t name_len = strlen(name);
+       const size_t request_max_len = evdns_request_len(name_len);
+       const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff;
+       /* the request data is alloced in a single block with the header */
+       struct request *const req =
+           mm_malloc(sizeof(struct request) + request_max_len);
+       int rlen;
+       char namebuf[256];
+       (void) flags;
+
+       ASSERT_LOCKED(base);
+
+       if (!req) return NULL;
+
+       if (name_len >= sizeof(namebuf)) {
+               mm_free(req);
+               return NULL;
+       }
+
+       memset(req, 0, sizeof(struct request));
+       req->base = base;
+
+       evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req);
+
+       if (base->global_randomize_case) {
+               unsigned i;
+               char randbits[(sizeof(namebuf)+7)/8];
+               strlcpy(namebuf, name, sizeof(namebuf));
+               evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
+               for (i = 0; i < name_len; ++i) {
+                       if (EVUTIL_ISALPHA(namebuf[i])) {
+                               if ((randbits[i >> 3] & (1<<(i & 7))))
+                                       namebuf[i] |= 0x20;
+                               else
+                                       namebuf[i] &= ~0x20;
+                       }
+               }
+               name = namebuf;
+       }
+
+       /* request data lives just after the header */
+       req->request = ((u8 *) req) + sizeof(struct request);
+       /* denotes that the request data shouldn't be free()ed */
+       req->request_appended = 1;
+       rlen = evdns_request_data_build(name, name_len, trans_id,
+           type, CLASS_INET, req->request, request_max_len);
+       if (rlen < 0)
+               goto err1;
+
+       req->request_len = rlen;
+       req->trans_id = trans_id;
+       req->tx_count = 0;
+       req->request_type = type;
+       req->user_pointer = user_ptr;
+       req->user_callback = callback;
+       req->ns = issuing_now ? nameserver_pick(base) : NULL;
+       req->next = req->prev = NULL;
+       req->handle = handle;
+       if (handle) {
+               handle->current_req = req;
+               handle->base = base;
+       }
+
+       return req;
+err1:
+       mm_free(req);
+       return NULL;
+}
+
+static void
+request_submit(struct request *const req) {
+       struct evdns_base *base = req->base;
+       ASSERT_LOCKED(base);
+       ASSERT_VALID_REQUEST(req);
+       if (req->ns) {
+               /* if it has a nameserver assigned then this is going */
+               /* straight into the inflight queue */
+               evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
+               base->global_requests_inflight++;
+               evdns_request_transmit(req);
+       } else {
+               evdns_request_insert(req, &base->req_waiting_head);
+               base->global_requests_waiting++;
+       }
+}
+
+/* exported function */
+void
+evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle)
+{
+       struct request *req;
+
+       if (!handle->current_req)
+               return;
+
+       if (!base) {
+               /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
+               base = handle->base;
+               if (!base)
+                       base = handle->current_req->base;
+       }
+
+       EVDNS_LOCK(base);
+       if (handle->pending_cb) {
+               EVDNS_UNLOCK(base);
+               return;
+       }
+
+       req = handle->current_req;
+       ASSERT_VALID_REQUEST(req);
+
+       reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL);
+       if (req->ns) {
+               /* remove from inflight queue */
+               request_finished(req, &REQ_HEAD(base, req->trans_id), 1);
+       } else {
+               /* remove from global_waiting head */
+               request_finished(req, &base->req_waiting_head, 1);
+       }
+       EVDNS_UNLOCK(base);
+}
+
+/* exported function */
+struct evdns_request *
+evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags,
+    evdns_callback_type callback, void *ptr) {
+       struct evdns_request *handle;
+       struct request *req;
+       log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
+       handle = mm_calloc(1, sizeof(*handle));
+       if (handle == NULL)
+               return NULL;
+       EVDNS_LOCK(base);
+       if (flags & DNS_QUERY_NO_SEARCH) {
+               req =
+                       request_new(base, handle, TYPE_A, name, flags,
+                                   callback, ptr);
+               if (req)
+                       request_submit(req);
+       } else {
+               search_request_new(base, handle, TYPE_A, name, flags,
+                   callback, ptr);
+       }
+       if (handle->current_req == NULL) {
+               mm_free(handle);
+               handle = NULL;
+       }
+       EVDNS_UNLOCK(base);
+       return handle;
+}
+
+int evdns_resolve_ipv4(const char *name, int flags,
+                                          evdns_callback_type callback, void *ptr)
+{
+       return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr)
+               ? 0 : -1;
+}
+
+
+/* exported function */
+struct evdns_request *
+evdns_base_resolve_ipv6(struct evdns_base *base,
+    const char *name, int flags,
+    evdns_callback_type callback, void *ptr)
+{
+       struct evdns_request *handle;
+       struct request *req;
+       log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
+       handle = mm_calloc(1, sizeof(*handle));
+       if (handle == NULL)
+               return NULL;
+       EVDNS_LOCK(base);
+       if (flags & DNS_QUERY_NO_SEARCH) {
+               req = request_new(base, handle, TYPE_AAAA, name, flags,
+                                 callback, ptr);
+               if (req)
+                       request_submit(req);
+       } else {
+               search_request_new(base, handle, TYPE_AAAA, name, flags,
+                   callback, ptr);
+       }
+       if (handle->current_req == NULL) {
+               mm_free(handle);
+               handle = NULL;
+       }
+       EVDNS_UNLOCK(base);
+       return handle;
+}
+
+int evdns_resolve_ipv6(const char *name, int flags,
+    evdns_callback_type callback, void *ptr) {
+       return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr)
+               ? 0 : -1;
+}
+
+struct evdns_request *
+evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+       char buf[32];
+       struct evdns_request *handle;
+       struct request *req;
+       u32 a;
+       EVUTIL_ASSERT(in);
+       a = ntohl(in->s_addr);
+       evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
+                       (int)(u8)((a    )&0xff),
+                       (int)(u8)((a>>8 )&0xff),
+                       (int)(u8)((a>>16)&0xff),
+                       (int)(u8)((a>>24)&0xff));
+       handle = mm_calloc(1, sizeof(*handle));
+       if (handle == NULL)
+               return NULL;
+       log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
+       EVDNS_LOCK(base);
+       req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
+       if (req)
+               request_submit(req);
+       if (handle->current_req == NULL) {
+               mm_free(handle);
+               handle = NULL;
+       }
+       EVDNS_UNLOCK(base);
+       return (handle);
+}
+
+int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+       return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr)
+               ? 0 : -1;
+}
+
+struct evdns_request *
+evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+       /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
+       char buf[73];
+       char *cp;
+       struct evdns_request *handle;
+       struct request *req;
+       int i;
+       EVUTIL_ASSERT(in);
+       cp = buf;
+       for (i=15; i >= 0; --i) {
+               u8 byte = in->s6_addr[i];
+               *cp++ = "0123456789abcdef"[byte & 0x0f];
+               *cp++ = '.';
+               *cp++ = "0123456789abcdef"[byte >> 4];
+               *cp++ = '.';
+       }
+       EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf));
+       memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
+       handle = mm_calloc(1, sizeof(*handle));
+       if (handle == NULL)
+               return NULL;
+       log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
+       EVDNS_LOCK(base);
+       req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
+       if (req)
+               request_submit(req);
+       if (handle->current_req == NULL) {
+               mm_free(handle);
+               handle = NULL;
+       }
+       EVDNS_UNLOCK(base);
+       return (handle);
+}
+
+int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+       return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr)
+               ? 0 : -1;
+}
+
+/* ================================================================= */
+/* Search support */
+/* */
+/* the libc resolver has support for searching a number of domains */
+/* to find a name. If nothing else then it takes the single domain */
+/* from the gethostname() call. */
+/* */
+/* It can also be configured via the domain and search options in a */
+/* resolv.conf. */
+/* */
+/* The ndots option controls how many dots it takes for the resolver */
+/* to decide that a name is non-local and so try a raw lookup first. */
+
+struct search_domain {
+       int len;
+       struct search_domain *next;
+       /* the text string is appended to this structure */
+};
+
+struct search_state {
+       int refcount;
+       int ndots;
+       int num_domains;
+       struct search_domain *head;
+};
+
+static void
+search_state_decref(struct search_state *const state) {
+       if (!state) return;
+       state->refcount--;
+       if (!state->refcount) {
+               struct search_domain *next, *dom;
+               for (dom = state->head; dom; dom = next) {
+                       next = dom->next;
+                       mm_free(dom);
+               }
+               mm_free(state);
+       }
+}
+
+static struct search_state *
+search_state_new(void) {
+       struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
+       if (!state) return NULL;
+       memset(state, 0, sizeof(struct search_state));
+       state->refcount = 1;
+       state->ndots = 1;
+
+       return state;
+}
+
+static void
+search_postfix_clear(struct evdns_base *base) {
+       search_state_decref(base->global_search_state);
+
+       base->global_search_state = search_state_new();
+}
+
+/* exported function */
+void
+evdns_base_search_clear(struct evdns_base *base)
+{
+       EVDNS_LOCK(base);
+       search_postfix_clear(base);
+       EVDNS_UNLOCK(base);
+}
+
+void
+evdns_search_clear(void) {
+       evdns_base_search_clear(current_base);
+}
+
+static void
+search_postfix_add(struct evdns_base *base, const char *domain) {
+       size_t domain_len;
+       struct search_domain *sdomain;
+       while (domain[0] == '.') domain++;
+       domain_len = strlen(domain);
+
+       ASSERT_LOCKED(base);
+       if (!base->global_search_state) base->global_search_state = search_state_new();
+       if (!base->global_search_state) return;
+       base->global_search_state->num_domains++;
+
+       sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
+       if (!sdomain) return;
+       memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
+       sdomain->next = base->global_search_state->head;
+       sdomain->len = (int) domain_len;
+
+       base->global_search_state->head = sdomain;
+}
+
+/* reverse the order of members in the postfix list. This is needed because, */
+/* when parsing resolv.conf we push elements in the wrong order */
+static void
+search_reverse(struct evdns_base *base) {
+       struct search_domain *cur, *prev = NULL, *next;
+       ASSERT_LOCKED(base);
+       cur = base->global_search_state->head;
+       while (cur) {
+               next = cur->next;
+               cur->next = prev;
+               prev = cur;
+               cur = next;
+       }
+
+       base->global_search_state->head = prev;
+}
+
+/* exported function */
+void
+evdns_base_search_add(struct evdns_base *base, const char *domain) {
+       EVDNS_LOCK(base);
+       search_postfix_add(base, domain);
+       EVDNS_UNLOCK(base);
+}
+void
+evdns_search_add(const char *domain) {
+       evdns_base_search_add(current_base, domain);
+}
+
+/* exported function */
+void
+evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) {
+       EVDNS_LOCK(base);
+       if (!base->global_search_state) base->global_search_state = search_state_new();
+       if (base->global_search_state)
+               base->global_search_state->ndots = ndots;
+       EVDNS_UNLOCK(base);
+}
+void
+evdns_search_ndots_set(const int ndots) {
+       evdns_base_search_ndots_set(current_base, ndots);
+}
+
+static void
+search_set_from_hostname(struct evdns_base *base) {
+       char hostname[HOST_NAME_MAX + 1], *domainname;
+
+       ASSERT_LOCKED(base);
+       search_postfix_clear(base);
+       if (gethostname(hostname, sizeof(hostname))) return;
+       domainname = strchr(hostname, '.');
+       if (!domainname) return;
+       search_postfix_add(base, domainname);
+}
+
+/* warning: returns malloced string */
+static char *
+search_make_new(const struct search_state *const state, int n, const char *const base_name) {
+       const size_t base_len = strlen(base_name);
+       const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
+       struct search_domain *dom;
+
+       for (dom = state->head; dom; dom = dom->next) {
+               if (!n--) {
+                       /* this is the postfix we want */
+                       /* the actual postfix string is kept at the end of the structure */
+                       const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
+                       const int postfix_len = dom->len;
+                       char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
+                       if (!newname) return NULL;
+                       memcpy(newname, base_name, base_len);
+                       if (need_to_append_dot) newname[base_len] = '.';
+                       memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
+                       newname[base_len + need_to_append_dot + postfix_len] = 0;
+                       return newname;
+               }
+       }
+
+       /* we ran off the end of the list and still didn't find the requested string */
+       EVUTIL_ASSERT(0);
+       return NULL; /* unreachable; stops warnings in some compilers. */
+}
+
+static struct request *
+search_request_new(struct evdns_base *base, struct evdns_request *handle,
+                  int type, const char *const name, int flags,
+                  evdns_callback_type user_callback, void *user_arg) {
+       ASSERT_LOCKED(base);
+       EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA);
+       EVUTIL_ASSERT(handle->current_req == NULL);
+       if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
+            base->global_search_state &&
+                base->global_search_state->num_domains) {
+               /* we have some domains to search */
+               struct request *req;
+               if (string_num_dots(name) >= base->global_search_state->ndots) {
+                       req = request_new(base, handle, type, name, flags, user_callback, user_arg);
+                       if (!req) return NULL;
+                       handle->search_index = -1;
+               } else {
+                       char *const new_name = search_make_new(base->global_search_state, 0, name);
+                       if (!new_name) return NULL;
+                       req = request_new(base, handle, type, new_name, flags, user_callback, user_arg);
+                       mm_free(new_name);
+                       if (!req) return NULL;
+                       handle->search_index = 0;
+               }
+               EVUTIL_ASSERT(handle->search_origname == NULL);
+               handle->search_origname = mm_strdup(name);
+               if (handle->search_origname == NULL) {
+                       /* XXX Should we dealloc req? If yes, how? */
+                       return NULL;
+               }
+               handle->search_state = base->global_search_state;
+               handle->search_flags = flags;
+               base->global_search_state->refcount++;
+               request_submit(req);
+               return req;
+       } else {
+               struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg);
+               if (!req) return NULL;
+               request_submit(req);
+               return req;
+       }
+}
+
+/* this is called when a request has failed to find a name. We need to check */
+/* if it is part of a search and, if so, try the next name in the list */
+/* returns: */
+/*   0 another request has been submitted */
+/*   1 no more requests needed */
+static int
+search_try_next(struct evdns_request *const handle) {
+       struct request *req = handle->current_req;
+       struct evdns_base *base = req->base;
+       struct request *newreq;
+       ASSERT_LOCKED(base);
+       if (handle->search_state) {
+               /* it is part of a search */
+               char *new_name;
+               handle->search_index++;
+               if (handle->search_index >= handle->search_state->num_domains) {
+                       /* no more postfixes to try, however we may need to try */
+                       /* this name without a postfix */
+                       if (string_num_dots(handle->search_origname) < handle->search_state->ndots) {
+                               /* yep, we need to try it raw */
+                               newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer);
+                               log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname);
+                               if (newreq) {
+                                       search_request_finished(handle);
+                                       goto submit_next;
+                               }
+                       }
+                       return 1;
+               }
+
+               new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname);
+               if (!new_name) return 1;
+               log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index);
+               newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer);
+               mm_free(new_name);
+               if (!newreq) return 1;
+               goto submit_next;
+       }
+       return 1;
+
+submit_next:
+       request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0);
+       handle->current_req = newreq;
+       newreq->handle = handle;
+       request_submit(newreq);
+       return 0;
+}
+
+static void
+search_request_finished(struct evdns_request *const handle) {
+       ASSERT_LOCKED(handle->current_req->base);
+       if (handle->search_state) {
+               search_state_decref(handle->search_state);
+               handle->search_state = NULL;
+       }
+       if (handle->search_origname) {
+               mm_free(handle->search_origname);
+               handle->search_origname = NULL;
+       }
+}
+
+/* ================================================================= */
+/* Parsing resolv.conf files */
+
+static void
+evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
+       /* if the file isn't found then we assume a local resolver */
+       ASSERT_LOCKED(base);
+       if (flags & DNS_OPTION_SEARCH) search_set_from_hostname(base);
+       if (flags & DNS_OPTION_NAMESERVERS) evdns_base_nameserver_ip_add(base,"127.0.0.1");
+}
+
+#ifndef _EVENT_HAVE_STRTOK_R
+static char *
+strtok_r(char *s, const char *delim, char **state) {
+       char *cp, *start;
+       start = cp = s ? s : *state;
+       if (!cp)
+               return NULL;
+       while (*cp && !strchr(delim, *cp))
+               ++cp;
+       if (!*cp) {
+               if (cp == start)
+                       return NULL;
+               *state = NULL;
+               return start;
+       } else {
+               *cp++ = '\0';
+               *state = cp;
+               return start;
+       }
+}
+#endif
+
+/* helper version of atoi which returns -1 on error */
+static int
+strtoint(const char *const str)
+{
+       char *endptr;
+       const int r = strtol(str, &endptr, 10);
+       if (*endptr) return -1;
+       return r;
+}
+
+/* Parse a number of seconds into a timeval; return -1 on error. */
+static int
+strtotimeval(const char *const str, struct timeval *out)
+{
+       double d;
+       char *endptr;
+       d = strtod(str, &endptr);
+       if (*endptr) return -1;
+       if (d < 0) return -1;
+       out->tv_sec = (int) d;
+       out->tv_usec = (int) ((d - (int) d)*1000000);
+       if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */
+               return -1;
+       return 0;
+}
+
+/* helper version of atoi that returns -1 on error and clips to bounds. */
+static int
+strtoint_clipped(const char *const str, int min, int max)
+{
+       int r = strtoint(str);
+       if (r == -1)
+               return r;
+       else if (r<min)
+               return min;
+       else if (r>max)
+               return max;
+       else
+               return r;
+}
+
+static int
+evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight)
+{
+       int old_n_heads = base->n_req_heads, n_heads;
+       struct request **old_heads = base->req_heads, **new_heads, *req;
+       int i;
+
+       ASSERT_LOCKED(base);
+       if (maxinflight < 1)
+               maxinflight = 1;
+       n_heads = (maxinflight+4) / 5;
+       EVUTIL_ASSERT(n_heads > 0);
+       new_heads = mm_calloc(n_heads, sizeof(struct request*));
+       if (!new_heads)
+               return (-1);
+       if (old_heads) {
+               for (i = 0; i < old_n_heads; ++i) {
+                       while (old_heads[i]) {
+                               req = old_heads[i];
+                               evdns_request_remove(req, &old_heads[i]);
+                               evdns_request_insert(req, &new_heads[req->trans_id % n_heads]);
+                       }
+               }
+               mm_free(old_heads);
+       }
+       base->req_heads = new_heads;
+       base->n_req_heads = n_heads;
+       base->global_max_requests_inflight = maxinflight;
+       return (0);
+}
+
+/* exported function */
+int
+evdns_base_set_option(struct evdns_base *base,
+    const char *option, const char *val)
+{
+       int res;
+       EVDNS_LOCK(base);
+       res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL);
+       EVDNS_UNLOCK(base);
+       return res;
+}
+
+static inline int
+str_matches_option(const char *s1, const char *optionname)
+{
+       /* Option names are given as "option:" We accept either 'option' in
+        * s1, or 'option:randomjunk'.  The latter form is to implement the
+        * resolv.conf parser. */
+       size_t optlen = strlen(optionname);
+       size_t slen = strlen(s1);
+       if (slen == optlen || slen == optlen - 1)
+               return !strncmp(s1, optionname, slen);
+       else if (slen > optlen)
+               return !strncmp(s1, optionname, optlen);
+       else
+               return 0;
+}
+
+static int
+evdns_base_set_option_impl(struct evdns_base *base,
+    const char *option, const char *val, int flags)
+{
+       ASSERT_LOCKED(base);
+       if (str_matches_option(option, "ndots:")) {
+               const int ndots = strtoint(val);
+               if (ndots == -1) return -1;
+               if (!(flags & DNS_OPTION_SEARCH)) return 0;
+               log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
+               if (!base->global_search_state) base->global_search_state = search_state_new();
+               if (!base->global_search_state) return -1;
+               base->global_search_state->ndots = ndots;
+       } else if (str_matches_option(option, "timeout:")) {
+               struct timeval tv;
+               if (strtotimeval(val, &tv) == -1) return -1;
+               if (!(flags & DNS_OPTION_MISC)) return 0;
+               log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val);
+               memcpy(&base->global_timeout, &tv, sizeof(struct timeval));
+       } else if (str_matches_option(option, "getaddrinfo-allow-skew:")) {
+               struct timeval tv;
+               if (strtotimeval(val, &tv) == -1) return -1;
+               if (!(flags & DNS_OPTION_MISC)) return 0;
+               log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s",
+                   val);
+               memcpy(&base->global_getaddrinfo_allow_skew, &tv,
+                   sizeof(struct timeval));
+       } else if (str_matches_option(option, "max-timeouts:")) {
+               const int maxtimeout = strtoint_clipped(val, 1, 255);
+               if (maxtimeout == -1) return -1;
+               if (!(flags & DNS_OPTION_MISC)) return 0;
+               log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
+                       maxtimeout);
+               base->global_max_nameserver_timeout = maxtimeout;
+       } else if (str_matches_option(option, "max-inflight:")) {
+               const int maxinflight = strtoint_clipped(val, 1, 65000);
+               if (maxinflight == -1) return -1;
+               if (!(flags & DNS_OPTION_MISC)) return 0;
+               log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
+                       maxinflight);
+               evdns_base_set_max_requests_inflight(base, maxinflight);
+       } else if (str_matches_option(option, "attempts:")) {
+               int retries = strtoint(val);
+               if (retries == -1) return -1;
+               if (retries > 255) retries = 255;
+               if (!(flags & DNS_OPTION_MISC)) return 0;
+               log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
+               base->global_max_retransmits = retries;
+       } else if (str_matches_option(option, "randomize-case:")) {
+               int randcase = strtoint(val);
+               if (!(flags & DNS_OPTION_MISC)) return 0;
+               base->global_randomize_case = randcase;
+       } else if (str_matches_option(option, "bind-to:")) {
+               /* XXX This only applies to successive nameservers, not
+                * to already-configured ones.  We might want to fix that. */
+               int len = sizeof(base->global_outgoing_address);
+               if (!(flags & DNS_OPTION_NAMESERVERS)) return 0;
+               if (evutil_parse_sockaddr_port(val,
+                       (struct sockaddr*)&base->global_outgoing_address, &len))
+                       return -1;
+               base->global_outgoing_addrlen = len;
+       } else if (str_matches_option(option, "initial-probe-timeout:")) {
+               struct timeval tv;
+               if (strtotimeval(val, &tv) == -1) return -1;
+               if (tv.tv_sec > 3600)
+                       tv.tv_sec = 3600;
+               if (!(flags & DNS_OPTION_MISC)) return 0;
+               log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s",
+                   val);
+               memcpy(&base->global_nameserver_probe_initial_timeout, &tv,
+                   sizeof(tv));
+       }
+       return 0;
+}
+
+int
+evdns_set_option(const char *option, const char *val, int flags)
+{
+       if (!current_base)
+               current_base = evdns_base_new(NULL, 0);
+       return evdns_base_set_option(current_base, option, val);
+}
+
+static void
+resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) {
+       char *strtok_state;
+       static const char *const delims = " \t";
+#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
+
+
+       char *const first_token = strtok_r(start, delims, &strtok_state);
+       ASSERT_LOCKED(base);
+       if (!first_token) return;
+
+       if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
+               const char *const nameserver = NEXT_TOKEN;
+
+               if (nameserver)
+                       evdns_base_nameserver_ip_add(base, nameserver);
+       } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
+               const char *const domain = NEXT_TOKEN;
+               if (domain) {
+                       search_postfix_clear(base);
+                       search_postfix_add(base, domain);
+               }
+       } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
+               const char *domain;
+               search_postfix_clear(base);
+
+               while ((domain = NEXT_TOKEN)) {
+                       search_postfix_add(base, domain);
+               }
+               search_reverse(base);
+       } else if (!strcmp(first_token, "options")) {
+               const char *option;
+               while ((option = NEXT_TOKEN)) {
+                       const char *val = strchr(option, ':');
+                       evdns_base_set_option_impl(base, option, val ? val+1 : "", flags);
+               }
+       }
+#undef NEXT_TOKEN
+}
+
+/* exported function */
+/* returns: */
+/*   0 no errors */
+/*   1 failed to open file */
+/*   2 failed to stat file */
+/*   3 file too large */
+/*   4 out of memory */
+/*   5 short read from file */
+int
+evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) {
+       int res;
+       EVDNS_LOCK(base);
+       res = evdns_base_resolv_conf_parse_impl(base, flags, filename);
+       EVDNS_UNLOCK(base);
+       return res;
+}
+
+static char *
+evdns_get_default_hosts_filename(void)
+{
+#ifdef WIN32
+       /* Windows is a little coy about where it puts its configuration
+        * files.  Sure, they're _usually_ in C:\windows\system32, but
+        * there's no reason in principle they couldn't be in
+        * W:\hoboken chicken emergency\
+        */
+       char path[MAX_PATH+1];
+       static const char hostfile[] = "\\drivers\\etc\\hosts";
+       char *path_out;
+       size_t len_out;
+
+       if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0))
+               return NULL;
+       len_out = strlen(path)+strlen(hostfile);
+       path_out = mm_malloc(len_out+1);
+       evutil_snprintf(path_out, len_out, "%s%s", path, hostfile);
+       return path_out;
+#else
+       return mm_strdup("/etc/hosts");
+#endif
+}
+
+static int
+evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) {
+       size_t n;
+       char *resolv;
+       char *start;
+       int err = 0;
+
+       log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
+
+       if (flags & DNS_OPTION_HOSTSFILE) {
+               char *fname = evdns_get_default_hosts_filename();
+               evdns_base_load_hosts(base, fname);
+               if (fname)
+                       mm_free(fname);
+       }
+
+       if ((err = evutil_read_file(filename, &resolv, &n, 0)) < 0) {
+               if (err == -1) {
+                       /* No file. */
+                       evdns_resolv_set_defaults(base, flags);
+                       return 1;
+               } else {
+                       return 2;
+               }
+       }
+
+       start = resolv;
+       for (;;) {
+               char *const newline = strchr(start, '\n');
+               if (!newline) {
+                       resolv_conf_parse_line(base, start, flags);
+                       break;
+               } else {
+                       *newline = 0;
+                       resolv_conf_parse_line(base, start, flags);
+                       start = newline + 1;
+               }
+       }
+
+       if (!base->server_head && (flags & DNS_OPTION_NAMESERVERS)) {
+               /* no nameservers were configured. */
+               evdns_base_nameserver_ip_add(base, "127.0.0.1");
+               err = 6;
+       }
+       if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) {
+               search_set_from_hostname(base);
+       }
+
+       mm_free(resolv);
+       return err;
+}
+
+int
+evdns_resolv_conf_parse(int flags, const char *const filename) {
+       if (!current_base)
+               current_base = evdns_base_new(NULL, 0);
+       return evdns_base_resolv_conf_parse(current_base, flags, filename);
+}
+
+
+#ifdef WIN32
+/* Add multiple nameservers from a space-or-comma-separated list. */
+static int
+evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) {
+       const char *addr;
+       char *buf;
+       int r;
+       ASSERT_LOCKED(base);
+       while (*ips) {
+               while (isspace(*ips) || *ips == ',' || *ips == '\t')
+                       ++ips;
+               addr = ips;
+               while (isdigit(*ips) || *ips == '.' || *ips == ':' ||
+                   *ips=='[' || *ips==']')
+                       ++ips;
+               buf = mm_malloc(ips-addr+1);
+               if (!buf) return 4;
+               memcpy(buf, addr, ips-addr);
+               buf[ips-addr] = '\0';
+               r = evdns_base_nameserver_ip_add(base, buf);
+               mm_free(buf);
+               if (r) return r;
+       }
+       return 0;
+}
+
+typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
+
+/* Use the windows GetNetworkParams interface in iphlpapi.dll to */
+/* figure out what our nameservers are. */
+static int
+load_nameservers_with_getnetworkparams(struct evdns_base *base)
+{
+       /* Based on MSDN examples and inspection of  c-ares code. */
+       FIXED_INFO *fixed;
+       HMODULE handle = 0;
+       ULONG size = sizeof(FIXED_INFO);
+       void *buf = NULL;
+       int status = 0, r, added_any;
+       IP_ADDR_STRING *ns;
+       GetNetworkParams_fn_t fn;
+
+       ASSERT_LOCKED(base);
+       if (!(handle = evutil_load_windows_system_library(
+                       TEXT("iphlpapi.dll")))) {
+               log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
+               status = -1;
+               goto done;
+       }
+       if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
+               log(EVDNS_LOG_WARN, "Could not get address of function.");
+               status = -1;
+               goto done;
+       }
+
+       buf = mm_malloc(size);
+       if (!buf) { status = 4; goto done; }
+       fixed = buf;
+       r = fn(fixed, &size);
+       if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
+               status = -1;
+               goto done;
+       }
+       if (r != ERROR_SUCCESS) {
+               mm_free(buf);
+               buf = mm_malloc(size);
+               if (!buf) { status = 4; goto done; }
+               fixed = buf;
+               r = fn(fixed, &size);
+               if (r != ERROR_SUCCESS) {
+                       log(EVDNS_LOG_DEBUG, "fn() failed.");
+                       status = -1;
+                       goto done;
+               }
+       }
+
+       EVUTIL_ASSERT(fixed);
+       added_any = 0;
+       ns = &(fixed->DnsServerList);
+       while (ns) {
+               r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String);
+               if (r) {
+                       log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
+                               (ns->IpAddress.String),(int)GetLastError());
+                       status = r;
+               } else {
+                       ++added_any;
+                       log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
+               }
+
+               ns = ns->Next;
+       }
+
+       if (!added_any) {
+               log(EVDNS_LOG_DEBUG, "No nameservers added.");
+               if (status == 0)
+                       status = -1;
+       } else {
+               status = 0;
+       }
+
+ done:
+       if (buf)
+               mm_free(buf);
+       if (handle)
+               FreeLibrary(handle);
+       return status;
+}
+
+static int
+config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey)
+{
+       char *buf;
+       DWORD bufsz = 0, type = 0;
+       int status = 0;
+
+       ASSERT_LOCKED(base);
+       if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
+           != ERROR_MORE_DATA)
+               return -1;
+       if (!(buf = mm_malloc(bufsz)))
+               return -1;
+
+       if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
+           == ERROR_SUCCESS && bufsz > 1) {
+               status = evdns_nameserver_ip_add_line(base,buf);
+       }
+
+       mm_free(buf);
+       return status;
+}
+
+#define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
+#define WIN_NS_9X_KEY  SERVICES_KEY TEXT("VxD\\MSTCP")
+#define WIN_NS_NT_KEY  SERVICES_KEY TEXT("Tcpip\\Parameters")
+
+static int
+load_nameservers_from_registry(struct evdns_base *base)
+{
+       int found = 0;
+       int r;
+#define TRY(k, name) \
+       if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
+               log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
+               found = 1;                                              \
+       } else if (!found) {                                            \
+               log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
+                   #k,#name);                                          \
+       }
+
+       ASSERT_LOCKED(base);
+
+       if (((int)GetVersion()) > 0) { /* NT */
+               HKEY nt_key = 0, interfaces_key = 0;
+
+               if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
+                                KEY_READ, &nt_key) != ERROR_SUCCESS) {
+                       log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
+                       return -1;
+               }
+               r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
+                            KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
+                            &interfaces_key);
+               if (r != ERROR_SUCCESS) {
+                       log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
+                       return -1;
+               }
+               TRY(nt_key, "NameServer");
+               TRY(nt_key, "DhcpNameServer");
+               TRY(interfaces_key, "NameServer");
+               TRY(interfaces_key, "DhcpNameServer");
+               RegCloseKey(interfaces_key);
+               RegCloseKey(nt_key);
+       } else {
+               HKEY win_key = 0;
+               if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
+                                KEY_READ, &win_key) != ERROR_SUCCESS) {
+                       log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
+                       return -1;
+               }
+               TRY(win_key, "NameServer");
+               RegCloseKey(win_key);
+       }
+
+       if (found == 0) {
+               log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
+       }
+
+       return found ? 0 : -1;
+#undef TRY
+}
+
+int
+evdns_base_config_windows_nameservers(struct evdns_base *base)
+{
+       int r;
+       char *fname;
+       if (base == NULL)
+               base = current_base;
+       if (base == NULL)
+               return -1;
+       EVDNS_LOCK(base);
+       if (load_nameservers_with_getnetworkparams(base) == 0) {
+               EVDNS_UNLOCK(base);
+               return 0;
+       }
+       r = load_nameservers_from_registry(base);
+
+       fname = evdns_get_default_hosts_filename();
+       evdns_base_load_hosts(base, fname);
+       if (fname)
+               mm_free(fname);
+
+       EVDNS_UNLOCK(base);
+       return r;
+}
+
+int
+evdns_config_windows_nameservers(void)
+{
+       if (!current_base) {
+               current_base = evdns_base_new(NULL, 1);
+               return current_base == NULL ? -1 : 0;
+       } else {
+               return evdns_base_config_windows_nameservers(current_base);
+       }
+}
+#endif
+
+struct evdns_base *
+evdns_base_new(struct event_base *event_base, int initialize_nameservers)
+{
+       struct evdns_base *base;
+
+       if (evutil_secure_rng_init() < 0) {
+               log(EVDNS_LOG_WARN, "Unable to seed random number generator; "
+                   "DNS can't run.");
+               return NULL;
+       }
+
+       /* Give the evutil library a hook into its evdns-enabled
+        * functionality.  We can't just call evdns_getaddrinfo directly or
+        * else libevent-core will depend on libevent-extras. */
+       evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo);
+
+       base = mm_malloc(sizeof(struct evdns_base));
+       if (base == NULL)
+               return (NULL);
+       memset(base, 0, sizeof(struct evdns_base));
+       base->req_waiting_head = NULL;
+
+       EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       EVDNS_LOCK(base);
+
+       /* Set max requests inflight and allocate req_heads. */
+       base->req_heads = NULL;
+
+       evdns_base_set_max_requests_inflight(base, 64);
+
+       base->server_head = NULL;
+       base->event_base = event_base;
+       base->global_good_nameservers = base->global_requests_inflight =
+               base->global_requests_waiting = 0;
+
+       base->global_timeout.tv_sec = 5;
+       base->global_timeout.tv_usec = 0;
+       base->global_max_reissues = 1;
+       base->global_max_retransmits = 3;
+       base->global_max_nameserver_timeout = 3;
+       base->global_search_state = NULL;
+       base->global_randomize_case = 1;
+       base->global_getaddrinfo_allow_skew.tv_sec = 3;
+       base->global_getaddrinfo_allow_skew.tv_usec = 0;
+       base->global_nameserver_probe_initial_timeout.tv_sec = 10;
+       base->global_nameserver_probe_initial_timeout.tv_usec = 0;
+
+       TAILQ_INIT(&base->hostsdb);
+
+       if (initialize_nameservers) {
+               int r;
+#ifdef WIN32
+               r = evdns_base_config_windows_nameservers(base);
+#else
+               r = evdns_base_resolv_conf_parse(base, DNS_OPTIONS_ALL, "/etc/resolv.conf");
+#endif
+               if (r == -1) {
+                       evdns_base_free_and_unlock(base, 0);
+                       return NULL;
+               }
+       }
+       EVDNS_UNLOCK(base);
+       return base;
+}
+
+int
+evdns_init(void)
+{
+       struct evdns_base *base = evdns_base_new(NULL, 1);
+       if (base) {
+               current_base = base;
+               return 0;
+       } else {
+               return -1;
+       }
+}
+
+const char *
+evdns_err_to_string(int err)
+{
+    switch (err) {
+       case DNS_ERR_NONE: return "no error";
+       case DNS_ERR_FORMAT: return "misformatted query";
+       case DNS_ERR_SERVERFAILED: return "server failed";
+       case DNS_ERR_NOTEXIST: return "name does not exist";
+       case DNS_ERR_NOTIMPL: return "query not implemented";
+       case DNS_ERR_REFUSED: return "refused";
+
+       case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
+       case DNS_ERR_UNKNOWN: return "unknown";
+       case DNS_ERR_TIMEOUT: return "request timed out";
+       case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
+       case DNS_ERR_CANCEL: return "dns request canceled";
+       case DNS_ERR_NODATA: return "no records in the reply";
+       default: return "[Unknown error code]";
+    }
+}
+
+static void
+evdns_nameserver_free(struct nameserver *server)
+{
+       if (server->socket >= 0)
+       evutil_closesocket(server->socket);
+       (void) event_del(&server->event);
+       event_debug_unassign(&server->event);
+       if (server->state == 0)
+               (void) event_del(&server->timeout_event);
+       event_debug_unassign(&server->timeout_event);
+       mm_free(server);
+}
+
+static void
+evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests)
+{
+       struct nameserver *server, *server_next;
+       struct search_domain *dom, *dom_next;
+       int i;
+
+       /* Requires that we hold the lock. */
+
+       /* TODO(nickm) we might need to refcount here. */
+
+       for (i = 0; i < base->n_req_heads; ++i) {
+               while (base->req_heads[i]) {
+                       if (fail_requests)
+                               reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL);
+                       request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1);
+               }
+       }
+       while (base->req_waiting_head) {
+               if (fail_requests)
+                       reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
+               request_finished(base->req_waiting_head, &base->req_waiting_head, 1);
+       }
+       base->global_requests_inflight = base->global_requests_waiting = 0;
+
+       for (server = base->server_head; server; server = server_next) {
+               server_next = server->next;
+               evdns_nameserver_free(server);
+               if (server_next == base->server_head)
+                       break;
+       }
+       base->server_head = NULL;
+       base->global_good_nameservers = 0;
+
+       if (base->global_search_state) {
+               for (dom = base->global_search_state->head; dom; dom = dom_next) {
+                       dom_next = dom->next;
+                       mm_free(dom);
+               }
+               mm_free(base->global_search_state);
+               base->global_search_state = NULL;
+       }
+
+       {
+               struct hosts_entry *victim;
+               while ((victim = TAILQ_FIRST(&base->hostsdb))) {
+                       TAILQ_REMOVE(&base->hostsdb, victim, next);
+                       mm_free(victim);
+               }
+       }
+
+       mm_free(base->req_heads);
+
+       EVDNS_UNLOCK(base);
+       EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+
+       mm_free(base);
+}
+
+void
+evdns_base_free(struct evdns_base *base, int fail_requests)
+{
+       EVDNS_LOCK(base);
+       evdns_base_free_and_unlock(base, fail_requests);
+}
+
+void
+evdns_shutdown(int fail_requests)
+{
+       if (current_base) {
+               struct evdns_base *b = current_base;
+               current_base = NULL;
+               evdns_base_free(b, fail_requests);
+       }
+       evdns_log_fn = NULL;
+}
+
+static int
+evdns_base_parse_hosts_line(struct evdns_base *base, char *line)
+{
+       char *strtok_state;
+       static const char *const delims = " \t";
+       char *const addr = strtok_r(line, delims, &strtok_state);
+       char *hostname, *hash;
+       struct sockaddr_storage ss;
+       int socklen = sizeof(ss);
+       ASSERT_LOCKED(base);
+
+#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
+
+       if (!addr || *addr == '#')
+               return 0;
+
+       memset(&ss, 0, sizeof(ss));
+       if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0)
+               return -1;
+       if (socklen > (int)sizeof(struct sockaddr_in6))
+               return -1;
+
+       if (sockaddr_getport((struct sockaddr*)&ss))
+               return -1;
+
+       while ((hostname = NEXT_TOKEN)) {
+               struct hosts_entry *he;
+               size_t namelen;
+               if ((hash = strchr(hostname, '#'))) {
+                       if (hash == hostname)
+                               return 0;
+                       *hash = '\0';
+               }
+
+               namelen = strlen(hostname);
+
+               he = mm_calloc(1, sizeof(struct hosts_entry)+namelen);
+               if (!he)
+                       return -1;
+               EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr));
+               memcpy(&he->addr, &ss, socklen);
+               memcpy(he->hostname, hostname, namelen+1);
+               he->addrlen = socklen;
+
+               TAILQ_INSERT_TAIL(&base->hostsdb, he, next);
+
+               if (hash)
+                       return 0;
+       }
+
+       return 0;
+#undef NEXT_TOKEN
+}
+
+static int
+evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
+{
+       char *str=NULL, *cp, *eol;
+       size_t len;
+       int err=0;
+
+       ASSERT_LOCKED(base);
+
+       if (hosts_fname == NULL ||
+           (err = evutil_read_file(hosts_fname, &str, &len, 0)) < 0) {
+               char tmp[64];
+               strlcpy(tmp, "127.0.0.1   localhost", sizeof(tmp));
+               evdns_base_parse_hosts_line(base, tmp);
+               strlcpy(tmp, "::1   localhost", sizeof(tmp));
+               evdns_base_parse_hosts_line(base, tmp);
+               return err ? -1 : 0;
+       }
+
+       /* This will break early if there is a NUL in the hosts file.
+        * Probably not a problem.*/
+       cp = str;
+       for (;;) {
+               eol = strchr(cp, '\n');
+
+               if (eol) {
+                       *eol = '\0';
+                       evdns_base_parse_hosts_line(base, cp);
+                       cp = eol+1;
+               } else {
+                       evdns_base_parse_hosts_line(base, cp);
+                       break;
+               }
+       }
+
+       mm_free(str);
+       return 0;
+}
+
+int
+evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname)
+{
+       int res;
+       if (!base)
+               base = current_base;
+       EVDNS_LOCK(base);
+       res = evdns_base_load_hosts_impl(base, hosts_fname);
+       EVDNS_UNLOCK(base);
+       return res;
+}
+
+/* A single request for a getaddrinfo, either v4 or v6. */
+struct getaddrinfo_subrequest {
+       struct evdns_request *r;
+       ev_uint32_t type;
+};
+
+/* State data used to implement an in-progress getaddrinfo. */
+struct evdns_getaddrinfo_request {
+       struct evdns_base *evdns_base;
+       /* Copy of the modified 'hints' data that we'll use to build
+        * answers. */
+       struct evutil_addrinfo hints;
+       /* The callback to invoke when we're done */
+       evdns_getaddrinfo_cb user_cb;
+       /* User-supplied data to give to the callback. */
+       void *user_data;
+       /* The port to use when building sockaddrs. */
+       ev_uint16_t port;
+       /* The sub_request for an A record (if any) */
+       struct getaddrinfo_subrequest ipv4_request;
+       /* The sub_request for an AAAA record (if any) */
+       struct getaddrinfo_subrequest ipv6_request;
+
+       /* The cname result that we were told (if any) */
+       char *cname_result;
+
+       /* If we have one request answered and one request still inflight,
+        * then this field holds the answer from the first request... */
+       struct evutil_addrinfo *pending_result;
+       /* And this event is a timeout that will tell us to cancel the second
+        * request if it's taking a long time. */
+       struct event timeout;
+
+       /* And this field holds the error code from the first request... */
+       int pending_error;
+       /* If this is set, the user canceled this request. */
+       unsigned user_canceled : 1;
+       /* If this is set, the user can no longer cancel this request; we're
+        * just waiting for the free. */
+       unsigned request_done : 1;
+};
+
+/* Convert an evdns errors to the equivalent getaddrinfo error. */
+static int
+evdns_err_to_getaddrinfo_err(int e1)
+{
+       /* XXX Do this better! */
+       if (e1 == DNS_ERR_NONE)
+               return 0;
+       else if (e1 == DNS_ERR_NOTEXIST)
+               return EVUTIL_EAI_NONAME;
+       else
+               return EVUTIL_EAI_FAIL;
+}
+
+/* Return the more informative of two getaddrinfo errors. */
+static int
+getaddrinfo_merge_err(int e1, int e2)
+{
+       /* XXXX be cleverer here. */
+       if (e1 == 0)
+               return e2;
+       else
+               return e1;
+}
+
+static void
+free_getaddrinfo_request(struct evdns_getaddrinfo_request *data)
+{
+       /* DO NOT CALL this if either of the requests is pending.  Only once
+        * both callbacks have been invoked is it safe to free the request */
+       if (data->pending_result)
+               evutil_freeaddrinfo(data->pending_result);
+       if (data->cname_result)
+               mm_free(data->cname_result);
+       event_del(&data->timeout);
+       mm_free(data);
+       return;
+}
+
+static void
+add_cname_to_reply(struct evdns_getaddrinfo_request *data,
+    struct evutil_addrinfo *ai)
+{
+       if (data->cname_result && ai) {
+               ai->ai_canonname = data->cname_result;
+               data->cname_result = NULL;
+       }
+}
+
+/* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
+ * request has finished, but the other one took too long to answer. Pass
+ * along the answer we got, and cancel the other request.
+ */
+static void
+evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr)
+{
+       int v4_timedout = 0, v6_timedout = 0;
+       struct evdns_getaddrinfo_request *data = ptr;
+
+       /* Cancel any pending requests, and note which one */
+       if (data->ipv4_request.r) {
+               evdns_cancel_request(NULL, data->ipv4_request.r);
+               v4_timedout = 1;
+               EVDNS_LOCK(data->evdns_base);
+               ++data->evdns_base->getaddrinfo_ipv4_timeouts;
+               EVDNS_UNLOCK(data->evdns_base);
+       }
+       if (data->ipv6_request.r) {
+               evdns_cancel_request(NULL, data->ipv6_request.r);
+               v6_timedout = 1;
+               EVDNS_LOCK(data->evdns_base);
+               ++data->evdns_base->getaddrinfo_ipv6_timeouts;
+               EVDNS_UNLOCK(data->evdns_base);
+       }
+
+       /* We only use this timeout callback when we have an answer for
+        * one address. */
+       EVUTIL_ASSERT(!v4_timedout || !v6_timedout);
+
+       /* Report the outcome of the other request that didn't time out. */
+       if (data->pending_result) {
+               add_cname_to_reply(data, data->pending_result);
+               data->user_cb(0, data->pending_result, data->user_data);
+               data->pending_result = NULL;
+       } else {
+               int e = data->pending_error;
+               if (!e)
+                       e = EVUTIL_EAI_AGAIN;
+               data->user_cb(e, NULL, data->user_data);
+       }
+
+       if (!v4_timedout && !v6_timedout) {
+               /* should be impossible? XXXX */
+               free_getaddrinfo_request(data);
+       }
+}
+
+static int
+evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base,
+    struct evdns_getaddrinfo_request *data)
+{
+       return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew);
+}
+
+static inline int
+evdns_result_is_answer(int result)
+{
+       return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED &&
+           result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL);
+}
+
+static void
+evdns_getaddrinfo_gotresolve(int result, char type, int count,
+    int ttl, void *addresses, void *arg)
+{
+       int i;
+       struct getaddrinfo_subrequest *req = arg;
+       struct getaddrinfo_subrequest *other_req;
+       struct evdns_getaddrinfo_request *data;
+
+       struct evutil_addrinfo *res;
+
+       struct sockaddr_in sin;
+       struct sockaddr_in6 sin6;
+       struct sockaddr *sa;
+       int socklen, addrlen;
+       void *addrp;
+       int err;
+       int user_canceled;
+
+       EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA);
+       if (req->type == DNS_IPv4_A) {
+               data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request);
+               other_req = &data->ipv6_request;
+       } else {
+               data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request);
+               other_req = &data->ipv4_request;
+       }
+
+       EVDNS_LOCK(data->evdns_base);
+       if (evdns_result_is_answer(result)) {
+               if (req->type == DNS_IPv4_A)
+                       ++data->evdns_base->getaddrinfo_ipv4_answered;
+               else
+                       ++data->evdns_base->getaddrinfo_ipv6_answered;
+       }
+       user_canceled = data->user_canceled;
+       if (other_req->r == NULL)
+               data->request_done = 1;
+       EVDNS_UNLOCK(data->evdns_base);
+
+       req->r = NULL;
+
+       if (result == DNS_ERR_CANCEL && ! user_canceled) {
+               /* Internal cancel request from timeout or internal error.
+                * we already answered the user. */
+               if (other_req->r == NULL)
+                       free_getaddrinfo_request(data);
+               return;
+       }
+
+       if (result == DNS_ERR_NONE) {
+               if (count == 0)
+                       err = EVUTIL_EAI_NODATA;
+               else
+                       err = 0;
+       } else {
+               err = evdns_err_to_getaddrinfo_err(result);
+       }
+
+       if (err) {
+               /* Looks like we got an error. */
+               if (other_req->r) {
+                       /* The other request is still working; maybe it will
+                        * succeed. */
+                       /* XXXX handle failure from set_timeout */
+                       evdns_getaddrinfo_set_timeout(data->evdns_base, data);
+                       data->pending_error = err;
+                       return;
+               }
+
+               if (user_canceled) {
+                       data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
+               } else if (data->pending_result) {
+                       /* If we have an answer waiting, and we weren't
+                        * canceled, ignore this error. */
+                       add_cname_to_reply(data, data->pending_result);
+                       data->user_cb(0, data->pending_result, data->user_data);
+                       data->pending_result = NULL;
+               } else {
+                       if (data->pending_error)
+                               err = getaddrinfo_merge_err(err,
+                                   data->pending_error);
+                       data->user_cb(err, NULL, data->user_data);
+               }
+               free_getaddrinfo_request(data);
+               return;
+       } else if (user_canceled) {
+               if (other_req->r) {
+                       /* The other request is still working; let it hit this
+                        * callback with EVUTIL_EAI_CANCEL callback and report
+                        * the failure. */
+                       return;
+               }
+               data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
+               free_getaddrinfo_request(data);
+               return;
+       }
+
+       /* Looks like we got some answers. We should turn them into addrinfos
+        * and then either queue those or return them all. */
+       EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA);
+
+       if (type == DNS_IPv4_A) {
+               memset(&sin, 0, sizeof(sin));
+               sin.sin_family = AF_INET;
+               sin.sin_port = htons(data->port);
+
+               sa = (struct sockaddr *)&sin;
+               socklen = sizeof(sin);
+               addrlen = 4;
+               addrp = &sin.sin_addr.s_addr;
+       } else {
+               memset(&sin6, 0, sizeof(sin6));
+               sin6.sin6_family = AF_INET6;
+               sin6.sin6_port = htons(data->port);
+
+               sa = (struct sockaddr *)&sin6;
+               socklen = sizeof(sin6);
+               addrlen = 16;
+               addrp = &sin6.sin6_addr.s6_addr;
+       }
+
+       res = NULL;
+       for (i=0; i < count; ++i) {
+               struct evutil_addrinfo *ai;
+               memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
+               ai = evutil_new_addrinfo(sa, socklen, &data->hints);
+               if (!ai) {
+                       if (other_req->r) {
+                               evdns_cancel_request(NULL, other_req->r);
+                       }
+                       data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data);
+                       if (res)
+                               evutil_freeaddrinfo(res);
+
+                       if (other_req->r == NULL)
+                               free_getaddrinfo_request(data);
+                       return;
+               }
+               res = evutil_addrinfo_append(res, ai);
+       }
+
+       if (other_req->r) {
+               /* The other request is still in progress; wait for it */
+               /* XXXX handle failure from set_timeout */
+               evdns_getaddrinfo_set_timeout(data->evdns_base, data);
+               data->pending_result = res;
+               return;
+       } else {
+               /* The other request is done or never started; append its
+                * results (if any) and return them. */
+               if (data->pending_result) {
+                       if (req->type == DNS_IPv4_A)
+                               res = evutil_addrinfo_append(res,
+                                   data->pending_result);
+                       else
+                               res = evutil_addrinfo_append(
+                                   data->pending_result, res);
+                       data->pending_result = NULL;
+               }
+
+               /* Call the user callback. */
+               add_cname_to_reply(data, res);
+               data->user_cb(0, res, data->user_data);
+
+               /* Free data. */
+               free_getaddrinfo_request(data);
+       }
+}
+
+static struct hosts_entry *
+find_hosts_entry(struct evdns_base *base, const char *hostname,
+    struct hosts_entry *find_after)
+{
+       struct hosts_entry *e;
+
+       if (find_after)
+               e = TAILQ_NEXT(find_after, next);
+       else
+               e = TAILQ_FIRST(&base->hostsdb);
+
+       for (; e; e = TAILQ_NEXT(e, next)) {
+               if (!evutil_ascii_strcasecmp(e->hostname, hostname))
+                       return e;
+       }
+       return NULL;
+}
+
+static int
+evdns_getaddrinfo_fromhosts(struct evdns_base *base,
+    const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port,
+    struct evutil_addrinfo **res)
+{
+       int n_found = 0;
+       struct hosts_entry *e;
+       struct evutil_addrinfo *ai=NULL;
+       int f = hints->ai_family;
+
+       EVDNS_LOCK(base);
+       for (e = find_hosts_entry(base, nodename, NULL); e;
+           e = find_hosts_entry(base, nodename, e)) {
+               struct evutil_addrinfo *ai_new;
+               ++n_found;
+               if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
+                   (e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
+                       continue;
+               ai_new = evutil_new_addrinfo(&e->addr.sa, e->addrlen, hints);
+               if (!ai_new) {
+                       n_found = 0;
+                       goto out;
+               }
+               sockaddr_setport(ai_new->ai_addr, port);
+               ai = evutil_addrinfo_append(ai, ai_new);
+       }
+       EVDNS_UNLOCK(base);
+out:
+       if (n_found) {
+               /* Note that we return an empty answer if we found entries for
+                * this hostname but none were of the right address type. */
+               *res = ai;
+               return 0;
+       } else {
+               if (ai)
+                       evutil_freeaddrinfo(ai);
+               return -1;
+       }
+}
+
+struct evdns_getaddrinfo_request *
+evdns_getaddrinfo(struct evdns_base *dns_base,
+    const char *nodename, const char *servname,
+    const struct evutil_addrinfo *hints_in,
+    evdns_getaddrinfo_cb cb, void *arg)
+{
+       struct evdns_getaddrinfo_request *data;
+       struct evutil_addrinfo hints;
+       struct evutil_addrinfo *res = NULL;
+       int err;
+       int port = 0;
+       int want_cname = 0;
+
+       if (!dns_base) {
+               dns_base = current_base;
+               if (!dns_base) {
+                       log(EVDNS_LOG_WARN,
+                           "Call to getaddrinfo_async with no "
+                           "evdns_base configured.");
+                       cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
+                       return NULL;
+               }
+       }
+
+       /* If we _must_ answer this immediately, do so. */
+       if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
+               res = NULL;
+               err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
+               cb(err, res, arg);
+               return NULL;
+       }
+
+       if (hints_in) {
+               memcpy(&hints, hints_in, sizeof(hints));
+       } else {
+               memset(&hints, 0, sizeof(hints));
+               hints.ai_family = PF_UNSPEC;
+       }
+
+       evutil_adjust_hints_for_addrconfig(&hints);
+
+       /* Now try to see if we _can_ answer immediately. */
+       /* (It would be nice to do this by calling getaddrinfo directly, with
+        * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
+        * a reliable way to distinguish the "that wasn't a numeric host!" case
+        * from any other EAI_NONAME cases.) */
+       err = evutil_getaddrinfo_common(nodename, servname, &hints, &res, &port);
+       if (err != EVUTIL_EAI_NEED_RESOLVE) {
+               cb(err, res, arg);
+               return NULL;
+       }
+
+       /* If there is an entry in the hosts file, we should give it now. */
+       if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
+               cb(0, res, arg);
+               return NULL;
+       }
+
+       /* Okay, things are serious now. We're going to need to actually
+        * launch a request.
+        */
+       data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
+       if (!data) {
+               cb(EVUTIL_EAI_MEMORY, NULL, arg);
+               return NULL;
+       }
+
+       memcpy(&data->hints, &hints, sizeof(data->hints));
+       data->port = (ev_uint16_t)port;
+       data->ipv4_request.type = DNS_IPv4_A;
+       data->ipv6_request.type = DNS_IPv6_AAAA;
+       data->user_cb = cb;
+       data->user_data = arg;
+       data->evdns_base = dns_base;
+
+       want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
+
+       /* If we are asked for a PF_UNSPEC address, we launch two requests in
+        * parallel: one for an A address and one for an AAAA address.  We
+        * can't send just one request, since many servers only answer one
+        * question per DNS request.
+        *
+        * Once we have the answer to one request, we allow for a short
+        * timeout before we report it, to see if the other one arrives.  If
+        * they both show up in time, then we report both the answers.
+        *
+        * If too many addresses of one type time out or fail, we should stop
+        * launching those requests. (XXX we don't do that yet.)
+        */
+
+       if (hints.ai_family != PF_INET6) {
+               log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
+                   nodename, &data->ipv4_request);
+
+               data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
+                   nodename, 0, evdns_getaddrinfo_gotresolve,
+                   &data->ipv4_request);
+               if (want_cname)
+                       data->ipv4_request.r->current_req->put_cname_in_ptr =
+                           &data->cname_result;
+       }
+       if (hints.ai_family != PF_INET) {
+               log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
+                   nodename, &data->ipv6_request);
+
+               data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
+                   nodename, 0, evdns_getaddrinfo_gotresolve,
+                   &data->ipv6_request);
+               if (want_cname)
+                       data->ipv6_request.r->current_req->put_cname_in_ptr =
+                           &data->cname_result;
+       }
+
+       evtimer_assign(&data->timeout, dns_base->event_base,
+           evdns_getaddrinfo_timeout_cb, data);
+
+       if (data->ipv4_request.r || data->ipv6_request.r) {
+               return data;
+       } else {
+               mm_free(data);
+               cb(EVUTIL_EAI_FAIL, NULL, arg);
+               return NULL;
+       }
+}
+
+void
+evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data)
+{
+       EVDNS_LOCK(data->evdns_base);
+       if (data->request_done) {
+               EVDNS_UNLOCK(data->evdns_base);
+               return;
+       }
+       event_del(&data->timeout);
+       data->user_canceled = 1;
+       if (data->ipv4_request.r)
+               evdns_cancel_request(data->evdns_base, data->ipv4_request.r);
+       if (data->ipv6_request.r)
+               evdns_cancel_request(data->evdns_base, data->ipv6_request.r);
+       EVDNS_UNLOCK(data->evdns_base);
+}
diff --git a/libevent/evdns.h b/libevent/evdns.h
new file mode 100644 (file)
index 0000000..513f9b7
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVDNS_H_
+#define _EVDNS_H_
+
+/** @file evdns.h
+
+  A dns subsystem for Libevent.
+
+  The <evdns.h> header is deprecated in Libevent 2.0 and later; please
+  use <event2/evdns.h> instead.  Depending on what functionality you
+  need, you may also want to include more of the other <event2/...>
+  headers.
+ */
+
+#include <event.h>
+#include <event2/dns.h>
+#include <event2/dns_compat.h>
+#include <event2/dns_struct.h>
+
+#endif /* _EVDNS_H_ */
diff --git a/libevent/event-internal.h b/libevent/event-internal.h
new file mode 100644 (file)
index 0000000..1798b70
--- /dev/null
@@ -0,0 +1,363 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT_INTERNAL_H_
+#define _EVENT_INTERNAL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include <time.h>
+#include <sys/queue.h>
+#include "event2/event_struct.h"
+#include "minheap-internal.h"
+#include "evsignal-internal.h"
+#include "mm-internal.h"
+#include "defer-internal.h"
+
+/* map union members back */
+
+/* mutually exclusive */
+#define ev_signal_next _ev.ev_signal.ev_signal_next
+#define ev_io_next     _ev.ev_io.ev_io_next
+#define ev_io_timeout  _ev.ev_io.ev_timeout
+
+/* used only by signals */
+#define ev_ncalls      _ev.ev_signal.ev_ncalls
+#define ev_pncalls     _ev.ev_signal.ev_pncalls
+
+/* Possible values for ev_closure in struct event. */
+#define EV_CLOSURE_NONE 0
+#define EV_CLOSURE_SIGNAL 1
+#define EV_CLOSURE_PERSIST 2
+
+/** Structure to define the backend of a given event_base. */
+struct eventop {
+       /** The name of this backend. */
+       const char *name;
+       /** Function to set up an event_base to use this backend.  It should
+        * create a new structure holding whatever information is needed to
+        * run the backend, and return it.  The returned pointer will get
+        * stored by event_init into the event_base.evbase field.  On failure,
+        * this function should return NULL. */
+       void *(*init)(struct event_base *);
+       /** Enable reading/writing on a given fd or signal.  'events' will be
+        * the events that we're trying to enable: one or more of EV_READ,
+        * EV_WRITE, EV_SIGNAL, and EV_ET.  'old' will be those events that
+        * were enabled on this fd previously.  'fdinfo' will be a structure
+        * associated with the fd by the evmap; its size is defined by the
+        * fdinfo field below.  It will be set to 0 the first time the fd is
+        * added.  The function should return 0 on success and -1 on error.
+        */
+       int (*add)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
+       /** As "add", except 'events' contains the events we mean to disable. */
+       int (*del)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
+       /** Function to implement the core of an event loop.  It must see which
+           added events are ready, and cause event_active to be called for each
+           active event (usually via event_io_active or such).  It should
+           return 0 on success and -1 on error.
+        */
+       int (*dispatch)(struct event_base *, struct timeval *);
+       /** Function to clean up and free our data from the event_base. */
+       void (*dealloc)(struct event_base *);
+       /** Flag: set if we need to reinitialize the event base after we fork.
+        */
+       int need_reinit;
+       /** Bit-array of supported event_method_features that this backend can
+        * provide. */
+       enum event_method_feature features;
+       /** Length of the extra information we should record for each fd that
+           has one or more active events.  This information is recorded
+           as part of the evmap entry for each fd, and passed as an argument
+           to the add and del functions above.
+        */
+       size_t fdinfo_len;
+};
+
+#ifdef WIN32
+/* If we're on win32, then file descriptors are not nice low densely packed
+   integers.  Instead, they are pointer-like windows handles, and we want to
+   use a hashtable instead of an array to map fds to events.
+*/
+#define EVMAP_USE_HT
+#endif
+
+/* #define HT_CACHE_HASH_VALS */
+
+#ifdef EVMAP_USE_HT
+#include "ht-internal.h"
+struct event_map_entry;
+HT_HEAD(event_io_map, event_map_entry);
+#else
+#define event_io_map event_signal_map
+#endif
+
+/* Used to map signal numbers to a list of events.  If EVMAP_USE_HT is not
+   defined, this structure is also used as event_io_map, which maps fds to a
+   list of events.
+*/
+struct event_signal_map {
+       /* An array of evmap_io * or of evmap_signal *; empty entries are
+        * set to NULL. */
+       void **entries;
+       /* The number of entries available in entries */
+       int nentries;
+};
+
+/* A list of events waiting on a given 'common' timeout value.  Ordinarily,
+ * events waiting for a timeout wait on a minheap.  Sometimes, however, a
+ * queue can be faster.
+ **/
+struct common_timeout_list {
+       /* List of events currently waiting in the queue. */
+       struct event_list events;
+       /* 'magic' timeval used to indicate the duration of events in this
+        * queue. */
+       struct timeval duration;
+       /* Event that triggers whenever one of the events in the queue is
+        * ready to activate */
+       struct event timeout_event;
+       /* The event_base that this timeout list is part of */
+       struct event_base *base;
+};
+
+/** Mask used to get the real tv_usec value from a common timeout. */
+#define COMMON_TIMEOUT_MICROSECONDS_MASK       0x000fffff
+
+struct event_change;
+
+/* List of 'changes' since the last call to eventop.dispatch.  Only maintained
+ * if the backend is using changesets. */
+struct event_changelist {
+       struct event_change *changes;
+       int n_changes;
+       int changes_size;
+};
+
+#ifndef _EVENT_DISABLE_DEBUG_MODE
+/* Global internal flag: set to one if debug mode is on. */
+extern int _event_debug_mode_on;
+#define EVENT_DEBUG_MODE_IS_ON() (_event_debug_mode_on)
+#else
+#define EVENT_DEBUG_MODE_IS_ON() (0)
+#endif
+
+struct event_base {
+       /** Function pointers and other data to describe this event_base's
+        * backend. */
+       const struct eventop *evsel;
+       /** Pointer to backend-specific data. */
+       void *evbase;
+
+       /** List of changes to tell backend about at next dispatch.  Only used
+        * by the O(1) backends. */
+       struct event_changelist changelist;
+
+       /** Function pointers used to describe the backend that this event_base
+        * uses for signals */
+       const struct eventop *evsigsel;
+       /** Data to implement the common signal handelr code. */
+       struct evsig_info sig;
+
+       /** Number of virtual events */
+       int virtual_event_count;
+       /** Number of total events added to this event_base */
+       int event_count;
+       /** Number of total events active in this event_base */
+       int event_count_active;
+
+       /** Set if we should terminate the loop once we're done processing
+        * events. */
+       int event_gotterm;
+       /** Set if we should terminate the loop immediately */
+       int event_break;
+
+       /** Set if we're running the event_base_loop function, to prevent
+        * reentrant invocation. */
+       int running_loop;
+
+       /* Active event management. */
+       /** An array of nactivequeues queues for active events (ones that
+        * have triggered, and whose callbacks need to be called).  Low
+        * priority numbers are more important, and stall higher ones.
+        */
+       struct event_list *activequeues;
+       /** The length of the activequeues array */
+       int nactivequeues;
+
+       /* common timeout logic */
+
+       /** An array of common_timeout_list* for all of the common timeout
+        * values we know. */
+       struct common_timeout_list **common_timeout_queues;
+       /** The number of entries used in common_timeout_queues */
+       int n_common_timeouts;
+       /** The total size of common_timeout_queues. */
+       int n_common_timeouts_allocated;
+
+       /** List of defered_cb that are active.  We run these after the active
+        * events. */
+       struct deferred_cb_queue defer_queue;
+
+       /** Mapping from file descriptors to enabled (added) events */
+       struct event_io_map io;
+
+       /** Mapping from signal numbers to enabled (added) events. */
+       struct event_signal_map sigmap;
+
+       /** All events that have been enabled (added) in this event_base */
+       struct event_list eventqueue;
+
+       /** Stored timeval; used to detect when time is running backwards. */
+       struct timeval event_tv;
+
+       /** Priority queue of events with timeouts. */
+       struct min_heap timeheap;
+
+       /** Stored timeval: used to avoid calling gettimeofday/clock_gettime
+        * too often. */
+       struct timeval tv_cache;
+
+#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
+       /** Difference between internal time (maybe from clock_gettime) and
+        * gettimeofday. */
+       struct timeval tv_clock_diff;
+       /** Second in which we last updated tv_clock_diff, in monotonic time. */
+       time_t last_updated_clock_diff;
+#endif
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       /* threading support */
+       /** The thread currently running the event_loop for this base */
+       unsigned long th_owner_id;
+       /** A lock to prevent conflicting accesses to this event_base */
+       void *th_base_lock;
+       /** The event whose callback is executing right now */
+       struct event *current_event;
+       /** A condition that gets signalled when we're done processing an
+        * event with waiters on it. */
+       void *current_event_cond;
+       /** Number of threads blocking on current_event_cond. */
+       int current_event_waiters;
+#endif
+
+#ifdef WIN32
+       /** IOCP support structure, if IOCP is enabled. */
+       struct event_iocp_port *iocp;
+#endif
+
+       /** Flags that this base was configured with */
+       enum event_base_config_flag flags;
+
+       /* Notify main thread to wake up break, etc. */
+       /** True if the base already has a pending notify, and we don't need
+        * to add any more. */
+       int is_notify_pending;
+       /** A socketpair used by some th_notify functions to wake up the main
+        * thread. */
+       evutil_socket_t th_notify_fd[2];
+       /** An event used by some th_notify functions to wake up the main
+        * thread. */
+       struct event th_notify;
+       /** A function used to wake up the main thread from another thread. */
+       int (*th_notify_fn)(struct event_base *base);
+};
+
+struct event_config_entry {
+       TAILQ_ENTRY(event_config_entry) next;
+
+       const char *avoid_method;
+};
+
+/** Internal structure: describes the configuration we want for an event_base
+ * that we're about to allocate. */
+struct event_config {
+       TAILQ_HEAD(event_configq, event_config_entry) entries;
+
+       int n_cpus_hint;
+       enum event_method_feature require_features;
+       enum event_base_config_flag flags;
+};
+
+/* Internal use only: Functions that might be missing from <sys/queue.h> */
+#if defined(_EVENT_HAVE_SYS_QUEUE_H) && !defined(_EVENT_HAVE_TAILQFOREACH)
+#ifndef TAILQ_FIRST
+#define        TAILQ_FIRST(head)               ((head)->tqh_first)
+#endif
+#ifndef TAILQ_END
+#define        TAILQ_END(head)                 NULL
+#endif
+#ifndef TAILQ_NEXT
+#define        TAILQ_NEXT(elm, field)          ((elm)->field.tqe_next)
+#endif
+
+#ifndef TAILQ_FOREACH
+#define TAILQ_FOREACH(var, head, field)                                        \
+       for ((var) = TAILQ_FIRST(head);                                 \
+            (var) != TAILQ_END(head);                                  \
+            (var) = TAILQ_NEXT(var, field))
+#endif
+
+#ifndef TAILQ_INSERT_BEFORE
+#define        TAILQ_INSERT_BEFORE(listelm, elm, field) do {                   \
+       (elm)->field.tqe_prev = (listelm)->field.tqe_prev;              \
+       (elm)->field.tqe_next = (listelm);                              \
+       *(listelm)->field.tqe_prev = (elm);                             \
+       (listelm)->field.tqe_prev = &(elm)->field.tqe_next;             \
+} while (0)
+#endif
+#endif /* TAILQ_FOREACH */
+
+#define N_ACTIVE_CALLBACKS(base)                                       \
+       ((base)->event_count_active + (base)->defer_queue.active_count)
+
+int _evsig_set_handler(struct event_base *base, int evsignal,
+                         void (*fn)(int));
+int _evsig_restore_handler(struct event_base *base, int evsignal);
+
+
+void event_active_nolock(struct event *ev, int res, short count);
+
+/* FIXME document. */
+void event_base_add_virtual(struct event_base *base);
+void event_base_del_virtual(struct event_base *base);
+
+/** For debugging: unless assertions are disabled, verify the referential
+    integrity of the internal data structures of 'base'.  This operation can
+    be expensive.
+
+    Returns on success; aborts on failure.
+*/
+void event_base_assert_ok(struct event_base *base);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT_INTERNAL_H_ */
+
diff --git a/libevent/event.3 b/libevent/event.3
new file mode 100644 (file)
index 0000000..5b33ec6
--- /dev/null
@@ -0,0 +1,624 @@
+.\"    $OpenBSD: event.3,v 1.4 2002/07/12 18:50:48 provos Exp $
+.\"
+.\" Copyright (c) 2000 Artur Grabowski <art@openbsd.org>
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
+.\" 3. The name of the author may not be used to endorse or promote products
+.\"    derived from this software without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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.
+.\"
+.Dd August 8, 2000
+.Dt EVENT 3
+.Os
+.Sh NAME
+.Nm event_init ,
+.Nm event_dispatch ,
+.Nm event_loop ,
+.Nm event_loopexit ,
+.Nm event_loopbreak ,
+.Nm event_set ,
+.Nm event_base_dispatch ,
+.Nm event_base_loop ,
+.Nm event_base_loopexit ,
+.Nm event_base_loopbreak ,
+.Nm event_base_set ,
+.Nm event_base_free ,
+.Nm event_add ,
+.Nm event_del ,
+.Nm event_once ,
+.Nm event_base_once ,
+.Nm event_pending ,
+.Nm event_initialized ,
+.Nm event_priority_init ,
+.Nm event_priority_set ,
+.Nm evtimer_set ,
+.Nm evtimer_add ,
+.Nm evtimer_del ,
+.Nm evtimer_pending ,
+.Nm evtimer_initialized ,
+.Nm signal_set ,
+.Nm signal_add ,
+.Nm signal_del ,
+.Nm signal_pending ,
+.Nm signal_initialized ,
+.Nm bufferevent_new ,
+.Nm bufferevent_free ,
+.Nm bufferevent_write ,
+.Nm bufferevent_write_buffer ,
+.Nm bufferevent_read ,
+.Nm bufferevent_enable ,
+.Nm bufferevent_disable ,
+.Nm bufferevent_settimeout ,
+.Nm bufferevent_base_set ,
+.Nm evbuffer_new ,
+.Nm evbuffer_free ,
+.Nm evbuffer_add ,
+.Nm evbuffer_add_buffer ,
+.Nm evbuffer_add_printf ,
+.Nm evbuffer_add_vprintf ,
+.Nm evbuffer_drain ,
+.Nm evbuffer_write ,
+.Nm evbuffer_read ,
+.Nm evbuffer_find ,
+.Nm evbuffer_readline ,
+.Nm evhttp_new ,
+.Nm evhttp_bind_socket ,
+.Nm evhttp_free
+.Nd execute a function when a specific event occurs
+.Sh SYNOPSIS
+.Fd #include <sys/time.h>
+.Fd #include <event.h>
+.Ft "struct event_base *"
+.Fn "event_init" "void"
+.Ft int
+.Fn "event_dispatch" "void"
+.Ft int
+.Fn "event_loop" "int flags"
+.Ft int
+.Fn "event_loopexit" "struct timeval *tv"
+.Ft int
+.Fn "event_loopbreak" "void"
+.Ft void
+.Fn "event_set" "struct event *ev" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg"
+.Ft int
+.Fn "event_base_dispatch" "struct event_base *base"
+.Ft int
+.Fn "event_base_loop" "struct event_base *base" "int flags"
+.Ft int
+.Fn "event_base_loopexit" "struct event_base *base" "struct timeval *tv"
+.Ft int
+.Fn "event_base_loopbreak" "struct event_base *base"
+.Ft int
+.Fn "event_base_set" "struct event_base *base" "struct event *"
+.Ft void
+.Fn "event_base_free" "struct event_base *base"
+.Ft int
+.Fn "event_add" "struct event *ev" "struct timeval *tv"
+.Ft int
+.Fn "event_del" "struct event *ev"
+.Ft int
+.Fn "event_once" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg" "struct timeval *tv"
+.Ft int
+.Fn "event_base_once" "struct event_base *base" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg" "struct timeval *tv"
+.Ft int
+.Fn "event_pending" "struct event *ev" "short event" "struct timeval *tv"
+.Ft int
+.Fn "event_initialized" "struct event *ev"
+.Ft int
+.Fn "event_priority_init" "int npriorities"
+.Ft int
+.Fn "event_priority_set" "struct event *ev" "int priority"
+.Ft void
+.Fn "evtimer_set" "struct event *ev" "void (*fn)(int, short, void *)" "void *arg"
+.Ft void
+.Fn "evtimer_add" "struct event *ev" "struct timeval *"
+.Ft void
+.Fn "evtimer_del" "struct event *ev"
+.Ft int
+.Fn "evtimer_pending" "struct event *ev" "struct timeval *tv"
+.Ft int
+.Fn "evtimer_initialized" "struct event *ev"
+.Ft void
+.Fn "signal_set" "struct event *ev" "int signal" "void (*fn)(int, short, void *)" "void *arg"
+.Ft void
+.Fn "signal_add" "struct event *ev" "struct timeval *"
+.Ft void
+.Fn "signal_del" "struct event *ev"
+.Ft int
+.Fn "signal_pending" "struct event *ev" "struct timeval *tv"
+.Ft int
+.Fn "signal_initialized" "struct event *ev"
+.Ft "struct bufferevent *"
+.Fn "bufferevent_new" "int fd" "evbuffercb readcb" "evbuffercb writecb" "everrorcb" "void *cbarg"
+.Ft void
+.Fn "bufferevent_free" "struct bufferevent *bufev"
+.Ft int
+.Fn "bufferevent_write" "struct bufferevent *bufev" "void *data" "size_t size"
+.Ft int
+.Fn "bufferevent_write_buffer" "struct bufferevent *bufev" "struct evbuffer *buf"
+.Ft size_t
+.Fn "bufferevent_read" "struct bufferevent *bufev" "void *data" "size_t size"
+.Ft int
+.Fn "bufferevent_enable" "struct bufferevent *bufev" "short event"
+.Ft int
+.Fn "bufferevent_disable" "struct bufferevent *bufev" "short event"
+.Ft void
+.Fn "bufferevent_settimeout" "struct bufferevent *bufev" "int timeout_read" "int timeout_write"
+.Ft int
+.Fn "bufferevent_base_set" "struct event_base *base" "struct bufferevent *bufev"
+.Ft "struct evbuffer *"
+.Fn "evbuffer_new" "void"
+.Ft void
+.Fn "evbuffer_free" "struct evbuffer *buf"
+.Ft int
+.Fn "evbuffer_add" "struct evbuffer *buf" "const void *data" "size_t size"
+.Ft int
+.Fn "evbuffer_add_buffer" "struct evbuffer *dst" "struct evbuffer *src"
+.Ft int
+.Fn "evbuffer_add_printf" "struct evbuffer *buf" "const char *fmt" "..."
+.Ft int
+.Fn "evbuffer_add_vprintf" "struct evbuffer *buf" "const char *fmt" "va_list ap"
+.Ft void
+.Fn "evbuffer_drain" "struct evbuffer *buf" "size_t size"
+.Ft int
+.Fn "evbuffer_write" "struct evbuffer *buf" "int fd"
+.Ft int
+.Fn "evbuffer_read" "struct evbuffer *buf" "int fd" "int size"
+.Ft "u_char *"
+.Fn "evbuffer_find" "struct evbuffer *buf" "const u_char *data" "size_t size"
+.Ft "char *"
+.Fn "evbuffer_readline" "struct evbuffer *buf"
+.Ft "struct evhttp *"
+.Fn "evhttp_new" "struct event_base *base"
+.Ft int
+.Fn "evhttp_bind_socket" "struct evhttp *http" "const char *address" "u_short port"
+.Ft "void"
+.Fn "evhttp_free" "struct evhttp *http"
+.Ft int
+.Fa (*event_sigcb)(void) ;
+.Ft volatile sig_atomic_t
+.Fa event_gotsig ;
+.Sh DESCRIPTION
+The
+.Nm event
+API provides a mechanism to execute a function when a specific event
+on a file descriptor occurs or after a given time has passed.
+.Pp
+The
+.Nm event
+API needs to be initialized with
+.Fn event_init
+before it can be used.
+.Pp
+In order to process events, an application needs to call
+.Fn event_dispatch .
+This function only returns on error, and should replace the event core
+of the application program.
+.Pp
+The function
+.Fn event_set
+prepares the event structure
+.Fa ev
+to be used in future calls to
+.Fn event_add
+and
+.Fn event_del .
+The event will be prepared to call the function specified by the
+.Fa fn
+argument with an
+.Fa int
+argument indicating the file descriptor, a
+.Fa short
+argument indicating the type of event, and a
+.Fa void *
+argument given in the
+.Fa arg
+argument.
+The
+.Fa fd
+indicates the file descriptor that should be monitored for events.
+The events can be either
+.Va EV_READ ,
+.Va EV_WRITE ,
+or both,
+indicating that an application can read or write from the file descriptor
+respectively without blocking.
+.Pp
+The function
+.Fa fn
+will be called with the file descriptor that triggered the event and
+the type of event which will be either
+.Va EV_TIMEOUT ,
+.Va EV_SIGNAL ,
+.Va EV_READ ,
+or
+.Va EV_WRITE .
+Additionally, an event which has registered interest in more than one of the
+preceeding events, via bitwise-OR to
+.Fn event_set ,
+can provide its callback function with a bitwise-OR of more than one triggered
+event.
+The additional flag
+.Va EV_PERSIST
+makes an
+.Fn event_add
+persistent until
+.Fn event_del
+has been called.
+.Pp
+Once initialized, the
+.Fa ev
+structure can be used repeatedly with
+.Fn event_add
+and
+.Fn event_del
+and does not need to be reinitialized unless the function called and/or
+the argument to it are to be changed.
+However, when an
+.Fa ev
+structure has been added to libevent using
+.Fn event_add
+the structure must persist until the event occurs (assuming
+.Fa EV_PERSIST
+is not set) or is removed
+using
+.Fn event_del .
+You may not reuse the same
+.Fa ev
+structure for multiple monitored descriptors; each descriptor
+needs its own
+.Fa ev .
+.Pp
+The function
+.Fn event_add
+schedules the execution of the
+.Fa ev
+event when the event specified in
+.Fn event_set
+occurs or in at least the time specified in the
+.Fa tv .
+If
+.Fa tv
+is
+.Dv NULL ,
+no timeout occurs and the function will only be called
+if a matching event occurs on the file descriptor.
+The event in the
+.Fa ev
+argument must be already initialized by
+.Fn event_set
+and may not be used in calls to
+.Fn event_set
+until it has timed out or been removed with
+.Fn event_del .
+If the event in the
+.Fa ev
+argument already has a scheduled timeout, the old timeout will be
+replaced by the new one.
+.Pp
+The function
+.Fn event_del
+will cancel the event in the argument
+.Fa ev .
+If the event has already executed or has never been added
+the call will have no effect.
+.Pp
+The functions
+.Fn evtimer_set ,
+.Fn evtimer_add ,
+.Fn evtimer_del ,
+.Fn evtimer_initialized ,
+and
+.Fn evtimer_pending
+are abbreviations for common situations where only a timeout is required.
+The file descriptor passed will be \-1, and the event type will be
+.Va EV_TIMEOUT .
+.Pp
+The functions
+.Fn signal_set ,
+.Fn signal_add ,
+.Fn signal_del ,
+.Fn signal_initialized ,
+and
+.Fn signal_pending
+are abbreviations.
+The event type will be a persistent
+.Va EV_SIGNAL .
+That means
+.Fn signal_set
+adds
+.Va EV_PERSIST .
+.Pp
+In order to avoid races in signal handlers, the
+.Nm event
+API provides two variables:
+.Va event_sigcb
+and
+.Va event_gotsig .
+A signal handler
+sets
+.Va event_gotsig
+to indicate that a signal has been received.
+The application sets
+.Va event_sigcb
+to a callback function.
+After the signal handler sets
+.Va event_gotsig ,
+.Nm event_dispatch
+will execute the callback function to process received signals.
+The callback returns 1 when no events are registered any more.
+It can return \-1 to indicate an error to the
+.Nm event
+library, causing
+.Fn event_dispatch
+to terminate with
+.Va errno
+set to
+.Er EINTR .
+.Pp
+The function
+.Fn event_once
+is similar to
+.Fn event_set .
+However, it schedules a callback to be called exactly once and does not
+require the caller to prepare an
+.Fa event
+structure.
+This function supports
+.Fa EV_TIMEOUT ,
+.Fa EV_READ ,
+and
+.Fa EV_WRITE .
+.Pp
+The
+.Fn event_pending
+function can be used to check if the event specified by
+.Fa event
+is pending to run.
+If
+.Va EV_TIMEOUT
+was specified and
+.Fa tv
+is not
+.Dv NULL ,
+the expiration time of the event will be returned in
+.Fa tv .
+.Pp
+The
+.Fn event_initialized
+macro can be used to check if an event has been initialized.
+.Pp
+The
+.Nm event_loop
+function provides an interface for single pass execution of pending
+events.
+The flags
+.Va EVLOOP_ONCE
+and
+.Va EVLOOP_NONBLOCK
+are recognized.
+The
+.Nm event_loopexit
+function exits from the event loop. The next
+.Fn event_loop
+iteration after the
+given timer expires will complete normally (handling all queued events) then
+exit without blocking for events again. Subsequent invocations of
+.Fn event_loop
+will proceed normally.
+The
+.Nm event_loopbreak
+function exits from the event loop immediately.
+.Fn event_loop
+will abort after the next event is completed;
+.Fn event_loopbreak
+is typically invoked from this event's callback. This behavior is analogous
+to the "break;" statement. Subsequent invocations of
+.Fn event_loop
+will proceed normally.
+.Pp
+It is the responsibility of the caller to provide these functions with
+pre-allocated event structures.
+.Pp
+.Sh EVENT PRIORITIES
+By default
+.Nm libevent
+schedules all active events with the same priority.
+However, sometimes it is desirable to process some events with a higher
+priority than others.
+For that reason,
+.Nm libevent
+supports strict priority queues.
+Active events with a lower priority are always processed before events
+with a higher priority.
+.Pp
+The number of different priorities can be set initially with the
+.Fn event_priority_init
+function.
+This function should be called before the first call to
+.Fn event_dispatch .
+The
+.Fn event_priority_set
+function can be used to assign a priority to an event.
+By default,
+.Nm libevent
+assigns the middle priority to all events unless their priority
+is explicitly set.
+.Sh THREAD SAFE EVENTS
+.Nm Libevent
+has experimental support for thread-safe events.
+When initializing the library via
+.Fn event_init ,
+an event base is returned.
+This event base can be used in conjunction with calls to
+.Fn event_base_set ,
+.Fn event_base_dispatch ,
+.Fn event_base_loop ,
+.Fn event_base_loopexit ,
+.Fn bufferevent_base_set
+and
+.Fn event_base_free .
+.Fn event_base_set
+should be called after preparing an event with
+.Fn event_set ,
+as
+.Fn event_set
+assigns the provided event to the most recently created event base.
+.Fn bufferevent_base_set
+should be called after preparing a bufferevent with
+.Fn bufferevent_new .
+.Fn event_base_free
+should be used to free memory associated with the event base
+when it is no longer needed.
+.Sh BUFFERED EVENTS
+.Nm libevent
+provides an abstraction on top of the regular event callbacks.
+This abstraction is called a
+.Va "buffered event" .
+A buffered event provides input and output buffers that get filled
+and drained automatically.
+The user of a buffered event no longer deals directly with the IO,
+but instead is reading from input and writing to output buffers.
+.Pp
+A new bufferevent is created by
+.Fn bufferevent_new .
+The parameter
+.Fa fd
+specifies the file descriptor from which data is read and written to.
+This file descriptor is not allowed to be a
+.Xr pipe 2 .
+The next three parameters are callbacks.
+The read and write callback have the following form:
+.Ft void
+.Fn "(*cb)" "struct bufferevent *bufev" "void *arg" .
+The error callback has the following form:
+.Ft void
+.Fn "(*cb)" "struct bufferevent *bufev" "short what" "void *arg" .
+The argument is specified by the fourth parameter
+.Fa "cbarg" .
+A
+.Fa bufferevent struct
+pointer is returned on success, NULL on error.
+Both the read and the write callback may be NULL.
+The error callback has to be always provided.
+.Pp
+Once initialized, the bufferevent structure can be used repeatedly with
+bufferevent_enable() and bufferevent_disable().
+The flags parameter can be a combination of
+.Va EV_READ
+and
+.Va EV_WRITE .
+When read enabled the bufferevent will try to read from the file
+descriptor and call the read callback.
+The write callback is executed
+whenever the output buffer is drained below the write low watermark,
+which is
+.Va 0
+by default.
+.Pp
+The
+.Fn bufferevent_write
+function can be used to write data to the file descriptor.
+The data is appended to the output buffer and written to the descriptor
+automatically as it becomes available for writing.
+.Fn bufferevent_write
+returns 0 on success or \-1 on failure.
+The
+.Fn bufferevent_read
+function is used to read data from the input buffer,
+returning the amount of data read.
+.Pp
+If multiple bases are in use, bufferevent_base_set() must be called before
+enabling the bufferevent for the first time.
+.Sh NON-BLOCKING HTTP SUPPORT
+.Nm libevent
+provides a very thin HTTP layer that can be used both to host an HTTP
+server and also to make HTTP requests.
+An HTTP server can be created by calling
+.Fn evhttp_new .
+It can be bound to any port and address with the
+.Fn evhttp_bind_socket
+function.
+When the HTTP server is no longer used, it can be freed via
+.Fn evhttp_free .
+.Pp
+To be notified of HTTP requests, a user needs to register callbacks with the
+HTTP server.
+This can be done by calling
+.Fn evhttp_set_cb .
+The second argument is the URI for which a callback is being registered.
+The corresponding callback will receive an
+.Va struct evhttp_request
+object that contains all information about the request.
+.Pp
+This section does not document all the possible function calls; please
+check
+.Va event.h
+for the public interfaces.
+.Sh ADDITIONAL NOTES
+It is possible to disable support for
+.Va epoll , kqueue , devpoll , poll
+or
+.Va select
+by setting the environment variable
+.Va EVENT_NOEPOLL , EVENT_NOKQUEUE , EVENT_NODEVPOLL , EVENT_NOPOLL
+or
+.Va EVENT_NOSELECT ,
+respectively.
+By setting the environment variable
+.Va EVENT_SHOW_METHOD ,
+.Nm libevent
+displays the kernel notification method that it uses.
+.Sh RETURN VALUES
+Upon successful completion
+.Fn event_add
+and
+.Fn event_del
+return 0.
+Otherwise, \-1 is returned and the global variable errno is
+set to indicate the error.
+.Sh SEE ALSO
+.Xr kqueue 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr evdns 3 ,
+.Xr timeout 9
+.Sh HISTORY
+The
+.Nm event
+API manpage is based on the
+.Xr timeout 9
+manpage by Artur Grabowski.
+The port of
+.Nm libevent
+to Windows is due to Michael A. Davis.
+Support for real-time signals is due to Taral.
+.Sh AUTHORS
+The
+.Nm event
+library was written by Niels Provos.
+.Sh BUGS
+This documentation is neither complete nor authoritative.
+If you are in doubt about the usage of this API then
+check the source code to find out how it works, write
+up the missing piece of documentation and send it to
+me for inclusion in this man page.
diff --git a/libevent/event.c b/libevent/event.c
new file mode 100644 (file)
index 0000000..f13cdcf
--- /dev/null
@@ -0,0 +1,2897 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+#include <sys/types.h>
+#if !defined(WIN32) && defined(_EVENT_HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_EVENTFD_H
+#include <sys/eventfd.h>
+#endif
+#include <ctype.h>
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+#include <time.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/event_compat.h"
+#include "event-internal.h"
+#include "defer-internal.h"
+#include "evthread-internal.h"
+#include "event2/thread.h"
+#include "event2/util.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "iocp-internal.h"
+#include "changelist-internal.h"
+#include "ht-internal.h"
+#include "util-internal.h"
+
+#ifdef _EVENT_HAVE_EVENT_PORTS
+extern const struct eventop evportops;
+#endif
+#ifdef _EVENT_HAVE_SELECT
+extern const struct eventop selectops;
+#endif
+#ifdef _EVENT_HAVE_POLL
+extern const struct eventop pollops;
+#endif
+#ifdef _EVENT_HAVE_EPOLL
+extern const struct eventop epollops;
+#endif
+#ifdef _EVENT_HAVE_WORKING_KQUEUE
+extern const struct eventop kqops;
+#endif
+#ifdef _EVENT_HAVE_DEVPOLL
+extern const struct eventop devpollops;
+#endif
+#ifdef WIN32
+extern const struct eventop win32ops;
+#endif
+
+/* Array of backends in order of preference. */
+static const struct eventop *eventops[] = {
+#ifdef _EVENT_HAVE_EVENT_PORTS
+       &evportops,
+#endif
+#ifdef _EVENT_HAVE_WORKING_KQUEUE
+       &kqops,
+#endif
+#ifdef _EVENT_HAVE_EPOLL
+       &epollops,
+#endif
+#ifdef _EVENT_HAVE_DEVPOLL
+       &devpollops,
+#endif
+#ifdef _EVENT_HAVE_POLL
+       &pollops,
+#endif
+#ifdef _EVENT_HAVE_SELECT
+       &selectops,
+#endif
+#ifdef WIN32
+       &win32ops,
+#endif
+       NULL
+};
+
+/* Global state; deprecated */
+struct event_base *event_global_current_base_ = NULL;
+#define current_base event_global_current_base_
+
+/* Global state */
+
+static int use_monotonic;
+
+/* Prototypes */
+static inline int event_add_internal(struct event *ev,
+    const struct timeval *tv, int tv_is_absolute);
+static inline int event_del_internal(struct event *ev);
+
+static void    event_queue_insert(struct event_base *, struct event *, int);
+static void    event_queue_remove(struct event_base *, struct event *, int);
+static int     event_haveevents(struct event_base *);
+
+static int     event_process_active(struct event_base *);
+
+static int     timeout_next(struct event_base *, struct timeval **);
+static void    timeout_process(struct event_base *);
+static void    timeout_correct(struct event_base *, struct timeval *);
+
+static inline void     event_signal_closure(struct event_base *, struct event *ev);
+static inline void     event_persist_closure(struct event_base *, struct event *ev);
+
+static int     evthread_notify_base(struct event_base *base);
+
+#ifndef _EVENT_DISABLE_DEBUG_MODE
+/* These functions implement a hashtable of which 'struct event *' structures
+ * have been setup or added.  We don't want to trust the content of the struct
+ * event itself, since we're trying to work through cases where an event gets
+ * clobbered or freed.  Instead, we keep a hashtable indexed by the pointer.
+ */
+
+struct event_debug_entry {
+       HT_ENTRY(event_debug_entry) node;
+       const struct event *ptr;
+       unsigned added : 1;
+};
+
+static inline unsigned
+hash_debug_entry(const struct event_debug_entry *e)
+{
+       /* We need to do this silliness to convince compilers that we
+        * honestly mean to cast e->ptr to an integer, and discard any
+        * part of it that doesn't fit in an unsigned.
+        */
+       unsigned u = (unsigned) ((ev_uintptr_t) e->ptr);
+       /* Our hashtable implementation is pretty sensitive to low bits,
+        * and every struct event is over 64 bytes in size, so we can
+        * just say >>6. */
+       return (u >> 6);
+}
+
+static inline int
+eq_debug_entry(const struct event_debug_entry *a,
+    const struct event_debug_entry *b)
+{
+       return a->ptr == b->ptr;
+}
+
+int _event_debug_mode_on = 0;
+/* Set if it's too late to enable event_debug_mode. */
+static int event_debug_mode_too_late = 0;
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+static void *_event_debug_map_lock = NULL;
+#endif
+static HT_HEAD(event_debug_map, event_debug_entry) global_debug_map =
+       HT_INITIALIZER();
+
+HT_PROTOTYPE(event_debug_map, event_debug_entry, node, hash_debug_entry,
+    eq_debug_entry)
+HT_GENERATE(event_debug_map, event_debug_entry, node, hash_debug_entry,
+    eq_debug_entry, 0.5, mm_malloc, mm_realloc, mm_free)
+
+/* Macro: record that ev is now setup (that is, ready for an add) */
+#define _event_debug_note_setup(ev) do {                               \
+       if (_event_debug_mode_on) {                                     \
+               struct event_debug_entry *dent,find;                    \
+               find.ptr = (ev);                                        \
+               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
+               if (dent) {                                             \
+                       dent->added = 0;                                \
+               } else {                                                \
+                       dent = mm_malloc(sizeof(*dent));                \
+                       if (!dent)                                      \
+                               event_err(1,                            \
+                                   "Out of memory in debugging code"); \
+                       dent->ptr = (ev);                               \
+                       dent->added = 0;                                \
+                       HT_INSERT(event_debug_map, &global_debug_map, dent); \
+               }                                                       \
+               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+       }                                                               \
+       event_debug_mode_too_late = 1;                                  \
+       } while (0)
+/* Macro: record that ev is no longer setup */
+#define _event_debug_note_teardown(ev) do {                            \
+       if (_event_debug_mode_on) {                                     \
+               struct event_debug_entry *dent,find;                    \
+               find.ptr = (ev);                                        \
+               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               dent = HT_REMOVE(event_debug_map, &global_debug_map, &find); \
+               if (dent)                                               \
+                       mm_free(dent);                                  \
+               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+       }                                                               \
+       event_debug_mode_too_late = 1;                                  \
+       } while (0)
+/* Macro: record that ev is now added */
+#define _event_debug_note_add(ev)      do {                            \
+       if (_event_debug_mode_on) {                                     \
+               struct event_debug_entry *dent,find;                    \
+               find.ptr = (ev);                                        \
+               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
+               if (dent) {                                             \
+                       dent->added = 1;                                \
+               } else {                                                \
+                       event_errx(_EVENT_ERR_ABORT,                    \
+                           "%s: noting an add on a non-setup event %p" \
+                           " (events: 0x%x, fd: %d, flags: 0x%x)",     \
+                           __func__, (ev), (ev)->ev_events,            \
+                           (ev)->ev_fd, (ev)->ev_flags);               \
+               }                                                       \
+               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+       }                                                               \
+       event_debug_mode_too_late = 1;                                  \
+       } while (0)
+/* Macro: record that ev is no longer added */
+#define _event_debug_note_del(ev) do {                                 \
+       if (_event_debug_mode_on) {                                     \
+               struct event_debug_entry *dent,find;                    \
+               find.ptr = (ev);                                        \
+               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
+               if (dent) {                                             \
+                       dent->added = 0;                                \
+               } else {                                                \
+                       event_errx(_EVENT_ERR_ABORT,                    \
+                           "%s: noting a del on a non-setup event %p"  \
+                           " (events: 0x%x, fd: %d, flags: 0x%x)",     \
+                           __func__, (ev), (ev)->ev_events,            \
+                           (ev)->ev_fd, (ev)->ev_flags);               \
+               }                                                       \
+               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+       }                                                               \
+       event_debug_mode_too_late = 1;                                  \
+       } while (0)
+/* Macro: assert that ev is setup (i.e., okay to add or inspect) */
+#define _event_debug_assert_is_setup(ev) do {                          \
+       if (_event_debug_mode_on) {                                     \
+               struct event_debug_entry *dent,find;                    \
+               find.ptr = (ev);                                        \
+               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
+               if (!dent) {                                            \
+                       event_errx(_EVENT_ERR_ABORT,                    \
+                           "%s called on a non-initialized event %p"   \
+                           " (events: 0x%x, fd: %d, flags: 0x%x)",     \
+                           __func__, (ev), (ev)->ev_events,            \
+                           (ev)->ev_fd, (ev)->ev_flags);               \
+               }                                                       \
+               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+       }                                                               \
+       } while (0)
+/* Macro: assert that ev is not added (i.e., okay to tear down or set
+ * up again) */
+#define _event_debug_assert_not_added(ev) do {                         \
+       if (_event_debug_mode_on) {                                     \
+               struct event_debug_entry *dent,find;                    \
+               find.ptr = (ev);                                        \
+               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
+               if (dent && dent->added) {                              \
+                       event_errx(_EVENT_ERR_ABORT,                    \
+                           "%s called on an already added event %p"    \
+                           " (events: 0x%x, fd: %d, flags: 0x%x)",     \
+                           __func__, (ev), (ev)->ev_events,            \
+                           (ev)->ev_fd, (ev)->ev_flags);               \
+               }                                                       \
+               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+       }                                                               \
+       } while (0)
+#else
+#define _event_debug_note_setup(ev) \
+       ((void)0)
+#define _event_debug_note_teardown(ev) \
+       ((void)0)
+#define _event_debug_note_add(ev) \
+       ((void)0)
+#define _event_debug_note_del(ev) \
+       ((void)0)
+#define _event_debug_assert_is_setup(ev) \
+       ((void)0)
+#define _event_debug_assert_not_added(ev) \
+       ((void)0)
+#endif
+
+#define EVENT_BASE_ASSERT_LOCKED(base)         \
+       EVLOCK_ASSERT_LOCKED((base)->th_base_lock)
+
+/* The first time this function is called, it sets use_monotonic to 1
+ * if we have a clock function that supports monotonic time */
+static void
+detect_monotonic(void)
+{
+#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
+       struct timespec ts;
+       static int use_monotonic_initialized = 0;
+
+       if (use_monotonic_initialized)
+               return;
+
+       if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
+               use_monotonic = 1;
+
+       use_monotonic_initialized = 1;
+#endif
+}
+
+/* How often (in seconds) do we check for changes in wall clock time relative
+ * to monotonic time?  Set this to -1 for 'never.' */
+#define CLOCK_SYNC_INTERVAL -1
+
+/** Set 'tp' to the current time according to 'base'.  We must hold the lock
+ * on 'base'.  If there is a cached time, return it.  Otherwise, use
+ * clock_gettime or gettimeofday as appropriate to find out the right time.
+ * Return 0 on success, -1 on failure.
+ */
+static int
+gettime(struct event_base *base, struct timeval *tp)
+{
+       EVENT_BASE_ASSERT_LOCKED(base);
+
+       if (base->tv_cache.tv_sec) {
+               *tp = base->tv_cache;
+               return (0);
+       }
+
+#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
+       if (use_monotonic) {
+               struct timespec ts;
+
+               if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
+                       return (-1);
+
+               tp->tv_sec = ts.tv_sec;
+               tp->tv_usec = ts.tv_nsec / 1000;
+               if (base->last_updated_clock_diff + CLOCK_SYNC_INTERVAL
+                   < ts.tv_sec) {
+                       struct timeval tv;
+                       evutil_gettimeofday(&tv,NULL);
+                       evutil_timersub(&tv, tp, &base->tv_clock_diff);
+                       base->last_updated_clock_diff = ts.tv_sec;
+               }
+
+               return (0);
+       }
+#endif
+
+       return (evutil_gettimeofday(tp, NULL));
+}
+
+int
+event_base_gettimeofday_cached(struct event_base *base, struct timeval *tv)
+{
+       int r;
+       if (!base) {
+               base = current_base;
+               if (!current_base)
+                       return evutil_gettimeofday(tv, NULL);
+       }
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       if (base->tv_cache.tv_sec == 0) {
+               r = evutil_gettimeofday(tv, NULL);
+       } else {
+#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
+               evutil_timeradd(&base->tv_cache, &base->tv_clock_diff, tv);
+#else
+               *tv = base->tv_cache;
+#endif
+               r = 0;
+       }
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       return r;
+}
+
+/** Make 'base' have no current cached time. */
+static inline void
+clear_time_cache(struct event_base *base)
+{
+       base->tv_cache.tv_sec = 0;
+}
+
+/** Replace the cached time in 'base' with the current time. */
+static inline void
+update_time_cache(struct event_base *base)
+{
+       base->tv_cache.tv_sec = 0;
+       if (!(base->flags & EVENT_BASE_FLAG_NO_CACHE_TIME))
+           gettime(base, &base->tv_cache);
+}
+
+struct event_base *
+event_init(void)
+{
+       struct event_base *base = event_base_new_with_config(NULL);
+
+       if (base == NULL) {
+               event_errx(1, "%s: Unable to construct event_base", __func__);
+               return NULL;
+       }
+
+       current_base = base;
+
+       return (base);
+}
+
+struct event_base *
+event_base_new(void)
+{
+       struct event_base *base = NULL;
+       struct event_config *cfg = event_config_new();
+       if (cfg) {
+               base = event_base_new_with_config(cfg);
+               event_config_free(cfg);
+       }
+       return base;
+}
+
+/** Return true iff 'method' is the name of a method that 'cfg' tells us to
+ * avoid. */
+static int
+event_config_is_avoided_method(const struct event_config *cfg,
+    const char *method)
+{
+       struct event_config_entry *entry;
+
+       TAILQ_FOREACH(entry, &cfg->entries, next) {
+               if (entry->avoid_method != NULL &&
+                   strcmp(entry->avoid_method, method) == 0)
+                       return (1);
+       }
+
+       return (0);
+}
+
+/** Return true iff 'method' is disabled according to the environment. */
+static int
+event_is_method_disabled(const char *name)
+{
+       char environment[64];
+       int i;
+
+       evutil_snprintf(environment, sizeof(environment), "EVENT_NO%s", name);
+       for (i = 8; environment[i] != '\0'; ++i)
+               environment[i] = EVUTIL_TOUPPER(environment[i]);
+       /* Note that evutil_getenv() ignores the environment entirely if
+        * we're setuid */
+       return (evutil_getenv(environment) != NULL);
+}
+
+int
+event_base_get_features(const struct event_base *base)
+{
+       return base->evsel->features;
+}
+
+void
+event_deferred_cb_queue_init(struct deferred_cb_queue *cb)
+{
+       memset(cb, 0, sizeof(struct deferred_cb_queue));
+       TAILQ_INIT(&cb->deferred_cb_list);
+}
+
+/** Helper for the deferred_cb queue: wake up the event base. */
+static void
+notify_base_cbq_callback(struct deferred_cb_queue *cb, void *baseptr)
+{
+       struct event_base *base = baseptr;
+       if (EVBASE_NEED_NOTIFY(base))
+               evthread_notify_base(base);
+}
+
+struct deferred_cb_queue *
+event_base_get_deferred_cb_queue(struct event_base *base)
+{
+       return base ? &base->defer_queue : NULL;
+}
+
+void
+event_enable_debug_mode(void)
+{
+#ifndef _EVENT_DISABLE_DEBUG_MODE
+       if (_event_debug_mode_on)
+               event_errx(1, "%s was called twice!", __func__);
+       if (event_debug_mode_too_late)
+               event_errx(1, "%s must be called *before* creating any events "
+                   "or event_bases",__func__);
+
+       _event_debug_mode_on = 1;
+
+       HT_INIT(event_debug_map, &global_debug_map);
+#endif
+}
+
+#if 0
+void
+event_disable_debug_mode(void)
+{
+       struct event_debug_entry **ent, *victim;
+
+       EVLOCK_LOCK(_event_debug_map_lock, 0);
+       for (ent = HT_START(event_debug_map, &global_debug_map); ent; ) {
+               victim = *ent;
+               ent = HT_NEXT_RMV(event_debug_map,&global_debug_map, ent);
+               mm_free(victim);
+       }
+       HT_CLEAR(event_debug_map, &global_debug_map);
+       EVLOCK_UNLOCK(_event_debug_map_lock , 0);
+}
+#endif
+
+struct event_base *
+event_base_new_with_config(const struct event_config *cfg)
+{
+       int i;
+       struct event_base *base;
+       int should_check_environment;
+
+#ifndef _EVENT_DISABLE_DEBUG_MODE
+       event_debug_mode_too_late = 1;
+#endif
+
+       if ((base = mm_calloc(1, sizeof(struct event_base))) == NULL) {
+               event_warn("%s: calloc", __func__);
+               return NULL;
+       }
+       detect_monotonic();
+       gettime(base, &base->event_tv);
+
+       min_heap_ctor(&base->timeheap);
+       TAILQ_INIT(&base->eventqueue);
+       base->sig.ev_signal_pair[0] = -1;
+       base->sig.ev_signal_pair[1] = -1;
+       base->th_notify_fd[0] = -1;
+       base->th_notify_fd[1] = -1;
+
+       event_deferred_cb_queue_init(&base->defer_queue);
+       base->defer_queue.notify_fn = notify_base_cbq_callback;
+       base->defer_queue.notify_arg = base;
+       if (cfg)
+               base->flags = cfg->flags;
+
+       evmap_io_initmap(&base->io);
+       evmap_signal_initmap(&base->sigmap);
+       event_changelist_init(&base->changelist);
+
+       base->evbase = NULL;
+
+       should_check_environment =
+           !(cfg && (cfg->flags & EVENT_BASE_FLAG_IGNORE_ENV));
+
+       for (i = 0; eventops[i] && !base->evbase; i++) {
+               if (cfg != NULL) {
+                       /* determine if this backend should be avoided */
+                       if (event_config_is_avoided_method(cfg,
+                               eventops[i]->name))
+                               continue;
+                       if ((eventops[i]->features & cfg->require_features)
+                           != cfg->require_features)
+                               continue;
+               }
+
+               /* also obey the environment variables */
+               if (should_check_environment &&
+                   event_is_method_disabled(eventops[i]->name))
+                       continue;
+
+               base->evsel = eventops[i];
+
+               base->evbase = base->evsel->init(base);
+       }
+
+       if (base->evbase == NULL) {
+               event_warnx("%s: no event mechanism available",
+                   __func__);
+               base->evsel = NULL;
+               event_base_free(base);
+               return NULL;
+       }
+
+       if (evutil_getenv("EVENT_SHOW_METHOD"))
+               event_msgx("libevent using: %s", base->evsel->name);
+
+       /* allocate a single active event queue */
+       if (event_base_priority_init(base, 1) < 0) {
+               event_base_free(base);
+               return NULL;
+       }
+
+       /* prepare for threading */
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       if (EVTHREAD_LOCKING_ENABLED() &&
+           (!cfg || !(cfg->flags & EVENT_BASE_FLAG_NOLOCK))) {
+               int r;
+               EVTHREAD_ALLOC_LOCK(base->th_base_lock,
+                   EVTHREAD_LOCKTYPE_RECURSIVE);
+               base->defer_queue.lock = base->th_base_lock;
+               EVTHREAD_ALLOC_COND(base->current_event_cond);
+               r = evthread_make_base_notifiable(base);
+               if (r<0) {
+                       event_warnx("%s: Unable to make base notifiable.", __func__);
+                       event_base_free(base);
+                       return NULL;
+               }
+       }
+#endif
+
+#ifdef WIN32
+       if (cfg && (cfg->flags & EVENT_BASE_FLAG_STARTUP_IOCP))
+               event_base_start_iocp(base, cfg->n_cpus_hint);
+#endif
+
+       return (base);
+}
+
+int
+event_base_start_iocp(struct event_base *base, int n_cpus)
+{
+#ifdef WIN32
+       if (base->iocp)
+               return 0;
+       base->iocp = event_iocp_port_launch(n_cpus);
+       if (!base->iocp) {
+               event_warnx("%s: Couldn't launch IOCP", __func__);
+               return -1;
+       }
+       return 0;
+#else
+       return -1;
+#endif
+}
+
+void
+event_base_stop_iocp(struct event_base *base)
+{
+#ifdef WIN32
+       int rv;
+
+       if (!base->iocp)
+               return;
+       rv = event_iocp_shutdown(base->iocp, -1);
+       EVUTIL_ASSERT(rv >= 0);
+       base->iocp = NULL;
+#endif
+}
+
+void
+event_base_free(struct event_base *base)
+{
+       int i, n_deleted=0;
+       struct event *ev;
+       /* XXXX grab the lock? If there is contention when one thread frees
+        * the base, then the contending thread will be very sad soon. */
+
+       /* event_base_free(NULL) is how to free the current_base if we
+        * made it with event_init and forgot to hold a reference to it. */
+       if (base == NULL && current_base)
+               base = current_base;
+       /* If we're freeing current_base, there won't be a current_base. */
+       if (base == current_base)
+               current_base = NULL;
+       /* Don't actually free NULL. */
+       if (base == NULL) {
+               event_warnx("%s: no base to free", __func__);
+               return;
+       }
+       /* XXX(niels) - check for internal events first */
+
+#ifdef WIN32
+       event_base_stop_iocp(base);
+#endif
+
+       /* threading fds if we have them */
+       if (base->th_notify_fd[0] != -1) {
+               event_del(&base->th_notify);
+               EVUTIL_CLOSESOCKET(base->th_notify_fd[0]);
+               if (base->th_notify_fd[1] != -1)
+                       EVUTIL_CLOSESOCKET(base->th_notify_fd[1]);
+               base->th_notify_fd[0] = -1;
+               base->th_notify_fd[1] = -1;
+               event_debug_unassign(&base->th_notify);
+       }
+
+       /* Delete all non-internal events. */
+       for (ev = TAILQ_FIRST(&base->eventqueue); ev; ) {
+               struct event *next = TAILQ_NEXT(ev, ev_next);
+               if (!(ev->ev_flags & EVLIST_INTERNAL)) {
+                       event_del(ev);
+                       ++n_deleted;
+               }
+               ev = next;
+       }
+       while ((ev = min_heap_top(&base->timeheap)) != NULL) {
+               event_del(ev);
+               ++n_deleted;
+       }
+       for (i = 0; i < base->n_common_timeouts; ++i) {
+               struct common_timeout_list *ctl =
+                   base->common_timeout_queues[i];
+               event_del(&ctl->timeout_event); /* Internal; doesn't count */
+               event_debug_unassign(&ctl->timeout_event);
+               for (ev = TAILQ_FIRST(&ctl->events); ev; ) {
+                       struct event *next = TAILQ_NEXT(ev,
+                           ev_timeout_pos.ev_next_with_common_timeout);
+                       if (!(ev->ev_flags & EVLIST_INTERNAL)) {
+                               event_del(ev);
+                               ++n_deleted;
+                       }
+                       ev = next;
+               }
+               mm_free(ctl);
+       }
+       if (base->common_timeout_queues)
+               mm_free(base->common_timeout_queues);
+
+       for (i = 0; i < base->nactivequeues; ++i) {
+               for (ev = TAILQ_FIRST(&base->activequeues[i]); ev; ) {
+                       struct event *next = TAILQ_NEXT(ev, ev_active_next);
+                       if (!(ev->ev_flags & EVLIST_INTERNAL)) {
+                               event_del(ev);
+                               ++n_deleted;
+                       }
+                       ev = next;
+               }
+       }
+
+       if (n_deleted)
+               event_debug(("%s: %d events were still set in base",
+                       __func__, n_deleted));
+
+       if (base->evsel != NULL && base->evsel->dealloc != NULL)
+               base->evsel->dealloc(base);
+
+       for (i = 0; i < base->nactivequeues; ++i)
+               EVUTIL_ASSERT(TAILQ_EMPTY(&base->activequeues[i]));
+
+       EVUTIL_ASSERT(min_heap_empty(&base->timeheap));
+       min_heap_dtor(&base->timeheap);
+
+       mm_free(base->activequeues);
+
+       EVUTIL_ASSERT(TAILQ_EMPTY(&base->eventqueue));
+
+       evmap_io_clear(&base->io);
+       evmap_signal_clear(&base->sigmap);
+       event_changelist_freemem(&base->changelist);
+
+       EVTHREAD_FREE_LOCK(base->th_base_lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       EVTHREAD_FREE_COND(base->current_event_cond);
+
+       mm_free(base);
+}
+
+/* reinitialize the event base after a fork */
+int
+event_reinit(struct event_base *base)
+{
+       const struct eventop *evsel;
+       int res = 0;
+       struct event *ev;
+       int was_notifiable = 0;
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       evsel = base->evsel;
+
+#if 0
+       /* Right now, reinit always takes effect, since even if the
+          backend doesn't require it, the signal socketpair code does.
+
+          XXX
+        */
+       /* check if this event mechanism requires reinit */
+       if (!evsel->need_reinit)
+               goto done;
+#endif
+
+       /* prevent internal delete */
+       if (base->sig.ev_signal_added) {
+               /* we cannot call event_del here because the base has
+                * not been reinitialized yet. */
+               event_queue_remove(base, &base->sig.ev_signal,
+                   EVLIST_INSERTED);
+               if (base->sig.ev_signal.ev_flags & EVLIST_ACTIVE)
+                       event_queue_remove(base, &base->sig.ev_signal,
+                           EVLIST_ACTIVE);
+               if (base->sig.ev_signal_pair[0] != -1)
+                       EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[0]);
+               if (base->sig.ev_signal_pair[1] != -1)
+                       EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[1]);
+               base->sig.ev_signal_added = 0;
+       }
+       if (base->th_notify_fd[0] != -1) {
+               /* we cannot call event_del here because the base has
+                * not been reinitialized yet. */
+               was_notifiable = 1;
+               event_queue_remove(base, &base->th_notify,
+                   EVLIST_INSERTED);
+               if (base->th_notify.ev_flags & EVLIST_ACTIVE)
+                       event_queue_remove(base, &base->th_notify,
+                           EVLIST_ACTIVE);
+               base->sig.ev_signal_added = 0;
+               EVUTIL_CLOSESOCKET(base->th_notify_fd[0]);
+               if (base->th_notify_fd[1] != -1)
+                       EVUTIL_CLOSESOCKET(base->th_notify_fd[1]);
+               base->th_notify_fd[0] = -1;
+               base->th_notify_fd[1] = -1;
+               event_debug_unassign(&base->th_notify);
+       }
+
+       if (base->evsel->dealloc != NULL)
+               base->evsel->dealloc(base);
+       base->evbase = evsel->init(base);
+       if (base->evbase == NULL) {
+               event_errx(1, "%s: could not reinitialize event mechanism",
+                   __func__);
+               res = -1;
+               goto done;
+       }
+
+       event_changelist_freemem(&base->changelist); /* XXX */
+       evmap_io_clear(&base->io);
+       evmap_signal_clear(&base->sigmap);
+
+       TAILQ_FOREACH(ev, &base->eventqueue, ev_next) {
+               if (ev->ev_events & (EV_READ|EV_WRITE)) {
+                       if (ev == &base->sig.ev_signal) {
+                               /* If we run into the ev_signal event, it's only
+                                * in eventqueue because some signal event was
+                                * added, which made evsig_add re-add ev_signal.
+                                * So don't double-add it. */
+                               continue;
+                       }
+                       if (evmap_io_add(base, ev->ev_fd, ev) == -1)
+                               res = -1;
+               } else if (ev->ev_events & EV_SIGNAL) {
+                       if (evmap_signal_add(base, (int)ev->ev_fd, ev) == -1)
+                               res = -1;
+               }
+       }
+
+       if (was_notifiable && res == 0)
+               res = evthread_make_base_notifiable(base);
+
+done:
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       return (res);
+}
+
+const char **
+event_get_supported_methods(void)
+{
+       static const char **methods = NULL;
+       const struct eventop **method;
+       const char **tmp;
+       int i = 0, k;
+
+       /* count all methods */
+       for (method = &eventops[0]; *method != NULL; ++method) {
+               ++i;
+       }
+
+       /* allocate one more than we need for the NULL pointer */
+       tmp = mm_calloc((i + 1), sizeof(char *));
+       if (tmp == NULL)
+               return (NULL);
+
+       /* populate the array with the supported methods */
+       for (k = 0, i = 0; eventops[k] != NULL; ++k) {
+               tmp[i++] = eventops[k]->name;
+       }
+       tmp[i] = NULL;
+
+       if (methods != NULL)
+               mm_free((char**)methods);
+
+       methods = tmp;
+
+       return (methods);
+}
+
+struct event_config *
+event_config_new(void)
+{
+       struct event_config *cfg = mm_calloc(1, sizeof(*cfg));
+
+       if (cfg == NULL)
+               return (NULL);
+
+       TAILQ_INIT(&cfg->entries);
+
+       return (cfg);
+}
+
+static void
+event_config_entry_free(struct event_config_entry *entry)
+{
+       if (entry->avoid_method != NULL)
+               mm_free((char *)entry->avoid_method);
+       mm_free(entry);
+}
+
+void
+event_config_free(struct event_config *cfg)
+{
+       struct event_config_entry *entry;
+
+       while ((entry = TAILQ_FIRST(&cfg->entries)) != NULL) {
+               TAILQ_REMOVE(&cfg->entries, entry, next);
+               event_config_entry_free(entry);
+       }
+       mm_free(cfg);
+}
+
+int
+event_config_set_flag(struct event_config *cfg, int flag)
+{
+       if (!cfg)
+               return -1;
+       cfg->flags |= flag;
+       return 0;
+}
+
+int
+event_config_avoid_method(struct event_config *cfg, const char *method)
+{
+       struct event_config_entry *entry = mm_malloc(sizeof(*entry));
+       if (entry == NULL)
+               return (-1);
+
+       if ((entry->avoid_method = mm_strdup(method)) == NULL) {
+               mm_free(entry);
+               return (-1);
+       }
+
+       TAILQ_INSERT_TAIL(&cfg->entries, entry, next);
+
+       return (0);
+}
+
+int
+event_config_require_features(struct event_config *cfg,
+    int features)
+{
+       if (!cfg)
+               return (-1);
+       cfg->require_features = features;
+       return (0);
+}
+
+int
+event_config_set_num_cpus_hint(struct event_config *cfg, int cpus)
+{
+       if (!cfg)
+               return (-1);
+       cfg->n_cpus_hint = cpus;
+       return (0);
+}
+
+int
+event_priority_init(int npriorities)
+{
+       return event_base_priority_init(current_base, npriorities);
+}
+
+int
+event_base_priority_init(struct event_base *base, int npriorities)
+{
+       int i;
+
+       if (N_ACTIVE_CALLBACKS(base) || npriorities < 1
+           || npriorities >= EVENT_MAX_PRIORITIES)
+               return (-1);
+
+       if (npriorities == base->nactivequeues)
+               return (0);
+
+       if (base->nactivequeues) {
+               mm_free(base->activequeues);
+               base->nactivequeues = 0;
+       }
+
+       /* Allocate our priority queues */
+       base->activequeues = (struct event_list *)
+         mm_calloc(npriorities, sizeof(struct event_list));
+       if (base->activequeues == NULL) {
+               event_warn("%s: calloc", __func__);
+               return (-1);
+       }
+       base->nactivequeues = npriorities;
+
+       for (i = 0; i < base->nactivequeues; ++i) {
+               TAILQ_INIT(&base->activequeues[i]);
+       }
+
+       return (0);
+}
+
+/* Returns true iff we're currently watching any events. */
+static int
+event_haveevents(struct event_base *base)
+{
+       /* Caller must hold th_base_lock */
+       return (base->virtual_event_count > 0 || base->event_count > 0);
+}
+
+/* "closure" function called when processing active signal events */
+static inline void
+event_signal_closure(struct event_base *base, struct event *ev)
+{
+       short ncalls;
+       int should_break;
+
+       /* Allows deletes to work */
+       ncalls = ev->ev_ncalls;
+       if (ncalls != 0)
+               ev->ev_pncalls = &ncalls;
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       while (ncalls) {
+               ncalls--;
+               ev->ev_ncalls = ncalls;
+               if (ncalls == 0)
+                       ev->ev_pncalls = NULL;
+               (*ev->ev_callback)(ev->ev_fd, ev->ev_res, ev->ev_arg);
+
+               EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+               should_break = base->event_break;
+               EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+               if (should_break) {
+                       if (ncalls != 0)
+                               ev->ev_pncalls = NULL;
+                       return;
+               }
+       }
+}
+
+/* Common timeouts are special timeouts that are handled as queues rather than
+ * in the minheap.  This is more efficient than the minheap if we happen to
+ * know that we're going to get several thousands of timeout events all with
+ * the same timeout value.
+ *
+ * Since all our timeout handling code assumes timevals can be copied,
+ * assigned, etc, we can't use "magic pointer" to encode these common
+ * timeouts.  Searching through a list to see if every timeout is common could
+ * also get inefficient.  Instead, we take advantage of the fact that tv_usec
+ * is 32 bits long, but only uses 20 of those bits (since it can never be over
+ * 999999.)  We use the top bits to encode 4 bites of magic number, and 8 bits
+ * of index into the event_base's aray of common timeouts.
+ */
+
+#define MICROSECONDS_MASK       COMMON_TIMEOUT_MICROSECONDS_MASK
+#define COMMON_TIMEOUT_IDX_MASK 0x0ff00000
+#define COMMON_TIMEOUT_IDX_SHIFT 20
+#define COMMON_TIMEOUT_MASK     0xf0000000
+#define COMMON_TIMEOUT_MAGIC    0x50000000
+
+#define COMMON_TIMEOUT_IDX(tv) \
+       (((tv)->tv_usec & COMMON_TIMEOUT_IDX_MASK)>>COMMON_TIMEOUT_IDX_SHIFT)
+
+/** Return true iff if 'tv' is a common timeout in 'base' */
+static inline int
+is_common_timeout(const struct timeval *tv,
+    const struct event_base *base)
+{
+       int idx;
+       if ((tv->tv_usec & COMMON_TIMEOUT_MASK) != COMMON_TIMEOUT_MAGIC)
+               return 0;
+       idx = COMMON_TIMEOUT_IDX(tv);
+       return idx < base->n_common_timeouts;
+}
+
+/* True iff tv1 and tv2 have the same common-timeout index, or if neither
+ * one is a common timeout. */
+static inline int
+is_same_common_timeout(const struct timeval *tv1, const struct timeval *tv2)
+{
+       return (tv1->tv_usec & ~MICROSECONDS_MASK) ==
+           (tv2->tv_usec & ~MICROSECONDS_MASK);
+}
+
+/** Requires that 'tv' is a common timeout.  Return the corresponding
+ * common_timeout_list. */
+static inline struct common_timeout_list *
+get_common_timeout_list(struct event_base *base, const struct timeval *tv)
+{
+       return base->common_timeout_queues[COMMON_TIMEOUT_IDX(tv)];
+}
+
+#if 0
+static inline int
+common_timeout_ok(const struct timeval *tv,
+    struct event_base *base)
+{
+       const struct timeval *expect =
+           &get_common_timeout_list(base, tv)->duration;
+       return tv->tv_sec == expect->tv_sec &&
+           tv->tv_usec == expect->tv_usec;
+}
+#endif
+
+/* Add the timeout for the first event in given common timeout list to the
+ * event_base's minheap. */
+static void
+common_timeout_schedule(struct common_timeout_list *ctl,
+    const struct timeval *now, struct event *head)
+{
+       struct timeval timeout = head->ev_timeout;
+       timeout.tv_usec &= MICROSECONDS_MASK;
+       event_add_internal(&ctl->timeout_event, &timeout, 1);
+}
+
+/* Callback: invoked when the timeout for a common timeout queue triggers.
+ * This means that (at least) the first event in that queue should be run,
+ * and the timeout should be rescheduled if there are more events. */
+static void
+common_timeout_callback(evutil_socket_t fd, short what, void *arg)
+{
+       struct timeval now;
+       struct common_timeout_list *ctl = arg;
+       struct event_base *base = ctl->base;
+       struct event *ev = NULL;
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       gettime(base, &now);
+       while (1) {
+               ev = TAILQ_FIRST(&ctl->events);
+               if (!ev || ev->ev_timeout.tv_sec > now.tv_sec ||
+                   (ev->ev_timeout.tv_sec == now.tv_sec &&
+                       (ev->ev_timeout.tv_usec&MICROSECONDS_MASK) > now.tv_usec))
+                       break;
+               event_del_internal(ev);
+               event_active_nolock(ev, EV_TIMEOUT, 1);
+       }
+       if (ev)
+               common_timeout_schedule(ctl, &now, ev);
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+#define MAX_COMMON_TIMEOUTS 256
+
+const struct timeval *
+event_base_init_common_timeout(struct event_base *base,
+    const struct timeval *duration)
+{
+       int i;
+       struct timeval tv;
+       const struct timeval *result=NULL;
+       struct common_timeout_list *new_ctl;
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       if (duration->tv_usec > 1000000) {
+               memcpy(&tv, duration, sizeof(struct timeval));
+               if (is_common_timeout(duration, base))
+                       tv.tv_usec &= MICROSECONDS_MASK;
+               tv.tv_sec += tv.tv_usec / 1000000;
+               tv.tv_usec %= 1000000;
+               duration = &tv;
+       }
+       for (i = 0; i < base->n_common_timeouts; ++i) {
+               const struct common_timeout_list *ctl =
+                   base->common_timeout_queues[i];
+               if (duration->tv_sec == ctl->duration.tv_sec &&
+                   duration->tv_usec ==
+                   (ctl->duration.tv_usec & MICROSECONDS_MASK)) {
+                       EVUTIL_ASSERT(is_common_timeout(&ctl->duration, base));
+                       result = &ctl->duration;
+                       goto done;
+               }
+       }
+       if (base->n_common_timeouts == MAX_COMMON_TIMEOUTS) {
+               event_warnx("%s: Too many common timeouts already in use; "
+                   "we only support %d per event_base", __func__,
+                   MAX_COMMON_TIMEOUTS);
+               goto done;
+       }
+       if (base->n_common_timeouts_allocated == base->n_common_timeouts) {
+               int n = base->n_common_timeouts < 16 ? 16 :
+                   base->n_common_timeouts*2;
+               struct common_timeout_list **newqueues =
+                   mm_realloc(base->common_timeout_queues,
+                       n*sizeof(struct common_timeout_queue *));
+               if (!newqueues) {
+                       event_warn("%s: realloc",__func__);
+                       goto done;
+               }
+               base->n_common_timeouts_allocated = n;
+               base->common_timeout_queues = newqueues;
+       }
+       new_ctl = mm_calloc(1, sizeof(struct common_timeout_list));
+       if (!new_ctl) {
+               event_warn("%s: calloc",__func__);
+               goto done;
+       }
+       TAILQ_INIT(&new_ctl->events);
+       new_ctl->duration.tv_sec = duration->tv_sec;
+       new_ctl->duration.tv_usec =
+           duration->tv_usec | COMMON_TIMEOUT_MAGIC |
+           (base->n_common_timeouts << COMMON_TIMEOUT_IDX_SHIFT);
+       evtimer_assign(&new_ctl->timeout_event, base,
+           common_timeout_callback, new_ctl);
+       new_ctl->timeout_event.ev_flags |= EVLIST_INTERNAL;
+       event_priority_set(&new_ctl->timeout_event, 0);
+       new_ctl->base = base;
+       base->common_timeout_queues[base->n_common_timeouts++] = new_ctl;
+       result = &new_ctl->duration;
+
+done:
+       if (result)
+               EVUTIL_ASSERT(is_common_timeout(result, base));
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       return result;
+}
+
+/* Closure function invoked when we're activating a persistent event. */
+static inline void
+event_persist_closure(struct event_base *base, struct event *ev)
+{
+       /* reschedule the persistent event if we have a timeout. */
+       if (ev->ev_io_timeout.tv_sec || ev->ev_io_timeout.tv_usec) {
+               /* If there was a timeout, we want it to run at an interval of
+                * ev_io_timeout after the last time it was _scheduled_ for,
+                * not ev_io_timeout after _now_.  If it fired for another
+                * reason, though, the timeout ought to start ticking _now_. */
+               struct timeval run_at;
+               EVUTIL_ASSERT(is_same_common_timeout(&ev->ev_timeout,
+                       &ev->ev_io_timeout));
+               if (is_common_timeout(&ev->ev_timeout, base)) {
+                       ev_uint32_t usec_mask;
+                       struct timeval delay, relative_to;
+                       delay = ev->ev_io_timeout;
+                       usec_mask = delay.tv_usec & ~MICROSECONDS_MASK;
+                       delay.tv_usec &= MICROSECONDS_MASK;
+                       if (ev->ev_res & EV_TIMEOUT) {
+                               relative_to = ev->ev_timeout;
+                               relative_to.tv_usec &= MICROSECONDS_MASK;
+                       } else {
+                               gettime(base, &relative_to);
+                       }
+                       evutil_timeradd(&relative_to, &delay, &run_at);
+                       run_at.tv_usec |= usec_mask;
+               } else {
+                       struct timeval relative_to;
+                       if (ev->ev_res & EV_TIMEOUT) {
+                               relative_to = ev->ev_timeout;
+                       } else {
+                               gettime(base, &relative_to);
+                       }
+                       evutil_timeradd(&ev->ev_io_timeout, &relative_to,
+                           &run_at);
+               }
+               event_add_internal(ev, &run_at, 1);
+       }
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       (*ev->ev_callback)(ev->ev_fd, ev->ev_res, ev->ev_arg);
+}
+
+/*
+  Helper for event_process_active to process all the events in a single queue,
+  releasing the lock as we go.  This function requires that the lock be held
+  when it's invoked.  Returns -1 if we get a signal or an event_break that
+  means we should stop processing any active events now.  Otherwise returns
+  the number of non-internal events that we processed.
+*/
+static int
+event_process_active_single_queue(struct event_base *base,
+    struct event_list *activeq)
+{
+       struct event *ev;
+       int count = 0;
+
+       EVUTIL_ASSERT(activeq != NULL);
+
+       for (ev = TAILQ_FIRST(activeq); ev; ev = TAILQ_FIRST(activeq)) {
+               if (ev->ev_events & EV_PERSIST)
+                       event_queue_remove(base, ev, EVLIST_ACTIVE);
+               else
+                       event_del_internal(ev);
+               if (!(ev->ev_flags & EVLIST_INTERNAL))
+                       ++count;
+
+               event_debug((
+                        "event_process_active: event: %p, %s%scall %p",
+                       ev,
+                       ev->ev_res & EV_READ ? "EV_READ " : " ",
+                       ev->ev_res & EV_WRITE ? "EV_WRITE " : " ",
+                       ev->ev_callback));
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+               base->current_event = ev;
+               base->current_event_waiters = 0;
+#endif
+
+               switch (ev->ev_closure) {
+               case EV_CLOSURE_SIGNAL:
+                       event_signal_closure(base, ev);
+                       break;
+               case EV_CLOSURE_PERSIST:
+                       event_persist_closure(base, ev);
+                       break;
+               default:
+               case EV_CLOSURE_NONE:
+                       EVBASE_RELEASE_LOCK(base, th_base_lock);
+                       (*ev->ev_callback)(
+                               ev->ev_fd, ev->ev_res, ev->ev_arg);
+                       break;
+               }
+
+               EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+               base->current_event = NULL;
+               if (base->current_event_waiters) {
+                       base->current_event_waiters = 0;
+                       EVTHREAD_COND_BROADCAST(base->current_event_cond);
+               }
+#endif
+
+               if (base->event_break)
+                       return -1;
+       }
+       return count;
+}
+
+/*
+   Process up to MAX_DEFERRED of the defered_cb entries in 'queue'.  If
+   *breakptr becomes set to 1, stop.  Requires that we start out holding
+   the lock on 'queue'; releases the lock around 'queue' for each deferred_cb
+   we process.
+ */
+static int
+event_process_deferred_callbacks(struct deferred_cb_queue *queue, int *breakptr)
+{
+       int count = 0;
+       struct deferred_cb *cb;
+
+#define MAX_DEFERRED 16
+       while ((cb = TAILQ_FIRST(&queue->deferred_cb_list))) {
+               cb->queued = 0;
+               TAILQ_REMOVE(&queue->deferred_cb_list, cb, cb_next);
+               --queue->active_count;
+               UNLOCK_DEFERRED_QUEUE(queue);
+
+               cb->cb(cb, cb->arg);
+
+               LOCK_DEFERRED_QUEUE(queue);
+               if (*breakptr)
+                       return -1;
+               if (++count == MAX_DEFERRED)
+                       break;
+       }
+#undef MAX_DEFERRED
+       return count;
+}
+
+/*
+ * Active events are stored in priority queues.  Lower priorities are always
+ * process before higher priorities.  Low priority events can starve high
+ * priority ones.
+ */
+
+static int
+event_process_active(struct event_base *base)
+{
+       /* Caller must hold th_base_lock */
+       struct event_list *activeq = NULL;
+       int i, c = 0;
+
+       for (i = 0; i < base->nactivequeues; ++i) {
+               if (TAILQ_FIRST(&base->activequeues[i]) != NULL) {
+                       activeq = &base->activequeues[i];
+                       c = event_process_active_single_queue(base, activeq);
+                       if (c < 0)
+                               return -1;
+                       else if (c > 0)
+                               break; /* Processed a real event; do not
+                                       * consider lower-priority events */
+                       /* If we get here, all of the events we processed
+                        * were internal.  Continue. */
+               }
+       }
+
+       event_process_deferred_callbacks(&base->defer_queue,&base->event_break);
+       return c;
+}
+
+/*
+ * Wait continuously for events.  We exit only if no events are left.
+ */
+
+int
+event_dispatch(void)
+{
+       return (event_loop(0));
+}
+
+int
+event_base_dispatch(struct event_base *event_base)
+{
+       return (event_base_loop(event_base, 0));
+}
+
+const char *
+event_base_get_method(const struct event_base *base)
+{
+       EVUTIL_ASSERT(base);
+       return (base->evsel->name);
+}
+
+/** Callback: used to implement event_base_loopexit by telling the event_base
+ * that it's time to exit its loop. */
+static void
+event_loopexit_cb(evutil_socket_t fd, short what, void *arg)
+{
+       struct event_base *base = arg;
+       base->event_gotterm = 1;
+}
+
+int
+event_loopexit(const struct timeval *tv)
+{
+       return (event_once(-1, EV_TIMEOUT, event_loopexit_cb,
+                   current_base, tv));
+}
+
+int
+event_base_loopexit(struct event_base *event_base, const struct timeval *tv)
+{
+       return (event_base_once(event_base, -1, EV_TIMEOUT, event_loopexit_cb,
+                   event_base, tv));
+}
+
+int
+event_loopbreak(void)
+{
+       return (event_base_loopbreak(current_base));
+}
+
+int
+event_base_loopbreak(struct event_base *event_base)
+{
+       int r = 0;
+       if (event_base == NULL)
+               return (-1);
+
+       EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
+       event_base->event_break = 1;
+
+       if (EVBASE_NEED_NOTIFY(event_base)) {
+               r = evthread_notify_base(event_base);
+       } else {
+               r = (0);
+       }
+       EVBASE_RELEASE_LOCK(event_base, th_base_lock);
+       return r;
+}
+
+int
+event_base_got_break(struct event_base *event_base)
+{
+       int res;
+       EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
+       res = event_base->event_break;
+       EVBASE_RELEASE_LOCK(event_base, th_base_lock);
+       return res;
+}
+
+int
+event_base_got_exit(struct event_base *event_base)
+{
+       int res;
+       EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
+       res = event_base->event_gotterm;
+       EVBASE_RELEASE_LOCK(event_base, th_base_lock);
+       return res;
+}
+
+/* not thread safe */
+
+int
+event_loop(int flags)
+{
+       return event_base_loop(current_base, flags);
+}
+
+int
+event_base_loop(struct event_base *base, int flags)
+{
+       const struct eventop *evsel = base->evsel;
+       struct timeval tv;
+       struct timeval *tv_p;
+       int res, done, retval = 0;
+
+       /* Grab the lock.  We will release it inside evsel.dispatch, and again
+        * as we invoke user callbacks. */
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       if (base->running_loop) {
+               event_warnx("%s: reentrant invocation.  Only one event_base_loop"
+                   " can run on each event_base at once.", __func__);
+               EVBASE_RELEASE_LOCK(base, th_base_lock);
+               return -1;
+       }
+
+       base->running_loop = 1;
+
+       clear_time_cache(base);
+
+       if (base->sig.ev_signal_added && base->sig.ev_n_signals_added)
+               evsig_set_base(base);
+
+       done = 0;
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       base->th_owner_id = EVTHREAD_GET_ID();
+#endif
+
+       base->event_gotterm = base->event_break = 0;
+
+       while (!done) {
+               /* Terminate the loop if we have been asked to */
+               if (base->event_gotterm) {
+                       break;
+               }
+
+               if (base->event_break) {
+                       break;
+               }
+
+               timeout_correct(base, &tv);
+
+               tv_p = &tv;
+               if (!N_ACTIVE_CALLBACKS(base) && !(flags & EVLOOP_NONBLOCK)) {
+                       timeout_next(base, &tv_p);
+               } else {
+                       /*
+                        * if we have active events, we just poll new events
+                        * without waiting.
+                        */
+                       evutil_timerclear(&tv);
+               }
+
+               /* If we have no events, we just exit */
+               if (!event_haveevents(base) && !N_ACTIVE_CALLBACKS(base)) {
+                       event_debug(("%s: no events registered.", __func__));
+                       retval = 1;
+                       goto done;
+               }
+
+               /* update last old time */
+               gettime(base, &base->event_tv);
+
+               clear_time_cache(base);
+
+               res = evsel->dispatch(base, tv_p);
+
+               if (res == -1) {
+                       event_debug(("%s: dispatch returned unsuccessfully.",
+                               __func__));
+                       retval = -1;
+                       goto done;
+               }
+
+               update_time_cache(base);
+
+               timeout_process(base);
+
+               if (N_ACTIVE_CALLBACKS(base)) {
+                       int n = event_process_active(base);
+                       if ((flags & EVLOOP_ONCE)
+                           && N_ACTIVE_CALLBACKS(base) == 0
+                           && n != 0)
+                               done = 1;
+               } else if (flags & EVLOOP_NONBLOCK)
+                       done = 1;
+       }
+       event_debug(("%s: asked to terminate loop.", __func__));
+
+done:
+       clear_time_cache(base);
+       base->running_loop = 0;
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+       return (retval);
+}
+
+/* Sets up an event for processing once */
+struct event_once {
+       struct event ev;
+
+       void (*cb)(evutil_socket_t, short, void *);
+       void *arg;
+};
+
+/* One-time callback to implement event_base_once: invokes the user callback,
+ * then deletes the allocated storage */
+static void
+event_once_cb(evutil_socket_t fd, short events, void *arg)
+{
+       struct event_once *eonce = arg;
+
+       (*eonce->cb)(fd, events, eonce->arg);
+       event_debug_unassign(&eonce->ev);
+       mm_free(eonce);
+}
+
+/* not threadsafe, event scheduled once. */
+int
+event_once(evutil_socket_t fd, short events,
+    void (*callback)(evutil_socket_t, short, void *),
+    void *arg, const struct timeval *tv)
+{
+       return event_base_once(current_base, fd, events, callback, arg, tv);
+}
+
+/* Schedules an event once */
+int
+event_base_once(struct event_base *base, evutil_socket_t fd, short events,
+    void (*callback)(evutil_socket_t, short, void *),
+    void *arg, const struct timeval *tv)
+{
+       struct event_once *eonce;
+       struct timeval etv;
+       int res = 0;
+
+       /* We cannot support signals that just fire once, or persistent
+        * events. */
+       if (events & (EV_SIGNAL|EV_PERSIST))
+               return (-1);
+
+       if ((eonce = mm_calloc(1, sizeof(struct event_once))) == NULL)
+               return (-1);
+
+       eonce->cb = callback;
+       eonce->arg = arg;
+
+       if (events == EV_TIMEOUT) {
+               if (tv == NULL) {
+                       evutil_timerclear(&etv);
+                       tv = &etv;
+               }
+
+               evtimer_assign(&eonce->ev, base, event_once_cb, eonce);
+       } else if (events & (EV_READ|EV_WRITE)) {
+               events &= EV_READ|EV_WRITE;
+
+               event_assign(&eonce->ev, base, fd, events, event_once_cb, eonce);
+       } else {
+               /* Bad event combination */
+               mm_free(eonce);
+               return (-1);
+       }
+
+       if (res == 0)
+               res = event_add(&eonce->ev, tv);
+       if (res != 0) {
+               mm_free(eonce);
+               return (res);
+       }
+
+       return (0);
+}
+
+int
+event_assign(struct event *ev, struct event_base *base, evutil_socket_t fd, short events, void (*callback)(evutil_socket_t, short, void *), void *arg)
+{
+       if (!base)
+               base = current_base;
+
+       _event_debug_assert_not_added(ev);
+
+       ev->ev_base = base;
+
+       ev->ev_callback = callback;
+       ev->ev_arg = arg;
+       ev->ev_fd = fd;
+       ev->ev_events = events;
+       ev->ev_res = 0;
+       ev->ev_flags = EVLIST_INIT;
+       ev->ev_ncalls = 0;
+       ev->ev_pncalls = NULL;
+
+       if (events & EV_SIGNAL) {
+               if ((events & (EV_READ|EV_WRITE)) != 0) {
+                       event_warnx("%s: EV_SIGNAL is not compatible with "
+                           "EV_READ or EV_WRITE", __func__);
+                       return -1;
+               }
+               ev->ev_closure = EV_CLOSURE_SIGNAL;
+       } else {
+               if (events & EV_PERSIST) {
+                       evutil_timerclear(&ev->ev_io_timeout);
+                       ev->ev_closure = EV_CLOSURE_PERSIST;
+               } else {
+                       ev->ev_closure = EV_CLOSURE_NONE;
+               }
+       }
+
+       min_heap_elem_init(ev);
+
+       if (base != NULL) {
+               /* by default, we put new events into the middle priority */
+               ev->ev_pri = base->nactivequeues / 2;
+       }
+
+       _event_debug_note_setup(ev);
+
+       return 0;
+}
+
+int
+event_base_set(struct event_base *base, struct event *ev)
+{
+       /* Only innocent events may be assigned to a different base */
+       if (ev->ev_flags != EVLIST_INIT)
+               return (-1);
+
+       _event_debug_assert_is_setup(ev);
+
+       ev->ev_base = base;
+       ev->ev_pri = base->nactivequeues/2;
+
+       return (0);
+}
+
+void
+event_set(struct event *ev, evutil_socket_t fd, short events,
+         void (*callback)(evutil_socket_t, short, void *), void *arg)
+{
+       int r;
+       r = event_assign(ev, current_base, fd, events, callback, arg);
+       EVUTIL_ASSERT(r == 0);
+}
+
+struct event *
+event_new(struct event_base *base, evutil_socket_t fd, short events, void (*cb)(evutil_socket_t, short, void *), void *arg)
+{
+       struct event *ev;
+       ev = mm_malloc(sizeof(struct event));
+       if (ev == NULL)
+               return (NULL);
+       if (event_assign(ev, base, fd, events, cb, arg) < 0) {
+               mm_free(ev);
+               return (NULL);
+       }
+
+       return (ev);
+}
+
+void
+event_free(struct event *ev)
+{
+       _event_debug_assert_is_setup(ev);
+
+       /* make sure that this event won't be coming back to haunt us. */
+       event_del(ev);
+       _event_debug_note_teardown(ev);
+       mm_free(ev);
+
+}
+
+void
+event_debug_unassign(struct event *ev)
+{
+       _event_debug_assert_not_added(ev);
+       _event_debug_note_teardown(ev);
+
+       ev->ev_flags &= ~EVLIST_INIT;
+}
+
+/*
+ * Set's the priority of an event - if an event is already scheduled
+ * changing the priority is going to fail.
+ */
+
+int
+event_priority_set(struct event *ev, int pri)
+{
+       _event_debug_assert_is_setup(ev);
+
+       if (ev->ev_flags & EVLIST_ACTIVE)
+               return (-1);
+       if (pri < 0 || pri >= ev->ev_base->nactivequeues)
+               return (-1);
+
+       ev->ev_pri = pri;
+
+       return (0);
+}
+
+/*
+ * Checks if a specific event is pending or scheduled.
+ */
+
+int
+event_pending(const struct event *ev, short event, struct timeval *tv)
+{
+       int flags = 0;
+
+       _event_debug_assert_is_setup(ev);
+
+       if (ev->ev_flags & EVLIST_INSERTED)
+               flags |= (ev->ev_events & (EV_READ|EV_WRITE|EV_SIGNAL));
+       if (ev->ev_flags & EVLIST_ACTIVE)
+               flags |= ev->ev_res;
+       if (ev->ev_flags & EVLIST_TIMEOUT)
+               flags |= EV_TIMEOUT;
+
+       event &= (EV_TIMEOUT|EV_READ|EV_WRITE|EV_SIGNAL);
+
+       /* See if there is a timeout that we should report */
+       if (tv != NULL && (flags & event & EV_TIMEOUT)) {
+               struct timeval tmp = ev->ev_timeout;
+               tmp.tv_usec &= MICROSECONDS_MASK;
+#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
+               /* correctly remamp to real time */
+               evutil_timeradd(&ev->ev_base->tv_clock_diff, &tmp, tv);
+#else
+               *tv = tmp;
+#endif
+       }
+
+       return (flags & event);
+}
+
+int
+event_initialized(const struct event *ev)
+{
+       if (!(ev->ev_flags & EVLIST_INIT))
+               return 0;
+
+       return 1;
+}
+
+void
+event_get_assignment(const struct event *event, struct event_base **base_out, evutil_socket_t *fd_out, short *events_out, event_callback_fn *callback_out, void **arg_out)
+{
+       _event_debug_assert_is_setup(event);
+
+       if (base_out)
+               *base_out = event->ev_base;
+       if (fd_out)
+               *fd_out = event->ev_fd;
+       if (events_out)
+               *events_out = event->ev_events;
+       if (callback_out)
+               *callback_out = event->ev_callback;
+       if (arg_out)
+               *arg_out = event->ev_arg;
+}
+
+size_t
+event_get_struct_event_size(void)
+{
+       return sizeof(struct event);
+}
+
+evutil_socket_t
+event_get_fd(const struct event *ev)
+{
+       _event_debug_assert_is_setup(ev);
+       return ev->ev_fd;
+}
+
+struct event_base *
+event_get_base(const struct event *ev)
+{
+       _event_debug_assert_is_setup(ev);
+       return ev->ev_base;
+}
+
+short
+event_get_events(const struct event *ev)
+{
+       _event_debug_assert_is_setup(ev);
+       return ev->ev_events;
+}
+
+event_callback_fn
+event_get_callback(const struct event *ev)
+{
+       _event_debug_assert_is_setup(ev);
+       return ev->ev_callback;
+}
+
+void *
+event_get_callback_arg(const struct event *ev)
+{
+       _event_debug_assert_is_setup(ev);
+       return ev->ev_arg;
+}
+
+int
+event_add(struct event *ev, const struct timeval *tv)
+{
+       int res;
+
+       if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
+               event_warnx("%s: event has no event_base set.", __func__);
+               return -1;
+       }
+
+       EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
+
+       res = event_add_internal(ev, tv, 0);
+
+       EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
+
+       return (res);
+}
+
+/* Helper callback: wake an event_base from another thread.  This version
+ * works by writing a byte to one end of a socketpair, so that the event_base
+ * listening on the other end will wake up as the corresponding event
+ * triggers */
+static int
+evthread_notify_base_default(struct event_base *base)
+{
+       char buf[1];
+       int r;
+       buf[0] = (char) 0;
+#ifdef WIN32
+       r = send(base->th_notify_fd[1], buf, 1, 0);
+#else
+       r = write(base->th_notify_fd[1], buf, 1);
+#endif
+       return (r < 0 && errno != EAGAIN) ? -1 : 0;
+}
+
+#if defined(_EVENT_HAVE_EVENTFD) && defined(_EVENT_HAVE_SYS_EVENTFD_H)
+/* Helper callback: wake an event_base from another thread.  This version
+ * assumes that you have a working eventfd() implementation. */
+static int
+evthread_notify_base_eventfd(struct event_base *base)
+{
+       ev_uint64_t msg = 1;
+       int r;
+       do {
+               r = write(base->th_notify_fd[0], (void*) &msg, sizeof(msg));
+       } while (r < 0 && errno == EAGAIN);
+
+       return (r < 0) ? -1 : 0;
+}
+#endif
+
+/** Tell the thread currently running the event_loop for base (if any) that it
+ * needs to stop waiting in its dispatch function (if it is) and process all
+ * active events and deferred callbacks (if there are any).  */
+static int
+evthread_notify_base(struct event_base *base)
+{
+       EVENT_BASE_ASSERT_LOCKED(base);
+       if (!base->th_notify_fn)
+               return -1;
+       if (base->is_notify_pending)
+               return 0;
+       base->is_notify_pending = 1;
+       return base->th_notify_fn(base);
+}
+
+/* Implementation function to add an event.  Works just like event_add,
+ * except: 1) it requires that we have the lock.  2) if tv_is_absolute is set,
+ * we treat tv as an absolute time, not as an interval to add to the current
+ * time */
+static inline int
+event_add_internal(struct event *ev, const struct timeval *tv,
+    int tv_is_absolute)
+{
+       struct event_base *base = ev->ev_base;
+       int res = 0;
+       int notify = 0;
+
+       EVENT_BASE_ASSERT_LOCKED(base);
+       _event_debug_assert_is_setup(ev);
+
+       event_debug((
+                "event_add: event: %p (fd %d), %s%s%scall %p",
+                ev,
+                (int)ev->ev_fd,
+                ev->ev_events & EV_READ ? "EV_READ " : " ",
+                ev->ev_events & EV_WRITE ? "EV_WRITE " : " ",
+                tv ? "EV_TIMEOUT " : " ",
+                ev->ev_callback));
+
+       EVUTIL_ASSERT(!(ev->ev_flags & ~EVLIST_ALL));
+
+       /*
+        * prepare for timeout insertion further below, if we get a
+        * failure on any step, we should not change any state.
+        */
+       if (tv != NULL && !(ev->ev_flags & EVLIST_TIMEOUT)) {
+               if (min_heap_reserve(&base->timeheap,
+                       1 + min_heap_size(&base->timeheap)) == -1)
+                       return (-1);  /* ENOMEM == errno */
+       }
+
+       /* If the main thread is currently executing a signal event's
+        * callback, and we are not the main thread, then we want to wait
+        * until the callback is done before we mess with the event, or else
+        * we can race on ev_ncalls and ev_pncalls below. */
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       if (base->current_event == ev && (ev->ev_events & EV_SIGNAL)
+           && !EVBASE_IN_THREAD(base)) {
+               ++base->current_event_waiters;
+               EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
+       }
+#endif
+
+       if ((ev->ev_events & (EV_READ|EV_WRITE|EV_SIGNAL)) &&
+           !(ev->ev_flags & (EVLIST_INSERTED|EVLIST_ACTIVE))) {
+               if (ev->ev_events & (EV_READ|EV_WRITE))
+                       res = evmap_io_add(base, ev->ev_fd, ev);
+               else if (ev->ev_events & EV_SIGNAL)
+                       res = evmap_signal_add(base, (int)ev->ev_fd, ev);
+               if (res != -1)
+                       event_queue_insert(base, ev, EVLIST_INSERTED);
+               if (res == 1) {
+                       /* evmap says we need to notify the main thread. */
+                       notify = 1;
+                       res = 0;
+               }
+       }
+
+       /*
+        * we should change the timeout state only if the previous event
+        * addition succeeded.
+        */
+       if (res != -1 && tv != NULL) {
+               struct timeval now;
+               int common_timeout;
+
+               /*
+                * for persistent timeout events, we remember the
+                * timeout value and re-add the event.
+                *
+                * If tv_is_absolute, this was already set.
+                */
+               if (ev->ev_closure == EV_CLOSURE_PERSIST && !tv_is_absolute)
+                       ev->ev_io_timeout = *tv;
+
+               /*
+                * we already reserved memory above for the case where we
+                * are not replacing an existing timeout.
+                */
+               if (ev->ev_flags & EVLIST_TIMEOUT) {
+                       /* XXX I believe this is needless. */
+                       if (min_heap_elt_is_top(ev))
+                               notify = 1;
+                       event_queue_remove(base, ev, EVLIST_TIMEOUT);
+               }
+
+               /* Check if it is active due to a timeout.  Rescheduling
+                * this timeout before the callback can be executed
+                * removes it from the active list. */
+               if ((ev->ev_flags & EVLIST_ACTIVE) &&
+                   (ev->ev_res & EV_TIMEOUT)) {
+                       if (ev->ev_events & EV_SIGNAL) {
+                               /* See if we are just active executing
+                                * this event in a loop
+                                */
+                               if (ev->ev_ncalls && ev->ev_pncalls) {
+                                       /* Abort loop */
+                                       *ev->ev_pncalls = 0;
+                               }
+                       }
+
+                       event_queue_remove(base, ev, EVLIST_ACTIVE);
+               }
+
+               gettime(base, &now);
+
+               common_timeout = is_common_timeout(tv, base);
+               if (tv_is_absolute) {
+                       ev->ev_timeout = *tv;
+               } else if (common_timeout) {
+                       struct timeval tmp = *tv;
+                       tmp.tv_usec &= MICROSECONDS_MASK;
+                       evutil_timeradd(&now, &tmp, &ev->ev_timeout);
+                       ev->ev_timeout.tv_usec |=
+                           (tv->tv_usec & ~MICROSECONDS_MASK);
+               } else {
+                       evutil_timeradd(&now, tv, &ev->ev_timeout);
+               }
+
+               event_debug((
+                        "event_add: timeout in %d seconds, call %p",
+                        (int)tv->tv_sec, ev->ev_callback));
+
+               event_queue_insert(base, ev, EVLIST_TIMEOUT);
+               if (common_timeout) {
+                       struct common_timeout_list *ctl =
+                           get_common_timeout_list(base, &ev->ev_timeout);
+                       if (ev == TAILQ_FIRST(&ctl->events)) {
+                               common_timeout_schedule(ctl, &now, ev);
+                       }
+               } else {
+                       /* See if the earliest timeout is now earlier than it
+                        * was before: if so, we will need to tell the main
+                        * thread to wake up earlier than it would
+                        * otherwise. */
+                       if (min_heap_elt_is_top(ev))
+                               notify = 1;
+               }
+       }
+
+       /* if we are not in the right thread, we need to wake up the loop */
+       if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
+               evthread_notify_base(base);
+
+       _event_debug_note_add(ev);
+
+       return (res);
+}
+
+int
+event_del(struct event *ev)
+{
+       int res;
+
+       if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
+               event_warnx("%s: event has no event_base set.", __func__);
+               return -1;
+       }
+
+       EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
+
+       res = event_del_internal(ev);
+
+       EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
+
+       return (res);
+}
+
+/* Helper for event_del: always called with th_base_lock held. */
+static inline int
+event_del_internal(struct event *ev)
+{
+       struct event_base *base;
+       int res = 0, notify = 0;
+
+       event_debug(("event_del: %p (fd %d), callback %p",
+               ev, (int)ev->ev_fd, ev->ev_callback));
+
+       /* An event without a base has not been added */
+       if (ev->ev_base == NULL)
+               return (-1);
+
+       EVENT_BASE_ASSERT_LOCKED(ev->ev_base);
+
+       /* If the main thread is currently executing this event's callback,
+        * and we are not the main thread, then we want to wait until the
+        * callback is done before we start removing the event.  That way,
+        * when this function returns, it will be safe to free the
+        * user-supplied argument. */
+       base = ev->ev_base;
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       if (base->current_event == ev && !EVBASE_IN_THREAD(base)) {
+               ++base->current_event_waiters;
+               EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
+       }
+#endif
+
+       EVUTIL_ASSERT(!(ev->ev_flags & ~EVLIST_ALL));
+
+       /* See if we are just active executing this event in a loop */
+       if (ev->ev_events & EV_SIGNAL) {
+               if (ev->ev_ncalls && ev->ev_pncalls) {
+                       /* Abort loop */
+                       *ev->ev_pncalls = 0;
+               }
+       }
+
+       if (ev->ev_flags & EVLIST_TIMEOUT) {
+               /* NOTE: We never need to notify the main thread because of a
+                * deleted timeout event: all that could happen if we don't is
+                * that the dispatch loop might wake up too early.  But the
+                * point of notifying the main thread _is_ to wake up the
+                * dispatch loop early anyway, so we wouldn't gain anything by
+                * doing it.
+                */
+               event_queue_remove(base, ev, EVLIST_TIMEOUT);
+       }
+
+       if (ev->ev_flags & EVLIST_ACTIVE)
+               event_queue_remove(base, ev, EVLIST_ACTIVE);
+
+       if (ev->ev_flags & EVLIST_INSERTED) {
+               event_queue_remove(base, ev, EVLIST_INSERTED);
+               if (ev->ev_events & (EV_READ|EV_WRITE))
+                       res = evmap_io_del(base, ev->ev_fd, ev);
+               else
+                       res = evmap_signal_del(base, (int)ev->ev_fd, ev);
+               if (res == 1) {
+                       /* evmap says we need to notify the main thread. */
+                       notify = 1;
+                       res = 0;
+               }
+       }
+
+       /* if we are not in the right thread, we need to wake up the loop */
+       if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
+               evthread_notify_base(base);
+
+       _event_debug_note_del(ev);
+
+       return (res);
+}
+
+void
+event_active(struct event *ev, int res, short ncalls)
+{
+       if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
+               event_warnx("%s: event has no event_base set.", __func__);
+               return;
+       }
+
+       EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
+
+       _event_debug_assert_is_setup(ev);
+
+       event_active_nolock(ev, res, ncalls);
+
+       EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
+}
+
+
+void
+event_active_nolock(struct event *ev, int res, short ncalls)
+{
+       struct event_base *base;
+
+       event_debug(("event_active: %p (fd %d), res %d, callback %p",
+               ev, (int)ev->ev_fd, (int)res, ev->ev_callback));
+
+
+       /* We get different kinds of events, add them together */
+       if (ev->ev_flags & EVLIST_ACTIVE) {
+               ev->ev_res |= res;
+               return;
+       }
+
+       base = ev->ev_base;
+
+       EVENT_BASE_ASSERT_LOCKED(base);
+
+       ev->ev_res = res;
+
+       if (ev->ev_events & EV_SIGNAL) {
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+               if (base->current_event == ev && !EVBASE_IN_THREAD(base)) {
+                       ++base->current_event_waiters;
+                       EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
+               }
+#endif
+               ev->ev_ncalls = ncalls;
+               ev->ev_pncalls = NULL;
+       }
+
+       event_queue_insert(base, ev, EVLIST_ACTIVE);
+
+       if (EVBASE_NEED_NOTIFY(base))
+               evthread_notify_base(base);
+}
+
+void
+event_deferred_cb_init(struct deferred_cb *cb, deferred_cb_fn fn, void *arg)
+{
+       memset(cb, 0, sizeof(struct deferred_cb));
+       cb->cb = fn;
+       cb->arg = arg;
+}
+
+void
+event_deferred_cb_cancel(struct deferred_cb_queue *queue,
+    struct deferred_cb *cb)
+{
+       if (!queue) {
+               if (current_base)
+                       queue = &current_base->defer_queue;
+               else
+                       return;
+       }
+
+       LOCK_DEFERRED_QUEUE(queue);
+       if (cb->queued) {
+               TAILQ_REMOVE(&queue->deferred_cb_list, cb, cb_next);
+               --queue->active_count;
+               cb->queued = 0;
+       }
+       UNLOCK_DEFERRED_QUEUE(queue);
+}
+
+void
+event_deferred_cb_schedule(struct deferred_cb_queue *queue,
+    struct deferred_cb *cb)
+{
+       if (!queue) {
+               if (current_base)
+                       queue = &current_base->defer_queue;
+               else
+                       return;
+       }
+
+       LOCK_DEFERRED_QUEUE(queue);
+       if (!cb->queued) {
+               cb->queued = 1;
+               TAILQ_INSERT_TAIL(&queue->deferred_cb_list, cb, cb_next);
+               ++queue->active_count;
+               if (queue->notify_fn)
+                       queue->notify_fn(queue, queue->notify_arg);
+       }
+       UNLOCK_DEFERRED_QUEUE(queue);
+}
+
+static int
+timeout_next(struct event_base *base, struct timeval **tv_p)
+{
+       /* Caller must hold th_base_lock */
+       struct timeval now;
+       struct event *ev;
+       struct timeval *tv = *tv_p;
+       int res = 0;
+
+       ev = min_heap_top(&base->timeheap);
+
+       if (ev == NULL) {
+               /* if no time-based events are active wait for I/O */
+               *tv_p = NULL;
+               goto out;
+       }
+
+       if (gettime(base, &now) == -1) {
+               res = -1;
+               goto out;
+       }
+
+       if (evutil_timercmp(&ev->ev_timeout, &now, <=)) {
+               evutil_timerclear(tv);
+               goto out;
+       }
+
+       evutil_timersub(&ev->ev_timeout, &now, tv);
+
+       EVUTIL_ASSERT(tv->tv_sec >= 0);
+       EVUTIL_ASSERT(tv->tv_usec >= 0);
+       event_debug(("timeout_next: in %d seconds", (int)tv->tv_sec));
+
+out:
+       return (res);
+}
+
+/*
+ * Determines if the time is running backwards by comparing the current time
+ * against the last time we checked.  Not needed when using clock monotonic.
+ * If time is running backwards, we adjust the firing time of every event by
+ * the amount that time seems to have jumped.
+ */
+static void
+timeout_correct(struct event_base *base, struct timeval *tv)
+{
+       /* Caller must hold th_base_lock. */
+       struct event **pev;
+       unsigned int size;
+       struct timeval off;
+       int i;
+
+       if (use_monotonic)
+               return;
+
+       /* Check if time is running backwards */
+       gettime(base, tv);
+
+       if (evutil_timercmp(tv, &base->event_tv, >=)) {
+               base->event_tv = *tv;
+               return;
+       }
+
+       event_debug(("%s: time is running backwards, corrected",
+                   __func__));
+       evutil_timersub(&base->event_tv, tv, &off);
+
+       /*
+        * We can modify the key element of the node without destroying
+        * the minheap property, because we change every element.
+        */
+       pev = base->timeheap.p;
+       size = base->timeheap.n;
+       for (; size-- > 0; ++pev) {
+               struct timeval *ev_tv = &(**pev).ev_timeout;
+               evutil_timersub(ev_tv, &off, ev_tv);
+       }
+       for (i=0; i<base->n_common_timeouts; ++i) {
+               struct event *ev;
+               struct common_timeout_list *ctl =
+                   base->common_timeout_queues[i];
+               TAILQ_FOREACH(ev, &ctl->events,
+                   ev_timeout_pos.ev_next_with_common_timeout) {
+                       struct timeval *ev_tv = &ev->ev_timeout;
+                       ev_tv->tv_usec &= MICROSECONDS_MASK;
+                       evutil_timersub(ev_tv, &off, ev_tv);
+                       ev_tv->tv_usec |= COMMON_TIMEOUT_MAGIC |
+                           (i<<COMMON_TIMEOUT_IDX_SHIFT);
+               }
+       }
+
+       /* Now remember what the new time turned out to be. */
+       base->event_tv = *tv;
+}
+
+/* Activate every event whose timeout has elapsed. */
+static void
+timeout_process(struct event_base *base)
+{
+       /* Caller must hold lock. */
+       struct timeval now;
+       struct event *ev;
+
+       if (min_heap_empty(&base->timeheap)) {
+               return;
+       }
+
+       gettime(base, &now);
+
+       while ((ev = min_heap_top(&base->timeheap))) {
+               if (evutil_timercmp(&ev->ev_timeout, &now, >))
+                       break;
+
+               /* delete this event from the I/O queues */
+               event_del_internal(ev);
+
+               event_debug(("timeout_process: call %p",
+                        ev->ev_callback));
+               event_active_nolock(ev, EV_TIMEOUT, 1);
+       }
+}
+
+/* Remove 'ev' from 'queue' (EVLIST_...) in base. */
+static void
+event_queue_remove(struct event_base *base, struct event *ev, int queue)
+{
+       EVENT_BASE_ASSERT_LOCKED(base);
+
+       if (!(ev->ev_flags & queue)) {
+               event_errx(1, "%s: %p(fd %d) not on queue %x", __func__,
+                          ev, ev->ev_fd, queue);
+               return;
+       }
+
+       if (~ev->ev_flags & EVLIST_INTERNAL)
+               base->event_count--;
+
+       ev->ev_flags &= ~queue;
+       switch (queue) {
+       case EVLIST_INSERTED:
+               TAILQ_REMOVE(&base->eventqueue, ev, ev_next);
+               break;
+       case EVLIST_ACTIVE:
+               base->event_count_active--;
+               TAILQ_REMOVE(&base->activequeues[ev->ev_pri],
+                   ev, ev_active_next);
+               break;
+       case EVLIST_TIMEOUT:
+               if (is_common_timeout(&ev->ev_timeout, base)) {
+                       struct common_timeout_list *ctl =
+                           get_common_timeout_list(base, &ev->ev_timeout);
+                       TAILQ_REMOVE(&ctl->events, ev,
+                           ev_timeout_pos.ev_next_with_common_timeout);
+               } else {
+                       min_heap_erase(&base->timeheap, ev);
+               }
+               break;
+       default:
+               event_errx(1, "%s: unknown queue %x", __func__, queue);
+       }
+}
+
+/* Add 'ev' to the common timeout list in 'ev'. */
+static void
+insert_common_timeout_inorder(struct common_timeout_list *ctl,
+    struct event *ev)
+{
+       struct event *e;
+       /* By all logic, we should just be able to append 'ev' to the end of
+        * ctl->events, since the timeout on each 'ev' is set to {the common
+        * timeout} + {the time when we add the event}, and so the events
+        * should arrive in order of their timeeouts.  But just in case
+        * there's some wacky threading issue going on, we do a search from
+        * the end of 'ev' to find the right insertion point.
+        */
+       TAILQ_FOREACH_REVERSE(e, &ctl->events,
+           event_list, ev_timeout_pos.ev_next_with_common_timeout) {
+               /* This timercmp is a little sneaky, since both ev and e have
+                * magic values in tv_usec.  Fortunately, they ought to have
+                * the _same_ magic values in tv_usec.  Let's assert for that.
+                */
+               EVUTIL_ASSERT(
+                       is_same_common_timeout(&e->ev_timeout, &ev->ev_timeout));
+               if (evutil_timercmp(&ev->ev_timeout, &e->ev_timeout, >=)) {
+                       TAILQ_INSERT_AFTER(&ctl->events, e, ev,
+                           ev_timeout_pos.ev_next_with_common_timeout);
+                       return;
+               }
+       }
+       TAILQ_INSERT_HEAD(&ctl->events, ev,
+           ev_timeout_pos.ev_next_with_common_timeout);
+}
+
+static void
+event_queue_insert(struct event_base *base, struct event *ev, int queue)
+{
+       EVENT_BASE_ASSERT_LOCKED(base);
+
+       if (ev->ev_flags & queue) {
+               /* Double insertion is possible for active events */
+               if (queue & EVLIST_ACTIVE)
+                       return;
+
+               event_errx(1, "%s: %p(fd %d) already on queue %x", __func__,
+                          ev, ev->ev_fd, queue);
+               return;
+       }
+
+       if (~ev->ev_flags & EVLIST_INTERNAL)
+               base->event_count++;
+
+       ev->ev_flags |= queue;
+       switch (queue) {
+       case EVLIST_INSERTED:
+               TAILQ_INSERT_TAIL(&base->eventqueue, ev, ev_next);
+               break;
+       case EVLIST_ACTIVE:
+               base->event_count_active++;
+               TAILQ_INSERT_TAIL(&base->activequeues[ev->ev_pri],
+                   ev,ev_active_next);
+               break;
+       case EVLIST_TIMEOUT: {
+               if (is_common_timeout(&ev->ev_timeout, base)) {
+                       struct common_timeout_list *ctl =
+                           get_common_timeout_list(base, &ev->ev_timeout);
+                       insert_common_timeout_inorder(ctl, ev);
+               } else
+                       min_heap_push(&base->timeheap, ev);
+               break;
+       }
+       default:
+               event_errx(1, "%s: unknown queue %x", __func__, queue);
+       }
+}
+
+/* Functions for debugging */
+
+const char *
+event_get_version(void)
+{
+       return (_EVENT_VERSION);
+}
+
+ev_uint32_t
+event_get_version_number(void)
+{
+       return (_EVENT_NUMERIC_VERSION);
+}
+
+/*
+ * No thread-safe interface needed - the information should be the same
+ * for all threads.
+ */
+
+const char *
+event_get_method(void)
+{
+       return (current_base->evsel->name);
+}
+
+#ifndef _EVENT_DISABLE_MM_REPLACEMENT
+static void *(*_mm_malloc_fn)(size_t sz) = NULL;
+static void *(*_mm_realloc_fn)(void *p, size_t sz) = NULL;
+static void (*_mm_free_fn)(void *p) = NULL;
+
+void *
+event_mm_malloc_(size_t sz)
+{
+       if (_mm_malloc_fn)
+               return _mm_malloc_fn(sz);
+       else
+               return malloc(sz);
+}
+
+void *
+event_mm_calloc_(size_t count, size_t size)
+{
+       if (_mm_malloc_fn) {
+               size_t sz = count * size;
+               void *p = _mm_malloc_fn(sz);
+               if (p)
+                       memset(p, 0, sz);
+               return p;
+       } else
+               return calloc(count, size);
+}
+
+char *
+event_mm_strdup_(const char *str)
+{
+       if (_mm_malloc_fn) {
+               size_t ln = strlen(str);
+               void *p = _mm_malloc_fn(ln+1);
+               if (p)
+                       memcpy(p, str, ln+1);
+               return p;
+       } else
+#ifdef WIN32
+               return _strdup(str);
+#else
+               return strdup(str);
+#endif
+}
+
+void *
+event_mm_realloc_(void *ptr, size_t sz)
+{
+       if (_mm_realloc_fn)
+               return _mm_realloc_fn(ptr, sz);
+       else
+               return realloc(ptr, sz);
+}
+
+void
+event_mm_free_(void *ptr)
+{
+       if (_mm_free_fn)
+               _mm_free_fn(ptr);
+       else
+               free(ptr);
+}
+
+void
+event_set_mem_functions(void *(*malloc_fn)(size_t sz),
+                       void *(*realloc_fn)(void *ptr, size_t sz),
+                       void (*free_fn)(void *ptr))
+{
+       _mm_malloc_fn = malloc_fn;
+       _mm_realloc_fn = realloc_fn;
+       _mm_free_fn = free_fn;
+}
+#endif
+
+#if defined(_EVENT_HAVE_EVENTFD) && defined(_EVENT_HAVE_SYS_EVENTFD_H)
+static void
+evthread_notify_drain_eventfd(evutil_socket_t fd, short what, void *arg)
+{
+       ev_uint64_t msg;
+       ev_ssize_t r;
+       struct event_base *base = arg;
+
+       r = read(fd, (void*) &msg, sizeof(msg));
+       if (r<0 && errno != EAGAIN) {
+               event_sock_warn(fd, "Error reading from eventfd");
+       }
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       base->is_notify_pending = 0;
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+#endif
+
+static void
+evthread_notify_drain_default(evutil_socket_t fd, short what, void *arg)
+{
+       unsigned char buf[1024];
+       struct event_base *base = arg;
+#ifdef WIN32
+       while (recv(fd, (char*)buf, sizeof(buf), 0) > 0)
+               ;
+#else
+       while (read(fd, (char*)buf, sizeof(buf)) > 0)
+               ;
+#endif
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       base->is_notify_pending = 0;
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+int
+evthread_make_base_notifiable(struct event_base *base)
+{
+       void (*cb)(evutil_socket_t, short, void *) = evthread_notify_drain_default;
+       int (*notify)(struct event_base *) = evthread_notify_base_default;
+
+       /* XXXX grab the lock here? */
+       if (!base)
+               return -1;
+
+       if (base->th_notify_fd[0] >= 0)
+               return 0;
+
+#if defined(_EVENT_HAVE_EVENTFD) && defined(_EVENT_HAVE_SYS_EVENTFD_H)
+#ifndef EFD_CLOEXEC
+#define EFD_CLOEXEC 0
+#endif
+       base->th_notify_fd[0] = eventfd(0, EFD_CLOEXEC);
+       if (base->th_notify_fd[0] >= 0) {
+               evutil_make_socket_closeonexec(base->th_notify_fd[0]);
+               notify = evthread_notify_base_eventfd;
+               cb = evthread_notify_drain_eventfd;
+       }
+#endif
+#if defined(_EVENT_HAVE_PIPE)
+       if (base->th_notify_fd[0] < 0) {
+               if ((base->evsel->features & EV_FEATURE_FDS)) {
+                       if (pipe(base->th_notify_fd) < 0) {
+                               event_warn("%s: pipe", __func__);
+                       } else {
+                               evutil_make_socket_closeonexec(base->th_notify_fd[0]);
+                               evutil_make_socket_closeonexec(base->th_notify_fd[1]);
+                       }
+               }
+       }
+#endif
+
+#ifdef WIN32
+#define LOCAL_SOCKETPAIR_AF AF_INET
+#else
+#define LOCAL_SOCKETPAIR_AF AF_UNIX
+#endif
+       if (base->th_notify_fd[0] < 0) {
+               if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0,
+                       base->th_notify_fd) == -1) {
+                       event_sock_warn(-1, "%s: socketpair", __func__);
+                       return (-1);
+               } else {
+                       evutil_make_socket_closeonexec(base->th_notify_fd[0]);
+                       evutil_make_socket_closeonexec(base->th_notify_fd[1]);
+               }
+       }
+
+       evutil_make_socket_nonblocking(base->th_notify_fd[0]);
+
+       base->th_notify_fn = notify;
+
+       /*
+         Making the second socket nonblocking is a bit subtle, given that we
+         ignore any EAGAIN returns when writing to it, and you don't usally
+         do that for a nonblocking socket. But if the kernel gives us EAGAIN,
+         then there's no need to add any more data to the buffer, since
+         the main thread is already either about to wake up and drain it,
+         or woken up and in the process of draining it.
+       */
+       if (base->th_notify_fd[1] > 0)
+               evutil_make_socket_nonblocking(base->th_notify_fd[1]);
+
+       /* prepare an event that we can use for wakeup */
+       event_assign(&base->th_notify, base, base->th_notify_fd[0],
+                                EV_READ|EV_PERSIST, cb, base);
+
+       /* we need to mark this as internal event */
+       base->th_notify.ev_flags |= EVLIST_INTERNAL;
+       event_priority_set(&base->th_notify, 0);
+
+       return event_add(&base->th_notify, NULL);
+}
+
+void
+event_base_dump_events(struct event_base *base, FILE *output)
+{
+       struct event *e;
+       int i;
+       fprintf(output, "Inserted events:\n");
+       TAILQ_FOREACH(e, &base->eventqueue, ev_next) {
+               fprintf(output, "  %p [fd %ld]%s%s%s%s%s\n",
+                               (void*)e, (long)e->ev_fd,
+                               (e->ev_events&EV_READ)?" Read":"",
+                               (e->ev_events&EV_WRITE)?" Write":"",
+                               (e->ev_events&EV_SIGNAL)?" Signal":"",
+                               (e->ev_events&EV_TIMEOUT)?" Timeout":"",
+                               (e->ev_events&EV_PERSIST)?" Persist":"");
+
+       }
+       for (i = 0; i < base->nactivequeues; ++i) {
+               if (TAILQ_EMPTY(&base->activequeues[i]))
+                       continue;
+               fprintf(output, "Active events [priority %d]:\n", i);
+               TAILQ_FOREACH(e, &base->eventqueue, ev_next) {
+                       fprintf(output, "  %p [fd %ld]%s%s%s%s\n",
+                                       (void*)e, (long)e->ev_fd,
+                                       (e->ev_res&EV_READ)?" Read active":"",
+                                       (e->ev_res&EV_WRITE)?" Write active":"",
+                                       (e->ev_res&EV_SIGNAL)?" Signal active":"",
+                                       (e->ev_res&EV_TIMEOUT)?" Timeout active":"");
+               }
+       }
+}
+
+void
+event_base_add_virtual(struct event_base *base)
+{
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       base->virtual_event_count++;
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+void
+event_base_del_virtual(struct event_base *base)
+{
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       EVUTIL_ASSERT(base->virtual_event_count > 0);
+       base->virtual_event_count--;
+       if (base->virtual_event_count == 0 && EVBASE_NEED_NOTIFY(base))
+               evthread_notify_base(base);
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+int
+event_global_setup_locks_(const int enable_locks)
+{
+#ifndef _EVENT_DISABLE_DEBUG_MODE
+       EVTHREAD_SETUP_GLOBAL_LOCK(_event_debug_map_lock, 0);
+#endif
+       if (evsig_global_setup_locks_(enable_locks) < 0)
+               return -1;
+       if (evutil_secure_rng_global_setup_locks_(enable_locks) < 0)
+               return -1;
+       return 0;
+}
+#endif
+
+void
+event_base_assert_ok(struct event_base *base)
+{
+       int i;
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       evmap_check_integrity(base);
+
+       /* Check the heap property */
+       for (i = 1; i < (int)base->timeheap.n; ++i) {
+               int parent = (i - 1) / 2;
+               struct event *ev, *p_ev;
+               ev = base->timeheap.p[i];
+               p_ev = base->timeheap.p[parent];
+               EVUTIL_ASSERT(ev->ev_flags & EV_TIMEOUT);
+               EVUTIL_ASSERT(evutil_timercmp(&p_ev->ev_timeout, &ev->ev_timeout, <=));
+               EVUTIL_ASSERT(ev->ev_timeout_pos.min_heap_idx == i);
+       }
+
+       /* Check that the common timeouts are fine */
+       for (i = 0; i < base->n_common_timeouts; ++i) {
+               struct common_timeout_list *ctl = base->common_timeout_queues[i];
+               struct event *last=NULL, *ev;
+               TAILQ_FOREACH(ev, &ctl->events, ev_timeout_pos.ev_next_with_common_timeout) {
+                       if (last)
+                               EVUTIL_ASSERT(evutil_timercmp(&last->ev_timeout, &ev->ev_timeout, <=));
+                       EVUTIL_ASSERT(ev->ev_flags & EV_TIMEOUT);
+                       EVUTIL_ASSERT(is_common_timeout(&ev->ev_timeout,base));
+                       EVUTIL_ASSERT(COMMON_TIMEOUT_IDX(&ev->ev_timeout) == i);
+                       last = ev;
+               }
+       }
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
diff --git a/libevent/event.h b/libevent/event.h
new file mode 100644 (file)
index 0000000..a3785b9
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT_H_
+#define _EVENT_H_
+
+/** @file event.h
+
+  A library for writing event-driven network servers.
+
+  The <event.h> header is deprecated in Libevent 2.0 and later; please
+  use <event2/event.h> instead.  Depending on what functionality you
+  need, you may also want to include more of the other event2/
+  headers.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _EVENT_HAVE_STDINT_H
+#include <stdint.h>
+#endif
+#include <stdarg.h>
+
+/* For int types. */
+#include <evutil.h>
+
+#ifdef WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include <winsock2.h>
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+typedef unsigned char u_char;
+typedef unsigned short u_short;
+#endif
+
+#include <event2/event_struct.h>
+#include <event2/event.h>
+#include <event2/event_compat.h>
+#include <event2/buffer.h>
+#include <event2/buffer_compat.h>
+#include <event2/bufferevent.h>
+#include <event2/bufferevent_struct.h>
+#include <event2/bufferevent_compat.h>
+#include <event2/tag.h>
+#include <event2/tag_compat.h>
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT_H_ */
diff --git a/libevent/event_iocp.c b/libevent/event_iocp.c
new file mode 100644 (file)
index 0000000..4321281
--- /dev/null
@@ -0,0 +1,290 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _WIN32_WINNT
+/* Minimum required for InitializeCriticalSectionAndSpinCount */
+#define _WIN32_WINNT 0x0403
+#endif
+#include <winsock2.h>
+#include <windows.h>
+#include <process.h>
+#include <stdio.h>
+#include <mswsock.h>
+
+#include "event2/util.h"
+#include "util-internal.h"
+#include "iocp-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "event-internal.h"
+#include "evthread-internal.h"
+
+#define NOTIFICATION_KEY ((ULONG_PTR)-1)
+
+void
+event_overlapped_init(struct event_overlapped *o, iocp_callback cb)
+{
+       memset(o, 0, sizeof(struct event_overlapped));
+       o->cb = cb;
+}
+
+static void
+handle_entry(OVERLAPPED *o, ULONG_PTR completion_key, DWORD nBytes, int ok)
+{
+       struct event_overlapped *eo =
+           EVUTIL_UPCAST(o, struct event_overlapped, overlapped);
+       eo->cb(eo, completion_key, nBytes, ok);
+}
+
+static void
+loop(void *_port)
+{
+       struct event_iocp_port *port = _port;
+       long ms = port->ms;
+       HANDLE p = port->port;
+
+       if (ms <= 0)
+               ms = INFINITE;
+
+       while (1) {
+               OVERLAPPED *overlapped=NULL;
+               ULONG_PTR key=0;
+               DWORD bytes=0;
+               int ok = GetQueuedCompletionStatus(p, &bytes, &key,
+                       &overlapped, ms);
+               EnterCriticalSection(&port->lock);
+               if (port->shutdown) {
+                       if (--port->n_live_threads == 0)
+                               ReleaseSemaphore(port->shutdownSemaphore, 1,
+                                               NULL);
+                       LeaveCriticalSection(&port->lock);
+                       return;
+               }
+               LeaveCriticalSection(&port->lock);
+
+               if (key != NOTIFICATION_KEY && overlapped)
+                       handle_entry(overlapped, key, bytes, ok);
+               else if (!overlapped)
+                       break;
+       }
+       event_warnx("GetQueuedCompletionStatus exited with no event.");
+       EnterCriticalSection(&port->lock);
+       if (--port->n_live_threads == 0)
+               ReleaseSemaphore(port->shutdownSemaphore, 1, NULL);
+       LeaveCriticalSection(&port->lock);
+}
+
+int
+event_iocp_port_associate(struct event_iocp_port *port, evutil_socket_t fd,
+    ev_uintptr_t key)
+{
+       HANDLE h;
+       h = CreateIoCompletionPort((HANDLE)fd, port->port, key, port->n_threads);
+       if (!h)
+               return -1;
+       return 0;
+}
+
+static void *
+get_extension_function(SOCKET s, const GUID *which_fn)
+{
+       void *ptr = NULL;
+       DWORD bytes=0;
+       WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER,
+           (GUID*)which_fn, sizeof(*which_fn),
+           &ptr, sizeof(ptr),
+           &bytes, NULL, NULL);
+
+       /* No need to detect errors here: if ptr is set, then we have a good
+          function pointer.  Otherwise, we should behave as if we had no
+          function pointer.
+       */
+       return ptr;
+}
+
+/* Mingw doesn't have these in its mswsock.h.  The values are copied from
+   wine.h.   Perhaps if we copy them exactly, the cargo will come again.
+*/
+#ifndef WSAID_ACCEPTEX
+#define WSAID_ACCEPTEX \
+       {0xb5367df1,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
+#endif
+#ifndef WSAID_CONNECTEX
+#define WSAID_CONNECTEX \
+       {0x25a207b9,0xddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}
+#endif
+#ifndef WSAID_GETACCEPTEXSOCKADDRS
+#define WSAID_GETACCEPTEXSOCKADDRS \
+       {0xb5367df2,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
+#endif
+
+static void
+init_extension_functions(struct win32_extension_fns *ext)
+{
+       const GUID acceptex = WSAID_ACCEPTEX;
+       const GUID connectex = WSAID_CONNECTEX;
+       const GUID getacceptexsockaddrs = WSAID_GETACCEPTEXSOCKADDRS;
+       SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
+       if (s == INVALID_SOCKET)
+               return;
+       ext->AcceptEx = get_extension_function(s, &acceptex);
+       ext->ConnectEx = get_extension_function(s, &connectex);
+       ext->GetAcceptExSockaddrs = get_extension_function(s,
+           &getacceptexsockaddrs);
+       closesocket(s);
+}
+
+static struct win32_extension_fns the_extension_fns;
+static int extension_fns_initialized = 0;
+
+const struct win32_extension_fns *
+event_get_win32_extension_fns(void)
+{
+       return &the_extension_fns;
+}
+
+#define N_CPUS_DEFAULT 2
+
+struct event_iocp_port *
+event_iocp_port_launch(int n_cpus)
+{
+       struct event_iocp_port *port;
+       int i;
+
+       if (!extension_fns_initialized)
+               init_extension_functions(&the_extension_fns);
+
+       if (!(port = mm_calloc(1, sizeof(struct event_iocp_port))))
+               return NULL;
+
+       if (n_cpus <= 0)
+               n_cpus = N_CPUS_DEFAULT;
+       port->n_threads = n_cpus * 2;
+       port->threads = mm_calloc(port->n_threads, sizeof(HANDLE));
+       if (!port->threads)
+               goto err;
+
+       port->port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0,
+                       n_cpus);
+       port->ms = -1;
+       if (!port->port)
+               goto err;
+
+       port->shutdownSemaphore = CreateSemaphore(NULL, 0, 1, NULL);
+       if (!port->shutdownSemaphore)
+               goto err;
+
+       for (i=0; i<port->n_threads; ++i) {
+               ev_uintptr_t th = _beginthread(loop, 0, port);
+               if (th == (ev_uintptr_t)-1)
+                       goto err;
+               port->threads[i] = (HANDLE)th;
+               ++port->n_live_threads;
+       }
+
+       InitializeCriticalSectionAndSpinCount(&port->lock, 1000);
+
+       return port;
+err:
+       if (port->port)
+               CloseHandle(port->port);
+       if (port->threads)
+               mm_free(port->threads);
+       if (port->shutdownSemaphore)
+               CloseHandle(port->shutdownSemaphore);
+       mm_free(port);
+       return NULL;
+}
+
+static void
+_event_iocp_port_unlock_and_free(struct event_iocp_port *port)
+{
+       DeleteCriticalSection(&port->lock);
+       CloseHandle(port->port);
+       CloseHandle(port->shutdownSemaphore);
+       mm_free(port->threads);
+       mm_free(port);
+}
+
+static int
+event_iocp_notify_all(struct event_iocp_port *port)
+{
+       int i, r, ok=1;
+       for (i=0; i<port->n_threads; ++i) {
+               r = PostQueuedCompletionStatus(port->port, 0, NOTIFICATION_KEY,
+                   NULL);
+               if (!r)
+                       ok = 0;
+       }
+       return ok ? 0 : -1;
+}
+
+int
+event_iocp_shutdown(struct event_iocp_port *port, long waitMsec)
+{
+       DWORD ms = INFINITE;
+       int n;
+
+       EnterCriticalSection(&port->lock);
+       port->shutdown = 1;
+       LeaveCriticalSection(&port->lock);
+       event_iocp_notify_all(port);
+
+       if (waitMsec >= 0)
+               ms = waitMsec;
+
+       WaitForSingleObject(port->shutdownSemaphore, ms);
+       EnterCriticalSection(&port->lock);
+       n = port->n_live_threads;
+       LeaveCriticalSection(&port->lock);
+       if (n == 0) {
+               _event_iocp_port_unlock_and_free(port);
+               return 0;
+       } else {
+               return -1;
+       }
+}
+
+int
+event_iocp_activate_overlapped(
+    struct event_iocp_port *port, struct event_overlapped *o,
+    ev_uintptr_t key, ev_uint32_t n)
+{
+       BOOL r;
+
+       r = PostQueuedCompletionStatus(port->port, n, key, &o->overlapped);
+       return (r==0) ? -1 : 0;
+}
+
+struct event_iocp_port *
+event_base_get_iocp(struct event_base *base)
+{
+#ifdef WIN32
+       return base->iocp;
+#else
+       return NULL;
+#endif
+}
diff --git a/libevent/event_rpcgen.py b/libevent/event_rpcgen.py
new file mode 100755 (executable)
index 0000000..e051aa9
--- /dev/null
@@ -0,0 +1,1717 @@
+#!/usr/bin/env python
+#
+# Copyright (c) 2005-2007 Niels Provos <provos@citi.umich.edu>
+# Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+# All rights reserved.
+#
+# Generates marshaling code based on libevent.
+
+# TODO:
+# 1) use optparse to allow the strategy shell to parse options, and
+#    to allow the instantiated factory (for the specific output language)
+#    to parse remaining options
+# 2) move the globals into a class that manages execution (including the
+#    progress outputs that space stderr at the moment)
+# 3) emit other languages
+
+import sys
+import re
+
+_NAME = "event_rpcgen.py"
+_VERSION = "0.1"
+
+# Globals
+line_count = 0
+
+white = re.compile(r'\s+')
+cppcomment = re.compile(r'\/\/.*$')
+nonident = re.compile(r'[^a-zA-Z0-9_]')
+structref = re.compile(r'^struct\[([a-zA-Z_][a-zA-Z0-9_]*)\]$')
+structdef = re.compile(r'^struct +[a-zA-Z_][a-zA-Z0-9_]* *{$')
+
+headerdirect = []
+cppdirect = []
+
+def TranslateList(mylist, mydict):
+    return map(lambda x: x % mydict, mylist)
+
+# Exception class for parse errors
+class RpcGenError(Exception):
+        def __init__(self, why):
+                self.why = why
+        def __str__(self):
+                return str(self.why)
+
+# Holds everything that makes a struct
+class Struct:
+    def __init__(self, name):
+        self._name = name
+        self._entries = []
+        self._tags = {}
+        print >>sys.stderr, '  Created struct: %s' % name
+
+    def AddEntry(self, entry):
+        if self._tags.has_key(entry.Tag()):
+            raise RpcGenError(
+                'Entry "%s" duplicates tag number %d from "%s" '
+                'around line %d' % (entry.Name(), entry.Tag(),
+                                    self._tags[entry.Tag()], line_count))
+        self._entries.append(entry)
+        self._tags[entry.Tag()] = entry.Name()
+        print >>sys.stderr, '    Added entry: %s' % entry.Name()
+
+    def Name(self):
+        return self._name
+
+    def EntryTagName(self, entry):
+        """Creates the name inside an enumeration for distinguishing data
+        types."""
+        name = "%s_%s" % (self._name, entry.Name())
+        return name.upper()
+
+    def PrintIndented(self, file, ident, code):
+        """Takes an array, add indentation to each entry and prints it."""
+        for entry in code:
+            print >>file, '%s%s' % (ident, entry)
+
+class StructCCode(Struct):
+    """ Knows how to generate C code for a struct """
+
+    def __init__(self, name):
+        Struct.__init__(self, name)
+
+    def PrintTags(self, file):
+        """Prints the tag definitions for a structure."""
+        print >>file, '/* Tag definition for %s */' % self._name
+        print >>file, 'enum %s_ {' % self._name.lower()
+        for entry in self._entries:
+            print >>file, '  %s=%d,' % (self.EntryTagName(entry),
+                                        entry.Tag())
+        print >>file, '  %s_MAX_TAGS' % (self._name.upper())
+        print >>file, '};\n'
+
+    def PrintForwardDeclaration(self, file):
+        print >>file, 'struct %s;' % self._name
+
+    def PrintDeclaration(self, file):
+        print >>file, '/* Structure declaration for %s */' % self._name
+        print >>file, 'struct %s_access_ {' % self._name
+        for entry in self._entries:
+            dcl = entry.AssignDeclaration('(*%s_assign)' % entry.Name())
+            dcl.extend(
+                entry.GetDeclaration('(*%s_get)' % entry.Name()))
+            if entry.Array():
+                dcl.extend(
+                    entry.AddDeclaration('(*%s_add)' % entry.Name()))
+            self.PrintIndented(file, '  ', dcl)
+        print >>file, '};\n'
+
+        print >>file, 'struct %s {' % self._name
+        print >>file, '  struct %s_access_ *base;\n' % self._name
+        for entry in self._entries:
+            dcl = entry.Declaration()
+            self.PrintIndented(file, '  ', dcl)
+        print >>file, ''
+        for entry in self._entries:
+            print >>file, '  ev_uint8_t %s_set;' % entry.Name()
+        print >>file, '};\n'
+
+        print >>file, \
+"""struct %(name)s *%(name)s_new(void);
+struct %(name)s *%(name)s_new_with_arg(void *);
+void %(name)s_free(struct %(name)s *);
+void %(name)s_clear(struct %(name)s *);
+void %(name)s_marshal(struct evbuffer *, const struct %(name)s *);
+int %(name)s_unmarshal(struct %(name)s *, struct evbuffer *);
+int %(name)s_complete(struct %(name)s *);
+void evtag_marshal_%(name)s(struct evbuffer *, ev_uint32_t,
+    const struct %(name)s *);
+int evtag_unmarshal_%(name)s(struct evbuffer *, ev_uint32_t,
+    struct %(name)s *);""" % { 'name' : self._name }
+
+
+        # Write a setting function of every variable
+        for entry in self._entries:
+            self.PrintIndented(file, '', entry.AssignDeclaration(
+                entry.AssignFuncName()))
+            self.PrintIndented(file, '', entry.GetDeclaration(
+                entry.GetFuncName()))
+            if entry.Array():
+                self.PrintIndented(file, '', entry.AddDeclaration(
+                    entry.AddFuncName()))
+
+        print >>file, '/* --- %s done --- */\n' % self._name
+
+    def PrintCode(self, file):
+        print >>file, ('/*\n'
+                       ' * Implementation of %s\n'
+                       ' */\n') % self._name
+
+        print >>file, \
+              'static struct %(name)s_access_ __%(name)s_base = {' % \
+              { 'name' : self._name }
+        for entry in self._entries:
+            self.PrintIndented(file, '  ', entry.CodeBase())
+        print >>file, '};\n'
+
+        # Creation
+        print >>file, (
+            'struct %(name)s *\n'
+            '%(name)s_new(void)\n'
+            '{\n'
+            '  return %(name)s_new_with_arg(NULL);\n'
+            '}\n'
+            '\n'
+            'struct %(name)s *\n'
+            '%(name)s_new_with_arg(void *unused)\n'
+            '{\n'
+            '  struct %(name)s *tmp;\n'
+            '  if ((tmp = malloc(sizeof(struct %(name)s))) == NULL) {\n'
+            '    event_warn("%%s: malloc", __func__);\n'
+            '    return (NULL);\n'
+            '  }\n'
+            '  tmp->base = &__%(name)s_base;\n') % { 'name' : self._name }
+
+        for entry in self._entries:
+            self.PrintIndented(file, '  ', entry.CodeInitialize('tmp'))
+            print >>file, '  tmp->%s_set = 0;\n' % entry.Name()
+
+        print >>file, (
+            '  return (tmp);\n'
+            '}\n')
+
+        # Adding
+        for entry in self._entries:
+            if entry.Array():
+                self.PrintIndented(file, '', entry.CodeAdd())
+            print >>file, ''
+
+        # Assigning
+        for entry in self._entries:
+            self.PrintIndented(file, '', entry.CodeAssign())
+            print >>file, ''
+
+        # Getting
+        for entry in self._entries:
+            self.PrintIndented(file, '', entry.CodeGet())
+            print >>file, ''
+
+        # Clearing
+        print >>file, ( 'void\n'
+                        '%(name)s_clear(struct %(name)s *tmp)\n'
+                        '{'
+                        ) % { 'name' : self._name }
+        for entry in self._entries:
+            self.PrintIndented(file, '  ', entry.CodeClear('tmp'))
+
+        print >>file, '}\n'
+
+        # Freeing
+        print >>file, ( 'void\n'
+                        '%(name)s_free(struct %(name)s *tmp)\n'
+                        '{'
+                        ) % { 'name' : self._name }
+
+        for entry in self._entries:
+            self.PrintIndented(file, '  ', entry.CodeFree('tmp'))
+
+        print >>file, ('  free(tmp);\n'
+                       '}\n')
+
+        # Marshaling
+        print >>file, ('void\n'
+                       '%(name)s_marshal(struct evbuffer *evbuf, '
+                       'const struct %(name)s *tmp)'
+                       '{') % { 'name' : self._name }
+        for entry in self._entries:
+            indent = '  '
+            # Optional entries do not have to be set
+            if entry.Optional():
+                indent += '  '
+                print >>file, '  if (tmp->%s_set) {' % entry.Name()
+            self.PrintIndented(
+                file, indent,
+                entry.CodeMarshal('evbuf', self.EntryTagName(entry),
+                                  entry.GetVarName('tmp'),
+                                  entry.GetVarLen('tmp')))
+            if entry.Optional():
+                print >>file, '  }'
+
+        print >>file, '}\n'
+
+        # Unmarshaling
+        print >>file, ('int\n'
+                       '%(name)s_unmarshal(struct %(name)s *tmp, '
+                       ' struct evbuffer *evbuf)\n'
+                       '{\n'
+                       '  ev_uint32_t tag;\n'
+                       '  while (evbuffer_get_length(evbuf) > 0) {\n'
+                       '    if (evtag_peek(evbuf, &tag) == -1)\n'
+                       '      return (-1);\n'
+                       '    switch (tag) {\n'
+                       ) % { 'name' : self._name }
+        for entry in self._entries:
+            print >>file, '      case %s:\n' % self.EntryTagName(entry)
+            if not entry.Array():
+                print >>file, (
+                    '        if (tmp->%s_set)\n'
+                    '          return (-1);'
+                    ) % (entry.Name())
+
+            self.PrintIndented(
+                file, '        ',
+                entry.CodeUnmarshal('evbuf',
+                                    self.EntryTagName(entry),
+                                    entry.GetVarName('tmp'),
+                                    entry.GetVarLen('tmp')))
+
+            print >>file, ( '        tmp->%s_set = 1;\n' % entry.Name() +
+                            '        break;\n' )
+        print >>file, ( '      default:\n'
+                        '        return -1;\n'
+                        '    }\n'
+                        '  }\n' )
+        # Check if it was decoded completely
+        print >>file, ( '  if (%(name)s_complete(tmp) == -1)\n'
+                        '    return (-1);'
+                        ) % { 'name' : self._name }
+
+        # Successfully decoded
+        print >>file, ( '  return (0);\n'
+                        '}\n')
+
+        # Checking if a structure has all the required data
+        print >>file, (
+            'int\n'
+            '%(name)s_complete(struct %(name)s *msg)\n'
+            '{' ) % { 'name' : self._name }
+        for entry in self._entries:
+            if not entry.Optional():
+                code = [
+                    'if (!msg->%(name)s_set)',
+                    '  return (-1);' ]
+                code = TranslateList(code, entry.GetTranslation())
+                self.PrintIndented(
+                    file, '  ', code)
+
+            self.PrintIndented(
+                file, '  ',
+                entry.CodeComplete('msg', entry.GetVarName('msg')))
+        print >>file, (
+            '  return (0);\n'
+            '}\n' )
+
+        # Complete message unmarshaling
+        print >>file, (
+            'int\n'
+            'evtag_unmarshal_%(name)s(struct evbuffer *evbuf, '
+            'ev_uint32_t need_tag, struct %(name)s *msg)\n'
+            '{\n'
+            '  ev_uint32_t tag;\n'
+            '  int res = -1;\n'
+            '\n'
+            '  struct evbuffer *tmp = evbuffer_new();\n'
+            '\n'
+            '  if (evtag_unmarshal(evbuf, &tag, tmp) == -1'
+            ' || tag != need_tag)\n'
+            '    goto error;\n'
+            '\n'
+            '  if (%(name)s_unmarshal(msg, tmp) == -1)\n'
+            '    goto error;\n'
+            '\n'
+            '  res = 0;\n'
+            '\n'
+            ' error:\n'
+            '  evbuffer_free(tmp);\n'
+            '  return (res);\n'
+            '}\n' ) % { 'name' : self._name }
+
+        # Complete message marshaling
+        print >>file, (
+            'void\n'
+            'evtag_marshal_%(name)s(struct evbuffer *evbuf, ev_uint32_t tag, '
+            'const struct %(name)s *msg)\n'
+            '{\n'
+            '  struct evbuffer *_buf = evbuffer_new();\n'
+            '  assert(_buf != NULL);\n'
+            '  %(name)s_marshal(_buf, msg);\n'
+            '  evtag_marshal_buffer(evbuf, tag, _buf);\n '
+            '  evbuffer_free(_buf);\n'
+            '}\n' ) % { 'name' : self._name }
+
+class Entry:
+    def __init__(self, type, name, tag):
+        self._type = type
+        self._name = name
+        self._tag = int(tag)
+        self._ctype = type
+        self._optional = 0
+        self._can_be_array = 0
+        self._array = 0
+        self._line_count = -1
+        self._struct = None
+        self._refname = None
+
+        self._optpointer = True
+        self._optaddarg = True
+
+    def GetInitializer(self):
+        assert 0, "Entry does not provide initializer"
+
+    def SetStruct(self, struct):
+        self._struct = struct
+
+    def LineCount(self):
+        assert self._line_count != -1
+        return self._line_count
+
+    def SetLineCount(self, number):
+        self._line_count = number
+
+    def Array(self):
+        return self._array
+
+    def Optional(self):
+        return self._optional
+
+    def Tag(self):
+        return self._tag
+
+    def Name(self):
+        return self._name
+
+    def Type(self):
+        return self._type
+
+    def MakeArray(self, yes=1):
+        self._array = yes
+
+    def MakeOptional(self):
+        self._optional = 1
+
+    def Verify(self):
+        if self.Array() and not self._can_be_array:
+            raise RpcGenError(
+                'Entry "%s" cannot be created as an array '
+                'around line %d' % (self._name, self.LineCount()))
+        if not self._struct:
+            raise RpcGenError(
+                'Entry "%s" does not know which struct it belongs to '
+                'around line %d' % (self._name, self.LineCount()))
+        if self._optional and self._array:
+            raise RpcGenError(
+                'Entry "%s" has illegal combination of optional and array '
+                'around line %d' % (self._name, self.LineCount()))
+
+    def GetTranslation(self, extradict = {}):
+        mapping = {
+            "parent_name" : self._struct.Name(),
+            "name" : self._name,
+            "ctype" : self._ctype,
+            "refname" : self._refname,
+            "optpointer" : self._optpointer and "*" or "",
+            "optreference" : self._optpointer and "&" or "",
+            "optaddarg" :
+            self._optaddarg and ", const %s value" % self._ctype or ""
+            }
+        for (k, v) in extradict.items():
+            mapping[k] = v
+
+        return mapping
+
+    def GetVarName(self, var):
+        return '%(var)s->%(name)s_data' % self.GetTranslation({ 'var' : var })
+
+    def GetVarLen(self, var):
+        return 'sizeof(%s)' % self._ctype
+
+    def GetFuncName(self):
+        return '%s_%s_get' % (self._struct.Name(), self._name)
+
+    def GetDeclaration(self, funcname):
+        code = [ 'int %s(struct %s *, %s *);' % (
+            funcname, self._struct.Name(), self._ctype ) ]
+        return code
+
+    def CodeGet(self):
+        code = (
+            'int',
+            '%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, '
+            '%(ctype)s *value)',
+            '{',
+            '  if (msg->%(name)s_set != 1)',
+            '    return (-1);',
+            '  *value = msg->%(name)s_data;',
+            '  return (0);',
+            '}' )
+        code = '\n'.join(code)
+        code = code % self.GetTranslation()
+        return code.split('\n')
+
+    def AssignFuncName(self):
+        return '%s_%s_assign' % (self._struct.Name(), self._name)
+
+    def AddFuncName(self):
+        return '%s_%s_add' % (self._struct.Name(), self._name)
+
+    def AssignDeclaration(self, funcname):
+        code = [ 'int %s(struct %s *, const %s);' % (
+            funcname, self._struct.Name(), self._ctype ) ]
+        return code
+
+    def CodeAssign(self):
+        code = [ 'int',
+                 '%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,'
+                 ' const %(ctype)s value)',
+                 '{',
+                 '  msg->%(name)s_set = 1;',
+                 '  msg->%(name)s_data = value;',
+                 '  return (0);',
+                 '}' ]
+        code = '\n'.join(code)
+        code = code % self.GetTranslation()
+        return code.split('\n')
+
+    def CodeClear(self, structname):
+        code = [ '%s->%s_set = 0;' % (structname, self.Name()) ]
+
+        return code
+
+    def CodeComplete(self, structname, var_name):
+        return []
+
+    def CodeFree(self, name):
+        return []
+
+    def CodeBase(self):
+        code = [
+            '%(parent_name)s_%(name)s_assign,',
+            '%(parent_name)s_%(name)s_get,'
+            ]
+        if self.Array():
+            code.append('%(parent_name)s_%(name)s_add,')
+
+        code = '\n'.join(code)
+        code = code % self.GetTranslation()
+        return code.split('\n')
+
+class EntryBytes(Entry):
+    def __init__(self, type, name, tag, length):
+        # Init base class
+        Entry.__init__(self, type, name, tag)
+
+        self._length = length
+        self._ctype = 'ev_uint8_t'
+
+    def GetInitializer(self):
+        return "NULL"
+
+    def GetVarLen(self, var):
+        return '(%s)' % self._length
+
+    def CodeArrayAdd(self, varname, value):
+        # XXX: copy here
+        return [ '%(varname)s = NULL;' % { 'varname' : varname } ]
+
+    def GetDeclaration(self, funcname):
+        code = [ 'int %s(struct %s *, %s **);' % (
+            funcname, self._struct.Name(), self._ctype ) ]
+        return code
+
+    def AssignDeclaration(self, funcname):
+        code = [ 'int %s(struct %s *, const %s *);' % (
+            funcname, self._struct.Name(), self._ctype ) ]
+        return code
+
+    def Declaration(self):
+        dcl  = ['ev_uint8_t %s_data[%s];' % (self._name, self._length)]
+
+        return dcl
+
+    def CodeGet(self):
+        name = self._name
+        code = [ 'int',
+                 '%s_%s_get(struct %s *msg, %s **value)' % (
+            self._struct.Name(), name,
+            self._struct.Name(), self._ctype),
+                 '{',
+                 '  if (msg->%s_set != 1)' % name,
+                 '    return (-1);',
+                 '  *value = msg->%s_data;' % name,
+                 '  return (0);',
+                 '}' ]
+        return code
+
+    def CodeAssign(self):
+        name = self._name
+        code = [ 'int',
+                 '%s_%s_assign(struct %s *msg, const %s *value)' % (
+            self._struct.Name(), name,
+            self._struct.Name(), self._ctype),
+                 '{',
+                 '  msg->%s_set = 1;' % name,
+                 '  memcpy(msg->%s_data, value, %s);' % (
+            name, self._length),
+                 '  return (0);',
+                 '}' ]
+        return code
+
+    def CodeUnmarshal(self, buf, tag_name, var_name, var_len):
+        code = [  'if (evtag_unmarshal_fixed(%(buf)s, %(tag)s, '
+                  '%(var)s, %(varlen)s) == -1) {',
+                  '  event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+                  '  return (-1);',
+                  '}'
+                  ]
+        return TranslateList(code,
+                             self.GetTranslation({
+            'var' : var_name,
+            'varlen' : var_len,
+            'buf' : buf,
+            'tag' : tag_name }))
+
+    def CodeMarshal(self, buf, tag_name, var_name, var_len):
+        code = ['evtag_marshal(%s, %s, %s, %s);' % (
+            buf, tag_name, var_name, var_len)]
+        return code
+
+    def CodeClear(self, structname):
+        code = [ '%s->%s_set = 0;' % (structname, self.Name()),
+                 'memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (
+            structname, self._name, structname, self._name)]
+
+        return code
+
+    def CodeInitialize(self, name):
+        code  = ['memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (
+            name, self._name, name, self._name)]
+        return code
+
+    def Verify(self):
+        if not self._length:
+            raise RpcGenError(
+                'Entry "%s" needs a length '
+                'around line %d' % (self._name, self.LineCount()))
+
+        Entry.Verify(self)
+
+class EntryInt(Entry):
+    def __init__(self, type, name, tag, bits=32):
+        # Init base class
+        Entry.__init__(self, type, name, tag)
+
+        self._can_be_array = 1
+        if bits == 32:
+            self._ctype = 'ev_uint32_t'
+            self._marshal_type = 'int'
+        if bits == 64:
+            self._ctype = 'ev_uint64_t'
+            self._marshal_type = 'int64'
+
+    def GetInitializer(self):
+        return "0"
+
+    def CodeArrayFree(self, var):
+        return []
+
+    def CodeArrayAssign(self, varname, srcvar):
+        return [ '%(varname)s = %(srcvar)s;' % { 'varname' : varname,
+                                                'srcvar' : srcvar } ]
+
+    def CodeArrayAdd(self, varname, value):
+        """Returns a new entry of this type."""
+        return [ '%(varname)s = %(value)s;' % { 'varname' : varname,
+                                              'value' : value } ]
+
+    def CodeUnmarshal(self, buf, tag_name, var_name, var_len):
+        code = [
+            'if (evtag_unmarshal_%(ma)s(%(buf)s, %(tag)s, &%(var)s) == -1) {',
+            '  event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+            '  return (-1);',
+            '}' ]
+        code = '\n'.join(code) % self.GetTranslation({
+            'ma'  : self._marshal_type,
+            'buf' : buf,
+            'tag' : tag_name,
+            'var' : var_name })
+        return code.split('\n')
+
+    def CodeMarshal(self, buf, tag_name, var_name, var_len):
+        code = [
+            'evtag_marshal_%s(%s, %s, %s);' % (
+            self._marshal_type, buf, tag_name, var_name)]
+        return code
+
+    def Declaration(self):
+        dcl  = ['%s %s_data;' % (self._ctype, self._name)]
+
+        return dcl
+
+    def CodeInitialize(self, name):
+        code = ['%s->%s_data = 0;' % (name, self._name)]
+        return code
+
+class EntryString(Entry):
+    def __init__(self, type, name, tag):
+        # Init base class
+        Entry.__init__(self, type, name, tag)
+
+        self._can_be_array = 1
+        self._ctype = 'char *'
+
+    def GetInitializer(self):
+        return "NULL"
+
+    def CodeArrayFree(self, varname):
+        code = [
+            'if (%(var)s != NULL) free(%(var)s);' ]
+
+        return TranslateList(code, { 'var' : varname })
+
+    def CodeArrayAssign(self, varname, srcvar):
+        code = [
+            'if (%(var)s != NULL)',
+            '  free(%(var)s);',
+            '%(var)s = strdup(%(srcvar)s);',
+            'if (%(var)s == NULL) {',
+            '  event_warnx("%%s: strdup", __func__);',
+            '  return (-1);',
+            '}' ]
+
+        return TranslateList(code, { 'var' : varname,
+                                     'srcvar' : srcvar })
+
+    def CodeArrayAdd(self, varname, value):
+        code = [
+            'if (%(value)s != NULL) {',
+            '  %(var)s = strdup(%(value)s);',
+            '  if (%(var)s == NULL) {',
+            '    goto error;',
+            '  }',
+            '} else {',
+            '  %(var)s = NULL;',
+            '}' ]
+
+        return TranslateList(code, { 'var' : varname,
+                                     'value' : value })
+
+    def GetVarLen(self, var):
+        return 'strlen(%s)' % self.GetVarName(var)
+
+    def CodeMakeInitalize(self, varname):
+        return '%(varname)s = NULL;' % { 'varname' : varname }
+
+    def CodeAssign(self):
+        name = self._name
+        code = """int
+%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
+    const %(ctype)s value)
+{
+  if (msg->%(name)s_data != NULL)
+    free(msg->%(name)s_data);
+  if ((msg->%(name)s_data = strdup(value)) == NULL)
+    return (-1);
+  msg->%(name)s_set = 1;
+  return (0);
+}""" % self.GetTranslation()
+
+        return code.split('\n')
+
+    def CodeUnmarshal(self, buf, tag_name, var_name, var_len):
+        code = ['if (evtag_unmarshal_string(%(buf)s, %(tag)s, &%(var)s) == -1) {',
+                '  event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+                '  return (-1);',
+                '}'
+                ]
+        code = '\n'.join(code) % self.GetTranslation({
+            'buf' : buf,
+            'tag' : tag_name,
+            'var' : var_name })
+        return code.split('\n')
+
+    def CodeMarshal(self, buf, tag_name, var_name, var_len):
+        code = ['evtag_marshal_string(%s, %s, %s);' % (
+            buf, tag_name, var_name)]
+        return code
+
+    def CodeClear(self, structname):
+        code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
+                 '  free(%s->%s_data);' % (structname, self.Name()),
+                 '  %s->%s_data = NULL;' % (structname, self.Name()),
+                 '  %s->%s_set = 0;' % (structname, self.Name()),
+                 '}'
+                 ]
+
+        return code
+
+    def CodeInitialize(self, name):
+        code  = ['%s->%s_data = NULL;' % (name, self._name)]
+        return code
+
+    def CodeFree(self, name):
+        code  = ['if (%s->%s_data != NULL)' % (name, self._name),
+                 '    free (%s->%s_data);' % (name, self._name)]
+
+        return code
+
+    def Declaration(self):
+        dcl  = ['char *%s_data;' % self._name]
+
+        return dcl
+
+class EntryStruct(Entry):
+    def __init__(self, type, name, tag, refname):
+        # Init base class
+        Entry.__init__(self, type, name, tag)
+
+        self._optpointer = False
+        self._can_be_array = 1
+        self._refname = refname
+        self._ctype = 'struct %s*' % refname
+        self._optaddarg = False
+
+    def GetInitializer(self):
+        return "NULL"
+
+    def GetVarLen(self, var):
+        return '-1'
+
+    def CodeArrayAdd(self, varname, value):
+        code = [
+            '%(varname)s = %(refname)s_new();',
+            'if (%(varname)s == NULL)',
+            '  goto error;' ]
+
+        return TranslateList(code, self.GetTranslation({ 'varname' : varname }))
+
+    def CodeArrayFree(self, var):
+        code = [ '%(refname)s_free(%(var)s);' % self.GetTranslation(
+            { 'var' : var }) ]
+        return code
+
+    def CodeArrayAssign(self, var, srcvar):
+        code = [
+            'int had_error = 0;',
+            'struct evbuffer *tmp = NULL;',
+            '%(refname)s_clear(%(var)s);',
+            'if ((tmp = evbuffer_new()) == NULL) {',
+            '  event_warn("%%s: evbuffer_new()", __func__);',
+            '  had_error = 1;',
+            '  goto done;',
+            '}',
+            '%(refname)s_marshal(tmp, %(srcvar)s);',
+            'if (%(refname)s_unmarshal(%(var)s, tmp) == -1) {',
+            '  event_warnx("%%s: %(refname)s_unmarshal", __func__);',
+            '  had_error = 1;',
+            '  goto done;',
+            '}',
+            'done:'
+            'if (tmp != NULL)',
+            '  evbuffer_free(tmp);',
+            'if (had_error) {',
+            '  %(refname)s_clear(%(var)s);',
+            '  return (-1);',
+            '}' ]
+
+        return TranslateList(code, self.GetTranslation({
+            'var' : var,
+            'srcvar' : srcvar}))
+
+    def CodeGet(self):
+        name = self._name
+        code = [ 'int',
+                 '%s_%s_get(struct %s *msg, %s *value)' % (
+            self._struct.Name(), name,
+            self._struct.Name(), self._ctype),
+                 '{',
+                 '  if (msg->%s_set != 1) {' % name,
+                 '    msg->%s_data = %s_new();' % (name, self._refname),
+                 '    if (msg->%s_data == NULL)' % name,
+                 '      return (-1);',
+                 '    msg->%s_set = 1;' % name,
+                 '  }',
+                 '  *value = msg->%s_data;' % name,
+                 '  return (0);',
+                 '}' ]
+        return code
+
+    def CodeAssign(self):
+        name = self._name
+        code = """int
+%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
+    const %(ctype)s value)
+{
+   struct evbuffer *tmp = NULL;
+   if (msg->%(name)s_set) {
+     %(refname)s_clear(msg->%(name)s_data);
+     msg->%(name)s_set = 0;
+   } else {
+     msg->%(name)s_data = %(refname)s_new();
+     if (msg->%(name)s_data == NULL) {
+       event_warn("%%s: %(refname)s_new()", __func__);
+       goto error;
+     }
+   }
+   if ((tmp = evbuffer_new()) == NULL) {
+     event_warn("%%s: evbuffer_new()", __func__);
+     goto error;
+   }
+   %(refname)s_marshal(tmp, value);
+   if (%(refname)s_unmarshal(msg->%(name)s_data, tmp) == -1) {
+     event_warnx("%%s: %(refname)s_unmarshal", __func__);
+     goto error;
+   }
+   msg->%(name)s_set = 1;
+   evbuffer_free(tmp);
+   return (0);
+ error:
+   if (tmp != NULL)
+     evbuffer_free(tmp);
+   if (msg->%(name)s_data != NULL) {
+     %(refname)s_free(msg->%(name)s_data);
+     msg->%(name)s_data = NULL;
+   }
+   return (-1);
+}""" % self.GetTranslation()
+        return code.split('\n')
+
+    def CodeComplete(self, structname, var_name):
+        code = [ 'if (%(structname)s->%(name)s_set && '
+                 '%(refname)s_complete(%(var)s) == -1)',
+                 '  return (-1);' ]
+
+        return TranslateList(code, self.GetTranslation({
+            'structname' : structname,
+            'var' : var_name }))
+
+    def CodeUnmarshal(self, buf, tag_name, var_name, var_len):
+        code = ['%(var)s = %(refname)s_new();',
+                'if (%(var)s == NULL)',
+                '  return (-1);',
+                'if (evtag_unmarshal_%(refname)s(%(buf)s, %(tag)s, '
+                '%(var)s) == -1) {',
+                  '  event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+                '  return (-1);',
+                '}'
+                ]
+        code = '\n'.join(code) % self.GetTranslation({
+            'buf' : buf,
+            'tag' : tag_name,
+            'var' : var_name })
+        return code.split('\n')
+
+    def CodeMarshal(self, buf, tag_name, var_name, var_len):
+        code = ['evtag_marshal_%s(%s, %s, %s);' % (
+            self._refname, buf, tag_name, var_name)]
+        return code
+
+    def CodeClear(self, structname):
+        code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
+                 '  %s_free(%s->%s_data);' % (
+            self._refname, structname, self.Name()),
+                 '  %s->%s_data = NULL;' % (structname, self.Name()),
+                 '  %s->%s_set = 0;' % (structname, self.Name()),
+                 '}'
+                 ]
+
+        return code
+
+    def CodeInitialize(self, name):
+        code  = ['%s->%s_data = NULL;' % (name, self._name)]
+        return code
+
+    def CodeFree(self, name):
+        code  = ['if (%s->%s_data != NULL)' % (name, self._name),
+                 '    %s_free(%s->%s_data);' % (
+            self._refname, name, self._name)]
+
+        return code
+
+    def Declaration(self):
+        dcl  = ['%s %s_data;' % (self._ctype, self._name)]
+
+        return dcl
+
+class EntryVarBytes(Entry):
+    def __init__(self, type, name, tag):
+        # Init base class
+        Entry.__init__(self, type, name, tag)
+
+        self._ctype = 'ev_uint8_t *'
+
+    def GetInitializer(self):
+        return "NULL"
+
+    def GetVarLen(self, var):
+        return '%(var)s->%(name)s_length' % self.GetTranslation({ 'var' : var })
+
+    def CodeArrayAdd(self, varname, value):
+        # xxx: copy
+        return [ '%(varname)s = NULL;' % { 'varname' : varname } ]
+
+    def GetDeclaration(self, funcname):
+        code = [ 'int %s(struct %s *, %s *, ev_uint32_t *);' % (
+            funcname, self._struct.Name(), self._ctype ) ]
+        return code
+
+    def AssignDeclaration(self, funcname):
+        code = [ 'int %s(struct %s *, const %s, ev_uint32_t);' % (
+            funcname, self._struct.Name(), self._ctype ) ]
+        return code
+
+    def CodeAssign(self):
+        name = self._name
+        code = [ 'int',
+                 '%s_%s_assign(struct %s *msg, '
+                 'const %s value, ev_uint32_t len)' % (
+            self._struct.Name(), name,
+            self._struct.Name(), self._ctype),
+                 '{',
+                 '  if (msg->%s_data != NULL)' % name,
+                 '    free (msg->%s_data);' % name,
+                 '  msg->%s_data = malloc(len);' % name,
+                 '  if (msg->%s_data == NULL)' % name,
+                 '    return (-1);',
+                 '  msg->%s_set = 1;' % name,
+                 '  msg->%s_length = len;' % name,
+                 '  memcpy(msg->%s_data, value, len);' % name,
+                 '  return (0);',
+                 '}' ]
+        return code
+
+    def CodeGet(self):
+        name = self._name
+        code = [ 'int',
+                 '%s_%s_get(struct %s *msg, %s *value, ev_uint32_t *plen)' % (
+            self._struct.Name(), name,
+            self._struct.Name(), self._ctype),
+                 '{',
+                 '  if (msg->%s_set != 1)' % name,
+                 '    return (-1);',
+                 '  *value = msg->%s_data;' % name,
+                 '  *plen = msg->%s_length;' % name,
+                 '  return (0);',
+                 '}' ]
+        return code
+
+    def CodeUnmarshal(self, buf, tag_name, var_name, var_len):
+        code = ['if (evtag_payload_length(%(buf)s, &%(varlen)s) == -1)',
+                '  return (-1);',
+                # We do not want DoS opportunities
+                'if (%(varlen)s > evbuffer_get_length(%(buf)s))',
+                '  return (-1);',
+                'if ((%(var)s = malloc(%(varlen)s)) == NULL)',
+                '  return (-1);',
+                'if (evtag_unmarshal_fixed(%(buf)s, %(tag)s, %(var)s, '
+                '%(varlen)s) == -1) {',
+                '  event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+                '  return (-1);',
+                '}'
+                ]
+        code = '\n'.join(code) % self.GetTranslation({
+            'buf' : buf,
+            'tag' : tag_name,
+            'var' : var_name,
+            'varlen' : var_len })
+        return code.split('\n')
+
+    def CodeMarshal(self, buf, tag_name, var_name, var_len):
+        code = ['evtag_marshal(%s, %s, %s, %s);' % (
+            buf, tag_name, var_name, var_len)]
+        return code
+
+    def CodeClear(self, structname):
+        code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
+                 '  free (%s->%s_data);' % (structname, self.Name()),
+                 '  %s->%s_data = NULL;' % (structname, self.Name()),
+                 '  %s->%s_length = 0;' % (structname, self.Name()),
+                 '  %s->%s_set = 0;' % (structname, self.Name()),
+                 '}'
+                 ]
+
+        return code
+
+    def CodeInitialize(self, name):
+        code  = ['%s->%s_data = NULL;' % (name, self._name),
+                 '%s->%s_length = 0;' % (name, self._name) ]
+        return code
+
+    def CodeFree(self, name):
+        code  = ['if (%s->%s_data != NULL)' % (name, self._name),
+                 '    free(%s->%s_data);' % (name, self._name)]
+
+        return code
+
+    def Declaration(self):
+        dcl  = ['ev_uint8_t *%s_data;' % self._name,
+                'ev_uint32_t %s_length;' % self._name]
+
+        return dcl
+
+class EntryArray(Entry):
+    def __init__(self, entry):
+        # Init base class
+        Entry.__init__(self, entry._type, entry._name, entry._tag)
+
+        self._entry = entry
+        self._refname = entry._refname
+        self._ctype = self._entry._ctype
+        self._optional = True
+        self._optpointer = self._entry._optpointer
+        self._optaddarg = self._entry._optaddarg
+
+        # provide a new function for accessing the variable name
+        def GetVarName(var_name):
+            return '%(var)s->%(name)s_data[%(index)s]' % \
+                   self._entry.GetTranslation({'var' : var_name,
+                                               'index' : self._index})
+        self._entry.GetVarName = GetVarName
+
+    def GetInitializer(self):
+        return "NULL"
+
+    def GetVarName(self, var_name):
+        return var_name
+
+    def GetVarLen(self, var_name):
+        return '-1'
+
+    def GetDeclaration(self, funcname):
+        """Allows direct access to elements of the array."""
+        code = [
+            'int %(funcname)s(struct %(parent_name)s *, int, %(ctype)s *);' %
+            self.GetTranslation({ 'funcname' : funcname }) ]
+        return code
+
+    def AssignDeclaration(self, funcname):
+        code = [ 'int %s(struct %s *, int, const %s);' % (
+            funcname, self._struct.Name(), self._ctype ) ]
+        return code
+
+    def AddDeclaration(self, funcname):
+        code = [
+            '%(ctype)s %(optpointer)s '
+            '%(funcname)s(struct %(parent_name)s *msg%(optaddarg)s);' % \
+            self.GetTranslation({ 'funcname' : funcname }) ]
+        return code
+
+    def CodeGet(self):
+        code = """int
+%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, int offset,
+    %(ctype)s *value)
+{
+  if (!msg->%(name)s_set || offset < 0 || offset >= msg->%(name)s_length)
+    return (-1);
+  *value = msg->%(name)s_data[offset];
+  return (0);
+}""" % self.GetTranslation()
+
+        return code.split('\n')
+
+    def CodeAssign(self):
+        code = [
+            'int',
+            '%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg, int off,',
+            '    const %(ctype)s value)',
+            '{',
+            '  if (!msg->%(name)s_set || off < 0 || off >= msg->%(name)s_length)',
+            '    return (-1);\n',
+            '  {' ]
+        code = TranslateList(code, self.GetTranslation())
+
+        codearrayassign = self._entry.CodeArrayAssign(
+            'msg->%(name)s_data[off]' % self.GetTranslation(), 'value')
+        code += map(lambda x: '    ' + x, codearrayassign)
+
+        code += TranslateList([
+            '  }',
+            '  return (0);',
+            '}' ], self.GetTranslation())
+
+        return code
+
+    def CodeAdd(self):
+        codearrayadd = self._entry.CodeArrayAdd(
+            'msg->%(name)s_data[msg->%(name)s_length - 1]' % self.GetTranslation(),
+            'value')
+        code = [
+            'static int',
+            '%(parent_name)s_%(name)s_expand_to_hold_more('
+            'struct %(parent_name)s *msg)',
+            '{',
+            '  int tobe_allocated = msg->%(name)s_num_allocated;',
+            '  %(ctype)s* new_data = NULL;',
+            '  tobe_allocated = !tobe_allocated ? 1 : tobe_allocated << 1;',
+            '  new_data = (%(ctype)s*) realloc(msg->%(name)s_data,',
+            '      tobe_allocated * sizeof(%(ctype)s));',
+            '  if (new_data == NULL)',
+            '    return -1;',
+            '  msg->%(name)s_data = new_data;',
+            '  msg->%(name)s_num_allocated = tobe_allocated;',
+            '  return 0;'
+            '}',
+            '',
+            '%(ctype)s %(optpointer)s',
+            '%(parent_name)s_%(name)s_add('
+            'struct %(parent_name)s *msg%(optaddarg)s)',
+            '{',
+            '  if (++msg->%(name)s_length >= msg->%(name)s_num_allocated) {',
+            '    if (%(parent_name)s_%(name)s_expand_to_hold_more(msg)<0)',
+            '      goto error;',
+            '  }' ]
+
+        code = TranslateList(code, self.GetTranslation())
+
+        code += map(lambda x: '  ' + x, codearrayadd)
+
+        code += TranslateList([
+            '  msg->%(name)s_set = 1;',
+            '  return %(optreference)s(msg->%(name)s_data['
+            'msg->%(name)s_length - 1]);',
+            'error:',
+            '  --msg->%(name)s_length;',
+            '  return (NULL);',
+            '}' ], self.GetTranslation())
+
+        return code
+
+    def CodeComplete(self, structname, var_name):
+        self._index = 'i'
+        tmp = self._entry.CodeComplete(structname, self._entry.GetVarName(var_name))
+        # skip the whole loop if there is nothing to check
+        if not tmp:
+            return []
+
+        translate = self.GetTranslation({ 'structname' : structname })
+        code = [
+            '{',
+            '  int i;',
+            '  for (i = 0; i < %(structname)s->%(name)s_length; ++i) {' ]
+
+        code = TranslateList(code, translate)
+
+        code += map(lambda x: '    ' + x, tmp)
+
+        code += [
+            '  }',
+            '}' ]
+
+        return code
+
+    def CodeUnmarshal(self, buf, tag_name, var_name, var_len):
+        translate = self.GetTranslation({ 'var' : var_name,
+                                          'buf' : buf,
+                                          'tag' : tag_name,
+                                          'init' : self._entry.GetInitializer()})
+        code = [
+            'if (%(var)s->%(name)s_length >= %(var)s->%(name)s_num_allocated &&',
+            '    %(parent_name)s_%(name)s_expand_to_hold_more(%(var)s) < 0) {',
+            '  puts("HEY NOW");',
+            '  return (-1);',
+            '}']
+
+        # the unmarshal code directly returns
+        code = TranslateList(code, translate)
+
+        self._index = '%(var)s->%(name)s_length' % translate
+        code += self._entry.CodeUnmarshal(buf, tag_name,
+                                        self._entry.GetVarName(var_name),
+                                        self._entry.GetVarLen(var_name))
+
+        code += [ '++%(var)s->%(name)s_length;' % translate ]
+
+        return code
+
+    def CodeMarshal(self, buf, tag_name, var_name, var_len):
+        code = ['{',
+                '  int i;',
+                '  for (i = 0; i < %(var)s->%(name)s_length; ++i) {' ]
+
+        self._index = 'i'
+        code += self._entry.CodeMarshal(buf, tag_name,
+                                        self._entry.GetVarName(var_name),
+                                        self._entry.GetVarLen(var_name))
+        code += ['  }',
+                 '}'
+                 ]
+
+        code = "\n".join(code) % self.GetTranslation({ 'var' : var_name })
+
+        return code.split('\n')
+
+    def CodeClear(self, structname):
+        translate = self.GetTranslation({ 'structname' : structname })
+        codearrayfree = self._entry.CodeArrayFree(
+            '%(structname)s->%(name)s_data[i]' % self.GetTranslation(
+            { 'structname' : structname } ))
+
+        code = [ 'if (%(structname)s->%(name)s_set == 1) {' ]
+
+        if codearrayfree:
+            code += [
+                '  int i;',
+                '  for (i = 0; i < %(structname)s->%(name)s_length; ++i) {' ]
+
+        code = TranslateList(code, translate)
+
+        if codearrayfree:
+            code += map(lambda x: '    ' + x, codearrayfree)
+            code += [
+                '  }' ]
+
+        code += TranslateList([
+                 '  free(%(structname)s->%(name)s_data);',
+                 '  %(structname)s->%(name)s_data = NULL;',
+                 '  %(structname)s->%(name)s_set = 0;',
+                 '  %(structname)s->%(name)s_length = 0;',
+                 '  %(structname)s->%(name)s_num_allocated = 0;',
+                 '}'
+                 ], translate)
+
+        return code
+
+    def CodeInitialize(self, name):
+        code  = ['%s->%s_data = NULL;' % (name, self._name),
+                 '%s->%s_length = 0;' % (name, self._name),
+                 '%s->%s_num_allocated = 0;' % (name, self._name)]
+        return code
+
+    def CodeFree(self, structname):
+        code = self.CodeClear(structname);
+
+        code += TranslateList([
+            'free(%(structname)s->%(name)s_data);' ],
+                              self.GetTranslation({'structname' : structname }))
+
+        return code
+
+    def Declaration(self):
+        dcl  = ['%s *%s_data;' % (self._ctype, self._name),
+                'int %s_length;' % self._name,
+                'int %s_num_allocated;' % self._name ]
+
+        return dcl
+
+def NormalizeLine(line):
+    global white
+    global cppcomment
+
+    line = cppcomment.sub('', line)
+    line = line.strip()
+    line = white.sub(' ', line)
+
+    return line
+
+def ProcessOneEntry(factory, newstruct, entry):
+    optional = 0
+    array = 0
+    entry_type = ''
+    name = ''
+    tag = ''
+    tag_set = None
+    separator = ''
+    fixed_length = ''
+
+    tokens = entry.split(' ')
+    while tokens:
+        token = tokens[0]
+        tokens = tokens[1:]
+
+        if not entry_type:
+            if not optional and token == 'optional':
+                optional = 1
+                continue
+
+            if not array and token == 'array':
+                array = 1
+                continue
+
+        if not entry_type:
+            entry_type = token
+            continue
+
+        if not name:
+            res = re.match(r'^([^\[\]]+)(\[.*\])?$', token)
+            if not res:
+                 raise RpcGenError(
+                     'Cannot parse name: \"%s\" '
+                     'around line %d' % (entry, line_count))
+            name = res.group(1)
+            fixed_length = res.group(2)
+            if fixed_length:
+                fixed_length = fixed_length[1:-1]
+            continue
+
+        if not separator:
+            separator = token
+            if separator != '=':
+                 raise RpcGenError('Expected "=" after name \"%s\" got %s'
+                                   % (name, token))
+            continue
+
+        if not tag_set:
+            tag_set = 1
+            if not re.match(r'^(0x)?[0-9]+$', token):
+                raise RpcGenError('Expected tag number: \"%s\"' % entry)
+            tag = int(token, 0)
+            continue
+
+        raise RpcGenError('Cannot parse \"%s\"' % entry)
+
+    if not tag_set:
+        raise RpcGenError('Need tag number: \"%s\"' % entry)
+
+    # Create the right entry
+    if entry_type == 'bytes':
+        if fixed_length:
+            newentry = factory.EntryBytes(entry_type, name, tag, fixed_length)
+        else:
+            newentry = factory.EntryVarBytes(entry_type, name, tag)
+    elif entry_type == 'int' and not fixed_length:
+        newentry = factory.EntryInt(entry_type, name, tag)
+    elif entry_type == 'int64' and not fixed_length:
+        newentry = factory.EntryInt(entry_type, name, tag, bits=64)
+    elif entry_type == 'string' and not fixed_length:
+        newentry = factory.EntryString(entry_type, name, tag)
+    else:
+        res = structref.match(entry_type)
+        if res:
+            # References another struct defined in our file
+            newentry = factory.EntryStruct(entry_type, name, tag, res.group(1))
+        else:
+            raise RpcGenError('Bad type: "%s" in "%s"' % (entry_type, entry))
+
+    structs = []
+
+    if optional:
+        newentry.MakeOptional()
+    if array:
+        newentry.MakeArray()
+
+    newentry.SetStruct(newstruct)
+    newentry.SetLineCount(line_count)
+    newentry.Verify()
+
+    if array:
+        # We need to encapsulate this entry into a struct
+        newname = newentry.Name()+ '_array'
+
+        # Now borgify the new entry.
+        newentry = factory.EntryArray(newentry)
+        newentry.SetStruct(newstruct)
+        newentry.SetLineCount(line_count)
+        newentry.MakeArray()
+
+    newstruct.AddEntry(newentry)
+
+    return structs
+
+def ProcessStruct(factory, data):
+    tokens = data.split(' ')
+
+    # First three tokens are: 'struct' 'name' '{'
+    newstruct = factory.Struct(tokens[1])
+
+    inside = ' '.join(tokens[3:-1])
+
+    tokens = inside.split(';')
+
+    structs = []
+
+    for entry in tokens:
+        entry = NormalizeLine(entry)
+        if not entry:
+            continue
+
+        # It's possible that new structs get defined in here
+        structs.extend(ProcessOneEntry(factory, newstruct, entry))
+
+    structs.append(newstruct)
+    return structs
+
+def GetNextStruct(file):
+    global line_count
+    global cppdirect
+
+    got_struct = 0
+
+    processed_lines = []
+
+    have_c_comment = 0
+    data = ''
+    while 1:
+        line = file.readline()
+        if not line:
+            break
+
+        line_count += 1
+        line = line[:-1]
+
+        if not have_c_comment and re.search(r'/\*', line):
+            if re.search(r'/\*.*?\*/', line):
+                line = re.sub(r'/\*.*?\*/', '', line)
+            else:
+                line = re.sub(r'/\*.*$', '', line)
+                have_c_comment = 1
+
+        if have_c_comment:
+            if not re.search(r'\*/', line):
+                continue
+            have_c_comment = 0
+            line = re.sub(r'^.*\*/', '', line)
+
+        line = NormalizeLine(line)
+
+        if not line:
+            continue
+
+        if not got_struct:
+            if re.match(r'#include ["<].*[>"]', line):
+                cppdirect.append(line)
+                continue
+
+            if re.match(r'^#(if( |def)|endif)', line):
+                cppdirect.append(line)
+                continue
+
+            if re.match(r'^#define', line):
+                headerdirect.append(line)
+                continue
+
+            if not structdef.match(line):
+                raise RpcGenError('Missing struct on line %d: %s'
+                                  % (line_count, line))
+            else:
+                got_struct = 1
+                data += line
+            continue
+
+        # We are inside the struct
+        tokens = line.split('}')
+        if len(tokens) == 1:
+            data += ' ' + line
+            continue
+
+        if len(tokens[1]):
+            raise RpcGenError('Trailing garbage after struct on line %d'
+                              % line_count)
+
+        # We found the end of the struct
+        data += ' %s}' % tokens[0]
+        break
+
+    # Remove any comments, that might be in there
+    data = re.sub(r'/\*.*\*/', '', data)
+
+    return data
+
+
+def Parse(factory, file):
+    """
+    Parses the input file and returns C code and corresponding header file.
+    """
+
+    entities = []
+
+    while 1:
+        # Just gets the whole struct nicely formatted
+        data = GetNextStruct(file)
+
+        if not data:
+            break
+
+        entities.extend(ProcessStruct(factory, data))
+
+    return entities
+
+class CCodeGenerator:
+    def __init__(self):
+        pass
+
+    def GuardName(self, name):
+        # Use the complete provided path to the input file, with all
+        # non-identifier characters replaced with underscores, to
+        # reduce the chance of a collision between guard macros.
+        return '_' + nonident.sub('_', name).upper() + '_'
+
+    def HeaderPreamble(self, name):
+        guard = self.GuardName(name)
+        pre = (
+            '/*\n'
+            ' * Automatically generated from %s\n'
+            ' */\n\n'
+            '#ifndef %s\n'
+            '#define %s\n\n' ) % (
+            name, guard, guard)
+
+        for statement in headerdirect:
+            pre += '%s\n' % statement
+        if headerdirect:
+            pre += '\n'
+
+        pre += (
+            '#include <event2/util.h> /* for ev_uint*_t */\n'
+            '#include <event2/rpc.h>\n'
+        )
+
+        return pre
+
+    def HeaderPostamble(self, name):
+        guard = self.GuardName(name)
+        return '#endif  /* %s */' % guard
+
+    def BodyPreamble(self, name, header_file):
+        global _NAME
+        global _VERSION
+
+        slash = header_file.rfind('/')
+        if slash != -1:
+            header_file = header_file[slash+1:]
+
+        pre = ( '/*\n'
+                ' * Automatically generated from %s\n'
+                ' * by %s/%s.  DO NOT EDIT THIS FILE.\n'
+                ' */\n\n' ) % (name, _NAME, _VERSION)
+        pre += ( '#include <stdlib.h>\n'
+                 '#include <string.h>\n'
+                 '#include <assert.h>\n'
+                 '#include <event2/event-config.h>\n'
+                 '#include <event2/event.h>\n'
+                 '#include <event2/buffer.h>\n'
+                 '#include <event2/tag.h>\n\n'
+                 '#ifdef _EVENT___func__\n'
+                 '#define __func__ _EVENT___func__\n'
+                 '#endif\n\n'
+                 )
+
+        for statement in cppdirect:
+            pre += '%s\n' % statement
+
+        pre += '\n#include "%s"\n\n' % header_file
+
+        pre += 'void event_warn(const char *fmt, ...);\n'
+        pre += 'void event_warnx(const char *fmt, ...);\n\n'
+
+        return pre
+
+    def HeaderFilename(self, filename):
+        return '.'.join(filename.split('.')[:-1]) + '.h'
+
+    def CodeFilename(self, filename):
+        return '.'.join(filename.split('.')[:-1]) + '.gen.c'
+
+    def Struct(self, name):
+        return StructCCode(name)
+
+    def EntryBytes(self, entry_type, name, tag, fixed_length):
+        return EntryBytes(entry_type, name, tag, fixed_length)
+
+    def EntryVarBytes(self, entry_type, name, tag):
+        return EntryVarBytes(entry_type, name, tag)
+
+    def EntryInt(self, entry_type, name, tag, bits=32):
+        return EntryInt(entry_type, name, tag, bits)
+
+    def EntryString(self, entry_type, name, tag):
+        return EntryString(entry_type, name, tag)
+
+    def EntryStruct(self, entry_type, name, tag, struct_name):
+        return EntryStruct(entry_type, name, tag, struct_name)
+
+    def EntryArray(self, entry):
+        return EntryArray(entry)
+
+class Usage(RpcGenError):
+    def __init__(self, argv0):
+        RpcGenError.__init__("usage: %s input.rpc [[output.h] output.c]"
+                             % argv0)
+
+class CommandLine:
+    def __init__(self, argv):
+        """Initialize a command-line to launch event_rpcgen, as if
+           from a command-line with CommandLine(sys.argv).  If you're
+           calling this directly, remember to provide a dummy value
+           for sys.argv[0]
+        """
+        self.filename = None
+        self.header_file = None
+        self.impl_file = None
+        self.factory = CCodeGenerator()
+
+        if len(argv) < 2 or len(argv) > 4:
+            raise Usage(argv[0])
+
+        self.filename = argv[1].replace('\\', '/')
+        if len(argv) == 3:
+            self.impl_file = argv[2].replace('\\', '/')
+        if len(argv) == 4:
+            self.header_file = argv[2].replace('\\', '/')
+            self.impl_file = argv[3].replace('\\', '/')
+
+        if not self.filename:
+            raise Usage(argv[0])
+
+        if not self.impl_file:
+            self.impl_file = self.factory.CodeFilename(self.filename)
+
+        if not self.header_file:
+            self.header_file = self.factory.HeaderFilename(self.impl_file)
+
+        if not self.impl_file.endswith('.c'):
+            raise RpcGenError("can only generate C implementation files")
+        if not self.header_file.endswith('.h'):
+            raise RpcGenError("can only generate C header files")
+
+    def run(self):
+        filename = self.filename
+        header_file = self.header_file
+        impl_file = self.impl_file
+        factory = self.factory
+
+        print >>sys.stderr, 'Reading \"%s\"' % filename
+
+        fp = open(filename, 'r')
+        entities = Parse(factory, fp)
+        fp.close()
+
+        print >>sys.stderr, '... creating "%s"' % header_file
+        header_fp = open(header_file, 'w')
+        print >>header_fp, factory.HeaderPreamble(filename)
+
+        # Create forward declarations: allows other structs to reference
+        # each other
+        for entry in entities:
+            entry.PrintForwardDeclaration(header_fp)
+        print >>header_fp, ''
+
+        for entry in entities:
+            entry.PrintTags(header_fp)
+            entry.PrintDeclaration(header_fp)
+        print >>header_fp, factory.HeaderPostamble(filename)
+        header_fp.close()
+
+        print >>sys.stderr, '... creating "%s"' % impl_file
+        impl_fp = open(impl_file, 'w')
+        print >>impl_fp, factory.BodyPreamble(filename, header_file)
+        for entry in entities:
+            entry.PrintCode(impl_fp)
+        impl_fp.close()
+
+if __name__ == '__main__':
+    try:
+        CommandLine(sys.argv).run()
+        sys.exit(0)
+
+    except RpcGenError, e:
+        print >>sys.stderr, e
+        sys.exit(1)
+
+    except EnvironmentError, e:
+        if e.filename and e.strerror:
+            print >>sys.stderr, "%s: %s" % (e.filename, e.strerror)
+            sys.exit(1)
+        elif e.strerror:
+            print >> sys.stderr, e.strerror
+            sys.exit(1)
+        else:
+            raise
diff --git a/libevent/event_tagging.c b/libevent/event_tagging.c
new file mode 100644 (file)
index 0000000..a83e719
--- /dev/null
@@ -0,0 +1,590 @@
+/*
+ * Copyright (c) 2003-2009 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#else
+#include <sys/ioctl.h>
+#endif
+
+#include <sys/queue.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifndef WIN32
+#include <syslog.h>
+#endif
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <limits.h>
+
+#include "event2/event.h"
+#include "event2/tag.h"
+#include "event2/buffer.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+
+/*
+  Here's our wire format:
+
+  Stream = TaggedData*
+
+  TaggedData = Tag Length Data
+       where the integer value of 'Length' is the length of 'data'.
+
+  Tag = HByte* LByte
+       where HByte is a byte with the high bit set, and LByte is a byte
+       with the high bit clear. The integer value of the tag is taken
+       by concatenating the lower 7 bits from all the tags.  So for example,
+       the tag 0x66 is encoded as [66], whereas the tag 0x166 is encoded as
+       [82 66]
+
+  Length = Integer
+
+  Integer = NNibbles Nibble* Padding?
+       where NNibbles is a 4-bit value encoding the number of nibbles-1,
+       and each Nibble is 4 bits worth of encoded integer, in big-endian
+       order.  If the total encoded integer size is an odd number of nibbles,
+       a final padding nibble with value 0 is appended.
+*/
+
+int evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf);
+int evtag_decode_int64(ev_uint64_t *pnumber, struct evbuffer *evbuf);
+int evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t tag);
+int evtag_decode_tag(ev_uint32_t *ptag, struct evbuffer *evbuf);
+
+void
+evtag_init(void)
+{
+}
+
+/*
+ * We encode integers by nibbles; the first nibble contains the number
+ * of significant nibbles - 1;  this allows us to encode up to 64-bit
+ * integers.  This function is byte-order independent.
+ *
+ * @param number a 32-bit unsigned integer to encode
+ * @param data a pointer to where the data should be written.  Must
+ *    have at least 5 bytes free.
+ * @return the number of bytes written into data.
+ */
+
+#define ENCODE_INT_INTERNAL(data, number) do {                         \
+       int off = 1, nibbles = 0;                                       \
+                                                                       \
+       memset(data, 0, sizeof(number)+1);                              \
+       while (number) {                                                \
+               if (off & 0x1)                                          \
+                       data[off/2] = (data[off/2] & 0xf0) | (number & 0x0f); \
+               else                                                    \
+                       data[off/2] = (data[off/2] & 0x0f) |            \
+                           ((number & 0x0f) << 4);                     \
+               number >>= 4;                                           \
+               off++;                                                  \
+       }                                                               \
+                                                                       \
+       if (off > 2)                                                    \
+               nibbles = off - 2;                                      \
+                                                                       \
+       /* Off - 1 is the number of encoded nibbles */                  \
+       data[0] = (data[0] & 0x0f) | ((nibbles & 0x0f) << 4);           \
+                                                                       \
+       return ((off + 1) / 2);                                         \
+} while (0)
+
+static inline int
+encode_int_internal(ev_uint8_t *data, ev_uint32_t number)
+{
+       ENCODE_INT_INTERNAL(data, number);
+}
+
+static inline int
+encode_int64_internal(ev_uint8_t *data, ev_uint64_t number)
+{
+       ENCODE_INT_INTERNAL(data, number);
+}
+
+void
+evtag_encode_int(struct evbuffer *evbuf, ev_uint32_t number)
+{
+       ev_uint8_t data[5];
+       int len = encode_int_internal(data, number);
+       evbuffer_add(evbuf, data, len);
+}
+
+void
+evtag_encode_int64(struct evbuffer *evbuf, ev_uint64_t number)
+{
+       ev_uint8_t data[9];
+       int len = encode_int64_internal(data, number);
+       evbuffer_add(evbuf, data, len);
+}
+
+/*
+ * Support variable length encoding of tags; we use the high bit in each
+ * octet as a continuation signal.
+ */
+
+int
+evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t tag)
+{
+       int bytes = 0;
+       ev_uint8_t data[5];
+
+       memset(data, 0, sizeof(data));
+       do {
+               ev_uint8_t lower = tag & 0x7f;
+               tag >>= 7;
+
+               if (tag)
+                       lower |= 0x80;
+
+               data[bytes++] = lower;
+       } while (tag);
+
+       if (evbuf != NULL)
+               evbuffer_add(evbuf, data, bytes);
+
+       return (bytes);
+}
+
+static int
+decode_tag_internal(ev_uint32_t *ptag, struct evbuffer *evbuf, int dodrain)
+{
+       ev_uint32_t number = 0;
+       size_t len = evbuffer_get_length(evbuf);
+       ev_uint8_t *data;
+       size_t count = 0;
+       int  shift = 0, done = 0;
+
+       /*
+        * the encoding of a number is at most one byte more than its
+        * storage size.  however, it may also be much smaller.
+        */
+       data = evbuffer_pullup(
+               evbuf, len < sizeof(number) + 1 ? len : sizeof(number) + 1);
+
+       while (count++ < len) {
+               ev_uint8_t lower = *data++;
+               number |= (lower & 0x7f) << shift;
+               shift += 7;
+
+               if (!(lower & 0x80)) {
+                       done = 1;
+                       break;
+               }
+       }
+
+       if (!done)
+               return (-1);
+
+       if (dodrain)
+               evbuffer_drain(evbuf, count);
+
+       if (ptag != NULL)
+               *ptag = number;
+
+       return count > INT_MAX ? INT_MAX : (int)(count);
+}
+
+int
+evtag_decode_tag(ev_uint32_t *ptag, struct evbuffer *evbuf)
+{
+       return (decode_tag_internal(ptag, evbuf, 1 /* dodrain */));
+}
+
+/*
+ * Marshal a data type, the general format is as follows:
+ *
+ * tag number: one byte; length: var bytes; payload: var bytes
+ */
+
+void
+evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag,
+    const void *data, ev_uint32_t len)
+{
+       evtag_encode_tag(evbuf, tag);
+       evtag_encode_int(evbuf, len);
+       evbuffer_add(evbuf, (void *)data, len);
+}
+
+void
+evtag_marshal_buffer(struct evbuffer *evbuf, ev_uint32_t tag,
+    struct evbuffer *data)
+{
+       evtag_encode_tag(evbuf, tag);
+       /* XXX support more than UINT32_MAX data */
+       evtag_encode_int(evbuf, (ev_uint32_t)evbuffer_get_length(data));
+       evbuffer_add_buffer(evbuf, data);
+}
+
+/* Marshaling for integers */
+void
+evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag, ev_uint32_t integer)
+{
+       ev_uint8_t data[5];
+       int len = encode_int_internal(data, integer);
+
+       evtag_encode_tag(evbuf, tag);
+       evtag_encode_int(evbuf, len);
+       evbuffer_add(evbuf, data, len);
+}
+
+void
+evtag_marshal_int64(struct evbuffer *evbuf, ev_uint32_t tag,
+    ev_uint64_t integer)
+{
+       ev_uint8_t data[9];
+       int len = encode_int64_internal(data, integer);
+
+       evtag_encode_tag(evbuf, tag);
+       evtag_encode_int(evbuf, len);
+       evbuffer_add(evbuf, data, len);
+}
+
+void
+evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag, const char *string)
+{
+       /* TODO support strings longer than UINT32_MAX ? */
+       evtag_marshal(buf, tag, string, (ev_uint32_t)strlen(string));
+}
+
+void
+evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag, struct timeval *tv)
+{
+       ev_uint8_t data[10];
+       int len = encode_int_internal(data, tv->tv_sec);
+       len += encode_int_internal(data + len, tv->tv_usec);
+       evtag_marshal(evbuf, tag, data, len);
+}
+
+#define DECODE_INT_INTERNAL(number, maxnibbles, pnumber, evbuf, offset) \
+do {                                                                   \
+       ev_uint8_t *data;                                               \
+       ev_ssize_t len = evbuffer_get_length(evbuf) - offset;           \
+       int nibbles = 0;                                                \
+                                                                       \
+       if (len <= 0)                                                   \
+               return (-1);                                            \
+                                                                       \
+       /* XXX(niels): faster? */                                       \
+       data = evbuffer_pullup(evbuf, offset + 1) + offset;             \
+                                                                       \
+       nibbles = ((data[0] & 0xf0) >> 4) + 1;                          \
+       if (nibbles > maxnibbles || (nibbles >> 1) + 1 > len)           \
+               return (-1);                                            \
+       len = (nibbles >> 1) + 1;                                       \
+                                                                       \
+       data = evbuffer_pullup(evbuf, offset + len) + offset;           \
+                                                                       \
+       while (nibbles > 0) {                                           \
+               number <<= 4;                                           \
+               if (nibbles & 0x1)                                      \
+                       number |= data[nibbles >> 1] & 0x0f;            \
+               else                                                    \
+                       number |= (data[nibbles >> 1] & 0xf0) >> 4;     \
+               nibbles--;                                              \
+       }                                                               \
+                                                                       \
+       *pnumber = number;                                              \
+                                                                       \
+       return (int)(len);                                              \
+} while (0)
+
+/* Internal: decode an integer from an evbuffer, without draining it.
+ *  Only integers up to 32-bits are supported.
+ *
+ * @param evbuf the buffer to read from
+ * @param offset an index into the buffer at which we should start reading.
+ * @param pnumber a pointer to receive the integer.
+ * @return The length of the number as encoded, or -1 on error.
+ */
+
+static int
+decode_int_internal(ev_uint32_t *pnumber, struct evbuffer *evbuf, int offset)
+{
+       ev_uint32_t number = 0;
+       DECODE_INT_INTERNAL(number, 8, pnumber, evbuf, offset);
+}
+
+static int
+decode_int64_internal(ev_uint64_t *pnumber, struct evbuffer *evbuf, int offset)
+{
+       ev_uint64_t number = 0;
+       DECODE_INT_INTERNAL(number, 16, pnumber, evbuf, offset);
+}
+
+int
+evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf)
+{
+       int res = decode_int_internal(pnumber, evbuf, 0);
+       if (res != -1)
+               evbuffer_drain(evbuf, res);
+
+       return (res == -1 ? -1 : 0);
+}
+
+int
+evtag_decode_int64(ev_uint64_t *pnumber, struct evbuffer *evbuf)
+{
+       int res = decode_int64_internal(pnumber, evbuf, 0);
+       if (res != -1)
+               evbuffer_drain(evbuf, res);
+
+       return (res == -1 ? -1 : 0);
+}
+
+int
+evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag)
+{
+       return (decode_tag_internal(ptag, evbuf, 0 /* dodrain */));
+}
+
+int
+evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength)
+{
+       int res, len;
+
+       len = decode_tag_internal(NULL, evbuf, 0 /* dodrain */);
+       if (len == -1)
+               return (-1);
+
+       res = decode_int_internal(plength, evbuf, len);
+       if (res == -1)
+               return (-1);
+
+       *plength += res + len;
+
+       return (0);
+}
+
+int
+evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength)
+{
+       int res, len;
+
+       len = decode_tag_internal(NULL, evbuf, 0 /* dodrain */);
+       if (len == -1)
+               return (-1);
+
+       res = decode_int_internal(plength, evbuf, len);
+       if (res == -1)
+               return (-1);
+
+       return (0);
+}
+
+/* just unmarshals the header and returns the length of the remaining data */
+
+int
+evtag_unmarshal_header(struct evbuffer *evbuf, ev_uint32_t *ptag)
+{
+       ev_uint32_t len;
+
+       if (decode_tag_internal(ptag, evbuf, 1 /* dodrain */) == -1)
+               return (-1);
+       if (evtag_decode_int(&len, evbuf) == -1)
+               return (-1);
+
+       if (evbuffer_get_length(evbuf) < len)
+               return (-1);
+
+       return (len);
+}
+
+int
+evtag_consume(struct evbuffer *evbuf)
+{
+       int len;
+       if ((len = evtag_unmarshal_header(evbuf, NULL)) == -1)
+               return (-1);
+       evbuffer_drain(evbuf, len);
+
+       return (0);
+}
+
+/* Reads the data type from an event buffer */
+
+int
+evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag, struct evbuffer *dst)
+{
+       int len;
+
+       if ((len = evtag_unmarshal_header(src, ptag)) == -1)
+               return (-1);
+
+       if (evbuffer_add(dst, evbuffer_pullup(src, len), len) == -1)
+               return (-1);
+
+       evbuffer_drain(src, len);
+
+       return (len);
+}
+
+/* Marshaling for integers */
+
+int
+evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
+    ev_uint32_t *pinteger)
+{
+       ev_uint32_t tag;
+       ev_uint32_t len;
+       int result;
+
+       if (decode_tag_internal(&tag, evbuf, 1 /* dodrain */) == -1)
+               return (-1);
+       if (need_tag != tag)
+               return (-1);
+       if (evtag_decode_int(&len, evbuf) == -1)
+               return (-1);
+
+       if (evbuffer_get_length(evbuf) < len)
+               return (-1);
+
+       result = decode_int_internal(pinteger, evbuf, 0);
+       evbuffer_drain(evbuf, len);
+       if (result < 0 || (size_t)result > len) /* XXX Should this be != rather than > ?*/
+               return (-1);
+       else
+               return result;
+}
+
+int
+evtag_unmarshal_int64(struct evbuffer *evbuf, ev_uint32_t need_tag,
+    ev_uint64_t *pinteger)
+{
+       ev_uint32_t tag;
+       ev_uint32_t len;
+       int result;
+
+       if (decode_tag_internal(&tag, evbuf, 1 /* dodrain */) == -1)
+               return (-1);
+       if (need_tag != tag)
+               return (-1);
+       if (evtag_decode_int(&len, evbuf) == -1)
+               return (-1);
+
+       if (evbuffer_get_length(evbuf) < len)
+               return (-1);
+
+       result = decode_int64_internal(pinteger, evbuf, 0);
+       evbuffer_drain(evbuf, len);
+       if (result < 0 || (size_t)result > len) /* XXX Should this be != rather than > ?*/
+               return (-1);
+       else
+               return result;
+}
+
+/* Unmarshal a fixed length tag */
+
+int
+evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag, void *data,
+    size_t len)
+{
+       ev_uint32_t tag;
+       int tag_len;
+
+       /* Now unmarshal a tag and check that it matches the tag we want */
+       if ((tag_len = evtag_unmarshal_header(src, &tag)) < 0 ||
+           tag != need_tag)
+               return (-1);
+
+       if ((size_t)tag_len != len)
+               return (-1);
+
+       evbuffer_remove(src, data, len);
+       return (0);
+}
+
+int
+evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
+    char **pstring)
+{
+       ev_uint32_t tag;
+       int tag_len;
+
+       if ((tag_len = evtag_unmarshal_header(evbuf, &tag)) == -1 ||
+           tag != need_tag)
+               return (-1);
+
+       *pstring = mm_malloc(tag_len + 1);
+       if (*pstring == NULL) {
+               event_warn("%s: malloc", __func__);
+               return -1;
+       }
+       evbuffer_remove(evbuf, *pstring, tag_len);
+       (*pstring)[tag_len] = '\0';
+
+       return (0);
+}
+
+int
+evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
+    struct timeval *ptv)
+{
+       ev_uint32_t tag;
+       ev_uint32_t integer;
+       int len, offset, offset2;
+       int result = -1;
+
+       if ((len = evtag_unmarshal_header(evbuf, &tag)) == -1)
+               return (-1);
+       if (tag != need_tag)
+               goto done;
+       if ((offset = decode_int_internal(&integer, evbuf, 0)) == -1)
+               goto done;
+       ptv->tv_sec = integer;
+       if ((offset2 = decode_int_internal(&integer, evbuf, offset)) == -1)
+               goto done;
+       ptv->tv_usec = integer;
+       if (offset + offset2 > len) /* XXX Should this be != instead of > ? */
+               goto done;
+
+       result = 0;
+ done:
+       evbuffer_drain(evbuf, len);
+       return result;
+}
diff --git a/libevent/evhttp.h b/libevent/evhttp.h
new file mode 100644 (file)
index 0000000..5ce15e6
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVHTTP_H_
+#define _EVHTTP_H_
+
+/** @file evhttp.h
+
+  An http implementation subsystem for Libevent.
+
+  The <evhttp.h> header is deprecated in Libevent 2.0 and later; please
+  use <event2/http.h> instead.  Depending on what functionality you
+  need, you may also want to include more of the other <event2/...>
+  headers.
+ */
+
+#include <event.h>
+#include <event2/http.h>
+#include <event2/http_struct.h>
+#include <event2/http_compat.h>
+
+#endif /* _EVHTTP_H_ */
diff --git a/libevent/evmap-internal.h b/libevent/evmap-internal.h
new file mode 100644 (file)
index 0000000..23b5a8a
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVMAP_H_
+#define _EVMAP_H_
+
+/** @file evmap-internal.h
+ *
+ * An event_map is a utility structure to map each fd or signal to zero or
+ * more events.  Functions to manipulate event_maps should only be used from
+ * inside libevent.  They generally need to hold the lock on the corresponding
+ * event_base.
+ **/
+
+struct event_base;
+struct event;
+
+/** Initialize an event_map for use.
+ */
+void evmap_io_initmap(struct event_io_map* ctx);
+void evmap_signal_initmap(struct event_signal_map* ctx);
+
+/** Remove all entries from an event_map.
+
+       @param ctx the map to clear.
+ */
+void evmap_io_clear(struct event_io_map* ctx);
+void evmap_signal_clear(struct event_signal_map* ctx);
+
+/** Add an IO event (some combination of EV_READ or EV_WRITE) to an
+    event_base's list of events on a given file descriptor, and tell the
+    underlying eventops about the fd if its state has changed.
+
+    Requires that ev is not already added.
+
+    @param base the event_base to operate on.
+    @param fd the file descriptor corresponding to ev.
+    @param ev the event to add.
+*/
+int evmap_io_add(struct event_base *base, evutil_socket_t fd, struct event *ev);
+/** Remove an IO event (some combination of EV_READ or EV_WRITE) to an
+    event_base's list of events on a given file descriptor, and tell the
+    underlying eventops about the fd if its state has changed.
+
+    @param base the event_base to operate on.
+    @param fd the file descriptor corresponding to ev.
+    @param ev the event to remove.
+ */
+int evmap_io_del(struct event_base *base, evutil_socket_t fd, struct event *ev);
+/** Active the set of events waiting on an event_base for a given fd.
+
+    @param base the event_base to operate on.
+    @param fd the file descriptor that has become active.
+    @param events a bitmask of EV_READ|EV_WRITE|EV_ET.
+*/
+void evmap_io_active(struct event_base *base, evutil_socket_t fd, short events);
+
+
+/* These functions behave in the same way as evmap_io_*, except they work on
+ * signals rather than fds.  signals use a linear map everywhere; fds use
+ * either a linear map or a hashtable. */
+int evmap_signal_add(struct event_base *base, int signum, struct event *ev);
+int evmap_signal_del(struct event_base *base, int signum, struct event *ev);
+void evmap_signal_active(struct event_base *base, evutil_socket_t signum, int ncalls);
+
+void *evmap_io_get_fdinfo(struct event_io_map *ctx, evutil_socket_t fd);
+
+void evmap_check_integrity(struct event_base *base);
+
+#endif /* _EVMAP_H_ */
diff --git a/libevent/evmap.c b/libevent/evmap.c
new file mode 100644 (file)
index 0000000..69c1067
--- /dev/null
@@ -0,0 +1,799 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+#include <sys/types.h>
+#if !defined(WIN32) && defined(_EVENT_HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <stdio.h>
+#include <stdlib.h>
+#ifndef WIN32
+#include <unistd.h>
+#endif
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+#include <time.h>
+
+#include "event-internal.h"
+#include "evmap-internal.h"
+#include "mm-internal.h"
+#include "changelist-internal.h"
+
+/** An entry for an evmap_io list: notes all the events that want to read or
+       write on a given fd, and the number of each.
+  */
+struct evmap_io {
+       struct event_list events;
+       ev_uint16_t nread;
+       ev_uint16_t nwrite;
+};
+
+/* An entry for an evmap_signal list: notes all the events that want to know
+   when a signal triggers. */
+struct evmap_signal {
+       struct event_list events;
+};
+
+/* On some platforms, fds start at 0 and increment by 1 as they are
+   allocated, and old numbers get used.  For these platforms, we
+   implement io maps just like signal maps: as an array of pointers to
+   struct evmap_io.  But on other platforms (windows), sockets are not
+   0-indexed, not necessarily consecutive, and not necessarily reused.
+   There, we use a hashtable to implement evmap_io.
+*/
+#ifdef EVMAP_USE_HT
+struct event_map_entry {
+       HT_ENTRY(event_map_entry) map_node;
+       evutil_socket_t fd;
+       union { /* This is a union in case we need to make more things that can
+                          be in the hashtable. */
+               struct evmap_io evmap_io;
+       } ent;
+};
+
+/* Helper used by the event_io_map hashtable code; tries to return a good hash
+ * of the fd in e->fd. */
+static inline unsigned
+hashsocket(struct event_map_entry *e)
+{
+       /* On win32, in practice, the low 2-3 bits of a SOCKET seem not to
+        * matter.  Our hashtable implementation really likes low-order bits,
+        * though, so let's do the rotate-and-add trick. */
+       unsigned h = (unsigned) e->fd;
+       h += (h >> 2) | (h << 30);
+       return h;
+}
+
+/* Helper used by the event_io_map hashtable code; returns true iff e1 and e2
+ * have the same e->fd. */
+static inline int
+eqsocket(struct event_map_entry *e1, struct event_map_entry *e2)
+{
+       return e1->fd == e2->fd;
+}
+
+HT_PROTOTYPE(event_io_map, event_map_entry, map_node, hashsocket, eqsocket)
+HT_GENERATE(event_io_map, event_map_entry, map_node, hashsocket, eqsocket,
+                       0.5, mm_malloc, mm_realloc, mm_free)
+
+#define GET_IO_SLOT(x, map, slot, type)                                        \
+       do {                                                            \
+               struct event_map_entry _key, *_ent;                     \
+               _key.fd = slot;                                         \
+               _ent = HT_FIND(event_io_map, map, &_key);               \
+               (x) = _ent ? &_ent->ent.type : NULL;                    \
+       } while (0);
+
+#define GET_IO_SLOT_AND_CTOR(x, map, slot, type, ctor, fdinfo_len)     \
+       do {                                                            \
+               struct event_map_entry _key, *_ent;                     \
+               _key.fd = slot;                                         \
+               _HT_FIND_OR_INSERT(event_io_map, map_node, hashsocket, map, \
+                   event_map_entry, &_key, ptr,                        \
+                   {                                                   \
+                           _ent = *ptr;                                \
+                   },                                                  \
+                   {                                                   \
+                           _ent = mm_calloc(1,sizeof(struct event_map_entry)+fdinfo_len); \
+                           if (EVUTIL_UNLIKELY(_ent == NULL))          \
+                                   return (-1);                        \
+                           _ent->fd = slot;                            \
+                           (ctor)(&_ent->ent.type);                    \
+                           _HT_FOI_INSERT(map_node, map, &_key, _ent, ptr) \
+                               });                                     \
+               (x) = &_ent->ent.type;                                  \
+       } while (0)
+
+void evmap_io_initmap(struct event_io_map *ctx)
+{
+       HT_INIT(event_io_map, ctx);
+}
+
+void evmap_io_clear(struct event_io_map *ctx)
+{
+       struct event_map_entry **ent, **next, *this;
+       for (ent = HT_START(event_io_map, ctx); ent; ent = next) {
+               this = *ent;
+               next = HT_NEXT_RMV(event_io_map, ctx, ent);
+               mm_free(this);
+       }
+       HT_CLEAR(event_io_map, ctx); /* remove all storage held by the ctx. */
+}
+#endif
+
+/* Set the variable 'x' to the field in event_map 'map' with fields of type
+   'struct type *' corresponding to the fd or signal 'slot'.  Set 'x' to NULL
+   if there are no entries for 'slot'.  Does no bounds-checking. */
+#define GET_SIGNAL_SLOT(x, map, slot, type)                    \
+       (x) = (struct type *)((map)->entries[slot])
+/* As GET_SLOT, but construct the entry for 'slot' if it is not present,
+   by allocating enough memory for a 'struct type', and initializing the new
+   value by calling the function 'ctor' on it.  Makes the function
+   return -1 on allocation failure.
+ */
+#define GET_SIGNAL_SLOT_AND_CTOR(x, map, slot, type, ctor, fdinfo_len) \
+       do {                                                            \
+               if ((map)->entries[slot] == NULL) {                     \
+                       (map)->entries[slot] =                          \
+                           mm_calloc(1,sizeof(struct type)+fdinfo_len); \
+                       if (EVUTIL_UNLIKELY((map)->entries[slot] == NULL)) \
+                               return (-1);                            \
+                       (ctor)((struct type *)(map)->entries[slot]);    \
+               }                                                       \
+               (x) = (struct type *)((map)->entries[slot]);            \
+       } while (0)
+
+/* If we aren't using hashtables, then define the IO_SLOT macros and functions
+   as thin aliases over the SIGNAL_SLOT versions. */
+#ifndef EVMAP_USE_HT
+#define GET_IO_SLOT(x,map,slot,type) GET_SIGNAL_SLOT(x,map,slot,type)
+#define GET_IO_SLOT_AND_CTOR(x,map,slot,type,ctor,fdinfo_len)  \
+       GET_SIGNAL_SLOT_AND_CTOR(x,map,slot,type,ctor,fdinfo_len)
+#define FDINFO_OFFSET sizeof(struct evmap_io)
+void
+evmap_io_initmap(struct event_io_map* ctx)
+{
+       evmap_signal_initmap(ctx);
+}
+void
+evmap_io_clear(struct event_io_map* ctx)
+{
+       evmap_signal_clear(ctx);
+}
+#endif
+
+
+/** Expand 'map' with new entries of width 'msize' until it is big enough
+       to store a value in 'slot'.
+ */
+static int
+evmap_make_space(struct event_signal_map *map, int slot, int msize)
+{
+       if (map->nentries <= slot) {
+               int nentries = map->nentries ? map->nentries : 32;
+               void **tmp;
+
+               while (nentries <= slot)
+                       nentries <<= 1;
+
+               tmp = (void **)mm_realloc(map->entries, nentries * msize);
+               if (tmp == NULL)
+                       return (-1);
+
+               memset(&tmp[map->nentries], 0,
+                   (nentries - map->nentries) * msize);
+
+               map->nentries = nentries;
+               map->entries = tmp;
+       }
+
+       return (0);
+}
+
+void
+evmap_signal_initmap(struct event_signal_map *ctx)
+{
+       ctx->nentries = 0;
+       ctx->entries = NULL;
+}
+
+void
+evmap_signal_clear(struct event_signal_map *ctx)
+{
+       if (ctx->entries != NULL) {
+               int i;
+               for (i = 0; i < ctx->nentries; ++i) {
+                       if (ctx->entries[i] != NULL)
+                               mm_free(ctx->entries[i]);
+               }
+               mm_free(ctx->entries);
+               ctx->entries = NULL;
+       }
+       ctx->nentries = 0;
+}
+
+
+/* code specific to file descriptors */
+
+/** Constructor for struct evmap_io */
+static void
+evmap_io_init(struct evmap_io *entry)
+{
+       TAILQ_INIT(&entry->events);
+       entry->nread = 0;
+       entry->nwrite = 0;
+}
+
+
+/* return -1 on error, 0 on success if nothing changed in the event backend,
+ * and 1 on success if something did. */
+int
+evmap_io_add(struct event_base *base, evutil_socket_t fd, struct event *ev)
+{
+       const struct eventop *evsel = base->evsel;
+       struct event_io_map *io = &base->io;
+       struct evmap_io *ctx = NULL;
+       int nread, nwrite, retval = 0;
+       short res = 0, old = 0;
+       struct event *old_ev;
+
+       EVUTIL_ASSERT(fd == ev->ev_fd);
+
+       if (fd < 0)
+               return 0;
+
+#ifndef EVMAP_USE_HT
+       if (fd >= io->nentries) {
+               if (evmap_make_space(io, fd, sizeof(struct evmap_io *)) == -1)
+                       return (-1);
+       }
+#endif
+       GET_IO_SLOT_AND_CTOR(ctx, io, fd, evmap_io, evmap_io_init,
+                                                evsel->fdinfo_len);
+
+       nread = ctx->nread;
+       nwrite = ctx->nwrite;
+
+       if (nread)
+               old |= EV_READ;
+       if (nwrite)
+               old |= EV_WRITE;
+
+       if (ev->ev_events & EV_READ) {
+               if (++nread == 1)
+                       res |= EV_READ;
+       }
+       if (ev->ev_events & EV_WRITE) {
+               if (++nwrite == 1)
+                       res |= EV_WRITE;
+       }
+       if (EVUTIL_UNLIKELY(nread > 0xffff || nwrite > 0xffff)) {
+               event_warnx("Too many events reading or writing on fd %d",
+                   (int)fd);
+               return -1;
+       }
+       if (EVENT_DEBUG_MODE_IS_ON() &&
+           (old_ev = TAILQ_FIRST(&ctx->events)) &&
+           (old_ev->ev_events&EV_ET) != (ev->ev_events&EV_ET)) {
+               event_warnx("Tried to mix edge-triggered and non-edge-triggered"
+                   " events on fd %d", (int)fd);
+               return -1;
+       }
+
+       if (res) {
+               void *extra = ((char*)ctx) + sizeof(struct evmap_io);
+               /* XXX(niels): we cannot mix edge-triggered and
+                * level-triggered, we should probably assert on
+                * this. */
+               if (evsel->add(base, ev->ev_fd,
+                       old, (ev->ev_events & EV_ET) | res, extra) == -1)
+                       return (-1);
+               retval = 1;
+       }
+
+       ctx->nread = (ev_uint16_t) nread;
+       ctx->nwrite = (ev_uint16_t) nwrite;
+       TAILQ_INSERT_TAIL(&ctx->events, ev, ev_io_next);
+
+       return (retval);
+}
+
+/* return -1 on error, 0 on success if nothing changed in the event backend,
+ * and 1 on success if something did. */
+int
+evmap_io_del(struct event_base *base, evutil_socket_t fd, struct event *ev)
+{
+       const struct eventop *evsel = base->evsel;
+       struct event_io_map *io = &base->io;
+       struct evmap_io *ctx;
+       int nread, nwrite, retval = 0;
+       short res = 0, old = 0;
+
+       if (fd < 0)
+               return 0;
+
+       EVUTIL_ASSERT(fd == ev->ev_fd);
+
+#ifndef EVMAP_USE_HT
+       if (fd >= io->nentries)
+               return (-1);
+#endif
+
+       GET_IO_SLOT(ctx, io, fd, evmap_io);
+
+       nread = ctx->nread;
+       nwrite = ctx->nwrite;
+
+       if (nread)
+               old |= EV_READ;
+       if (nwrite)
+               old |= EV_WRITE;
+
+       if (ev->ev_events & EV_READ) {
+               if (--nread == 0)
+                       res |= EV_READ;
+               EVUTIL_ASSERT(nread >= 0);
+       }
+       if (ev->ev_events & EV_WRITE) {
+               if (--nwrite == 0)
+                       res |= EV_WRITE;
+               EVUTIL_ASSERT(nwrite >= 0);
+       }
+
+       if (res) {
+               void *extra = ((char*)ctx) + sizeof(struct evmap_io);
+               if (evsel->del(base, ev->ev_fd, old, res, extra) == -1)
+                       return (-1);
+               retval = 1;
+       }
+
+       ctx->nread = nread;
+       ctx->nwrite = nwrite;
+       TAILQ_REMOVE(&ctx->events, ev, ev_io_next);
+
+       return (retval);
+}
+
+void
+evmap_io_active(struct event_base *base, evutil_socket_t fd, short events)
+{
+       struct event_io_map *io = &base->io;
+       struct evmap_io *ctx;
+       struct event *ev;
+
+#ifndef EVMAP_USE_HT
+       EVUTIL_ASSERT(fd < io->nentries);
+#endif
+       GET_IO_SLOT(ctx, io, fd, evmap_io);
+
+       EVUTIL_ASSERT(ctx);
+       TAILQ_FOREACH(ev, &ctx->events, ev_io_next) {
+               if (ev->ev_events & events)
+                       event_active_nolock(ev, ev->ev_events & events, 1);
+       }
+}
+
+/* code specific to signals */
+
+static void
+evmap_signal_init(struct evmap_signal *entry)
+{
+       TAILQ_INIT(&entry->events);
+}
+
+
+int
+evmap_signal_add(struct event_base *base, int sig, struct event *ev)
+{
+       const struct eventop *evsel = base->evsigsel;
+       struct event_signal_map *map = &base->sigmap;
+       struct evmap_signal *ctx = NULL;
+
+       if (sig >= map->nentries) {
+               if (evmap_make_space(
+                       map, sig, sizeof(struct evmap_signal *)) == -1)
+                       return (-1);
+       }
+       GET_SIGNAL_SLOT_AND_CTOR(ctx, map, sig, evmap_signal, evmap_signal_init,
+           base->evsigsel->fdinfo_len);
+
+       if (TAILQ_EMPTY(&ctx->events)) {
+               if (evsel->add(base, ev->ev_fd, 0, EV_SIGNAL, NULL)
+                   == -1)
+                       return (-1);
+       }
+
+       TAILQ_INSERT_TAIL(&ctx->events, ev, ev_signal_next);
+
+       return (1);
+}
+
+int
+evmap_signal_del(struct event_base *base, int sig, struct event *ev)
+{
+       const struct eventop *evsel = base->evsigsel;
+       struct event_signal_map *map = &base->sigmap;
+       struct evmap_signal *ctx;
+
+       if (sig >= map->nentries)
+               return (-1);
+
+       GET_SIGNAL_SLOT(ctx, map, sig, evmap_signal);
+
+       if (TAILQ_FIRST(&ctx->events) == TAILQ_LAST(&ctx->events, event_list)) {
+               if (evsel->del(base, ev->ev_fd, 0, EV_SIGNAL, NULL) == -1)
+                       return (-1);
+       }
+
+       TAILQ_REMOVE(&ctx->events, ev, ev_signal_next);
+
+       return (1);
+}
+
+void
+evmap_signal_active(struct event_base *base, evutil_socket_t sig, int ncalls)
+{
+       struct event_signal_map *map = &base->sigmap;
+       struct evmap_signal *ctx;
+       struct event *ev;
+
+       EVUTIL_ASSERT(sig < map->nentries);
+       GET_SIGNAL_SLOT(ctx, map, sig, evmap_signal);
+
+       TAILQ_FOREACH(ev, &ctx->events, ev_signal_next)
+               event_active_nolock(ev, EV_SIGNAL, ncalls);
+}
+
+void *
+evmap_io_get_fdinfo(struct event_io_map *map, evutil_socket_t fd)
+{
+       struct evmap_io *ctx;
+       GET_IO_SLOT(ctx, map, fd, evmap_io);
+       if (ctx)
+               return ((char*)ctx) + sizeof(struct evmap_io);
+       else
+               return NULL;
+}
+
+/** Per-fd structure for use with changelists.  It keeps track, for each fd or
+ * signal using the changelist, of where its entry in the changelist is.
+ */
+struct event_changelist_fdinfo {
+       int idxplus1; /* this is the index +1, so that memset(0) will make it
+                      * a no-such-element */
+};
+
+void
+event_changelist_init(struct event_changelist *changelist)
+{
+       changelist->changes = NULL;
+       changelist->changes_size = 0;
+       changelist->n_changes = 0;
+}
+
+/** Helper: return the changelist_fdinfo corresponding to a given change. */
+static inline struct event_changelist_fdinfo *
+event_change_get_fdinfo(struct event_base *base,
+    const struct event_change *change)
+{
+       char *ptr;
+       if (change->read_change & EV_CHANGE_SIGNAL) {
+               struct evmap_signal *ctx;
+               GET_SIGNAL_SLOT(ctx, &base->sigmap, change->fd, evmap_signal);
+               ptr = ((char*)ctx) + sizeof(struct evmap_signal);
+       } else {
+               struct evmap_io *ctx;
+               GET_IO_SLOT(ctx, &base->io, change->fd, evmap_io);
+               ptr = ((char*)ctx) + sizeof(struct evmap_io);
+       }
+       return (void*)ptr;
+}
+
+#ifdef DEBUG_CHANGELIST
+/** Make sure that the changelist is consistent with the evmap structures. */
+static void
+event_changelist_check(struct event_base *base)
+{
+       int i;
+       struct event_changelist *changelist = &base->changelist;
+
+       EVUTIL_ASSERT(changelist->changes_size >= changelist->n_changes);
+       for (i = 0; i < changelist->n_changes; ++i) {
+               struct event_change *c = &changelist->changes[i];
+               struct event_changelist_fdinfo *f;
+               EVUTIL_ASSERT(c->fd >= 0);
+               f = event_change_get_fdinfo(base, c);
+               EVUTIL_ASSERT(f);
+               EVUTIL_ASSERT(f->idxplus1 == i + 1);
+       }
+
+       for (i = 0; i < base->io.nentries; ++i) {
+               struct evmap_io *io = base->io.entries[i];
+               struct event_changelist_fdinfo *f;
+               if (!io)
+                       continue;
+               f = (void*)
+                   ( ((char*)io) + sizeof(struct evmap_io) );
+               if (f->idxplus1) {
+                       struct event_change *c = &changelist->changes[f->idxplus1 - 1];
+                       EVUTIL_ASSERT(c->fd == i);
+               }
+       }
+}
+#else
+#define event_changelist_check(base)  ((void)0)
+#endif
+
+void
+event_changelist_remove_all(struct event_changelist *changelist,
+    struct event_base *base)
+{
+       int i;
+
+       event_changelist_check(base);
+
+       for (i = 0; i < changelist->n_changes; ++i) {
+               struct event_change *ch = &changelist->changes[i];
+               struct event_changelist_fdinfo *fdinfo =
+                   event_change_get_fdinfo(base, ch);
+               EVUTIL_ASSERT(fdinfo->idxplus1 == i + 1);
+               fdinfo->idxplus1 = 0;
+       }
+
+       changelist->n_changes = 0;
+
+       event_changelist_check(base);
+}
+
+void
+event_changelist_freemem(struct event_changelist *changelist)
+{
+       if (changelist->changes)
+               mm_free(changelist->changes);
+       event_changelist_init(changelist); /* zero it all out. */
+}
+
+/** Increase the size of 'changelist' to hold more changes. */
+static int
+event_changelist_grow(struct event_changelist *changelist)
+{
+       int new_size;
+       struct event_change *new_changes;
+       if (changelist->changes_size < 64)
+               new_size = 64;
+       else
+               new_size = changelist->changes_size * 2;
+
+       new_changes = mm_realloc(changelist->changes,
+           new_size * sizeof(struct event_change));
+
+       if (EVUTIL_UNLIKELY(new_changes == NULL))
+               return (-1);
+
+       changelist->changes = new_changes;
+       changelist->changes_size = new_size;
+
+       return (0);
+}
+
+/** Return a pointer to the changelist entry for the file descriptor or signal
+ * 'fd', whose fdinfo is 'fdinfo'.  If none exists, construct it, setting its
+ * old_events field to old_events.
+ */
+static struct event_change *
+event_changelist_get_or_construct(struct event_changelist *changelist,
+    evutil_socket_t fd,
+    short old_events,
+    struct event_changelist_fdinfo *fdinfo)
+{
+       struct event_change *change;
+
+       if (fdinfo->idxplus1 == 0) {
+               int idx;
+               EVUTIL_ASSERT(changelist->n_changes <= changelist->changes_size);
+
+               if (changelist->n_changes == changelist->changes_size) {
+                       if (event_changelist_grow(changelist) < 0)
+                               return NULL;
+               }
+
+               idx = changelist->n_changes++;
+               change = &changelist->changes[idx];
+               fdinfo->idxplus1 = idx + 1;
+
+               memset(change, 0, sizeof(struct event_change));
+               change->fd = fd;
+               change->old_events = old_events;
+       } else {
+               change = &changelist->changes[fdinfo->idxplus1 - 1];
+               EVUTIL_ASSERT(change->fd == fd);
+       }
+       return change;
+}
+
+int
+event_changelist_add(struct event_base *base, evutil_socket_t fd, short old, short events,
+    void *p)
+{
+       struct event_changelist *changelist = &base->changelist;
+       struct event_changelist_fdinfo *fdinfo = p;
+       struct event_change *change;
+
+       event_changelist_check(base);
+
+       change = event_changelist_get_or_construct(changelist, fd, old, fdinfo);
+       if (!change)
+               return -1;
+
+       /* An add replaces any previous delete, but doesn't result in a no-op,
+        * since the delete might fail (because the fd had been closed since
+        * the last add, for instance. */
+
+       if (events & (EV_READ|EV_SIGNAL)) {
+               change->read_change = EV_CHANGE_ADD |
+                   (events & (EV_ET|EV_PERSIST|EV_SIGNAL));
+       }
+       if (events & EV_WRITE) {
+               change->write_change = EV_CHANGE_ADD |
+                   (events & (EV_ET|EV_PERSIST|EV_SIGNAL));
+       }
+
+       event_changelist_check(base);
+       return (0);
+}
+
+int
+event_changelist_del(struct event_base *base, evutil_socket_t fd, short old, short events,
+    void *p)
+{
+       struct event_changelist *changelist = &base->changelist;
+       struct event_changelist_fdinfo *fdinfo = p;
+       struct event_change *change;
+
+       event_changelist_check(base);
+       change = event_changelist_get_or_construct(changelist, fd, old, fdinfo);
+       event_changelist_check(base);
+       if (!change)
+               return -1;
+
+       /* A delete removes any previous add, rather than replacing it:
+          on those platforms where "add, delete, dispatch" is not the same
+          as "no-op, dispatch", we want the no-op behavior.
+
+          As well as checking the current operation we should also check
+          the original set of events to make sure were not ignoring
+          the case where the add operation is present on an event that
+          was already set.
+
+          If we have a no-op item, we could remove it it from the list
+          entirely, but really there's not much point: skipping the no-op
+          change when we do the dispatch later is far cheaper than rejuggling
+          the array now.
+
+          As this stands, it also lets through deletions of events that are
+          not currently set.
+        */
+
+       if (events & (EV_READ|EV_SIGNAL)) {
+               if (!(change->old_events & (EV_READ | EV_SIGNAL)) &&
+                   (change->read_change & EV_CHANGE_ADD))
+                       change->read_change = 0;
+               else
+                       change->read_change = EV_CHANGE_DEL;
+       }
+       if (events & EV_WRITE) {
+               if (!(change->old_events & EV_WRITE) &&
+                   (change->write_change & EV_CHANGE_ADD))
+                       change->write_change = 0;
+               else
+                       change->write_change = EV_CHANGE_DEL;
+       }
+
+       event_changelist_check(base);
+       return (0);
+}
+
+void
+evmap_check_integrity(struct event_base *base)
+{
+#define EVLIST_X_SIGFOUND 0x1000
+#define EVLIST_X_IOFOUND 0x2000
+
+       evutil_socket_t i;
+       struct event *ev;
+       struct event_io_map *io = &base->io;
+       struct event_signal_map *sigmap = &base->sigmap;
+#ifdef EVMAP_USE_HT
+       struct event_map_entry **mapent;
+#endif
+       int nsignals, ntimers, nio;
+       nsignals = ntimers = nio = 0;
+
+       TAILQ_FOREACH(ev, &base->eventqueue, ev_next) {
+               EVUTIL_ASSERT(ev->ev_flags & EVLIST_INSERTED);
+               EVUTIL_ASSERT(ev->ev_flags & EVLIST_INIT);
+               ev->ev_flags &= ~(EVLIST_X_SIGFOUND|EVLIST_X_IOFOUND);
+       }
+
+#ifdef EVMAP_USE_HT
+       HT_FOREACH(mapent, event_io_map, io) {
+               struct evmap_io *ctx = &(*mapent)->ent.evmap_io;
+               i = (*mapent)->fd;
+#else
+       for (i = 0; i < io->nentries; ++i) {
+               struct evmap_io *ctx = io->entries[i];
+
+               if (!ctx)
+                       continue;
+#endif
+
+               TAILQ_FOREACH(ev, &ctx->events, ev_io_next) {
+                       EVUTIL_ASSERT(!(ev->ev_flags & EVLIST_X_IOFOUND));
+                       EVUTIL_ASSERT(ev->ev_fd == i);
+                       ev->ev_flags |= EVLIST_X_IOFOUND;
+                       nio++;
+               }
+       }
+
+       for (i = 0; i < sigmap->nentries; ++i) {
+               struct evmap_signal *ctx = sigmap->entries[i];
+               if (!ctx)
+                       continue;
+
+               TAILQ_FOREACH(ev, &ctx->events, ev_signal_next) {
+                       EVUTIL_ASSERT(!(ev->ev_flags & EVLIST_X_SIGFOUND));
+                       EVUTIL_ASSERT(ev->ev_fd == i);
+                       ev->ev_flags |= EVLIST_X_SIGFOUND;
+                       nsignals++;
+               }
+       }
+
+       TAILQ_FOREACH(ev, &base->eventqueue, ev_next) {
+               if (ev->ev_events & (EV_READ|EV_WRITE)) {
+                       EVUTIL_ASSERT(ev->ev_flags & EVLIST_X_IOFOUND);
+                       --nio;
+               }
+               if (ev->ev_events & EV_SIGNAL) {
+                       EVUTIL_ASSERT(ev->ev_flags & EVLIST_X_SIGFOUND);
+                       --nsignals;
+               }
+       }
+
+       EVUTIL_ASSERT(nio == 0);
+       EVUTIL_ASSERT(nsignals == 0);
+       /* There is no "EVUTIL_ASSERT(ntimers == 0)": eventqueue is only for
+        * pending signals and io events.
+        */
+}
diff --git a/libevent/evport.c b/libevent/evport.c
new file mode 100644 (file)
index 0000000..0d714d8
--- /dev/null
@@ -0,0 +1,473 @@
+/*
+ * Submitted by David Pacheco (dp.spambait@gmail.com)
+ *
+ * Copyright 2006-2007 Niels Provos
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY SUN MICROSYSTEMS, INC. ``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 SUN MICROSYSTEMS, INC. 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) 2007 Sun Microsystems. All rights reserved.
+ * Use is subject to license terms.
+ */
+
+/*
+ * evport.c: event backend using Solaris 10 event ports. See port_create(3C).
+ * This implementation is loosely modeled after the one used for select(2) (in
+ * select.c).
+ *
+ * The outstanding events are tracked in a data structure called evport_data.
+ * Each entry in the ed_fds array corresponds to a file descriptor, and contains
+ * pointers to the read and write events that correspond to that fd. (That is,
+ * when the file is readable, the "read" event should handle it, etc.)
+ *
+ * evport_add and evport_del update this data structure. evport_dispatch uses it
+ * to determine where to callback when an event occurs (which it gets from
+ * port_getn).
+ *
+ * Helper functions are used: grow() grows the file descriptor array as
+ * necessary when large fd's come in. reassociate() takes care of maintaining
+ * the proper file-descriptor/event-port associations.
+ *
+ * As in the select(2) implementation, signals are handled by evsignal.
+ */
+
+#include "event2/event-config.h"
+
+#include <sys/time.h>
+#include <sys/queue.h>
+#include <errno.h>
+#include <poll.h>
+#include <port.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "event2/thread.h"
+
+#include "evthread-internal.h"
+#include "event-internal.h"
+#include "log-internal.h"
+#include "evsignal-internal.h"
+#include "evmap-internal.h"
+
+/*
+ * Default value for ed_nevents, which is the maximum file descriptor number we
+ * can handle. If an event comes in for a file descriptor F > nevents, we will
+ * grow the array of file descriptors, doubling its size.
+ */
+#define DEFAULT_NFDS   16
+
+
+/*
+ * EVENTS_PER_GETN is the maximum number of events to retrieve from port_getn on
+ * any particular call. You can speed things up by increasing this, but it will
+ * (obviously) require more memory.
+ */
+#define EVENTS_PER_GETN 8
+
+/*
+ * Per-file-descriptor information about what events we're subscribed to. These
+ * fields are NULL if no event is subscribed to either of them.
+ */
+
+struct fd_info {
+       short fdi_what;         /* combinations of EV_READ and EV_WRITE */
+};
+
+#define FDI_HAS_READ(fdi)  ((fdi)->fdi_what & EV_READ)
+#define FDI_HAS_WRITE(fdi) ((fdi)->fdi_what & EV_WRITE)
+#define FDI_HAS_EVENTS(fdi) (FDI_HAS_READ(fdi) || FDI_HAS_WRITE(fdi))
+#define FDI_TO_SYSEVENTS(fdi) (FDI_HAS_READ(fdi) ? POLLIN : 0) | \
+    (FDI_HAS_WRITE(fdi) ? POLLOUT : 0)
+
+struct evport_data {
+       int             ed_port;        /* event port for system events  */
+       int             ed_nevents;     /* number of allocated fdi's     */
+       struct fd_info *ed_fds;         /* allocated fdi table           */
+       /* fdi's that we need to reassoc */
+       int ed_pending[EVENTS_PER_GETN]; /* fd's with pending events */
+};
+
+static void*   evport_init(struct event_base *);
+static int evport_add(struct event_base *, int fd, short old, short events, void *);
+static int evport_del(struct event_base *, int fd, short old, short events, void *);
+static int     evport_dispatch(struct event_base *, struct timeval *);
+static void    evport_dealloc(struct event_base *);
+
+const struct eventop evportops = {
+       "evport",
+       evport_init,
+       evport_add,
+       evport_del,
+       evport_dispatch,
+       evport_dealloc,
+       1, /* need reinit */
+       0, /* features */
+       0, /* fdinfo length */
+};
+
+/*
+ * Initialize the event port implementation.
+ */
+
+static void*
+evport_init(struct event_base *base)
+{
+       struct evport_data *evpd;
+       int i;
+
+       if (!(evpd = mm_calloc(1, sizeof(struct evport_data))))
+               return (NULL);
+
+       if ((evpd->ed_port = port_create()) == -1) {
+               mm_free(evpd);
+               return (NULL);
+       }
+
+       /*
+        * Initialize file descriptor structure
+        */
+       evpd->ed_fds = mm_calloc(DEFAULT_NFDS, sizeof(struct fd_info));
+       if (evpd->ed_fds == NULL) {
+               close(evpd->ed_port);
+               mm_free(evpd);
+               return (NULL);
+       }
+       evpd->ed_nevents = DEFAULT_NFDS;
+       for (i = 0; i < EVENTS_PER_GETN; i++)
+               evpd->ed_pending[i] = -1;
+
+       evsig_init(base);
+
+       return (evpd);
+}
+
+#ifdef CHECK_INVARIANTS
+/*
+ * Checks some basic properties about the evport_data structure. Because it
+ * checks all file descriptors, this function can be expensive when the maximum
+ * file descriptor ever used is rather large.
+ */
+
+static void
+check_evportop(struct evport_data *evpd)
+{
+       EVUTIL_ASSERT(evpd);
+       EVUTIL_ASSERT(evpd->ed_nevents > 0);
+       EVUTIL_ASSERT(evpd->ed_port > 0);
+       EVUTIL_ASSERT(evpd->ed_fds > 0);
+}
+
+/*
+ * Verifies very basic integrity of a given port_event.
+ */
+static void
+check_event(port_event_t* pevt)
+{
+       /*
+        * We've only registered for PORT_SOURCE_FD events. The only
+        * other thing we can legitimately receive is PORT_SOURCE_ALERT,
+        * but since we're not using port_alert either, we can assume
+        * PORT_SOURCE_FD.
+        */
+       EVUTIL_ASSERT(pevt->portev_source == PORT_SOURCE_FD);
+       EVUTIL_ASSERT(pevt->portev_user == NULL);
+}
+
+#else
+#define check_evportop(epop)
+#define check_event(pevt)
+#endif /* CHECK_INVARIANTS */
+
+/*
+ * Doubles the size of the allocated file descriptor array.
+ */
+static int
+grow(struct evport_data *epdp, int factor)
+{
+       struct fd_info *tmp;
+       int oldsize = epdp->ed_nevents;
+       int newsize = factor * oldsize;
+       EVUTIL_ASSERT(factor > 1);
+
+       check_evportop(epdp);
+
+       tmp = mm_realloc(epdp->ed_fds, sizeof(struct fd_info) * newsize);
+       if (NULL == tmp)
+               return -1;
+       epdp->ed_fds = tmp;
+       memset((char*) (epdp->ed_fds + oldsize), 0,
+           (newsize - oldsize)*sizeof(struct fd_info));
+       epdp->ed_nevents = newsize;
+
+       check_evportop(epdp);
+
+       return 0;
+}
+
+
+/*
+ * (Re)associates the given file descriptor with the event port. The OS events
+ * are specified (implicitly) from the fd_info struct.
+ */
+static int
+reassociate(struct evport_data *epdp, struct fd_info *fdip, int fd)
+{
+       int sysevents = FDI_TO_SYSEVENTS(fdip);
+
+       if (sysevents != 0) {
+               if (port_associate(epdp->ed_port, PORT_SOURCE_FD,
+                                  fd, sysevents, NULL) == -1) {
+                       event_warn("port_associate");
+                       return (-1);
+               }
+       }
+
+       check_evportop(epdp);
+
+       return (0);
+}
+
+/*
+ * Main event loop - polls port_getn for some number of events, and processes
+ * them.
+ */
+
+static int
+evport_dispatch(struct event_base *base, struct timeval *tv)
+{
+       int i, res;
+       struct evport_data *epdp = base->evbase;
+       port_event_t pevtlist[EVENTS_PER_GETN];
+
+       /*
+        * port_getn will block until it has at least nevents events. It will
+        * also return how many it's given us (which may be more than we asked
+        * for, as long as it's less than our maximum (EVENTS_PER_GETN)) in
+        * nevents.
+        */
+       int nevents = 1;
+
+       /*
+        * We have to convert a struct timeval to a struct timespec
+        * (only difference is nanoseconds vs. microseconds). If no time-based
+        * events are active, we should wait for I/O (and tv == NULL).
+        */
+       struct timespec ts;
+       struct timespec *ts_p = NULL;
+       if (tv != NULL) {
+               ts.tv_sec = tv->tv_sec;
+               ts.tv_nsec = tv->tv_usec * 1000;
+               ts_p = &ts;
+       }
+
+       /*
+        * Before doing anything else, we need to reassociate the events we hit
+        * last time which need reassociation. See comment at the end of the
+        * loop below.
+        */
+       for (i = 0; i < EVENTS_PER_GETN; ++i) {
+               struct fd_info *fdi = NULL;
+               if (epdp->ed_pending[i] != -1) {
+                       fdi = &(epdp->ed_fds[epdp->ed_pending[i]]);
+               }
+
+               if (fdi != NULL && FDI_HAS_EVENTS(fdi)) {
+                       int fd = epdp->ed_pending[i];
+                       reassociate(epdp, fdi, fd);
+                       epdp->ed_pending[i] = -1;
+               }
+       }
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+       res = port_getn(epdp->ed_port, pevtlist, EVENTS_PER_GETN,
+           (unsigned int *) &nevents, ts_p);
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       if (res == -1) {
+               if (errno == EINTR || errno == EAGAIN) {
+                       return (0);
+               } else if (errno == ETIME) {
+                       if (nevents == 0)
+                               return (0);
+               } else {
+                       event_warn("port_getn");
+                       return (-1);
+               }
+       }
+
+       event_debug(("%s: port_getn reports %d events", __func__, nevents));
+
+       for (i = 0; i < nevents; ++i) {
+               struct fd_info *fdi;
+               port_event_t *pevt = &pevtlist[i];
+               int fd = (int) pevt->portev_object;
+
+               check_evportop(epdp);
+               check_event(pevt);
+               epdp->ed_pending[i] = fd;
+
+               /*
+                * Figure out what kind of event it was
+                * (because we have to pass this to the callback)
+                */
+               res = 0;
+               if (pevt->portev_events & (POLLERR|POLLHUP)) {
+                       res = EV_READ | EV_WRITE;
+               } else {
+                       if (pevt->portev_events & POLLIN)
+                               res |= EV_READ;
+                       if (pevt->portev_events & POLLOUT)
+                               res |= EV_WRITE;
+               }
+
+               /*
+                * Check for the error situations or a hangup situation
+                */
+               if (pevt->portev_events & (POLLERR|POLLHUP|POLLNVAL))
+                       res |= EV_READ|EV_WRITE;
+
+               EVUTIL_ASSERT(epdp->ed_nevents > fd);
+               fdi = &(epdp->ed_fds[fd]);
+
+               evmap_io_active(base, fd, res);
+       } /* end of all events gotten */
+
+       check_evportop(epdp);
+
+       return (0);
+}
+
+
+/*
+ * Adds the given event (so that you will be notified when it happens via
+ * the callback function).
+ */
+
+static int
+evport_add(struct event_base *base, int fd, short old, short events, void *p)
+{
+       struct evport_data *evpd = base->evbase;
+       struct fd_info *fdi;
+       int factor;
+       (void)p;
+
+       check_evportop(evpd);
+
+       /*
+        * If necessary, grow the file descriptor info table
+        */
+
+       factor = 1;
+       while (fd >= factor * evpd->ed_nevents)
+               factor *= 2;
+
+       if (factor > 1) {
+               if (-1 == grow(evpd, factor)) {
+                       return (-1);
+               }
+       }
+
+       fdi = &evpd->ed_fds[fd];
+       fdi->fdi_what |= events;
+
+       return reassociate(evpd, fdi, fd);
+}
+
+/*
+ * Removes the given event from the list of events to wait for.
+ */
+
+static int
+evport_del(struct event_base *base, int fd, short old, short events, void *p)
+{
+       struct evport_data *evpd = base->evbase;
+       struct fd_info *fdi;
+       int i;
+       int associated = 1;
+       (void)p;
+
+       check_evportop(evpd);
+
+       if (evpd->ed_nevents < fd) {
+               return (-1);
+       }
+
+       for (i = 0; i < EVENTS_PER_GETN; ++i) {
+               if (evpd->ed_pending[i] == fd) {
+                       associated = 0;
+                       break;
+               }
+       }
+
+       fdi = &evpd->ed_fds[fd];
+       if (events & EV_READ)
+               fdi->fdi_what &= ~EV_READ;
+       if (events & EV_WRITE)
+               fdi->fdi_what &= ~EV_WRITE;
+
+       if (associated) {
+               if (!FDI_HAS_EVENTS(fdi) &&
+                   port_dissociate(evpd->ed_port, PORT_SOURCE_FD, fd) == -1) {
+                       /*
+                        * Ignore EBADFD error the fd could have been closed
+                        * before event_del() was called.
+                        */
+                       if (errno != EBADFD) {
+                               event_warn("port_dissociate");
+                               return (-1);
+                       }
+               } else {
+                       if (FDI_HAS_EVENTS(fdi)) {
+                               return (reassociate(evpd, fdi, fd));
+                       }
+               }
+       } else {
+               if ((fdi->fdi_what & (EV_READ|EV_WRITE)) == 0) {
+                       evpd->ed_pending[i] = -1;
+               }
+       }
+       return 0;
+}
+
+
+static void
+evport_dealloc(struct event_base *base)
+{
+       struct evport_data *evpd = base->evbase;
+
+       evsig_dealloc(base);
+
+       close(evpd->ed_port);
+
+       if (evpd->ed_fds)
+               mm_free(evpd->ed_fds);
+       mm_free(evpd);
+}
diff --git a/libevent/evrpc-internal.h b/libevent/evrpc-internal.h
new file mode 100644 (file)
index 0000000..d6ea41a
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVRPC_INTERNAL_H_
+#define _EVRPC_INTERNAL_H_
+
+#include "http-internal.h"
+
+struct evrpc;
+struct evrpc_request_wrapper;
+
+#define EVRPC_URI_PREFIX "/.rpc."
+
+struct evrpc_hook {
+       TAILQ_ENTRY(evrpc_hook) next;
+
+       /* returns EVRPC_TERMINATE; if the rpc should be aborted.
+        * a hook is is allowed to rewrite the evbuffer
+        */
+       int (*process)(void *, struct evhttp_request *,
+           struct evbuffer *, void *);
+       void *process_arg;
+};
+
+TAILQ_HEAD(evrpc_hook_list, evrpc_hook);
+
+/*
+ * this is shared between the base and the pool, so that we can reuse
+ * the hook adding functions; we alias both evrpc_pool and evrpc_base
+ * to this common structure.
+ */
+
+struct evrpc_hook_ctx;
+TAILQ_HEAD(evrpc_pause_list, evrpc_hook_ctx);
+
+struct _evrpc_hooks {
+       /* hooks for processing outbound and inbound rpcs */
+       struct evrpc_hook_list in_hooks;
+       struct evrpc_hook_list out_hooks;
+
+       struct evrpc_pause_list pause_requests;
+};
+
+#define input_hooks common.in_hooks
+#define output_hooks common.out_hooks
+#define paused_requests common.pause_requests
+
+struct evrpc_base {
+       struct _evrpc_hooks common;
+
+       /* the HTTP server under which we register our RPC calls */
+       struct evhttp* http_server;
+
+       /* a list of all RPCs registered with us */
+       TAILQ_HEAD(evrpc_list, evrpc) registered_rpcs;
+};
+
+struct evrpc_req_generic;
+void evrpc_reqstate_free(struct evrpc_req_generic* rpc_state);
+
+/* A pool for holding evhttp_connection objects */
+struct evrpc_pool {
+       struct _evrpc_hooks common;
+
+       struct event_base *base;
+
+       struct evconq connections;
+
+       int timeout;
+
+       TAILQ_HEAD(evrpc_requestq, evrpc_request_wrapper) (requests);
+};
+
+struct evrpc_hook_ctx {
+       TAILQ_ENTRY(evrpc_hook_ctx) next;
+
+       void *ctx;
+       void (*cb)(void *, enum EVRPC_HOOK_RESULT);
+};
+
+struct evrpc_meta {
+       TAILQ_ENTRY(evrpc_meta) next;
+       char *key;
+
+       void *data;
+       size_t data_size;
+};
+
+TAILQ_HEAD(evrpc_meta_list, evrpc_meta);
+
+struct evrpc_hook_meta {
+       struct evrpc_meta_list meta_data;
+       struct evhttp_connection *evcon;
+};
+
+/* allows association of meta data with a request */
+static void evrpc_hook_associate_meta(struct evrpc_hook_meta **pctx,
+    struct evhttp_connection *evcon);
+
+/* creates a new meta data store */
+static struct evrpc_hook_meta *evrpc_hook_meta_new(void);
+
+/* frees the meta data associated with a request */
+static void evrpc_hook_context_free(struct evrpc_hook_meta *ctx);
+
+/* the server side of an rpc */
+
+/* We alias the RPC specific structs to this voided one */
+struct evrpc_req_generic {
+       /*
+        * allows association of meta data via hooks - needs to be
+        * synchronized with evrpc_request_wrapper
+        */
+       struct evrpc_hook_meta *hook_meta;
+
+       /* the unmarshaled request object */
+       void *request;
+
+       /* the empty reply object that needs to be filled in */
+       void *reply;
+
+       /*
+        * the static structure for this rpc; that can be used to
+        * automatically unmarshal and marshal the http buffers.
+        */
+       struct evrpc *rpc;
+
+       /*
+        * the http request structure on which we need to answer.
+        */
+       struct evhttp_request* http_req;
+
+       /*
+        * Temporary data store for marshaled data
+        */
+       struct evbuffer* rpc_data;
+};
+
+/* the client side of an rpc request */
+struct evrpc_request_wrapper {
+       /*
+        * allows association of meta data via hooks - needs to be
+        * synchronized with evrpc_req_generic.
+        */
+       struct evrpc_hook_meta *hook_meta;
+
+       TAILQ_ENTRY(evrpc_request_wrapper) next;
+
+       /* pool on which this rpc request is being made */
+       struct evrpc_pool *pool;
+
+       /* connection on which the request is being sent */
+       struct evhttp_connection *evcon;
+
+       /* the actual  request */
+       struct evhttp_request *req;
+
+       /* event for implementing request timeouts */
+       struct event ev_timeout;
+
+       /* the name of the rpc */
+       char *name;
+
+       /* callback */
+       void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg);
+       void *cb_arg;
+
+       void *request;
+       void *reply;
+
+       /* unmarshals the buffer into the proper request structure */
+       void (*request_marshal)(struct evbuffer *, void *);
+
+       /* removes all stored state in the reply */
+       void (*reply_clear)(void *);
+
+       /* marshals the reply into a buffer */
+       int (*reply_unmarshal)(void *, struct evbuffer*);
+};
+
+#endif /* _EVRPC_INTERNAL_H_ */
diff --git a/libevent/evrpc.c b/libevent/evrpc.c
new file mode 100644 (file)
index 0000000..4bf3d2b
--- /dev/null
@@ -0,0 +1,1174 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+
+#include <sys/types.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <stdio.h>
+#include <stdlib.h>
+#ifndef WIN32
+#include <unistd.h>
+#endif
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+
+#include <sys/queue.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/rpc.h"
+#include "event2/rpc_struct.h"
+#include "evrpc-internal.h"
+#include "event2/http.h"
+#include "event2/buffer.h"
+#include "event2/tag.h"
+#include "event2/http_struct.h"
+#include "event2/http_compat.h"
+#include "event2/util.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+
+struct evrpc_base *
+evrpc_init(struct evhttp *http_server)
+{
+       struct evrpc_base* base = mm_calloc(1, sizeof(struct evrpc_base));
+       if (base == NULL)
+               return (NULL);
+
+       /* we rely on the tagging sub system */
+       evtag_init();
+
+       TAILQ_INIT(&base->registered_rpcs);
+       TAILQ_INIT(&base->input_hooks);
+       TAILQ_INIT(&base->output_hooks);
+
+       TAILQ_INIT(&base->paused_requests);
+
+       base->http_server = http_server;
+
+       return (base);
+}
+
+void
+evrpc_free(struct evrpc_base *base)
+{
+       struct evrpc *rpc;
+       struct evrpc_hook *hook;
+       struct evrpc_hook_ctx *pause;
+       int r;
+
+       while ((rpc = TAILQ_FIRST(&base->registered_rpcs)) != NULL) {
+               r = evrpc_unregister_rpc(base, rpc->uri);
+               EVUTIL_ASSERT(r == 0);
+       }
+       while ((pause = TAILQ_FIRST(&base->paused_requests)) != NULL) {
+               TAILQ_REMOVE(&base->paused_requests, pause, next);
+               mm_free(pause);
+       }
+       while ((hook = TAILQ_FIRST(&base->input_hooks)) != NULL) {
+               r = evrpc_remove_hook(base, EVRPC_INPUT, hook);
+               EVUTIL_ASSERT(r);
+       }
+       while ((hook = TAILQ_FIRST(&base->output_hooks)) != NULL) {
+               r = evrpc_remove_hook(base, EVRPC_OUTPUT, hook);
+               EVUTIL_ASSERT(r);
+       }
+       mm_free(base);
+}
+
+void *
+evrpc_add_hook(void *vbase,
+    enum EVRPC_HOOK_TYPE hook_type,
+    int (*cb)(void *, struct evhttp_request *, struct evbuffer *, void *),
+    void *cb_arg)
+{
+       struct _evrpc_hooks *base = vbase;
+       struct evrpc_hook_list *head = NULL;
+       struct evrpc_hook *hook = NULL;
+       switch (hook_type) {
+       case EVRPC_INPUT:
+               head = &base->in_hooks;
+               break;
+       case EVRPC_OUTPUT:
+               head = &base->out_hooks;
+               break;
+       default:
+               EVUTIL_ASSERT(hook_type == EVRPC_INPUT || hook_type == EVRPC_OUTPUT);
+       }
+
+       hook = mm_calloc(1, sizeof(struct evrpc_hook));
+       EVUTIL_ASSERT(hook != NULL);
+
+       hook->process = cb;
+       hook->process_arg = cb_arg;
+       TAILQ_INSERT_TAIL(head, hook, next);
+
+       return (hook);
+}
+
+static int
+evrpc_remove_hook_internal(struct evrpc_hook_list *head, void *handle)
+{
+       struct evrpc_hook *hook = NULL;
+       TAILQ_FOREACH(hook, head, next) {
+               if (hook == handle) {
+                       TAILQ_REMOVE(head, hook, next);
+                       mm_free(hook);
+                       return (1);
+               }
+       }
+
+       return (0);
+}
+
+/*
+ * remove the hook specified by the handle
+ */
+
+int
+evrpc_remove_hook(void *vbase, enum EVRPC_HOOK_TYPE hook_type, void *handle)
+{
+       struct _evrpc_hooks *base = vbase;
+       struct evrpc_hook_list *head = NULL;
+       switch (hook_type) {
+       case EVRPC_INPUT:
+               head = &base->in_hooks;
+               break;
+       case EVRPC_OUTPUT:
+               head = &base->out_hooks;
+               break;
+       default:
+               EVUTIL_ASSERT(hook_type == EVRPC_INPUT || hook_type == EVRPC_OUTPUT);
+       }
+
+       return (evrpc_remove_hook_internal(head, handle));
+}
+
+static int
+evrpc_process_hooks(struct evrpc_hook_list *head, void *ctx,
+    struct evhttp_request *req, struct evbuffer *evbuf)
+{
+       struct evrpc_hook *hook;
+       TAILQ_FOREACH(hook, head, next) {
+               int res = hook->process(ctx, req, evbuf, hook->process_arg);
+               if (res != EVRPC_CONTINUE)
+                       return (res);
+       }
+
+       return (EVRPC_CONTINUE);
+}
+
+static void evrpc_pool_schedule(struct evrpc_pool *pool);
+static void evrpc_request_cb(struct evhttp_request *, void *);
+
+/*
+ * Registers a new RPC with the HTTP server.   The evrpc object is expected
+ * to have been filled in via the EVRPC_REGISTER_OBJECT macro which in turn
+ * calls this function.
+ */
+
+static char *
+evrpc_construct_uri(const char *uri)
+{
+       char *constructed_uri;
+       size_t constructed_uri_len;
+
+       constructed_uri_len = strlen(EVRPC_URI_PREFIX) + strlen(uri) + 1;
+       if ((constructed_uri = mm_malloc(constructed_uri_len)) == NULL)
+               event_err(1, "%s: failed to register rpc at %s",
+                   __func__, uri);
+       memcpy(constructed_uri, EVRPC_URI_PREFIX, strlen(EVRPC_URI_PREFIX));
+       memcpy(constructed_uri + strlen(EVRPC_URI_PREFIX), uri, strlen(uri));
+       constructed_uri[constructed_uri_len - 1] = '\0';
+
+       return (constructed_uri);
+}
+
+int
+evrpc_register_rpc(struct evrpc_base *base, struct evrpc *rpc,
+    void (*cb)(struct evrpc_req_generic *, void *), void *cb_arg)
+{
+       char *constructed_uri = evrpc_construct_uri(rpc->uri);
+
+       rpc->base = base;
+       rpc->cb = cb;
+       rpc->cb_arg = cb_arg;
+
+       TAILQ_INSERT_TAIL(&base->registered_rpcs, rpc, next);
+
+       evhttp_set_cb(base->http_server,
+           constructed_uri,
+           evrpc_request_cb,
+           rpc);
+
+       mm_free(constructed_uri);
+
+       return (0);
+}
+
+int
+evrpc_unregister_rpc(struct evrpc_base *base, const char *name)
+{
+       char *registered_uri = NULL;
+       struct evrpc *rpc;
+       int r;
+
+       /* find the right rpc; linear search might be slow */
+       TAILQ_FOREACH(rpc, &base->registered_rpcs, next) {
+               if (strcmp(rpc->uri, name) == 0)
+                       break;
+       }
+       if (rpc == NULL) {
+               /* We did not find an RPC with this name */
+               return (-1);
+       }
+       TAILQ_REMOVE(&base->registered_rpcs, rpc, next);
+
+       registered_uri = evrpc_construct_uri(name);
+
+       /* remove the http server callback */
+       r = evhttp_del_cb(base->http_server, registered_uri);
+       EVUTIL_ASSERT(r == 0);
+
+       mm_free(registered_uri);
+
+       mm_free((char *)rpc->uri);
+       mm_free(rpc);
+       return (0);
+}
+
+static int evrpc_pause_request(void *vbase, void *ctx,
+    void (*cb)(void *, enum EVRPC_HOOK_RESULT));
+static void evrpc_request_cb_closure(void *, enum EVRPC_HOOK_RESULT);
+
+static void
+evrpc_request_cb(struct evhttp_request *req, void *arg)
+{
+       struct evrpc *rpc = arg;
+       struct evrpc_req_generic *rpc_state = NULL;
+
+       /* let's verify the outside parameters */
+       if (req->type != EVHTTP_REQ_POST ||
+           evbuffer_get_length(req->input_buffer) <= 0)
+               goto error;
+
+       rpc_state = mm_calloc(1, sizeof(struct evrpc_req_generic));
+       if (rpc_state == NULL)
+               goto error;
+       rpc_state->rpc = rpc;
+       rpc_state->http_req = req;
+       rpc_state->rpc_data = NULL;
+
+       if (TAILQ_FIRST(&rpc->base->input_hooks) != NULL) {
+               int hook_res;
+
+               evrpc_hook_associate_meta(&rpc_state->hook_meta, req->evcon);
+
+               /*
+                * allow hooks to modify the outgoing request
+                */
+               hook_res = evrpc_process_hooks(&rpc->base->input_hooks,
+                   rpc_state, req, req->input_buffer);
+               switch (hook_res) {
+               case EVRPC_TERMINATE:
+                       goto error;
+               case EVRPC_PAUSE:
+                       evrpc_pause_request(rpc->base, rpc_state,
+                           evrpc_request_cb_closure);
+                       return;
+               case EVRPC_CONTINUE:
+                       break;
+               default:
+                       EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
+                           hook_res == EVRPC_CONTINUE ||
+                           hook_res == EVRPC_PAUSE);
+               }
+       }
+
+       evrpc_request_cb_closure(rpc_state, EVRPC_CONTINUE);
+       return;
+
+error:
+       if (rpc_state != NULL)
+               evrpc_reqstate_free(rpc_state);
+       evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
+       return;
+}
+
+static void
+evrpc_request_cb_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
+{
+       struct evrpc_req_generic *rpc_state = arg;
+       struct evrpc *rpc;
+       struct evhttp_request *req;
+
+       EVUTIL_ASSERT(rpc_state);
+       rpc = rpc_state->rpc;
+       req = rpc_state->http_req;
+
+       if (hook_res == EVRPC_TERMINATE)
+               goto error;
+
+       /* let's check that we can parse the request */
+       rpc_state->request = rpc->request_new(rpc->request_new_arg);
+       if (rpc_state->request == NULL)
+               goto error;
+
+       if (rpc->request_unmarshal(
+                   rpc_state->request, req->input_buffer) == -1) {
+               /* we failed to parse the request; that's a bummer */
+               goto error;
+       }
+
+       /* at this point, we have a well formed request, prepare the reply */
+
+       rpc_state->reply = rpc->reply_new(rpc->reply_new_arg);
+       if (rpc_state->reply == NULL)
+               goto error;
+
+       /* give the rpc to the user; they can deal with it */
+       rpc->cb(rpc_state, rpc->cb_arg);
+
+       return;
+
+error:
+       if (rpc_state != NULL)
+               evrpc_reqstate_free(rpc_state);
+       evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
+       return;
+}
+
+
+void
+evrpc_reqstate_free(struct evrpc_req_generic* rpc_state)
+{
+       struct evrpc *rpc;
+       EVUTIL_ASSERT(rpc_state != NULL);
+       rpc = rpc_state->rpc;
+
+       /* clean up all memory */
+       if (rpc_state->hook_meta != NULL)
+               evrpc_hook_context_free(rpc_state->hook_meta);
+       if (rpc_state->request != NULL)
+               rpc->request_free(rpc_state->request);
+       if (rpc_state->reply != NULL)
+               rpc->reply_free(rpc_state->reply);
+       if (rpc_state->rpc_data != NULL)
+               evbuffer_free(rpc_state->rpc_data);
+       mm_free(rpc_state);
+}
+
+static void
+evrpc_request_done_closure(void *, enum EVRPC_HOOK_RESULT);
+
+void
+evrpc_request_done(struct evrpc_req_generic *rpc_state)
+{
+       struct evhttp_request *req;
+       struct evrpc *rpc;
+
+       EVUTIL_ASSERT(rpc_state);
+
+       req = rpc_state->http_req;
+       rpc = rpc_state->rpc;
+
+       if (rpc->reply_complete(rpc_state->reply) == -1) {
+               /* the reply was not completely filled in.  error out */
+               goto error;
+       }
+
+       if ((rpc_state->rpc_data = evbuffer_new()) == NULL) {
+               /* out of memory */
+               goto error;
+       }
+
+       /* serialize the reply */
+       rpc->reply_marshal(rpc_state->rpc_data, rpc_state->reply);
+
+       if (TAILQ_FIRST(&rpc->base->output_hooks) != NULL) {
+               int hook_res;
+
+               evrpc_hook_associate_meta(&rpc_state->hook_meta, req->evcon);
+
+               /* do hook based tweaks to the request */
+               hook_res = evrpc_process_hooks(&rpc->base->output_hooks,
+                   rpc_state, req, rpc_state->rpc_data);
+               switch (hook_res) {
+               case EVRPC_TERMINATE:
+                       goto error;
+               case EVRPC_PAUSE:
+                       if (evrpc_pause_request(rpc->base, rpc_state,
+                               evrpc_request_done_closure) == -1)
+                               goto error;
+                       return;
+               case EVRPC_CONTINUE:
+                       break;
+               default:
+                       EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
+                           hook_res == EVRPC_CONTINUE ||
+                           hook_res == EVRPC_PAUSE);
+               }
+       }
+
+       evrpc_request_done_closure(rpc_state, EVRPC_CONTINUE);
+       return;
+
+error:
+       if (rpc_state != NULL)
+               evrpc_reqstate_free(rpc_state);
+       evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
+       return;
+}
+
+void *
+evrpc_get_request(struct evrpc_req_generic *req)
+{
+       return req->request;
+}
+
+void *
+evrpc_get_reply(struct evrpc_req_generic *req)
+{
+       return req->reply;
+}
+
+static void
+evrpc_request_done_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
+{
+       struct evrpc_req_generic *rpc_state = arg;
+       struct evhttp_request *req;
+       EVUTIL_ASSERT(rpc_state);
+       req = rpc_state->http_req;
+
+       if (hook_res == EVRPC_TERMINATE)
+               goto error;
+
+       /* on success, we are going to transmit marshaled binary data */
+       if (evhttp_find_header(req->output_headers, "Content-Type") == NULL) {
+               evhttp_add_header(req->output_headers,
+                   "Content-Type", "application/octet-stream");
+       }
+       evhttp_send_reply(req, HTTP_OK, "OK", rpc_state->rpc_data);
+
+       evrpc_reqstate_free(rpc_state);
+
+       return;
+
+error:
+       if (rpc_state != NULL)
+               evrpc_reqstate_free(rpc_state);
+       evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
+       return;
+}
+
+
+/* Client implementation of RPC site */
+
+static int evrpc_schedule_request(struct evhttp_connection *connection,
+    struct evrpc_request_wrapper *ctx);
+
+struct evrpc_pool *
+evrpc_pool_new(struct event_base *base)
+{
+       struct evrpc_pool *pool = mm_calloc(1, sizeof(struct evrpc_pool));
+       if (pool == NULL)
+               return (NULL);
+
+       TAILQ_INIT(&pool->connections);
+       TAILQ_INIT(&pool->requests);
+
+       TAILQ_INIT(&pool->paused_requests);
+
+       TAILQ_INIT(&pool->input_hooks);
+       TAILQ_INIT(&pool->output_hooks);
+
+       pool->base = base;
+       pool->timeout = -1;
+
+       return (pool);
+}
+
+static void
+evrpc_request_wrapper_free(struct evrpc_request_wrapper *request)
+{
+       if (request->hook_meta != NULL)
+               evrpc_hook_context_free(request->hook_meta);
+       mm_free(request->name);
+       mm_free(request);
+}
+
+void
+evrpc_pool_free(struct evrpc_pool *pool)
+{
+       struct evhttp_connection *connection;
+       struct evrpc_request_wrapper *request;
+       struct evrpc_hook_ctx *pause;
+       struct evrpc_hook *hook;
+       int r;
+
+       while ((request = TAILQ_FIRST(&pool->requests)) != NULL) {
+               TAILQ_REMOVE(&pool->requests, request, next);
+               evrpc_request_wrapper_free(request);
+       }
+
+       while ((pause = TAILQ_FIRST(&pool->paused_requests)) != NULL) {
+               TAILQ_REMOVE(&pool->paused_requests, pause, next);
+               mm_free(pause);
+       }
+
+       while ((connection = TAILQ_FIRST(&pool->connections)) != NULL) {
+               TAILQ_REMOVE(&pool->connections, connection, next);
+               evhttp_connection_free(connection);
+       }
+
+       while ((hook = TAILQ_FIRST(&pool->input_hooks)) != NULL) {
+               r = evrpc_remove_hook(pool, EVRPC_INPUT, hook);
+               EVUTIL_ASSERT(r);
+       }
+
+       while ((hook = TAILQ_FIRST(&pool->output_hooks)) != NULL) {
+               r = evrpc_remove_hook(pool, EVRPC_OUTPUT, hook);
+               EVUTIL_ASSERT(r);
+       }
+
+       mm_free(pool);
+}
+
+/*
+ * Add a connection to the RPC pool.   A request scheduled on the pool
+ * may use any available connection.
+ */
+
+void
+evrpc_pool_add_connection(struct evrpc_pool *pool,
+    struct evhttp_connection *connection)
+{
+       EVUTIL_ASSERT(connection->http_server == NULL);
+       TAILQ_INSERT_TAIL(&pool->connections, connection, next);
+
+       /*
+        * associate an event base with this connection
+        */
+       if (pool->base != NULL)
+               evhttp_connection_set_base(connection, pool->base);
+
+       /*
+        * unless a timeout was specifically set for a connection,
+        * the connection inherits the timeout from the pool.
+        */
+       if (connection->timeout == -1)
+               connection->timeout = pool->timeout;
+
+       /*
+        * if we have any requests pending, schedule them with the new
+        * connections.
+        */
+
+       if (TAILQ_FIRST(&pool->requests) != NULL) {
+               struct evrpc_request_wrapper *request =
+                   TAILQ_FIRST(&pool->requests);
+               TAILQ_REMOVE(&pool->requests, request, next);
+               evrpc_schedule_request(connection, request);
+       }
+}
+
+void
+evrpc_pool_remove_connection(struct evrpc_pool *pool,
+    struct evhttp_connection *connection)
+{
+       TAILQ_REMOVE(&pool->connections, connection, next);
+}
+
+void
+evrpc_pool_set_timeout(struct evrpc_pool *pool, int timeout_in_secs)
+{
+       struct evhttp_connection *evcon;
+       TAILQ_FOREACH(evcon, &pool->connections, next) {
+               evcon->timeout = timeout_in_secs;
+       }
+       pool->timeout = timeout_in_secs;
+}
+
+
+static void evrpc_reply_done(struct evhttp_request *, void *);
+static void evrpc_request_timeout(evutil_socket_t, short, void *);
+
+/*
+ * Finds a connection object associated with the pool that is currently
+ * idle and can be used to make a request.
+ */
+static struct evhttp_connection *
+evrpc_pool_find_connection(struct evrpc_pool *pool)
+{
+       struct evhttp_connection *connection;
+       TAILQ_FOREACH(connection, &pool->connections, next) {
+               if (TAILQ_FIRST(&connection->requests) == NULL)
+                       return (connection);
+       }
+
+       return (NULL);
+}
+
+/*
+ * Prototypes responsible for evrpc scheduling and hooking
+ */
+
+static void evrpc_schedule_request_closure(void *ctx, enum EVRPC_HOOK_RESULT);
+
+/*
+ * We assume that the ctx is no longer queued on the pool.
+ */
+static int
+evrpc_schedule_request(struct evhttp_connection *connection,
+    struct evrpc_request_wrapper *ctx)
+{
+       struct evhttp_request *req = NULL;
+       struct evrpc_pool *pool = ctx->pool;
+       struct evrpc_status status;
+
+       if ((req = evhttp_request_new(evrpc_reply_done, ctx)) == NULL)
+               goto error;
+
+       /* serialize the request data into the output buffer */
+       ctx->request_marshal(req->output_buffer, ctx->request);
+
+       /* we need to know the connection that we might have to abort */
+       ctx->evcon = connection;
+
+       /* if we get paused we also need to know the request */
+       ctx->req = req;
+
+       if (TAILQ_FIRST(&pool->output_hooks) != NULL) {
+               int hook_res;
+
+               evrpc_hook_associate_meta(&ctx->hook_meta, connection);
+
+               /* apply hooks to the outgoing request */
+               hook_res = evrpc_process_hooks(&pool->output_hooks,
+                   ctx, req, req->output_buffer);
+
+               switch (hook_res) {
+               case EVRPC_TERMINATE:
+                       goto error;
+               case EVRPC_PAUSE:
+                       /* we need to be explicitly resumed */
+                       if (evrpc_pause_request(pool, ctx,
+                               evrpc_schedule_request_closure) == -1)
+                               goto error;
+                       return (0);
+               case EVRPC_CONTINUE:
+                       /* we can just continue */
+                       break;
+               default:
+                       EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
+                           hook_res == EVRPC_CONTINUE ||
+                           hook_res == EVRPC_PAUSE);
+               }
+       }
+
+       evrpc_schedule_request_closure(ctx, EVRPC_CONTINUE);
+       return (0);
+
+error:
+       memset(&status, 0, sizeof(status));
+       status.error = EVRPC_STATUS_ERR_UNSTARTED;
+       (*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
+       evrpc_request_wrapper_free(ctx);
+       return (-1);
+}
+
+static void
+evrpc_schedule_request_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
+{
+       struct evrpc_request_wrapper *ctx = arg;
+       struct evhttp_connection *connection = ctx->evcon;
+       struct evhttp_request *req = ctx->req;
+       struct evrpc_pool *pool = ctx->pool;
+       struct evrpc_status status;
+       char *uri = NULL;
+       int res = 0;
+
+       if (hook_res == EVRPC_TERMINATE)
+               goto error;
+
+       uri = evrpc_construct_uri(ctx->name);
+       if (uri == NULL)
+               goto error;
+
+       if (pool->timeout > 0) {
+               /*
+                * a timeout after which the whole rpc is going to be aborted.
+                */
+               struct timeval tv;
+               evutil_timerclear(&tv);
+               tv.tv_sec = pool->timeout;
+               evtimer_add(&ctx->ev_timeout, &tv);
+       }
+
+       /* start the request over the connection */
+       res = evhttp_make_request(connection, req, EVHTTP_REQ_POST, uri);
+       mm_free(uri);
+
+       if (res == -1)
+               goto error;
+
+       return;
+
+error:
+       memset(&status, 0, sizeof(status));
+       status.error = EVRPC_STATUS_ERR_UNSTARTED;
+       (*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
+       evrpc_request_wrapper_free(ctx);
+}
+
+/* we just queue the paused request on the pool under the req object */
+static int
+evrpc_pause_request(void *vbase, void *ctx,
+    void (*cb)(void *, enum EVRPC_HOOK_RESULT))
+{
+       struct _evrpc_hooks *base = vbase;
+       struct evrpc_hook_ctx *pause = mm_malloc(sizeof(*pause));
+       if (pause == NULL)
+               return (-1);
+
+       pause->ctx = ctx;
+       pause->cb = cb;
+
+       TAILQ_INSERT_TAIL(&base->pause_requests, pause, next);
+       return (0);
+}
+
+int
+evrpc_resume_request(void *vbase, void *ctx, enum EVRPC_HOOK_RESULT res)
+{
+       struct _evrpc_hooks *base = vbase;
+       struct evrpc_pause_list *head = &base->pause_requests;
+       struct evrpc_hook_ctx *pause;
+
+       TAILQ_FOREACH(pause, head, next) {
+               if (pause->ctx == ctx)
+                       break;
+       }
+
+       if (pause == NULL)
+               return (-1);
+
+       (*pause->cb)(pause->ctx, res);
+       TAILQ_REMOVE(head, pause, next);
+       mm_free(pause);
+       return (0);
+}
+
+int
+evrpc_make_request(struct evrpc_request_wrapper *ctx)
+{
+       struct evrpc_pool *pool = ctx->pool;
+
+       /* initialize the event structure for this rpc */
+       evtimer_assign(&ctx->ev_timeout, pool->base, evrpc_request_timeout, ctx);
+
+       /* we better have some available connections on the pool */
+       EVUTIL_ASSERT(TAILQ_FIRST(&pool->connections) != NULL);
+
+       /*
+        * if no connection is available, we queue the request on the pool,
+        * the next time a connection is empty, the rpc will be send on that.
+        */
+       TAILQ_INSERT_TAIL(&pool->requests, ctx, next);
+
+       evrpc_pool_schedule(pool);
+
+       return (0);
+}
+
+
+struct evrpc_request_wrapper *
+evrpc_make_request_ctx(
+       struct evrpc_pool *pool, void *request, void *reply,
+       const char *rpcname,
+       void (*req_marshal)(struct evbuffer*, void *),
+       void (*rpl_clear)(void *),
+       int (*rpl_unmarshal)(void *, struct evbuffer *),
+       void (*cb)(struct evrpc_status *, void *, void *, void *),
+       void *cbarg)
+{
+       struct evrpc_request_wrapper *ctx = (struct evrpc_request_wrapper *)
+           mm_malloc(sizeof(struct evrpc_request_wrapper));
+       if (ctx == NULL)
+               return (NULL);
+
+       ctx->pool = pool;
+       ctx->hook_meta = NULL;
+       ctx->evcon = NULL;
+       ctx->name = mm_strdup(rpcname);
+       if (ctx->name == NULL) {
+               mm_free(ctx);
+               return (NULL);
+       }
+       ctx->cb = cb;
+       ctx->cb_arg = cbarg;
+       ctx->request = request;
+       ctx->reply = reply;
+       ctx->request_marshal = req_marshal;
+       ctx->reply_clear = rpl_clear;
+       ctx->reply_unmarshal = rpl_unmarshal;
+
+       return (ctx);
+}
+
+static void
+evrpc_reply_done_closure(void *, enum EVRPC_HOOK_RESULT);
+
+static void
+evrpc_reply_done(struct evhttp_request *req, void *arg)
+{
+       struct evrpc_request_wrapper *ctx = arg;
+       struct evrpc_pool *pool = ctx->pool;
+       int hook_res = EVRPC_CONTINUE;
+
+       /* cancel any timeout we might have scheduled */
+       event_del(&ctx->ev_timeout);
+
+       ctx->req = req;
+
+       /* we need to get the reply now */
+       if (req == NULL) {
+               evrpc_reply_done_closure(ctx, EVRPC_CONTINUE);
+               return;
+       }
+
+       if (TAILQ_FIRST(&pool->input_hooks) != NULL) {
+               evrpc_hook_associate_meta(&ctx->hook_meta, ctx->evcon);
+
+               /* apply hooks to the incoming request */
+               hook_res = evrpc_process_hooks(&pool->input_hooks,
+                   ctx, req, req->input_buffer);
+
+               switch (hook_res) {
+               case EVRPC_TERMINATE:
+               case EVRPC_CONTINUE:
+                       break;
+               case EVRPC_PAUSE:
+                       /*
+                        * if we get paused we also need to know the
+                        * request.  unfortunately, the underlying
+                        * layer is going to free it.  we need to
+                        * request ownership explicitly
+                        */
+                       if (req != NULL)
+                               evhttp_request_own(req);
+
+                       evrpc_pause_request(pool, ctx,
+                           evrpc_reply_done_closure);
+                       return;
+               default:
+                       EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
+                           hook_res == EVRPC_CONTINUE ||
+                           hook_res == EVRPC_PAUSE);
+               }
+       }
+
+       evrpc_reply_done_closure(ctx, hook_res);
+
+       /* http request is being freed by underlying layer */
+}
+
+static void
+evrpc_reply_done_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
+{
+       struct evrpc_request_wrapper *ctx = arg;
+       struct evhttp_request *req = ctx->req;
+       struct evrpc_pool *pool = ctx->pool;
+       struct evrpc_status status;
+       int res = -1;
+
+       memset(&status, 0, sizeof(status));
+       status.http_req = req;
+
+       /* we need to get the reply now */
+       if (req == NULL) {
+               status.error = EVRPC_STATUS_ERR_TIMEOUT;
+       } else if (hook_res == EVRPC_TERMINATE) {
+               status.error = EVRPC_STATUS_ERR_HOOKABORTED;
+       } else {
+               res = ctx->reply_unmarshal(ctx->reply, req->input_buffer);
+               if (res == -1)
+                       status.error = EVRPC_STATUS_ERR_BADPAYLOAD;
+       }
+
+       if (res == -1) {
+               /* clear everything that we might have written previously */
+               ctx->reply_clear(ctx->reply);
+       }
+
+       (*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
+
+       evrpc_request_wrapper_free(ctx);
+
+       /* the http layer owned the original request structure, but if we
+        * got paused, we asked for ownership and need to free it here. */
+       if (req != NULL && evhttp_request_is_owned(req))
+               evhttp_request_free(req);
+
+       /* see if we can schedule another request */
+       evrpc_pool_schedule(pool);
+}
+
+static void
+evrpc_pool_schedule(struct evrpc_pool *pool)
+{
+       struct evrpc_request_wrapper *ctx = TAILQ_FIRST(&pool->requests);
+       struct evhttp_connection *evcon;
+
+       /* if no requests are pending, we have no work */
+       if (ctx == NULL)
+               return;
+
+       if ((evcon = evrpc_pool_find_connection(pool)) != NULL) {
+               TAILQ_REMOVE(&pool->requests, ctx, next);
+               evrpc_schedule_request(evcon, ctx);
+       }
+}
+
+static void
+evrpc_request_timeout(evutil_socket_t fd, short what, void *arg)
+{
+       struct evrpc_request_wrapper *ctx = arg;
+       struct evhttp_connection *evcon = ctx->evcon;
+       EVUTIL_ASSERT(evcon != NULL);
+
+       evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
+}
+
+/*
+ * frees potential meta data associated with a request.
+ */
+
+static void
+evrpc_meta_data_free(struct evrpc_meta_list *meta_data)
+{
+       struct evrpc_meta *entry;
+       EVUTIL_ASSERT(meta_data != NULL);
+
+       while ((entry = TAILQ_FIRST(meta_data)) != NULL) {
+               TAILQ_REMOVE(meta_data, entry, next);
+               mm_free(entry->key);
+               mm_free(entry->data);
+               mm_free(entry);
+       }
+}
+
+static struct evrpc_hook_meta *
+evrpc_hook_meta_new(void)
+{
+       struct evrpc_hook_meta *ctx;
+       ctx = mm_malloc(sizeof(struct evrpc_hook_meta));
+       EVUTIL_ASSERT(ctx != NULL);
+
+       TAILQ_INIT(&ctx->meta_data);
+       ctx->evcon = NULL;
+
+       return (ctx);
+}
+
+static void
+evrpc_hook_associate_meta(struct evrpc_hook_meta **pctx,
+    struct evhttp_connection *evcon)
+{
+       struct evrpc_hook_meta *ctx = *pctx;
+       if (ctx == NULL)
+               *pctx = ctx = evrpc_hook_meta_new();
+       ctx->evcon = evcon;
+}
+
+static void
+evrpc_hook_context_free(struct evrpc_hook_meta *ctx)
+{
+       evrpc_meta_data_free(&ctx->meta_data);
+       mm_free(ctx);
+}
+
+/* Adds meta data */
+void
+evrpc_hook_add_meta(void *ctx, const char *key,
+    const void *data, size_t data_size)
+{
+       struct evrpc_request_wrapper *req = ctx;
+       struct evrpc_hook_meta *store = NULL;
+       struct evrpc_meta *meta = NULL;
+
+       if ((store = req->hook_meta) == NULL)
+               store = req->hook_meta = evrpc_hook_meta_new();
+
+       meta = mm_malloc(sizeof(struct evrpc_meta));
+       EVUTIL_ASSERT(meta != NULL);
+       meta->key = mm_strdup(key);
+       EVUTIL_ASSERT(meta->key != NULL);
+       meta->data_size = data_size;
+       meta->data = mm_malloc(data_size);
+       EVUTIL_ASSERT(meta->data != NULL);
+       memcpy(meta->data, data, data_size);
+
+       TAILQ_INSERT_TAIL(&store->meta_data, meta, next);
+}
+
+int
+evrpc_hook_find_meta(void *ctx, const char *key, void **data, size_t *data_size)
+{
+       struct evrpc_request_wrapper *req = ctx;
+       struct evrpc_meta *meta = NULL;
+
+       if (req->hook_meta == NULL)
+               return (-1);
+
+       TAILQ_FOREACH(meta, &req->hook_meta->meta_data, next) {
+               if (strcmp(meta->key, key) == 0) {
+                       *data = meta->data;
+                       *data_size = meta->data_size;
+                       return (0);
+               }
+       }
+
+       return (-1);
+}
+
+struct evhttp_connection *
+evrpc_hook_get_connection(void *ctx)
+{
+       struct evrpc_request_wrapper *req = ctx;
+       return (req->hook_meta != NULL ? req->hook_meta->evcon : NULL);
+}
+
+int
+evrpc_send_request_generic(struct evrpc_pool *pool,
+    void *request, void *reply,
+    void (*cb)(struct evrpc_status *, void *, void *, void *),
+    void *cb_arg,
+    const char *rpcname,
+    void (*req_marshal)(struct evbuffer *, void *),
+    void (*rpl_clear)(void *),
+    int (*rpl_unmarshal)(void *, struct evbuffer *))
+{
+       struct evrpc_status status;
+       struct evrpc_request_wrapper *ctx;
+       ctx = evrpc_make_request_ctx(pool, request, reply,
+           rpcname, req_marshal, rpl_clear, rpl_unmarshal, cb, cb_arg);
+       if (ctx == NULL)
+               goto error;
+       return (evrpc_make_request(ctx));
+error:
+       memset(&status, 0, sizeof(status));
+       status.error = EVRPC_STATUS_ERR_UNSTARTED;
+       (*(cb))(&status, request, reply, cb_arg);
+       return (-1);
+}
+
+/** Takes a request object and fills it in with the right magic */
+static struct evrpc *
+evrpc_register_object(const char *name,
+    void *(*req_new)(void*), void *req_new_arg, void (*req_free)(void *),
+    int (*req_unmarshal)(void *, struct evbuffer *),
+    void *(*rpl_new)(void*), void *rpl_new_arg, void (*rpl_free)(void *),
+    int (*rpl_complete)(void *),
+    void (*rpl_marshal)(struct evbuffer *, void *))
+{
+       struct evrpc* rpc = (struct evrpc *)mm_calloc(1, sizeof(struct evrpc));
+       if (rpc == NULL)
+               return (NULL);
+       rpc->uri = mm_strdup(name);
+       if (rpc->uri == NULL) {
+               mm_free(rpc);
+               return (NULL);
+       }
+       rpc->request_new = req_new;
+       rpc->request_new_arg = req_new_arg;
+       rpc->request_free = req_free;
+       rpc->request_unmarshal = req_unmarshal;
+       rpc->reply_new = rpl_new;
+       rpc->reply_new_arg = rpl_new_arg;
+       rpc->reply_free = rpl_free;
+       rpc->reply_complete = rpl_complete;
+       rpc->reply_marshal = rpl_marshal;
+       return (rpc);
+}
+
+int
+evrpc_register_generic(struct evrpc_base *base, const char *name,
+    void (*callback)(struct evrpc_req_generic *, void *), void *cbarg,
+    void *(*req_new)(void *), void *req_new_arg, void (*req_free)(void *),
+    int (*req_unmarshal)(void *, struct evbuffer *),
+    void *(*rpl_new)(void *), void *rpl_new_arg, void (*rpl_free)(void *),
+    int (*rpl_complete)(void *),
+    void (*rpl_marshal)(struct evbuffer *, void *))
+{
+       struct evrpc* rpc =
+           evrpc_register_object(name, req_new, req_new_arg, req_free, req_unmarshal,
+               rpl_new, rpl_new_arg, rpl_free, rpl_complete, rpl_marshal);
+       if (rpc == NULL)
+               return (-1);
+       evrpc_register_rpc(base, rpc,
+           (void (*)(struct evrpc_req_generic*, void *))callback, cbarg);
+       return (0);
+}
+
+/** accessors for obscure and undocumented functionality */
+struct evrpc_pool *
+evrpc_request_get_pool(struct evrpc_request_wrapper *ctx)
+{
+       return (ctx->pool);
+}
+
+void
+evrpc_request_set_pool(struct evrpc_request_wrapper *ctx,
+    struct evrpc_pool *pool)
+{
+       ctx->pool = pool;
+}
+
+void
+evrpc_request_set_cb(struct evrpc_request_wrapper *ctx,
+    void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg),
+    void *cb_arg)
+{
+       ctx->cb = cb;
+       ctx->cb_arg = cb_arg;
+}
diff --git a/libevent/evrpc.h b/libevent/evrpc.h
new file mode 100644 (file)
index 0000000..5b88262
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVRPC_H_
+#define _EVRPC_H_
+
+/** @file evrpc.h
+
+  An RPC system for Libevent.
+
+  The <evrpc.h> header is deprecated in Libevent 2.0 and later; please
+  use <event2/rpc.h> instead.  Depending on what functionality you
+  need, you may also want to include more of the other <event2/...>
+  headers.
+ */
+
+#include <event.h>
+#include <event2/rpc.h>
+#include <event2/rpc_struct.h>
+#include <event2/rpc_compat.h>
+
+#endif /* _EVRPC_H_ */
diff --git a/libevent/evsignal-internal.h b/libevent/evsignal-internal.h
new file mode 100644 (file)
index 0000000..426f4a4
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVSIGNAL_H_
+#define _EVSIGNAL_H_
+
+#ifndef evutil_socket_t
+#include "event2/util.h"
+#endif
+#include <signal.h>
+
+typedef void (*ev_sighandler_t)(int);
+
+/* Data structure for the default signal-handling implementation in signal.c
+ */
+struct evsig_info {
+       /* Event watching ev_signal_pair[1] */
+       struct event ev_signal;
+       /* Socketpair used to send notifications from the signal handler */
+       evutil_socket_t ev_signal_pair[2];
+       /* True iff we've added the ev_signal event yet. */
+       int ev_signal_added;
+       /* Count of the number of signals we're currently watching. */
+       int ev_n_signals_added;
+
+       /* Array of previous signal handler objects before Libevent started
+        * messing with them.  Used to restore old signal handlers. */
+#ifdef _EVENT_HAVE_SIGACTION
+       struct sigaction **sh_old;
+#else
+       ev_sighandler_t **sh_old;
+#endif
+       /* Size of sh_old. */
+       int sh_old_max;
+};
+int evsig_init(struct event_base *);
+void evsig_dealloc(struct event_base *);
+
+void evsig_set_base(struct event_base *base);
+
+#endif /* _EVSIGNAL_H_ */
diff --git a/libevent/evthread-internal.h b/libevent/evthread-internal.h
new file mode 100644 (file)
index 0000000..ccfcdde
--- /dev/null
@@ -0,0 +1,382 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVTHREAD_INTERNAL_H_
+#define _EVTHREAD_INTERNAL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/thread.h"
+#include "event2/event-config.h"
+#include "util-internal.h"
+
+struct event_base;
+
+#ifndef WIN32
+/* On Windows, the way we currently make DLLs, it's not allowed for us to
+ * have shared global structures.  Thus, we only do the direct-call-to-function
+ * code path if we know that the local shared library system supports it.
+ */
+#define EVTHREAD_EXPOSE_STRUCTS
+#endif
+
+#if ! defined(_EVENT_DISABLE_THREAD_SUPPORT) && defined(EVTHREAD_EXPOSE_STRUCTS)
+/* Global function pointers to lock-related functions. NULL if locking isn't
+   enabled. */
+extern struct evthread_lock_callbacks _evthread_lock_fns;
+extern struct evthread_condition_callbacks _evthread_cond_fns;
+extern unsigned long (*_evthread_id_fn)(void);
+extern int _evthread_lock_debugging_enabled;
+
+/** Return the ID of the current thread, or 1 if threading isn't enabled. */
+#define EVTHREAD_GET_ID() \
+       (_evthread_id_fn ? _evthread_id_fn() : 1)
+
+/** Return true iff we're in the thread that is currently (or most recently)
+ * running a given event_base's loop. Requires lock. */
+#define EVBASE_IN_THREAD(base)                          \
+       (_evthread_id_fn == NULL ||                      \
+       (base)->th_owner_id == _evthread_id_fn())
+
+/** Return true iff we need to notify the base's main thread about changes to
+ * its state, because it's currently running the main loop in another
+ * thread. Requires lock. */
+#define EVBASE_NEED_NOTIFY(base)                        \
+       (_evthread_id_fn != NULL &&                      \
+           (base)->running_loop &&                      \
+           (base)->th_owner_id != _evthread_id_fn())
+
+/** Allocate a new lock, and store it in lockvar, a void*.  Sets lockvar to
+    NULL if locking is not enabled. */
+#define EVTHREAD_ALLOC_LOCK(lockvar, locktype)         \
+       ((lockvar) = _evthread_lock_fns.alloc ?         \
+           _evthread_lock_fns.alloc(locktype) : NULL)
+
+/** Free a given lock, if it is present and locking is enabled. */
+#define EVTHREAD_FREE_LOCK(lockvar, locktype)                          \
+       do {                                                            \
+               void *_lock_tmp_ = (lockvar);                           \
+               if (_lock_tmp_ && _evthread_lock_fns.free)              \
+                       _evthread_lock_fns.free(_lock_tmp_, (locktype)); \
+       } while (0)
+
+/** Acquire a lock. */
+#define EVLOCK_LOCK(lockvar,mode)                                      \
+       do {                                                            \
+               if (lockvar)                                            \
+                       _evthread_lock_fns.lock(mode, lockvar);         \
+       } while (0)
+
+/** Release a lock */
+#define EVLOCK_UNLOCK(lockvar,mode)                                    \
+       do {                                                            \
+               if (lockvar)                                            \
+                       _evthread_lock_fns.unlock(mode, lockvar);       \
+       } while (0)
+
+/** Helper: put lockvar1 and lockvar2 into pointerwise ascending order. */
+#define _EVLOCK_SORTLOCKS(lockvar1, lockvar2)                          \
+       do {                                                            \
+               if (lockvar1 && lockvar2 && lockvar1 > lockvar2) {      \
+                       void *tmp = lockvar1;                           \
+                       lockvar1 = lockvar2;                            \
+                       lockvar2 = tmp;                                 \
+               }                                                       \
+       } while (0)
+
+/** Lock an event_base, if it is set up for locking.  Acquires the lock
+    in the base structure whose field is named 'lockvar'. */
+#define EVBASE_ACQUIRE_LOCK(base, lockvar) do {                                \
+               EVLOCK_LOCK((base)->lockvar, 0);                        \
+       } while (0)
+
+/** Unlock an event_base, if it is set up for locking. */
+#define EVBASE_RELEASE_LOCK(base, lockvar) do {                                \
+               EVLOCK_UNLOCK((base)->lockvar, 0);                      \
+       } while (0)
+
+/** If lock debugging is enabled, and lock is non-null, assert that 'lock' is
+ * locked and held by us. */
+#define EVLOCK_ASSERT_LOCKED(lock)                                     \
+       do {                                                            \
+               if ((lock) && _evthread_lock_debugging_enabled) {       \
+                       EVUTIL_ASSERT(_evthread_is_debug_lock_held(lock)); \
+               }                                                       \
+       } while (0)
+
+/** Try to grab the lock for 'lockvar' without blocking, and return 1 if we
+ * manage to get it. */
+static inline int EVLOCK_TRY_LOCK(void *lock);
+static inline int
+EVLOCK_TRY_LOCK(void *lock)
+{
+       if (lock && _evthread_lock_fns.lock) {
+               int r = _evthread_lock_fns.lock(EVTHREAD_TRY, lock);
+               return !r;
+       } else {
+               /* Locking is disabled either globally or for this thing;
+                * of course we count as having the lock. */
+               return 1;
+       }
+}
+
+/** Allocate a new condition variable and store it in the void *, condvar */
+#define EVTHREAD_ALLOC_COND(condvar)                                   \
+       do {                                                            \
+               (condvar) = _evthread_cond_fns.alloc_condition ?        \
+                   _evthread_cond_fns.alloc_condition(0) : NULL;       \
+       } while (0)
+/** Deallocate and free a condition variable in condvar */
+#define EVTHREAD_FREE_COND(cond)                                       \
+       do {                                                            \
+               if (cond)                                               \
+                       _evthread_cond_fns.free_condition((cond));      \
+       } while (0)
+/** Signal one thread waiting on cond */
+#define EVTHREAD_COND_SIGNAL(cond)                                     \
+       ( (cond) ? _evthread_cond_fns.signal_condition((cond), 0) : 0 )
+/** Signal all threads waiting on cond */
+#define EVTHREAD_COND_BROADCAST(cond)                                  \
+       ( (cond) ? _evthread_cond_fns.signal_condition((cond), 1) : 0 )
+/** Wait until the condition 'cond' is signalled.  Must be called while
+ * holding 'lock'.  The lock will be released until the condition is
+ * signalled, at which point it will be acquired again.  Returns 0 for
+ * success, -1 for failure. */
+#define EVTHREAD_COND_WAIT(cond, lock)                                 \
+       ( (cond) ? _evthread_cond_fns.wait_condition((cond), (lock), NULL) : 0 )
+/** As EVTHREAD_COND_WAIT, but gives up after 'tv' has elapsed.  Returns 1
+ * on timeout. */
+#define EVTHREAD_COND_WAIT_TIMED(cond, lock, tv)                       \
+       ( (cond) ? _evthread_cond_fns.wait_condition((cond), (lock), (tv)) : 0 )
+
+/** True iff locking functions have been configured. */
+#define EVTHREAD_LOCKING_ENABLED()             \
+       (_evthread_lock_fns.lock != NULL)
+
+#elif ! defined(_EVENT_DISABLE_THREAD_SUPPORT)
+
+unsigned long _evthreadimpl_get_id(void);
+int _evthreadimpl_is_lock_debugging_enabled(void);
+void *_evthreadimpl_lock_alloc(unsigned locktype);
+void _evthreadimpl_lock_free(void *lock, unsigned locktype);
+int _evthreadimpl_lock_lock(unsigned mode, void *lock);
+int _evthreadimpl_lock_unlock(unsigned mode, void *lock);
+void *_evthreadimpl_cond_alloc(unsigned condtype);
+void _evthreadimpl_cond_free(void *cond);
+int _evthreadimpl_cond_signal(void *cond, int broadcast);
+int _evthreadimpl_cond_wait(void *cond, void *lock, const struct timeval *tv);
+int _evthreadimpl_locking_enabled(void);
+
+#define EVTHREAD_GET_ID() _evthreadimpl_get_id()
+#define EVBASE_IN_THREAD(base)                         \
+       ((base)->th_owner_id == _evthreadimpl_get_id())
+#define EVBASE_NEED_NOTIFY(base)                        \
+       ((base)->running_loop &&                         \
+           ((base)->th_owner_id != _evthreadimpl_get_id()))
+
+#define EVTHREAD_ALLOC_LOCK(lockvar, locktype)         \
+       ((lockvar) = _evthreadimpl_lock_alloc(locktype))
+
+#define EVTHREAD_FREE_LOCK(lockvar, locktype)                          \
+       do {                                                            \
+               void *_lock_tmp_ = (lockvar);                           \
+               if (_lock_tmp_)                                         \
+                       _evthreadimpl_lock_free(_lock_tmp_, (locktype)); \
+       } while (0)
+
+/** Acquire a lock. */
+#define EVLOCK_LOCK(lockvar,mode)                                      \
+       do {                                                            \
+               if (lockvar)                                            \
+                       _evthreadimpl_lock_lock(mode, lockvar);         \
+       } while (0)
+
+/** Release a lock */
+#define EVLOCK_UNLOCK(lockvar,mode)                                    \
+       do {                                                            \
+               if (lockvar)                                            \
+                       _evthreadimpl_lock_unlock(mode, lockvar);       \
+       } while (0)
+
+/** Lock an event_base, if it is set up for locking.  Acquires the lock
+    in the base structure whose field is named 'lockvar'. */
+#define EVBASE_ACQUIRE_LOCK(base, lockvar) do {                                \
+               EVLOCK_LOCK((base)->lockvar, 0);                        \
+       } while (0)
+
+/** Unlock an event_base, if it is set up for locking. */
+#define EVBASE_RELEASE_LOCK(base, lockvar) do {                                \
+               EVLOCK_UNLOCK((base)->lockvar, 0);                      \
+       } while (0)
+
+/** If lock debugging is enabled, and lock is non-null, assert that 'lock' is
+ * locked and held by us. */
+#define EVLOCK_ASSERT_LOCKED(lock)                                     \
+       do {                                                            \
+               if ((lock) && _evthreadimpl_is_lock_debugging_enabled()) { \
+                       EVUTIL_ASSERT(_evthread_is_debug_lock_held(lock)); \
+               }                                                       \
+       } while (0)
+
+/** Try to grab the lock for 'lockvar' without blocking, and return 1 if we
+ * manage to get it. */
+static inline int EVLOCK_TRY_LOCK(void *lock);
+static inline int
+EVLOCK_TRY_LOCK(void *lock)
+{
+       if (lock) {
+               int r = _evthreadimpl_lock_lock(EVTHREAD_TRY, lock);
+               return !r;
+       } else {
+               /* Locking is disabled either globally or for this thing;
+                * of course we count as having the lock. */
+               return 1;
+       }
+}
+
+/** Allocate a new condition variable and store it in the void *, condvar */
+#define EVTHREAD_ALLOC_COND(condvar)                                   \
+       do {                                                            \
+               (condvar) = _evthreadimpl_cond_alloc(0);                \
+       } while (0)
+/** Deallocate and free a condition variable in condvar */
+#define EVTHREAD_FREE_COND(cond)                                       \
+       do {                                                            \
+               if (cond)                                               \
+                       _evthreadimpl_cond_free((cond));                \
+       } while (0)
+/** Signal one thread waiting on cond */
+#define EVTHREAD_COND_SIGNAL(cond)                                     \
+       ( (cond) ? _evthreadimpl_cond_signal((cond), 0) : 0 )
+/** Signal all threads waiting on cond */
+#define EVTHREAD_COND_BROADCAST(cond)                                  \
+       ( (cond) ? _evthreadimpl_cond_signal((cond), 1) : 0 )
+/** Wait until the condition 'cond' is signalled.  Must be called while
+ * holding 'lock'.  The lock will be released until the condition is
+ * signalled, at which point it will be acquired again.  Returns 0 for
+ * success, -1 for failure. */
+#define EVTHREAD_COND_WAIT(cond, lock)                                 \
+       ( (cond) ? _evthreadimpl_cond_wait((cond), (lock), NULL) : 0 )
+/** As EVTHREAD_COND_WAIT, but gives up after 'tv' has elapsed.  Returns 1
+ * on timeout. */
+#define EVTHREAD_COND_WAIT_TIMED(cond, lock, tv)                       \
+       ( (cond) ? _evthreadimpl_cond_wait((cond), (lock), (tv)) : 0 )
+
+#define EVTHREAD_LOCKING_ENABLED()             \
+       (_evthreadimpl_locking_enabled())
+
+#else /* _EVENT_DISABLE_THREAD_SUPPORT */
+
+#define EVTHREAD_GET_ID()      1
+#define EVTHREAD_ALLOC_LOCK(lockvar, locktype) _EVUTIL_NIL_STMT
+#define EVTHREAD_FREE_LOCK(lockvar, locktype) _EVUTIL_NIL_STMT
+
+#define EVLOCK_LOCK(lockvar, mode) _EVUTIL_NIL_STMT
+#define EVLOCK_UNLOCK(lockvar, mode) _EVUTIL_NIL_STMT
+#define EVLOCK_LOCK2(lock1,lock2,mode1,mode2) _EVUTIL_NIL_STMT
+#define EVLOCK_UNLOCK2(lock1,lock2,mode1,mode2) _EVUTIL_NIL_STMT
+
+#define EVBASE_IN_THREAD(base) 1
+#define EVBASE_NEED_NOTIFY(base) 0
+#define EVBASE_ACQUIRE_LOCK(base, lock) _EVUTIL_NIL_STMT
+#define EVBASE_RELEASE_LOCK(base, lock) _EVUTIL_NIL_STMT
+#define EVLOCK_ASSERT_LOCKED(lock) _EVUTIL_NIL_STMT
+
+#define EVLOCK_TRY_LOCK(lock) 1
+
+#define EVTHREAD_ALLOC_COND(condvar) _EVUTIL_NIL_STMT
+#define EVTHREAD_FREE_COND(cond) _EVUTIL_NIL_STMT
+#define EVTHREAD_COND_SIGNAL(cond) _EVUTIL_NIL_STMT
+#define EVTHREAD_COND_BROADCAST(cond) _EVUTIL_NIL_STMT
+#define EVTHREAD_COND_WAIT(cond, lock) _EVUTIL_NIL_STMT
+#define EVTHREAD_COND_WAIT_TIMED(cond, lock, howlong) _EVUTIL_NIL_STMT
+
+#define EVTHREAD_LOCKING_ENABLED() 0
+
+#endif
+
+/* This code is shared between both lock impls */
+#if ! defined(_EVENT_DISABLE_THREAD_SUPPORT)
+/** Helper: put lockvar1 and lockvar2 into pointerwise ascending order. */
+#define _EVLOCK_SORTLOCKS(lockvar1, lockvar2)                          \
+       do {                                                            \
+               if (lockvar1 && lockvar2 && lockvar1 > lockvar2) {      \
+                       void *tmp = lockvar1;                           \
+                       lockvar1 = lockvar2;                            \
+                       lockvar2 = tmp;                                 \
+               }                                                       \
+       } while (0)
+
+/** Acquire both lock1 and lock2.  Always allocates locks in the same order,
+ * so that two threads locking two locks with LOCK2 will not deadlock. */
+#define EVLOCK_LOCK2(lock1,lock2,mode1,mode2)                          \
+       do {                                                            \
+               void *_lock1_tmplock = (lock1);                         \
+               void *_lock2_tmplock = (lock2);                         \
+               _EVLOCK_SORTLOCKS(_lock1_tmplock,_lock2_tmplock);       \
+               EVLOCK_LOCK(_lock1_tmplock,mode1);                      \
+               if (_lock2_tmplock != _lock1_tmplock)                   \
+                       EVLOCK_LOCK(_lock2_tmplock,mode2);              \
+       } while (0)
+/** Release both lock1 and lock2.  */
+#define EVLOCK_UNLOCK2(lock1,lock2,mode1,mode2)                                \
+       do {                                                            \
+               void *_lock1_tmplock = (lock1);                         \
+               void *_lock2_tmplock = (lock2);                         \
+               _EVLOCK_SORTLOCKS(_lock1_tmplock,_lock2_tmplock);       \
+               if (_lock2_tmplock != _lock1_tmplock)                   \
+                       EVLOCK_UNLOCK(_lock2_tmplock,mode2);            \
+               EVLOCK_UNLOCK(_lock1_tmplock,mode1);                    \
+       } while (0)
+
+int _evthread_is_debug_lock_held(void *lock);
+void *_evthread_debug_get_real_lock(void *lock);
+
+void *evthread_setup_global_lock_(void *lock_, unsigned locktype,
+    int enable_locks);
+
+#define EVTHREAD_SETUP_GLOBAL_LOCK(lockvar, locktype)                  \
+       do {                                                            \
+               lockvar = evthread_setup_global_lock_(lockvar,          \
+                   (locktype), enable_locks);                          \
+               if (!lockvar) {                                         \
+                       event_warn("Couldn't allocate %s", #lockvar);   \
+                       return -1;                                      \
+               }                                                       \
+       } while (0);
+
+int event_global_setup_locks_(const int enable_locks);
+int evsig_global_setup_locks_(const int enable_locks);
+int evutil_secure_rng_global_setup_locks_(const int enable_locks);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVTHREAD_INTERNAL_H_ */
diff --git a/libevent/evthread.c b/libevent/evthread.c
new file mode 100644 (file)
index 0000000..90e195d
--- /dev/null
@@ -0,0 +1,445 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+
+#include "event2/thread.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+#include "evthread-internal.h"
+
+#ifdef EVTHREAD_EXPOSE_STRUCTS
+#define GLOBAL
+#else
+#define GLOBAL static
+#endif
+
+/* globals */
+GLOBAL int _evthread_lock_debugging_enabled = 0;
+GLOBAL struct evthread_lock_callbacks _evthread_lock_fns = {
+       0, 0, NULL, NULL, NULL, NULL
+};
+GLOBAL unsigned long (*_evthread_id_fn)(void) = NULL;
+GLOBAL struct evthread_condition_callbacks _evthread_cond_fns = {
+       0, NULL, NULL, NULL, NULL
+};
+
+/* Used for debugging */
+static struct evthread_lock_callbacks _original_lock_fns = {
+       0, 0, NULL, NULL, NULL, NULL
+};
+static struct evthread_condition_callbacks _original_cond_fns = {
+       0, NULL, NULL, NULL, NULL
+};
+
+void
+evthread_set_id_callback(unsigned long (*id_fn)(void))
+{
+       _evthread_id_fn = id_fn;
+}
+
+int
+evthread_set_lock_callbacks(const struct evthread_lock_callbacks *cbs)
+{
+       struct evthread_lock_callbacks *target =
+           _evthread_lock_debugging_enabled
+           ? &_original_lock_fns : &_evthread_lock_fns;
+
+       if (!cbs) {
+               if (target->alloc)
+                       event_warnx("Trying to disable lock functions after "
+                           "they have been set up will probaby not work.");
+               memset(target, 0, sizeof(_evthread_lock_fns));
+               return 0;
+       }
+       if (target->alloc) {
+               /* Uh oh; we already had locking callbacks set up.*/
+               if (target->lock_api_version == cbs->lock_api_version &&
+                       target->supported_locktypes == cbs->supported_locktypes &&
+                       target->alloc == cbs->alloc &&
+                       target->free == cbs->free &&
+                       target->lock == cbs->lock &&
+                       target->unlock == cbs->unlock) {
+                       /* no change -- allow this. */
+                       return 0;
+               }
+               event_warnx("Can't change lock callbacks once they have been "
+                   "initialized.");
+               return -1;
+       }
+       if (cbs->alloc && cbs->free && cbs->lock && cbs->unlock) {
+               memcpy(target, cbs, sizeof(_evthread_lock_fns));
+               return event_global_setup_locks_(1);
+       } else {
+               return -1;
+       }
+}
+
+int
+evthread_set_condition_callbacks(const struct evthread_condition_callbacks *cbs)
+{
+       struct evthread_condition_callbacks *target =
+           _evthread_lock_debugging_enabled
+           ? &_original_cond_fns : &_evthread_cond_fns;
+
+       if (!cbs) {
+               if (target->alloc_condition)
+                       event_warnx("Trying to disable condition functions "
+                           "after they have been set up will probaby not "
+                           "work.");
+               memset(target, 0, sizeof(_evthread_cond_fns));
+               return 0;
+       }
+       if (target->alloc_condition) {
+               /* Uh oh; we already had condition callbacks set up.*/
+               if (target->condition_api_version == cbs->condition_api_version &&
+                       target->alloc_condition == cbs->alloc_condition &&
+                       target->free_condition == cbs->free_condition &&
+                       target->signal_condition == cbs->signal_condition &&
+                       target->wait_condition == cbs->wait_condition) {
+                       /* no change -- allow this. */
+                       return 0;
+               }
+               event_warnx("Can't change condition callbacks once they "
+                   "have been initialized.");
+               return -1;
+       }
+       if (cbs->alloc_condition && cbs->free_condition &&
+           cbs->signal_condition && cbs->wait_condition) {
+               memcpy(target, cbs, sizeof(_evthread_cond_fns));
+       }
+       if (_evthread_lock_debugging_enabled) {
+               _evthread_cond_fns.alloc_condition = cbs->alloc_condition;
+               _evthread_cond_fns.free_condition = cbs->free_condition;
+               _evthread_cond_fns.signal_condition = cbs->signal_condition;
+       }
+       return 0;
+}
+
+struct debug_lock {
+       unsigned locktype;
+       unsigned long held_by;
+       /* XXXX if we ever use read-write locks, we will need a separate
+        * lock to protect count. */
+       int count;
+       void *lock;
+};
+
+static void *
+debug_lock_alloc(unsigned locktype)
+{
+       struct debug_lock *result = mm_malloc(sizeof(struct debug_lock));
+       if (!result)
+               return NULL;
+       if (_original_lock_fns.alloc) {
+               if (!(result->lock = _original_lock_fns.alloc(
+                               locktype|EVTHREAD_LOCKTYPE_RECURSIVE))) {
+                       mm_free(result);
+                       return NULL;
+               }
+       } else {
+               result->lock = NULL;
+       }
+       result->locktype = locktype;
+       result->count = 0;
+       result->held_by = 0;
+       return result;
+}
+
+static void
+debug_lock_free(void *lock_, unsigned locktype)
+{
+       struct debug_lock *lock = lock_;
+       EVUTIL_ASSERT(lock->count == 0);
+       EVUTIL_ASSERT(locktype == lock->locktype);
+       if (_original_lock_fns.free) {
+               _original_lock_fns.free(lock->lock,
+                   lock->locktype|EVTHREAD_LOCKTYPE_RECURSIVE);
+       }
+       lock->lock = NULL;
+       lock->count = -100;
+       mm_free(lock);
+}
+
+static void
+evthread_debug_lock_mark_locked(unsigned mode, struct debug_lock *lock)
+{
+       ++lock->count;
+       if (!(lock->locktype & EVTHREAD_LOCKTYPE_RECURSIVE))
+               EVUTIL_ASSERT(lock->count == 1);
+       if (_evthread_id_fn) {
+               unsigned long me;
+               me = _evthread_id_fn();
+               if (lock->count > 1)
+                       EVUTIL_ASSERT(lock->held_by == me);
+               lock->held_by = me;
+       }
+}
+
+static int
+debug_lock_lock(unsigned mode, void *lock_)
+{
+       struct debug_lock *lock = lock_;
+       int res = 0;
+       if (lock->locktype & EVTHREAD_LOCKTYPE_READWRITE)
+               EVUTIL_ASSERT(mode & (EVTHREAD_READ|EVTHREAD_WRITE));
+       else
+               EVUTIL_ASSERT((mode & (EVTHREAD_READ|EVTHREAD_WRITE)) == 0);
+       if (_original_lock_fns.lock)
+               res = _original_lock_fns.lock(mode, lock->lock);
+       if (!res) {
+               evthread_debug_lock_mark_locked(mode, lock);
+       }
+       return res;
+}
+
+static void
+evthread_debug_lock_mark_unlocked(unsigned mode, struct debug_lock *lock)
+{
+       if (lock->locktype & EVTHREAD_LOCKTYPE_READWRITE)
+               EVUTIL_ASSERT(mode & (EVTHREAD_READ|EVTHREAD_WRITE));
+       else
+               EVUTIL_ASSERT((mode & (EVTHREAD_READ|EVTHREAD_WRITE)) == 0);
+       if (_evthread_id_fn) {
+               EVUTIL_ASSERT(lock->held_by == _evthread_id_fn());
+               if (lock->count == 1)
+                       lock->held_by = 0;
+       }
+       --lock->count;
+       EVUTIL_ASSERT(lock->count >= 0);
+}
+
+static int
+debug_lock_unlock(unsigned mode, void *lock_)
+{
+       struct debug_lock *lock = lock_;
+       int res = 0;
+       evthread_debug_lock_mark_unlocked(mode, lock);
+       if (_original_lock_fns.unlock)
+               res = _original_lock_fns.unlock(mode, lock->lock);
+       return res;
+}
+
+static int
+debug_cond_wait(void *_cond, void *_lock, const struct timeval *tv)
+{
+       int r;
+       struct debug_lock *lock = _lock;
+       EVUTIL_ASSERT(lock);
+       EVLOCK_ASSERT_LOCKED(_lock);
+       evthread_debug_lock_mark_unlocked(0, lock);
+       r = _original_cond_fns.wait_condition(_cond, lock->lock, tv);
+       evthread_debug_lock_mark_locked(0, lock);
+       return r;
+}
+
+void
+evthread_enable_lock_debuging(void)
+{
+       struct evthread_lock_callbacks cbs = {
+               EVTHREAD_LOCK_API_VERSION,
+               EVTHREAD_LOCKTYPE_RECURSIVE,
+               debug_lock_alloc,
+               debug_lock_free,
+               debug_lock_lock,
+               debug_lock_unlock
+       };
+       if (_evthread_lock_debugging_enabled)
+               return;
+       memcpy(&_original_lock_fns, &_evthread_lock_fns,
+           sizeof(struct evthread_lock_callbacks));
+       memcpy(&_evthread_lock_fns, &cbs,
+           sizeof(struct evthread_lock_callbacks));
+
+       memcpy(&_original_cond_fns, &_evthread_cond_fns,
+           sizeof(struct evthread_condition_callbacks));
+       _evthread_cond_fns.wait_condition = debug_cond_wait;
+       _evthread_lock_debugging_enabled = 1;
+
+       /* XXX return value should get checked. */
+       event_global_setup_locks_(0);
+}
+
+int
+_evthread_is_debug_lock_held(void *lock_)
+{
+       struct debug_lock *lock = lock_;
+       if (! lock->count)
+               return 0;
+       if (_evthread_id_fn) {
+               unsigned long me = _evthread_id_fn();
+               if (lock->held_by != me)
+                       return 0;
+       }
+       return 1;
+}
+
+void *
+_evthread_debug_get_real_lock(void *lock_)
+{
+       struct debug_lock *lock = lock_;
+       return lock->lock;
+}
+
+void *
+evthread_setup_global_lock_(void *lock_, unsigned locktype, int enable_locks)
+{
+       /* there are four cases here:
+          1) we're turning on debugging; locking is not on.
+          2) we're turning on debugging; locking is on.
+          3) we're turning on locking; debugging is not on.
+          4) we're turning on locking; debugging is on. */
+
+       if (!enable_locks && _original_lock_fns.alloc == NULL) {
+               /* Case 1: allocate a debug lock. */
+               EVUTIL_ASSERT(lock_ == NULL);
+               return debug_lock_alloc(locktype);
+       } else if (!enable_locks && _original_lock_fns.alloc != NULL) {
+               /* Case 2: wrap the lock in a debug lock. */
+               struct debug_lock *lock;
+               EVUTIL_ASSERT(lock_ != NULL);
+
+               if (!(locktype & EVTHREAD_LOCKTYPE_RECURSIVE)) {
+                       /* We can't wrap it: We need a recursive lock */
+                       _original_lock_fns.free(lock_, locktype);
+                       return debug_lock_alloc(locktype);
+               }
+               lock = mm_malloc(sizeof(struct debug_lock));
+               if (!lock) {
+                       _original_lock_fns.free(lock_, locktype);
+                       return NULL;
+               }
+               lock->lock = lock_;
+               lock->locktype = locktype;
+               lock->count = 0;
+               lock->held_by = 0;
+               return lock;
+       } else if (enable_locks && ! _evthread_lock_debugging_enabled) {
+               /* Case 3: allocate a regular lock */
+               EVUTIL_ASSERT(lock_ == NULL);
+               return _evthread_lock_fns.alloc(locktype);
+       } else {
+               /* Case 4: Fill in a debug lock with a real lock */
+               struct debug_lock *lock = lock_;
+               EVUTIL_ASSERT(enable_locks &&
+                             _evthread_lock_debugging_enabled);
+               EVUTIL_ASSERT(lock->locktype == locktype);
+               EVUTIL_ASSERT(lock->lock == NULL);
+               lock->lock = _original_lock_fns.alloc(
+                       locktype|EVTHREAD_LOCKTYPE_RECURSIVE);
+               if (!lock->lock) {
+                       lock->count = -200;
+                       mm_free(lock);
+                       return NULL;
+               }
+               return lock;
+       }
+}
+
+
+#ifndef EVTHREAD_EXPOSE_STRUCTS
+unsigned long
+_evthreadimpl_get_id()
+{
+       return _evthread_id_fn ? _evthread_id_fn() : 1;
+}
+void *
+_evthreadimpl_lock_alloc(unsigned locktype)
+{
+       return _evthread_lock_fns.alloc ?
+           _evthread_lock_fns.alloc(locktype) : NULL;
+}
+void
+_evthreadimpl_lock_free(void *lock, unsigned locktype)
+{
+       if (_evthread_lock_fns.free)
+               _evthread_lock_fns.free(lock, locktype);
+}
+int
+_evthreadimpl_lock_lock(unsigned mode, void *lock)
+{
+       if (_evthread_lock_fns.lock)
+               return _evthread_lock_fns.lock(mode, lock);
+       else
+               return 0;
+}
+int
+_evthreadimpl_lock_unlock(unsigned mode, void *lock)
+{
+       if (_evthread_lock_fns.unlock)
+               return _evthread_lock_fns.unlock(mode, lock);
+       else
+               return 0;
+}
+void *
+_evthreadimpl_cond_alloc(unsigned condtype)
+{
+       return _evthread_cond_fns.alloc_condition ?
+           _evthread_cond_fns.alloc_condition(condtype) : NULL;
+}
+void
+_evthreadimpl_cond_free(void *cond)
+{
+       if (_evthread_cond_fns.free_condition)
+               _evthread_cond_fns.free_condition(cond);
+}
+int
+_evthreadimpl_cond_signal(void *cond, int broadcast)
+{
+       if (_evthread_cond_fns.signal_condition)
+               return _evthread_cond_fns.signal_condition(cond, broadcast);
+       else
+               return 0;
+}
+int
+_evthreadimpl_cond_wait(void *cond, void *lock, const struct timeval *tv)
+{
+       if (_evthread_cond_fns.wait_condition)
+               return _evthread_cond_fns.wait_condition(cond, lock, tv);
+       else
+               return 0;
+}
+int
+_evthreadimpl_is_lock_debugging_enabled(void)
+{
+       return _evthread_lock_debugging_enabled;
+}
+
+int
+_evthreadimpl_locking_enabled(void)
+{
+       return _evthread_lock_fns.lock != NULL;
+}
+#endif
+
+#endif
diff --git a/libevent/evthread_pthread.c b/libevent/evthread_pthread.c
new file mode 100644 (file)
index 0000000..c4d06ea
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+/* With glibc we need to define this to get PTHREAD_MUTEX_RECURSIVE. */
+#define _GNU_SOURCE
+#include <pthread.h>
+
+struct event_base;
+#include "event2/thread.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include "mm-internal.h"
+#include "evthread-internal.h"
+
+static pthread_mutexattr_t attr_recursive;
+
+static void *
+evthread_posix_lock_alloc(unsigned locktype)
+{
+       pthread_mutexattr_t *attr = NULL;
+       pthread_mutex_t *lock = mm_malloc(sizeof(pthread_mutex_t));
+       if (!lock)
+               return NULL;
+       if (locktype & EVTHREAD_LOCKTYPE_RECURSIVE)
+               attr = &attr_recursive;
+       if (pthread_mutex_init(lock, attr)) {
+               mm_free(lock);
+               return NULL;
+       }
+       return lock;
+}
+
+static void
+evthread_posix_lock_free(void *_lock, unsigned locktype)
+{
+       pthread_mutex_t *lock = _lock;
+       pthread_mutex_destroy(lock);
+       mm_free(lock);
+}
+
+static int
+evthread_posix_lock(unsigned mode, void *_lock)
+{
+       pthread_mutex_t *lock = _lock;
+       if (mode & EVTHREAD_TRY)
+               return pthread_mutex_trylock(lock);
+       else
+               return pthread_mutex_lock(lock);
+}
+
+static int
+evthread_posix_unlock(unsigned mode, void *_lock)
+{
+       pthread_mutex_t *lock = _lock;
+       return pthread_mutex_unlock(lock);
+}
+
+static unsigned long
+evthread_posix_get_id(void)
+{
+       union {
+               pthread_t thr;
+#if _EVENT_SIZEOF_PTHREAD_T > _EVENT_SIZEOF_LONG
+               ev_uint64_t id;
+#else
+               unsigned long id;
+#endif
+       } r;
+#if _EVENT_SIZEOF_PTHREAD_T < _EVENT_SIZEOF_LONG
+       memset(&r, 0, sizeof(r));
+#endif
+       r.thr = pthread_self();
+       return (unsigned long)r.id;
+}
+
+static void *
+evthread_posix_cond_alloc(unsigned condflags)
+{
+       pthread_cond_t *cond = mm_malloc(sizeof(pthread_cond_t));
+       if (!cond)
+               return NULL;
+       if (pthread_cond_init(cond, NULL)) {
+               mm_free(cond);
+               return NULL;
+       }
+       return cond;
+}
+
+static void
+evthread_posix_cond_free(void *_cond)
+{
+       pthread_cond_t *cond = _cond;
+       pthread_cond_destroy(cond);
+       mm_free(cond);
+}
+
+static int
+evthread_posix_cond_signal(void *_cond, int broadcast)
+{
+       pthread_cond_t *cond = _cond;
+       int r;
+       if (broadcast)
+               r = pthread_cond_broadcast(cond);
+       else
+               r = pthread_cond_signal(cond);
+       return r ? -1 : 0;
+}
+
+static int
+evthread_posix_cond_wait(void *_cond, void *_lock, const struct timeval *tv)
+{
+       int r;
+       pthread_cond_t *cond = _cond;
+       pthread_mutex_t *lock = _lock;
+
+       if (tv) {
+               struct timeval now, abstime;
+               struct timespec ts;
+               evutil_gettimeofday(&now, NULL);
+               evutil_timeradd(&now, tv, &abstime);
+               ts.tv_sec = abstime.tv_sec;
+               ts.tv_nsec = abstime.tv_usec*1000;
+               r = pthread_cond_timedwait(cond, lock, &ts);
+               if (r == ETIMEDOUT)
+                       return 1;
+               else if (r)
+                       return -1;
+               else
+                       return 0;
+       } else {
+               r = pthread_cond_wait(cond, lock);
+               return r ? -1 : 0;
+       }
+}
+
+int
+evthread_use_pthreads(void)
+{
+       struct evthread_lock_callbacks cbs = {
+               EVTHREAD_LOCK_API_VERSION,
+               EVTHREAD_LOCKTYPE_RECURSIVE,
+               evthread_posix_lock_alloc,
+               evthread_posix_lock_free,
+               evthread_posix_lock,
+               evthread_posix_unlock
+       };
+       struct evthread_condition_callbacks cond_cbs = {
+               EVTHREAD_CONDITION_API_VERSION,
+               evthread_posix_cond_alloc,
+               evthread_posix_cond_free,
+               evthread_posix_cond_signal,
+               evthread_posix_cond_wait
+       };
+       /* Set ourselves up to get recursive locks. */
+       if (pthread_mutexattr_init(&attr_recursive))
+               return -1;
+       if (pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE))
+               return -1;
+
+       evthread_set_lock_callbacks(&cbs);
+       evthread_set_condition_callbacks(&cond_cbs);
+       evthread_set_id_callback(evthread_posix_get_id);
+       return 0;
+}
diff --git a/libevent/evthread_win32.c b/libevent/evthread_win32.c
new file mode 100644 (file)
index 0000000..2389d72
--- /dev/null
@@ -0,0 +1,339 @@
+/*
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#ifndef _WIN32_WINNT
+/* Minimum required for InitializeCriticalSectionAndSpinCount */
+#define _WIN32_WINNT 0x0403
+#endif
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#include <sys/locking.h>
+#endif
+
+struct event_base;
+#include "event2/thread.h"
+
+#include "mm-internal.h"
+#include "evthread-internal.h"
+
+#define SPIN_COUNT 2000
+
+static void *
+evthread_win32_lock_create(unsigned locktype)
+{
+       CRITICAL_SECTION *lock = mm_malloc(sizeof(CRITICAL_SECTION));
+       if (!lock)
+               return NULL;
+       if (InitializeCriticalSectionAndSpinCount(lock, SPIN_COUNT) == 0) {
+               mm_free(lock);
+               return NULL;
+       }
+       return lock;
+}
+
+static void
+evthread_win32_lock_free(void *_lock, unsigned locktype)
+{
+       CRITICAL_SECTION *lock = _lock;
+       DeleteCriticalSection(lock);
+       mm_free(lock);
+}
+
+static int
+evthread_win32_lock(unsigned mode, void *_lock)
+{
+       CRITICAL_SECTION *lock = _lock;
+       if ((mode & EVTHREAD_TRY)) {
+               return ! TryEnterCriticalSection(lock);
+       } else {
+               EnterCriticalSection(lock);
+               return 0;
+       }
+}
+
+static int
+evthread_win32_unlock(unsigned mode, void *_lock)
+{
+       CRITICAL_SECTION *lock = _lock;
+       LeaveCriticalSection(lock);
+       return 0;
+}
+
+static unsigned long
+evthread_win32_get_id(void)
+{
+       return (unsigned long) GetCurrentThreadId();
+}
+
+#ifdef WIN32_HAVE_CONDITION_VARIABLES
+static void WINAPI (*InitializeConditionVariable_fn)(PCONDITION_VARIABLE)
+       = NULL;
+static BOOL WINAPI (*SleepConditionVariableCS_fn)(
+       PCONDITION_VARIABLE, PCRITICAL_SECTION, DWORD) = NULL;
+static void WINAPI (*WakeAllConditionVariable_fn)(PCONDITION_VARIABLE) = NULL;
+static void WINAPI (*WakeConditionVariable_fn)(PCONDITION_VARIABLE) = NULL;
+
+static int
+evthread_win32_condvar_init(void)
+{
+       HANDLE lib;
+
+       lib = GetModuleHandle(TEXT("kernel32.dll"));
+       if (lib == NULL)
+               return 0;
+
+#define LOAD(name)                             \
+       name##_fn = GetProcAddress(lib, #name)
+       LOAD(InitializeConditionVariable);
+       LOAD(SleepConditionVariable);
+       LOAD(WakeAllConditionVariable);
+       LOAD(WakeConditionVariable);
+
+       return InitializeConditionVariable_fn && SleepConditionVariableCS_fn &&
+           WakeAllConditionVariable_fn && WakeConditionVariable_fn;
+}
+
+/* XXXX Even if we can build this, we don't necessarily want to: the functions
+ * in question didn't exist before Vista, so we'd better LoadProc them. */
+static void *
+evthread_win32_condvar_alloc(unsigned condflags)
+{
+       CONDITION_VARIABLE *cond = mm_malloc(sizeof(CONDITION_VARIABLE));
+       if (!cond)
+               return NULL;
+       InitializeConditionVariable_fn(cond);
+       return cond;
+}
+
+static void
+evthread_win32_condvar_free(void *_cond)
+{
+       CONDITION_VARIABLE *cond = _cond;
+       /* There doesn't _seem_ to be a cleaup fn here... */
+       mm_free(cond);
+}
+
+static int
+evthread_win32_condvar_signal(void *_cond, int broadcast)
+{
+       CONDITION_VARIABLE *cond = _cond;
+       if (broadcast)
+               WakeAllConditionVariable_fn(cond);
+       else
+               WakeConditionVariable_fn(cond);
+       return 0;
+}
+
+static int
+evthread_win32_condvar_wait(void *_cond, void *_lock, const struct timeval *tv)
+{
+       CONDITION_VARIABLE *cond = _cond;
+       CRITICAL_SECTION *lock = _lock;
+       DWORD ms, err;
+       BOOL result;
+
+       if (tv)
+               ms = evutil_tv_to_msec(tv);
+       else
+               ms = INFINITE;
+       result = SleepConditionVariableCS_fn(cond, lock, ms);
+       if (result) {
+               if (GetLastError() == WAIT_TIMEOUT)
+                       return 1;
+               else
+                       return -1;
+       } else {
+               return 0;
+       }
+}
+#endif
+
+struct evthread_win32_cond {
+       HANDLE event;
+
+       CRITICAL_SECTION lock;
+       int n_waiting;
+       int n_to_wake;
+       int generation;
+};
+
+static void *
+evthread_win32_cond_alloc(unsigned flags)
+{
+       struct evthread_win32_cond *cond;
+       if (!(cond = mm_malloc(sizeof(struct evthread_win32_cond))))
+               return NULL;
+       if (InitializeCriticalSectionAndSpinCount(&cond->lock, SPIN_COUNT)==0) {
+               mm_free(cond);
+               return NULL;
+       }
+       if ((cond->event = CreateEvent(NULL,TRUE,FALSE,NULL)) == NULL) {
+               DeleteCriticalSection(&cond->lock);
+               mm_free(cond);
+               return NULL;
+       }
+       cond->n_waiting = cond->n_to_wake = cond->generation = 0;
+       return cond;
+}
+
+static void
+evthread_win32_cond_free(void *_cond)
+{
+       struct evthread_win32_cond *cond = _cond;
+       DeleteCriticalSection(&cond->lock);
+       CloseHandle(cond->event);
+       mm_free(cond);
+}
+
+static int
+evthread_win32_cond_signal(void *_cond, int broadcast)
+{
+       struct evthread_win32_cond *cond = _cond;
+       EnterCriticalSection(&cond->lock);
+       if (broadcast)
+               cond->n_to_wake = cond->n_waiting;
+       else
+               ++cond->n_to_wake;
+       cond->generation++;
+       SetEvent(cond->event);
+       LeaveCriticalSection(&cond->lock);
+       return 0;
+}
+
+static int
+evthread_win32_cond_wait(void *_cond, void *_lock, const struct timeval *tv)
+{
+       struct evthread_win32_cond *cond = _cond;
+       CRITICAL_SECTION *lock = _lock;
+       int generation_at_start;
+       int waiting = 1;
+       int result = -1;
+       DWORD ms = INFINITE, ms_orig = INFINITE, startTime, endTime;
+       if (tv)
+               ms_orig = ms = evutil_tv_to_msec(tv);
+
+       EnterCriticalSection(&cond->lock);
+       ++cond->n_waiting;
+       generation_at_start = cond->generation;
+       LeaveCriticalSection(&cond->lock);
+
+       LeaveCriticalSection(lock);
+
+       startTime = GetTickCount();
+       do {
+               DWORD res;
+               res = WaitForSingleObject(cond->event, ms);
+               EnterCriticalSection(&cond->lock);
+               if (cond->n_to_wake &&
+                   cond->generation != generation_at_start) {
+                       --cond->n_to_wake;
+                       --cond->n_waiting;
+                       result = 0;
+                       waiting = 0;
+                       goto out;
+               } else if (res != WAIT_OBJECT_0) {
+                       result = (res==WAIT_TIMEOUT) ? 1 : -1;
+                       --cond->n_waiting;
+                       waiting = 0;
+                       goto out;
+               } else if (ms != INFINITE) {
+                       endTime = GetTickCount();
+                       if (startTime + ms_orig <= endTime) {
+                               result = 1; /* Timeout */
+                               --cond->n_waiting;
+                               waiting = 0;
+                               goto out;
+                       } else {
+                               ms = startTime + ms_orig - endTime;
+                       }
+               }
+               /* If we make it here, we are still waiting. */
+               if (cond->n_to_wake == 0) {
+                       /* There is nobody else who should wake up; reset
+                        * the event. */
+                       ResetEvent(cond->event);
+               }
+       out:
+               LeaveCriticalSection(&cond->lock);
+       } while (waiting);
+
+       EnterCriticalSection(lock);
+
+       EnterCriticalSection(&cond->lock);
+       if (!cond->n_waiting)
+               ResetEvent(cond->event);
+       LeaveCriticalSection(&cond->lock);
+
+       return result;
+}
+
+int
+evthread_use_windows_threads(void)
+{
+       struct evthread_lock_callbacks cbs = {
+               EVTHREAD_LOCK_API_VERSION,
+               EVTHREAD_LOCKTYPE_RECURSIVE,
+               evthread_win32_lock_create,
+               evthread_win32_lock_free,
+               evthread_win32_lock,
+               evthread_win32_unlock
+       };
+
+
+       struct evthread_condition_callbacks cond_cbs = {
+               EVTHREAD_CONDITION_API_VERSION,
+               evthread_win32_cond_alloc,
+               evthread_win32_cond_free,
+               evthread_win32_cond_signal,
+               evthread_win32_cond_wait
+       };
+#ifdef WIN32_HAVE_CONDITION_VARIABLES
+       struct evthread_condition_callbacks condvar_cbs = {
+               EVTHREAD_CONDITION_API_VERSION,
+               evthread_win32_condvar_alloc,
+               evthread_win32_condvar_free,
+               evthread_win32_condvar_signal,
+               evthread_win32_condvar_wait
+       };
+#endif
+
+       evthread_set_lock_callbacks(&cbs);
+       evthread_set_id_callback(evthread_win32_get_id);
+#ifdef WIN32_HAVE_CONDITION_VARIABLES
+       if (evthread_win32_condvar_init()) {
+               evthread_set_condition_callbacks(&condvar_cbs);
+               return 0;
+       }
+#endif
+       evthread_set_condition_callbacks(&cond_cbs);
+
+       return 0;
+}
+
diff --git a/libevent/evutil.c b/libevent/evutil.c
new file mode 100644 (file)
index 0000000..b663459
--- /dev/null
@@ -0,0 +1,2177 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#define _GNU_SOURCE
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#include <io.h>
+#include <tchar.h>
+#endif
+
+#include <sys/types.h>
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef _EVENT_HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef _EVENT_HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef _EVENT_HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef _EVENT_HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+
+#ifndef _EVENT_HAVE_GETTIMEOFDAY
+#include <sys/timeb.h>
+#include <time.h>
+#endif
+#include <sys/stat.h>
+
+#include "event2/util.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+
+#include "strlcpy-internal.h"
+#include "ipv6-internal.h"
+
+#ifdef WIN32
+#define open _open
+#define read _read
+#define close _close
+#define fstat _fstati64
+#define stat _stati64
+#endif
+
+int
+evutil_open_closeonexec(const char *pathname, int flags, unsigned mode)
+{
+       int fd;
+
+#ifdef O_CLOEXEC
+       flags |= O_CLOEXEC;
+#endif
+
+       if (flags & O_CREAT)
+               fd = open(pathname, flags, (mode_t)mode);
+       else
+               fd = open(pathname, flags);
+       if (fd < 0)
+               return -1;
+
+#if !defined(O_CLOEXEC) && defined(FD_CLOEXEC)
+       if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
+               return -1;
+#endif
+
+       return fd;
+}
+
+/**
+   Read the contents of 'filename' into a newly allocated NUL-terminated
+   string.  Set *content_out to hold this string, and *len_out to hold its
+   length (not including the appended NUL).  If 'is_binary', open the file in
+   binary mode.
+
+   Returns 0 on success, -1 if the open fails, and -2 for all other failures.
+
+   Used internally only; may go away in a future version.
+ */
+int
+evutil_read_file(const char *filename, char **content_out, size_t *len_out,
+    int is_binary)
+{
+       int fd, r;
+       struct stat st;
+       char *mem;
+       size_t read_so_far=0;
+       int mode = O_RDONLY;
+
+       EVUTIL_ASSERT(content_out);
+       EVUTIL_ASSERT(len_out);
+       *content_out = NULL;
+       *len_out = 0;
+
+#ifdef O_BINARY
+       if (is_binary)
+               mode |= O_BINARY;
+#endif
+
+       fd = evutil_open_closeonexec(filename, mode, 0);
+       if (fd < 0)
+               return -1;
+       if (fstat(fd, &st) || st.st_size < 0 ||
+           st.st_size > EV_SSIZE_MAX-1 ) {
+               close(fd);
+               return -2;
+       }
+       mem = mm_malloc((size_t)st.st_size + 1);
+       if (!mem) {
+               close(fd);
+               return -2;
+       }
+       read_so_far = 0;
+#ifdef WIN32
+#define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
+#else
+#define N_TO_READ(x) (x)
+#endif
+       while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
+               read_so_far += r;
+               if (read_so_far >= (size_t)st.st_size)
+                       break;
+               EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
+       }
+       close(fd);
+       if (r < 0) {
+               mm_free(mem);
+               return -2;
+       }
+       mem[read_so_far] = 0;
+
+       *len_out = read_so_far;
+       *content_out = mem;
+       return 0;
+}
+
+int
+evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
+{
+#ifndef WIN32
+       return socketpair(family, type, protocol, fd);
+#else
+       return evutil_ersatz_socketpair(family, type, protocol, fd);
+#endif
+}
+
+int
+evutil_ersatz_socketpair(int family, int type, int protocol,
+    evutil_socket_t fd[2])
+{
+       /* This code is originally from Tor.  Used with permission. */
+
+       /* This socketpair does not work when localhost is down. So
+        * it's really not the same thing at all. But it's close enough
+        * for now, and really, when localhost is down sometimes, we
+        * have other problems too.
+        */
+#ifdef WIN32
+#define ERR(e) WSA##e
+#else
+#define ERR(e) e
+#endif
+       evutil_socket_t listener = -1;
+       evutil_socket_t connector = -1;
+       evutil_socket_t acceptor = -1;
+       struct sockaddr_in listen_addr;
+       struct sockaddr_in connect_addr;
+       ev_socklen_t size;
+       int saved_errno = -1;
+
+       if (protocol
+               || (family != AF_INET
+#ifdef AF_UNIX
+                   && family != AF_UNIX
+#endif
+               )) {
+               EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
+               return -1;
+       }
+       if (!fd) {
+               EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
+               return -1;
+       }
+
+       listener = socket(AF_INET, type, 0);
+       if (listener < 0)
+               return -1;
+       memset(&listen_addr, 0, sizeof(listen_addr));
+       listen_addr.sin_family = AF_INET;
+       listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+       listen_addr.sin_port = 0;       /* kernel chooses port.  */
+       if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
+               == -1)
+               goto tidy_up_and_fail;
+       if (listen(listener, 1) == -1)
+               goto tidy_up_and_fail;
+
+       connector = socket(AF_INET, type, 0);
+       if (connector < 0)
+               goto tidy_up_and_fail;
+       /* We want to find out the port number to connect to.  */
+       size = sizeof(connect_addr);
+       if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
+               goto tidy_up_and_fail;
+       if (size != sizeof (connect_addr))
+               goto abort_tidy_up_and_fail;
+       if (connect(connector, (struct sockaddr *) &connect_addr,
+                               sizeof(connect_addr)) == -1)
+               goto tidy_up_and_fail;
+
+       size = sizeof(listen_addr);
+       acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
+       if (acceptor < 0)
+               goto tidy_up_and_fail;
+       if (size != sizeof(listen_addr))
+               goto abort_tidy_up_and_fail;
+       evutil_closesocket(listener);
+       /* Now check we are talking to ourself by matching port and host on the
+          two sockets.  */
+       if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
+               goto tidy_up_and_fail;
+       if (size != sizeof (connect_addr)
+               || listen_addr.sin_family != connect_addr.sin_family
+               || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
+               || listen_addr.sin_port != connect_addr.sin_port)
+               goto abort_tidy_up_and_fail;
+       fd[0] = connector;
+       fd[1] = acceptor;
+
+       return 0;
+
+ abort_tidy_up_and_fail:
+       saved_errno = ERR(ECONNABORTED);
+ tidy_up_and_fail:
+       if (saved_errno < 0)
+               saved_errno = EVUTIL_SOCKET_ERROR();
+       if (listener != -1)
+               evutil_closesocket(listener);
+       if (connector != -1)
+               evutil_closesocket(connector);
+       if (acceptor != -1)
+               evutil_closesocket(acceptor);
+
+       EVUTIL_SET_SOCKET_ERROR(saved_errno);
+       return -1;
+#undef ERR
+}
+
+int
+evutil_make_socket_nonblocking(evutil_socket_t fd)
+{
+#ifdef WIN32
+       {
+               u_long nonblocking = 1;
+               if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
+                       event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
+                       return -1;
+               }
+       }
+#else
+       {
+               int flags;
+               if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
+                       event_warn("fcntl(%d, F_GETFL)", fd);
+                       return -1;
+               }
+               if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
+                       event_warn("fcntl(%d, F_SETFL)", fd);
+                       return -1;
+               }
+       }
+#endif
+       return 0;
+}
+
+int
+evutil_make_listen_socket_reuseable(evutil_socket_t sock)
+{
+#ifndef WIN32
+       int one = 1;
+       /* REUSEADDR on Unix means, "don't hang on to this address after the
+        * listener is closed."  On Windows, though, it means "don't keep other
+        * processes from binding to this address while we're using it. */
+       return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
+           (ev_socklen_t)sizeof(one));
+#else
+       return 0;
+#endif
+}
+
+int
+evutil_make_socket_closeonexec(evutil_socket_t fd)
+{
+#if !defined(WIN32) && defined(_EVENT_HAVE_SETFD)
+       int flags;
+       if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
+               event_warn("fcntl(%d, F_GETFD)", fd);
+               return -1;
+       }
+       if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
+               event_warn("fcntl(%d, F_SETFD)", fd);
+               return -1;
+       }
+#endif
+       return 0;
+}
+
+int
+evutil_closesocket(evutil_socket_t sock)
+{
+#ifndef WIN32
+       return close(sock);
+#else
+       return closesocket(sock);
+#endif
+}
+
+ev_int64_t
+evutil_strtoll(const char *s, char **endptr, int base)
+{
+#ifdef _EVENT_HAVE_STRTOLL
+       return (ev_int64_t)strtoll(s, endptr, base);
+#elif _EVENT_SIZEOF_LONG == 8
+       return (ev_int64_t)strtol(s, endptr, base);
+#elif defined(WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
+       /* XXXX on old versions of MS APIs, we only support base
+        * 10. */
+       ev_int64_t r;
+       if (base != 10)
+               return 0;
+       r = (ev_int64_t) _atoi64(s);
+       while (isspace(*s))
+               ++s;
+       if (*s == '-')
+               ++s;
+       while (isdigit(*s))
+               ++s;
+       if (endptr)
+               *endptr = (char*) s;
+       return r;
+#elif defined(WIN32)
+       return (ev_int64_t) _strtoi64(s, endptr, base);
+#elif defined(_EVENT_SIZEOF_LONG_LONG) && _EVENT_SIZEOF_LONG_LONG == 8
+       long long r;
+       int n;
+       if (base != 10 && base != 16)
+               return 0;
+       if (base == 10) {
+               n = sscanf(s, "%lld", &r);
+       } else {
+               unsigned long long ru=0;
+               n = sscanf(s, "%llx", &ru);
+               if (ru > EV_INT64_MAX)
+                       return 0;
+               r = (long long) ru;
+       }
+       if (n != 1)
+               return 0;
+       while (EVUTIL_ISSPACE(*s))
+               ++s;
+       if (*s == '-')
+               ++s;
+       if (base == 10) {
+               while (EVUTIL_ISDIGIT(*s))
+                       ++s;
+       } else {
+               while (EVUTIL_ISXDIGIT(*s))
+                       ++s;
+       }
+       if (endptr)
+               *endptr = (char*) s;
+       return r;
+#else
+#error "I don't know how to parse 64-bit integers."
+#endif
+}
+
+#ifndef _EVENT_HAVE_GETTIMEOFDAY
+/* No gettimeofday; this muse be windows. */
+int
+evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+       struct _timeb tb;
+
+       if (tv == NULL)
+               return -1;
+
+       /* XXXX
+        * _ftime is not the greatest interface here; GetSystemTimeAsFileTime
+        * would give us better resolution, whereas something cobbled together
+        * with GetTickCount could maybe give us monotonic behavior.
+        *
+        * Either way, I think this value might be skewed to ignore the
+        * timezone, and just return local time.  That's not so good.
+        */
+       _ftime(&tb);
+       tv->tv_sec = (long) tb.time;
+       tv->tv_usec = ((int) tb.millitm) * 1000;
+       return 0;
+}
+#endif
+
+#ifdef WIN32
+int
+evutil_socket_geterror(evutil_socket_t sock)
+{
+       int optval, optvallen=sizeof(optval);
+       int err = WSAGetLastError();
+       if (err == WSAEWOULDBLOCK && sock >= 0) {
+               if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
+                                          &optvallen))
+                       return err;
+               if (optval)
+                       return optval;
+       }
+       return err;
+}
+#endif
+
+/* XXX we should use an enum here. */
+/* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
+int
+evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
+{
+       int made_fd = 0;
+
+       if (*fd_ptr < 0) {
+               if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
+                       goto err;
+               made_fd = 1;
+               if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
+                       goto err;
+               }
+       }
+
+       if (connect(*fd_ptr, sa, socklen) < 0) {
+               int e = evutil_socket_geterror(*fd_ptr);
+               if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
+                       return 0;
+               if (EVUTIL_ERR_CONNECT_REFUSED(e))
+                       return 2;
+               goto err;
+       } else {
+               return 1;
+       }
+
+err:
+       if (made_fd) {
+               evutil_closesocket(*fd_ptr);
+               *fd_ptr = -1;
+       }
+       return -1;
+}
+
+/* Check whether a socket on which we called connect() is done
+   connecting. Return 1 for connected, 0 for not yet, -1 for error.  In the
+   error case, set the current socket errno to the error that happened during
+   the connect operation. */
+int
+evutil_socket_finished_connecting(evutil_socket_t fd)
+{
+       int e;
+       ev_socklen_t elen = sizeof(e);
+
+       if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
+               return -1;
+
+       if (e) {
+               if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
+                       return 0;
+               EVUTIL_SET_SOCKET_ERROR(e);
+               return -1;
+       }
+
+       return 1;
+}
+
+#if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
+     EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
+     EVUTIL_AI_ADDRCONFIG) != \
+    (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
+     EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
+     EVUTIL_AI_ADDRCONFIG)
+#error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
+#endif
+
+/* We sometimes need to know whether we have an ipv4 address and whether we
+   have an ipv6 address. If 'have_checked_interfaces', then we've already done
+   the test.  If 'had_ipv4_address', then it turns out we had an ipv4 address.
+   If 'had_ipv6_address', then it turns out we had an ipv6 address.   These are
+   set by evutil_check_interfaces. */
+static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
+
+/* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8
+ */
+#define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127)
+
+/* Macro: True iff the IPv4 address 'addr', in host order, is a class D
+ * (multiclass) address.
+ */
+#define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
+
+/* Test whether we have an ipv4 interface and an ipv6 interface.  Return 0 if
+ * the test seemed successful. */
+static int
+evutil_check_interfaces(int force_recheck)
+{
+       const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
+           "\x00\x00\x00\x00\x00\x00\x00\x00";
+       evutil_socket_t fd = -1;
+       struct sockaddr_in sin, sin_out;
+       struct sockaddr_in6 sin6, sin6_out;
+       ev_socklen_t sin_out_len = sizeof(sin_out);
+       ev_socklen_t sin6_out_len = sizeof(sin6_out);
+       int r;
+       char buf[128];
+       if (have_checked_interfaces && !force_recheck)
+               return 0;
+
+       /* To check whether we have an interface open for a given protocol, we
+        * try to make a UDP 'connection' to a remote host on the internet.
+        * We don't actually use it, so the address doesn't matter, but we
+        * want to pick one that keep us from using a host- or link-local
+        * interface. */
+       memset(&sin, 0, sizeof(sin));
+       sin.sin_family = AF_INET;
+       sin.sin_port = htons(53);
+       r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
+       EVUTIL_ASSERT(r);
+
+       memset(&sin6, 0, sizeof(sin6));
+       sin6.sin6_family = AF_INET6;
+       sin6.sin6_port = htons(53);
+       r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
+       EVUTIL_ASSERT(r);
+
+       memset(&sin_out, 0, sizeof(sin_out));
+       memset(&sin6_out, 0, sizeof(sin6_out));
+
+       /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
+       if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
+           connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
+           getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
+               /* We might have an IPv4 interface. */
+               ev_uint32_t addr = ntohl(sin_out.sin_addr.s_addr);
+               if (addr == 0 ||
+                   EVUTIL_V4ADDR_IS_LOCALHOST(addr) ||
+                   EVUTIL_V4ADDR_IS_CLASSD(addr)) {
+                       evutil_inet_ntop(AF_INET, &sin_out.sin_addr,
+                           buf, sizeof(buf));
+                       /* This is a reserved, ipv4compat, ipv4map, loopback,
+                        * link-local or unspecified address.  The host should
+                        * never have given it to us; it could never connect
+                        * to sin. */
+                       event_warnx("Got a strange local ipv4 address %s",buf);
+               } else {
+                       event_debug(("Detected an IPv4 interface"));
+                       had_ipv4_address = 1;
+               }
+       }
+       if (fd >= 0)
+               evutil_closesocket(fd);
+
+       if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
+           connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
+           getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
+               /* We might have an IPv6 interface. */
+               const unsigned char *addr =
+                   (unsigned char*)sin6_out.sin6_addr.s6_addr;
+               if (!memcmp(addr, ZEROES, 8) ||
+                   (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80)) {
+                       /* This is a reserved, ipv4compat, ipv4map, loopback,
+                        * link-local or unspecified address.  The host should
+                        * never have given it to us; it could never connect
+                        * to sin6. */
+                       evutil_inet_ntop(AF_INET6, &sin6_out.sin6_addr,
+                           buf, sizeof(buf));
+                       event_warnx("Got a strange local ipv6 address %s",buf);
+               } else {
+                       event_debug(("Detected an IPv4 interface"));
+                       had_ipv6_address = 1;
+               }
+       }
+
+       if (fd >= 0)
+               evutil_closesocket(fd);
+
+       return 0;
+}
+
+/* Internal addrinfo flag.  This one is set when we allocate the addrinfo from
+ * inside libevent.  Otherwise, the built-in getaddrinfo() function allocated
+ * it, and we should trust what they said.
+ **/
+#define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
+
+/* Helper: construct a new addrinfo containing the socket address in
+ * 'sa', which must be a sockaddr_in or a sockaddr_in6.  Take the
+ * socktype and protocol info from hints.  If they weren't set, then
+ * allocate both a TCP and a UDP addrinfo.
+ */
+struct evutil_addrinfo *
+evutil_new_addrinfo(struct sockaddr *sa, ev_socklen_t socklen,
+    const struct evutil_addrinfo *hints)
+{
+       struct evutil_addrinfo *res;
+       EVUTIL_ASSERT(hints);
+
+       if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
+               /* Indecisive user! Give them a UDP and a TCP. */
+               struct evutil_addrinfo *r1, *r2;
+               struct evutil_addrinfo tmp;
+               memcpy(&tmp, hints, sizeof(tmp));
+               tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
+               r1 = evutil_new_addrinfo(sa, socklen, &tmp);
+               if (!r1)
+                       return NULL;
+               tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
+               r2 = evutil_new_addrinfo(sa, socklen, &tmp);
+               if (!r2) {
+                       evutil_freeaddrinfo(r1);
+                       return NULL;
+               }
+               r1->ai_next = r2;
+               return r1;
+       }
+
+       /* We're going to allocate extra space to hold the sockaddr. */
+       res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
+       if (!res)
+               return NULL;
+       res->ai_addr = (struct sockaddr*)
+           (((char*)res) + sizeof(struct evutil_addrinfo));
+       memcpy(res->ai_addr, sa, socklen);
+       res->ai_addrlen = socklen;
+       res->ai_family = sa->sa_family; /* Same or not? XXX */
+       res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
+       res->ai_socktype = hints->ai_socktype;
+       res->ai_protocol = hints->ai_protocol;
+
+       return res;
+}
+
+/* Append the addrinfo 'append' to the end of 'first', and return the start of
+ * the list.  Either element can be NULL, in which case we return the element
+ * that is not NULL. */
+struct evutil_addrinfo *
+evutil_addrinfo_append(struct evutil_addrinfo *first,
+    struct evutil_addrinfo *append)
+{
+       struct evutil_addrinfo *ai = first;
+       if (!ai)
+               return append;
+       while (ai->ai_next)
+               ai = ai->ai_next;
+       ai->ai_next = append;
+
+       return first;
+}
+
+static int
+parse_numeric_servname(const char *servname)
+{
+       int n;
+       char *endptr=NULL;
+       n = (int) strtol(servname, &endptr, 10);
+       if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
+               return n;
+       else
+               return -1;
+}
+
+/** Parse a service name in 'servname', which can be a decimal port.
+ * Return the port number, or -1 on error.
+ */
+static int
+evutil_parse_servname(const char *servname, const char *protocol,
+    const struct evutil_addrinfo *hints)
+{
+       int n = parse_numeric_servname(servname);
+       if (n>=0)
+               return n;
+#if defined(_EVENT_HAVE_GETSERVBYNAME) || defined(WIN32)
+       if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
+               struct servent *ent = getservbyname(servname, protocol);
+               if (ent) {
+                       return ntohs(ent->s_port);
+               }
+       }
+#endif
+       return -1;
+}
+
+/* Return a string corresponding to a protocol number that we can pass to
+ * getservyname.  */
+static const char *
+evutil_unparse_protoname(int proto)
+{
+       switch (proto) {
+       case 0:
+               return NULL;
+       case IPPROTO_TCP:
+               return "tcp";
+       case IPPROTO_UDP:
+               return "udp";
+#ifdef IPPROTO_SCTP
+       case IPPROTO_SCTP:
+               return "sctp";
+#endif
+       default:
+#ifdef _EVENT_HAVE_GETPROTOBYNUMBER
+               {
+                       struct protoent *ent = getprotobynumber(proto);
+                       if (ent)
+                               return ent->p_name;
+               }
+#endif
+               return NULL;
+       }
+}
+
+static void
+evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
+{
+       /* If we can guess the protocol from the socktype, do so. */
+       if (!hints->ai_protocol && hints->ai_socktype) {
+               if (hints->ai_socktype == SOCK_DGRAM)
+                       hints->ai_protocol = IPPROTO_UDP;
+               else if (hints->ai_socktype == SOCK_STREAM)
+                       hints->ai_protocol = IPPROTO_TCP;
+       }
+
+       /* Set the socktype if it isn't set. */
+       if (!hints->ai_socktype && hints->ai_protocol) {
+               if (hints->ai_protocol == IPPROTO_UDP)
+                       hints->ai_socktype = SOCK_DGRAM;
+               else if (hints->ai_protocol == IPPROTO_TCP)
+                       hints->ai_socktype = SOCK_STREAM;
+#ifdef IPPROTO_SCTP
+               else if (hints->ai_protocol == IPPROTO_SCTP)
+                       hints->ai_socktype = SOCK_STREAM;
+#endif
+       }
+}
+
+#if AF_UNSPEC != PF_UNSPEC
+#error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
+#endif
+
+/** Implements the part of looking up hosts by name that's common to both
+ * the blocking and nonblocking resolver:
+ *   - Adjust 'hints' to have a reasonable socktype and protocol.
+ *   - Look up the port based on 'servname', and store it in *portnum,
+ *   - Handle the nodename==NULL case
+ *   - Handle some invalid arguments cases.
+ *   - Handle the cases where nodename is an IPv4 or IPv6 address.
+ *
+ * If we need the resolver to look up the hostname, we return
+ * EVUTIL_EAI_NEED_RESOLVE.  Otherwise, we can completely implement
+ * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
+ * set *res as getaddrinfo would.
+ */
+int
+evutil_getaddrinfo_common(const char *nodename, const char *servname,
+    struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
+{
+       int port = 0;
+       const char *pname;
+
+       if (nodename == NULL && servname == NULL)
+               return EVUTIL_EAI_NONAME;
+
+       /* We only understand 3 families */
+       if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
+           hints->ai_family != PF_INET6)
+               return EVUTIL_EAI_FAMILY;
+
+       evutil_getaddrinfo_infer_protocols(hints);
+
+       /* Look up the port number and protocol, if possible. */
+       pname = evutil_unparse_protoname(hints->ai_protocol);
+       if (servname) {
+               /* XXXX We could look at the protocol we got back from
+                * getservbyname, but it doesn't seem too useful. */
+               port = evutil_parse_servname(servname, pname, hints);
+               if (port < 0) {
+                       return EVUTIL_EAI_NONAME;
+               }
+       }
+
+       /* If we have no node name, then we're supposed to bind to 'any' and
+        * connect to localhost. */
+       if (nodename == NULL) {
+               struct evutil_addrinfo *res4=NULL, *res6=NULL;
+               if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
+                       struct sockaddr_in6 sin6;
+                       memset(&sin6, 0, sizeof(sin6));
+                       sin6.sin6_family = AF_INET6;
+                       sin6.sin6_port = htons(port);
+                       if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
+                               /* Bind to :: */
+                       } else {
+                               /* connect to ::1 */
+                               sin6.sin6_addr.s6_addr[15] = 1;
+                       }
+                       res6 = evutil_new_addrinfo((struct sockaddr*)&sin6,
+                           sizeof(sin6), hints);
+                       if (!res6)
+                               return EVUTIL_EAI_MEMORY;
+               }
+
+               if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
+                       struct sockaddr_in sin;
+                       memset(&sin, 0, sizeof(sin));
+                       sin.sin_family = AF_INET;
+                       sin.sin_port = htons(port);
+                       if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
+                               /* Bind to 0.0.0.0 */
+                       } else {
+                               /* connect to 127.0.0.1 */
+                               sin.sin_addr.s_addr = htonl(0x7f000001);
+                       }
+                       res4 = evutil_new_addrinfo((struct sockaddr*)&sin,
+                           sizeof(sin), hints);
+                       if (!res4) {
+                               if (res6)
+                                       evutil_freeaddrinfo(res6);
+                               return EVUTIL_EAI_MEMORY;
+                       }
+               }
+               *res = evutil_addrinfo_append(res4, res6);
+               return 0;
+       }
+
+       /* If we can, we should try to parse the hostname without resolving
+        * it. */
+       /* Try ipv6. */
+       if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
+               struct sockaddr_in6 sin6;
+               memset(&sin6, 0, sizeof(sin6));
+               if (1==evutil_inet_pton(AF_INET6, nodename, &sin6.sin6_addr)) {
+                       /* Got an ipv6 address. */
+                       sin6.sin6_family = AF_INET6;
+                       sin6.sin6_port = htons(port);
+                       *res = evutil_new_addrinfo((struct sockaddr*)&sin6,
+                           sizeof(sin6), hints);
+                       if (!*res)
+                               return EVUTIL_EAI_MEMORY;
+                       return 0;
+               }
+       }
+
+       /* Try ipv4. */
+       if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
+               struct sockaddr_in sin;
+               memset(&sin, 0, sizeof(sin));
+               if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
+                       /* Got an ipv6 address. */
+                       sin.sin_family = AF_INET;
+                       sin.sin_port = htons(port);
+                       *res = evutil_new_addrinfo((struct sockaddr*)&sin,
+                           sizeof(sin), hints);
+                       if (!*res)
+                               return EVUTIL_EAI_MEMORY;
+                       return 0;
+               }
+       }
+
+
+       /* If we have reached this point, we definitely need to do a DNS
+        * lookup. */
+       if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
+               /* If we're not allowed to do one, then say so. */
+               return EVUTIL_EAI_NONAME;
+       }
+       *portnum = port;
+       return EVUTIL_EAI_NEED_RESOLVE;
+}
+
+#ifdef _EVENT_HAVE_GETADDRINFO
+#define USE_NATIVE_GETADDRINFO
+#endif
+
+#ifdef USE_NATIVE_GETADDRINFO
+/* A mask of all the flags that we declare, so we can clear them before calling
+ * the native getaddrinfo */
+static const unsigned int ALL_NONNATIVE_AI_FLAGS =
+#ifndef AI_PASSIVE
+    EVUTIL_AI_PASSIVE |
+#endif
+#ifndef AI_CANONNAME
+    EVUTIL_AI_CANONNAME |
+#endif
+#ifndef AI_NUMERICHOST
+    EVUTIL_AI_NUMERICHOST |
+#endif
+#ifndef AI_NUMERICSERV
+    EVUTIL_AI_NUMERICSERV |
+#endif
+#ifndef AI_ADDRCONFIG
+    EVUTIL_AI_ADDRCONFIG |
+#endif
+#ifndef AI_ALL
+    EVUTIL_AI_ALL |
+#endif
+#ifndef AI_V4MAPPED
+    EVUTIL_AI_V4MAPPED |
+#endif
+    EVUTIL_AI_LIBEVENT_ALLOCATED;
+
+static const unsigned int ALL_NATIVE_AI_FLAGS =
+#ifdef AI_PASSIVE
+    AI_PASSIVE |
+#endif
+#ifdef AI_CANONNAME
+    AI_CANONNAME |
+#endif
+#ifdef AI_NUMERICHOST
+    AI_NUMERICHOST |
+#endif
+#ifdef AI_NUMERICSERV
+    AI_NUMERICSERV |
+#endif
+#ifdef AI_ADDRCONFIG
+    AI_ADDRCONFIG |
+#endif
+#ifdef AI_ALL
+    AI_ALL |
+#endif
+#ifdef AI_V4MAPPED
+    AI_V4MAPPED |
+#endif
+    0;
+#endif
+
+#ifndef USE_NATIVE_GETADDRINFO
+/* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
+ * a struct hostent.
+ */
+static struct evutil_addrinfo *
+addrinfo_from_hostent(const struct hostent *ent,
+    int port, const struct evutil_addrinfo *hints)
+{
+       int i;
+       struct sockaddr_in sin;
+       struct sockaddr_in6 sin6;
+       struct sockaddr *sa;
+       int socklen;
+       struct evutil_addrinfo *res=NULL, *ai;
+       void *addrp;
+
+       if (ent->h_addrtype == PF_INET) {
+               memset(&sin, 0, sizeof(sin));
+               sin.sin_family = AF_INET;
+               sin.sin_port = htons(port);
+               sa = (struct sockaddr *)&sin;
+               socklen = sizeof(struct sockaddr_in);
+               addrp = &sin.sin_addr;
+               if (ent->h_length != sizeof(sin.sin_addr)) {
+                       event_warnx("Weird h_length from gethostbyname");
+                       return NULL;
+               }
+       } else if (ent->h_addrtype == PF_INET6) {
+               memset(&sin6, 0, sizeof(sin6));
+               sin6.sin6_family = AF_INET6;
+               sin6.sin6_port = htons(port);
+               sa = (struct sockaddr *)&sin6;
+               socklen = sizeof(struct sockaddr_in);
+               addrp = &sin6.sin6_addr;
+               if (ent->h_length != sizeof(sin6.sin6_addr)) {
+                       event_warnx("Weird h_length from gethostbyname");
+                       return NULL;
+               }
+       } else
+               return NULL;
+
+       for (i = 0; ent->h_addr_list[i]; ++i) {
+               memcpy(addrp, ent->h_addr_list[i], ent->h_length);
+               ai = evutil_new_addrinfo(sa, socklen, hints);
+               if (!ai) {
+                       evutil_freeaddrinfo(res);
+                       return NULL;
+               }
+               res = evutil_addrinfo_append(res, ai);
+       }
+
+       if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
+               res->ai_canonname = mm_strdup(ent->h_name);
+               if (res->ai_canonname == NULL) {
+                       evutil_freeaddrinfo(res);
+                       return NULL;
+               }
+       }
+
+       return res;
+}
+#endif
+
+/* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
+ * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
+ * that we'll only get addresses we could maybe connect to.
+ */
+void
+evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints)
+{
+       if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
+               return;
+       if (hints->ai_family != PF_UNSPEC)
+               return;
+       if (!have_checked_interfaces)
+               evutil_check_interfaces(0);
+       if (had_ipv4_address && !had_ipv6_address) {
+               hints->ai_family = PF_INET;
+       } else if (!had_ipv4_address && had_ipv6_address) {
+               hints->ai_family = PF_INET6;
+       }
+}
+
+#ifdef USE_NATIVE_GETADDRINFO
+static int need_numeric_port_hack_=0;
+static int need_socktype_protocol_hack_=0;
+static int tested_for_getaddrinfo_hacks=0;
+
+/* Some older BSDs (like OpenBSD up to 4.6) used to believe that
+   giving a numeric port without giving an ai_socktype was verboten.
+   We test for this so we can apply an appropriate workaround.  If it
+   turns out that the bug is present, then:
+
+    - If nodename==NULL and servname is numeric, we build an answer
+      ourselves using evutil_getaddrinfo_common().
+
+    - If nodename!=NULL and servname is numeric, then we set
+      servname=NULL when calling getaddrinfo, and post-process the
+      result to set the ports on it.
+
+   We test for this bug at runtime, since otherwise we can't have the
+   same binary run on multiple BSD versions.
+
+   - Some versions of Solaris believe that it's nice to leave to protocol
+     field set to 0.  We test for this so we can apply an appropriate
+     workaround.
+*/
+static void
+test_for_getaddrinfo_hacks(void)
+{
+       int r, r2;
+       struct evutil_addrinfo *ai=NULL, *ai2=NULL;
+       struct evutil_addrinfo hints;
+
+       memset(&hints,0,sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_flags =
+#ifdef AI_NUMERICHOST
+           AI_NUMERICHOST |
+#endif
+#ifdef AI_NUMERICSERV
+           AI_NUMERICSERV |
+#endif
+           0;
+       r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
+       hints.ai_socktype = SOCK_STREAM;
+       r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
+       if (r2 == 0 && r != 0) {
+               need_numeric_port_hack_=1;
+       }
+       if (ai2 && ai2->ai_protocol == 0) {
+               need_socktype_protocol_hack_=1;
+       }
+
+       if (ai)
+               freeaddrinfo(ai);
+       if (ai2)
+               freeaddrinfo(ai2);
+       tested_for_getaddrinfo_hacks=1;
+}
+
+static inline int
+need_numeric_port_hack(void)
+{
+       if (!tested_for_getaddrinfo_hacks)
+               test_for_getaddrinfo_hacks();
+       return need_numeric_port_hack_;
+}
+
+static inline int
+need_socktype_protocol_hack(void)
+{
+       if (!tested_for_getaddrinfo_hacks)
+               test_for_getaddrinfo_hacks();
+       return need_socktype_protocol_hack_;
+}
+
+static void
+apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
+{
+       /* Now we run through the list and set the ports on all of the
+        * results where ports would make sense. */
+       for ( ; *ai; ai = &(*ai)->ai_next) {
+               struct sockaddr *sa = (*ai)->ai_addr;
+               if (sa && sa->sa_family == AF_INET) {
+                       struct sockaddr_in *sin = (struct sockaddr_in*)sa;
+                       sin->sin_port = htons(port);
+               } else if (sa && sa->sa_family == AF_INET6) {
+                       struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
+                       sin6->sin6_port = htons(port);
+               } else {
+                       /* A numeric port makes no sense here; remove this one
+                        * from the list. */
+                       struct evutil_addrinfo *victim = *ai;
+                       *ai = victim->ai_next;
+                       victim->ai_next = NULL;
+                       freeaddrinfo(victim);
+               }
+       }
+}
+
+static int
+apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
+{
+       struct evutil_addrinfo *ai_new;
+       for (; ai; ai = ai->ai_next) {
+               evutil_getaddrinfo_infer_protocols(ai);
+               if (ai->ai_socktype || ai->ai_protocol)
+                       continue;
+               ai_new = mm_malloc(sizeof(*ai_new));
+               if (!ai_new)
+                       return -1;
+               memcpy(ai_new, ai, sizeof(*ai_new));
+               ai->ai_socktype = SOCK_STREAM;
+               ai->ai_protocol = IPPROTO_TCP;
+               ai_new->ai_socktype = SOCK_DGRAM;
+               ai_new->ai_protocol = IPPROTO_UDP;
+
+               ai_new->ai_next = ai->ai_next;
+               ai->ai_next = ai_new;
+       }
+       return 0;
+}
+#endif
+
+int
+evutil_getaddrinfo(const char *nodename, const char *servname,
+    const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
+{
+#ifdef USE_NATIVE_GETADDRINFO
+       struct evutil_addrinfo hints;
+       int portnum=-1, need_np_hack, err;
+
+       if (hints_in) {
+               memcpy(&hints, hints_in, sizeof(hints));
+       } else {
+               memset(&hints, 0, sizeof(hints));
+               hints.ai_family = PF_UNSPEC;
+       }
+
+#ifndef AI_ADDRCONFIG
+       /* Not every system has AI_ADDRCONFIG, so fake it. */
+       if (hints.ai_family == PF_UNSPEC &&
+           (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
+               evutil_adjust_hints_for_addrconfig(&hints);
+       }
+#endif
+
+#ifndef AI_NUMERICSERV
+       /* Not every system has AI_NUMERICSERV, so fake it. */
+       if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
+               if (servname && parse_numeric_servname(servname)<0)
+                       return EVUTIL_EAI_NONAME;
+       }
+#endif
+
+       /* Enough operating systems handle enough common non-resolve
+        * cases here weirdly enough that we are better off just
+        * overriding them.  For example:
+        *
+        * - Windows doesn't like to infer the protocol from the
+        *   socket type, or fill in socket or protocol types much at
+        *   all.  It also seems to do its own broken implicit
+        *   always-on version of AI_ADDRCONFIG that keeps it from
+        *   ever resolving even a literal IPv6 address when
+        *   ai_addrtype is PF_UNSPEC.
+        */
+#ifdef WIN32
+       {
+               int tmp_port;
+               err = evutil_getaddrinfo_common(nodename,servname,&hints,
+                   res, &tmp_port);
+               if (err == 0 ||
+                   err == EVUTIL_EAI_MEMORY ||
+                   err == EVUTIL_EAI_NONAME)
+                       return err;
+               /* If we make it here, the system getaddrinfo can
+                * have a crack at it. */
+       }
+#endif
+
+       /* See documentation for need_numeric_port_hack above.*/
+       need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
+           && ((portnum=parse_numeric_servname(servname)) >= 0);
+       if (need_np_hack) {
+               if (!nodename)
+                       return evutil_getaddrinfo_common(
+                               NULL,servname,&hints, res, &portnum);
+               servname = NULL;
+       }
+
+       if (need_socktype_protocol_hack()) {
+               evutil_getaddrinfo_infer_protocols(&hints);
+       }
+
+       /* Make sure that we didn't actually steal any AI_FLAGS values that
+        * the system is using.  (This is a constant expression, and should ge
+        * optimized out.)
+        *
+        * XXXX Turn this into a compile-time failure rather than a run-time
+        * failure.
+        */
+       EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
+
+       /* Clear any flags that only libevent understands. */
+       hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
+
+       err = getaddrinfo(nodename, servname, &hints, res);
+       if (need_np_hack)
+               apply_numeric_port_hack(portnum, res);
+
+       if (need_socktype_protocol_hack()) {
+               if (apply_socktype_protocol_hack(*res) < 0) {
+                       evutil_freeaddrinfo(*res);
+                       *res = NULL;
+                       return EVUTIL_EAI_MEMORY;
+               }
+       }
+       return err;
+#else
+       int port=0, err;
+       struct hostent *ent = NULL;
+       struct evutil_addrinfo hints;
+
+       if (hints_in) {
+               memcpy(&hints, hints_in, sizeof(hints));
+       } else {
+               memset(&hints, 0, sizeof(hints));
+               hints.ai_family = PF_UNSPEC;
+       }
+
+       evutil_adjust_hints_for_addrconfig(&hints);
+
+       err = evutil_getaddrinfo_common(nodename, servname, &hints, res, &port);
+       if (err != EVUTIL_EAI_NEED_RESOLVE) {
+               /* We either succeeded or failed.  No need to continue */
+               return err;
+       }
+
+       err = 0;
+       /* Use any of the various gethostbyname_r variants as available. */
+       {
+#ifdef _EVENT_HAVE_GETHOSTBYNAME_R_6_ARG
+               /* This one is what glibc provides. */
+               char buf[2048];
+               struct hostent hostent;
+               int r;
+               r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
+                   &err);
+#elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_5_ARG)
+               char buf[2048];
+               struct hostent hostent;
+               ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
+                   &err);
+#elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_3_ARG)
+               struct hostent_data data;
+               struct hostent hostent;
+               memset(&data, 0, sizeof(data));
+               err = gethostbyname_r(nodename, &hostent, &data);
+               ent = err ? NULL : &hostent;
+#else
+               /* fall back to gethostbyname. */
+               /* XXXX This needs a lock everywhere but Windows. */
+               ent = gethostbyname(nodename);
+#ifdef WIN32
+               err = WSAGetLastError();
+#else
+               err = h_errno;
+#endif
+#endif
+
+               /* Now we have either ent or err set. */
+               if (!ent) {
+                       /* XXX is this right for windows ? */
+                       switch (err) {
+                       case TRY_AGAIN:
+                               return EVUTIL_EAI_AGAIN;
+                       case NO_RECOVERY:
+                       default:
+                               return EVUTIL_EAI_FAIL;
+                       case HOST_NOT_FOUND:
+                               return EVUTIL_EAI_NONAME;
+                       case NO_ADDRESS:
+#if NO_DATA != NO_ADDRESS
+                       case NO_DATA:
+#endif
+                               return EVUTIL_EAI_NODATA;
+                       }
+               }
+
+               if (ent->h_addrtype != hints.ai_family &&
+                   hints.ai_family != PF_UNSPEC) {
+                       /* This wasn't the type we were hoping for.  Too bad
+                        * we never had a chance to ask gethostbyname for what
+                        * we wanted. */
+                       return EVUTIL_EAI_NONAME;
+               }
+
+               /* Make sure we got _some_ answers. */
+               if (ent->h_length == 0)
+                       return EVUTIL_EAI_NODATA;
+
+               /* If we got an address type we don't know how to make a
+                  sockaddr for, give up. */
+               if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
+                       return EVUTIL_EAI_FAMILY;
+
+               *res = addrinfo_from_hostent(ent, port, &hints);
+               if (! *res)
+                       return EVUTIL_EAI_MEMORY;
+       }
+
+       return 0;
+#endif
+}
+
+void
+evutil_freeaddrinfo(struct evutil_addrinfo *ai)
+{
+#ifdef _EVENT_HAVE_GETADDRINFO
+       if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
+               freeaddrinfo(ai);
+               return;
+       }
+#endif
+       while (ai) {
+               struct evutil_addrinfo *next = ai->ai_next;
+               if (ai->ai_canonname)
+                       mm_free(ai->ai_canonname);
+               mm_free(ai);
+               ai = next;
+       }
+}
+
+static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
+
+void
+evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn)
+{
+       if (!evdns_getaddrinfo_impl)
+               evdns_getaddrinfo_impl = fn;
+}
+
+/* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
+ * otherwise do a blocking resolve and pass the result to the callback in the
+ * way that evdns_getaddrinfo would.
+ */
+int
+evutil_getaddrinfo_async(struct evdns_base *dns_base,
+    const char *nodename, const char *servname,
+    const struct evutil_addrinfo *hints_in,
+    void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
+{
+       if (dns_base && evdns_getaddrinfo_impl) {
+               evdns_getaddrinfo_impl(
+                       dns_base, nodename, servname, hints_in, cb, arg);
+       } else {
+               struct evutil_addrinfo *ai=NULL;
+               int err;
+               err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
+               cb(err, ai, arg);
+       }
+       return 0;
+}
+
+const char *
+evutil_gai_strerror(int err)
+{
+       /* As a sneaky side-benefit, this case statement will get most
+        * compilers to tell us if any of the error codes we defined
+        * conflict with the platform's native error codes. */
+       switch (err) {
+       case EVUTIL_EAI_CANCEL:
+               return "Request canceled";
+       case 0:
+               return "No error";
+
+       case EVUTIL_EAI_ADDRFAMILY:
+               return "address family for nodename not supported";
+       case EVUTIL_EAI_AGAIN:
+               return "temporary failure in name resolution";
+       case EVUTIL_EAI_BADFLAGS:
+               return "invalid value for ai_flags";
+       case EVUTIL_EAI_FAIL:
+               return "non-recoverable failure in name resolution";
+       case EVUTIL_EAI_FAMILY:
+               return "ai_family not supported";
+       case EVUTIL_EAI_MEMORY:
+               return "memory allocation failure";
+       case EVUTIL_EAI_NODATA:
+               return "no address associated with nodename";
+       case EVUTIL_EAI_NONAME:
+               return "nodename nor servname provided, or not known";
+       case EVUTIL_EAI_SERVICE:
+               return "servname not supported for ai_socktype";
+       case EVUTIL_EAI_SOCKTYPE:
+               return "ai_socktype not supported";
+       case EVUTIL_EAI_SYSTEM:
+               return "system error";
+       default:
+#if defined(USE_NATIVE_GETADDRINFO) && defined(WIN32)
+               return gai_strerrorA(err);
+#elif defined(USE_NATIVE_GETADDRINFO)
+               return gai_strerror(err);
+#else
+               return "Unknown error code";
+#endif
+       }
+}
+
+#ifdef WIN32
+#define E(code, s) { code, (s " [" #code " ]") }
+static struct { int code; const char *msg; } windows_socket_errors[] = {
+  E(WSAEINTR, "Interrupted function call"),
+  E(WSAEACCES, "Permission denied"),
+  E(WSAEFAULT, "Bad address"),
+  E(WSAEINVAL, "Invalid argument"),
+  E(WSAEMFILE, "Too many open files"),
+  E(WSAEWOULDBLOCK,  "Resource temporarily unavailable"),
+  E(WSAEINPROGRESS, "Operation now in progress"),
+  E(WSAEALREADY, "Operation already in progress"),
+  E(WSAENOTSOCK, "Socket operation on nonsocket"),
+  E(WSAEDESTADDRREQ, "Destination address required"),
+  E(WSAEMSGSIZE, "Message too long"),
+  E(WSAEPROTOTYPE, "Protocol wrong for socket"),
+  E(WSAENOPROTOOPT, "Bad protocol option"),
+  E(WSAEPROTONOSUPPORT, "Protocol not supported"),
+  E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
+  /* What's the difference between NOTSUPP and NOSUPPORT? :) */
+  E(WSAEOPNOTSUPP, "Operation not supported"),
+  E(WSAEPFNOSUPPORT,  "Protocol family not supported"),
+  E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
+  E(WSAEADDRINUSE, "Address already in use"),
+  E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
+  E(WSAENETDOWN, "Network is down"),
+  E(WSAENETUNREACH, "Network is unreachable"),
+  E(WSAENETRESET, "Network dropped connection on reset"),
+  E(WSAECONNABORTED, "Software caused connection abort"),
+  E(WSAECONNRESET, "Connection reset by peer"),
+  E(WSAENOBUFS, "No buffer space available"),
+  E(WSAEISCONN, "Socket is already connected"),
+  E(WSAENOTCONN, "Socket is not connected"),
+  E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
+  E(WSAETIMEDOUT, "Connection timed out"),
+  E(WSAECONNREFUSED, "Connection refused"),
+  E(WSAEHOSTDOWN, "Host is down"),
+  E(WSAEHOSTUNREACH, "No route to host"),
+  E(WSAEPROCLIM, "Too many processes"),
+
+  /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
+  E(WSASYSNOTREADY, "Network subsystem is unavailable"),
+  E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
+  E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
+  E(WSAEDISCON, "Graceful shutdown now in progress"),
+#ifdef WSATYPE_NOT_FOUND
+  E(WSATYPE_NOT_FOUND, "Class type not found"),
+#endif
+  E(WSAHOST_NOT_FOUND, "Host not found"),
+  E(WSATRY_AGAIN, "Nonauthoritative host not found"),
+  E(WSANO_RECOVERY, "This is a nonrecoverable error"),
+  E(WSANO_DATA, "Valid name, no data record of requested type)"),
+
+  /* There are some more error codes whose numeric values are marked
+   * <b>OS dependent</b>. They start with WSA_, apparently for the same
+   * reason that practitioners of some craft traditions deliberately
+   * introduce imperfections into their baskets and rugs "to allow the
+   * evil spirits to escape."  If we catch them, then our binaries
+   * might not report consistent results across versions of Windows.
+   * Thus, I'm going to let them all fall through.
+   */
+  { -1, NULL },
+};
+#undef E
+/** Equivalent to strerror, but for windows socket errors. */
+const char *
+evutil_socket_error_to_string(int errcode)
+{
+  /* XXXX Is there really no built-in function to do this? */
+  int i;
+  for (i=0; windows_socket_errors[i].code >= 0; ++i) {
+    if (errcode == windows_socket_errors[i].code)
+      return windows_socket_errors[i].msg;
+  }
+  return strerror(errcode);
+}
+#endif
+
+int
+evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
+{
+       int r;
+       va_list ap;
+       va_start(ap, format);
+       r = evutil_vsnprintf(buf, buflen, format, ap);
+       va_end(ap);
+       return r;
+}
+
+int
+evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
+{
+       int r;
+       if (!buflen)
+               return 0;
+#ifdef _MSC_VER
+       r = _vsnprintf(buf, buflen, format, ap);
+       if (r < 0)
+               r = _vscprintf(format, ap);
+#elif defined(sgi)
+       /* Make sure we always use the correct vsnprintf on IRIX */
+       extern int      _xpg5_vsnprintf(char * __restrict,
+               __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
+               const char * __restrict, /* va_list */ char *);
+
+       r = _xpg5_vsnprintf(buf, buflen, format, ap);
+#else
+       r = vsnprintf(buf, buflen, format, ap);
+#endif
+       buf[buflen-1] = '\0';
+       return r;
+}
+
+#define USE_INTERNAL_NTOP
+#define USE_INTERNAL_PTON
+
+const char *
+evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
+{
+#if defined(_EVENT_HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
+       return inet_ntop(af, src, dst, len);
+#else
+       if (af == AF_INET) {
+               const struct in_addr *in = src;
+               const ev_uint32_t a = ntohl(in->s_addr);
+               int r;
+               r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
+                   (int)(ev_uint8_t)((a>>24)&0xff),
+                   (int)(ev_uint8_t)((a>>16)&0xff),
+                   (int)(ev_uint8_t)((a>>8 )&0xff),
+                   (int)(ev_uint8_t)((a    )&0xff));
+               if (r<0||(size_t)r>=len)
+                       return NULL;
+               else
+                       return dst;
+#ifdef AF_INET6
+       } else if (af == AF_INET6) {
+               const struct in6_addr *addr = src;
+               char buf[64], *cp;
+               int longestGapLen = 0, longestGapPos = -1, i,
+                       curGapPos = -1, curGapLen = 0;
+               ev_uint16_t words[8];
+               for (i = 0; i < 8; ++i) {
+                       words[i] =
+                           (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
+               }
+               if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
+                   words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
+                       (words[5] == 0xffff))) {
+                       /* This is an IPv4 address. */
+                       if (words[5] == 0) {
+                               evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
+                                   addr->s6_addr[12], addr->s6_addr[13],
+                                   addr->s6_addr[14], addr->s6_addr[15]);
+                       } else {
+                               evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
+                                   addr->s6_addr[12], addr->s6_addr[13],
+                                   addr->s6_addr[14], addr->s6_addr[15]);
+                       }
+                       if (strlen(buf) > len)
+                               return NULL;
+                       strlcpy(dst, buf, len);
+                       return dst;
+               }
+               i = 0;
+               while (i < 8) {
+                       if (words[i] == 0) {
+                               curGapPos = i++;
+                               curGapLen = 1;
+                               while (i<8 && words[i] == 0) {
+                                       ++i; ++curGapLen;
+                               }
+                               if (curGapLen > longestGapLen) {
+                                       longestGapPos = curGapPos;
+                                       longestGapLen = curGapLen;
+                               }
+                       } else {
+                               ++i;
+                       }
+               }
+               if (longestGapLen<=1)
+                       longestGapPos = -1;
+
+               cp = buf;
+               for (i = 0; i < 8; ++i) {
+                       if (words[i] == 0 && longestGapPos == i) {
+                               if (i == 0)
+                                       *cp++ = ':';
+                               *cp++ = ':';
+                               while (i < 8 && words[i] == 0)
+                                       ++i;
+                               --i; /* to compensate for loop increment. */
+                       } else {
+                               evutil_snprintf(cp,
+                                                               sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
+                               cp += strlen(cp);
+                               if (i != 7)
+                                       *cp++ = ':';
+                       }
+               }
+               *cp = '\0';
+               if (strlen(buf) > len)
+                       return NULL;
+               strlcpy(dst, buf, len);
+               return dst;
+#endif
+       } else {
+               return NULL;
+       }
+#endif
+}
+
+int
+evutil_inet_pton(int af, const char *src, void *dst)
+{
+#if defined(_EVENT_HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
+       return inet_pton(af, src, dst);
+#else
+       if (af == AF_INET) {
+               int a,b,c,d;
+               char more;
+               struct in_addr *addr = dst;
+               if (sscanf(src, "%d.%d.%d.%d%c", &a,&b,&c,&d,&more) != 4)
+                       return 0;
+               if (a < 0 || a > 255) return 0;
+               if (b < 0 || b > 255) return 0;
+               if (c < 0 || c > 255) return 0;
+               if (d < 0 || d > 255) return 0;
+               addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
+               return 1;
+#ifdef AF_INET6
+       } else if (af == AF_INET6) {
+               struct in6_addr *out = dst;
+               ev_uint16_t words[8];
+               int gapPos = -1, i, setWords=0;
+               const char *dot = strchr(src, '.');
+               const char *eow; /* end of words. */
+               if (dot == src)
+                       return 0;
+               else if (!dot)
+                       eow = src+strlen(src);
+               else {
+                       int byte1,byte2,byte3,byte4;
+                       char more;
+                       for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT(*eow); --eow)
+                               ;
+                       ++eow;
+
+                       /* We use "scanf" because some platform inet_aton()s are too lax
+                        * about IPv4 addresses of the form "1.2.3" */
+                       if (sscanf(eow, "%d.%d.%d.%d%c",
+                                          &byte1,&byte2,&byte3,&byte4,&more) != 4)
+                               return 0;
+
+                       if (byte1 > 255 || byte1 < 0 ||
+                               byte2 > 255 || byte2 < 0 ||
+                               byte3 > 255 || byte3 < 0 ||
+                               byte4 > 255 || byte4 < 0)
+                               return 0;
+
+                       words[6] = (byte1<<8) | byte2;
+                       words[7] = (byte3<<8) | byte4;
+                       setWords += 2;
+               }
+
+               i = 0;
+               while (src < eow) {
+                       if (i > 7)
+                               return 0;
+                       if (EVUTIL_ISXDIGIT(*src)) {
+                               char *next;
+                               long r = strtol(src, &next, 16);
+                               if (next > 4+src)
+                                       return 0;
+                               if (next == src)
+                                       return 0;
+                               if (r<0 || r>65536)
+                                       return 0;
+
+                               words[i++] = (ev_uint16_t)r;
+                               setWords++;
+                               src = next;
+                               if (*src != ':' && src != eow)
+                                       return 0;
+                               ++src;
+                       } else if (*src == ':' && i > 0 && gapPos==-1) {
+                               gapPos = i;
+                               ++src;
+                       } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
+                               gapPos = i;
+                               src += 2;
+                       } else {
+                               return 0;
+                       }
+               }
+
+               if (setWords > 8 ||
+                       (setWords == 8 && gapPos != -1) ||
+                       (setWords < 8 && gapPos == -1))
+                       return 0;
+
+               if (gapPos >= 0) {
+                       int nToMove = setWords - (dot ? 2 : 0) - gapPos;
+                       int gapLen = 8 - setWords;
+                       /* assert(nToMove >= 0); */
+                       if (nToMove < 0)
+                               return -1; /* should be impossible */
+                       memmove(&words[gapPos+gapLen], &words[gapPos],
+                                       sizeof(ev_uint16_t)*nToMove);
+                       memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
+               }
+               for (i = 0; i < 8; ++i) {
+                       out->s6_addr[2*i  ] = words[i] >> 8;
+                       out->s6_addr[2*i+1] = words[i] & 0xff;
+               }
+
+               return 1;
+#endif
+       } else {
+               return -1;
+       }
+#endif
+}
+
+int
+evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
+{
+       int port;
+       char buf[128];
+       const char *cp, *addr_part, *port_part;
+       int is_ipv6;
+       /* recognized formats are:
+        * [ipv6]:port
+        * ipv6
+        * [ipv6]
+        * ipv4:port
+        * ipv4
+        */
+
+       cp = strchr(ip_as_string, ':');
+       if (*ip_as_string == '[') {
+               int len;
+               if (!(cp = strchr(ip_as_string, ']'))) {
+                       return -1;
+               }
+               len = (int) ( cp-(ip_as_string + 1) );
+               if (len > (int)sizeof(buf)-1) {
+                       return -1;
+               }
+               memcpy(buf, ip_as_string+1, len);
+               buf[len] = '\0';
+               addr_part = buf;
+               if (cp[1] == ':')
+                       port_part = cp+2;
+               else
+                       port_part = NULL;
+               is_ipv6 = 1;
+       } else if (cp && strchr(cp+1, ':')) {
+               is_ipv6 = 1;
+               addr_part = ip_as_string;
+               port_part = NULL;
+       } else if (cp) {
+               is_ipv6 = 0;
+               if (cp - ip_as_string > (int)sizeof(buf)-1) {
+                       return -1;
+               }
+               memcpy(buf, ip_as_string, cp-ip_as_string);
+               buf[cp-ip_as_string] = '\0';
+               addr_part = buf;
+               port_part = cp+1;
+       } else {
+               addr_part = ip_as_string;
+               port_part = NULL;
+               is_ipv6 = 0;
+       }
+
+       if (port_part == NULL) {
+               port = 0;
+       } else {
+               port = atoi(port_part);
+               if (port <= 0 || port > 65535) {
+                       return -1;
+               }
+       }
+
+       if (!addr_part)
+               return -1; /* Should be impossible. */
+#ifdef AF_INET6
+       if (is_ipv6)
+       {
+               struct sockaddr_in6 sin6;
+               memset(&sin6, 0, sizeof(sin6));
+#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+               sin6.sin6_len = sizeof(sin6);
+#endif
+               sin6.sin6_family = AF_INET6;
+               sin6.sin6_port = htons(port);
+               if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr))
+                       return -1;
+               if ((int)sizeof(sin6) > *outlen)
+                       return -1;
+               memset(out, 0, *outlen);
+               memcpy(out, &sin6, sizeof(sin6));
+               *outlen = sizeof(sin6);
+               return 0;
+       }
+       else
+#endif
+       {
+               struct sockaddr_in sin;
+               memset(&sin, 0, sizeof(sin));
+#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+               sin.sin_len = sizeof(sin);
+#endif
+               sin.sin_family = AF_INET;
+               sin.sin_port = htons(port);
+               if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
+                       return -1;
+               if ((int)sizeof(sin) > *outlen)
+                       return -1;
+               memset(out, 0, *outlen);
+               memcpy(out, &sin, sizeof(sin));
+               *outlen = sizeof(sin);
+               return 0;
+       }
+}
+
+const char *
+evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen)
+{
+       char b[128];
+       const char *res=NULL;
+       int port;
+       if (sa->sa_family == AF_INET) {
+               const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
+               res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
+               port = ntohs(sin->sin_port);
+               if (res) {
+                       evutil_snprintf(out, outlen, "%s:%d", b, port);
+                       return out;
+               }
+       } else if (sa->sa_family == AF_INET6) {
+               const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
+               res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
+               port = ntohs(sin6->sin6_port);
+               if (res) {
+                       evutil_snprintf(out, outlen, "[%s]:%d", b, port);
+                       return out;
+               }
+       }
+
+       evutil_snprintf(out, outlen, "<addr with socktype %d>",
+           (int)sa->sa_family);
+       return out;
+}
+
+int
+evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
+    int include_port)
+{
+       int r;
+       if (0 != (r = (sa1->sa_family - sa2->sa_family)))
+               return r;
+
+       if (sa1->sa_family == AF_INET) {
+               const struct sockaddr_in *sin1, *sin2;
+               sin1 = (const struct sockaddr_in *)sa1;
+               sin2 = (const struct sockaddr_in *)sa2;
+               if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
+                       return -1;
+               else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
+                       return 1;
+               else if (include_port &&
+                   (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
+                       return r;
+               else
+                       return 0;
+       }
+#ifdef AF_INET6
+       else if (sa1->sa_family == AF_INET6) {
+               const struct sockaddr_in6 *sin1, *sin2;
+               sin1 = (const struct sockaddr_in6 *)sa1;
+               sin2 = (const struct sockaddr_in6 *)sa2;
+               if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
+                       return r;
+               else if (include_port &&
+                   (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
+                       return r;
+               else
+                       return 0;
+       }
+#endif
+       return 1;
+}
+
+/* Tables to implement ctypes-replacement EVUTIL_IS*() functions.  Each table
+ * has 256 bits to look up whether a character is in some set or not.  This
+ * fails on non-ASCII platforms, but so does every other place where we
+ * take a char and write it onto the network.
+ **/
+static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
+  { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
+  { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
+  { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
+  { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
+static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
+/* Upper-casing and lowercasing tables to map characters to upper/lowercase
+ * equivalents. */
+static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
+  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,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,52,53,54,55,56,57,58,59,60,61,62,63,
+  64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
+  80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
+  96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
+  80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
+  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
+  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
+  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
+  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
+  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
+  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
+  224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
+  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
+};
+static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
+  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,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,52,53,54,55,56,57,58,59,60,61,62,63,
+  64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
+  112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
+  96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
+  112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
+  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
+  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
+  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
+  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
+  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
+  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
+  224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
+  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
+};
+
+#define IMPL_CTYPE_FN(name)                                            \
+       int EVUTIL_##name(char c) {                                     \
+               ev_uint8_t u = c;                                       \
+               return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
+       }
+IMPL_CTYPE_FN(ISALPHA)
+IMPL_CTYPE_FN(ISALNUM)
+IMPL_CTYPE_FN(ISSPACE)
+IMPL_CTYPE_FN(ISDIGIT)
+IMPL_CTYPE_FN(ISXDIGIT)
+IMPL_CTYPE_FN(ISPRINT)
+IMPL_CTYPE_FN(ISLOWER)
+IMPL_CTYPE_FN(ISUPPER)
+
+char EVUTIL_TOLOWER(char c)
+{
+       return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
+}
+char EVUTIL_TOUPPER(char c)
+{
+       return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
+}
+int
+evutil_ascii_strcasecmp(const char *s1, const char *s2)
+{
+       char c1, c2;
+       while (1) {
+               c1 = EVUTIL_TOLOWER(*s1++);
+               c2 = EVUTIL_TOLOWER(*s2++);
+               if (c1 < c2)
+                       return -1;
+               else if (c1 > c2)
+                       return 1;
+               else if (c1 == 0)
+                       return 0;
+       }
+}
+int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
+{
+       char c1, c2;
+       while (n--) {
+               c1 = EVUTIL_TOLOWER(*s1++);
+               c2 = EVUTIL_TOLOWER(*s2++);
+               if (c1 < c2)
+                       return -1;
+               else if (c1 > c2)
+                       return 1;
+               else if (c1 == 0)
+                       return 0;
+       }
+       return 0;
+}
+
+static int
+evutil_issetugid(void)
+{
+#ifdef _EVENT_HAVE_ISSETUGID
+       return issetugid();
+#else
+
+#ifdef _EVENT_HAVE_GETEUID
+       if (getuid() != geteuid())
+               return 1;
+#endif
+#ifdef _EVENT_HAVE_GETEGID
+       if (getgid() != getegid())
+               return 1;
+#endif
+       return 0;
+#endif
+}
+
+const char *
+evutil_getenv(const char *varname)
+{
+       if (evutil_issetugid())
+               return NULL;
+
+       return getenv(varname);
+}
+
+long
+_evutil_weakrand(void)
+{
+#ifdef WIN32
+       return rand();
+#else
+       return random();
+#endif
+}
+
+int
+evutil_sockaddr_is_loopback(const struct sockaddr *addr)
+{
+       static const char LOOPBACK_S6[16] =
+           "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
+       if (addr->sa_family == AF_INET) {
+               struct sockaddr_in *sin = (struct sockaddr_in *)addr;
+               return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
+       } else if (addr->sa_family == AF_INET6) {
+               struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
+               return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
+       }
+       return 0;
+}
+
+#define MAX_SECONDS_IN_MSEC_LONG \
+       (((LONG_MAX) - 999) / 1000)
+
+long
+evutil_tv_to_msec(const struct timeval *tv)
+{
+       if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
+               return -1;
+
+       return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
+}
+
+int
+evutil_hex_char_to_int(char c)
+{
+       switch(c)
+       {
+               case '0': return 0;
+               case '1': return 1;
+               case '2': return 2;
+               case '3': return 3;
+               case '4': return 4;
+               case '5': return 5;
+               case '6': return 6;
+               case '7': return 7;
+               case '8': return 8;
+               case '9': return 9;
+               case 'A': case 'a': return 10;
+               case 'B': case 'b': return 11;
+               case 'C': case 'c': return 12;
+               case 'D': case 'd': return 13;
+               case 'E': case 'e': return 14;
+               case 'F': case 'f': return 15;
+       }
+       return -1;
+}
+
+#ifdef WIN32
+HANDLE
+evutil_load_windows_system_library(const TCHAR *library_name)
+{
+  TCHAR path[MAX_PATH];
+  unsigned n;
+  n = GetSystemDirectory(path, MAX_PATH);
+  if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
+    return 0;
+  _tcscat(path, TEXT("\\"));
+  _tcscat(path, library_name);
+  return LoadLibrary(path);
+}
+#endif
+
diff --git a/libevent/evutil.h b/libevent/evutil.h
new file mode 100644 (file)
index 0000000..02bca89
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVUTIL_H_
+#define _EVUTIL_H_
+
+/** @file evutil.h
+
+  Utility and compatibility functions for Libevent.
+
+  The <evutil.h> header is deprecated in Libevent 2.0 and later; please
+  use <event2/util.h> instead.
+*/
+
+#include <event2/util.h>
+
+#endif /* _EVUTIL_H_ */
diff --git a/libevent/evutil_rand.c b/libevent/evutil_rand.c
new file mode 100644 (file)
index 0000000..3cc163d
--- /dev/null
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* This file has our secure PRNG code.  On platforms that have arc4random(),
+ * we just use that.  Otherwise, we include arc4random.c as a bunch of static
+ * functions, and wrap it lightly.  We don't expose the arc4random*() APIs
+ * because A) they aren't in our namespace, and B) it's not nice to name your
+ * APIs after their implementations.  We keep them in a separate file
+ * so that other people can rip it out and use it for whatever.
+ */
+
+#include "event2/event-config.h"
+
+#include <limits.h>
+
+#include "util-internal.h"
+#include "evthread-internal.h"
+
+#ifdef _EVENT_HAVE_ARC4RANDOM
+#include <stdlib.h>
+#include <string.h>
+int
+evutil_secure_rng_init(void)
+{
+       /* call arc4random() now to force it to self-initialize */
+       (void) arc4random();
+       return 0;
+}
+int
+evutil_secure_rng_global_setup_locks_(const int enable_locks)
+{
+       return 0;
+}
+
+static void
+ev_arc4random_buf(void *buf, size_t n)
+{
+#ifdef _EVENT_HAVE_ARC4RANDOM_BUF
+       return arc4random_buf(buf, n);
+#else
+       unsigned char *b = buf;
+       /* Make sure that we start out with b at a 4-byte alignment; plenty
+        * of CPUs care about this for 32-bit access. */
+       if (n >= 4 && ((ev_uintptr_t)b) & 3) {
+               ev_uint32_t u = arc4random();
+               int n_bytes = 4 - (((ev_uintptr_t)b) & 3);
+               memcpy(b, &u, n_bytes);
+               b += n_bytes;
+               n -= n_bytes;
+       }
+       while (n >= 4) {
+               *(ev_uint32_t*)b = arc4random();
+               b += 4;
+               n -= 4;
+       }
+       if (n) {
+               ev_uint32_t u = arc4random();
+               memcpy(b, &u, n);
+       }
+#endif
+}
+
+#else /* !_EVENT_HAVE_ARC4RANDOM { */
+
+#ifdef _EVENT_ssize_t
+#define ssize_t _EVENT_SSIZE_t
+#endif
+#define ARC4RANDOM_EXPORT static
+#define _ARC4_LOCK() EVLOCK_LOCK(arc4rand_lock, 0)
+#define _ARC4_UNLOCK() EVLOCK_UNLOCK(arc4rand_lock, 0)
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+static void *arc4rand_lock;
+#endif
+
+#define ARC4RANDOM_UINT32 ev_uint32_t
+#define ARC4RANDOM_NOSTIR
+#define ARC4RANDOM_NORANDOM
+#define ARC4RANDOM_NOUNIFORM
+
+#include "./arc4random.c"
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+int
+evutil_secure_rng_global_setup_locks_(const int enable_locks)
+{
+       EVTHREAD_SETUP_GLOBAL_LOCK(arc4rand_lock, 0);
+       return 0;
+}
+#endif
+
+int
+evutil_secure_rng_init(void)
+{
+       int val;
+
+       _ARC4_LOCK();
+       if (!arc4_seeded_ok)
+               arc4_stir();
+       val = arc4_seeded_ok ? 0 : -1;
+       _ARC4_UNLOCK();
+       return val;
+}
+
+static void
+ev_arc4random_buf(void *buf, size_t n)
+{
+       arc4random_buf(buf, n);
+}
+
+#endif /* } !_EVENT_HAVE_ARC4RANDOM */
+
+void
+evutil_secure_rng_get_bytes(void *buf, size_t n)
+{
+       ev_arc4random_buf(buf, n);
+}
+
+void
+evutil_secure_rng_add_bytes(const char *buf, size_t n)
+{
+       arc4random_addrandom((unsigned char*)buf,
+           n>(size_t)INT_MAX ? INT_MAX : (int)n);
+}
+
diff --git a/libevent/ht-internal.h b/libevent/ht-internal.h
new file mode 100644 (file)
index 0000000..4673825
--- /dev/null
@@ -0,0 +1,484 @@
+/* Based on work Copyright 2002 Christopher Clark */
+/* Copyright 2005-2012 Nick Mathewson */
+/* Copyright 2009-2012 Niels Provos and Nick Mathewson */
+/* See license at end. */
+
+/* Based on ideas by Christopher Clark and interfaces from Niels Provos. */
+
+#ifndef _EVENT_HT_H
+#define _EVENT_HT_H
+
+#define HT_HEAD(name, type)                                             \
+  struct name {                                                         \
+    /* The hash table itself. */                                        \
+    struct type **hth_table;                                            \
+    /* How long is the hash table? */                                   \
+    unsigned hth_table_length;                                          \
+    /* How many elements does the table contain? */                     \
+    unsigned hth_n_entries;                                             \
+    /* How many elements will we allow in the table before resizing it? */ \
+    unsigned hth_load_limit;                                            \
+    /* Position of hth_table_length in the primes table. */             \
+    int hth_prime_idx;                                                  \
+  }
+
+#define HT_INITIALIZER()                        \
+  { NULL, 0, 0, 0, -1 }
+
+#ifdef HT_CACHE_HASH_VALUES
+#define HT_ENTRY(type)                          \
+  struct {                                      \
+    struct type *hte_next;                      \
+    unsigned hte_hash;                          \
+  }
+#else
+#define HT_ENTRY(type)                          \
+  struct {                                      \
+    struct type *hte_next;                      \
+  }
+#endif
+
+#define HT_EMPTY(head)                          \
+  ((head)->hth_n_entries == 0)
+
+/* How many elements in 'head'? */
+#define HT_SIZE(head)                           \
+  ((head)->hth_n_entries)
+
+#define HT_FIND(name, head, elm)     name##_HT_FIND((head), (elm))
+#define HT_INSERT(name, head, elm)   name##_HT_INSERT((head), (elm))
+#define HT_REPLACE(name, head, elm)  name##_HT_REPLACE((head), (elm))
+#define HT_REMOVE(name, head, elm)   name##_HT_REMOVE((head), (elm))
+#define HT_START(name, head)         name##_HT_START(head)
+#define HT_NEXT(name, head, elm)     name##_HT_NEXT((head), (elm))
+#define HT_NEXT_RMV(name, head, elm) name##_HT_NEXT_RMV((head), (elm))
+#define HT_CLEAR(name, head)         name##_HT_CLEAR(head)
+#define HT_INIT(name, head)          name##_HT_INIT(head)
+/* Helper: */
+static inline unsigned
+ht_improve_hash(unsigned h)
+{
+  /* Aim to protect against poor hash functions by adding logic here
+   * - logic taken from java 1.4 hashtable source */
+  h += ~(h << 9);
+  h ^=  ((h >> 14) | (h << 18)); /* >>> */
+  h +=  (h << 4);
+  h ^=  ((h >> 10) | (h << 22)); /* >>> */
+  return h;
+}
+
+#if 0
+/** Basic string hash function, from Java standard String.hashCode(). */
+static inline unsigned
+ht_string_hash(const char *s)
+{
+  unsigned h = 0;
+  int m = 1;
+  while (*s) {
+    h += ((signed char)*s++)*m;
+    m = (m<<5)-1; /* m *= 31 */
+  }
+  return h;
+}
+#endif
+
+/** Basic string hash function, from Python's str.__hash__() */
+static inline unsigned
+ht_string_hash(const char *s)
+{
+  unsigned h;
+  const unsigned char *cp = (const unsigned char *)s;
+  h = *cp << 7;
+  while (*cp) {
+    h = (1000003*h) ^ *cp++;
+  }
+  /* This conversion truncates the length of the string, but that's ok. */
+  h ^= (unsigned)(cp-(const unsigned char*)s);
+  return h;
+}
+
+#ifdef HT_CACHE_HASH_VALUES
+#define _HT_SET_HASH(elm, field, hashfn)        \
+       do { (elm)->field.hte_hash = hashfn(elm); } while (0)
+#define _HT_SET_HASHVAL(elm, field, val)       \
+       do { (elm)->field.hte_hash = (val); } while (0)
+#define _HT_ELT_HASH(elm, field, hashfn)       \
+       ((elm)->field.hte_hash)
+#else
+#define _HT_SET_HASH(elm, field, hashfn)       \
+       ((void)0)
+#define _HT_ELT_HASH(elm, field, hashfn)       \
+       (hashfn(elm))
+#define _HT_SET_HASHVAL(elm, field, val)       \
+        ((void)0)
+#endif
+
+/* Helper: alias for the bucket containing 'elm'. */
+#define _HT_BUCKET(head, field, elm, hashfn)                           \
+       ((head)->hth_table[_HT_ELT_HASH(elm,field,hashfn) % head->hth_table_length])
+
+#define HT_FOREACH(x, name, head)                 \
+  for ((x) = HT_START(name, head);                \
+       (x) != NULL;                               \
+       (x) = HT_NEXT(name, head, x))
+
+#define HT_PROTOTYPE(name, type, field, hashfn, eqfn)                   \
+  int name##_HT_GROW(struct name *ht, unsigned min_capacity);           \
+  void name##_HT_CLEAR(struct name *ht);                                \
+  int _##name##_HT_REP_IS_BAD(const struct name *ht);                   \
+  static inline void                                                    \
+  name##_HT_INIT(struct name *head) {                                   \
+    head->hth_table_length = 0;                                         \
+    head->hth_table = NULL;                                             \
+    head->hth_n_entries = 0;                                            \
+    head->hth_load_limit = 0;                                           \
+    head->hth_prime_idx = -1;                                           \
+  }                                                                     \
+  /* Helper: returns a pointer to the right location in the table       \
+   * 'head' to find or insert the element 'elm'. */                     \
+  static inline struct type **                                          \
+  _##name##_HT_FIND_P(struct name *head, struct type *elm)              \
+  {                                                                     \
+    struct type **p;                                                    \
+    if (!head->hth_table)                                               \
+      return NULL;                                                      \
+    p = &_HT_BUCKET(head, field, elm, hashfn);                         \
+    while (*p) {                                                        \
+      if (eqfn(*p, elm))                                                \
+        return p;                                                       \
+      p = &(*p)->field.hte_next;                                        \
+    }                                                                   \
+    return p;                                                           \
+  }                                                                     \
+  /* Return a pointer to the element in the table 'head' matching 'elm', \
+   * or NULL if no such element exists */                               \
+  static inline struct type *                                           \
+  name##_HT_FIND(const struct name *head, struct type *elm)             \
+  {                                                                     \
+    struct type **p;                                                    \
+    struct name *h = (struct name *) head;                              \
+    _HT_SET_HASH(elm, field, hashfn);                                   \
+    p = _##name##_HT_FIND_P(h, elm);                                    \
+    return p ? *p : NULL;                                               \
+  }                                                                     \
+  /* Insert the element 'elm' into the table 'head'.  Do not call this  \
+   * function if the table might already contain a matching element. */ \
+  static inline void                                                    \
+  name##_HT_INSERT(struct name *head, struct type *elm)                 \
+  {                                                                     \
+    struct type **p;                                                    \
+    if (!head->hth_table || head->hth_n_entries >= head->hth_load_limit) \
+      name##_HT_GROW(head, head->hth_n_entries+1);                      \
+    ++head->hth_n_entries;                                              \
+    _HT_SET_HASH(elm, field, hashfn);                                   \
+    p = &_HT_BUCKET(head, field, elm, hashfn);                         \
+    elm->field.hte_next = *p;                                           \
+    *p = elm;                                                           \
+  }                                                                     \
+  /* Insert the element 'elm' into the table 'head'. If there already   \
+   * a matching element in the table, replace that element and return   \
+   * it. */                                                             \
+  static inline struct type *                                           \
+  name##_HT_REPLACE(struct name *head, struct type *elm)                \
+  {                                                                     \
+    struct type **p, *r;                                                \
+    if (!head->hth_table || head->hth_n_entries >= head->hth_load_limit) \
+      name##_HT_GROW(head, head->hth_n_entries+1);                      \
+    _HT_SET_HASH(elm, field, hashfn);                                   \
+    p = _##name##_HT_FIND_P(head, elm);                                 \
+    r = *p;                                                             \
+    *p = elm;                                                           \
+    if (r && (r!=elm)) {                                                \
+      elm->field.hte_next = r->field.hte_next;                          \
+      r->field.hte_next = NULL;                                         \
+      return r;                                                         \
+    } else {                                                            \
+      ++head->hth_n_entries;                                            \
+      return NULL;                                                      \
+    }                                                                   \
+  }                                                                     \
+  /* Remove any element matching 'elm' from the table 'head'.  If such  \
+   * an element is found, return it; otherwise return NULL. */          \
+  static inline struct type *                                           \
+  name##_HT_REMOVE(struct name *head, struct type *elm)                 \
+  {                                                                     \
+    struct type **p, *r;                                                \
+    _HT_SET_HASH(elm, field, hashfn);                                   \
+    p = _##name##_HT_FIND_P(head,elm);                                  \
+    if (!p || !*p)                                                      \
+      return NULL;                                                      \
+    r = *p;                                                             \
+    *p = r->field.hte_next;                                             \
+    r->field.hte_next = NULL;                                           \
+    --head->hth_n_entries;                                              \
+    return r;                                                           \
+  }                                                                     \
+  /* Invoke the function 'fn' on every element of the table 'head',     \
+   * using 'data' as its second argument.  If the function returns      \
+   * nonzero, remove the most recently examined element before invoking \
+   * the function again. */                                             \
+  static inline void                                                    \
+  name##_HT_FOREACH_FN(struct name *head,                               \
+                       int (*fn)(struct type *, void *),                \
+                       void *data)                                      \
+  {                                                                     \
+    unsigned idx;                                                       \
+    struct type **p, **nextp, *next;                                    \
+    if (!head->hth_table)                                               \
+      return;                                                           \
+    for (idx=0; idx < head->hth_table_length; ++idx) {                  \
+      p = &head->hth_table[idx];                                        \
+      while (*p) {                                                      \
+        nextp = &(*p)->field.hte_next;                                  \
+        next = *nextp;                                                  \
+        if (fn(*p, data)) {                                             \
+          --head->hth_n_entries;                                        \
+          *p = next;                                                    \
+        } else {                                                        \
+          p = nextp;                                                    \
+        }                                                               \
+      }                                                                 \
+    }                                                                   \
+  }                                                                     \
+  /* Return a pointer to the first element in the table 'head', under   \
+   * an arbitrary order.  This order is stable under remove operations, \
+   * but not under others. If the table is empty, return NULL. */       \
+  static inline struct type **                                          \
+  name##_HT_START(struct name *head)                                    \
+  {                                                                     \
+    unsigned b = 0;                                                     \
+    while (b < head->hth_table_length) {                                \
+      if (head->hth_table[b])                                           \
+        return &head->hth_table[b];                                     \
+      ++b;                                                              \
+    }                                                                   \
+    return NULL;                                                        \
+  }                                                                     \
+  /* Return the next element in 'head' after 'elm', under the arbitrary \
+   * order used by HT_START.  If there are no more elements, return     \
+   * NULL.  If 'elm' is to be removed from the table, you must call     \
+   * this function for the next value before you remove it.             \
+   */                                                                   \
+  static inline struct type **                                          \
+  name##_HT_NEXT(struct name *head, struct type **elm)                  \
+  {                                                                     \
+    if ((*elm)->field.hte_next) {                                       \
+      return &(*elm)->field.hte_next;                                   \
+    } else {                                                            \
+      unsigned b = (_HT_ELT_HASH(*elm, field, hashfn) % head->hth_table_length)+1; \
+      while (b < head->hth_table_length) {                              \
+        if (head->hth_table[b])                                         \
+          return &head->hth_table[b];                                   \
+        ++b;                                                            \
+      }                                                                 \
+      return NULL;                                                      \
+    }                                                                   \
+  }                                                                     \
+  static inline struct type **                                          \
+  name##_HT_NEXT_RMV(struct name *head, struct type **elm)              \
+  {                                                                     \
+    unsigned h = _HT_ELT_HASH(*elm, field, hashfn);                    \
+    *elm = (*elm)->field.hte_next;                                      \
+    --head->hth_n_entries;                                              \
+    if (*elm) {                                                         \
+      return elm;                                                       \
+    } else {                                                            \
+      unsigned b = (h % head->hth_table_length)+1;                      \
+      while (b < head->hth_table_length) {                              \
+        if (head->hth_table[b])                                         \
+          return &head->hth_table[b];                                   \
+        ++b;                                                            \
+      }                                                                 \
+      return NULL;                                                      \
+    }                                                                   \
+  }
+
+#define HT_GENERATE(name, type, field, hashfn, eqfn, load, mallocfn,    \
+                    reallocfn, freefn)                                  \
+  static unsigned name##_PRIMES[] = {                                   \
+    53, 97, 193, 389,                                                   \
+    769, 1543, 3079, 6151,                                              \
+    12289, 24593, 49157, 98317,                                         \
+    196613, 393241, 786433, 1572869,                                    \
+    3145739, 6291469, 12582917, 25165843,                               \
+    50331653, 100663319, 201326611, 402653189,                          \
+    805306457, 1610612741                                               \
+  };                                                                    \
+  static unsigned name##_N_PRIMES =                                     \
+    (unsigned)(sizeof(name##_PRIMES)/sizeof(name##_PRIMES[0]));         \
+  /* Expand the internal table of 'head' until it is large enough to    \
+   * hold 'size' elements.  Return 0 on success, -1 on allocation       \
+   * failure. */                                                        \
+  int                                                                   \
+  name##_HT_GROW(struct name *head, unsigned size)                      \
+  {                                                                     \
+    unsigned new_len, new_load_limit;                                   \
+    int prime_idx;                                                      \
+    struct type **new_table;                                            \
+    if (head->hth_prime_idx == (int)name##_N_PRIMES - 1)                \
+      return 0;                                                         \
+    if (head->hth_load_limit > size)                                    \
+      return 0;                                                         \
+    prime_idx = head->hth_prime_idx;                                    \
+    do {                                                                \
+      new_len = name##_PRIMES[++prime_idx];                             \
+      new_load_limit = (unsigned)(load*new_len);                        \
+    } while (new_load_limit <= size &&                                  \
+             prime_idx < (int)name##_N_PRIMES);                         \
+    if ((new_table = mallocfn(new_len*sizeof(struct type*)))) {         \
+      unsigned b;                                                       \
+      memset(new_table, 0, new_len*sizeof(struct type*));               \
+      for (b = 0; b < head->hth_table_length; ++b) {                    \
+        struct type *elm, *next;                                        \
+        unsigned b2;                                                    \
+        elm = head->hth_table[b];                                       \
+        while (elm) {                                                   \
+          next = elm->field.hte_next;                                   \
+          b2 = _HT_ELT_HASH(elm, field, hashfn) % new_len;              \
+          elm->field.hte_next = new_table[b2];                          \
+          new_table[b2] = elm;                                          \
+          elm = next;                                                   \
+        }                                                               \
+      }                                                                 \
+      if (head->hth_table)                                              \
+        freefn(head->hth_table);                                        \
+      head->hth_table = new_table;                                      \
+    } else {                                                            \
+      unsigned b, b2;                                                   \
+      new_table = reallocfn(head->hth_table, new_len*sizeof(struct type*)); \
+      if (!new_table) return -1;                                        \
+      memset(new_table + head->hth_table_length, 0,                     \
+             (new_len - head->hth_table_length)*sizeof(struct type*));  \
+      for (b=0; b < head->hth_table_length; ++b) {                      \
+        struct type *e, **pE;                                           \
+        for (pE = &new_table[b], e = *pE; e != NULL; e = *pE) {         \
+          b2 = _HT_ELT_HASH(e, field, hashfn) % new_len;                \
+          if (b2 == b) {                                                \
+            pE = &e->field.hte_next;                                    \
+          } else {                                                      \
+            *pE = e->field.hte_next;                                    \
+            e->field.hte_next = new_table[b2];                          \
+            new_table[b2] = e;                                          \
+          }                                                             \
+        }                                                               \
+      }                                                                 \
+      head->hth_table = new_table;                                      \
+    }                                                                   \
+    head->hth_table_length = new_len;                                   \
+    head->hth_prime_idx = prime_idx;                                    \
+    head->hth_load_limit = new_load_limit;                              \
+    return 0;                                                           \
+  }                                                                     \
+  /* Free all storage held by 'head'.  Does not free 'head' itself, or  \
+   * individual elements. */                                            \
+  void                                                                  \
+  name##_HT_CLEAR(struct name *head)                                    \
+  {                                                                     \
+    if (head->hth_table)                                                \
+      freefn(head->hth_table);                                          \
+    head->hth_table_length = 0;                                         \
+    name##_HT_INIT(head);                                               \
+  }                                                                     \
+  /* Debugging helper: return false iff the representation of 'head' is \
+   * internally consistent. */                                          \
+  int                                                                   \
+  _##name##_HT_REP_IS_BAD(const struct name *head)                      \
+  {                                                                     \
+    unsigned n, i;                                                      \
+    struct type *elm;                                                   \
+    if (!head->hth_table_length) {                                      \
+      if (!head->hth_table && !head->hth_n_entries &&                   \
+          !head->hth_load_limit && head->hth_prime_idx == -1)           \
+        return 0;                                                       \
+      else                                                              \
+        return 1;                                                       \
+    }                                                                   \
+    if (!head->hth_table || head->hth_prime_idx < 0 ||                  \
+        !head->hth_load_limit)                                          \
+      return 2;                                                         \
+    if (head->hth_n_entries > head->hth_load_limit)                     \
+      return 3;                                                         \
+    if (head->hth_table_length != name##_PRIMES[head->hth_prime_idx])   \
+      return 4;                                                         \
+    if (head->hth_load_limit != (unsigned)(load*head->hth_table_length)) \
+      return 5;                                                         \
+    for (n = i = 0; i < head->hth_table_length; ++i) {                  \
+      for (elm = head->hth_table[i]; elm; elm = elm->field.hte_next) {  \
+        if (_HT_ELT_HASH(elm, field, hashfn) != hashfn(elm))           \
+          return 1000 + i;                                              \
+        if ((_HT_ELT_HASH(elm, field, hashfn) % head->hth_table_length) != i) \
+          return 10000 + i;                                             \
+        ++n;                                                            \
+      }                                                                 \
+    }                                                                   \
+    if (n != head->hth_n_entries)                                       \
+      return 6;                                                         \
+    return 0;                                                           \
+  }
+
+/** Implements an over-optimized "find and insert if absent" block;
+ * not meant for direct usage by typical code, or usage outside the critical
+ * path.*/
+#define _HT_FIND_OR_INSERT(name, field, hashfn, head, eltype, elm, var, y, n) \
+  {                                                                     \
+    struct name *_##var##_head = head;                                  \
+    struct eltype **var;                                                                                               \
+    if (!_##var##_head->hth_table ||                                    \
+        _##var##_head->hth_n_entries >= _##var##_head->hth_load_limit)  \
+      name##_HT_GROW(_##var##_head, _##var##_head->hth_n_entries+1);     \
+    _HT_SET_HASH((elm), field, hashfn);                                \
+    var = _##name##_HT_FIND_P(_##var##_head, (elm));                    \
+    if (*var) {                                                         \
+      y;                                                                \
+    } else {                                                            \
+      n;                                                                \
+    }                                                                   \
+  }
+#define _HT_FOI_INSERT(field, head, elm, newent, var)       \
+  {                                                         \
+    _HT_SET_HASHVAL(newent, field, (elm)->field.hte_hash);  \
+    newent->field.hte_next = NULL;                          \
+    *var = newent;                                          \
+    ++((head)->hth_n_entries);                              \
+  }
+
+/*
+ * Copyright 2005, Nick Mathewson.  Implementation logic is adapted from code
+ * by Cristopher Clark, retrofit to allow drop-in memory management, and to
+ * use the same interface as Niels Provos's tree.h.  This is probably still
+ * a derived work, so the original license below still applies.
+ *
+ * Copyright (c) 2002, Christopher Clark
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * 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.
+ *
+ * * Neither the name of the original author; nor the names of any contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER
+ * 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.
+*/
+
+#endif
+
diff --git a/libevent/http-internal.h b/libevent/http-internal.h
new file mode 100644 (file)
index 0000000..5f66673
--- /dev/null
@@ -0,0 +1,195 @@
+/*
+ * Copyright 2001-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * This header file contains definitions for dealing with HTTP requests
+ * that are internal to libevent.  As user of the library, you should not
+ * need to know about these.
+ */
+
+#ifndef _HTTP_INTERNAL_H_
+#define _HTTP_INTERNAL_H_
+
+#include "event2/event_struct.h"
+#include "util-internal.h"
+#include "defer-internal.h"
+
+#define HTTP_CONNECT_TIMEOUT   45
+#define HTTP_WRITE_TIMEOUT     50
+#define HTTP_READ_TIMEOUT      50
+
+#define HTTP_PREFIX            "http://"
+#define HTTP_DEFAULTPORT       80
+
+enum message_read_status {
+       ALL_DATA_READ = 1,
+       MORE_DATA_EXPECTED = 0,
+       DATA_CORRUPTED = -1,
+       REQUEST_CANCELED = -2,
+       DATA_TOO_LONG = -3
+};
+
+enum evhttp_connection_error {
+       EVCON_HTTP_TIMEOUT,
+       EVCON_HTTP_EOF,
+       EVCON_HTTP_INVALID_HEADER,
+       EVCON_HTTP_BUFFER_ERROR,
+       EVCON_HTTP_REQUEST_CANCEL
+};
+
+struct evbuffer;
+struct addrinfo;
+struct evhttp_request;
+
+/* Indicates an unknown request method. */
+#define _EVHTTP_REQ_UNKNOWN (1<<15)
+
+enum evhttp_connection_state {
+       EVCON_DISCONNECTED,     /**< not currently connected not trying either*/
+       EVCON_CONNECTING,       /**< tries to currently connect */
+       EVCON_IDLE,             /**< connection is established */
+       EVCON_READING_FIRSTLINE,/**< reading Request-Line (incoming conn) or
+                                **< Status-Line (outgoing conn) */
+       EVCON_READING_HEADERS,  /**< reading request/response headers */
+       EVCON_READING_BODY,     /**< reading request/response body */
+       EVCON_READING_TRAILER,  /**< reading request/response chunked trailer */
+       EVCON_WRITING           /**< writing request/response headers/body */
+};
+
+struct event_base;
+
+/* A client or server connection. */
+struct evhttp_connection {
+       /* we use this tailq only if this connection was created for an http
+        * server */
+       TAILQ_ENTRY(evhttp_connection) next;
+
+       evutil_socket_t fd;
+       struct bufferevent *bufev;
+
+       struct event retry_ev;          /* for retrying connects */
+
+       char *bind_address;             /* address to use for binding the src */
+       u_short bind_port;              /* local port for binding the src */
+
+       char *address;                  /* address to connect to */
+       u_short port;
+
+       size_t max_headers_size;
+       ev_uint64_t max_body_size;
+
+       int flags;
+#define EVHTTP_CON_INCOMING    0x0001  /* only one request on it ever */
+#define EVHTTP_CON_OUTGOING    0x0002  /* multiple requests possible */
+#define EVHTTP_CON_CLOSEDETECT  0x0004  /* detecting if persistent close */
+
+       int timeout;                    /* timeout in seconds for events */
+       int retry_cnt;                  /* retry count */
+       int retry_max;                  /* maximum number of retries */
+
+       enum evhttp_connection_state state;
+
+       /* for server connections, the http server they are connected with */
+       struct evhttp *http_server;
+
+       TAILQ_HEAD(evcon_requestq, evhttp_request) requests;
+
+       void (*cb)(struct evhttp_connection *, void *);
+       void *cb_arg;
+
+       void (*closecb)(struct evhttp_connection *, void *);
+       void *closecb_arg;
+
+       struct deferred_cb read_more_deferred_cb;
+
+       struct event_base *base;
+       struct evdns_base *dns_base;
+};
+
+/* A callback for an http server */
+struct evhttp_cb {
+       TAILQ_ENTRY(evhttp_cb) next;
+
+       char *what;
+
+       void (*cb)(struct evhttp_request *req, void *);
+       void *cbarg;
+};
+
+/* both the http server as well as the rpc system need to queue connections */
+TAILQ_HEAD(evconq, evhttp_connection);
+
+/* each bound socket is stored in one of these */
+struct evhttp_bound_socket {
+       TAILQ_ENTRY(evhttp_bound_socket) next;
+
+       struct evconnlistener *listener;
+};
+
+/* server alias list item. */
+struct evhttp_server_alias {
+       TAILQ_ENTRY(evhttp_server_alias) next;
+
+       char *alias; /* the server alias. */
+};
+
+struct evhttp {
+       /* Next vhost, if this is a vhost. */
+       TAILQ_ENTRY(evhttp) next_vhost;
+
+       /* All listeners for this host */
+       TAILQ_HEAD(boundq, evhttp_bound_socket) sockets;
+
+       TAILQ_HEAD(httpcbq, evhttp_cb) callbacks;
+
+       /* All live connections on this host. */
+       struct evconq connections;
+
+       TAILQ_HEAD(vhostsq, evhttp) virtualhosts;
+
+       TAILQ_HEAD(aliasq, evhttp_server_alias) aliases;
+
+       /* NULL if this server is not a vhost */
+       char *vhost_pattern;
+
+       int timeout;
+
+       size_t default_max_headers_size;
+       ev_uint64_t default_max_body_size;
+
+       /* Bitmask of all HTTP methods that we accept and pass to user
+        * callbacks. */
+       ev_uint16_t allowed_methods;
+
+       /* Fallback callback if all the other callbacks for this connection
+          don't match. */
+       void (*gencb)(struct evhttp_request *req, void *);
+       void *gencbarg;
+
+       struct event_base *base;
+};
+
+/* XXX most of these functions could be static. */
+
+/* resets the connection; can be reused for more requests */
+void evhttp_connection_reset(struct evhttp_connection *);
+
+/* connects if necessary */
+int evhttp_connection_connect(struct evhttp_connection *);
+
+/* notifies the current request that it failed; resets connection */
+void evhttp_connection_fail(struct evhttp_connection *,
+    enum evhttp_connection_error error);
+
+enum message_read_status;
+
+enum message_read_status evhttp_parse_firstline(struct evhttp_request *, struct evbuffer*);
+enum message_read_status evhttp_parse_headers(struct evhttp_request *, struct evbuffer*);
+
+void evhttp_start_read(struct evhttp_connection *);
+
+/* response sending HTML the data in the buffer */
+void evhttp_response_code(struct evhttp_request *, int, const char *);
+void evhttp_send_page(struct evhttp_request *, struct evbuffer *);
+
+#endif /* _HTTP_H */
diff --git a/libevent/http.c b/libevent/http.c
new file mode 100644 (file)
index 0000000..b9687df
--- /dev/null
@@ -0,0 +1,4515 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef _EVENT_HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef HAVE_SYS_IOCCOM_H
+#include <sys/ioccom.h>
+#endif
+
+#ifndef WIN32
+#include <sys/resource.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#else
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+
+#include <sys/queue.h>
+
+#ifdef _EVENT_HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef _EVENT_HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef _EVENT_HAVE_NETDB_H
+#include <netdb.h>
+#endif
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifndef WIN32
+#include <syslog.h>
+#endif
+#include <signal.h>
+#include <time.h>
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef _EVENT_HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#undef timeout_pending
+#undef timeout_initialized
+
+#include "strlcpy-internal.h"
+#include "event2/http.h"
+#include "event2/event.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/http_struct.h"
+#include "event2/http_compat.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "log-internal.h"
+#include "util-internal.h"
+#include "http-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+
+#ifndef _EVENT_HAVE_GETNAMEINFO
+#define NI_MAXSERV 32
+#define NI_MAXHOST 1025
+
+#ifndef NI_NUMERICHOST
+#define NI_NUMERICHOST 1
+#endif
+
+#ifndef NI_NUMERICSERV
+#define NI_NUMERICSERV 2
+#endif
+
+static int
+fake_getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
+       size_t hostlen, char *serv, size_t servlen, int flags)
+{
+       struct sockaddr_in *sin = (struct sockaddr_in *)sa;
+
+       if (serv != NULL) {
+               char tmpserv[16];
+               evutil_snprintf(tmpserv, sizeof(tmpserv),
+                   "%d", ntohs(sin->sin_port));
+               if (strlcpy(serv, tmpserv, servlen) >= servlen)
+                       return (-1);
+       }
+
+       if (host != NULL) {
+               if (flags & NI_NUMERICHOST) {
+                       if (strlcpy(host, inet_ntoa(sin->sin_addr),
+                           hostlen) >= hostlen)
+                               return (-1);
+                       else
+                               return (0);
+               } else {
+                       struct hostent *hp;
+                       hp = gethostbyaddr((char *)&sin->sin_addr,
+                           sizeof(struct in_addr), AF_INET);
+                       if (hp == NULL)
+                               return (-2);
+
+                       if (strlcpy(host, hp->h_name, hostlen) >= hostlen)
+                               return (-1);
+                       else
+                               return (0);
+               }
+       }
+       return (0);
+}
+
+#endif
+
+#define REQ_VERSION_BEFORE(req, major_v, minor_v)                      \
+       ((req)->major < (major_v) ||                                    \
+           ((req)->major == (major_v) && (req)->minor < (minor_v)))
+
+#define REQ_VERSION_ATLEAST(req, major_v, minor_v)                     \
+       ((req)->major > (major_v) ||                                    \
+           ((req)->major == (major_v) && (req)->minor >= (minor_v)))
+
+#ifndef MIN
+#define MIN(a,b) (((a)<(b))?(a):(b))
+#endif
+
+extern int debug;
+
+static evutil_socket_t bind_socket_ai(struct evutil_addrinfo *, int reuse);
+static evutil_socket_t bind_socket(const char *, ev_uint16_t, int reuse);
+static void name_from_addr(struct sockaddr *, ev_socklen_t, char **, char **);
+static int evhttp_associate_new_request_with_connection(
+       struct evhttp_connection *evcon);
+static void evhttp_connection_start_detectclose(
+       struct evhttp_connection *evcon);
+static void evhttp_connection_stop_detectclose(
+       struct evhttp_connection *evcon);
+static void evhttp_request_dispatch(struct evhttp_connection* evcon);
+static void evhttp_read_firstline(struct evhttp_connection *evcon,
+                                 struct evhttp_request *req);
+static void evhttp_read_header(struct evhttp_connection *evcon,
+    struct evhttp_request *req);
+static int evhttp_add_header_internal(struct evkeyvalq *headers,
+    const char *key, const char *value);
+static const char *evhttp_response_phrase_internal(int code);
+static void evhttp_get_request(struct evhttp *, evutil_socket_t, struct sockaddr *, ev_socklen_t);
+static void evhttp_write_buffer(struct evhttp_connection *,
+    void (*)(struct evhttp_connection *, void *), void *);
+static void evhttp_make_header(struct evhttp_connection *, struct evhttp_request *);
+
+/* callbacks for bufferevent */
+static void evhttp_read_cb(struct bufferevent *, void *);
+static void evhttp_write_cb(struct bufferevent *, void *);
+static void evhttp_error_cb(struct bufferevent *bufev, short what, void *arg);
+static int evhttp_decode_uri_internal(const char *uri, size_t length,
+    char *ret, int decode_plus);
+static int evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
+                 const char *hostname);
+
+#ifndef _EVENT_HAVE_STRSEP
+/* strsep replacement for platforms that lack it.  Only works if
+ * del is one character long. */
+static char *
+strsep(char **s, const char *del)
+{
+       char *d, *tok;
+       EVUTIL_ASSERT(strlen(del) == 1);
+       if (!s || !*s)
+               return NULL;
+       tok = *s;
+       d = strstr(tok, del);
+       if (d) {
+               *d = '\0';
+               *s = d + 1;
+       } else
+               *s = NULL;
+       return tok;
+}
+#endif
+
+static size_t
+html_replace(const char ch, const char **escaped)
+{
+       switch (ch) {
+       case '<':
+               *escaped = "&lt;";
+               return 4;
+       case '>':
+               *escaped = "&gt;";
+               return 4;
+       case '"':
+               *escaped = "&quot;";
+               return 6;
+       case '\'':
+               *escaped = "&#039;";
+               return 6;
+       case '&':
+               *escaped = "&amp;";
+               return 5;
+       default:
+               break;
+       }
+
+       return 1;
+}
+
+/*
+ * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
+ * &#039; and &amp; correspondingly.
+ *
+ * The returned string needs to be freed by the caller.
+ */
+
+char *
+evhttp_htmlescape(const char *html)
+{
+       size_t i;
+       size_t new_size = 0, old_size = 0;
+       char *escaped_html, *p;
+
+       if (html == NULL)
+               return (NULL);
+
+       old_size = strlen(html);
+       for (i = 0; i < old_size; ++i) {
+               const char *replaced = NULL;
+               const size_t replace_size = html_replace(html[i], &replaced);
+               if (replace_size > EV_SIZE_MAX - new_size) {
+                       event_warn("%s: html_replace overflow", __func__);
+                       return (NULL);
+               }
+               new_size += replace_size;
+       }
+
+       if (new_size == EV_SIZE_MAX)
+               return (NULL);
+       p = escaped_html = mm_malloc(new_size + 1);
+       if (escaped_html == NULL) {
+               event_warn("%s: malloc(%lu)", __func__,
+                          (unsigned long)(new_size + 1));
+               return (NULL);
+       }
+       for (i = 0; i < old_size; ++i) {
+               const char *replaced = &html[i];
+               const size_t len = html_replace(html[i], &replaced);
+               memcpy(p, replaced, len);
+               p += len;
+       }
+
+       *p = '\0';
+
+       return (escaped_html);
+}
+
+/** Given an evhttp_cmd_type, returns a constant string containing the
+ * equivalent HTTP command, or NULL if the evhttp_command_type is
+ * unrecognized. */
+static const char *
+evhttp_method(enum evhttp_cmd_type type)
+{
+       const char *method;
+
+       switch (type) {
+       case EVHTTP_REQ_GET:
+               method = "GET";
+               break;
+       case EVHTTP_REQ_POST:
+               method = "POST";
+               break;
+       case EVHTTP_REQ_HEAD:
+               method = "HEAD";
+               break;
+       case EVHTTP_REQ_PUT:
+               method = "PUT";
+               break;
+       case EVHTTP_REQ_DELETE:
+               method = "DELETE";
+               break;
+       case EVHTTP_REQ_OPTIONS:
+               method = "OPTIONS";
+               break;
+       case EVHTTP_REQ_TRACE:
+               method = "TRACE";
+               break;
+       case EVHTTP_REQ_CONNECT:
+               method = "CONNECT";
+               break;
+       case EVHTTP_REQ_PATCH:
+               method = "PATCH";
+               break;
+       default:
+               method = NULL;
+               break;
+       }
+
+       return (method);
+}
+
+/**
+ * Determines if a response should have a body.
+ * Follows the rules in RFC 2616 section 4.3.
+ * @return 1 if the response MUST have a body; 0 if the response MUST NOT have
+ *     a body.
+ */
+static int
+evhttp_response_needs_body(struct evhttp_request *req)
+{
+       return (req->response_code != HTTP_NOCONTENT &&
+               req->response_code != HTTP_NOTMODIFIED &&
+               (req->response_code < 100 || req->response_code >= 200) &&
+               req->type != EVHTTP_REQ_HEAD);
+}
+
+/** Helper: adds the event 'ev' with the timeout 'timeout', or with
+ * default_timeout if timeout is -1.
+ */
+static int
+evhttp_add_event(struct event *ev, int timeout, int default_timeout)
+{
+       if (timeout != 0) {
+               struct timeval tv;
+
+               evutil_timerclear(&tv);
+               tv.tv_sec = timeout != -1 ? timeout : default_timeout;
+               return event_add(ev, &tv);
+       } else {
+               return event_add(ev, NULL);
+       }
+}
+
+/** Helper: called after we've added some data to an evcon's bufferevent's
+ * output buffer.  Sets the evconn's writing-is-done callback, and puts
+ * the bufferevent into writing mode.
+ */
+static void
+evhttp_write_buffer(struct evhttp_connection *evcon,
+    void (*cb)(struct evhttp_connection *, void *), void *arg)
+{
+       event_debug(("%s: preparing to write buffer\n", __func__));
+
+       /* Set call back */
+       evcon->cb = cb;
+       evcon->cb_arg = arg;
+
+       bufferevent_enable(evcon->bufev, EV_WRITE);
+
+       /* Disable the read callback: we don't actually care about data;
+        * we only care about close detection.  (We don't disable reading,
+        * since we *do* want to learn about any close events.) */
+       bufferevent_setcb(evcon->bufev,
+           NULL, /*read*/
+           evhttp_write_cb,
+           evhttp_error_cb,
+           evcon);
+}
+
+static void
+evhttp_send_continue_done(struct evhttp_connection *evcon, void *arg)
+{
+       bufferevent_disable(evcon->bufev, EV_WRITE);
+}
+
+static void
+evhttp_send_continue(struct evhttp_connection *evcon,
+                       struct evhttp_request *req)
+{
+       bufferevent_enable(evcon->bufev, EV_WRITE);
+       evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
+                       "HTTP/%d.%d 100 Continue\r\n\r\n",
+                       req->major, req->minor);
+       evcon->cb = evhttp_send_continue_done;
+       evcon->cb_arg = NULL;
+       bufferevent_setcb(evcon->bufev,
+           evhttp_read_cb,
+           evhttp_write_cb,
+           evhttp_error_cb,
+           evcon);
+}
+
+/** Helper: returns true iff evconn is in any connected state. */
+static int
+evhttp_connected(struct evhttp_connection *evcon)
+{
+       switch (evcon->state) {
+       case EVCON_DISCONNECTED:
+       case EVCON_CONNECTING:
+               return (0);
+       case EVCON_IDLE:
+       case EVCON_READING_FIRSTLINE:
+       case EVCON_READING_HEADERS:
+       case EVCON_READING_BODY:
+       case EVCON_READING_TRAILER:
+       case EVCON_WRITING:
+       default:
+               return (1);
+       }
+}
+
+/* Create the headers needed for an outgoing HTTP request, adds them to
+ * the request's header list, and writes the request line to the
+ * connection's output buffer.
+ */
+static void
+evhttp_make_header_request(struct evhttp_connection *evcon,
+    struct evhttp_request *req)
+{
+       const char *method;
+
+       evhttp_remove_header(req->output_headers, "Proxy-Connection");
+
+       /* Generate request line */
+       method = evhttp_method(req->type);
+       evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
+           "%s %s HTTP/%d.%d\r\n",
+           method, req->uri, req->major, req->minor);
+
+       /* Add the content length on a post or put request if missing */
+       if ((req->type == EVHTTP_REQ_POST || req->type == EVHTTP_REQ_PUT) &&
+           evhttp_find_header(req->output_headers, "Content-Length") == NULL){
+               char size[22];
+               evutil_snprintf(size, sizeof(size), EV_SIZE_FMT,
+                   EV_SIZE_ARG(evbuffer_get_length(req->output_buffer)));
+               evhttp_add_header(req->output_headers, "Content-Length", size);
+       }
+}
+
+/** Return true if the list of headers in 'headers', intepreted with respect
+ * to flags, means that we should send a "connection: close" when the request
+ * is done. */
+static int
+evhttp_is_connection_close(int flags, struct evkeyvalq* headers)
+{
+       if (flags & EVHTTP_PROXY_REQUEST) {
+               /* proxy connection */
+               const char *connection = evhttp_find_header(headers, "Proxy-Connection");
+               return (connection == NULL || evutil_ascii_strcasecmp(connection, "keep-alive") != 0);
+       } else {
+               const char *connection = evhttp_find_header(headers, "Connection");
+               return (connection != NULL && evutil_ascii_strcasecmp(connection, "close") == 0);
+       }
+}
+
+/* Return true iff 'headers' contains 'Connection: keep-alive' */
+static int
+evhttp_is_connection_keepalive(struct evkeyvalq* headers)
+{
+       const char *connection = evhttp_find_header(headers, "Connection");
+       return (connection != NULL
+           && evutil_ascii_strncasecmp(connection, "keep-alive", 10) == 0);
+}
+
+/* Add a correct "Date" header to headers, unless it already has one. */
+static void
+evhttp_maybe_add_date_header(struct evkeyvalq *headers)
+{
+       if (evhttp_find_header(headers, "Date") == NULL) {
+               char date[50];
+#ifndef WIN32
+               struct tm cur;
+#endif
+               struct tm *cur_p;
+               time_t t = time(NULL);
+#ifdef WIN32
+               cur_p = gmtime(&t);
+#else
+               gmtime_r(&t, &cur);
+               cur_p = &cur;
+#endif
+               if (strftime(date, sizeof(date),
+                       "%a, %d %b %Y %H:%M:%S GMT", cur_p) != 0) {
+                       evhttp_add_header(headers, "Date", date);
+               }
+       }
+}
+
+/* Add a "Content-Length" header with value 'content_length' to headers,
+ * unless it already has a content-length or transfer-encoding header. */
+static void
+evhttp_maybe_add_content_length_header(struct evkeyvalq *headers,
+    size_t content_length)
+{
+       if (evhttp_find_header(headers, "Transfer-Encoding") == NULL &&
+           evhttp_find_header(headers, "Content-Length") == NULL) {
+               char len[22];
+               evutil_snprintf(len, sizeof(len), EV_SIZE_FMT,
+                   EV_SIZE_ARG(content_length));
+               evhttp_add_header(headers, "Content-Length", len);
+       }
+}
+
+/*
+ * Create the headers needed for an HTTP reply in req->output_headers,
+ * and write the first HTTP response for req line to evcon.
+ */
+static void
+evhttp_make_header_response(struct evhttp_connection *evcon,
+    struct evhttp_request *req)
+{
+       int is_keepalive = evhttp_is_connection_keepalive(req->input_headers);
+       evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
+           "HTTP/%d.%d %d %s\r\n",
+           req->major, req->minor, req->response_code,
+           req->response_code_line);
+
+       if (req->major == 1) {
+               if (req->minor >= 1)
+                       evhttp_maybe_add_date_header(req->output_headers);
+
+               /*
+                * if the protocol is 1.0; and the connection was keep-alive
+                * we need to add a keep-alive header, too.
+                */
+               if (req->minor == 0 && is_keepalive)
+                       evhttp_add_header(req->output_headers,
+                           "Connection", "keep-alive");
+
+               if ((req->minor >= 1 || is_keepalive) &&
+                   evhttp_response_needs_body(req)) {
+                       /*
+                        * we need to add the content length if the
+                        * user did not give it, this is required for
+                        * persistent connections to work.
+                        */
+                       evhttp_maybe_add_content_length_header(
+                               req->output_headers,
+                               evbuffer_get_length(req->output_buffer));
+               }
+       }
+
+       /* Potentially add headers for unidentified content. */
+       if (evhttp_response_needs_body(req)) {
+               if (evhttp_find_header(req->output_headers,
+                       "Content-Type") == NULL) {
+                       evhttp_add_header(req->output_headers,
+                           "Content-Type", "text/html; charset=ISO-8859-1");
+               }
+       }
+
+       /* if the request asked for a close, we send a close, too */
+       if (evhttp_is_connection_close(req->flags, req->input_headers)) {
+               evhttp_remove_header(req->output_headers, "Connection");
+               if (!(req->flags & EVHTTP_PROXY_REQUEST))
+                   evhttp_add_header(req->output_headers, "Connection", "close");
+               evhttp_remove_header(req->output_headers, "Proxy-Connection");
+       }
+}
+
+/** Generate all headers appropriate for sending the http request in req (or
+ * the response, if we're sending a response), and write them to evcon's
+ * bufferevent. Also writes all data from req->output_buffer */
+static void
+evhttp_make_header(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+       struct evkeyval *header;
+       struct evbuffer *output = bufferevent_get_output(evcon->bufev);
+
+       /*
+        * Depending if this is a HTTP request or response, we might need to
+        * add some new headers or remove existing headers.
+        */
+       if (req->kind == EVHTTP_REQUEST) {
+               evhttp_make_header_request(evcon, req);
+       } else {
+               evhttp_make_header_response(evcon, req);
+       }
+
+       TAILQ_FOREACH(header, req->output_headers, next) {
+               evbuffer_add_printf(output, "%s: %s\r\n",
+                   header->key, header->value);
+       }
+       evbuffer_add(output, "\r\n", 2);
+
+       if (evbuffer_get_length(req->output_buffer) > 0) {
+               /*
+                * For a request, we add the POST data, for a reply, this
+                * is the regular data.
+                */
+               /* XXX We might want to support waiting (a limited amount of
+                  time) for a continue status line from the server before
+                  sending POST/PUT message bodies. */
+               evbuffer_add_buffer(output, req->output_buffer);
+       }
+}
+
+void
+evhttp_connection_set_max_headers_size(struct evhttp_connection *evcon,
+    ev_ssize_t new_max_headers_size)
+{
+       if (new_max_headers_size<0)
+               evcon->max_headers_size = EV_SIZE_MAX;
+       else
+               evcon->max_headers_size = new_max_headers_size;
+}
+void
+evhttp_connection_set_max_body_size(struct evhttp_connection* evcon,
+    ev_ssize_t new_max_body_size)
+{
+       if (new_max_body_size<0)
+               evcon->max_body_size = EV_UINT64_MAX;
+       else
+               evcon->max_body_size = new_max_body_size;
+}
+
+static int
+evhttp_connection_incoming_fail(struct evhttp_request *req,
+    enum evhttp_connection_error error)
+{
+       switch (error) {
+       case EVCON_HTTP_TIMEOUT:
+       case EVCON_HTTP_EOF:
+               /*
+                * these are cases in which we probably should just
+                * close the connection and not send a reply.  this
+                * case may happen when a browser keeps a persistent
+                * connection open and we timeout on the read.  when
+                * the request is still being used for sending, we
+                * need to disassociated it from the connection here.
+                */
+               if (!req->userdone) {
+                       /* remove it so that it will not be freed */
+                       TAILQ_REMOVE(&req->evcon->requests, req, next);
+                       /* indicate that this request no longer has a
+                        * connection object
+                        */
+                       req->evcon = NULL;
+               }
+               return (-1);
+       case EVCON_HTTP_INVALID_HEADER:
+       case EVCON_HTTP_BUFFER_ERROR:
+       case EVCON_HTTP_REQUEST_CANCEL:
+       default:        /* xxx: probably should just error on default */
+               /* the callback looks at the uri to determine errors */
+               if (req->uri) {
+                       mm_free(req->uri);
+                       req->uri = NULL;
+               }
+               if (req->uri_elems) {
+                       evhttp_uri_free(req->uri_elems);
+                       req->uri_elems = NULL;
+               }
+
+               /*
+                * the callback needs to send a reply, once the reply has
+                * been send, the connection should get freed.
+                */
+               (*req->cb)(req, req->cb_arg);
+       }
+
+       return (0);
+}
+
+/* Called when evcon has experienced a (non-recoverable? -NM) error, as
+ * given in error. If it's an outgoing connection, reset the connection,
+ * retry any pending requests, and inform the user.  If it's incoming,
+ * delegates to evhttp_connection_incoming_fail(). */
+void
+evhttp_connection_fail(struct evhttp_connection *evcon,
+    enum evhttp_connection_error error)
+{
+       struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
+       void (*cb)(struct evhttp_request *, void *);
+       void *cb_arg;
+       EVUTIL_ASSERT(req != NULL);
+
+       bufferevent_disable(evcon->bufev, EV_READ|EV_WRITE);
+
+       if (evcon->flags & EVHTTP_CON_INCOMING) {
+               /*
+                * for incoming requests, there are two different
+                * failure cases.  it's either a network level error
+                * or an http layer error. for problems on the network
+                * layer like timeouts we just drop the connections.
+                * For HTTP problems, we might have to send back a
+                * reply before the connection can be freed.
+                */
+               if (evhttp_connection_incoming_fail(req, error) == -1)
+                       evhttp_connection_free(evcon);
+               return;
+       }
+
+       /* when the request was canceled, the callback is not executed */
+       if (error != EVCON_HTTP_REQUEST_CANCEL) {
+               /* save the callback for later; the cb might free our object */
+               cb = req->cb;
+               cb_arg = req->cb_arg;
+       } else {
+               cb = NULL;
+               cb_arg = NULL;
+       }
+
+       /* do not fail all requests; the next request is going to get
+        * send over a new connection.   when a user cancels a request,
+        * all other pending requests should be processed as normal
+        */
+       TAILQ_REMOVE(&evcon->requests, req, next);
+       evhttp_request_free(req);
+
+       /* reset the connection */
+       evhttp_connection_reset(evcon);
+
+       /* We are trying the next request that was queued on us */
+       if (TAILQ_FIRST(&evcon->requests) != NULL)
+               evhttp_connection_connect(evcon);
+
+       /* inform the user */
+       if (cb != NULL)
+               (*cb)(NULL, cb_arg);
+}
+
+/* Bufferevent callback: invoked when any data has been written from an
+ * http connection's bufferevent */
+static void
+evhttp_write_cb(struct bufferevent *bufev, void *arg)
+{
+       struct evhttp_connection *evcon = arg;
+
+       /* Activate our call back */
+       if (evcon->cb != NULL)
+               (*evcon->cb)(evcon, evcon->cb_arg);
+}
+
+/**
+ * Advance the connection state.
+ * - If this is an outgoing connection, we've just processed the response;
+ *   idle or close the connection.
+ * - If this is an incoming connection, we've just processed the request;
+ *   respond.
+ */
+static void
+evhttp_connection_done(struct evhttp_connection *evcon)
+{
+       struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+       int con_outgoing = evcon->flags & EVHTTP_CON_OUTGOING;
+
+       if (con_outgoing) {
+               /* idle or close the connection */
+               int need_close;
+               TAILQ_REMOVE(&evcon->requests, req, next);
+               req->evcon = NULL;
+
+               evcon->state = EVCON_IDLE;
+
+               need_close =
+                   evhttp_is_connection_close(req->flags, req->input_headers)||
+                   evhttp_is_connection_close(req->flags, req->output_headers);
+
+               /* check if we got asked to close the connection */
+               if (need_close)
+                       evhttp_connection_reset(evcon);
+
+               if (TAILQ_FIRST(&evcon->requests) != NULL) {
+                       /*
+                        * We have more requests; reset the connection
+                        * and deal with the next request.
+                        */
+                       if (!evhttp_connected(evcon))
+                               evhttp_connection_connect(evcon);
+                       else
+                               evhttp_request_dispatch(evcon);
+               } else if (!need_close) {
+                       /*
+                        * The connection is going to be persistent, but we
+                        * need to detect if the other side closes it.
+                        */
+                       evhttp_connection_start_detectclose(evcon);
+               }
+       } else {
+               /*
+                * incoming connection - we need to leave the request on the
+                * connection so that we can reply to it.
+                */
+               evcon->state = EVCON_WRITING;
+       }
+
+       /* notify the user of the request */
+       (*req->cb)(req, req->cb_arg);
+
+       /* if this was an outgoing request, we own and it's done. so free it.
+        * unless the callback specifically requested to own the request.
+        */
+       if (con_outgoing && ((req->flags & EVHTTP_USER_OWNED) == 0)) {
+               evhttp_request_free(req);
+       }
+}
+
+/*
+ * Handles reading from a chunked request.
+ *   return ALL_DATA_READ:
+ *     all data has been read
+ *   return MORE_DATA_EXPECTED:
+ *     more data is expected
+ *   return DATA_CORRUPTED:
+ *     data is corrupted
+ *   return REQUEST_CANCELED:
+ *     request was canceled by the user calling evhttp_cancel_request
+ *   return DATA_TOO_LONG:
+ *     ran over the maximum limit
+ */
+
+static enum message_read_status
+evhttp_handle_chunked_read(struct evhttp_request *req, struct evbuffer *buf)
+{
+       if (req == NULL || buf == NULL) {
+           return DATA_CORRUPTED;
+       }
+
+       while (1) {
+               size_t buflen;
+
+               if ((buflen = evbuffer_get_length(buf)) == 0) {
+                       break;
+               }
+
+               /* evbuffer_get_length returns size_t, but len variable is ssize_t,
+                * check for overflow conditions */
+               if (buflen > EV_SSIZE_MAX) {
+                       return DATA_CORRUPTED;
+               }
+
+               if (req->ntoread < 0) {
+                       /* Read chunk size */
+                       ev_int64_t ntoread;
+                       char *p = evbuffer_readln(buf, NULL, EVBUFFER_EOL_CRLF);
+                       char *endp;
+                       int error;
+                       if (p == NULL)
+                               break;
+                       /* the last chunk is on a new line? */
+                       if (strlen(p) == 0) {
+                               mm_free(p);
+                               continue;
+                       }
+                       ntoread = evutil_strtoll(p, &endp, 16);
+                       error = (*p == '\0' ||
+                           (*endp != '\0' && *endp != ' ') ||
+                           ntoread < 0);
+                       mm_free(p);
+                       if (error) {
+                               /* could not get chunk size */
+                               return (DATA_CORRUPTED);
+                       }
+
+                       /* ntoread is signed int64, body_size is unsigned size_t, check for under/overflow conditions */
+                       if ((ev_uint64_t)ntoread > EV_SIZE_MAX - req->body_size) {
+                           return DATA_CORRUPTED;
+                       }
+
+                       if (req->body_size + (size_t)ntoread > req->evcon->max_body_size) {
+                               /* failed body length test */
+                               event_debug(("Request body is too long"));
+                               return (DATA_TOO_LONG);
+                       }
+
+                       req->body_size += (size_t)ntoread;
+                       req->ntoread = ntoread;
+                       if (req->ntoread == 0) {
+                               /* Last chunk */
+                               return (ALL_DATA_READ);
+                       }
+                       continue;
+               }
+
+               /* req->ntoread is signed int64, len is ssize_t, based on arch,
+                * ssize_t could only be 32b, check for these conditions */
+               if (req->ntoread > EV_SSIZE_MAX) {
+                       return DATA_CORRUPTED;
+               }
+
+               /* don't have enough to complete a chunk; wait for more */
+               if (req->ntoread > 0 && buflen < (ev_uint64_t)req->ntoread)
+                       return (MORE_DATA_EXPECTED);
+
+               /* Completed chunk */
+               evbuffer_remove_buffer(buf, req->input_buffer, (size_t)req->ntoread);
+               req->ntoread = -1;
+               if (req->chunk_cb != NULL) {
+                       req->flags |= EVHTTP_REQ_DEFER_FREE;
+                       (*req->chunk_cb)(req, req->cb_arg);
+                       evbuffer_drain(req->input_buffer,
+                           evbuffer_get_length(req->input_buffer));
+                       req->flags &= ~EVHTTP_REQ_DEFER_FREE;
+                       if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
+                               return (REQUEST_CANCELED);
+                       }
+               }
+       }
+
+       return (MORE_DATA_EXPECTED);
+}
+
+static void
+evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+       struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
+
+       switch (evhttp_parse_headers(req, buf)) {
+       case DATA_CORRUPTED:
+       case DATA_TOO_LONG:
+               evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+               break;
+       case ALL_DATA_READ:
+               bufferevent_disable(evcon->bufev, EV_READ);
+               evhttp_connection_done(evcon);
+               break;
+       case MORE_DATA_EXPECTED:
+       case REQUEST_CANCELED: /* ??? */
+       default:
+               bufferevent_enable(evcon->bufev, EV_READ);
+               break;
+       }
+}
+
+static void
+evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+       struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
+
+       if (req->chunked) {
+               switch (evhttp_handle_chunked_read(req, buf)) {
+               case ALL_DATA_READ:
+                       /* finished last chunk */
+                       evcon->state = EVCON_READING_TRAILER;
+                       evhttp_read_trailer(evcon, req);
+                       return;
+               case DATA_CORRUPTED:
+               case DATA_TOO_LONG:/*separate error for this? XXX */
+                       /* corrupted data */
+                       evhttp_connection_fail(evcon,
+                           EVCON_HTTP_INVALID_HEADER);
+                       return;
+               case REQUEST_CANCELED:
+                       /* request canceled */
+                       evhttp_request_free(req);
+                       return;
+               case MORE_DATA_EXPECTED:
+               default:
+                       break;
+               }
+       } else if (req->ntoread < 0) {
+               /* Read until connection close. */
+               if ((size_t)(req->body_size + evbuffer_get_length(buf)) < req->body_size) {
+                       evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+                       return;
+               }
+
+               req->body_size += evbuffer_get_length(buf);
+               evbuffer_add_buffer(req->input_buffer, buf);
+       } else if (req->chunk_cb != NULL || evbuffer_get_length(buf) >= (size_t)req->ntoread) {
+               /* XXX: the above get_length comparison has to be fixed for overflow conditions! */
+               /* We've postponed moving the data until now, but we're
+                * about to use it. */
+               size_t n = evbuffer_get_length(buf);
+
+               if (n > (size_t) req->ntoread)
+                       n = (size_t) req->ntoread;
+               req->ntoread -= n;
+               req->body_size += n;
+               evbuffer_remove_buffer(buf, req->input_buffer, n);
+       }
+
+       if (req->body_size > req->evcon->max_body_size ||
+           (!req->chunked && req->ntoread >= 0 &&
+               (size_t)req->ntoread > req->evcon->max_body_size)) {
+               /* XXX: The above casted comparison must checked for overflow */
+               /* failed body length test */
+               event_debug(("Request body is too long"));
+               evhttp_connection_fail(evcon,
+                                      EVCON_HTTP_INVALID_HEADER);
+               return;
+       }
+
+       if (evbuffer_get_length(req->input_buffer) > 0 && req->chunk_cb != NULL) {
+               req->flags |= EVHTTP_REQ_DEFER_FREE;
+               (*req->chunk_cb)(req, req->cb_arg);
+               req->flags &= ~EVHTTP_REQ_DEFER_FREE;
+               evbuffer_drain(req->input_buffer,
+                   evbuffer_get_length(req->input_buffer));
+               if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
+                       evhttp_request_free(req);
+                       return;
+               }
+       }
+
+       if (req->ntoread == 0) {
+               bufferevent_disable(evcon->bufev, EV_READ);
+               /* Completed content length */
+               evhttp_connection_done(evcon);
+               return;
+       }
+
+       /* Read more! */
+       bufferevent_enable(evcon->bufev, EV_READ);
+}
+
+#define get_deferred_queue(evcon)              \
+       (event_base_get_deferred_cb_queue((evcon)->base))
+
+/*
+ * Gets called when more data becomes available
+ */
+
+static void
+evhttp_read_cb(struct bufferevent *bufev, void *arg)
+{
+       struct evhttp_connection *evcon = arg;
+       struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+
+       /* Cancel if it's pending. */
+       event_deferred_cb_cancel(get_deferred_queue(evcon),
+           &evcon->read_more_deferred_cb);
+
+       switch (evcon->state) {
+       case EVCON_READING_FIRSTLINE:
+               evhttp_read_firstline(evcon, req);
+               /* note the request may have been freed in
+                * evhttp_read_body */
+               break;
+       case EVCON_READING_HEADERS:
+               evhttp_read_header(evcon, req);
+               /* note the request may have been freed in
+                * evhttp_read_body */
+               break;
+       case EVCON_READING_BODY:
+               evhttp_read_body(evcon, req);
+               /* note the request may have been freed in
+                * evhttp_read_body */
+               break;
+       case EVCON_READING_TRAILER:
+               evhttp_read_trailer(evcon, req);
+               break;
+       case EVCON_IDLE:
+               {
+#ifdef USE_DEBUG
+                       struct evbuffer *input;
+                       size_t total_len;
+
+                       input = bufferevent_get_input(evcon->bufev);
+                       total_len = evbuffer_get_length(input);
+                       event_debug(("%s: read "EV_SIZE_FMT
+                               " bytes in EVCON_IDLE state,"
+                               " resetting connection",
+                               __func__, EV_SIZE_ARG(total_len)));
+#endif
+
+                       evhttp_connection_reset(evcon);
+               }
+               break;
+       case EVCON_DISCONNECTED:
+       case EVCON_CONNECTING:
+       case EVCON_WRITING:
+       default:
+               event_errx(1, "%s: illegal connection state %d",
+                          __func__, evcon->state);
+       }
+}
+
+static void
+evhttp_deferred_read_cb(struct deferred_cb *cb, void *data)
+{
+       struct evhttp_connection *evcon = data;
+       evhttp_read_cb(evcon->bufev, evcon);
+}
+
+static void
+evhttp_write_connectioncb(struct evhttp_connection *evcon, void *arg)
+{
+       /* This is after writing the request to the server */
+       struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+       EVUTIL_ASSERT(req != NULL);
+
+       EVUTIL_ASSERT(evcon->state == EVCON_WRITING);
+
+       /* We are done writing our header and are now expecting the response */
+       req->kind = EVHTTP_RESPONSE;
+
+       evhttp_start_read(evcon);
+}
+
+/*
+ * Clean up a connection object
+ */
+
+void
+evhttp_connection_free(struct evhttp_connection *evcon)
+{
+       struct evhttp_request *req;
+
+       /* notify interested parties that this connection is going down */
+       if (evcon->fd != -1) {
+               if (evhttp_connected(evcon) && evcon->closecb != NULL)
+                       (*evcon->closecb)(evcon, evcon->closecb_arg);
+       }
+
+       /* remove all requests that might be queued on this
+        * connection.  for server connections, this should be empty.
+        * because it gets dequeued either in evhttp_connection_done or
+        * evhttp_connection_fail.
+        */
+       while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
+               TAILQ_REMOVE(&evcon->requests, req, next);
+               evhttp_request_free(req);
+       }
+
+       if (evcon->http_server != NULL) {
+               struct evhttp *http = evcon->http_server;
+               TAILQ_REMOVE(&http->connections, evcon, next);
+       }
+
+       if (event_initialized(&evcon->retry_ev)) {
+               event_del(&evcon->retry_ev);
+               event_debug_unassign(&evcon->retry_ev);
+       }
+
+       if (evcon->bufev != NULL)
+               bufferevent_free(evcon->bufev);
+
+       event_deferred_cb_cancel(get_deferred_queue(evcon),
+           &evcon->read_more_deferred_cb);
+
+       if (evcon->fd != -1) {
+               shutdown(evcon->fd, EVUTIL_SHUT_WR);
+               evutil_closesocket(evcon->fd);
+       }
+
+       if (evcon->bind_address != NULL)
+               mm_free(evcon->bind_address);
+
+       if (evcon->address != NULL)
+               mm_free(evcon->address);
+
+       mm_free(evcon);
+}
+
+void
+evhttp_connection_set_local_address(struct evhttp_connection *evcon,
+    const char *address)
+{
+       EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
+       if (evcon->bind_address)
+               mm_free(evcon->bind_address);
+       if ((evcon->bind_address = mm_strdup(address)) == NULL)
+               event_warn("%s: strdup", __func__);
+}
+
+void
+evhttp_connection_set_local_port(struct evhttp_connection *evcon,
+    ev_uint16_t port)
+{
+       EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
+       evcon->bind_port = port;
+}
+
+static void
+evhttp_request_dispatch(struct evhttp_connection* evcon)
+{
+       struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+
+       /* this should not usually happy but it's possible */
+       if (req == NULL)
+               return;
+
+       /* delete possible close detection events */
+       evhttp_connection_stop_detectclose(evcon);
+
+       /* we assume that the connection is connected already */
+       EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
+
+       evcon->state = EVCON_WRITING;
+
+       /* Create the header from the store arguments */
+       evhttp_make_header(evcon, req);
+
+       evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
+}
+
+/* Reset our connection state: disables reading/writing, closes our fd (if
+* any), clears out buffers, and puts us in state DISCONNECTED. */
+void
+evhttp_connection_reset(struct evhttp_connection *evcon)
+{
+       struct evbuffer *tmp;
+
+       /* XXXX This is not actually an optimal fix.  Instead we ought to have
+          an API for "stop connecting", or use bufferevent_setfd to turn off
+          connecting.  But for Libevent 2.0, this seems like a minimal change
+          least likely to disrupt the rest of the bufferevent and http code.
+
+          Why is this here?  If the fd is set in the bufferevent, and the
+          bufferevent is connecting, then you can't actually stop the
+          bufferevent from trying to connect with bufferevent_disable().  The
+          connect will never trigger, since we close the fd, but the timeout
+          might.  That caused an assertion failure in evhttp_connection_fail.
+       */
+       bufferevent_disable_hard(evcon->bufev, EV_READ|EV_WRITE);
+
+       if (evcon->fd != -1) {
+               /* inform interested parties about connection close */
+               if (evhttp_connected(evcon) && evcon->closecb != NULL)
+                       (*evcon->closecb)(evcon, evcon->closecb_arg);
+
+               shutdown(evcon->fd, EVUTIL_SHUT_WR);
+               evutil_closesocket(evcon->fd);
+               evcon->fd = -1;
+       }
+
+       /* we need to clean up any buffered data */
+       tmp = bufferevent_get_output(evcon->bufev);
+       evbuffer_drain(tmp, evbuffer_get_length(tmp));
+       tmp = bufferevent_get_input(evcon->bufev);
+       evbuffer_drain(tmp, evbuffer_get_length(tmp));
+
+       evcon->state = EVCON_DISCONNECTED;
+}
+
+static void
+evhttp_connection_start_detectclose(struct evhttp_connection *evcon)
+{
+       evcon->flags |= EVHTTP_CON_CLOSEDETECT;
+
+       bufferevent_enable(evcon->bufev, EV_READ);
+}
+
+static void
+evhttp_connection_stop_detectclose(struct evhttp_connection *evcon)
+{
+       evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
+
+       bufferevent_disable(evcon->bufev, EV_READ);
+}
+
+static void
+evhttp_connection_retry(evutil_socket_t fd, short what, void *arg)
+{
+       struct evhttp_connection *evcon = arg;
+
+       evcon->state = EVCON_DISCONNECTED;
+       evhttp_connection_connect(evcon);
+}
+
+static void
+evhttp_connection_cb_cleanup(struct evhttp_connection *evcon)
+{
+       struct evcon_requestq requests;
+
+       if (evcon->retry_max < 0 || evcon->retry_cnt < evcon->retry_max) {
+               evtimer_assign(&evcon->retry_ev, evcon->base, evhttp_connection_retry, evcon);
+               /* XXXX handle failure from evhttp_add_event */
+               evhttp_add_event(&evcon->retry_ev,
+                   MIN(3600, 2 << evcon->retry_cnt),
+                   HTTP_CONNECT_TIMEOUT);
+               evcon->retry_cnt++;
+               return;
+       }
+       evhttp_connection_reset(evcon);
+
+       /*
+        * User callback can do evhttp_make_request() on the same
+        * evcon so new request will be added to evcon->requests.  To
+        * avoid freeing it prematurely we iterate over the copy of
+        * the queue.
+        */
+       TAILQ_INIT(&requests);
+       while (TAILQ_FIRST(&evcon->requests) != NULL) {
+               struct evhttp_request *request = TAILQ_FIRST(&evcon->requests);
+               TAILQ_REMOVE(&evcon->requests, request, next);
+               TAILQ_INSERT_TAIL(&requests, request, next);
+       }
+
+       /* for now, we just signal all requests by executing their callbacks */
+       while (TAILQ_FIRST(&requests) != NULL) {
+               struct evhttp_request *request = TAILQ_FIRST(&requests);
+               TAILQ_REMOVE(&requests, request, next);
+               request->evcon = NULL;
+
+               /* we might want to set an error here */
+               request->cb(request, request->cb_arg);
+               evhttp_request_free(request);
+       }
+}
+
+static void
+evhttp_error_cb(struct bufferevent *bufev, short what, void *arg)
+{
+       struct evhttp_connection *evcon = arg;
+       struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+
+       switch (evcon->state) {
+       case EVCON_CONNECTING:
+               if (what & BEV_EVENT_TIMEOUT) {
+                       event_debug(("%s: connection timeout for \"%s:%d\" on %d",
+                               __func__, evcon->address, evcon->port,
+                               evcon->fd));
+                       evhttp_connection_cb_cleanup(evcon);
+                       return;
+               }
+               break;
+
+       case EVCON_READING_BODY:
+               if (!req->chunked && req->ntoread < 0
+                   && what == (BEV_EVENT_READING|BEV_EVENT_EOF)) {
+                       /* EOF on read can be benign */
+                       evhttp_connection_done(evcon);
+                       return;
+               }
+               break;
+
+       case EVCON_DISCONNECTED:
+       case EVCON_IDLE:
+       case EVCON_READING_FIRSTLINE:
+       case EVCON_READING_HEADERS:
+       case EVCON_READING_TRAILER:
+       case EVCON_WRITING:
+       default:
+               break;
+       }
+
+       /* when we are in close detect mode, a read error means that
+        * the other side closed their connection.
+        */
+       if (evcon->flags & EVHTTP_CON_CLOSEDETECT) {
+               evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
+               EVUTIL_ASSERT(evcon->http_server == NULL);
+               /* For connections from the client, we just
+                * reset the connection so that it becomes
+                * disconnected.
+                */
+               EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
+               evhttp_connection_reset(evcon);
+               return;
+       }
+
+       if (what & BEV_EVENT_TIMEOUT) {
+               evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
+       } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
+               evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
+       } else {
+               evhttp_connection_fail(evcon, EVCON_HTTP_BUFFER_ERROR);
+       }
+}
+
+/*
+ * Event callback for asynchronous connection attempt.
+ */
+static void
+evhttp_connection_cb(struct bufferevent *bufev, short what, void *arg)
+{
+       struct evhttp_connection *evcon = arg;
+       int error;
+       ev_socklen_t errsz = sizeof(error);
+
+       if (!(what & BEV_EVENT_CONNECTED)) {
+               /* some operating systems return ECONNREFUSED immediately
+                * when connecting to a local address.  the cleanup is going
+                * to reschedule this function call.
+                */
+#ifndef WIN32
+               if (errno == ECONNREFUSED)
+                       goto cleanup;
+#endif
+               evhttp_error_cb(bufev, what, arg);
+               return;
+       }
+
+       /* Check if the connection completed */
+       if (getsockopt(evcon->fd, SOL_SOCKET, SO_ERROR, (void*)&error,
+                      &errsz) == -1) {
+               event_debug(("%s: getsockopt for \"%s:%d\" on %d",
+                       __func__, evcon->address, evcon->port, evcon->fd));
+               goto cleanup;
+       }
+
+       if (error) {
+               event_debug(("%s: connect failed for \"%s:%d\" on %d: %s",
+                   __func__, evcon->address, evcon->port, evcon->fd,
+                       evutil_socket_error_to_string(error)));
+               goto cleanup;
+       }
+
+       /* We are connected to the server now */
+       event_debug(("%s: connected to \"%s:%d\" on %d\n",
+                       __func__, evcon->address, evcon->port, evcon->fd));
+
+       /* Reset the retry count as we were successful in connecting */
+       evcon->retry_cnt = 0;
+       evcon->state = EVCON_IDLE;
+
+       /* reset the bufferevent cbs */
+       bufferevent_setcb(evcon->bufev,
+           evhttp_read_cb,
+           evhttp_write_cb,
+           evhttp_error_cb,
+           evcon);
+
+       if (evcon->timeout == -1)
+               bufferevent_settimeout(evcon->bufev,
+                   HTTP_READ_TIMEOUT, HTTP_WRITE_TIMEOUT);
+       else {
+               struct timeval tv;
+               tv.tv_sec = evcon->timeout;
+               tv.tv_usec = 0;
+               bufferevent_set_timeouts(evcon->bufev, &tv, &tv);
+       }
+
+       /* try to start requests that have queued up on this connection */
+       evhttp_request_dispatch(evcon);
+       return;
+
+ cleanup:
+       evhttp_connection_cb_cleanup(evcon);
+}
+
+/*
+ * Check if we got a valid response code.
+ */
+
+static int
+evhttp_valid_response_code(int code)
+{
+       if (code == 0)
+               return (0);
+
+       return (1);
+}
+
+static int
+evhttp_parse_http_version(const char *version, struct evhttp_request *req)
+{
+       int major, minor;
+       char ch;
+       int n = sscanf(version, "HTTP/%d.%d%c", &major, &minor, &ch);
+       if (n != 2 || major > 1) {
+               event_debug(("%s: bad version %s on message %p from %s",
+                       __func__, version, req, req->remote_host));
+               return (-1);
+       }
+       req->major = major;
+       req->minor = minor;
+       return (0);
+}
+
+/* Parses the status line of a web server */
+
+static int
+evhttp_parse_response_line(struct evhttp_request *req, char *line)
+{
+       char *protocol;
+       char *number;
+       const char *readable = "";
+
+       protocol = strsep(&line, " ");
+       if (line == NULL)
+               return (-1);
+       number = strsep(&line, " ");
+       if (line != NULL)
+               readable = line;
+
+       if (evhttp_parse_http_version(protocol, req) < 0)
+               return (-1);
+
+       req->response_code = atoi(number);
+       if (!evhttp_valid_response_code(req->response_code)) {
+               event_debug(("%s: bad response code \"%s\"",
+                       __func__, number));
+               return (-1);
+       }
+
+       if ((req->response_code_line = mm_strdup(readable)) == NULL) {
+               event_warn("%s: strdup", __func__);
+               return (-1);
+       }
+
+       return (0);
+}
+
+/* Parse the first line of a HTTP request */
+
+static int
+evhttp_parse_request_line(struct evhttp_request *req, char *line)
+{
+       char *method;
+       char *uri;
+       char *version;
+       const char *hostname;
+       const char *scheme;
+
+       /* Parse the request line */
+       method = strsep(&line, " ");
+       if (line == NULL)
+               return (-1);
+       uri = strsep(&line, " ");
+       if (line == NULL)
+               return (-1);
+       version = strsep(&line, " ");
+       if (line != NULL)
+               return (-1);
+
+       /* First line */
+       if (strcmp(method, "GET") == 0) {
+               req->type = EVHTTP_REQ_GET;
+       } else if (strcmp(method, "POST") == 0) {
+               req->type = EVHTTP_REQ_POST;
+       } else if (strcmp(method, "HEAD") == 0) {
+               req->type = EVHTTP_REQ_HEAD;
+       } else if (strcmp(method, "PUT") == 0) {
+               req->type = EVHTTP_REQ_PUT;
+       } else if (strcmp(method, "DELETE") == 0) {
+               req->type = EVHTTP_REQ_DELETE;
+       } else if (strcmp(method, "OPTIONS") == 0) {
+               req->type = EVHTTP_REQ_OPTIONS;
+       } else if (strcmp(method, "TRACE") == 0) {
+               req->type = EVHTTP_REQ_TRACE;
+       } else if (strcmp(method, "PATCH") == 0) {
+               req->type = EVHTTP_REQ_PATCH;
+       } else {
+               req->type = _EVHTTP_REQ_UNKNOWN;
+               event_debug(("%s: bad method %s on request %p from %s",
+                       __func__, method, req, req->remote_host));
+               /* No error yet; we'll give a better error later when
+                * we see that req->type is unsupported. */
+       }
+
+       if (evhttp_parse_http_version(version, req) < 0)
+               return (-1);
+
+       if ((req->uri = mm_strdup(uri)) == NULL) {
+               event_debug(("%s: mm_strdup", __func__));
+               return (-1);
+       }
+
+       if ((req->uri_elems = evhttp_uri_parse_with_flags(req->uri,
+                   EVHTTP_URI_NONCONFORMANT)) == NULL) {
+               return -1;
+       }
+
+       /* If we have an absolute-URI, check to see if it is an http request
+          for a known vhost or server alias. If we don't know about this
+          host, we consider it a proxy request. */
+       scheme = evhttp_uri_get_scheme(req->uri_elems);
+       hostname = evhttp_uri_get_host(req->uri_elems);
+       if (scheme && (!evutil_ascii_strcasecmp(scheme, "http") ||
+                      !evutil_ascii_strcasecmp(scheme, "https")) &&
+           hostname &&
+           !evhttp_find_vhost(req->evcon->http_server, NULL, hostname))
+               req->flags |= EVHTTP_PROXY_REQUEST;
+
+       return (0);
+}
+
+const char *
+evhttp_find_header(const struct evkeyvalq *headers, const char *key)
+{
+       struct evkeyval *header;
+
+       TAILQ_FOREACH(header, headers, next) {
+               if (evutil_ascii_strcasecmp(header->key, key) == 0)
+                       return (header->value);
+       }
+
+       return (NULL);
+}
+
+void
+evhttp_clear_headers(struct evkeyvalq *headers)
+{
+       struct evkeyval *header;
+
+       for (header = TAILQ_FIRST(headers);
+           header != NULL;
+           header = TAILQ_FIRST(headers)) {
+               TAILQ_REMOVE(headers, header, next);
+               mm_free(header->key);
+               mm_free(header->value);
+               mm_free(header);
+       }
+}
+
+/*
+ * Returns 0,  if the header was successfully removed.
+ * Returns -1, if the header could not be found.
+ */
+
+int
+evhttp_remove_header(struct evkeyvalq *headers, const char *key)
+{
+       struct evkeyval *header;
+
+       TAILQ_FOREACH(header, headers, next) {
+               if (evutil_ascii_strcasecmp(header->key, key) == 0)
+                       break;
+       }
+
+       if (header == NULL)
+               return (-1);
+
+       /* Free and remove the header that we found */
+       TAILQ_REMOVE(headers, header, next);
+       mm_free(header->key);
+       mm_free(header->value);
+       mm_free(header);
+
+       return (0);
+}
+
+static int
+evhttp_header_is_valid_value(const char *value)
+{
+       const char *p = value;
+
+       while ((p = strpbrk(p, "\r\n")) != NULL) {
+               /* we really expect only one new line */
+               p += strspn(p, "\r\n");
+               /* we expect a space or tab for continuation */
+               if (*p != ' ' && *p != '\t')
+                       return (0);
+       }
+       return (1);
+}
+
+int
+evhttp_add_header(struct evkeyvalq *headers,
+    const char *key, const char *value)
+{
+       event_debug(("%s: key: %s val: %s\n", __func__, key, value));
+
+       if (strchr(key, '\r') != NULL || strchr(key, '\n') != NULL) {
+               /* drop illegal headers */
+               event_debug(("%s: dropping illegal header key\n", __func__));
+               return (-1);
+       }
+
+       if (!evhttp_header_is_valid_value(value)) {
+               event_debug(("%s: dropping illegal header value\n", __func__));
+               return (-1);
+       }
+
+       return (evhttp_add_header_internal(headers, key, value));
+}
+
+static int
+evhttp_add_header_internal(struct evkeyvalq *headers,
+    const char *key, const char *value)
+{
+       struct evkeyval *header = mm_calloc(1, sizeof(struct evkeyval));
+       if (header == NULL) {
+               event_warn("%s: calloc", __func__);
+               return (-1);
+       }
+       if ((header->key = mm_strdup(key)) == NULL) {
+               mm_free(header);
+               event_warn("%s: strdup", __func__);
+               return (-1);
+       }
+       if ((header->value = mm_strdup(value)) == NULL) {
+               mm_free(header->key);
+               mm_free(header);
+               event_warn("%s: strdup", __func__);
+               return (-1);
+       }
+
+       TAILQ_INSERT_TAIL(headers, header, next);
+
+       return (0);
+}
+
+/*
+ * Parses header lines from a request or a response into the specified
+ * request object given an event buffer.
+ *
+ * Returns
+ *   DATA_CORRUPTED      on error
+ *   MORE_DATA_EXPECTED  when we need to read more headers
+ *   ALL_DATA_READ       when all headers have been read.
+ */
+
+enum message_read_status
+evhttp_parse_firstline(struct evhttp_request *req, struct evbuffer *buffer)
+{
+       char *line;
+       enum message_read_status status = ALL_DATA_READ;
+
+       size_t line_length;
+       /* XXX try */
+       line = evbuffer_readln(buffer, &line_length, EVBUFFER_EOL_CRLF);
+       if (line == NULL) {
+               if (req->evcon != NULL &&
+                   evbuffer_get_length(buffer) > req->evcon->max_headers_size)
+                       return (DATA_TOO_LONG);
+               else
+                       return (MORE_DATA_EXPECTED);
+       }
+
+       if (req->evcon != NULL &&
+           line_length > req->evcon->max_headers_size) {
+               mm_free(line);
+               return (DATA_TOO_LONG);
+       }
+
+       req->headers_size = line_length;
+
+       switch (req->kind) {
+       case EVHTTP_REQUEST:
+               if (evhttp_parse_request_line(req, line) == -1)
+                       status = DATA_CORRUPTED;
+               break;
+       case EVHTTP_RESPONSE:
+               if (evhttp_parse_response_line(req, line) == -1)
+                       status = DATA_CORRUPTED;
+               break;
+       default:
+               status = DATA_CORRUPTED;
+       }
+
+       mm_free(line);
+       return (status);
+}
+
+static int
+evhttp_append_to_last_header(struct evkeyvalq *headers, const char *line)
+{
+       struct evkeyval *header = TAILQ_LAST(headers, evkeyvalq);
+       char *newval;
+       size_t old_len, line_len;
+
+       if (header == NULL)
+               return (-1);
+
+       old_len = strlen(header->value);
+       line_len = strlen(line);
+
+       newval = mm_realloc(header->value, old_len + line_len + 1);
+       if (newval == NULL)
+               return (-1);
+
+       memcpy(newval + old_len, line, line_len + 1);
+       header->value = newval;
+
+       return (0);
+}
+
+enum message_read_status
+evhttp_parse_headers(struct evhttp_request *req, struct evbuffer* buffer)
+{
+       enum message_read_status errcode = DATA_CORRUPTED;
+       char *line;
+       enum message_read_status status = MORE_DATA_EXPECTED;
+
+       struct evkeyvalq* headers = req->input_headers;
+       size_t line_length;
+       while ((line = evbuffer_readln(buffer, &line_length, EVBUFFER_EOL_CRLF))
+              != NULL) {
+               char *skey, *svalue;
+
+               req->headers_size += line_length;
+
+               if (req->evcon != NULL &&
+                   req->headers_size > req->evcon->max_headers_size) {
+                       errcode = DATA_TOO_LONG;
+                       goto error;
+               }
+
+               if (*line == '\0') { /* Last header - Done */
+                       status = ALL_DATA_READ;
+                       mm_free(line);
+                       break;
+               }
+
+               /* Check if this is a continuation line */
+               if (*line == ' ' || *line == '\t') {
+                       if (evhttp_append_to_last_header(headers, line) == -1)
+                               goto error;
+                       mm_free(line);
+                       continue;
+               }
+
+               /* Processing of header lines */
+               svalue = line;
+               skey = strsep(&svalue, ":");
+               if (svalue == NULL)
+                       goto error;
+
+               svalue += strspn(svalue, " ");
+
+               if (evhttp_add_header(headers, skey, svalue) == -1)
+                       goto error;
+
+               mm_free(line);
+       }
+
+       if (status == MORE_DATA_EXPECTED) {
+               if (req->evcon != NULL &&
+               req->headers_size + evbuffer_get_length(buffer) > req->evcon->max_headers_size)
+                       return (DATA_TOO_LONG);
+       }
+
+       return (status);
+
+ error:
+       mm_free(line);
+       return (errcode);
+}
+
+static int
+evhttp_get_body_length(struct evhttp_request *req)
+{
+       struct evkeyvalq *headers = req->input_headers;
+       const char *content_length;
+       const char *connection;
+
+       content_length = evhttp_find_header(headers, "Content-Length");
+       connection = evhttp_find_header(headers, "Connection");
+
+       if (content_length == NULL && connection == NULL)
+               req->ntoread = -1;
+       else if (content_length == NULL &&
+           evutil_ascii_strcasecmp(connection, "Close") != 0) {
+               /* Bad combination, we don't know when it will end */
+               event_warnx("%s: we got no content length, but the "
+                   "server wants to keep the connection open: %s.",
+                   __func__, connection);
+               return (-1);
+       } else if (content_length == NULL) {
+               req->ntoread = -1;
+       } else {
+               char *endp;
+               ev_int64_t ntoread = evutil_strtoll(content_length, &endp, 10);
+               if (*content_length == '\0' || *endp != '\0' || ntoread < 0) {
+                       event_debug(("%s: illegal content length: %s",
+                               __func__, content_length));
+                       return (-1);
+               }
+               req->ntoread = ntoread;
+       }
+
+       event_debug(("%s: bytes to read: "EV_I64_FMT" (in buffer "EV_SIZE_FMT")\n",
+               __func__, EV_I64_ARG(req->ntoread),
+               EV_SIZE_ARG(evbuffer_get_length(bufferevent_get_input(req->evcon->bufev)))));
+
+       return (0);
+}
+
+static int
+evhttp_method_may_have_body(enum evhttp_cmd_type type)
+{
+       switch (type) {
+       case EVHTTP_REQ_POST:
+       case EVHTTP_REQ_PUT:
+       case EVHTTP_REQ_PATCH:
+               return 1;
+       case EVHTTP_REQ_TRACE:
+               return 0;
+       /* XXX May any of the below methods have a body? */
+       case EVHTTP_REQ_GET:
+       case EVHTTP_REQ_HEAD:
+       case EVHTTP_REQ_DELETE:
+       case EVHTTP_REQ_OPTIONS:
+       case EVHTTP_REQ_CONNECT:
+               return 0;
+       default:
+               return 0;
+       }
+}
+
+static void
+evhttp_get_body(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+       const char *xfer_enc;
+
+       /* If this is a request without a body, then we are done */
+       if (req->kind == EVHTTP_REQUEST &&
+           !evhttp_method_may_have_body(req->type)) {
+               evhttp_connection_done(evcon);
+               return;
+       }
+       evcon->state = EVCON_READING_BODY;
+       xfer_enc = evhttp_find_header(req->input_headers, "Transfer-Encoding");
+       if (xfer_enc != NULL && evutil_ascii_strcasecmp(xfer_enc, "chunked") == 0) {
+               req->chunked = 1;
+               req->ntoread = -1;
+       } else {
+               if (evhttp_get_body_length(req) == -1) {
+                       evhttp_connection_fail(evcon,
+                           EVCON_HTTP_INVALID_HEADER);
+                       return;
+               }
+               if (req->kind == EVHTTP_REQUEST && req->ntoread < 1) {
+                       /* An incoming request with no content-length and no
+                        * transfer-encoding has no body. */
+                       evhttp_connection_done(evcon);
+                       return;
+               }
+       }
+
+       /* Should we send a 100 Continue status line? */
+       if (req->kind == EVHTTP_REQUEST && REQ_VERSION_ATLEAST(req, 1, 1)) {
+               const char *expect;
+
+               expect = evhttp_find_header(req->input_headers, "Expect");
+               if (expect) {
+                       if (!evutil_ascii_strcasecmp(expect, "100-continue")) {
+                               /* XXX It would be nice to do some sanity
+                                  checking here. Does the resource exist?
+                                  Should the resource accept post requests? If
+                                  no, we should respond with an error. For
+                                  now, just optimistically tell the client to
+                                  send their message body. */
+                               if (req->ntoread > 0) {
+                                       /* ntoread is ev_int64_t, max_body_size is ev_uint64_t */ 
+                                       if ((req->evcon->max_body_size <= EV_INT64_MAX) && (ev_uint64_t)req->ntoread > req->evcon->max_body_size) {
+                                               evhttp_send_error(req, HTTP_ENTITYTOOLARGE, NULL);
+                                               return;
+                                       }
+                               }
+                               if (!evbuffer_get_length(bufferevent_get_input(evcon->bufev)))
+                                       evhttp_send_continue(evcon, req);
+                       } else {
+                               evhttp_send_error(req, HTTP_EXPECTATIONFAILED,
+                                       NULL);
+                               return;
+                       }
+               }
+       }
+
+       evhttp_read_body(evcon, req);
+       /* note the request may have been freed in evhttp_read_body */
+}
+
+static void
+evhttp_read_firstline(struct evhttp_connection *evcon,
+                     struct evhttp_request *req)
+{
+       enum message_read_status res;
+
+       res = evhttp_parse_firstline(req, bufferevent_get_input(evcon->bufev));
+       if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
+               /* Error while reading, terminate */
+               event_debug(("%s: bad header lines on %d\n",
+                       __func__, evcon->fd));
+               evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+               return;
+       } else if (res == MORE_DATA_EXPECTED) {
+               /* Need more header lines */
+               return;
+       }
+
+       evcon->state = EVCON_READING_HEADERS;
+       evhttp_read_header(evcon, req);
+}
+
+static void
+evhttp_read_header(struct evhttp_connection *evcon,
+                  struct evhttp_request *req)
+{
+       enum message_read_status res;
+       evutil_socket_t fd = evcon->fd;
+
+       res = evhttp_parse_headers(req, bufferevent_get_input(evcon->bufev));
+       if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
+               /* Error while reading, terminate */
+               event_debug(("%s: bad header lines on %d\n", __func__, fd));
+               evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+               return;
+       } else if (res == MORE_DATA_EXPECTED) {
+               /* Need more header lines */
+               return;
+       }
+
+       /* Disable reading for now */
+       bufferevent_disable(evcon->bufev, EV_READ);
+
+       /* Done reading headers, do the real work */
+       switch (req->kind) {
+       case EVHTTP_REQUEST:
+               event_debug(("%s: checking for post data on %d\n",
+                               __func__, fd));
+               evhttp_get_body(evcon, req);
+               /* note the request may have been freed in evhttp_get_body */
+               break;
+
+       case EVHTTP_RESPONSE:
+               /* Start over if we got a 100 Continue response. */
+               if (req->response_code == 100) {
+                       evhttp_start_read(evcon);
+                       return;
+               }
+               if (!evhttp_response_needs_body(req)) {
+                       event_debug(("%s: skipping body for code %d\n",
+                                       __func__, req->response_code));
+                       evhttp_connection_done(evcon);
+               } else {
+                       event_debug(("%s: start of read body for %s on %d\n",
+                               __func__, req->remote_host, fd));
+                       evhttp_get_body(evcon, req);
+                       /* note the request may have been freed in
+                        * evhttp_get_body */
+               }
+               break;
+
+       default:
+               event_warnx("%s: bad header on %d", __func__, fd);
+               evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+               break;
+       }
+       /* request may have been freed above */
+}
+
+/*
+ * Creates a TCP connection to the specified port and executes a callback
+ * when finished.  Failure or success is indicate by the passed connection
+ * object.
+ *
+ * Although this interface accepts a hostname, it is intended to take
+ * only numeric hostnames so that non-blocking DNS resolution can
+ * happen elsewhere.
+ */
+
+struct evhttp_connection *
+evhttp_connection_new(const char *address, unsigned short port)
+{
+       return (evhttp_connection_base_new(NULL, NULL, address, port));
+}
+
+struct evhttp_connection *
+evhttp_connection_base_new(struct event_base *base, struct evdns_base *dnsbase,
+    const char *address, unsigned short port)
+{
+       struct evhttp_connection *evcon = NULL;
+
+       event_debug(("Attempting connection to %s:%d\n", address, port));
+
+       if ((evcon = mm_calloc(1, sizeof(struct evhttp_connection))) == NULL) {
+               event_warn("%s: calloc failed", __func__);
+               goto error;
+       }
+
+       evcon->fd = -1;
+       evcon->port = port;
+
+       evcon->max_headers_size = EV_SIZE_MAX;
+       evcon->max_body_size = EV_SIZE_MAX;
+
+       evcon->timeout = -1;
+       evcon->retry_cnt = evcon->retry_max = 0;
+
+       if ((evcon->address = mm_strdup(address)) == NULL) {
+               event_warn("%s: strdup failed", __func__);
+               goto error;
+       }
+
+       if ((evcon->bufev = bufferevent_new(-1,
+                   evhttp_read_cb,
+                   evhttp_write_cb,
+                   evhttp_error_cb, evcon)) == NULL) {
+               event_warn("%s: bufferevent_new failed", __func__);
+               goto error;
+       }
+
+       evcon->state = EVCON_DISCONNECTED;
+       TAILQ_INIT(&evcon->requests);
+
+       if (base != NULL) {
+               evcon->base = base;
+               bufferevent_base_set(base, evcon->bufev);
+       }
+
+
+       event_deferred_cb_init(&evcon->read_more_deferred_cb,
+           evhttp_deferred_read_cb, evcon);
+
+       evcon->dns_base = dnsbase;
+
+       return (evcon);
+
+ error:
+       if (evcon != NULL)
+               evhttp_connection_free(evcon);
+       return (NULL);
+}
+
+struct bufferevent *
+evhttp_connection_get_bufferevent(struct evhttp_connection *evcon)
+{
+       return evcon->bufev;
+}
+
+void
+evhttp_connection_set_base(struct evhttp_connection *evcon,
+    struct event_base *base)
+{
+       EVUTIL_ASSERT(evcon->base == NULL);
+       EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
+       evcon->base = base;
+       bufferevent_base_set(base, evcon->bufev);
+}
+
+void
+evhttp_connection_set_timeout(struct evhttp_connection *evcon,
+    int timeout_in_secs)
+{
+       evcon->timeout = timeout_in_secs;
+
+       if (evcon->timeout == -1)
+               bufferevent_settimeout(evcon->bufev,
+                   HTTP_READ_TIMEOUT, HTTP_WRITE_TIMEOUT);
+       else
+               bufferevent_settimeout(evcon->bufev,
+                   evcon->timeout, evcon->timeout);
+}
+
+void
+evhttp_connection_set_retries(struct evhttp_connection *evcon,
+    int retry_max)
+{
+       evcon->retry_max = retry_max;
+}
+
+void
+evhttp_connection_set_closecb(struct evhttp_connection *evcon,
+    void (*cb)(struct evhttp_connection *, void *), void *cbarg)
+{
+       evcon->closecb = cb;
+       evcon->closecb_arg = cbarg;
+}
+
+void
+evhttp_connection_get_peer(struct evhttp_connection *evcon,
+    char **address, ev_uint16_t *port)
+{
+       *address = evcon->address;
+       *port = evcon->port;
+}
+
+int
+evhttp_connection_connect(struct evhttp_connection *evcon)
+{
+       if (evcon->state == EVCON_CONNECTING)
+               return (0);
+
+       evhttp_connection_reset(evcon);
+
+       EVUTIL_ASSERT(!(evcon->flags & EVHTTP_CON_INCOMING));
+       evcon->flags |= EVHTTP_CON_OUTGOING;
+
+       evcon->fd = bind_socket(
+               evcon->bind_address, evcon->bind_port, 0 /*reuse*/);
+       if (evcon->fd == -1) {
+               event_debug(("%s: failed to bind to \"%s\"",
+                       __func__, evcon->bind_address));
+               return (-1);
+       }
+
+       /* Set up a callback for successful connection setup */
+       bufferevent_setfd(evcon->bufev, evcon->fd);
+       bufferevent_setcb(evcon->bufev,
+           NULL /* evhttp_read_cb */,
+           NULL /* evhttp_write_cb */,
+           evhttp_connection_cb,
+           evcon);
+       bufferevent_settimeout(evcon->bufev, 0,
+           evcon->timeout != -1 ? evcon->timeout : HTTP_CONNECT_TIMEOUT);
+       /* make sure that we get a write callback */
+       bufferevent_enable(evcon->bufev, EV_WRITE);
+
+       if (bufferevent_socket_connect_hostname(evcon->bufev, evcon->dns_base,
+               AF_UNSPEC, evcon->address, evcon->port) < 0) {
+               event_sock_warn(evcon->fd, "%s: connection to \"%s\" failed",
+                   __func__, evcon->address);
+               /* some operating systems return ECONNREFUSED immediately
+                * when connecting to a local address.  the cleanup is going
+                * to reschedule this function call.
+                */
+               evhttp_connection_cb_cleanup(evcon);
+               return (0);
+       }
+
+       evcon->state = EVCON_CONNECTING;
+
+       return (0);
+}
+
+/*
+ * Starts an HTTP request on the provided evhttp_connection object.
+ * If the connection object is not connected to the web server already,
+ * this will start the connection.
+ */
+
+int
+evhttp_make_request(struct evhttp_connection *evcon,
+    struct evhttp_request *req,
+    enum evhttp_cmd_type type, const char *uri)
+{
+       /* We are making a request */
+       req->kind = EVHTTP_REQUEST;
+       req->type = type;
+       if (req->uri != NULL)
+               mm_free(req->uri);
+       if ((req->uri = mm_strdup(uri)) == NULL) {
+               event_warn("%s: strdup", __func__);
+               evhttp_request_free(req);
+               return (-1);
+       }
+
+       /* Set the protocol version if it is not supplied */
+       if (!req->major && !req->minor) {
+               req->major = 1;
+               req->minor = 1;
+       }
+
+       EVUTIL_ASSERT(req->evcon == NULL);
+       req->evcon = evcon;
+       EVUTIL_ASSERT(!(req->flags & EVHTTP_REQ_OWN_CONNECTION));
+
+       TAILQ_INSERT_TAIL(&evcon->requests, req, next);
+
+       /* If the connection object is not connected; make it so */
+       if (!evhttp_connected(evcon)) {
+               int res = evhttp_connection_connect(evcon);
+              /* evhttp_connection_fail(), which is called through
+               * evhttp_connection_connect(), assumes that req lies in
+               * evcon->requests.  Thus, enqueue the request in advance and r
+               * it in the error case. */
+              if (res != 0)
+                      TAILQ_REMOVE(&evcon->requests, req, next);
+
+               return res;
+       }
+
+       /*
+        * If it's connected already and we are the first in the queue,
+        * then we can dispatch this request immediately.  Otherwise, it
+        * will be dispatched once the pending requests are completed.
+        */
+       if (TAILQ_FIRST(&evcon->requests) == req)
+               evhttp_request_dispatch(evcon);
+
+       return (0);
+}
+
+void
+evhttp_cancel_request(struct evhttp_request *req)
+{
+       struct evhttp_connection *evcon = req->evcon;
+       if (evcon != NULL) {
+               /* We need to remove it from the connection */
+               if (TAILQ_FIRST(&evcon->requests) == req) {
+                       /* it's currently being worked on, so reset
+                        * the connection.
+                        */
+                       evhttp_connection_fail(evcon,
+                           EVCON_HTTP_REQUEST_CANCEL);
+
+                       /* connection fail freed the request */
+                       return;
+               } else {
+                       /* otherwise, we can just remove it from the
+                        * queue
+                        */
+                       TAILQ_REMOVE(&evcon->requests, req, next);
+               }
+       }
+
+       evhttp_request_free(req);
+}
+
+/*
+ * Reads data from file descriptor into request structure
+ * Request structure needs to be set up correctly.
+ */
+
+void
+evhttp_start_read(struct evhttp_connection *evcon)
+{
+       /* Set up an event to read the headers */
+       bufferevent_disable(evcon->bufev, EV_WRITE);
+       bufferevent_enable(evcon->bufev, EV_READ);
+       evcon->state = EVCON_READING_FIRSTLINE;
+       /* Reset the bufferevent callbacks */
+       bufferevent_setcb(evcon->bufev,
+           evhttp_read_cb,
+           evhttp_write_cb,
+           evhttp_error_cb,
+           evcon);
+
+       /* If there's still data pending, process it next time through the
+        * loop.  Don't do it now; that could get recusive. */
+       if (evbuffer_get_length(bufferevent_get_input(evcon->bufev))) {
+               event_deferred_cb_schedule(get_deferred_queue(evcon),
+                   &evcon->read_more_deferred_cb);
+       }
+}
+
+static void
+evhttp_send_done(struct evhttp_connection *evcon, void *arg)
+{
+       int need_close;
+       struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+       TAILQ_REMOVE(&evcon->requests, req, next);
+
+       need_close =
+           (REQ_VERSION_BEFORE(req, 1, 1) &&
+               !evhttp_is_connection_keepalive(req->input_headers))||
+           evhttp_is_connection_close(req->flags, req->input_headers) ||
+           evhttp_is_connection_close(req->flags, req->output_headers);
+
+       EVUTIL_ASSERT(req->flags & EVHTTP_REQ_OWN_CONNECTION);
+       evhttp_request_free(req);
+
+       if (need_close) {
+               evhttp_connection_free(evcon);
+               return;
+       }
+
+       /* we have a persistent connection; try to accept another request. */
+       if (evhttp_associate_new_request_with_connection(evcon) == -1) {
+               evhttp_connection_free(evcon);
+       }
+}
+
+/*
+ * Returns an error page.
+ */
+
+void
+evhttp_send_error(struct evhttp_request *req, int error, const char *reason)
+{
+
+#define ERR_FORMAT "<HTML><HEAD>\n" \
+           "<TITLE>%d %s</TITLE>\n" \
+           "</HEAD><BODY>\n" \
+           "<H1>%s</H1>\n" \
+           "</BODY></HTML>\n"
+
+       struct evbuffer *buf = evbuffer_new();
+       if (buf == NULL) {
+               /* if we cannot allocate memory; we just drop the connection */
+               evhttp_connection_free(req->evcon);
+               return;
+       }
+       if (reason == NULL) {
+               reason = evhttp_response_phrase_internal(error);
+       }
+
+       evhttp_response_code(req, error, reason);
+
+       evbuffer_add_printf(buf, ERR_FORMAT, error, reason, reason);
+
+       evhttp_send_page(req, buf);
+
+       evbuffer_free(buf);
+#undef ERR_FORMAT
+}
+
+/* Requires that headers and response code are already set up */
+
+static inline void
+evhttp_send(struct evhttp_request *req, struct evbuffer *databuf)
+{
+       struct evhttp_connection *evcon = req->evcon;
+
+       if (evcon == NULL) {
+               evhttp_request_free(req);
+               return;
+       }
+
+       EVUTIL_ASSERT(TAILQ_FIRST(&evcon->requests) == req);
+
+       /* we expect no more calls form the user on this request */
+       req->userdone = 1;
+
+       /* xxx: not sure if we really should expose the data buffer this way */
+       if (databuf != NULL)
+               evbuffer_add_buffer(req->output_buffer, databuf);
+
+       /* Adds headers to the response */
+       evhttp_make_header(evcon, req);
+
+       evhttp_write_buffer(evcon, evhttp_send_done, NULL);
+}
+
+void
+evhttp_send_reply(struct evhttp_request *req, int code, const char *reason,
+    struct evbuffer *databuf)
+{
+       evhttp_response_code(req, code, reason);
+
+       evhttp_send(req, databuf);
+}
+
+void
+evhttp_send_reply_start(struct evhttp_request *req, int code,
+    const char *reason)
+{
+       evhttp_response_code(req, code, reason);
+       if (evhttp_find_header(req->output_headers, "Content-Length") == NULL &&
+           REQ_VERSION_ATLEAST(req, 1, 1) &&
+           evhttp_response_needs_body(req)) {
+               /*
+                * prefer HTTP/1.1 chunked encoding to closing the connection;
+                * note RFC 2616 section 4.4 forbids it with Content-Length:
+                * and it's not necessary then anyway.
+                */
+               evhttp_add_header(req->output_headers, "Transfer-Encoding",
+                   "chunked");
+               req->chunked = 1;
+       } else {
+               req->chunked = 0;
+       }
+       evhttp_make_header(req->evcon, req);
+       evhttp_write_buffer(req->evcon, NULL, NULL);
+}
+
+void
+evhttp_send_reply_chunk(struct evhttp_request *req, struct evbuffer *databuf)
+{
+       struct evhttp_connection *evcon = req->evcon;
+       struct evbuffer *output;
+
+       if (evcon == NULL)
+               return;
+
+       output = bufferevent_get_output(evcon->bufev);
+
+       if (evbuffer_get_length(databuf) == 0)
+               return;
+       if (!evhttp_response_needs_body(req))
+               return;
+       if (req->chunked) {
+               evbuffer_add_printf(output, "%x\r\n",
+                                   (unsigned)evbuffer_get_length(databuf));
+       }
+       evbuffer_add_buffer(output, databuf);
+       if (req->chunked) {
+               evbuffer_add(output, "\r\n", 2);
+       }
+       evhttp_write_buffer(evcon, NULL, NULL);
+}
+
+void
+evhttp_send_reply_end(struct evhttp_request *req)
+{
+       struct evhttp_connection *evcon = req->evcon;
+       struct evbuffer *output;
+
+       if (evcon == NULL) {
+               evhttp_request_free(req);
+               return;
+       }
+
+       output = bufferevent_get_output(evcon->bufev);
+
+       /* we expect no more calls form the user on this request */
+       req->userdone = 1;
+
+       if (req->chunked) {
+               evbuffer_add(output, "0\r\n\r\n", 5);
+               evhttp_write_buffer(req->evcon, evhttp_send_done, NULL);
+               req->chunked = 0;
+       } else if (evbuffer_get_length(output) == 0) {
+               /* let the connection know that we are done with the request */
+               evhttp_send_done(evcon, NULL);
+       } else {
+               /* make the callback execute after all data has been written */
+               evcon->cb = evhttp_send_done;
+               evcon->cb_arg = NULL;
+       }
+}
+
+static const char *informational_phrases[] = {
+       /* 100 */ "Continue",
+       /* 101 */ "Switching Protocols"
+};
+
+static const char *success_phrases[] = {
+       /* 200 */ "OK",
+       /* 201 */ "Created",
+       /* 202 */ "Accepted",
+       /* 203 */ "Non-Authoritative Information",
+       /* 204 */ "No Content",
+       /* 205 */ "Reset Content",
+       /* 206 */ "Partial Content"
+};
+
+static const char *redirection_phrases[] = {
+       /* 300 */ "Multiple Choices",
+       /* 301 */ "Moved Permanently",
+       /* 302 */ "Found",
+       /* 303 */ "See Other",
+       /* 304 */ "Not Modified",
+       /* 305 */ "Use Proxy",
+       /* 307 */ "Temporary Redirect"
+};
+
+static const char *client_error_phrases[] = {
+       /* 400 */ "Bad Request",
+       /* 401 */ "Unauthorized",
+       /* 402 */ "Payment Required",
+       /* 403 */ "Forbidden",
+       /* 404 */ "Not Found",
+       /* 405 */ "Method Not Allowed",
+       /* 406 */ "Not Acceptable",
+       /* 407 */ "Proxy Authentication Required",
+       /* 408 */ "Request Time-out",
+       /* 409 */ "Conflict",
+       /* 410 */ "Gone",
+       /* 411 */ "Length Required",
+       /* 412 */ "Precondition Failed",
+       /* 413 */ "Request Entity Too Large",
+       /* 414 */ "Request-URI Too Large",
+       /* 415 */ "Unsupported Media Type",
+       /* 416 */ "Requested range not satisfiable",
+       /* 417 */ "Expectation Failed"
+};
+
+static const char *server_error_phrases[] = {
+       /* 500 */ "Internal Server Error",
+       /* 501 */ "Not Implemented",
+       /* 502 */ "Bad Gateway",
+       /* 503 */ "Service Unavailable",
+       /* 504 */ "Gateway Time-out",
+       /* 505 */ "HTTP Version not supported"
+};
+
+struct response_class {
+       const char *name;
+       size_t num_responses;
+       const char **responses;
+};
+
+#ifndef MEMBERSOF
+#define MEMBERSOF(x) (sizeof(x)/sizeof(x[0]))
+#endif
+
+static const struct response_class response_classes[] = {
+       /* 1xx */ { "Informational", MEMBERSOF(informational_phrases), informational_phrases },
+       /* 2xx */ { "Success", MEMBERSOF(success_phrases), success_phrases },
+       /* 3xx */ { "Redirection", MEMBERSOF(redirection_phrases), redirection_phrases },
+       /* 4xx */ { "Client Error", MEMBERSOF(client_error_phrases), client_error_phrases },
+       /* 5xx */ { "Server Error", MEMBERSOF(server_error_phrases), server_error_phrases }
+};
+
+static const char *
+evhttp_response_phrase_internal(int code)
+{
+       int klass = code / 100 - 1;
+       int subcode = code % 100;
+
+       /* Unknown class - can't do any better here */
+       if (klass < 0 || klass >= (int) MEMBERSOF(response_classes))
+               return "Unknown Status Class";
+
+       /* Unknown sub-code, return class name at least */
+       if (subcode >= (int) response_classes[klass].num_responses)
+               return response_classes[klass].name;
+
+       return response_classes[klass].responses[subcode];
+}
+
+void
+evhttp_response_code(struct evhttp_request *req, int code, const char *reason)
+{
+       req->kind = EVHTTP_RESPONSE;
+       req->response_code = code;
+       if (req->response_code_line != NULL)
+               mm_free(req->response_code_line);
+       if (reason == NULL)
+               reason = evhttp_response_phrase_internal(code);
+       req->response_code_line = mm_strdup(reason);
+       if (req->response_code_line == NULL) {
+               event_warn("%s: strdup", __func__);
+               /* XXX what else can we do? */
+       }
+}
+
+void
+evhttp_send_page(struct evhttp_request *req, struct evbuffer *databuf)
+{
+       if (!req->major || !req->minor) {
+               req->major = 1;
+               req->minor = 1;
+       }
+
+       if (req->kind != EVHTTP_RESPONSE)
+               evhttp_response_code(req, 200, "OK");
+
+       evhttp_clear_headers(req->output_headers);
+       evhttp_add_header(req->output_headers, "Content-Type", "text/html");
+       evhttp_add_header(req->output_headers, "Connection", "close");
+
+       evhttp_send(req, databuf);
+}
+
+static const char uri_chars[256] = {
+       /* 0 */
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 1, 1, 0,
+       1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,
+       /* 64 */
+       0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
+       1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 1,
+       0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
+       1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 1, 0,
+       /* 128 */
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       /* 192 */
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
+};
+
+#define CHAR_IS_UNRESERVED(c)                  \
+       (uri_chars[(unsigned char)(c)])
+
+/*
+ * Helper functions to encode/decode a string for inclusion in a URI.
+ * The returned string must be freed by the caller.
+ */
+char *
+evhttp_uriencode(const char *uri, ev_ssize_t len, int space_as_plus)
+{
+       struct evbuffer *buf = evbuffer_new();
+       const char *p, *end;
+       char *result;
+
+       if (buf == NULL)
+               return (NULL);
+
+       if (len >= 0)
+               end = uri+len;
+       else
+               end = uri+strlen(uri);
+
+       for (p = uri; p < end; p++) {
+               if (CHAR_IS_UNRESERVED(*p)) {
+                       evbuffer_add(buf, p, 1);
+               } else if (*p == ' ' && space_as_plus) {
+                       evbuffer_add(buf, "+", 1);
+               } else {
+                       evbuffer_add_printf(buf, "%%%02X", (unsigned char)(*p));
+               }
+       }
+       evbuffer_add(buf, "", 1); /* NUL-terminator. */
+       result = mm_malloc(evbuffer_get_length(buf));
+       if (!result)
+               return NULL;
+       evbuffer_remove(buf, result, evbuffer_get_length(buf));
+       evbuffer_free(buf);
+
+       return (result);
+}
+
+char *
+evhttp_encode_uri(const char *str)
+{
+       return evhttp_uriencode(str, -1, 0);
+}
+
+/*
+ * @param decode_plus_ctl: if 1, we decode plus into space.  If 0, we don't.
+ *     If -1, when true we transform plus to space only after we've seen
+ *     a ?.  -1 is deprecated.
+ * @return the number of bytes written to 'ret'.
+ */
+static int
+evhttp_decode_uri_internal(
+       const char *uri, size_t length, char *ret, int decode_plus_ctl)
+{
+       char c;
+       int j;
+       int decode_plus = (decode_plus_ctl == 1) ? 1: 0;
+       unsigned i;
+
+       for (i = j = 0; i < length; i++) {
+               c = uri[i];
+               if (c == '?') {
+                       if (decode_plus_ctl < 0)
+                               decode_plus = 1;
+               } else if (c == '+' && decode_plus) {
+                       c = ' ';
+               } else if (c == '%' && EVUTIL_ISXDIGIT(uri[i+1]) &&
+                   EVUTIL_ISXDIGIT(uri[i+2])) {
+                       char tmp[3];
+                       tmp[0] = uri[i+1];
+                       tmp[1] = uri[i+2];
+                       tmp[2] = '\0';
+                       c = (char)strtol(tmp, NULL, 16);
+                       i += 2;
+               }
+               ret[j++] = c;
+       }
+       ret[j] = '\0';
+
+       return (j);
+}
+
+/* deprecated */
+char *
+evhttp_decode_uri(const char *uri)
+{
+       char *ret;
+
+       if ((ret = mm_malloc(strlen(uri) + 1)) == NULL) {
+               event_warn("%s: malloc(%lu)", __func__,
+                         (unsigned long)(strlen(uri) + 1));
+               return (NULL);
+       }
+
+       evhttp_decode_uri_internal(uri, strlen(uri),
+           ret, -1 /*always_decode_plus*/);
+
+       return (ret);
+}
+
+char *
+evhttp_uridecode(const char *uri, int decode_plus, size_t *size_out)
+{
+       char *ret;
+       int n;
+
+       if ((ret = mm_malloc(strlen(uri) + 1)) == NULL) {
+               event_warn("%s: malloc(%lu)", __func__,
+                         (unsigned long)(strlen(uri) + 1));
+               return (NULL);
+       }
+
+       n = evhttp_decode_uri_internal(uri, strlen(uri),
+           ret, !!decode_plus/*always_decode_plus*/);
+
+       if (size_out) {
+               EVUTIL_ASSERT(n >= 0);
+               *size_out = (size_t)n;
+       }
+
+       return (ret);
+}
+
+/*
+ * Helper function to parse out arguments in a query.
+ * The arguments are separated by key and value.
+ */
+
+static int
+evhttp_parse_query_impl(const char *str, struct evkeyvalq *headers,
+    int is_whole_uri)
+{
+       char *line=NULL;
+       char *argument;
+       char *p;
+       const char *query_part;
+       int result = -1;
+       struct evhttp_uri *uri=NULL;
+
+       TAILQ_INIT(headers);
+
+       if (is_whole_uri) {
+               uri = evhttp_uri_parse(str);
+               if (!uri)
+                       goto error;
+               query_part = evhttp_uri_get_query(uri);
+       } else {
+               query_part = str;
+       }
+
+       /* No arguments - we are done */
+       if (!query_part || !strlen(query_part)) {
+               result = 0;
+               goto done;
+       }
+
+       if ((line = mm_strdup(query_part)) == NULL) {
+               event_warn("%s: strdup", __func__);
+               goto error;
+       }
+
+       p = argument = line;
+       while (p != NULL && *p != '\0') {
+               char *key, *value, *decoded_value;
+               argument = strsep(&p, "&");
+
+               value = argument;
+               key = strsep(&value, "=");
+               if (value == NULL || *key == '\0') {
+                       goto error;
+               }
+
+               if ((decoded_value = mm_malloc(strlen(value) + 1)) == NULL) {
+                       event_warn("%s: mm_malloc", __func__);
+                       goto error;
+               }
+               evhttp_decode_uri_internal(value, strlen(value),
+                   decoded_value, 1 /*always_decode_plus*/);
+               event_debug(("Query Param: %s -> %s\n", key, decoded_value));
+               evhttp_add_header_internal(headers, key, decoded_value);
+               mm_free(decoded_value);
+       }
+
+       result = 0;
+       goto done;
+error:
+       evhttp_clear_headers(headers);
+done:
+       if (line)
+               mm_free(line);
+       if (uri)
+               evhttp_uri_free(uri);
+       return result;
+}
+
+int
+evhttp_parse_query(const char *uri, struct evkeyvalq *headers)
+{
+       return evhttp_parse_query_impl(uri, headers, 1);
+}
+int
+evhttp_parse_query_str(const char *uri, struct evkeyvalq *headers)
+{
+       return evhttp_parse_query_impl(uri, headers, 0);
+}
+
+static struct evhttp_cb *
+evhttp_dispatch_callback(struct httpcbq *callbacks, struct evhttp_request *req)
+{
+       struct evhttp_cb *cb;
+       size_t offset = 0;
+       char *translated;
+       const char *path;
+
+       /* Test for different URLs */
+       path = evhttp_uri_get_path(req->uri_elems);
+       offset = strlen(path);
+       if ((translated = mm_malloc(offset + 1)) == NULL)
+               return (NULL);
+       evhttp_decode_uri_internal(path, offset, translated,
+           0 /* decode_plus */);
+
+       TAILQ_FOREACH(cb, callbacks, next) {
+               if (!strcmp(cb->what, translated)) {
+                       mm_free(translated);
+                       return (cb);
+               }
+       }
+
+       mm_free(translated);
+       return (NULL);
+}
+
+
+static int
+prefix_suffix_match(const char *pattern, const char *name, int ignorecase)
+{
+       char c;
+
+       while (1) {
+               switch (c = *pattern++) {
+               case '\0':
+                       return *name == '\0';
+
+               case '*':
+                       while (*name != '\0') {
+                               if (prefix_suffix_match(pattern, name,
+                                       ignorecase))
+                                       return (1);
+                               ++name;
+                       }
+                       return (0);
+               default:
+                       if (c != *name) {
+                               if (!ignorecase ||
+                                   EVUTIL_TOLOWER(c) != EVUTIL_TOLOWER(*name))
+                                       return (0);
+                       }
+                       ++name;
+               }
+       }
+       /* NOTREACHED */
+}
+
+/*
+   Search the vhost hierarchy beginning with http for a server alias
+   matching hostname.  If a match is found, and outhttp is non-null,
+   outhttp is set to the matching http object and 1 is returned.
+*/
+
+static int
+evhttp_find_alias(struct evhttp *http, struct evhttp **outhttp,
+                 const char *hostname)
+{
+       struct evhttp_server_alias *alias;
+       struct evhttp *vhost;
+
+       TAILQ_FOREACH(alias, &http->aliases, next) {
+               /* XXX Do we need to handle IP addresses? */
+               if (!evutil_ascii_strcasecmp(alias->alias, hostname)) {
+                       if (outhttp)
+                               *outhttp = http;
+                       return 1;
+               }
+       }
+
+       /* XXX It might be good to avoid recursion here, but I don't
+          see a way to do that w/o a list. */
+       TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
+               if (evhttp_find_alias(vhost, outhttp, hostname))
+                       return 1;
+       }
+
+       return 0;
+}
+
+/*
+   Attempts to find the best http object to handle a request for a hostname.
+   All aliases for the root http object and vhosts are searched for an exact
+   match. Then, the vhost hierarchy is traversed again for a matching
+   pattern.
+
+   If an alias or vhost is matched, 1 is returned, and outhttp, if non-null,
+   is set with the best matching http object. If there are no matches, the
+   root http object is stored in outhttp and 0 is returned.
+*/
+
+static int
+evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
+                 const char *hostname)
+{
+       struct evhttp *vhost;
+       struct evhttp *oldhttp;
+       int match_found = 0;
+
+       if (evhttp_find_alias(http, outhttp, hostname))
+               return 1;
+
+       do {
+               oldhttp = http;
+               TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
+                       if (prefix_suffix_match(vhost->vhost_pattern,
+                               hostname, 1 /* ignorecase */)) {
+                               http = vhost;
+                               match_found = 1;
+                               break;
+                       }
+               }
+       } while (oldhttp != http);
+
+       if (outhttp)
+               *outhttp = http;
+
+       return match_found;
+}
+
+static void
+evhttp_handle_request(struct evhttp_request *req, void *arg)
+{
+       struct evhttp *http = arg;
+       struct evhttp_cb *cb = NULL;
+       const char *hostname;
+
+       /* we have a new request on which the user needs to take action */
+       req->userdone = 0;
+
+       if (req->type == 0 || req->uri == NULL) {
+               evhttp_send_error(req, HTTP_BADREQUEST, NULL);
+               return;
+       }
+
+       if ((http->allowed_methods & req->type) == 0) {
+               event_debug(("Rejecting disallowed method %x (allowed: %x)\n",
+                       (unsigned)req->type, (unsigned)http->allowed_methods));
+               evhttp_send_error(req, HTTP_NOTIMPLEMENTED, NULL);
+               return;
+       }
+
+       /* handle potential virtual hosts */
+       hostname = evhttp_request_get_host(req);
+       if (hostname != NULL) {
+               evhttp_find_vhost(http, &http, hostname);
+       }
+
+       if ((cb = evhttp_dispatch_callback(&http->callbacks, req)) != NULL) {
+               (*cb->cb)(req, cb->cbarg);
+               return;
+       }
+
+       /* Generic call back */
+       if (http->gencb) {
+               (*http->gencb)(req, http->gencbarg);
+               return;
+       } else {
+               /* We need to send a 404 here */
+#define ERR_FORMAT "<html><head>" \
+                   "<title>404 Not Found</title>" \
+                   "</head><body>" \
+                   "<h1>Not Found</h1>" \
+                   "<p>The requested URL %s was not found on this server.</p>"\
+                   "</body></html>\n"
+
+               char *escaped_html;
+               struct evbuffer *buf;
+
+               if ((escaped_html = evhttp_htmlescape(req->uri)) == NULL) {
+                       evhttp_connection_free(req->evcon);
+                       return;
+               }
+
+               if ((buf = evbuffer_new()) == NULL) {
+                       mm_free(escaped_html);
+                       evhttp_connection_free(req->evcon);
+                       return;
+               }
+
+               evhttp_response_code(req, HTTP_NOTFOUND, "Not Found");
+
+               evbuffer_add_printf(buf, ERR_FORMAT, escaped_html);
+
+               mm_free(escaped_html);
+
+               evhttp_send_page(req, buf);
+
+               evbuffer_free(buf);
+#undef ERR_FORMAT
+       }
+}
+
+/* Listener callback when a connection arrives at a server. */
+static void
+accept_socket_cb(struct evconnlistener *listener, evutil_socket_t nfd, struct sockaddr *peer_sa, int peer_socklen, void *arg)
+{
+       struct evhttp *http = arg;
+
+       evhttp_get_request(http, nfd, peer_sa, peer_socklen);
+}
+
+int
+evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port)
+{
+       struct evhttp_bound_socket *bound =
+               evhttp_bind_socket_with_handle(http, address, port);
+       if (bound == NULL)
+               return (-1);
+       return (0);
+}
+
+struct evhttp_bound_socket *
+evhttp_bind_socket_with_handle(struct evhttp *http, const char *address, ev_uint16_t port)
+{
+       evutil_socket_t fd;
+       struct evhttp_bound_socket *bound;
+
+       if ((fd = bind_socket(address, port, 1 /*reuse*/)) == -1)
+               return (NULL);
+
+       if (listen(fd, 128) == -1) {
+               event_sock_warn(fd, "%s: listen", __func__);
+               evutil_closesocket(fd);
+               return (NULL);
+       }
+
+       bound = evhttp_accept_socket_with_handle(http, fd);
+
+       if (bound != NULL) {
+               event_debug(("Bound to port %d - Awaiting connections ... ",
+                       port));
+               return (bound);
+       }
+
+       return (NULL);
+}
+
+int
+evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd)
+{
+       struct evhttp_bound_socket *bound =
+               evhttp_accept_socket_with_handle(http, fd);
+       if (bound == NULL)
+               return (-1);
+       return (0);
+}
+
+
+struct evhttp_bound_socket *
+evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd)
+{
+       struct evhttp_bound_socket *bound;
+       struct evconnlistener *listener;
+       const int flags =
+           LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC|LEV_OPT_CLOSE_ON_FREE;
+
+       listener = evconnlistener_new(http->base, NULL, NULL,
+           flags,
+           0, /* Backlog is '0' because we already said 'listen' */
+           fd);
+       if (!listener)
+               return (NULL);
+
+       bound = evhttp_bind_listener(http, listener);
+       if (!bound) {
+               evconnlistener_free(listener);
+               return (NULL);
+       }
+       return (bound);
+}
+
+struct evhttp_bound_socket *
+evhttp_bind_listener(struct evhttp *http, struct evconnlistener *listener)
+{
+       struct evhttp_bound_socket *bound;
+
+       bound = mm_malloc(sizeof(struct evhttp_bound_socket));
+       if (bound == NULL)
+               return (NULL);
+
+       bound->listener = listener;
+       TAILQ_INSERT_TAIL(&http->sockets, bound, next);
+
+       evconnlistener_set_cb(listener, accept_socket_cb, http);
+       return bound;
+}
+
+evutil_socket_t
+evhttp_bound_socket_get_fd(struct evhttp_bound_socket *bound)
+{
+       return evconnlistener_get_fd(bound->listener);
+}
+
+struct evconnlistener *
+evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound)
+{
+       return bound->listener;
+}
+
+void
+evhttp_del_accept_socket(struct evhttp *http, struct evhttp_bound_socket *bound)
+{
+       TAILQ_REMOVE(&http->sockets, bound, next);
+       evconnlistener_free(bound->listener);
+       mm_free(bound);
+}
+
+static struct evhttp*
+evhttp_new_object(void)
+{
+       struct evhttp *http = NULL;
+
+       if ((http = mm_calloc(1, sizeof(struct evhttp))) == NULL) {
+               event_warn("%s: calloc", __func__);
+               return (NULL);
+       }
+
+       http->timeout = -1;
+       evhttp_set_max_headers_size(http, EV_SIZE_MAX);
+       evhttp_set_max_body_size(http, EV_SIZE_MAX);
+       evhttp_set_allowed_methods(http,
+           EVHTTP_REQ_GET |
+           EVHTTP_REQ_POST |
+           EVHTTP_REQ_HEAD |
+           EVHTTP_REQ_PUT |
+           EVHTTP_REQ_DELETE);
+
+       TAILQ_INIT(&http->sockets);
+       TAILQ_INIT(&http->callbacks);
+       TAILQ_INIT(&http->connections);
+       TAILQ_INIT(&http->virtualhosts);
+       TAILQ_INIT(&http->aliases);
+
+       return (http);
+}
+
+struct evhttp *
+evhttp_new(struct event_base *base)
+{
+       struct evhttp *http = NULL;
+
+       http = evhttp_new_object();
+       if (http == NULL)
+               return (NULL);
+       http->base = base;
+
+       return (http);
+}
+
+/*
+ * Start a web server on the specified address and port.
+ */
+
+struct evhttp *
+evhttp_start(const char *address, unsigned short port)
+{
+       struct evhttp *http = NULL;
+
+       http = evhttp_new_object();
+       if (http == NULL)
+               return (NULL);
+       if (evhttp_bind_socket(http, address, port) == -1) {
+               mm_free(http);
+               return (NULL);
+       }
+
+       return (http);
+}
+
+void
+evhttp_free(struct evhttp* http)
+{
+       struct evhttp_cb *http_cb;
+       struct evhttp_connection *evcon;
+       struct evhttp_bound_socket *bound;
+       struct evhttp* vhost;
+       struct evhttp_server_alias *alias;
+
+       /* Remove the accepting part */
+       while ((bound = TAILQ_FIRST(&http->sockets)) != NULL) {
+               TAILQ_REMOVE(&http->sockets, bound, next);
+
+               evconnlistener_free(bound->listener);
+
+               mm_free(bound);
+       }
+
+       while ((evcon = TAILQ_FIRST(&http->connections)) != NULL) {
+               /* evhttp_connection_free removes the connection */
+               evhttp_connection_free(evcon);
+       }
+
+       while ((http_cb = TAILQ_FIRST(&http->callbacks)) != NULL) {
+               TAILQ_REMOVE(&http->callbacks, http_cb, next);
+               mm_free(http_cb->what);
+               mm_free(http_cb);
+       }
+
+       while ((vhost = TAILQ_FIRST(&http->virtualhosts)) != NULL) {
+               TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
+
+               evhttp_free(vhost);
+       }
+
+       if (http->vhost_pattern != NULL)
+               mm_free(http->vhost_pattern);
+
+       while ((alias = TAILQ_FIRST(&http->aliases)) != NULL) {
+               TAILQ_REMOVE(&http->aliases, alias, next);
+               mm_free(alias->alias);
+               mm_free(alias);
+       }
+
+       mm_free(http);
+}
+
+int
+evhttp_add_virtual_host(struct evhttp* http, const char *pattern,
+    struct evhttp* vhost)
+{
+       /* a vhost can only be a vhost once and should not have bound sockets */
+       if (vhost->vhost_pattern != NULL ||
+           TAILQ_FIRST(&vhost->sockets) != NULL)
+               return (-1);
+
+       vhost->vhost_pattern = mm_strdup(pattern);
+       if (vhost->vhost_pattern == NULL)
+               return (-1);
+
+       TAILQ_INSERT_TAIL(&http->virtualhosts, vhost, next_vhost);
+
+       return (0);
+}
+
+int
+evhttp_remove_virtual_host(struct evhttp* http, struct evhttp* vhost)
+{
+       if (vhost->vhost_pattern == NULL)
+               return (-1);
+
+       TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
+
+       mm_free(vhost->vhost_pattern);
+       vhost->vhost_pattern = NULL;
+
+       return (0);
+}
+
+int
+evhttp_add_server_alias(struct evhttp *http, const char *alias)
+{
+       struct evhttp_server_alias *evalias;
+
+       evalias = mm_calloc(1, sizeof(*evalias));
+       if (!evalias)
+               return -1;
+
+       evalias->alias = mm_strdup(alias);
+       if (!evalias->alias) {
+               mm_free(evalias);
+               return -1;
+       }
+
+       TAILQ_INSERT_TAIL(&http->aliases, evalias, next);
+
+       return 0;
+}
+
+int
+evhttp_remove_server_alias(struct evhttp *http, const char *alias)
+{
+       struct evhttp_server_alias *evalias;
+
+       TAILQ_FOREACH(evalias, &http->aliases, next) {
+               if (evutil_ascii_strcasecmp(evalias->alias, alias) == 0) {
+                       TAILQ_REMOVE(&http->aliases, evalias, next);
+                       mm_free(evalias->alias);
+                       mm_free(evalias);
+                       return 0;
+               }
+       }
+
+       return -1;
+}
+
+void
+evhttp_set_timeout(struct evhttp* http, int timeout_in_secs)
+{
+       http->timeout = timeout_in_secs;
+}
+
+void
+evhttp_set_max_headers_size(struct evhttp* http, ev_ssize_t max_headers_size)
+{
+       if (max_headers_size < 0)
+               http->default_max_headers_size = EV_SIZE_MAX;
+       else
+               http->default_max_headers_size = max_headers_size;
+}
+
+void
+evhttp_set_max_body_size(struct evhttp* http, ev_ssize_t max_body_size)
+{
+       if (max_body_size < 0)
+               http->default_max_body_size = EV_UINT64_MAX;
+       else
+               http->default_max_body_size = max_body_size;
+}
+
+void
+evhttp_set_allowed_methods(struct evhttp* http, ev_uint16_t methods)
+{
+       http->allowed_methods = methods;
+}
+
+int
+evhttp_set_cb(struct evhttp *http, const char *uri,
+    void (*cb)(struct evhttp_request *, void *), void *cbarg)
+{
+       struct evhttp_cb *http_cb;
+
+       TAILQ_FOREACH(http_cb, &http->callbacks, next) {
+               if (strcmp(http_cb->what, uri) == 0)
+                       return (-1);
+       }
+
+       if ((http_cb = mm_calloc(1, sizeof(struct evhttp_cb))) == NULL) {
+               event_warn("%s: calloc", __func__);
+               return (-2);
+       }
+
+       http_cb->what = mm_strdup(uri);
+       if (http_cb->what == NULL) {
+               event_warn("%s: strdup", __func__);
+               mm_free(http_cb);
+               return (-3);
+       }
+       http_cb->cb = cb;
+       http_cb->cbarg = cbarg;
+
+       TAILQ_INSERT_TAIL(&http->callbacks, http_cb, next);
+
+       return (0);
+}
+
+int
+evhttp_del_cb(struct evhttp *http, const char *uri)
+{
+       struct evhttp_cb *http_cb;
+
+       TAILQ_FOREACH(http_cb, &http->callbacks, next) {
+               if (strcmp(http_cb->what, uri) == 0)
+                       break;
+       }
+       if (http_cb == NULL)
+               return (-1);
+
+       TAILQ_REMOVE(&http->callbacks, http_cb, next);
+       mm_free(http_cb->what);
+       mm_free(http_cb);
+
+       return (0);
+}
+
+void
+evhttp_set_gencb(struct evhttp *http,
+    void (*cb)(struct evhttp_request *, void *), void *cbarg)
+{
+       http->gencb = cb;
+       http->gencbarg = cbarg;
+}
+
+/*
+ * Request related functions
+ */
+
+struct evhttp_request *
+evhttp_request_new(void (*cb)(struct evhttp_request *, void *), void *arg)
+{
+       struct evhttp_request *req = NULL;
+
+       /* Allocate request structure */
+       if ((req = mm_calloc(1, sizeof(struct evhttp_request))) == NULL) {
+               event_warn("%s: calloc", __func__);
+               goto error;
+       }
+
+       req->headers_size = 0;
+       req->body_size = 0;
+
+       req->kind = EVHTTP_RESPONSE;
+       req->input_headers = mm_calloc(1, sizeof(struct evkeyvalq));
+       if (req->input_headers == NULL) {
+               event_warn("%s: calloc", __func__);
+               goto error;
+       }
+       TAILQ_INIT(req->input_headers);
+
+       req->output_headers = mm_calloc(1, sizeof(struct evkeyvalq));
+       if (req->output_headers == NULL) {
+               event_warn("%s: calloc", __func__);
+               goto error;
+       }
+       TAILQ_INIT(req->output_headers);
+
+       if ((req->input_buffer = evbuffer_new()) == NULL) {
+               event_warn("%s: evbuffer_new", __func__);
+               goto error;
+       }
+
+       if ((req->output_buffer = evbuffer_new()) == NULL) {
+               event_warn("%s: evbuffer_new", __func__);
+               goto error;
+       }
+
+       req->cb = cb;
+       req->cb_arg = arg;
+
+       return (req);
+
+ error:
+       if (req != NULL)
+               evhttp_request_free(req);
+       return (NULL);
+}
+
+void
+evhttp_request_free(struct evhttp_request *req)
+{
+       if ((req->flags & EVHTTP_REQ_DEFER_FREE) != 0) {
+               req->flags |= EVHTTP_REQ_NEEDS_FREE;
+               return;
+       }
+
+       if (req->remote_host != NULL)
+               mm_free(req->remote_host);
+       if (req->uri != NULL)
+               mm_free(req->uri);
+       if (req->uri_elems != NULL)
+               evhttp_uri_free(req->uri_elems);
+       if (req->response_code_line != NULL)
+               mm_free(req->response_code_line);
+       if (req->host_cache != NULL)
+               mm_free(req->host_cache);
+
+       evhttp_clear_headers(req->input_headers);
+       mm_free(req->input_headers);
+
+       evhttp_clear_headers(req->output_headers);
+       mm_free(req->output_headers);
+
+       if (req->input_buffer != NULL)
+               evbuffer_free(req->input_buffer);
+
+       if (req->output_buffer != NULL)
+               evbuffer_free(req->output_buffer);
+
+       mm_free(req);
+}
+
+void
+evhttp_request_own(struct evhttp_request *req)
+{
+       req->flags |= EVHTTP_USER_OWNED;
+}
+
+int
+evhttp_request_is_owned(struct evhttp_request *req)
+{
+       return (req->flags & EVHTTP_USER_OWNED) != 0;
+}
+
+struct evhttp_connection *
+evhttp_request_get_connection(struct evhttp_request *req)
+{
+       return req->evcon;
+}
+
+struct event_base *
+evhttp_connection_get_base(struct evhttp_connection *conn)
+{
+       return conn->base;
+}
+
+void
+evhttp_request_set_chunked_cb(struct evhttp_request *req,
+    void (*cb)(struct evhttp_request *, void *))
+{
+       req->chunk_cb = cb;
+}
+
+/*
+ * Allows for inspection of the request URI
+ */
+
+const char *
+evhttp_request_get_uri(const struct evhttp_request *req) {
+       if (req->uri == NULL)
+               event_debug(("%s: request %p has no uri\n", __func__, req));
+       return (req->uri);
+}
+
+const struct evhttp_uri *
+evhttp_request_get_evhttp_uri(const struct evhttp_request *req) {
+       if (req->uri_elems == NULL)
+               event_debug(("%s: request %p has no uri elems\n",
+                           __func__, req));
+       return (req->uri_elems);
+}
+
+const char *
+evhttp_request_get_host(struct evhttp_request *req)
+{
+       const char *host = NULL;
+
+       if (req->host_cache)
+               return req->host_cache;
+
+       if (req->uri_elems)
+               host = evhttp_uri_get_host(req->uri_elems);
+       if (!host && req->input_headers) {
+               const char *p;
+               size_t len;
+
+               host = evhttp_find_header(req->input_headers, "Host");
+               /* The Host: header may include a port. Remove it here
+                  to be consistent with uri_elems case above. */
+               if (host) {
+                       p = host + strlen(host) - 1;
+                       while (p > host && EVUTIL_ISDIGIT(*p))
+                               --p;
+                       if (p > host && *p == ':') {
+                               len = p - host;
+                               req->host_cache = mm_malloc(len + 1);
+                               if (!req->host_cache) {
+                                       event_warn("%s: malloc", __func__);
+                                       return NULL;
+                               }
+                               memcpy(req->host_cache, host, len);
+                               req->host_cache[len] = '\0';
+                               host = req->host_cache;
+                       }
+               }
+       }
+
+       return host;
+}
+
+enum evhttp_cmd_type
+evhttp_request_get_command(const struct evhttp_request *req) {
+       return (req->type);
+}
+
+int
+evhttp_request_get_response_code(const struct evhttp_request *req)
+{
+       return req->response_code;
+}
+
+/** Returns the input headers */
+struct evkeyvalq *evhttp_request_get_input_headers(struct evhttp_request *req)
+{
+       return (req->input_headers);
+}
+
+/** Returns the output headers */
+struct evkeyvalq *evhttp_request_get_output_headers(struct evhttp_request *req)
+{
+       return (req->output_headers);
+}
+
+/** Returns the input buffer */
+struct evbuffer *evhttp_request_get_input_buffer(struct evhttp_request *req)
+{
+       return (req->input_buffer);
+}
+
+/** Returns the output buffer */
+struct evbuffer *evhttp_request_get_output_buffer(struct evhttp_request *req)
+{
+       return (req->output_buffer);
+}
+
+
+/*
+ * Takes a file descriptor to read a request from.
+ * The callback is executed once the whole request has been read.
+ */
+
+static struct evhttp_connection*
+evhttp_get_request_connection(
+       struct evhttp* http,
+       evutil_socket_t fd, struct sockaddr *sa, ev_socklen_t salen)
+{
+       struct evhttp_connection *evcon;
+       char *hostname = NULL, *portname = NULL;
+
+       name_from_addr(sa, salen, &hostname, &portname);
+       if (hostname == NULL || portname == NULL) {
+               if (hostname) mm_free(hostname);
+               if (portname) mm_free(portname);
+               return (NULL);
+       }
+
+       event_debug(("%s: new request from %s:%s on %d\n",
+                       __func__, hostname, portname, fd));
+
+       /* we need a connection object to put the http request on */
+       evcon = evhttp_connection_base_new(
+               http->base, NULL, hostname, atoi(portname));
+       mm_free(hostname);
+       mm_free(portname);
+       if (evcon == NULL)
+               return (NULL);
+
+       evcon->max_headers_size = http->default_max_headers_size;
+       evcon->max_body_size = http->default_max_body_size;
+
+       evcon->flags |= EVHTTP_CON_INCOMING;
+       evcon->state = EVCON_READING_FIRSTLINE;
+
+       evcon->fd = fd;
+
+       bufferevent_setfd(evcon->bufev, fd);
+
+       return (evcon);
+}
+
+static int
+evhttp_associate_new_request_with_connection(struct evhttp_connection *evcon)
+{
+       struct evhttp *http = evcon->http_server;
+       struct evhttp_request *req;
+       if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL)
+               return (-1);
+
+       if ((req->remote_host = mm_strdup(evcon->address)) == NULL) {
+               event_warn("%s: strdup", __func__);
+               evhttp_request_free(req);
+               return (-1);
+       }
+       req->remote_port = evcon->port;
+
+       req->evcon = evcon;     /* the request ends up owning the connection */
+       req->flags |= EVHTTP_REQ_OWN_CONNECTION;
+
+       /* We did not present the request to the user user yet, so treat it as
+        * if the user was done with the request.  This allows us to free the
+        * request on a persistent connection if the client drops it without
+        * sending a request.
+        */
+       req->userdone = 1;
+
+       TAILQ_INSERT_TAIL(&evcon->requests, req, next);
+
+       req->kind = EVHTTP_REQUEST;
+
+
+       evhttp_start_read(evcon);
+
+       return (0);
+}
+
+static void
+evhttp_get_request(struct evhttp *http, evutil_socket_t fd,
+    struct sockaddr *sa, ev_socklen_t salen)
+{
+       struct evhttp_connection *evcon;
+
+       evcon = evhttp_get_request_connection(http, fd, sa, salen);
+       if (evcon == NULL) {
+               event_sock_warn(fd, "%s: cannot get connection on %d", __func__, fd);
+               evutil_closesocket(fd);
+               return;
+       }
+
+       /* the timeout can be used by the server to close idle connections */
+       if (http->timeout != -1)
+               evhttp_connection_set_timeout(evcon, http->timeout);
+
+       /*
+        * if we want to accept more than one request on a connection,
+        * we need to know which http server it belongs to.
+        */
+       evcon->http_server = http;
+       TAILQ_INSERT_TAIL(&http->connections, evcon, next);
+
+       if (evhttp_associate_new_request_with_connection(evcon) == -1)
+               evhttp_connection_free(evcon);
+}
+
+
+/*
+ * Network helper functions that we do not want to export to the rest of
+ * the world.
+ */
+
+static void
+name_from_addr(struct sockaddr *sa, ev_socklen_t salen,
+    char **phost, char **pport)
+{
+       char ntop[NI_MAXHOST];
+       char strport[NI_MAXSERV];
+       int ni_result;
+
+#ifdef _EVENT_HAVE_GETNAMEINFO
+       ni_result = getnameinfo(sa, salen,
+               ntop, sizeof(ntop), strport, sizeof(strport),
+               NI_NUMERICHOST|NI_NUMERICSERV);
+
+       if (ni_result != 0) {
+#ifdef EAI_SYSTEM
+               /* Windows doesn't have an EAI_SYSTEM. */
+               if (ni_result == EAI_SYSTEM)
+                       event_err(1, "getnameinfo failed");
+               else
+#endif
+                       event_errx(1, "getnameinfo failed: %s", gai_strerror(ni_result));
+               return;
+       }
+#else
+       ni_result = fake_getnameinfo(sa, salen,
+               ntop, sizeof(ntop), strport, sizeof(strport),
+               NI_NUMERICHOST|NI_NUMERICSERV);
+       if (ni_result != 0)
+                       return;
+#endif
+
+       *phost = mm_strdup(ntop);
+       *pport = mm_strdup(strport);
+}
+
+/* Create a non-blocking socket and bind it */
+/* todo: rename this function */
+static evutil_socket_t
+bind_socket_ai(struct evutil_addrinfo *ai, int reuse)
+{
+       evutil_socket_t fd;
+
+       int on = 1, r;
+       int serrno;
+
+       /* Create listen socket */
+       fd = socket(ai ? ai->ai_family : AF_INET, SOCK_STREAM, 0);
+       if (fd == -1) {
+                       event_sock_warn(-1, "socket");
+                       return (-1);
+       }
+
+       if (evutil_make_socket_nonblocking(fd) < 0)
+               goto out;
+       if (evutil_make_socket_closeonexec(fd) < 0)
+               goto out;
+
+       setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
+       if (reuse)
+               evutil_make_listen_socket_reuseable(fd);
+
+       if (ai != NULL) {
+               r = bind(fd, ai->ai_addr, (ev_socklen_t)ai->ai_addrlen);
+               if (r == -1)
+                       goto out;
+       }
+
+       return (fd);
+
+ out:
+       serrno = EVUTIL_SOCKET_ERROR();
+       evutil_closesocket(fd);
+       EVUTIL_SET_SOCKET_ERROR(serrno);
+       return (-1);
+}
+
+static struct evutil_addrinfo *
+make_addrinfo(const char *address, ev_uint16_t port)
+{
+       struct evutil_addrinfo *ai = NULL;
+
+       struct evutil_addrinfo hints;
+       char strport[NI_MAXSERV];
+       int ai_result;
+
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = AF_UNSPEC;
+       hints.ai_socktype = SOCK_STREAM;
+       /* turn NULL hostname into INADDR_ANY, and skip looking up any address
+        * types we don't have an interface to connect to. */
+       hints.ai_flags = EVUTIL_AI_PASSIVE|EVUTIL_AI_ADDRCONFIG;
+       evutil_snprintf(strport, sizeof(strport), "%d", port);
+       if ((ai_result = evutil_getaddrinfo(address, strport, &hints, &ai))
+           != 0) {
+               if (ai_result == EVUTIL_EAI_SYSTEM)
+                       event_warn("getaddrinfo");
+               else
+                       event_warnx("getaddrinfo: %s",
+                           evutil_gai_strerror(ai_result));
+               return (NULL);
+       }
+
+       return (ai);
+}
+
+static evutil_socket_t
+bind_socket(const char *address, ev_uint16_t port, int reuse)
+{
+       evutil_socket_t fd;
+       struct evutil_addrinfo *aitop = NULL;
+
+       /* just create an unbound socket */
+       if (address == NULL && port == 0)
+               return bind_socket_ai(NULL, 0);
+
+       aitop = make_addrinfo(address, port);
+
+       if (aitop == NULL)
+               return (-1);
+
+       fd = bind_socket_ai(aitop, reuse);
+
+       evutil_freeaddrinfo(aitop);
+
+       return (fd);
+}
+
+struct evhttp_uri {
+       unsigned flags;
+       char *scheme; /* scheme; e.g http, ftp etc */
+       char *userinfo; /* userinfo (typically username:pass), or NULL */
+       char *host; /* hostname, IP address, or NULL */
+       int port; /* port, or zero */
+       char *path; /* path, or "". */
+       char *query; /* query, or NULL */
+       char *fragment; /* fragment or NULL */
+};
+
+struct evhttp_uri *
+evhttp_uri_new(void)
+{
+       struct evhttp_uri *uri = mm_calloc(sizeof(struct evhttp_uri), 1);
+       if (uri)
+               uri->port = -1;
+       return uri;
+}
+
+void
+evhttp_uri_set_flags(struct evhttp_uri *uri, unsigned flags)
+{
+       uri->flags = flags;
+}
+
+/* Return true if the string starting at s and ending immediately before eos
+ * is a valid URI scheme according to RFC3986
+ */
+static int
+scheme_ok(const char *s, const char *eos)
+{
+       /* scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
+       EVUTIL_ASSERT(eos >= s);
+       if (s == eos)
+               return 0;
+       if (!EVUTIL_ISALPHA(*s))
+               return 0;
+       while (++s < eos) {
+               if (! EVUTIL_ISALNUM(*s) &&
+                   *s != '+' && *s != '-' && *s != '.')
+                       return 0;
+       }
+       return 1;
+}
+
+#define SUBDELIMS "!$&'()*+,;="
+
+/* Return true iff [s..eos) is a valid userinfo */
+static int
+userinfo_ok(const char *s, const char *eos)
+{
+       while (s < eos) {
+               if (CHAR_IS_UNRESERVED(*s) ||
+                   strchr(SUBDELIMS, *s) ||
+                   *s == ':')
+                       ++s;
+               else if (*s == '%' && s+2 < eos &&
+                   EVUTIL_ISXDIGIT(s[1]) &&
+                   EVUTIL_ISXDIGIT(s[2]))
+                       s += 3;
+               else
+                       return 0;
+       }
+       return 1;
+}
+
+static int
+regname_ok(const char *s, const char *eos)
+{
+       while (s && s<eos) {
+               if (CHAR_IS_UNRESERVED(*s) ||
+                   strchr(SUBDELIMS, *s))
+                       ++s;
+               else if (*s == '%' &&
+                   EVUTIL_ISXDIGIT(s[1]) &&
+                   EVUTIL_ISXDIGIT(s[2]))
+                       s += 3;
+               else
+                       return 0;
+       }
+       return 1;
+}
+
+static int
+parse_port(const char *s, const char *eos)
+{
+       int portnum = 0;
+       while (s < eos) {
+               if (! EVUTIL_ISDIGIT(*s))
+                       return -1;
+               portnum = (portnum * 10) + (*s - '0');
+               if (portnum < 0)
+                       return -1;
+               ++s;
+       }
+       return portnum;
+}
+
+/* returns 0 for bad, 1 for ipv6, 2 for IPvFuture */
+static int
+bracket_addr_ok(const char *s, const char *eos)
+{
+       if (s + 3 > eos || *s != '[' || *(eos-1) != ']')
+               return 0;
+       if (s[1] == 'v') {
+               /* IPvFuture, or junk.
+                  "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
+                */
+               s += 2; /* skip [v */
+               --eos;
+               if (!EVUTIL_ISXDIGIT(*s)) /*require at least one*/
+                       return 0;
+               while (s < eos && *s != '.') {
+                       if (EVUTIL_ISXDIGIT(*s))
+                               ++s;
+                       else
+                               return 0;
+               }
+               if (*s != '.')
+                       return 0;
+               ++s;
+               while (s < eos) {
+                       if (CHAR_IS_UNRESERVED(*s) ||
+                           strchr(SUBDELIMS, *s) ||
+                           *s == ':')
+                               ++s;
+                       else
+                               return 0;
+               }
+               return 2;
+       } else {
+               /* IPv6, or junk */
+               char buf[64];
+               ev_ssize_t n_chars = eos-s-2;
+               struct in6_addr in6;
+               if (n_chars >= 64) /* way too long */
+                       return 0;
+               memcpy(buf, s+1, n_chars);
+               buf[n_chars]='\0';
+               return (evutil_inet_pton(AF_INET6,buf,&in6)==1) ? 1 : 0;
+       }
+}
+
+static int
+parse_authority(struct evhttp_uri *uri, char *s, char *eos)
+{
+       char *cp, *port;
+       EVUTIL_ASSERT(eos);
+       if (eos == s) {
+               uri->host = mm_strdup("");
+               if (uri->host == NULL) {
+                       event_warn("%s: strdup", __func__);
+                       return -1;
+               }
+               return 0;
+       }
+
+       /* Optionally, we start with "userinfo@" */
+
+       cp = strchr(s, '@');
+       if (cp && cp < eos) {
+               if (! userinfo_ok(s,cp))
+                       return -1;
+               *cp++ = '\0';
+               uri->userinfo = mm_strdup(s);
+               if (uri->userinfo == NULL) {
+                       event_warn("%s: strdup", __func__);
+                       return -1;
+               }
+       } else {
+               cp = s;
+       }
+       /* Optionally, we end with ":port" */
+       for (port=eos-1; port >= cp && EVUTIL_ISDIGIT(*port); --port)
+               ;
+       if (port >= cp && *port == ':') {
+               if (port+1 == eos) /* Leave port unspecified; the RFC allows a
+                                   * nil port */
+                       uri->port = -1;
+               else if ((uri->port = parse_port(port+1, eos))<0)
+                       return -1;
+               eos = port;
+       }
+       /* Now, cp..eos holds the "host" port, which can be an IPv4Address,
+        * an IP-Literal, or a reg-name */
+       EVUTIL_ASSERT(eos >= cp);
+       if (*cp == '[' && eos >= cp+2 && *(eos-1) == ']') {
+               /* IPv6address, IP-Literal, or junk. */
+               if (! bracket_addr_ok(cp, eos))
+                       return -1;
+       } else {
+               /* Make sure the host part is ok. */
+               if (! regname_ok(cp,eos)) /* Match IPv4Address or reg-name */
+                       return -1;
+       }
+       uri->host = mm_malloc(eos-cp+1);
+       if (uri->host == NULL) {
+               event_warn("%s: malloc", __func__);
+               return -1;
+       }
+       memcpy(uri->host, cp, eos-cp);
+       uri->host[eos-cp] = '\0';
+       return 0;
+
+}
+
+static char *
+end_of_authority(char *cp)
+{
+       while (*cp) {
+               if (*cp == '?' || *cp == '#' || *cp == '/')
+                       return cp;
+               ++cp;
+       }
+       return cp;
+}
+
+enum uri_part {
+       PART_PATH,
+       PART_QUERY,
+       PART_FRAGMENT
+};
+
+/* Return the character after the longest prefix of 'cp' that matches...
+ *   *pchar / "/" if allow_qchars is false, or
+ *   *(pchar / "/" / "?") if allow_qchars is true.
+ */
+static char *
+end_of_path(char *cp, enum uri_part part, unsigned flags)
+{
+       if (flags & EVHTTP_URI_NONCONFORMANT) {
+               /* If NONCONFORMANT:
+                *   Path is everything up to a # or ? or nul.
+                *   Query is everything up a # or nul
+                *   Fragment is everything up to a nul.
+                */
+               switch (part) {
+               case PART_PATH:
+                       while (*cp && *cp != '#' && *cp != '?')
+                               ++cp;
+                       break;
+               case PART_QUERY:
+                       while (*cp && *cp != '#')
+                               ++cp;
+                       break;
+               case PART_FRAGMENT:
+                       cp += strlen(cp);
+                       break;
+               };
+               return cp;
+       }
+
+       while (*cp) {
+               if (CHAR_IS_UNRESERVED(*cp) ||
+                   strchr(SUBDELIMS, *cp) ||
+                   *cp == ':' || *cp == '@' || *cp == '/')
+                       ++cp;
+               else if (*cp == '%' && EVUTIL_ISXDIGIT(cp[1]) &&
+                   EVUTIL_ISXDIGIT(cp[2]))
+                       cp += 3;
+               else if (*cp == '?' && part != PART_PATH)
+                       ++cp;
+               else
+                       return cp;
+       }
+       return cp;
+}
+
+static int
+path_matches_noscheme(const char *cp)
+{
+       while (*cp) {
+               if (*cp == ':')
+                       return 0;
+               else if (*cp == '/')
+                       return 1;
+               ++cp;
+       }
+       return 1;
+}
+
+struct evhttp_uri *
+evhttp_uri_parse(const char *source_uri)
+{
+       return evhttp_uri_parse_with_flags(source_uri, 0);
+}
+
+struct evhttp_uri *
+evhttp_uri_parse_with_flags(const char *source_uri, unsigned flags)
+{
+       char *readbuf = NULL, *readp = NULL, *token = NULL, *query = NULL;
+       char *path = NULL, *fragment = NULL;
+       int got_authority = 0;
+
+       struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
+       if (uri == NULL) {
+               event_warn("%s: calloc", __func__);
+               goto err;
+       }
+       uri->port = -1;
+       uri->flags = flags;
+
+       readbuf = mm_strdup(source_uri);
+       if (readbuf == NULL) {
+               event_warn("%s: strdup", __func__);
+               goto err;
+       }
+
+       readp = readbuf;
+       token = NULL;
+
+       /* We try to follow RFC3986 here as much as we can, and match
+          the productions
+
+             URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
+
+             relative-ref  = relative-part [ "?" query ] [ "#" fragment ]
+        */
+
+       /* 1. scheme: */
+       token = strchr(readp, ':');
+       if (token && scheme_ok(readp,token)) {
+               *token = '\0';
+               uri->scheme = mm_strdup(readp);
+               if (uri->scheme == NULL) {
+                       event_warn("%s: strdup", __func__);
+                       goto err;
+               }
+               readp = token+1; /* eat : */
+       }
+
+       /* 2. Optionally, "//" then an 'authority' part. */
+       if (readp[0]=='/' && readp[1] == '/') {
+               char *authority;
+               readp += 2;
+               authority = readp;
+               path = end_of_authority(readp);
+               if (parse_authority(uri, authority, path) < 0)
+                       goto err;
+               readp = path;
+               got_authority = 1;
+       }
+
+       /* 3. Query: path-abempty, path-absolute, path-rootless, or path-empty
+        */
+       path = readp;
+       readp = end_of_path(path, PART_PATH, flags);
+
+       /* Query */
+       if (*readp == '?') {
+               *readp = '\0';
+               ++readp;
+               query = readp;
+               readp = end_of_path(readp, PART_QUERY, flags);
+       }
+       /* fragment */
+       if (*readp == '#') {
+               *readp = '\0';
+               ++readp;
+               fragment = readp;
+               readp = end_of_path(readp, PART_FRAGMENT, flags);
+       }
+       if (*readp != '\0') {
+               goto err;
+       }
+
+       /* These next two cases may be unreachable; I'm leaving them
+        * in to be defensive. */
+       /* If you didn't get an authority, the path can't begin with "//" */
+       if (!got_authority && path[0]=='/' && path[1]=='/')
+               goto err;
+       /* If you did get an authority, the path must begin with "/" or be
+        * empty. */
+       if (got_authority && path[0] != '/' && path[0] != '\0')
+               goto err;
+       /* (End of maybe-unreachable cases) */
+
+       /* If there was no scheme, the first part of the path (if any) must
+        * have no colon in it. */
+       if (! uri->scheme && !path_matches_noscheme(path))
+               goto err;
+
+       EVUTIL_ASSERT(path);
+       uri->path = mm_strdup(path);
+       if (uri->path == NULL) {
+               event_warn("%s: strdup", __func__);
+               goto err;
+       }
+
+       if (query) {
+               uri->query = mm_strdup(query);
+               if (uri->query == NULL) {
+                       event_warn("%s: strdup", __func__);
+                       goto err;
+               }
+       }
+       if (fragment) {
+               uri->fragment = mm_strdup(fragment);
+               if (uri->fragment == NULL) {
+                       event_warn("%s: strdup", __func__);
+                       goto err;
+               }
+       }
+
+       mm_free(readbuf);
+
+       return uri;
+err:
+       if (uri)
+               evhttp_uri_free(uri);
+       if (readbuf)
+               mm_free(readbuf);
+       return NULL;
+}
+
+void
+evhttp_uri_free(struct evhttp_uri *uri)
+{
+#define _URI_FREE_STR(f)               \
+       if (uri->f) {                   \
+               mm_free(uri->f);                \
+       }
+
+       _URI_FREE_STR(scheme);
+       _URI_FREE_STR(userinfo);
+       _URI_FREE_STR(host);
+       _URI_FREE_STR(path);
+       _URI_FREE_STR(query);
+       _URI_FREE_STR(fragment);
+
+       mm_free(uri);
+#undef _URI_FREE_STR
+}
+
+char *
+evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit)
+{
+       struct evbuffer *tmp = 0;
+       size_t joined_size = 0;
+       char *output = NULL;
+
+#define _URI_ADD(f)    evbuffer_add(tmp, uri->f, strlen(uri->f))
+
+       if (!uri || !buf || !limit)
+               return NULL;
+
+       tmp = evbuffer_new();
+       if (!tmp)
+               return NULL;
+
+       if (uri->scheme) {
+               _URI_ADD(scheme);
+               evbuffer_add(tmp, ":", 1);
+       }
+       if (uri->host) {
+               evbuffer_add(tmp, "//", 2);
+               if (uri->userinfo)
+                       evbuffer_add_printf(tmp,"%s@", uri->userinfo);
+               _URI_ADD(host);
+               if (uri->port >= 0)
+                       evbuffer_add_printf(tmp,":%d", uri->port);
+
+               if (uri->path && uri->path[0] != '/' && uri->path[0] != '\0')
+                       goto err;
+       }
+
+       if (uri->path)
+               _URI_ADD(path);
+
+       if (uri->query) {
+               evbuffer_add(tmp, "?", 1);
+               _URI_ADD(query);
+       }
+
+       if (uri->fragment) {
+               evbuffer_add(tmp, "#", 1);
+               _URI_ADD(fragment);
+       }
+
+       evbuffer_add(tmp, "\0", 1); /* NUL */
+
+       joined_size = evbuffer_get_length(tmp);
+
+       if (joined_size > limit) {
+               /* It doesn't fit. */
+               evbuffer_free(tmp);
+               return NULL;
+       }
+               evbuffer_remove(tmp, buf, joined_size);
+
+       output = buf;
+err:
+       evbuffer_free(tmp);
+
+       return output;
+#undef _URI_ADD
+}
+
+const char *
+evhttp_uri_get_scheme(const struct evhttp_uri *uri)
+{
+       return uri->scheme;
+}
+const char *
+evhttp_uri_get_userinfo(const struct evhttp_uri *uri)
+{
+       return uri->userinfo;
+}
+const char *
+evhttp_uri_get_host(const struct evhttp_uri *uri)
+{
+       return uri->host;
+}
+int
+evhttp_uri_get_port(const struct evhttp_uri *uri)
+{
+       return uri->port;
+}
+const char *
+evhttp_uri_get_path(const struct evhttp_uri *uri)
+{
+       return uri->path;
+}
+const char *
+evhttp_uri_get_query(const struct evhttp_uri *uri)
+{
+       return uri->query;
+}
+const char *
+evhttp_uri_get_fragment(const struct evhttp_uri *uri)
+{
+       return uri->fragment;
+}
+
+#define _URI_SET_STR(f) do {                                   \
+       if (uri->f)                                             \
+               mm_free(uri->f);                                \
+       if (f) {                                                \
+               if ((uri->f = mm_strdup(f)) == NULL) {          \
+                       event_warn("%s: strdup()", __func__);   \
+                       return -1;                              \
+               }                                               \
+       } else {                                                \
+               uri->f = NULL;                                  \
+       }                                                       \
+       } while(0)
+
+int
+evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme)
+{
+       if (scheme && !scheme_ok(scheme, scheme+strlen(scheme)))
+               return -1;
+
+       _URI_SET_STR(scheme);
+       return 0;
+}
+int
+evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo)
+{
+       if (userinfo && !userinfo_ok(userinfo, userinfo+strlen(userinfo)))
+               return -1;
+       _URI_SET_STR(userinfo);
+       return 0;
+}
+int
+evhttp_uri_set_host(struct evhttp_uri *uri, const char *host)
+{
+       if (host) {
+               if (host[0] == '[') {
+                       if (! bracket_addr_ok(host, host+strlen(host)))
+                               return -1;
+               } else {
+                       if (! regname_ok(host, host+strlen(host)))
+                               return -1;
+               }
+       }
+
+       _URI_SET_STR(host);
+       return 0;
+}
+int
+evhttp_uri_set_port(struct evhttp_uri *uri, int port)
+{
+       if (port < -1)
+               return -1;
+       uri->port = port;
+       return 0;
+}
+#define end_of_cpath(cp,p,f) \
+       ((const char*)(end_of_path(((char*)(cp)), (p), (f))))
+
+int
+evhttp_uri_set_path(struct evhttp_uri *uri, const char *path)
+{
+       if (path && end_of_cpath(path, PART_PATH, uri->flags) != path+strlen(path))
+               return -1;
+
+       _URI_SET_STR(path);
+       return 0;
+}
+int
+evhttp_uri_set_query(struct evhttp_uri *uri, const char *query)
+{
+       if (query && end_of_cpath(query, PART_QUERY, uri->flags) != query+strlen(query))
+               return -1;
+       _URI_SET_STR(query);
+       return 0;
+}
+int
+evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment)
+{
+       if (fragment && end_of_cpath(fragment, PART_FRAGMENT, uri->flags) != fragment+strlen(fragment))
+               return -1;
+       _URI_SET_STR(fragment);
+       return 0;
+}
diff --git a/libevent/include/Makefile.am b/libevent/include/Makefile.am
new file mode 100644 (file)
index 0000000..5153db2
--- /dev/null
@@ -0,0 +1,47 @@
+# include/Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+AUTOMAKE_OPTIONS = foreign
+
+EVENT2_EXPORT = \
+       event2/buffer.h \
+       event2/buffer_compat.h \
+       event2/bufferevent.h \
+       event2/bufferevent_compat.h \
+       event2/bufferevent_ssl.h \
+       event2/bufferevent_struct.h \
+       event2/dns.h \
+       event2/dns_compat.h \
+       event2/dns_struct.h \
+       event2/event.h \
+       event2/event_compat.h \
+       event2/event_struct.h \
+       event2/http.h \
+       event2/http_compat.h \
+       event2/http_struct.h \
+       event2/keyvalq_struct.h \
+       event2/listener.h \
+       event2/rpc.h \
+       event2/rpc_compat.h \
+       event2/rpc_struct.h \
+       event2/tag.h \
+       event2/tag_compat.h \
+       event2/thread.h \
+       event2/util.h
+
+EXTRA_SRC = $(EVENT2_EXPORT)
+
+## Without the nobase_ prefixing, Automake would strip "event2/" from
+## the source header filename to derive the installed header filename.
+## With nobase_ the installed path is $(includedir)/event2/ev*.h.
+
+if INSTALL_LIBEVENT
+nobase_include_HEADERS =       $(EVENT2_EXPORT)
+nobase_nodist_include_HEADERS = ./event2/event-config.h
+else
+noinst_HEADERS =               $(EVENT2_EXPORT)
+nodist_noinst_HEADERS =                ./event2/event-config.h
+endif
diff --git a/libevent/include/event2/buffer.h b/libevent/include/event2/buffer.h
new file mode 100644 (file)
index 0000000..16236c4
--- /dev/null
@@ -0,0 +1,838 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_BUFFER_H_
+#define _EVENT2_BUFFER_H_
+
+/** @file event2/buffer.h
+
+  Functions for buffering data for network sending or receiving.
+
+  An evbuffer can be used for preparing data before sending it to
+  the network or conversely for reading data from the network.
+  Evbuffers try to avoid memory copies as much as possible.  As a
+  result, evbuffers can be used to pass data around without actually
+  incurring the overhead of copying the data.
+
+  A new evbuffer can be allocated with evbuffer_new(), and can be
+  freed with evbuffer_free().  Most users will be using evbuffers via
+  the bufferevent interface.  To access a bufferevent's evbuffers, use
+  bufferevent_get_input() and bufferevent_get_output().
+
+  There are several guidelines for using evbuffers.
+
+  - if you already know how much data you are going to add as a result
+    of calling evbuffer_add() multiple times, it makes sense to use
+    evbuffer_expand() first to make sure that enough memory is allocated
+    before hand.
+
+  - evbuffer_add_buffer() adds the contents of one buffer to the other
+    without incurring any unnecessary memory copies.
+
+  - evbuffer_add() and evbuffer_add_buffer() do not mix very well:
+    if you use them, you will wind up with fragmented memory in your
+       buffer.
+
+  - For high-performance code, you may want to avoid copying data into and out
+    of buffers.  You can skip the copy step by using
+    evbuffer_reserve_space()/evbuffer_commit_space() when writing into a
+    buffer, and evbuffer_peek() when reading.
+
+  In Libevent 2.0 and later, evbuffers are represented using a linked
+  list of memory chunks, with pointers to the first and last chunk in
+  the chain.
+
+  As the contents of an evbuffer can be stored in multiple different
+  memory blocks, it cannot be accessed directly.  Instead, evbuffer_pullup()
+  can be used to force a specified number of bytes to be contiguous. This
+  will cause memory reallocation and memory copies if the data is split
+  across multiple blocks.  It is more efficient, however, to use
+  evbuffer_peek() if you don't require that the memory to be contiguous.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#include <stdarg.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_UIO_H
+#include <sys/uio.h>
+#endif
+#include <event2/util.h>
+
+/**
+   An evbuffer is an opaque data type for efficiently buffering data to be
+   sent or received on the network.
+
+   @see event2/event.h for more information
+*/
+struct evbuffer
+#ifdef _EVENT_IN_DOXYGEN
+{}
+#endif
+;
+
+/**
+    Pointer to a position within an evbuffer.
+
+    Used when repeatedly searching through a buffer.  Calling any function
+    that modifies or re-packs the buffer contents may invalidate all
+    evbuffer_ptrs for that buffer.  Do not modify these values except with
+    evbuffer_ptr_set.
+ */
+struct evbuffer_ptr {
+       ev_ssize_t pos;
+
+       /* Do not alter the values of fields. */
+       struct {
+               void *chain;
+               size_t pos_in_chain;
+       } _internal;
+};
+
+/** Describes a single extent of memory inside an evbuffer.  Used for
+    direct-access functions.
+
+    @see evbuffer_reserve_space, evbuffer_commit_space, evbuffer_peek
+ */
+#ifdef _EVENT_HAVE_SYS_UIO_H
+#define evbuffer_iovec iovec
+/* Internal use -- defined only if we are using the native struct iovec */
+#define _EVBUFFER_IOVEC_IS_NATIVE
+#else
+struct evbuffer_iovec {
+       /** The start of the extent of memory. */
+       void *iov_base;
+       /** The length of the extent of memory. */
+       size_t iov_len;
+};
+#endif
+
+/**
+  Allocate storage for a new evbuffer.
+
+  @return a pointer to a newly allocated evbuffer struct, or NULL if an error
+       occurred
+ */
+struct evbuffer *evbuffer_new(void);
+/**
+  Deallocate storage for an evbuffer.
+
+  @param buf pointer to the evbuffer to be freed
+ */
+void evbuffer_free(struct evbuffer *buf);
+
+/**
+   Enable locking on an evbuffer so that it can safely be used by multiple
+   threads at the same time.
+
+   NOTE: when locking is enabled, the lock will be held when callbacks are
+   invoked.  This could result in deadlock if you aren't careful.  Plan
+   accordingly!
+
+   @param buf An evbuffer to make lockable.
+   @param lock A lock object, or NULL if we should allocate our own.
+   @return 0 on success, -1 on failure.
+ */
+int evbuffer_enable_locking(struct evbuffer *buf, void *lock);
+
+/**
+   Acquire the lock on an evbuffer.  Has no effect if locking was not enabled
+   with evbuffer_enable_locking.
+*/
+void evbuffer_lock(struct evbuffer *buf);
+
+/**
+   Release the lock on an evbuffer.  Has no effect if locking was not enabled
+   with evbuffer_enable_locking.
+*/
+void evbuffer_unlock(struct evbuffer *buf);
+
+
+/** If this flag is set, then we will not use evbuffer_peek(),
+ * evbuffer_remove(), evbuffer_remove_buffer(), and so on to read bytes
+ * from this buffer: we'll only take bytes out of this buffer by
+ * writing them to the network (as with evbuffer_write_atmost), by
+ * removing them without observing them (as with evbuffer_drain),
+ * or by copying them all out at once (as with evbuffer_add_buffer).
+ *
+ * Using this option allows the implementation to use sendfile-based
+ * operations for evbuffer_add_file(); see that function for more
+ * information.
+ *
+ * This flag is on by default for bufferevents that can take advantage
+ * of it; you should never actually need to set it on a bufferevent's
+ * output buffer.
+ */
+#define EVBUFFER_FLAG_DRAINS_TO_FD 1
+
+/** Change the flags that are set for an evbuffer by adding more.
+ *
+ * @param buffer the evbuffer that the callback is watching.
+ * @param cb the callback whose status we want to change.
+ * @param flags One or more EVBUFFER_FLAG_* options
+ * @return 0 on success, -1 on failure.
+ */
+int evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags);
+/** Change the flags that are set for an evbuffer by removing some.
+ *
+ * @param buffer the evbuffer that the callback is watching.
+ * @param cb the callback whose status we want to change.
+ * @param flags One or more EVBUFFER_FLAG_* options
+ * @return 0 on success, -1 on failure.
+ */
+int evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags);
+
+/**
+  Returns the total number of bytes stored in the evbuffer
+
+  @param buf pointer to the evbuffer
+  @return the number of bytes stored in the evbuffer
+*/
+size_t evbuffer_get_length(const struct evbuffer *buf);
+
+/**
+   Returns the number of contiguous available bytes in the first buffer chain.
+
+   This is useful when processing data that might be split into multiple
+   chains, or that might all be in the first chain.  Calls to
+   evbuffer_pullup() that cause reallocation and copying of data can thus be
+   avoided.
+
+   @param buf pointer to the evbuffer
+   @return 0 if no data is available, otherwise the number of available bytes
+     in the first buffer chain.
+*/
+size_t evbuffer_get_contiguous_space(const struct evbuffer *buf);
+
+/**
+  Expands the available space in an evbuffer.
+
+  Expands the available space in the evbuffer to at least datlen, so that
+  appending datlen additional bytes will not require any new allocations.
+
+  @param buf the evbuffer to be expanded
+  @param datlen the new minimum length requirement
+  @return 0 if successful, or -1 if an error occurred
+*/
+int evbuffer_expand(struct evbuffer *buf, size_t datlen);
+
+/**
+   Reserves space in the last chain or chains of an evbuffer.
+
+   Makes space available in the last chain or chains of an evbuffer that can
+   be arbitrarily written to by a user.  The space does not become
+   available for reading until it has been committed with
+   evbuffer_commit_space().
+
+   The space is made available as one or more extents, represented by
+   an initial pointer and a length.  You can force the memory to be
+   available as only one extent.  Allowing more extents, however, makes the
+   function more efficient.
+
+   Multiple subsequent calls to this function will make the same space
+   available until evbuffer_commit_space() has been called.
+
+   It is an error to do anything that moves around the buffer's internal
+   memory structures before committing the space.
+
+   NOTE: The code currently does not ever use more than two extents.
+   This may change in future versions.
+
+   @param buf the evbuffer in which to reserve space.
+   @param size how much space to make available, at minimum.  The
+      total length of the extents may be greater than the requested
+      length.
+   @param vec an array of one or more evbuffer_iovec structures to
+      hold pointers to the reserved extents of memory.
+   @param n_vec The length of the vec array.  Must be at least 1;
+       2 is more efficient.
+   @return the number of provided extents, or -1 on error.
+   @see evbuffer_commit_space()
+*/
+int
+evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
+    struct evbuffer_iovec *vec, int n_vec);
+
+/**
+   Commits previously reserved space.
+
+   Commits some of the space previously reserved with
+   evbuffer_reserve_space().  It then becomes available for reading.
+
+   This function may return an error if the pointer in the extents do
+   not match those returned from evbuffer_reserve_space, or if data
+   has been added to the buffer since the space was reserved.
+
+   If you want to commit less data than you got reserved space for,
+   modify the iov_len pointer of the appropriate extent to a smaller
+   value.  Note that you may have received more space than you
+   requested if it was available!
+
+   @param buf the evbuffer in which to reserve space.
+   @param vec one or two extents returned by evbuffer_reserve_space.
+   @param n_vecs the number of extents.
+   @return 0 on success, -1 on error
+   @see evbuffer_reserve_space()
+*/
+int evbuffer_commit_space(struct evbuffer *buf,
+    struct evbuffer_iovec *vec, int n_vecs);
+
+/**
+  Append data to the end of an evbuffer.
+
+  @param buf the evbuffer to be appended to
+  @param data pointer to the beginning of the data buffer
+  @param datlen the number of bytes to be copied from the data buffer
+  @return 0 on success, -1 on failure.
+ */
+int evbuffer_add(struct evbuffer *buf, const void *data, size_t datlen);
+
+
+/**
+  Read data from an evbuffer and drain the bytes read.
+
+  If more bytes are requested than are available in the evbuffer, we
+  only extract as many bytes as were available.
+
+  @param buf the evbuffer to be read from
+  @param data the destination buffer to store the result
+  @param datlen the maximum size of the destination buffer
+  @return the number of bytes read, or -1 if we can't drain the buffer.
+ */
+int evbuffer_remove(struct evbuffer *buf, void *data, size_t datlen);
+
+/**
+  Read data from an evbuffer, and leave the buffer unchanged.
+
+  If more bytes are requested than are available in the evbuffer, we
+  only extract as many bytes as were available.
+
+  @param buf the evbuffer to be read from
+  @param data_out the destination buffer to store the result
+  @param datlen the maximum size of the destination buffer
+  @return the number of bytes read, or -1 if we can't drain the buffer.
+ */
+ev_ssize_t evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen);
+
+/**
+  Read data from an evbuffer into another evbuffer, draining
+  the bytes from the source buffer.  This function avoids copy
+  operations to the extent possible.
+
+  If more bytes are requested than are available in src, the src
+  buffer is drained completely.
+
+  @param src the evbuffer to be read from
+  @param dst the destination evbuffer to store the result into
+  @param datlen the maximum numbers of bytes to transfer
+  @return the number of bytes read
+ */
+int evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
+    size_t datlen);
+
+/** Used to tell evbuffer_readln what kind of line-ending to look for.
+ */
+enum evbuffer_eol_style {
+       /** Any sequence of CR and LF characters is acceptable as an
+        * EOL.
+        *
+        * Note that this style can produce ambiguous results: the
+        * sequence "CRLF" will be treated as a single EOL if it is
+        * all in the buffer at once, but if you first read a CR from
+        * the network and later read an LF from the network, it will
+        * be treated as two EOLs.
+        */
+       EVBUFFER_EOL_ANY,
+       /** An EOL is an LF, optionally preceded by a CR.  This style is
+        * most useful for implementing text-based internet protocols. */
+       EVBUFFER_EOL_CRLF,
+       /** An EOL is a CR followed by an LF. */
+       EVBUFFER_EOL_CRLF_STRICT,
+       /** An EOL is a LF. */
+       EVBUFFER_EOL_LF
+};
+
+/**
+ * Read a single line from an evbuffer.
+ *
+ * Reads a line terminated by an EOL as determined by the evbuffer_eol_style
+ * argument.  Returns a newly allocated nul-terminated string; the caller must
+ * free the returned value.  The EOL is not included in the returned string.
+ *
+ * @param buffer the evbuffer to read from
+ * @param n_read_out if non-NULL, points to a size_t that is set to the
+ *       number of characters in the returned string.  This is useful for
+ *       strings that can contain NUL characters.
+ * @param eol_style the style of line-ending to use.
+ * @return pointer to a single line, or NULL if an error occurred
+ */
+char *evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
+    enum evbuffer_eol_style eol_style);
+
+/**
+  Move all data from one evbuffer into another evbuffer.
+
+  This is a destructive add.  The data from one buffer moves into
+  the other buffer.  However, no unnecessary memory copies occur.
+
+  @param outbuf the output buffer
+  @param inbuf the input buffer
+  @return 0 if successful, or -1 if an error occurred
+
+  @see evbuffer_remove_buffer()
+ */
+int evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf);
+
+/**
+   A cleanup function for a piece of memory added to an evbuffer by
+   reference.
+
+   @see evbuffer_add_reference()
+ */
+typedef void (*evbuffer_ref_cleanup_cb)(const void *data,
+    size_t datalen, void *extra);
+
+/**
+  Reference memory into an evbuffer without copying.
+
+  The memory needs to remain valid until all the added data has been
+  read.  This function keeps just a reference to the memory without
+  actually incurring the overhead of a copy.
+
+  @param outbuf the output buffer
+  @param data the memory to reference
+  @param datlen how memory to reference
+  @param cleanupfn callback to be invoked when the memory is no longer
+       referenced by this evbuffer.
+  @param cleanupfn_arg optional argument to the cleanup callback
+  @return 0 if successful, or -1 if an error occurred
+ */
+int evbuffer_add_reference(struct evbuffer *outbuf,
+    const void *data, size_t datlen,
+    evbuffer_ref_cleanup_cb cleanupfn, void *cleanupfn_arg);
+
+/**
+  Copy data from a file into the evbuffer for writing to a socket.
+
+  This function avoids unnecessary data copies between userland and
+  kernel.  If sendfile is available and the EVBUFFER_FLAG_DRAINS_TO_FD
+  flag is set, it uses those functions.  Otherwise, it tries to use
+  mmap (or CreateFileMapping on Windows).
+
+  The function owns the resulting file descriptor and will close it
+  when finished transferring data.
+
+  The results of using evbuffer_remove() or evbuffer_pullup() on
+  evbuffers whose data was added using this function are undefined.
+
+  @param outbuf the output buffer
+  @param fd the file descriptor
+  @param offset the offset from which to read data
+  @param length how much data to read
+  @return 0 if successful, or -1 if an error occurred
+*/
+
+int evbuffer_add_file(struct evbuffer *outbuf, int fd, ev_off_t offset,
+    ev_off_t length);
+
+/**
+  Append a formatted string to the end of an evbuffer.
+
+  The string is formated as printf.
+
+  @param buf the evbuffer that will be appended to
+  @param fmt a format string
+  @param ... arguments that will be passed to printf(3)
+  @return The number of bytes added if successful, or -1 if an error occurred.
+
+  @see evutil_printf(), evbuffer_add_vprintf()
+ */
+int evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
+#ifdef __GNUC__
+  __attribute__((format(printf, 2, 3)))
+#endif
+;
+
+/**
+  Append a va_list formatted string to the end of an evbuffer.
+
+  @param buf the evbuffer that will be appended to
+  @param fmt a format string
+  @param ap a varargs va_list argument array that will be passed to vprintf(3)
+  @return The number of bytes added if successful, or -1 if an error occurred.
+ */
+int evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap);
+
+
+/**
+  Remove a specified number of bytes data from the beginning of an evbuffer.
+
+  @param buf the evbuffer to be drained
+  @param len the number of bytes to drain from the beginning of the buffer
+  @return 0 on success, -1 on failure.
+ */
+int evbuffer_drain(struct evbuffer *buf, size_t len);
+
+
+/**
+  Write the contents of an evbuffer to a file descriptor.
+
+  The evbuffer will be drained after the bytes have been successfully written.
+
+  @param buffer the evbuffer to be written and drained
+  @param fd the file descriptor to be written to
+  @return the number of bytes written, or -1 if an error occurred
+  @see evbuffer_read()
+ */
+int evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd);
+
+/**
+  Write some of the contents of an evbuffer to a file descriptor.
+
+  The evbuffer will be drained after the bytes have been successfully written.
+
+  @param buffer the evbuffer to be written and drained
+  @param fd the file descriptor to be written to
+  @param howmuch the largest allowable number of bytes to write, or -1
+       to write as many bytes as we can.
+  @return the number of bytes written, or -1 if an error occurred
+  @see evbuffer_read()
+ */
+int evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
+                                                 ev_ssize_t howmuch);
+
+/**
+  Read from a file descriptor and store the result in an evbuffer.
+
+  @param buffer the evbuffer to store the result
+  @param fd the file descriptor to read from
+  @param howmuch the number of bytes to be read
+  @return the number of bytes read, or -1 if an error occurred
+  @see evbuffer_write()
+ */
+int evbuffer_read(struct evbuffer *buffer, evutil_socket_t fd, int howmuch);
+
+/**
+   Search for a string within an evbuffer.
+
+   @param buffer the evbuffer to be searched
+   @param what the string to be searched for
+   @param len the length of the search string
+   @param start NULL or a pointer to a valid struct evbuffer_ptr.
+   @return a struct evbuffer_ptr whose 'pos' field has the offset of the
+     first occurrence of the string in the buffer after 'start'.  The 'pos'
+     field of the result is -1 if the string was not found.
+ */
+struct evbuffer_ptr evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start);
+
+/**
+   Search for a string within part of an evbuffer.
+
+   @param buffer the evbuffer to be searched
+   @param what the string to be searched for
+   @param len the length of the search string
+   @param start NULL or a pointer to a valid struct evbuffer_ptr that
+     indicates where we should start searching.
+   @param end NULL or a pointer to a valid struct evbuffer_ptr that
+     indicates where we should stop searching.
+   @return a struct evbuffer_ptr whose 'pos' field has the offset of the
+     first occurrence of the string in the buffer after 'start'.  The 'pos'
+     field of the result is -1 if the string was not found.
+ */
+struct evbuffer_ptr evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start, const struct evbuffer_ptr *end);
+
+/**
+   Defines how to adjust an evbuffer_ptr by evbuffer_ptr_set()
+
+   @see evbuffer_ptr_set() */
+enum evbuffer_ptr_how {
+       /** Sets the pointer to the position; can be called on with an
+           uninitialized evbuffer_ptr. */
+       EVBUFFER_PTR_SET,
+       /** Advances the pointer by adding to the current position. */
+       EVBUFFER_PTR_ADD
+};
+
+/**
+   Sets the search pointer in the buffer to position.
+
+   If evbuffer_ptr is not initialized.  This function can only be called
+   with EVBUFFER_PTR_SET.
+
+   @param buffer the evbuffer to be search
+   @param ptr a pointer to a struct evbuffer_ptr
+   @param position the position at which to start the next search
+   @param how determines how the pointer should be manipulated.
+   @returns 0 on success or -1 otherwise
+*/
+int
+evbuffer_ptr_set(struct evbuffer *buffer, struct evbuffer_ptr *ptr,
+    size_t position, enum evbuffer_ptr_how how);
+
+/**
+   Search for an end-of-line string within an evbuffer.
+
+   @param buffer the evbuffer to be searched
+   @param start NULL or a pointer to a valid struct evbuffer_ptr to start
+      searching at.
+   @param eol_len_out If non-NULL, the pointed-to value will be set to
+      the length of the end-of-line string.
+   @param eol_style The kind of EOL to look for; see evbuffer_readln() for
+      more information
+   @return a struct evbuffer_ptr whose 'pos' field has the offset of the
+     first occurrence EOL in the buffer after 'start'.  The 'pos'
+     field of the result is -1 if the string was not found.
+ */
+struct evbuffer_ptr evbuffer_search_eol(struct evbuffer *buffer,
+    struct evbuffer_ptr *start, size_t *eol_len_out,
+    enum evbuffer_eol_style eol_style);
+
+/** Function to peek at data inside an evbuffer without removing it or
+    copying it out.
+
+    Pointers to the data are returned by filling the 'vec_out' array
+    with pointers to one or more extents of data inside the buffer.
+
+    The total data in the extents that you get back may be more than
+    you requested (if there is more data last extent than you asked
+    for), or less (if you do not provide enough evbuffer_iovecs, or if
+    the buffer does not have as much data as you asked to see).
+
+    @param buffer the evbuffer to peek into,
+    @param len the number of bytes to try to peek.  If len is negative, we
+       will try to fill as much of vec_out as we can.  If len is negative
+       and vec_out is not provided, we return the number of evbuffer_iovecs
+       that would be needed to get all the data in the buffer.
+    @param start_at an evbuffer_ptr indicating the point at which we
+       should start looking for data.  NULL means, "At the start of the
+       buffer."
+    @param vec_out an array of evbuffer_iovec
+    @param n_vec the length of vec_out.  If 0, we only count how many
+       extents would be necessary to point to the requested amount of
+       data.
+    @return The number of extents needed.  This may be less than n_vec
+       if we didn't need all the evbuffer_iovecs we were given, or more
+       than n_vec if we would need more to return all the data that was
+       requested.
+ */
+int evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
+    struct evbuffer_ptr *start_at,
+    struct evbuffer_iovec *vec_out, int n_vec);
+
+
+/** Structure passed to an evbuffer_cb_func evbuffer callback
+
+    @see evbuffer_cb_func, evbuffer_add_cb()
+ */
+struct evbuffer_cb_info {
+       /** The number of bytes in this evbuffer when callbacks were last
+        * invoked. */
+       size_t orig_size;
+       /** The number of bytes added since callbacks were last invoked. */
+       size_t n_added;
+       /** The number of bytes removed since callbacks were last invoked. */
+       size_t n_deleted;
+};
+
+/** Type definition for a callback that is invoked whenever data is added or
+    removed from an evbuffer.
+
+    An evbuffer may have one or more callbacks set at a time.  The order
+    in which they are executed is undefined.
+
+    A callback function may add more callbacks, or remove itself from the
+    list of callbacks, or add or remove data from the buffer.  It may not
+    remove another callback from the list.
+
+    If a callback adds or removes data from the buffer or from another
+    buffer, this can cause a recursive invocation of your callback or
+    other callbacks.  If you ask for an infinite loop, you might just get
+    one: watch out!
+
+    @param buffer the buffer whose size has changed
+    @param info a structure describing how the buffer changed.
+    @param arg a pointer to user data
+*/
+typedef void (*evbuffer_cb_func)(struct evbuffer *buffer, const struct evbuffer_cb_info *info, void *arg);
+
+struct evbuffer_cb_entry;
+/** Add a new callback to an evbuffer.
+
+  Subsequent calls to evbuffer_add_cb() add new callbacks.  To remove this
+  callback, call evbuffer_remove_cb or evbuffer_remove_cb_entry.
+
+  @param buffer the evbuffer to be monitored
+  @param cb the callback function to invoke when the evbuffer is modified,
+       or NULL to remove all callbacks.
+  @param cbarg an argument to be provided to the callback function
+  @return a handle to the callback on success, or NULL on failure.
+ */
+struct evbuffer_cb_entry *evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg);
+
+/** Remove a callback from an evbuffer, given a handle returned from
+    evbuffer_add_cb.
+
+    Calling this function invalidates the handle.
+
+    @return 0 if a callback was removed, or -1 if no matching callback was
+    found.
+ */
+int evbuffer_remove_cb_entry(struct evbuffer *buffer,
+                            struct evbuffer_cb_entry *ent);
+
+/** Remove a callback from an evbuffer, given the function and argument
+    used to add it.
+
+    @return 0 if a callback was removed, or -1 if no matching callback was
+    found.
+ */
+int evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg);
+
+/** If this flag is not set, then a callback is temporarily disabled, and
+ * should not be invoked.
+ *
+ * @see evbuffer_cb_set_flags(), evbuffer_cb_clear_flags()
+ */
+#define EVBUFFER_CB_ENABLED 1
+
+/** Change the flags that are set for a callback on a buffer by adding more.
+
+    @param buffer the evbuffer that the callback is watching.
+    @param cb the callback whose status we want to change.
+    @param flags EVBUFFER_CB_ENABLED to re-enable the callback.
+    @return 0 on success, -1 on failure.
+ */
+int evbuffer_cb_set_flags(struct evbuffer *buffer,
+                         struct evbuffer_cb_entry *cb, ev_uint32_t flags);
+
+/** Change the flags that are set for a callback on a buffer by removing some
+
+    @param buffer the evbuffer that the callback is watching.
+    @param cb the callback whose status we want to change.
+    @param flags EVBUFFER_CB_ENABLED to disable the callback.
+    @return 0 on success, -1 on failure.
+ */
+int evbuffer_cb_clear_flags(struct evbuffer *buffer,
+                         struct evbuffer_cb_entry *cb, ev_uint32_t flags);
+
+#if 0
+/** Postpone calling a given callback until unsuspend is called later.
+
+    This is different from disabling the callback, since the callback will get
+       invoked later if the buffer size changes between now and when we unsuspend
+       it.
+
+       @param the buffer that the callback is watching.
+       @param cb the callback we want to suspend.
+ */
+void evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb);
+/** Stop postponing a callback that we postponed with evbuffer_cb_suspend.
+
+       If data was added to or removed from the buffer while the callback was
+       suspended, the callback will get called once now.
+
+       @param the buffer that the callback is watching.
+       @param cb the callback we want to stop suspending.
+ */
+void evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb);
+#endif
+
+/**
+  Makes the data at the begging of an evbuffer contiguous.
+
+  @param buf the evbuffer to make contiguous
+  @param size the number of bytes to make contiguous, or -1 to make the
+       entire buffer contiguous.
+  @return a pointer to the contiguous memory array
+*/
+
+unsigned char *evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size);
+
+/**
+  Prepends data to the beginning of the evbuffer
+
+  @param buf the evbuffer to which to prepend data
+  @param data a pointer to the memory to prepend
+  @param size the number of bytes to prepend
+  @return 0 if successful, or -1 otherwise
+*/
+
+int evbuffer_prepend(struct evbuffer *buf, const void *data, size_t size);
+
+/**
+  Prepends all data from the src evbuffer to the beginning of the dst
+  evbuffer.
+
+  @param dst the evbuffer to which to prepend data
+  @param src the evbuffer to prepend; it will be emptied as a result
+  @return 0 if successful, or -1 otherwise
+*/
+int evbuffer_prepend_buffer(struct evbuffer *dst, struct evbuffer* src);
+
+/**
+   Prevent calls that modify an evbuffer from succeeding. A buffer may
+   frozen at the front, at the back, or at both the front and the back.
+
+   If the front of a buffer is frozen, operations that drain data from
+   the front of the buffer, or that prepend data to the buffer, will
+   fail until it is unfrozen.   If the back a buffer is frozen, operations
+   that append data from the buffer will fail until it is unfrozen.
+
+   @param buf The buffer to freeze
+   @param at_front If true, we freeze the front of the buffer.  If false,
+      we freeze the back.
+   @return 0 on success, -1 on failure.
+*/
+int evbuffer_freeze(struct evbuffer *buf, int at_front);
+/**
+   Re-enable calls that modify an evbuffer.
+
+   @param buf The buffer to un-freeze
+   @param at_front If true, we unfreeze the front of the buffer.  If false,
+      we unfreeze the back.
+   @return 0 on success, -1 on failure.
+ */
+int evbuffer_unfreeze(struct evbuffer *buf, int at_front);
+
+struct event_base;
+/**
+   Force all the callbacks on an evbuffer to be run, not immediately after
+   the evbuffer is altered, but instead from inside the event loop.
+
+   This can be used to serialize all the callbacks to a single thread
+   of execution.
+ */
+int evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_BUFFER_H_ */
diff --git a/libevent/include/event2/buffer_compat.h b/libevent/include/event2/buffer_compat.h
new file mode 100644 (file)
index 0000000..a713ee3
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _EVENT2_BUFFER_COMPAT_H_
+#define _EVENT2_BUFFER_COMPAT_H_
+
+/** @file event2/buffer_compat.h
+
+       Obsolete and deprecated versions of the functions in buffer.h: provided
+       only for backward compatibility.
+ */
+
+
+/**
+   Obsolete alias for evbuffer_readln(buffer, NULL, EOL_STYLE_ANY).
+
+   @deprecated This function is deprecated because its behavior is not correct
+      for almost any protocol, and also because it's wholly subsumed by
+      evbuffer_readln().
+
+   @param buffer the evbuffer to read from
+   @return pointer to a single line, or NULL if an error occurred
+
+*/
+char *evbuffer_readline(struct evbuffer *buffer);
+
+/** Type definition for a callback that is invoked whenever data is added or
+    removed from an evbuffer.
+
+    An evbuffer may have one or more callbacks set at a time.  The order
+    in which they are executed is undefined.
+
+    A callback function may add more callbacks, or remove itself from the
+    list of callbacks, or add or remove data from the buffer.  It may not
+    remove another callback from the list.
+
+    If a callback adds or removes data from the buffer or from another
+    buffer, this can cause a recursive invocation of your callback or
+    other callbacks.  If you ask for an infinite loop, you might just get
+    one: watch out!
+
+    @param buffer the buffer whose size has changed
+    @param old_len the previous length of the buffer
+    @param new_len the current length of the buffer
+    @param arg a pointer to user data
+*/
+typedef void (*evbuffer_cb)(struct evbuffer *buffer, size_t old_len, size_t new_len, void *arg);
+
+/**
+  Replace all callbacks on an evbuffer with a single new callback, or
+  remove them.
+
+  Subsequent calls to evbuffer_setcb() replace callbacks set by previous
+  calls.  Setting the callback to NULL removes any previously set callback.
+
+  @deprecated This function is deprecated because it clears all previous
+     callbacks set on the evbuffer, which can cause confusing behavior if
+     multiple parts of the code all want to add their own callbacks on a
+     buffer.  Instead, use evbuffer_add(), evbuffer_del(), and
+     evbuffer_setflags() to manage your own evbuffer callbacks without
+     interfering with callbacks set by others.
+
+  @param buffer the evbuffer to be monitored
+  @param cb the callback function to invoke when the evbuffer is modified,
+        or NULL to remove all callbacks.
+  @param cbarg an argument to be provided to the callback function
+ */
+void evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg);
+
+
+/**
+  Find a string within an evbuffer.
+
+  @param buffer the evbuffer to be searched
+  @param what the string to be searched for
+  @param len the length of the search string
+  @return a pointer to the beginning of the search string, or NULL if the search failed.
+ */
+unsigned char *evbuffer_find(struct evbuffer *buffer, const unsigned char *what, size_t len);
+
+/** deprecated in favor of calling the functions directly */
+#define EVBUFFER_LENGTH(x)     evbuffer_get_length(x)
+/** deprecated in favor of calling the functions directly */
+#define EVBUFFER_DATA(x)       evbuffer_pullup((x), -1)
+
+#endif
+
diff --git a/libevent/include/event2/bufferevent.h b/libevent/include/event2/bufferevent.h
new file mode 100644 (file)
index 0000000..f3d8b1a
--- /dev/null
@@ -0,0 +1,821 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_BUFFEREVENT_H_
+#define _EVENT2_BUFFEREVENT_H_
+
+/**
+   @file event2/bufferevent.h
+
+  Functions for buffering data for network sending or receiving.  Bufferevents
+  are higher level than evbuffers: each has an underlying evbuffer for reading
+  and one for writing, and callbacks that are invoked under certain
+  circumstances.
+
+  A bufferevent provides input and output buffers that get filled and
+  drained automatically.  The user of a bufferevent no longer deals
+  directly with the I/O, but instead is reading from input and writing
+  to output buffers.
+
+  Once initialized, the bufferevent structure can be used repeatedly
+  with bufferevent_enable() and bufferevent_disable().
+
+  When reading is enabled, the bufferevent will try to read from the
+  file descriptor onto its input buffer, and and call the read callback.
+  When writing is enabled, the bufferevent will try to write data onto its
+  file descriptor when writing is enabled, and call the write callback
+  when the output buffer is sufficiently drained.
+
+  Bufferevents come in several flavors, including:
+
+  <dl>
+    <dt>Socket-based bufferevents</dt>
+      <dd>A bufferevent that reads and writes data onto a network
+          socket. Created with bufferevent_socket_new().</dd>
+
+    <dt>Paired bufferevents</dt>
+      <dd>A pair of bufferevents that send and receive data to one
+          another without touching the network.  Created with
+          bufferevent_pair_new().</dd>
+
+    <dt>Filtering bufferevents</dt>
+       <dd>A bufferevent that transforms data, and sends or receives it
+          over another underlying bufferevent.  Created with
+          bufferevent_filter_new().</dd>
+
+    <dt>SSL-backed bufferevents</dt>
+      <dd>A bufferevent that uses the openssl library to send and
+          receive data over an encrypted connection. Created with
+         bufferevent_openssl_socket_new() or
+         bufferevent_openssl_filter_new().</dd>
+  </dl>
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/** @name Bufferevent event codes
+
+    These flags are passed as arguments to a bufferevent's event callback.
+
+    @{
+*/
+#define BEV_EVENT_READING      0x01    /**< error encountered while reading */
+#define BEV_EVENT_WRITING      0x02    /**< error encountered while writing */
+#define BEV_EVENT_EOF          0x10    /**< eof file reached */
+#define BEV_EVENT_ERROR                0x20    /**< unrecoverable error encountered */
+#define BEV_EVENT_TIMEOUT      0x40    /**< user-specified timeout reached */
+#define BEV_EVENT_CONNECTED    0x80    /**< connect operation finished. */
+/**@}*/
+
+/**
+   An opaque type for handling buffered IO
+
+   @see event2/bufferevent.h
+ */
+struct bufferevent
+#ifdef _EVENT_IN_DOXYGEN
+{}
+#endif
+;
+struct event_base;
+struct evbuffer;
+struct sockaddr;
+
+/**
+   A read or write callback for a bufferevent.
+
+   The read callback is triggered when new data arrives in the input
+   buffer and the amount of readable data exceed the low watermark
+   which is 0 by default.
+
+   The write callback is triggered if the write buffer has been
+   exhausted or fell below its low watermark.
+
+   @param bev the bufferevent that triggered the callback
+   @param ctx the user-specified context for this bufferevent
+ */
+typedef void (*bufferevent_data_cb)(struct bufferevent *bev, void *ctx);
+
+/**
+   An event/error callback for a bufferevent.
+
+   The event callback is triggered if either an EOF condition or another
+   unrecoverable error was encountered.
+
+   @param bev the bufferevent for which the error condition was reached
+   @param what a conjunction of flags: BEV_EVENT_READING or BEV_EVENT_WRITING
+         to indicate if the error was encountered on the read or write path,
+         and one of the following flags: BEV_EVENT_EOF, BEV_EVENT_ERROR,
+         BEV_EVENT_TIMEOUT, BEV_EVENT_CONNECTED.
+
+   @param ctx the user-specified context for this bufferevent
+*/
+typedef void (*bufferevent_event_cb)(struct bufferevent *bev, short what, void *ctx);
+
+/** Options that can be specified when creating a bufferevent */
+enum bufferevent_options {
+       /** If set, we close the underlying file
+        * descriptor/bufferevent/whatever when this bufferevent is freed. */
+       BEV_OPT_CLOSE_ON_FREE = (1<<0),
+
+       /** If set, and threading is enabled, operations on this bufferevent
+        * are protected by a lock */
+       BEV_OPT_THREADSAFE = (1<<1),
+
+       /** If set, callbacks are run deferred in the event loop. */
+       BEV_OPT_DEFER_CALLBACKS = (1<<2),
+
+       /** If set, callbacks are executed without locks being held on the
+       * bufferevent.  This option currently requires that
+       * BEV_OPT_DEFER_CALLBACKS also be set; a future version of Libevent
+       * might remove the requirement.*/
+       BEV_OPT_UNLOCK_CALLBACKS = (1<<3)
+};
+
+/**
+  Create a new socket bufferevent over an existing socket.
+
+  @param base the event base to associate with the new bufferevent.
+  @param fd the file descriptor from which data is read and written to.
+           This file descriptor is not allowed to be a pipe(2).
+           It is safe to set the fd to -1, so long as you later
+           set it with bufferevent_setfd or bufferevent_socket_connect().
+  @param options Zero or more BEV_OPT_* flags
+  @return a pointer to a newly allocated bufferevent struct, or NULL if an
+         error occurred
+  @see bufferevent_free()
+  */
+struct bufferevent *bufferevent_socket_new(struct event_base *base, evutil_socket_t fd, int options);
+
+/**
+   Launch a connect() attempt with a socket-based bufferevent.
+
+   When the connect succeeds, the eventcb will be invoked with
+   BEV_EVENT_CONNECTED set.
+
+   If the bufferevent does not already have a socket set, we allocate a new
+   socket here and make it nonblocking before we begin.
+
+   If no address is provided, we assume that the socket is already connecting,
+   and configure the bufferevent so that a BEV_EVENT_CONNECTED event will be
+   yielded when it is done connecting.
+
+   @param bufev an existing bufferevent allocated with
+       bufferevent_socket_new().
+   @param addr the address we should connect to
+   @param socklen The length of the address
+   @return 0 on success, -1 on failure.
+ */
+int bufferevent_socket_connect(struct bufferevent *, struct sockaddr *, int);
+
+struct evdns_base;
+/**
+   Resolve the hostname 'hostname' and connect to it as with
+   bufferevent_socket_connect().
+
+   @param bufev An existing bufferevent allocated with bufferevent_socket_new()
+   @param evdns_base Optionally, an evdns_base to use for resolving hostnames
+      asynchronously. May be set to NULL for a blocking resolve.
+   @param family A preferred address family to resolve addresses to, or
+      AF_UNSPEC for no preference.  Only AF_INET, AF_INET6, and AF_UNSPEC are
+      supported.
+   @param hostname The hostname to resolve; see below for notes on recognized
+      formats
+   @param port The port to connect to on the resolved address.
+   @return 0 if successful, -1 on failure.
+
+   Recognized hostname formats are:
+
+       www.example.com (hostname)
+       1.2.3.4         (ipv4address)
+       ::1             (ipv6address)
+       [::1]           ([ipv6address])
+
+   Performance note: If you do not provide an evdns_base, this function
+   may block while it waits for a DNS response.         This is probably not
+   what you want.
+ */
+int bufferevent_socket_connect_hostname(struct bufferevent *,
+    struct evdns_base *, int, const char *, int);
+
+/**
+   Return the error code for the last failed DNS lookup attempt made by
+   bufferevent_socket_connect_hostname().
+
+   @param bev The bufferevent object.
+   @return DNS error code.
+   @see evutil_gai_strerror()
+*/
+int bufferevent_socket_get_dns_error(struct bufferevent *bev);
+
+/**
+  Assign a bufferevent to a specific event_base.
+
+  NOTE that only socket bufferevents support this function.
+
+  @param base an event_base returned by event_init()
+  @param bufev a bufferevent struct returned by bufferevent_new()
+     or bufferevent_socket_new()
+  @return 0 if successful, or -1 if an error occurred
+  @see bufferevent_new()
+ */
+int bufferevent_base_set(struct event_base *base, struct bufferevent *bufev);
+
+/**
+   Return the event_base used by a bufferevent
+*/
+struct event_base *bufferevent_get_base(struct bufferevent *bev);
+
+/**
+  Assign a priority to a bufferevent.
+
+  Only supported for socket bufferevents.
+
+  @param bufev a bufferevent struct
+  @param pri the priority to be assigned
+  @return 0 if successful, or -1 if an error occurred
+  */
+int bufferevent_priority_set(struct bufferevent *bufev, int pri);
+
+
+/**
+  Deallocate the storage associated with a bufferevent structure.
+
+  @param bufev the bufferevent structure to be freed.
+  */
+void bufferevent_free(struct bufferevent *bufev);
+
+
+/**
+  Changes the callbacks for a bufferevent.
+
+  @param bufev the bufferevent object for which to change callbacks
+  @param readcb callback to invoke when there is data to be read, or NULL if
+        no callback is desired
+  @param writecb callback to invoke when the file descriptor is ready for
+        writing, or NULL if no callback is desired
+  @param eventcb callback to invoke when there is an event on the file
+        descriptor
+  @param cbarg an argument that will be supplied to each of the callbacks
+        (readcb, writecb, and errorcb)
+  @see bufferevent_new()
+  */
+void bufferevent_setcb(struct bufferevent *bufev,
+    bufferevent_data_cb readcb, bufferevent_data_cb writecb,
+    bufferevent_event_cb eventcb, void *cbarg);
+
+/**
+  Changes the file descriptor on which the bufferevent operates.
+  Not supported for all bufferevent types.
+
+  @param bufev the bufferevent object for which to change the file descriptor
+  @param fd the file descriptor to operate on
+*/
+int bufferevent_setfd(struct bufferevent *bufev, evutil_socket_t fd);
+
+/**
+   Returns the file descriptor associated with a bufferevent, or -1 if
+   no file descriptor is associated with the bufferevent.
+ */
+evutil_socket_t bufferevent_getfd(struct bufferevent *bufev);
+
+/**
+   Returns the underlying bufferevent associated with a bufferevent (if
+   the bufferevent is a wrapper), or NULL if there is no underlying bufferevent.
+ */
+struct bufferevent *bufferevent_get_underlying(struct bufferevent *bufev);
+
+/**
+  Write data to a bufferevent buffer.
+
+  The bufferevent_write() function can be used to write data to the file
+  descriptor.  The data is appended to the output buffer and written to the
+  descriptor automatically as it becomes available for writing.
+
+  @param bufev the bufferevent to be written to
+  @param data a pointer to the data to be written
+  @param size the length of the data, in bytes
+  @return 0 if successful, or -1 if an error occurred
+  @see bufferevent_write_buffer()
+  */
+int bufferevent_write(struct bufferevent *bufev,
+    const void *data, size_t size);
+
+
+/**
+  Write data from an evbuffer to a bufferevent buffer. The evbuffer is
+  being drained as a result.
+
+  @param bufev the bufferevent to be written to
+  @param buf the evbuffer to be written
+  @return 0 if successful, or -1 if an error occurred
+  @see bufferevent_write()
+ */
+int bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf);
+
+
+/**
+  Read data from a bufferevent buffer.
+
+  The bufferevent_read() function is used to read data from the input buffer.
+
+  @param bufev the bufferevent to be read from
+  @param data pointer to a buffer that will store the data
+  @param size the size of the data buffer, in bytes
+  @return the amount of data read, in bytes.
+ */
+size_t bufferevent_read(struct bufferevent *bufev, void *data, size_t size);
+
+/**
+  Read data from a bufferevent buffer into an evbuffer.         This avoids
+  memory copies.
+
+  @param bufev the bufferevent to be read from
+  @param buf the evbuffer to which to add data
+  @return 0 if successful, or -1 if an error occurred.
+ */
+int bufferevent_read_buffer(struct bufferevent *bufev, struct evbuffer *buf);
+
+/**
+   Returns the input buffer.
+
+   The user MUST NOT set the callback on this buffer.
+
+   @param bufev the bufferevent from which to get the evbuffer
+   @return the evbuffer object for the input buffer
+ */
+
+struct evbuffer *bufferevent_get_input(struct bufferevent *bufev);
+
+/**
+   Returns the output buffer.
+
+   The user MUST NOT set the callback on this buffer.
+
+   When filters are being used, the filters need to be manually
+   triggered if the output buffer was manipulated.
+
+   @param bufev the bufferevent from which to get the evbuffer
+   @return the evbuffer object for the output buffer
+ */
+
+struct evbuffer *bufferevent_get_output(struct bufferevent *bufev);
+
+/**
+  Enable a bufferevent.
+
+  @param bufev the bufferevent to be enabled
+  @param event any combination of EV_READ | EV_WRITE.
+  @return 0 if successful, or -1 if an error occurred
+  @see bufferevent_disable()
+ */
+int bufferevent_enable(struct bufferevent *bufev, short event);
+
+/**
+  Disable a bufferevent.
+
+  @param bufev the bufferevent to be disabled
+  @param event any combination of EV_READ | EV_WRITE.
+  @return 0 if successful, or -1 if an error occurred
+  @see bufferevent_enable()
+ */
+int bufferevent_disable(struct bufferevent *bufev, short event);
+
+/**
+   Return the events that are enabled on a given bufferevent.
+
+   @param bufev the bufferevent to inspect
+   @return A combination of EV_READ | EV_WRITE
+ */
+short bufferevent_get_enabled(struct bufferevent *bufev);
+
+/**
+  Set the read and write timeout for a bufferevent.
+
+  A bufferevent's timeout will fire the first time that the indicated
+  amount of time has elapsed since a successful read or write operation,
+  during which the bufferevent was trying to read or write.
+
+  (In other words, if reading or writing is disabled, or if the
+  bufferevent's read or write operation has been suspended because
+  there's no data to write, or not enough banwidth, or so on, the
+  timeout isn't active.  The timeout only becomes active when we we're
+  willing to actually read or write.)
+
+  Calling bufferevent_enable or setting a timeout for a bufferevent
+  whose timeout is already pending resets its timeout.
+
+  If the timeout elapses, the corresponding operation (EV_READ or
+  EV_WRITE) becomes disabled until you re-enable it again.  The
+  bufferevent's event callback is called with the
+  BEV_EVENT_TIMEOUT|BEV_EVENT_READING or
+  BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING.
+
+  @param bufev the bufferevent to be modified
+  @param timeout_read the read timeout, or NULL
+  @param timeout_write the write timeout, or NULL
+ */
+int bufferevent_set_timeouts(struct bufferevent *bufev,
+    const struct timeval *timeout_read, const struct timeval *timeout_write);
+
+/**
+  Sets the watermarks for read and write events.
+
+  On input, a bufferevent does not invoke the user read callback unless
+  there is at least low watermark data in the buffer.  If the read buffer
+  is beyond the high watermark, the bufferevent stops reading from the network.
+
+  On output, the user write callback is invoked whenever the buffered data
+  falls below the low watermark.  Filters that write to this bufev will try
+  not to write more bytes to this buffer than the high watermark would allow,
+  except when flushing.
+
+  @param bufev the bufferevent to be modified
+  @param events EV_READ, EV_WRITE or both
+  @param lowmark the lower watermark to set
+  @param highmark the high watermark to set
+*/
+
+void bufferevent_setwatermark(struct bufferevent *bufev, short events,
+    size_t lowmark, size_t highmark);
+
+/**
+   Acquire the lock on a bufferevent.  Has no effect if locking was not
+   enabled with BEV_OPT_THREADSAFE.
+ */
+void bufferevent_lock(struct bufferevent *bufev);
+
+/**
+   Release the lock on a bufferevent.  Has no effect if locking was not
+   enabled with BEV_OPT_THREADSAFE.
+ */
+void bufferevent_unlock(struct bufferevent *bufev);
+
+/**
+   Flags that can be passed into filters to let them know how to
+   deal with the incoming data.
+*/
+enum bufferevent_flush_mode {
+       /** usually set when processing data */
+       BEV_NORMAL = 0,
+
+       /** want to checkpoint all data sent. */
+       BEV_FLUSH = 1,
+
+       /** encountered EOF on read or done sending data */
+       BEV_FINISHED = 2
+};
+
+/**
+   Triggers the bufferevent to produce more data if possible.
+
+   @param bufev the bufferevent object
+   @param iotype either EV_READ or EV_WRITE or both.
+   @param mode either BEV_NORMAL or BEV_FLUSH or BEV_FINISHED
+   @return -1 on failure, 0 if no data was produces, 1 if data was produced
+ */
+int bufferevent_flush(struct bufferevent *bufev,
+    short iotype,
+    enum bufferevent_flush_mode mode);
+
+/**
+   @name Filtering support
+
+   @{
+*/
+/**
+   Values that filters can return.
+ */
+enum bufferevent_filter_result {
+       /** everything is okay */
+       BEV_OK = 0,
+
+       /** the filter needs to read more data before output */
+       BEV_NEED_MORE = 1,
+
+       /** the filter encountered a critical error, no further data
+           can be processed. */
+       BEV_ERROR = 2
+};
+
+/** A callback function to implement a filter for a bufferevent.
+
+    @param src An evbuffer to drain data from.
+    @param dst An evbuffer to add data to.
+    @param limit A suggested upper bound of bytes to write to dst.
+       The filter may ignore this value, but doing so means that
+       it will overflow the high-water mark associated with dst.
+       -1 means "no limit".
+    @param mode Whether we should write data as may be convenient
+       (BEV_NORMAL), or flush as much data as we can (BEV_FLUSH),
+       or flush as much as we can, possibly including an end-of-stream
+       marker (BEV_FINISH).
+    @param ctx A user-supplied pointer.
+
+    @return BEV_OK if we wrote some data; BEV_NEED_MORE if we can't
+       produce any more output until we get some input; and BEV_ERROR
+       on an error.
+ */
+typedef enum bufferevent_filter_result (*bufferevent_filter_cb)(
+    struct evbuffer *src, struct evbuffer *dst, ev_ssize_t dst_limit,
+    enum bufferevent_flush_mode mode, void *ctx);
+
+/**
+   Allocate a new filtering bufferevent on top of an existing bufferevent.
+
+   @param underlying the underlying bufferevent.
+   @param input_filter The filter to apply to data we read from the underlying
+     bufferevent
+   @param output_filter The filer to apply to data we write to the underlying
+     bufferevent
+   @param options A bitfield of bufferevent options.
+   @param free_context A function to use to free the filter context when
+     this bufferevent is freed.
+   @param ctx A context pointer to pass to the filter functions.
+ */
+struct bufferevent *
+bufferevent_filter_new(struct bufferevent *underlying,
+                      bufferevent_filter_cb input_filter,
+                      bufferevent_filter_cb output_filter,
+                      int options,
+                      void (*free_context)(void *),
+                      void *ctx);
+/**@}*/
+
+/**
+   Allocate a pair of linked bufferevents.  The bufferevents behave as would
+   two bufferevent_sock instances connected to opposite ends of a
+   socketpair(), except that no internal socketpair is allocated.
+
+   @param base The event base to associate with the socketpair.
+   @param options A set of options for this bufferevent
+   @param pair A pointer to an array to hold the two new bufferevent objects.
+   @return 0 on success, -1 on failure.
+ */
+int bufferevent_pair_new(struct event_base *base, int options,
+    struct bufferevent *pair[2]);
+
+/**
+   Given one bufferevent returned by bufferevent_pair_new(), returns the
+   other one if it still exists.  Otherwise returns NULL.
+ */
+struct bufferevent *bufferevent_pair_get_partner(struct bufferevent *bev);
+
+/**
+   Abstract type used to configure rate-limiting on a bufferevent or a group
+   of bufferevents.
+ */
+struct ev_token_bucket_cfg;
+
+/**
+   A group of bufferevents which are configured to respect the same rate
+   limit.
+*/
+struct bufferevent_rate_limit_group;
+
+/** Maximum configurable rate- or burst-limit. */
+#define EV_RATE_LIMIT_MAX EV_SSIZE_MAX
+
+/**
+   Initialize and return a new object to configure the rate-limiting behavior
+   of bufferevents.
+
+   @param read_rate The maximum number of bytes to read per tick on
+     average.
+   @param read_burst The maximum number of bytes to read in any single tick.
+   @param write_rate The maximum number of bytes to write per tick on
+     average.
+   @param write_burst The maximum number of bytes to write in any single tick.
+   @param tick_len The length of a single tick.         Defaults to one second.
+     Any fractions of a millisecond are ignored.
+
+   Note that all rate-limits hare are currently best-effort: future versions
+   of Libevent may implement them more tightly.
+ */
+struct ev_token_bucket_cfg *ev_token_bucket_cfg_new(
+       size_t read_rate, size_t read_burst,
+       size_t write_rate, size_t write_burst,
+       const struct timeval *tick_len);
+
+/** Free all storage held in 'cfg'.
+
+    Note: 'cfg' is not currently reference-counted; it is not safe to free it
+    until no bufferevent is using it.
+ */
+void ev_token_bucket_cfg_free(struct ev_token_bucket_cfg *cfg);
+
+/**
+   Set the rate-limit of a the bufferevent 'bev' to the one specified in
+   'cfg'.  If 'cfg' is NULL, disable any per-bufferevent rate-limiting on
+   'bev'.
+
+   Note that only some bufferevent types currently respect rate-limiting.
+   They are: socket-based bufferevents (normal and IOCP-based), and SSL-based
+   bufferevents.
+
+   Return 0 on sucess, -1 on failure.
+ */
+int bufferevent_set_rate_limit(struct bufferevent *bev,
+    struct ev_token_bucket_cfg *cfg);
+
+/**
+   Create a new rate-limit group for bufferevents.  A rate-limit group
+   constrains the maximum number of bytes sent and received, in toto,
+   by all of its bufferevents.
+
+   @param base An event_base to run any necessary timeouts for the group.
+      Note that all bufferevents in the group do not necessarily need to share
+      this event_base.
+   @param cfg The rate-limit for this group.
+
+   Note that all rate-limits hare are currently best-effort: future versions
+   of Libevent may implement them more tightly.
+
+   Note also that only some bufferevent types currently respect rate-limiting.
+   They are: socket-based bufferevents (normal and IOCP-based), and SSL-based
+   bufferevents.
+ */
+struct bufferevent_rate_limit_group *bufferevent_rate_limit_group_new(
+       struct event_base *base,
+       const struct ev_token_bucket_cfg *cfg);
+/**
+   Change the rate-limiting settings for a given rate-limiting group.
+
+   Return 0 on success, -1 on failure.
+*/
+int bufferevent_rate_limit_group_set_cfg(
+       struct bufferevent_rate_limit_group *,
+       const struct ev_token_bucket_cfg *);
+
+/**
+   Change the smallest quantum we're willing to allocate to any single
+   bufferevent in a group for reading or writing at a time.
+
+   The rationale is that, because of TCP/IP protocol overheads and kernel
+   behavior, if a rate-limiting group is so tight on bandwidth that you're
+   only willing to send 1 byte per tick per bufferevent, you might instead
+   want to batch up the reads and writes so that you send N bytes per
+   1/N of the bufferevents (chosen at random) each tick, so you still wind
+   up send 1 byte per tick per bufferevent on average, but you don't send
+   so many tiny packets.
+
+   The default min-share is currently 64 bytes.
+
+   Returns 0 on success, -1 on faulre.
+ */
+int bufferevent_rate_limit_group_set_min_share(
+       struct bufferevent_rate_limit_group *, size_t);
+
+/**
+   Free a rate-limiting group.  The group must have no members when
+   this function is called.
+*/
+void bufferevent_rate_limit_group_free(struct bufferevent_rate_limit_group *);
+
+/**
+   Add 'bev' to the list of bufferevents whose aggregate reading and writing
+   is restricted by 'g'.  If 'g' is NULL, remove 'bev' from its current group.
+
+   A bufferevent may belong to no more than one rate-limit group at a time.
+   If 'bev' is already a member of a group, it will be removed from its old
+   group before being added to 'g'.
+
+   Return 0 on success and -1 on failure.
+ */
+int bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
+    struct bufferevent_rate_limit_group *g);
+
+/** Remove 'bev' from its current rate-limit group (if any). */
+int bufferevent_remove_from_rate_limit_group(struct bufferevent *bev);
+
+/**
+   @name Rate limit inspection
+
+   Return the current read or write bucket size for a bufferevent.
+   If it is not configured with a per-bufferevent ratelimit, return
+   EV_SSIZE_MAX.  This function does not inspect the group limit, if any.
+   Note that it can return a negative value if the bufferevent has been
+   made to read or write more than its limit.
+
+   @{
+ */
+ev_ssize_t bufferevent_get_read_limit(struct bufferevent *bev);
+ev_ssize_t bufferevent_get_write_limit(struct bufferevent *bev);
+/*@}*/
+
+ev_ssize_t bufferevent_get_max_to_read(struct bufferevent *bev);
+ev_ssize_t bufferevent_get_max_to_write(struct bufferevent *bev);
+
+/**
+   @name GrouprRate limit inspection
+
+   Return the read or write bucket size for a bufferevent rate limit
+   group.  Note that it can return a negative value if bufferevents in
+   the group have been made to read or write more than their limits.
+
+   @{
+ */
+ev_ssize_t bufferevent_rate_limit_group_get_read_limit(
+       struct bufferevent_rate_limit_group *);
+ev_ssize_t bufferevent_rate_limit_group_get_write_limit(
+       struct bufferevent_rate_limit_group *);
+/*@}*/
+
+/**
+   @name Rate limit manipulation
+
+   Subtract a number of bytes from a bufferevent's read or write bucket.
+   The decrement value can be negative, if you want to manually refill
+   the bucket. If the change puts the bucket above or below zero, the
+   bufferevent will resume or suspend reading writing as appropriate.
+   These functions make no change in the buckets for the bufferevent's
+   group, if any.
+
+   Returns 0 on success, -1 on internal error.
+
+   @{
+ */
+int bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr);
+int bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr);
+/*@}*/
+
+/**
+   @name Group rate limit manipulation
+
+   Subtract a number of bytes from a bufferevent rate-limiting group's
+   read or write bucket.  The decrement value can be negative, if you
+   want to manually refill the bucket. If the change puts the bucket
+   above or below zero, the bufferevents in the group will resume or
+   suspend reading writing as appropriate.
+
+   Returns 0 on success, -1 on internal error.
+
+   @{
+ */
+int bufferevent_rate_limit_group_decrement_read(
+       struct bufferevent_rate_limit_group *, ev_ssize_t);
+int bufferevent_rate_limit_group_decrement_write(
+       struct bufferevent_rate_limit_group *, ev_ssize_t);
+/*@}*/
+
+
+/**
+ * Inspect the total bytes read/written on a group.
+ *
+ * Set the variable pointed to by total_read_out to the total number of bytes
+ * ever read on grp, and the variable pointed to by total_written_out to the
+ * total number of bytes ever written on grp. */
+void bufferevent_rate_limit_group_get_totals(
+    struct bufferevent_rate_limit_group *grp,
+    ev_uint64_t *total_read_out, ev_uint64_t *total_written_out);
+
+/**
+ * Reset the total bytes read/written on a group.
+ *
+ * Reset the number of bytes read or written on grp as given by
+ * bufferevent_rate_limit_group_reset_totals(). */
+void
+bufferevent_rate_limit_group_reset_totals(
+       struct bufferevent_rate_limit_group *grp);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_BUFFEREVENT_H_ */
diff --git a/libevent/include/event2/bufferevent_compat.h b/libevent/include/event2/bufferevent_compat.h
new file mode 100644 (file)
index 0000000..3256fd1
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos, Nick Mathewson
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_BUFFEREVENT_COMPAT_H_
+#define _EVENT2_BUFFEREVENT_COMPAT_H_
+
+#define evbuffercb bufferevent_data_cb
+#define everrorcb bufferevent_event_cb
+
+/**
+  Create a new bufferevent for an fd.
+
+  This function is deprecated.  Use bufferevent_socket_new and
+  bufferevent_set_callbacks instead.
+
+  Libevent provides an abstraction on top of the regular event callbacks.
+  This abstraction is called a buffered event.  A buffered event provides
+  input and output buffers that get filled and drained automatically.  The
+  user of a buffered event no longer deals directly with the I/O, but
+  instead is reading from input and writing to output buffers.
+
+  Once initialized, the bufferevent structure can be used repeatedly with
+  bufferevent_enable() and bufferevent_disable().
+
+  When read enabled the bufferevent will try to read from the file descriptor
+  and call the read callback.  The write callback is executed whenever the
+  output buffer is drained below the write low watermark, which is 0 by
+  default.
+
+  If multiple bases are in use, bufferevent_base_set() must be called before
+  enabling the bufferevent for the first time.
+
+  @deprecated This function is deprecated because it uses the current
+    event base, and as such can be error prone for multithreaded programs.
+    Use bufferevent_socket_new() instead.
+
+  @param fd the file descriptor from which data is read and written to.
+        This file descriptor is not allowed to be a pipe(2).
+  @param readcb callback to invoke when there is data to be read, or NULL if
+        no callback is desired
+  @param writecb callback to invoke when the file descriptor is ready for
+        writing, or NULL if no callback is desired
+  @param errorcb callback to invoke when there is an error on the file
+        descriptor
+  @param cbarg an argument that will be supplied to each of the callbacks
+        (readcb, writecb, and errorcb)
+  @return a pointer to a newly allocated bufferevent struct, or NULL if an
+         error occurred
+  @see bufferevent_base_set(), bufferevent_free()
+  */
+struct bufferevent *bufferevent_new(evutil_socket_t fd,
+    evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
+
+
+/**
+  Set the read and write timeout for a buffered event.
+
+  @param bufev the bufferevent to be modified
+  @param timeout_read the read timeout
+  @param timeout_write the write timeout
+ */
+void bufferevent_settimeout(struct bufferevent *bufev,
+    int timeout_read, int timeout_write);
+
+#define EVBUFFER_READ          BEV_EVENT_READING
+#define EVBUFFER_WRITE         BEV_EVENT_WRITING
+#define EVBUFFER_EOF           BEV_EVENT_EOF
+#define EVBUFFER_ERROR         BEV_EVENT_ERROR
+#define EVBUFFER_TIMEOUT       BEV_EVENT_TIMEOUT
+
+/** macro for getting access to the input buffer of a bufferevent */
+#define EVBUFFER_INPUT(x)      bufferevent_get_input(x)
+/** macro for getting access to the output buffer of a bufferevent */
+#define EVBUFFER_OUTPUT(x)     bufferevent_get_output(x)
+
+#endif
diff --git a/libevent/include/event2/bufferevent_ssl.h b/libevent/include/event2/bufferevent_ssl.h
new file mode 100644 (file)
index 0000000..c612e99
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_BUFFEREVENT_SSL_H_
+#define _EVENT2_BUFFEREVENT_SSL_H_
+
+/** @file event2/bufferevent_ssl.h
+
+    OpenSSL support for bufferevents.
+ */
+
+#include <event2/event-config.h>
+#include <event2/bufferevent.h>
+#include <event2/util.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* This is what openssl's SSL objects are underneath. */
+struct ssl_st;
+
+/**
+   The state of an SSL object to be used when creating a new
+   SSL bufferevent.
+ */
+enum bufferevent_ssl_state {
+       BUFFEREVENT_SSL_OPEN = 0,
+       BUFFEREVENT_SSL_CONNECTING = 1,
+       BUFFEREVENT_SSL_ACCEPTING = 2
+};
+
+#if defined(_EVENT_HAVE_OPENSSL) || defined(_EVENT_IN_DOXYGEN)
+/**
+   Create a new SSL bufferevent to send its data over another bufferevent.
+
+   @param base An event_base to use to detect reading and writing.  It
+      must also be the base for the underlying bufferevent.
+   @param underlying A socket to use for this SSL
+   @param ssl A SSL* object from openssl.
+   @param state The current state of the SSL connection
+   @param options One or more bufferevent_options
+   @return A new bufferevent on success, or NULL on failure
+*/
+struct bufferevent *
+bufferevent_openssl_filter_new(struct event_base *base,
+    struct bufferevent *underlying,
+    struct ssl_st *ssl,
+    enum bufferevent_ssl_state state,
+    int options);
+
+/**
+   Create a new SSL bufferevent to send its data over an SSL * on a socket.
+
+   @param base An event_base to use to detect reading and writing
+   @param fd A socket to use for this SSL
+   @param ssl A SSL* object from openssl.
+   @param state The current state of the SSL connection
+   @param options One or more bufferevent_options
+   @return A new bufferevent on success, or NULL on failure.
+*/
+struct bufferevent *
+bufferevent_openssl_socket_new(struct event_base *base,
+    evutil_socket_t fd,
+    struct ssl_st *ssl,
+    enum bufferevent_ssl_state state,
+    int options);
+
+/** Return the underlying openssl SSL * object for an SSL bufferevent. */
+struct ssl_st *
+bufferevent_openssl_get_ssl(struct bufferevent *bufev);
+
+/** Tells a bufferevent to begin SSL renegotiation. */
+int bufferevent_ssl_renegotiate(struct bufferevent *bev);
+
+/** Return the most recent OpenSSL error reported on an SSL bufferevent. */
+unsigned long bufferevent_get_openssl_error(struct bufferevent *bev);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_BUFFEREVENT_SSL_H_ */
diff --git a/libevent/include/event2/bufferevent_struct.h b/libevent/include/event2/bufferevent_struct.h
new file mode 100644 (file)
index 0000000..02835c1
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_BUFFEREVENT_STRUCT_H_
+#define _EVENT2_BUFFEREVENT_STRUCT_H_
+
+/** @file event2/bufferevent_struct.h
+
+  Data structures for bufferevents.  Using these structures may hurt forward
+  compatibility with later versions of Libevent: be careful!
+
+  @deprecated Use of bufferevent_struct.h is completely deprecated; these
+    structures are only exposed for backward compatibility with programs
+    written before Libevent 2.0 that used them.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+/* For struct event */
+#include <event2/event_struct.h>
+
+struct event_watermark {
+       size_t low;
+       size_t high;
+};
+
+/**
+  Shared implementation of a bufferevent.
+
+  This type is exposed only because it was exposed in previous versions,
+  and some people's code may rely on manipulating it.  Otherwise, you
+  should really not rely on the layout, size, or contents of this structure:
+  it is fairly volatile, and WILL change in future versions of the code.
+**/
+struct bufferevent {
+       /** Event base for which this bufferevent was created. */
+       struct event_base *ev_base;
+       /** Pointer to a table of function pointers to set up how this
+           bufferevent behaves. */
+       const struct bufferevent_ops *be_ops;
+
+       /** A read event that triggers when a timeout has happened or a socket
+           is ready to read data.  Only used by some subtypes of
+           bufferevent. */
+       struct event ev_read;
+       /** A write event that triggers when a timeout has happened or a socket
+           is ready to write data.  Only used by some subtypes of
+           bufferevent. */
+       struct event ev_write;
+
+       /** An input buffer. Only the bufferevent is allowed to add data to
+           this buffer, though the user is allowed to drain it. */
+       struct evbuffer *input;
+
+       /** An input buffer. Only the bufferevent is allowed to drain data
+           from this buffer, though the user is allowed to add it. */
+       struct evbuffer *output;
+
+       struct event_watermark wm_read;
+       struct event_watermark wm_write;
+
+       bufferevent_data_cb readcb;
+       bufferevent_data_cb writecb;
+       /* This should be called 'eventcb', but renaming it would break
+        * backward compatibility */
+       bufferevent_event_cb errorcb;
+       void *cbarg;
+
+       struct timeval timeout_read;
+       struct timeval timeout_write;
+
+       /** Events that are currently enabled: currently EV_READ and EV_WRITE
+           are supported. */
+       short enabled;
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_BUFFEREVENT_STRUCT_H_ */
diff --git a/libevent/include/event2/dns.h b/libevent/include/event2/dns.h
new file mode 100644 (file)
index 0000000..ca0da3c
--- /dev/null
@@ -0,0 +1,643 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+/*
+ * The original DNS code is due to Adam Langley with heavy
+ * modifications by Nick Mathewson.  Adam put his DNS software in the
+ * public domain.  You can find his original copyright below.  Please,
+ * aware that the code as part of Libevent is governed by the 3-clause
+ * BSD license above.
+ *
+ * This software is Public Domain. To view a copy of the public domain dedication,
+ * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
+ * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
+ *
+ * I ask and expect, but do not require, that all derivative works contain an
+ * attribution similar to:
+ *     Parts developed by Adam Langley <agl@imperialviolet.org>
+ *
+ * You may wish to replace the word "Parts" with something else depending on
+ * the amount of original code.
+ *
+ * (Derivative works does not include programs which link against, run or include
+ * the source verbatim in their source distributions)
+ */
+
+/** @file event2/dns.h
+ *
+ * Welcome, gentle reader
+ *
+ * Async DNS lookups are really a whole lot harder than they should be,
+ * mostly stemming from the fact that the libc resolver has never been
+ * very good at them. Before you use this library you should see if libc
+ * can do the job for you with the modern async call getaddrinfo_a
+ * (see http://www.imperialviolet.org/page25.html#e498). Otherwise,
+ * please continue.
+ *
+ * The library keeps track of the state of nameservers and will avoid
+ * them when they go down. Otherwise it will round robin between them.
+ *
+ * Quick start guide:
+ *   #include "evdns.h"
+ *   void callback(int result, char type, int count, int ttl,
+ *              void *addresses, void *arg);
+ *   evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
+ *   evdns_resolve("www.hostname.com", 0, callback, NULL);
+ *
+ * When the lookup is complete the callback function is called. The
+ * first argument will be one of the DNS_ERR_* defines in evdns.h.
+ * Hopefully it will be DNS_ERR_NONE, in which case type will be
+ * DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
+ * which the data can be cached for (in seconds), addresses will point
+ * to an array of uint32_t's and arg will be whatever you passed to
+ * evdns_resolve.
+ *
+ * Searching:
+ *
+ * In order for this library to be a good replacement for glibc's resolver it
+ * supports searching. This involves setting a list of default domains, in
+ * which names will be queried for. The number of dots in the query name
+ * determines the order in which this list is used.
+ *
+ * Searching appears to be a single lookup from the point of view of the API,
+ * although many DNS queries may be generated from a single call to
+ * evdns_resolve. Searching can also drastically slow down the resolution
+ * of names.
+ *
+ * To disable searching:
+ *   1. Never set it up. If you never call evdns_resolv_conf_parse or
+ *   evdns_search_add then no searching will occur.
+ *
+ *   2. If you do call evdns_resolv_conf_parse then don't pass
+ *   DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it).
+ *
+ *   3. When calling evdns_resolve, pass the DNS_QUERY_NO_SEARCH flag.
+ *
+ * The order of searches depends on the number of dots in the name. If the
+ * number is greater than the ndots setting then the names is first tried
+ * globally. Otherwise each search domain is appended in turn.
+ *
+ * The ndots setting can either be set from a resolv.conf, or by calling
+ * evdns_search_ndots_set.
+ *
+ * For example, with ndots set to 1 (the default) and a search domain list of
+ * ["myhome.net"]:
+ *  Query: www
+ *  Order: www.myhome.net, www.
+ *
+ *  Query: www.abc
+ *  Order: www.abc., www.abc.myhome.net
+ *
+ * Internals:
+ *
+ * Requests are kept in two queues. The first is the inflight queue. In
+ * this queue requests have an allocated transaction id and nameserver.
+ * They will soon be transmitted if they haven't already been.
+ *
+ * The second is the waiting queue. The size of the inflight ring is
+ * limited and all other requests wait in waiting queue for space. This
+ * bounds the number of concurrent requests so that we don't flood the
+ * nameserver. Several algorithms require a full walk of the inflight
+ * queue and so bounding its size keeps thing going nicely under huge
+ * (many thousands of requests) loads.
+ *
+ * If a nameserver loses too many requests it is considered down and we
+ * try not to use it. After a while we send a probe to that nameserver
+ * (a lookup for google.com) and, if it replies, we consider it working
+ * again. If the nameserver fails a probe we wait longer to try again
+ * with the next probe.
+ */
+
+#ifndef _EVENT2_DNS_H_
+#define _EVENT2_DNS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* For integer types. */
+#include <event2/util.h>
+
+/** Error codes 0-5 are as described in RFC 1035. */
+#define DNS_ERR_NONE 0
+/** The name server was unable to interpret the query */
+#define DNS_ERR_FORMAT 1
+/** The name server was unable to process this query due to a problem with the
+ * name server */
+#define DNS_ERR_SERVERFAILED 2
+/** The domain name does not exist */
+#define DNS_ERR_NOTEXIST 3
+/** The name server does not support the requested kind of query */
+#define DNS_ERR_NOTIMPL 4
+/** The name server refuses to reform the specified operation for policy
+ * reasons */
+#define DNS_ERR_REFUSED 5
+/** The reply was truncated or ill-formatted */
+#define DNS_ERR_TRUNCATED 65
+/** An unknown error occurred */
+#define DNS_ERR_UNKNOWN 66
+/** Communication with the server timed out */
+#define DNS_ERR_TIMEOUT 67
+/** The request was canceled because the DNS subsystem was shut down. */
+#define DNS_ERR_SHUTDOWN 68
+/** The request was canceled via a call to evdns_cancel_request */
+#define DNS_ERR_CANCEL 69
+/** There were no answers and no error condition in the DNS packet.
+ * This can happen when you ask for an address that exists, but a record
+ * type that doesn't. */
+#define DNS_ERR_NODATA 70
+
+#define DNS_IPv4_A 1
+#define DNS_PTR 2
+#define DNS_IPv6_AAAA 3
+
+#define DNS_QUERY_NO_SEARCH 1
+
+#define DNS_OPTION_SEARCH 1
+#define DNS_OPTION_NAMESERVERS 2
+#define DNS_OPTION_MISC 4
+#define DNS_OPTION_HOSTSFILE 8
+#define DNS_OPTIONS_ALL 15
+
+/* Obsolete name for DNS_QUERY_NO_SEARCH */
+#define DNS_NO_SEARCH DNS_QUERY_NO_SEARCH
+
+/**
+ * The callback that contains the results from a lookup.
+ * - result is one of the DNS_ERR_* values (DNS_ERR_NONE for success)
+ * - type is either DNS_IPv4_A or DNS_PTR or DNS_IPv6_AAAA
+ * - count contains the number of addresses of form type
+ * - ttl is the number of seconds the resolution may be cached for.
+ * - addresses needs to be cast according to type.  It will be an array of
+ *   4-byte sequences for ipv4, or an array of 16-byte sequences for ipv6,
+ *   or a nul-terminated string for PTR.
+ */
+typedef void (*evdns_callback_type) (int result, char type, int count, int ttl, void *addresses, void *arg);
+
+struct evdns_base;
+struct event_base;
+
+/**
+  Initialize the asynchronous DNS library.
+
+  This function initializes support for non-blocking name resolution by
+  calling evdns_resolv_conf_parse() on UNIX and
+  evdns_config_windows_nameservers() on Windows.
+
+  @param event_base the event base to associate the dns client with
+  @param initialize_nameservers 1 if resolve.conf processing should occur
+  @return evdns_base object if successful, or NULL if an error occurred.
+  @see evdns_base_free()
+ */
+struct evdns_base * evdns_base_new(struct event_base *event_base, int initialize_nameservers);
+
+
+/**
+  Shut down the asynchronous DNS resolver and terminate all active requests.
+
+  If the 'fail_requests' option is enabled, all active requests will return
+  an empty result with the error flag set to DNS_ERR_SHUTDOWN. Otherwise,
+  the requests will be silently discarded.
+
+  @param evdns_base the evdns base to free
+  @param fail_requests if zero, active requests will be aborted; if non-zero,
+               active requests will return DNS_ERR_SHUTDOWN.
+  @see evdns_base_new()
+ */
+void evdns_base_free(struct evdns_base *base, int fail_requests);
+
+/**
+  Convert a DNS error code to a string.
+
+  @param err the DNS error code
+  @return a string containing an explanation of the error code
+*/
+const char *evdns_err_to_string(int err);
+
+
+/**
+  Add a nameserver.
+
+  The address should be an IPv4 address in network byte order.
+  The type of address is chosen so that it matches in_addr.s_addr.
+
+  @param base the evdns_base to which to add the name server
+  @param address an IP address in network byte order
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_base_nameserver_ip_add()
+ */
+int evdns_base_nameserver_add(struct evdns_base *base,
+    unsigned long int address);
+
+/**
+  Get the number of configured nameservers.
+
+  This returns the number of configured nameservers (not necessarily the
+  number of running nameservers).  This is useful for double-checking
+  whether our calls to the various nameserver configuration functions
+  have been successful.
+
+  @param base the evdns_base to which to apply this operation
+  @return the number of configured nameservers
+  @see evdns_base_nameserver_add()
+ */
+int evdns_base_count_nameservers(struct evdns_base *base);
+
+/**
+  Remove all configured nameservers, and suspend all pending resolves.
+
+  Resolves will not necessarily be re-attempted until evdns_base_resume() is called.
+
+  @param base the evdns_base to which to apply this operation
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_base_resume()
+ */
+int evdns_base_clear_nameservers_and_suspend(struct evdns_base *base);
+
+
+/**
+  Resume normal operation and continue any suspended resolve requests.
+
+  Re-attempt resolves left in limbo after an earlier call to
+  evdns_base_clear_nameservers_and_suspend().
+
+  @param base the evdns_base to which to apply this operation
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_base_clear_nameservers_and_suspend()
+ */
+int evdns_base_resume(struct evdns_base *base);
+
+/**
+  Add a nameserver by string address.
+
+  This function parses a n IPv4 or IPv6 address from a string and adds it as a
+  nameserver.  It supports the following formats:
+  - [IPv6Address]:port
+  - [IPv6Address]
+  - IPv6Address
+  - IPv4Address:port
+  - IPv4Address
+
+  If no port is specified, it defaults to 53.
+
+  @param base the evdns_base to which to apply this operation
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_base_nameserver_add()
+ */
+int evdns_base_nameserver_ip_add(struct evdns_base *base,
+    const char *ip_as_string);
+
+/**
+   Add a nameserver by sockaddr.
+ **/
+int
+evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
+    const struct sockaddr *sa, ev_socklen_t len, unsigned flags);
+
+struct evdns_request;
+
+/**
+  Lookup an A record for a given name.
+
+  @param base the evdns_base to which to apply this operation
+  @param name a DNS hostname
+  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+  @param callback a callback function to invoke when the request is completed
+  @param ptr an argument to pass to the callback function
+  @return an evdns_request object if successful, or NULL if an error occurred.
+  @see evdns_resolve_ipv6(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6(), evdns_cancel_request()
+ */
+struct evdns_request *evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+  Lookup an AAAA record for a given name.
+
+  @param base the evdns_base to which to apply this operation
+  @param name a DNS hostname
+  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+  @param callback a callback function to invoke when the request is completed
+  @param ptr an argument to pass to the callback function
+  @return an evdns_request object if successful, or NULL if an error occurred.
+  @see evdns_resolve_ipv4(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6(), evdns_cancel_request()
+ */
+struct evdns_request *evdns_base_resolve_ipv6(struct evdns_base *base, const char *name, int flags, evdns_callback_type callback, void *ptr);
+
+struct in_addr;
+struct in6_addr;
+
+/**
+  Lookup a PTR record for a given IP address.
+
+  @param base the evdns_base to which to apply this operation
+  @param in an IPv4 address
+  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+  @param callback a callback function to invoke when the request is completed
+  @param ptr an argument to pass to the callback function
+  @return an evdns_request object if successful, or NULL if an error occurred.
+  @see evdns_resolve_reverse_ipv6(), evdns_cancel_request()
+ */
+struct evdns_request *evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr);
+
+
+/**
+  Lookup a PTR record for a given IPv6 address.
+
+  @param base the evdns_base to which to apply this operation
+  @param in an IPv6 address
+  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+  @param callback a callback function to invoke when the request is completed
+  @param ptr an argument to pass to the callback function
+  @return an evdns_request object if successful, or NULL if an error occurred.
+  @see evdns_resolve_reverse_ipv6(), evdns_cancel_request()
+ */
+struct evdns_request *evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+  Cancels a pending DNS resolution request.
+
+  @param base the evdns_base that was used to make the request
+  @param req the evdns_request that was returned by calling a resolve function
+  @see evdns_base_resolve_ipv4(), evdns_base_resolve_ipv6, evdns_base_resolve_reverse
+*/
+void evdns_cancel_request(struct evdns_base *base, struct evdns_request *req);
+
+/**
+  Set the value of a configuration option.
+
+  The currently available configuration options are:
+
+    ndots, timeout, max-timeouts, max-inflight, attempts, randomize-case,
+    bind-to, initial-probe-timeout, getaddrinfo-allow-skew.
+
+  In versions before Libevent 2.0.3-alpha, the option name needed to end with
+  a colon.
+
+  @param base the evdns_base to which to apply this operation
+  @param option the name of the configuration option to be modified
+  @param val the value to be set
+  @return 0 if successful, or -1 if an error occurred
+ */
+int evdns_base_set_option(struct evdns_base *base, const char *option, const char *val);
+
+
+/**
+  Parse a resolv.conf file.
+
+  The 'flags' parameter determines what information is parsed from the
+  resolv.conf file. See the man page for resolv.conf for the format of this
+  file.
+
+  The following directives are not parsed from the file: sortlist, rotate,
+  no-check-names, inet6, debug.
+
+  If this function encounters an error, the possible return values are: 1 =
+  failed to open file, 2 = failed to stat file, 3 = file too large, 4 = out of
+  memory, 5 = short read from file, 6 = no nameservers listed in the file
+
+  @param base the evdns_base to which to apply this operation
+  @param flags any of DNS_OPTION_NAMESERVERS|DNS_OPTION_SEARCH|DNS_OPTION_MISC|
+    DNS_OPTIONS_HOSTSFILE|DNS_OPTIONS_ALL
+  @param filename the path to the resolv.conf file
+  @return 0 if successful, or various positive error codes if an error
+    occurred (see above)
+  @see resolv.conf(3), evdns_config_windows_nameservers()
+ */
+int evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename);
+
+/**
+   Load an /etc/hosts-style file from 'hosts_fname' into 'base'.
+
+   If hosts_fname is NULL, add minimal entries for localhost, and nothing
+   else.
+
+   Note that only evdns_getaddrinfo uses the /etc/hosts entries.
+
+   Return 0 on success, negative on failure.
+*/
+int evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname);
+
+/**
+  Obtain nameserver information using the Windows API.
+
+  Attempt to configure a set of nameservers based on platform settings on
+  a win32 host.  Preferentially tries to use GetNetworkParams; if that fails,
+  looks in the registry.
+
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_resolv_conf_parse()
+ */
+#ifdef WIN32
+int evdns_base_config_windows_nameservers(struct evdns_base *);
+#define EVDNS_BASE_CONFIG_WINDOWS_NAMESERVERS_IMPLEMENTED
+#endif
+
+
+/**
+  Clear the list of search domains.
+ */
+void evdns_base_search_clear(struct evdns_base *base);
+
+
+/**
+  Add a domain to the list of search domains
+
+  @param domain the domain to be added to the search list
+ */
+void evdns_base_search_add(struct evdns_base *base, const char *domain);
+
+
+/**
+  Set the 'ndots' parameter for searches.
+
+  Sets the number of dots which, when found in a name, causes
+  the first query to be without any search domain.
+
+  @param ndots the new ndots parameter
+ */
+void evdns_base_search_ndots_set(struct evdns_base *base, const int ndots);
+
+/**
+  A callback that is invoked when a log message is generated
+
+  @param is_warning indicates if the log message is a 'warning'
+  @param msg the content of the log message
+ */
+typedef void (*evdns_debug_log_fn_type)(int is_warning, const char *msg);
+
+
+/**
+  Set the callback function to handle DNS log messages.  If this
+  callback is not set, evdns log messages are handled with the regular
+  Libevent logging system.
+
+  @param fn the callback to be invoked when a log message is generated
+ */
+void evdns_set_log_fn(evdns_debug_log_fn_type fn);
+
+/**
+   Set a callback that will be invoked to generate transaction IDs.  By
+   default, we pick transaction IDs based on the current clock time, which
+   is bad for security.
+
+   @param fn the new callback, or NULL to use the default.
+
+   NOTE: This function has no effect in Libevent 2.0.4-alpha and later,
+   since Libevent now provides its own secure RNG.
+ */
+void evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void));
+
+/**
+   Set a callback used to generate random bytes.  By default, we use
+   the same function as passed to evdns_set_transaction_id_fn to generate
+   bytes two at a time.  If a function is provided here, it's also used
+   to generate transaction IDs.
+
+   NOTE: This function has no effect in Libevent 2.0.4-alpha and later,
+   since Libevent now provides its own secure RNG.
+*/
+void evdns_set_random_bytes_fn(void (*fn)(char *, size_t));
+
+/*
+ * Functions used to implement a DNS server.
+ */
+
+struct evdns_server_request;
+struct evdns_server_question;
+
+/**
+   A callback to implement a DNS server.  The callback function receives a DNS
+   request.  It should then optionally add a number of answers to the reply
+   using the evdns_server_request_add_*_reply functions, before calling either
+   evdns_server_request_respond to send the reply back, or
+   evdns_server_request_drop to decline to answer the request.
+
+   @param req A newly received request
+   @param user_data A pointer that was passed to
+      evdns_add_server_port_with_base().
+ */
+typedef void (*evdns_request_callback_fn_type)(struct evdns_server_request *, void *);
+#define EVDNS_ANSWER_SECTION 0
+#define EVDNS_AUTHORITY_SECTION 1
+#define EVDNS_ADDITIONAL_SECTION 2
+
+#define EVDNS_TYPE_A      1
+#define EVDNS_TYPE_NS     2
+#define EVDNS_TYPE_CNAME   5
+#define EVDNS_TYPE_SOA    6
+#define EVDNS_TYPE_PTR   12
+#define EVDNS_TYPE_MX    15
+#define EVDNS_TYPE_TXT   16
+#define EVDNS_TYPE_AAAA          28
+
+#define EVDNS_QTYPE_AXFR 252
+#define EVDNS_QTYPE_ALL         255
+
+#define EVDNS_CLASS_INET   1
+
+/* flags that can be set in answers; as part of the err parameter */
+#define EVDNS_FLAGS_AA 0x400
+#define EVDNS_FLAGS_RD 0x080
+
+/** Create a new DNS server port.
+
+    @param base The event base to handle events for the server port.
+    @param socket A UDP socket to accept DNS requests.
+    @param flags Always 0 for now.
+    @param callback A function to invoke whenever we get a DNS request
+      on the socket.
+    @param user_data Data to pass to the callback.
+    @return an evdns_server_port structure for this server port.
+ */
+struct evdns_server_port *evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type callback, void *user_data);
+/** Close down a DNS server port, and free associated structures. */
+void evdns_close_server_port(struct evdns_server_port *port);
+
+/** Sets some flags in a reply we're building.
+    Allows setting of the AA or RD flags
+ */
+void evdns_server_request_set_flags(struct evdns_server_request *req, int flags);
+
+/* Functions to add an answer to an in-progress DNS reply.
+ */
+int evdns_server_request_add_reply(struct evdns_server_request *req, int section, const char *name, int type, int dns_class, int ttl, int datalen, int is_name, const char *data);
+int evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl);
+int evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl);
+int evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl);
+int evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl);
+
+/**
+   Send back a response to a DNS request, and free the request structure.
+*/
+int evdns_server_request_respond(struct evdns_server_request *req, int err);
+/**
+   Free a DNS request without sending back a reply.
+*/
+int evdns_server_request_drop(struct evdns_server_request *req);
+struct sockaddr;
+/**
+    Get the address that made a DNS request.
+ */
+int evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len);
+
+/** Callback for evdns_getaddrinfo. */
+typedef void (*evdns_getaddrinfo_cb)(int result, struct evutil_addrinfo *res, void *arg);
+
+struct evdns_base;
+struct evdns_getaddrinfo_request;
+/** Make a non-blocking getaddrinfo request using the dns_base in 'dns_base'.
+ *
+ * If we can answer the request immediately (with an error or not!), then we
+ * invoke cb immediately and return NULL.  Otherwise we return
+ * an evdns_getaddrinfo_request and invoke cb later.
+ *
+ * When the callback is invoked, we pass as its first argument the error code
+ * that getaddrinfo would return (or 0 for no error).  As its second argument,
+ * we pass the evutil_addrinfo structures we found (or NULL on error).  We
+ * pass 'arg' as the third argument.
+ *
+ * Limitations:
+ *
+ * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
+ * - For ai_socktype, we only handle SOCKTYPE_STREAM, SOCKTYPE_UDP, and 0.
+ * - For ai_protocol, we only handle IPPROTO_TCP, IPPROTO_UDP, and 0.
+ */
+struct evdns_getaddrinfo_request *evdns_getaddrinfo(
+    struct evdns_base *dns_base,
+    const char *nodename, const char *servname,
+    const struct evutil_addrinfo *hints_in,
+    evdns_getaddrinfo_cb cb, void *arg);
+
+/* Cancel an in-progress evdns_getaddrinfo.  This MUST NOT be called after the
+ * getaddrinfo's callback has been invoked.  The resolves will be canceled,
+ * and the callback will be invoked with the error EVUTIL_EAI_CANCEL. */
+void evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *req);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* !_EVENT2_DNS_H_ */
diff --git a/libevent/include/event2/dns_compat.h b/libevent/include/event2/dns_compat.h
new file mode 100644 (file)
index 0000000..7c1c776
--- /dev/null
@@ -0,0 +1,336 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_DNS_COMPAT_H_
+#define _EVENT2_DNS_COMPAT_H_
+
+/** @file event2/dns_compat.h
+
+  Potentially non-threadsafe versions of the functions in dns.h: provided
+  only for backwards compatibility.
+
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+  Initialize the asynchronous DNS library.
+
+  This function initializes support for non-blocking name resolution by
+  calling evdns_resolv_conf_parse() on UNIX and
+  evdns_config_windows_nameservers() on Windows.
+
+  @deprecated This function is deprecated because it always uses the current
+    event base, and is easily confused by multiple calls to event_init(), and
+    so is not safe for multithreaded use.  Additionally, it allocates a global
+    structure that only one thread can use. The replacement is
+    evdns_base_new().
+
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_shutdown()
+ */
+int evdns_init(void);
+
+struct evdns_base;
+/**
+   Return the global evdns_base created by event_init() and used by the other
+   deprecated functions.
+
+   @deprecated This function is deprecated because use of the global
+     evdns_base is error-prone.
+ */
+struct evdns_base *evdns_get_global_base(void);
+
+/**
+  Shut down the asynchronous DNS resolver and terminate all active requests.
+
+  If the 'fail_requests' option is enabled, all active requests will return
+  an empty result with the error flag set to DNS_ERR_SHUTDOWN. Otherwise,
+  the requests will be silently discarded.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_shutdown().
+
+  @param fail_requests if zero, active requests will be aborted; if non-zero,
+               active requests will return DNS_ERR_SHUTDOWN.
+  @see evdns_init()
+ */
+void evdns_shutdown(int fail_requests);
+
+/**
+  Add a nameserver.
+
+  The address should be an IPv4 address in network byte order.
+  The type of address is chosen so that it matches in_addr.s_addr.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_nameserver_add().
+
+  @param address an IP address in network byte order
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_nameserver_ip_add()
+ */
+int evdns_nameserver_add(unsigned long int address);
+
+/**
+  Get the number of configured nameservers.
+
+  This returns the number of configured nameservers (not necessarily the
+  number of running nameservers).  This is useful for double-checking
+  whether our calls to the various nameserver configuration functions
+  have been successful.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_count_nameservers().
+
+  @return the number of configured nameservers
+  @see evdns_nameserver_add()
+ */
+int evdns_count_nameservers(void);
+
+/**
+  Remove all configured nameservers, and suspend all pending resolves.
+
+  Resolves will not necessarily be re-attempted until evdns_resume() is called.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_clear_nameservers_and_suspend().
+
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_resume()
+ */
+int evdns_clear_nameservers_and_suspend(void);
+
+/**
+  Resume normal operation and continue any suspended resolve requests.
+
+  Re-attempt resolves left in limbo after an earlier call to
+  evdns_clear_nameservers_and_suspend().
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_resume().
+
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_clear_nameservers_and_suspend()
+ */
+int evdns_resume(void);
+
+/**
+  Add a nameserver.
+
+  This wraps the evdns_nameserver_add() function by parsing a string as an IP
+  address and adds it as a nameserver.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_nameserver_ip_add().
+
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_nameserver_add()
+ */
+int evdns_nameserver_ip_add(const char *ip_as_string);
+
+/**
+  Lookup an A record for a given name.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_resolve_ipv4().
+
+  @param name a DNS hostname
+  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+  @param callback a callback function to invoke when the request is completed
+  @param ptr an argument to pass to the callback function
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_resolve_ipv6(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
+ */
+int evdns_resolve_ipv4(const char *name, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+  Lookup an AAAA record for a given name.
+
+  @param name a DNS hostname
+  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+  @param callback a callback function to invoke when the request is completed
+  @param ptr an argument to pass to the callback function
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_resolve_ipv4(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
+ */
+int evdns_resolve_ipv6(const char *name, int flags, evdns_callback_type callback, void *ptr);
+
+struct in_addr;
+struct in6_addr;
+
+/**
+  Lookup a PTR record for a given IP address.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_resolve_reverse().
+
+  @param in an IPv4 address
+  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+  @param callback a callback function to invoke when the request is completed
+  @param ptr an argument to pass to the callback function
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_resolve_reverse_ipv6()
+ */
+int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+  Lookup a PTR record for a given IPv6 address.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_resolve_reverse_ipv6().
+
+  @param in an IPv6 address
+  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+  @param callback a callback function to invoke when the request is completed
+  @param ptr an argument to pass to the callback function
+  @return 0 if successful, or -1 if an error occurred
+  @see evdns_resolve_reverse_ipv6()
+ */
+int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+  Set the value of a configuration option.
+
+  The currently available configuration options are:
+
+    ndots, timeout, max-timeouts, max-inflight, and attempts
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_set_option().
+
+  @param option the name of the configuration option to be modified
+  @param val the value to be set
+  @param flags Ignored.
+  @return 0 if successful, or -1 if an error occurred
+ */
+int evdns_set_option(const char *option, const char *val, int flags);
+
+/**
+  Parse a resolv.conf file.
+
+  The 'flags' parameter determines what information is parsed from the
+  resolv.conf file. See the man page for resolv.conf for the format of this
+  file.
+
+  The following directives are not parsed from the file: sortlist, rotate,
+  no-check-names, inet6, debug.
+
+  If this function encounters an error, the possible return values are: 1 =
+  failed to open file, 2 = failed to stat file, 3 = file too large, 4 = out of
+  memory, 5 = short read from file, 6 = no nameservers listed in the file
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_resolv_conf_parse().
+
+  @param flags any of DNS_OPTION_NAMESERVERS|DNS_OPTION_SEARCH|DNS_OPTION_MISC|
+    DNS_OPTIONS_ALL
+  @param filename the path to the resolv.conf file
+  @return 0 if successful, or various positive error codes if an error
+    occurred (see above)
+  @see resolv.conf(3), evdns_config_windows_nameservers()
+ */
+int evdns_resolv_conf_parse(int flags, const char *const filename);
+
+/**
+  Clear the list of search domains.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_search_clear().
+ */
+void evdns_search_clear(void);
+
+/**
+  Add a domain to the list of search domains
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_search_add().
+
+  @param domain the domain to be added to the search list
+ */
+void evdns_search_add(const char *domain);
+
+/**
+  Set the 'ndots' parameter for searches.
+
+  Sets the number of dots which, when found in a name, causes
+  the first query to be without any search domain.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which evdns_base it applies to.  The recommended
+    function is evdns_base_search_ndots_set().
+
+  @param ndots the new ndots parameter
+ */
+void evdns_search_ndots_set(const int ndots);
+
+/**
+   As evdns_server_new_with_base.
+
+  @deprecated This function is deprecated because it does not allow the
+    caller to specify which even_base it uses.  The recommended
+    function is evdns_add_server_port_with_base().
+
+*/
+struct evdns_server_port *evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type callback, void *user_data);
+
+#ifdef WIN32
+int evdns_config_windows_nameservers(void);
+#define EVDNS_CONFIG_WINDOWS_NAMESERVERS_IMPLEMENTED
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_EVENT_COMPAT_H_ */
diff --git a/libevent/include/event2/dns_struct.h b/libevent/include/event2/dns_struct.h
new file mode 100644 (file)
index 0000000..5a02a0b
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_DNS_STRUCT_H_
+#define _EVENT2_DNS_STRUCT_H_
+
+/** @file event2/dns_struct.h
+
+  Data structures for dns.  Using these structures may hurt forward
+  compatibility with later versions of Libevent: be careful!
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/*
+ * Structures used to implement a DNS server.
+ */
+
+struct evdns_server_request {
+       int flags;
+       int nquestions;
+       struct evdns_server_question **questions;
+};
+struct evdns_server_question {
+       int type;
+#ifdef __cplusplus
+       int dns_question_class;
+#else
+       /* You should refer to this field as "dns_question_class".  The
+        * name "class" works in C for backward compatibility, and will be
+        * removed in a future version. (1.5 or later). */
+       int class;
+#define dns_question_class class
+#endif
+       char name[1];
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_DNS_STRUCT_H_ */
+
diff --git a/libevent/include/event2/event.h b/libevent/include/event2/event.h
new file mode 100644 (file)
index 0000000..3993707
--- /dev/null
@@ -0,0 +1,1197 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_EVENT_H_
+#define _EVENT2_EVENT_H_
+
+/**
+   @mainpage
+
+  @section intro Introduction
+
+  Libevent is an event notification library for developing scalable network
+  servers.  The Libevent API provides a mechanism to execute a callback
+  function when a specific event occurs on a file descriptor or after a
+  timeout has been reached. Furthermore, Libevent also support callbacks due
+  to signals or regular timeouts.
+
+  Libevent is meant to replace the event loop found in event driven network
+  servers. An application just needs to call event_dispatch() and then add or
+  remove events dynamically without having to change the event loop.
+
+
+  Currently, Libevent supports /dev/poll, kqueue(2), select(2), poll(2),
+  epoll(4), and evports. The internal event mechanism is completely
+  independent of the exposed event API, and a simple update of Libevent can
+  provide new functionality without having to redesign the applications. As a
+  result, Libevent allows for portable application development and provides
+  the most scalable event notification mechanism available on an operating
+  system.  Libevent can also be used for multithreaded programs.  Libevent
+  should compile on Linux, *BSD, Mac OS X, Solaris and, Windows.
+
+  @section usage Standard usage
+
+  Every program that uses Libevent must inclurde the <event2/event.h>
+  header, and pass the -levent flag to the linker.  (You can instead link
+  -levent_core if you only want the main event and buffered IO-based code,
+  and don't want to link any protocol code.)
+
+  @section setup Library setup
+
+  Before you call any other Libevent functions, you need to set up the
+  library.  If you're going to use Libevent from multiple threads in a
+  multithreaded application, you need to initialize thread support --
+  typically by using evthread_use_pthreads() or
+  evthread_use_windows_threads().  See <event2/thread.h> for more
+  information.
+
+  This is also the point where you can replace Libevent's memory
+  management functions with event_set_mem_functions, and enable debug mode
+  with event_enable_debug_mode().
+
+  @section base Creating an event base
+
+  Next, you need to create an event_base structure, using event_base_new()
+  or event_base_new_with_config().  The event_base is responsible for
+  keeping track of which events are "pending" (that is to say, being
+  watched to see if they become active) and which events are "active".
+  Every event is associated with a single event_base.
+
+  @section event Event notification
+
+  For each file descriptor that you wish to monitor, you must create an
+  event structure with event_new().  (You may also declare an event
+  structure and call event_assign() to initialize the members of the
+  structure.)  To enable notification, you add the structure to the list
+  of monitored events by calling event_add().  The event structure must
+  remain allocated as long as it is active, so it should generally be
+  allocated on the heap.
+
+  @section loop Dispaching evets.
+
+  Finally, you call event_base_dispatch() to loop and dispatch events.
+  You can also use event_base_loop() for more fine-grained control.
+
+  Currently, only one thread can be dispatching a given event_base at a
+  time.  If you want to run events in multiple threads at once, you can
+  either have a single event_base whose events add work to a work queue,
+  or you can create multiple event_base objects.
+
+  @section bufferevent I/O Buffers
+
+  Libevent provides a buffered I/O abstraction on top of the regular event
+  callbacks. This abstraction is called a bufferevent. A bufferevent
+  provides input and output buffers that get filled and drained
+  automatically. The user of a buffered event no longer deals directly
+  with the I/O, but instead is reading from input and writing to output
+  buffers.
+
+  Once initialized via bufferevent_socket_new(), the bufferevent structure
+  can be used repeatedly with bufferevent_enable() and
+  bufferevent_disable().  Instead of reading and writing directly to a
+  socket, you would call bufferevent_read() and bufferevent_write().
+
+  When read enabled the bufferevent will try to read from the file descriptor
+  and call the read callback. The write callback is executed whenever the
+  output buffer is drained below the write low watermark, which is 0 by
+  default.
+
+  See <event2/bufferevent*.h> for more information.
+
+  @section timers Timers
+
+  Libevent can also be used to create timers that invoke a callback after a
+  certain amount of time has expired. The evtimer_new() function returns
+  an event struct to use as a timer. To activate the timer, call
+  evtimer_add(). Timers can be deactivated by calling evtimer_del().
+
+  @section evdns Asynchronous DNS resolution
+
+  Libevent provides an asynchronous DNS resolver that should be used instead
+  of the standard DNS resolver functions.  See the <event2/dns.h>
+  functions for more detail.
+
+  @section evhttp Event-driven HTTP servers
+
+  Libevent provides a very simple event-driven HTTP server that can be
+  embedded in your program and used to service HTTP requests.
+
+  To use this capability, you need to include the <event2/http.h> header in your
+  program.  See that header for more information.
+
+  @section evrpc A framework for RPC servers and clients
+
+  Libevent provides a framework for creating RPC servers and clients.  It
+  takes care of marshaling and unmarshaling all data structures.
+
+  @section api API Reference
+
+  To browse the complete documentation of the libevent API, click on any of
+  the following links.
+
+  event2/event.h
+  The primary libevent header
+
+  event2/thread.h
+  Functions for use by multithreaded programs
+
+  event2/buffer.h and event2/bufferevent.h
+  Buffer management for network reading and writing
+
+  event2/util.h
+  Utility functions for portable nonblocking network code
+
+  event2/dns.h
+  Asynchronous DNS resolution
+
+  event2/http.h
+  An embedded libevent-based HTTP server
+
+  event2/rpc.h
+  A framework for creating RPC servers and clients
+
+ */
+
+/** @file event2/event.h
+
+  Core functions for waiting for and receiving events, and using event bases.
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <stdio.h>
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+ * Structure to hold information and state for a Libevent dispatch loop.
+ *
+ * The event_base lies at the center of Libevent; every application will
+ * have one.  It keeps track of all pending and active events, and
+ * notifies your application of the active ones.
+ *
+ * This is an opaque structure; you can allocate one using
+ * event_base_new() or event_base_new_with_config().
+ *
+ * @see event_base_new(), event_base_free(), event_base_loop(),
+ *    event_base_new_with_config()
+ */
+struct event_base
+#ifdef _EVENT_IN_DOXYGEN
+{/*Empty body so that doxygen will generate documentation here.*/}
+#endif
+;
+
+/**
+ * @struct event
+ *
+ * Structure to represent a single event.
+ *
+ * An event can have some underlying condition it represents: a socket
+ * becoming readable or writeable (or both), or a signal becoming raised.
+ * (An event that represents no underlying condition is still useful: you
+ * can use one to implement a timer, or to communicate between threads.)
+ *
+ * Generally, you can create events with event_new(), then make them
+ * pending with event_add().  As your event_base runs, it will run the
+ * callbacks of an events whose conditions are triggered.  When you
+ * longer want the event, free it with event_free().
+ *
+ * In more depth:
+ *
+ * An event may be "pending" (one whose condition we are watching),
+ * "active" (one whose condition has triggered and whose callback is about
+ * to run), neither, or both.  Events come into existence via
+ * event_assign() or event_new(), and are then neither active nor pending.
+ *
+ * To make an event pending, pass it to event_add().  When doing so, you
+ * can also set a timeout for the event.
+ *
+ * Events become active during an event_base_loop() call when either their
+ * condition has triggered, or when their timeout has elapsed.  You can
+ * also activate an event manually using event_active().  The even_base
+ * loop will run the callbacks of active events; after it has done so, it
+ * marks them as no longer active.
+ *
+ * You can make an event non-pending by passing it to event_del().  This
+ * also makes the event non-active.
+ *
+ * Events can be "persistent" or "non-persistent".  A non-persistent event
+ * becomes non-pending as soon as it is triggered: thus, it only runs at
+ * most once per call to event_add().  A persistent event remains pending
+ * even when it becomes active: you'll need to event_del() it manually in
+ * order to make it non-pending.  When a persistent event with a timeout
+ * becomes active, its timeout is reset: this means you can use persistent
+ * events to implement periodic timeouts.
+ *
+ * This should be treated as an opaque structure; you should never read or
+ * write any of its fields directly.  For backward compatibility with old
+ * code, it is defined in the event2/event_struct.h header; including this
+ * header may make your code incompatible with other versions of Libevent.
+ *
+ * @see event_new(), event_free(), event_assign(), event_get_assignment(),
+ *    event_add(), event_del(), event_active(), event_pending(),
+ *    event_get_fd(), event_get_base(), event_get_events(),
+ *    event_get_callback(), event_get_callback_arg(),
+ *    event_priority_set()
+ */
+struct event
+#ifdef _EVENT_IN_DOXYGEN
+{/*Empty body so that doxygen will generate documentation here.*/}
+#endif
+;
+
+/**
+ * Configuration for an event_base.
+ *
+ * There are many options that can be used to alter the behavior and
+ * implementation of an event_base.  To avoid having to pass them all in a
+ * complex many-argument constructor, we provide an abstract data type
+ * wrhere you set up configation information before passing it to
+ * event_base_new_with_config().
+ *
+ * @see event_config_new(), event_config_free(), event_base_new_with_config(),
+ *   event_config_avoid_method(), event_config_require_features(),
+ *   event_config_set_flag(), event_config_set_num_cpus_hint()
+ */
+struct event_config
+#ifdef _EVENT_IN_DOXYGEN
+{/*Empty body so that doxygen will generate documentation here.*/}
+#endif
+;
+
+/**
+ * Enable some relatively expensive debugging checks in Libevent that
+ * would normally be turned off.  Generally, these checks cause code that
+ * would otherwise crash mysteriously to fail earlier with an assertion
+ * failure.  Note that this method MUST be called before any events or
+ * event_bases have been created.
+ *
+ * Debug mode can currently catch the following errors:
+ *    An event is re-assigned while it is added
+ *    Any function is called on a non-assigned event
+ *
+ * Note that debugging mode uses memory to track every event that has been
+ * initialized (via event_assign, event_set, or event_new) but not yet
+ * released (via event_free or event_debug_unassign).  If you want to use
+ * debug mode, and you find yourself running out of memory, you will need
+ * to use event_debug_unassign to explicitly stop tracking events that
+ * are no longer considered set-up.
+ *
+ * @see event_debug_unassign()
+ */
+void event_enable_debug_mode(void);
+
+/**
+ * When debugging mode is enabled, informs Libevent that an event should no
+ * longer be considered as assigned. When debugging mode is not enabled, does
+ * nothing.
+ *
+ * This function must only be called on a non-added event.
+ *
+ * @see event_enable_debug_mode()
+ */
+void event_debug_unassign(struct event *);
+
+/**
+ * Create and return a new event_base to use with the rest of Libevent.
+ *
+ * @return a new event_base on success, or NULL on failure.
+ *
+ * @see event_base_free(), event_base_new_with_config()
+ */
+struct event_base *event_base_new(void);
+
+/**
+  Reinitialize the event base after a fork
+
+  Some event mechanisms do not survive across fork.   The event base needs
+  to be reinitialized with the event_reinit() function.
+
+  @param base the event base that needs to be re-initialized
+  @return 0 if successful, or -1 if some events could not be re-added.
+  @see event_base_new()
+*/
+int event_reinit(struct event_base *base);
+
+/**
+   Event dispatching loop
+
+  This loop will run the event base until either there are no more added
+  events, or until something calls event_base_loopbreak() or
+  event_base_loopexit().
+
+  @param base the event_base structure returned by event_base_new() or
+     event_base_new_with_config()
+  @return 0 if successful, -1 if an error occurred, or 1 if no events were
+    registered.
+  @see event_base_loop()
+ */
+int event_base_dispatch(struct event_base *);
+
+/**
+ Get the kernel event notification mechanism used by Libevent.
+
+ @param eb the event_base structure returned by event_base_new()
+ @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
+ */
+const char *event_base_get_method(const struct event_base *);
+
+/**
+   Gets all event notification mechanisms supported by Libevent.
+
+   This functions returns the event mechanism in order preferred by
+   Libevent.  Note that this list will include all backends that
+   Libevent has compiled-in support for, and will not necessarily check
+   your OS to see whether it has the required resources.
+
+   @return an array with pointers to the names of support methods.
+     The end of the array is indicated by a NULL pointer.  If an
+     error is encountered NULL is returned.
+*/
+const char **event_get_supported_methods(void);
+
+/**
+   Allocates a new event configuration object.
+
+   The event configuration object can be used to change the behavior of
+   an event base.
+
+   @return an event_config object that can be used to store configuration, or
+     NULL if an error is encountered.
+   @see event_base_new_with_config(), event_config_free(), event_config
+*/
+struct event_config *event_config_new(void);
+
+/**
+   Deallocates all memory associated with an event configuration object
+
+   @param cfg the event configuration object to be freed.
+*/
+void event_config_free(struct event_config *cfg);
+
+/**
+   Enters an event method that should be avoided into the configuration.
+
+   This can be used to avoid event mechanisms that do not support certain
+   file descriptor types, or for debugging to avoid certain event
+   mechanisms.  An application can make use of multiple event bases to
+   accommodate incompatible file descriptor types.
+
+   @param cfg the event configuration object
+   @param method the name of the event method to avoid
+   @return 0 on success, -1 on failure.
+*/
+int event_config_avoid_method(struct event_config *cfg, const char *method);
+
+/**
+   A flag used to describe which features an event_base (must) provide.
+
+   Because of OS limitations, not every Libevent backend supports every
+   possible feature.  You can use this type with
+   event_config_require_features() to tell Libevent to only proceed if your
+   event_base implements a given feature, and you can receive this type from
+   event_base_get_features() to see which features are available.
+*/
+enum event_method_feature {
+    /** Require an event method that allows edge-triggered events with EV_ET. */
+    EV_FEATURE_ET = 0x01,
+    /** Require an event method where having one event triggered among
+     * many is [approximately] an O(1) operation. This excludes (for
+     * example) select and poll, which are approximately O(N) for N
+     * equal to the total number of possible events. */
+    EV_FEATURE_O1 = 0x02,
+    /** Require an event method that allows file descriptors as well as
+     * sockets. */
+    EV_FEATURE_FDS = 0x04
+};
+
+/**
+   A flag passed to event_config_set_flag().
+
+    These flags change the behavior of an allocated event_base.
+
+    @see event_config_set_flag(), event_base_new_with_config(),
+       event_method_feature
+ */
+enum event_base_config_flag {
+       /** Do not allocate a lock for the event base, even if we have
+           locking set up. */
+       EVENT_BASE_FLAG_NOLOCK = 0x01,
+       /** Do not check the EVENT_* environment variables when configuring
+           an event_base  */
+       EVENT_BASE_FLAG_IGNORE_ENV = 0x02,
+       /** Windows only: enable the IOCP dispatcher at startup
+
+           If this flag is set then bufferevent_socket_new() and
+           evconn_listener_new() will use IOCP-backed implementations
+           instead of the usual select-based one on Windows.
+        */
+       EVENT_BASE_FLAG_STARTUP_IOCP = 0x04,
+       /** Instead of checking the current time every time the event loop is
+           ready to run timeout callbacks, check after each timeout callback.
+        */
+       EVENT_BASE_FLAG_NO_CACHE_TIME = 0x08,
+
+       /** If we are using the epoll backend, this flag says that it is
+           safe to use Libevent's internal change-list code to batch up
+           adds and deletes in order to try to do as few syscalls as
+           possible.  Setting this flag can make your code run faster, but
+           it may trigger a Linux bug: it is not safe to use this flag
+           if you have any fds cloned by dup() or its variants.  Doing so
+           will produce strange and hard-to-diagnose bugs.
+
+           This flag can also be activated by settnig the
+           EVENT_EPOLL_USE_CHANGELIST environment variable.
+
+           This flag has no effect if you wind up using a backend other than
+           epoll.
+        */
+       EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST = 0x10
+};
+
+/**
+   Return a bitmask of the features implemented by an event base.  This
+   will be a bitwise OR of one or more of the values of
+   event_method_feature
+
+   @see event_method_feature
+ */
+int event_base_get_features(const struct event_base *base);
+
+/**
+   Enters a required event method feature that the application demands.
+
+   Note that not every feature or combination of features is supported
+   on every platform.  Code that requests features should be prepared
+   to handle the case where event_base_new_with_config() returns NULL, as in:
+   <pre>
+     event_config_require_features(cfg, EV_FEATURE_ET);
+     base = event_base_new_with_config(cfg);
+     if (base == NULL) {
+       // We can't get edge-triggered behavior here.
+       event_config_require_features(cfg, 0);
+       base = event_base_new_with_config(cfg);
+     }
+   </pre>
+
+   @param cfg the event configuration object
+   @param feature a bitfield of one or more event_method_feature values.
+          Replaces values from previous calls to this function.
+   @return 0 on success, -1 on failure.
+   @see event_method_feature, event_base_new_with_config()
+*/
+int event_config_require_features(struct event_config *cfg, int feature);
+
+/**
+ * Sets one or more flags to configure what parts of the eventual event_base
+ * will be initialized, and how they'll work.
+ *
+ * @see event_base_config_flags, event_base_new_with_config()
+ **/
+int event_config_set_flag(struct event_config *cfg, int flag);
+
+/**
+ * Records a hint for the number of CPUs in the system. This is used for
+ * tuning thread pools, etc, for optimal performance.  In Libevent 2.0,
+ * it is only on Windows, and only when IOCP is in use.
+ *
+ * @param cfg the event configuration object
+ * @param cpus the number of cpus
+ * @return 0 on success, -1 on failure.
+ */
+int event_config_set_num_cpus_hint(struct event_config *cfg, int cpus);
+
+/**
+  Initialize the event API.
+
+  Use event_base_new_with_config() to initialize a new event base, taking
+  the specified configuration under consideration.  The configuration object
+  can currently be used to avoid certain event notification mechanisms.
+
+  @param cfg the event configuration object
+  @return an initialized event_base that can be used to registering events,
+     or NULL if no event base can be created with the requested event_config.
+  @see event_base_new(), event_base_free(), event_init(), event_assign()
+*/
+struct event_base *event_base_new_with_config(const struct event_config *);
+
+/**
+  Deallocate all memory associated with an event_base, and free the base.
+
+  Note that this function will not close any fds or free any memory passed
+  to event_new as the argument to callback.
+
+  @param eb an event_base to be freed
+ */
+void event_base_free(struct event_base *);
+
+/** @name Log severities
+ */
+/**@{*/
+#define _EVENT_LOG_DEBUG 0
+#define _EVENT_LOG_MSG   1
+#define _EVENT_LOG_WARN  2
+#define _EVENT_LOG_ERR   3
+/**@}*/
+
+/**
+  A callback function used to intercept Libevent's log messages.
+
+  @see event_set_log_callback
+ */
+typedef void (*event_log_cb)(int severity, const char *msg);
+/**
+  Redirect Libevent's log messages.
+
+  @param cb a function taking two arguments: an integer severity between
+     _EVENT_LOG_DEBUG and _EVENT_LOG_ERR, and a string.  If cb is NULL,
+        then the default log is used.
+
+  NOTE: The function you provide *must not* call any other libevent
+  functionality.  Doing so can produce undefined behavior.
+  */
+void event_set_log_callback(event_log_cb cb);
+
+/**
+   A function to be called if Libevent encounters a fatal internal error.
+
+   @see event_set_fatal_callback
+ */
+typedef void (*event_fatal_cb)(int err);
+
+/**
+ Override Libevent's behavior in the event of a fatal internal error.
+
+ By default, Libevent will call exit(1) if a programming error makes it
+ impossible to continue correct operation.  This function allows you to supply
+ another callback instead.  Note that if the function is ever invoked,
+ something is wrong with your program, or with Libevent: any subsequent calls
+ to Libevent may result in undefined behavior.
+
+ Libevent will (almost) always log an _EVENT_LOG_ERR message before calling
+ this function; look at the last log message to see why Libevent has died.
+ */
+void event_set_fatal_callback(event_fatal_cb cb);
+
+/**
+  Associate a different event base with an event.
+
+  The event to be associated must not be currently active or pending.
+
+  @param eb the event base
+  @param ev the event
+  @return 0 on success, -1 on failure.
+ */
+int event_base_set(struct event_base *, struct event *);
+
+/** @name Loop flags
+
+    These flags control the behavior of event_base_loop().
+ */
+/**@{*/
+/** Block until we have an active event, then exit once all active events
+ * have had their callbacks run. */
+#define EVLOOP_ONCE    0x01
+/** Do not block: see which events are ready now, run the callbacks
+ * of the highest-priority ones, then exit. */
+#define EVLOOP_NONBLOCK        0x02
+/**@}*/
+
+/**
+  Wait for events to become active, and run their callbacks.
+
+  This is a more flexible version of event_base_dispatch().
+
+  By default, this loop will run the event base until either there are no more
+  added events, or until something calls event_base_loopbreak() or
+  evenet_base_loopexit().  You can override this behavior with the 'flags'
+  argument.
+
+  @param eb the event_base structure returned by event_base_new() or
+     event_base_new_with_config()
+  @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
+  @return 0 if successful, -1 if an error occurred, or 1 if no events were
+    registered.
+  @see event_base_loopexit(), event_base_dispatch(), EVLOOP_ONCE,
+     EVLOOP_NONBLOCK
+  */
+int event_base_loop(struct event_base *, int);
+
+/**
+  Exit the event loop after the specified time
+
+  The next event_base_loop() iteration after the given timer expires will
+  complete normally (handling all queued events) then exit without
+  blocking for events again.
+
+  Subsequent invocations of event_base_loop() will proceed normally.
+
+  @param eb the event_base structure returned by event_init()
+  @param tv the amount of time after which the loop should terminate,
+    or NULL to exit after running all currently active events.
+  @return 0 if successful, or -1 if an error occurred
+  @see event_base_loopbreak()
+ */
+int event_base_loopexit(struct event_base *, const struct timeval *);
+
+/**
+  Abort the active event_base_loop() immediately.
+
+  event_base_loop() will abort the loop after the next event is completed;
+  event_base_loopbreak() is typically invoked from this event's callback.
+  This behavior is analogous to the "break;" statement.
+
+  Subsequent invocations of event_loop() will proceed normally.
+
+  @param eb the event_base structure returned by event_init()
+  @return 0 if successful, or -1 if an error occurred
+  @see event_base_loopexit()
+ */
+int event_base_loopbreak(struct event_base *);
+
+/**
+  Checks if the event loop was told to exit by event_loopexit().
+
+  This function will return true for an event_base at every point after
+  event_loopexit() is called, until the event loop is next entered.
+
+  @param eb the event_base structure returned by event_init()
+  @return true if event_base_loopexit() was called on this event base,
+    or 0 otherwise
+  @see event_base_loopexit()
+  @see event_base_got_break()
+ */
+int event_base_got_exit(struct event_base *);
+
+/**
+  Checks if the event loop was told to abort immediately by event_loopbreak().
+
+  This function will return true for an event_base at every point after
+  event_loopbreak() is called, until the event loop is next entered.
+
+  @param eb the event_base structure returned by event_init()
+  @return true if event_base_loopbreak() was called on this event base,
+    or 0 otherwise
+  @see event_base_loopbreak()
+  @see event_base_got_exit()
+ */
+int event_base_got_break(struct event_base *);
+
+/**
+ * @name event flags
+ *
+ * Flags to pass to event_new(), event_assign(), event_pending(), and
+ * anything else with an argument of the form "short events"
+ */
+/**@{*/
+/** Indicates that a timeout has occurred.  It's not necessary to pass
+ * this flag to event_for new()/event_assign() to get a timeout. */
+#define EV_TIMEOUT     0x01
+/** Wait for a socket or FD to become readable */
+#define EV_READ                0x02
+/** Wait for a socket or FD to become writeable */
+#define EV_WRITE       0x04
+/** Wait for a POSIX signal to be raised*/
+#define EV_SIGNAL      0x08
+/**
+ * Persistent event: won't get removed automatically when activated.
+ *
+ * When a persistent event with a timeout becomes activated, its timeout
+ * is reset to 0.
+ */
+#define EV_PERSIST     0x10
+/** Select edge-triggered behavior, if supported by the backend. */
+#define EV_ET       0x20
+/**@}*/
+
+/**
+   @name evtimer_* macros
+
+    Aliases for working with one-shot timer events */
+/**@{*/
+#define evtimer_assign(ev, b, cb, arg) \
+       event_assign((ev), (b), -1, 0, (cb), (arg))
+#define evtimer_new(b, cb, arg)               event_new((b), -1, 0, (cb), (arg))
+#define evtimer_add(ev, tv)            event_add((ev), (tv))
+#define evtimer_del(ev)                        event_del(ev)
+#define evtimer_pending(ev, tv)                event_pending((ev), EV_TIMEOUT, (tv))
+#define evtimer_initialized(ev)                event_initialized(ev)
+/**@}*/
+
+/**
+   @name evsignal_* macros
+
+   Aliases for working with signal events
+ */
+/**@{*/
+#define evsignal_add(ev, tv)           event_add((ev), (tv))
+#define evsignal_assign(ev, b, x, cb, arg)                     \
+       event_assign((ev), (b), (x), EV_SIGNAL|EV_PERSIST, cb, (arg))
+#define evsignal_new(b, x, cb, arg)                            \
+       event_new((b), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
+#define evsignal_del(ev)               event_del(ev)
+#define evsignal_pending(ev, tv)       event_pending((ev), EV_SIGNAL, (tv))
+#define evsignal_initialized(ev)       event_initialized(ev)
+/**@}*/
+
+/**
+   A callback function for an event.
+
+   It receives three arguments:
+
+   @param fd An fd or signal
+   @param events One or more EV_* flags
+   @param arg A user-supplied argument.
+
+   @see event_new()
+ */
+typedef void (*event_callback_fn)(evutil_socket_t, short, void *);
+
+/**
+  Allocate and asssign a new event structure, ready to be added.
+
+  The function event_new() returns a new event that can be used in
+  future calls to event_add() and event_del().  The fd and events
+  arguments determine which conditions will trigger the event; the
+  callback and callback_arg arguments tell Libevent what to do when the
+  event becomes active.
+
+  If events contains one of EV_READ, EV_WRITE, or EV_READ|EV_WRITE, then
+  fd is a file descriptor or socket that should get monitored for
+  readiness to read, readiness to write, or readiness for either operation
+  (respectively).  If events contains EV_SIGNAL, then fd is a signal
+  number to wait for.  If events contains none of those flags, then the
+  event can be triggered only by a timeout or by manual activation with
+  event_active(): In this case, fd must be -1.
+
+  The EV_PERSIST flag can also be passed in the events argument: it makes
+  event_add() persistent until event_del() is called.
+
+  The EV_ET flag is compatible with EV_READ and EV_WRITE, and supported
+  only by certain backends.  It tells Libevent to use edge-triggered
+  events.
+
+  The EV_TIMEOUT flag has no effect here.
+
+  It is okay to have multiple events all listening on the same fds; but
+  they must either all be edge-triggered, or all not be edge triggerd.
+
+  When the event becomes active, the event loop will run the provided
+  callbuck function, with three arguments.  The first will be the provided
+  fd value.  The second will be a bitfield of the events that triggered:
+  EV_READ, EV_WRITE, or EV_SIGNAL.  Here the EV_TIMEOUT flag indicates
+  that a timeout occurred, and EV_ET indicates that an edge-triggered
+  event occurred.  The third event will be the callback_arg pointer that
+  you provide.
+
+  @param base the event base to which the event should be attached.
+  @param fd the file descriptor or signal to be monitored, or -1.
+  @param events desired events to monitor: bitfield of EV_READ, EV_WRITE,
+      EV_SIGNAL, EV_PERSIST, EV_ET.
+  @param callback callback function to be invoked when the event occurs
+  @param callback_arg an argument to be passed to the callback function
+
+  @return a newly allocated struct event that must later be freed with
+    event_free().
+  @see event_free(), event_add(), event_del(), event_assign()
+ */
+struct event *event_new(struct event_base *, evutil_socket_t, short, event_callback_fn, void *);
+
+
+/**
+  Prepare a new, already-allocated event structure to be added.
+
+  The function event_assign() prepares the event structure ev to be used
+  in future calls to event_add() and event_del().  Unlike event_new(), it
+  doesn't allocate memory itself: it requires that you have already
+  allocated a struct event, probably on the heap.  Doing this will
+  typically make your code depend on the size of the event structure, and
+  thereby create incompatibility with future versions of Libevent.
+
+  The easiest way to avoid this problem is just to use event_new() and
+  event_free() instead.
+
+  A slightly harder way to future-proof your code is to use
+  event_get_struct_event_size() to determine the required size of an event
+  at runtime.
+
+  Note that it is NOT safe to call this function on an event that is
+  active or pending.  Doing so WILL corrupt internal data structures in
+  Libevent, and lead to strange, hard-to-diagnose bugs.  You _can_ use
+  event_assign to change an existing event, but only if it is not active
+  or pending!
+
+  The arguments for this function, and the behavior of the events that it
+  makes, are as for event_new().
+
+  @param ev an event struct to be modified
+  @param base the event base to which ev should be attached.
+  @param fd the file descriptor to be monitored
+  @param events desired events to monitor; can be EV_READ and/or EV_WRITE
+  @param callback callback function to be invoked when the event occurs
+  @param callback_arg an argument to be passed to the callback function
+
+  @return 0 if success, or -1 on invalid arguments.
+
+  @see event_new(), event_add(), event_del(), event_base_once(),
+    event_get_struct_event_size()
+  */
+int event_assign(struct event *, struct event_base *, evutil_socket_t, short, event_callback_fn, void *);
+
+/**
+   Deallocate a struct event * returned by event_new().
+
+   If the event is pending or active, first make it non-pending and
+   non-active.
+ */
+void event_free(struct event *);
+
+/**
+  Schedule a one-time event
+
+  The function event_base_once() is similar to event_set().  However, it
+  schedules a callback to be called exactly once, and does not require the
+  caller to prepare an event structure.
+
+  Note that in Libevent 2.0 and earlier, if the event is never triggered,
+  the internal memory used to hold it will never be freed.  This may be
+  fixed in a later version of Libevent.
+
+  @param base an event_base
+  @param fd a file descriptor to monitor, or -1 for no fd.
+  @param events event(s) to monitor; can be any of EV_READ |
+         EV_WRITE, or EV_TIMEOUT
+  @param callback callback function to be invoked when the event occurs
+  @param arg an argument to be passed to the callback function
+  @param timeout the maximum amount of time to wait for the event. NULL
+         makes an EV_READ/EV_WRITE event make forever; NULL makes an
+        EV_TIMEOUT event succees immediately.
+  @return 0 if successful, or -1 if an error occurred
+ */
+int event_base_once(struct event_base *, evutil_socket_t, short, event_callback_fn, void *, const struct timeval *);
+
+/**
+  Add an event to the set of pending events.
+
+  The function event_add() schedules the execution of the ev event when the
+  event specified in event_assign()/event_new() occurs, or when the time
+  specified in timeout has elapesed.  If atimeout is NULL, no timeout
+  occurs and the function will only be
+  called if a matching event occurs.  The event in the
+  ev argument must be already initialized by event_assign() or event_new()
+  and may not be used
+  in calls to event_assign() until it is no longer pending.
+
+  If the event in the ev argument already has a scheduled timeout, calling
+  event_add() replaces the old timeout with the new one, or clears the old
+  timeout if the timeout argument is NULL.
+
+  @param ev an event struct initialized via event_set()
+  @param timeout the maximum amount of time to wait for the event, or NULL
+         to wait forever
+  @return 0 if successful, or -1 if an error occurred
+  @see event_del(), event_assign(), event_new()
+  */
+int event_add(struct event *ev, const struct timeval *timeout);
+
+/**
+  Remove an event from the set of monitored events.
+
+  The function event_del() will cancel the event in the argument ev.  If the
+  event has already executed or has never been added the call will have no
+  effect.
+
+  @param ev an event struct to be removed from the working set
+  @return 0 if successful, or -1 if an error occurred
+  @see event_add()
+ */
+int event_del(struct event *);
+
+
+/**
+  Make an event active.
+
+  You can use this function on a pending or a non-pending event to make it
+  active, so that its callback will be run by event_base_dispatch() or
+  event_base_loop().
+
+  One common use in multithreaded programs is to wake the thread running
+  event_base_loop() from another thread.
+
+  @param ev an event to make active.
+  @param res a set of flags to pass to the event's callback.
+  @param ncalls an obsolete argument: this is ignored.
+ **/
+void event_active(struct event *ev, int res, short ncalls);
+
+/**
+  Checks if a specific event is pending or scheduled.
+
+  @param ev an event struct previously passed to event_add()
+  @param events the requested event type; any of EV_TIMEOUT|EV_READ|
+         EV_WRITE|EV_SIGNAL
+  @param tv if this field is not NULL, and the event has a timeout,
+         this field is set to hold the time at which the timeout will
+        expire.
+
+  @return true if the event is pending on any of the events in 'what', (that
+  is to say, it has been added), or 0 if the event is not added.
+ */
+int event_pending(const struct event *ev, short events, struct timeval *tv);
+
+
+/**
+  Test if an event structure might be initialized.
+
+  The event_initialized() function can be used to check if an event has been
+  initialized.
+
+  Warning: This function is only useful for distinguishing a a zeroed-out
+    piece of memory from an initialized event, it can easily be confused by
+    uninitialized memory.  Thus, it should ONLY be used to distinguish an
+    initialized event from zero.
+
+  @param ev an event structure to be tested
+  @return 1 if the structure might be initialized, or 0 if it has not been
+          initialized
+ */
+int event_initialized(const struct event *ev);
+
+/**
+   Get the signal number assigned to a signal event
+*/
+#define event_get_signal(ev) ((int)event_get_fd(ev))
+
+/**
+   Get the socket or signal assigned to an event, or -1 if the event has
+   no socket.
+*/
+evutil_socket_t event_get_fd(const struct event *ev);
+
+/**
+   Get the event_base associated with an event.
+*/
+struct event_base *event_get_base(const struct event *ev);
+
+/**
+   Return the events (EV_READ, EV_WRITE, etc) assigned to an event.
+*/
+short event_get_events(const struct event *ev);
+
+/**
+   Return the callback assigned to an event.
+*/
+event_callback_fn event_get_callback(const struct event *ev);
+
+/**
+   Return the callback argument assigned to an event.
+*/
+void *event_get_callback_arg(const struct event *ev);
+
+/**
+   Extract _all_ of arguments given to construct a given event.  The
+   event_base is copied into *base_out, the fd is copied into *fd_out, and so
+   on.
+
+   If any of the "_out" arguments is NULL, it will be ignored.
+ */
+void event_get_assignment(const struct event *event,
+    struct event_base **base_out, evutil_socket_t *fd_out, short *events_out,
+    event_callback_fn *callback_out, void **arg_out);
+
+/**
+   Return the size of struct event that the Libevent library was compiled
+   with.
+
+   This will be NO GREATER than sizeof(struct event) if you're running with
+   the same version of Libevent that your application was built with, but
+   otherwise might not.
+
+   Note that it might be SMALLER than sizeof(struct event) if some future
+   version of Libevent adds extra padding to the end of struct event.
+   We might do this to help ensure ABI-compatibility between different
+   versions of Libevent.
+ */
+size_t event_get_struct_event_size(void);
+
+/**
+   Get the Libevent version.
+
+   Note that this will give you the version of the library that you're
+   currently linked against, not the version of the headers that you've
+   compiled against.
+
+   @return a string containing the version number of Libevent
+*/
+const char *event_get_version(void);
+
+/**
+   Return a numeric representation of Libevent's version.
+
+   Note that this will give you the version of the library that you're
+   currently linked against, not the version of the headers you've used to
+   compile.
+
+   The format uses one byte each for the major, minor, and patchlevel parts of
+   the version number.  The low-order byte is unused.  For example, version
+   2.0.1-alpha has a numeric representation of 0x02000100
+*/
+ev_uint32_t event_get_version_number(void);
+
+/** As event_get_version, but gives the version of Libevent's headers. */
+#define LIBEVENT_VERSION _EVENT_VERSION
+/** As event_get_version_number, but gives the version number of Libevent's
+ * headers. */
+#define LIBEVENT_VERSION_NUMBER _EVENT_NUMERIC_VERSION
+
+/** Largest number of priorities that Libevent can support. */
+#define EVENT_MAX_PRIORITIES 256
+/**
+  Set the number of different event priorities
+
+  By default Libevent schedules all active events with the same priority.
+  However, some time it is desirable to process some events with a higher
+  priority than others.  For that reason, Libevent supports strict priority
+  queues.  Active events with a lower priority are always processed before
+  events with a higher priority.
+
+  The number of different priorities can be set initially with the
+  event_base_priority_init() function.  This function should be called
+  before the first call to event_base_dispatch().  The
+  event_priority_set() function can be used to assign a priority to an
+  event.  By default, Libevent assigns the middle priority to all events
+  unless their priority is explicitly set.
+
+  Note that urgent-priority events can starve less-urgent events: after
+  running all urgent-priority callbacks, Libevent checks for more urgent
+  events again, before running less-urgent events.  Less-urgent events
+  will not have their callbacks run until there are no events more urgent
+  than them that want to be active.
+
+  @param eb the event_base structure returned by event_base_new()
+  @param npriorities the maximum number of priorities
+  @return 0 if successful, or -1 if an error occurred
+  @see event_priority_set()
+ */
+int    event_base_priority_init(struct event_base *, int);
+
+/**
+  Assign a priority to an event.
+
+  @param ev an event struct
+  @param priority the new priority to be assigned
+  @return 0 if successful, or -1 if an error occurred
+  @see event_priority_init()
+  */
+int    event_priority_set(struct event *, int);
+
+/**
+   Prepare an event_base to use a large number of timeouts with the same
+   duration.
+
+   Libevent's default scheduling algorithm is optimized for having a large
+   number of timeouts with their durations more or less randomly
+   distributed.  But if you have a large number of timeouts that all have
+   the same duration (for example, if you have a large number of
+   connections that all have a 10-second timeout), then you can improve
+   Libevent's performance by telling Libevent about it.
+
+   To do this, call this function with the common duration.  It will return a
+   pointer to a different, opaque timeout value.  (Don't depend on its actual
+   contents!)  When you use this timeout value in event_add(), Libevent will
+   schedule the event more efficiently.
+
+   (This optimization probably will not be worthwhile until you have thousands
+   or tens of thousands of events with the same timeout.)
+ */
+const struct timeval *event_base_init_common_timeout(struct event_base *base,
+    const struct timeval *duration);
+
+#if !defined(_EVENT_DISABLE_MM_REPLACEMENT) || defined(_EVENT_IN_DOXYGEN)
+/**
+ Override the functions that Libevent uses for memory management.
+
+ Usually, Libevent uses the standard libc functions malloc, realloc, and
+ free to allocate memory.  Passing replacements for those functions to
+ event_set_mem_functions() overrides this behavior.
+
+ Note that all memory returned from Libevent will be allocated by the
+ replacement functions rather than by malloc() and realloc().  Thus, if you
+ have replaced those functions, it will not be appropriate to free() memory
+ that you get from Libevent.  Instead, you must use the free_fn replacement
+ that you provided.
+
+ Note also that if you are going to call this function, you should do so
+ before any call to any Libevent function that does allocation.
+ Otherwise, those funtions will allocate their memory using malloc(), but
+ then later free it using your provided free_fn.
+
+ @param malloc_fn A replacement for malloc.
+ @param realloc_fn A replacement for realloc
+ @param free_fn A replacement for free.
+ **/
+void event_set_mem_functions(
+       void *(*malloc_fn)(size_t sz),
+       void *(*realloc_fn)(void *ptr, size_t sz),
+       void (*free_fn)(void *ptr));
+/** This definition is present if Libevent was built with support for
+    event_set_mem_functions() */
+#define EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
+#endif
+
+void event_base_dump_events(struct event_base *, FILE *);
+
+/** Sets 'tv' to the current time (as returned by gettimeofday()),
+    looking at the cached value in 'base' if possible, and calling
+    gettimeofday() or clock_gettime() as appropriate if there is no
+    cached time.
+
+    Generally, this value will only be cached while actually
+    processing event callbacks, and may be very inaccuate if your
+    callbacks take a long time to execute.
+
+    Returns 0 on success, negative on failure.
+ */
+int event_base_gettimeofday_cached(struct event_base *base,
+    struct timeval *tv);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_EVENT_H_ */
diff --git a/libevent/include/event2/event_compat.h b/libevent/include/event2/event_compat.h
new file mode 100644 (file)
index 0000000..14a10e9
--- /dev/null
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_EVENT_COMPAT_H_
+#define _EVENT2_EVENT_COMPAT_H_
+
+/** @file event2/event_compat.h
+
+  Potentially non-threadsafe versions of the functions in event.h: provided
+  only for backwards compatibility.
+
+  In the oldest versions of Libevent, event_base was not a first-class
+  structure.  Instead, there was a single event base that every function
+  manipulated.  Later, when separate event bases were added, the old functions
+  that didn't take an event_base argument needed to work by manipulating the
+  "current" event base.  This could lead to thread-safety issues, and obscure,
+  hard-to-diagnose bugs.
+
+  @deprecated All functions in this file are by definition deprecated.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+  Initialize the event API.
+
+  The event API needs to be initialized with event_init() before it can be
+  used.  Sets the global current base that gets used for events that have no
+  base associated with them.
+
+  @deprecated This function is deprecated because it replaces the "current"
+    event_base, and is totally unsafe for multithreaded use.  The replacement
+    is event_base_new().
+
+  @see event_base_set(), event_base_new()
+ */
+struct event_base *event_init(void);
+
+/**
+  Loop to process events.
+
+  Like event_base_dispatch(), but uses the "current" base.
+
+  @deprecated This function is deprecated because it is easily confused by
+    multiple calls to event_init(), and because it is not safe for
+    multithreaded use.  The replacement is event_base_dispatch().
+
+  @see event_base_dispatch(), event_init()
+ */
+int event_dispatch(void);
+
+/**
+  Handle events.
+
+  This function behaves like event_base_loop(), but uses the "current" base
+
+  @deprecated This function is deprecated because it uses the event base from
+    the last call to event_init, and is therefore not safe for multithreaded
+    use.  The replacement is event_base_loop().
+
+  @see event_base_loop(), event_init()
+*/
+int event_loop(int);
+
+
+/**
+  Exit the event loop after the specified time.
+
+  This function behaves like event_base_loopexit(), except that it uses the
+  "current" base.
+
+  @deprecated This function is deprecated because it uses the event base from
+    the last call to event_init, and is therefore not safe for multithreaded
+    use.  The replacement is event_base_loopexit().
+
+  @see event_init, event_base_loopexit()
+  */
+int event_loopexit(const struct timeval *);
+
+
+/**
+  Abort the active event_loop() immediately.
+
+  This function behaves like event_base_loopbreakt(), except that it uses the
+  "current" base.
+
+  @deprecated This function is deprecated because it uses the event base from
+    the last call to event_init, and is therefore not safe for multithreaded
+    use.  The replacement is event_base_loopbreak().
+
+  @see event_base_loopbreak(), event_init()
+ */
+int event_loopbreak(void);
+
+/**
+  Schedule a one-time event to occur.
+
+  @deprecated This function is obsolete, and has been replaced by
+    event_base_once(). Its use is deprecated because it relies on the
+    "current" base configured by event_init().
+
+  @see event_base_once()
+ */
+int event_once(evutil_socket_t , short,
+    void (*)(evutil_socket_t, short, void *), void *, const struct timeval *);
+
+
+/**
+  Get the kernel event notification mechanism used by Libevent.
+
+  @deprecated This function is obsolete, and has been replaced by
+    event_base_get_method(). Its use is deprecated because it relies on the
+    "current" base configured by event_init().
+
+  @see event_base_get_method()
+ */
+const char *event_get_method(void);
+
+
+/**
+  Set the number of different event priorities.
+
+  @deprecated This function is deprecated because it is easily confused by
+    multiple calls to event_init(), and because it is not safe for
+    multithreaded use.  The replacement is event_base_priority_init().
+
+  @see event_base_priority_init()
+ */
+int    event_priority_init(int);
+
+/**
+  Prepare an event structure to be added.
+
+  @deprecated event_set() is not recommended for new code, because it requires
+     a subsequent call to event_base_set() to be safe under most circumstances.
+     Use event_assign() or event_new() instead.
+ */
+void event_set(struct event *, evutil_socket_t, short, void (*)(evutil_socket_t, short, void *), void *);
+
+#define evtimer_set(ev, cb, arg)       event_set((ev), -1, 0, (cb), (arg))
+#define evsignal_set(ev, x, cb, arg)   \
+       event_set((ev), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
+
+
+/**
+   @name timeout_* macros
+
+   @deprecated These macros are deprecated because their naming is inconsistent
+     with the rest of Libevent.  Use the evtimer_* macros instead.
+   @{
+ */
+#define timeout_add(ev, tv)            event_add((ev), (tv))
+#define timeout_set(ev, cb, arg)       event_set((ev), -1, 0, (cb), (arg))
+#define timeout_del(ev)                        event_del(ev)
+#define timeout_pending(ev, tv)                event_pending((ev), EV_TIMEOUT, (tv))
+#define timeout_initialized(ev)                event_initialized(ev)
+/**@}*/
+
+/**
+   @name signal_* macros
+
+   @deprecated These macros are deprecated because their naming is inconsistent
+     with the rest of Libevent.  Use the evsignal_* macros instead.
+   @{
+ */
+#define signal_add(ev, tv)             event_add((ev), (tv))
+#define signal_set(ev, x, cb, arg)                             \
+       event_set((ev), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
+#define signal_del(ev)                 event_del(ev)
+#define signal_pending(ev, tv)         event_pending((ev), EV_SIGNAL, (tv))
+#define signal_initialized(ev)         event_initialized(ev)
+/**@}*/
+
+#ifndef EVENT_FD
+/* These macros are obsolete; use event_get_fd and event_get_signal instead. */
+#define EVENT_FD(ev)           ((int)event_get_fd(ev))
+#define EVENT_SIGNAL(ev)       event_get_signal(ev)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_EVENT_COMPAT_H_ */
diff --git a/libevent/include/event2/event_struct.h b/libevent/include/event2/event_struct.h
new file mode 100644 (file)
index 0000000..2ed4272
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_EVENT_STRUCT_H_
+#define _EVENT2_EVENT_STRUCT_H_
+
+/** @file event2/event_struct.h
+
+  Structures used by event.h.  Using these structures directly WILL harm
+  forward compatibility: be careful.
+
+  No field declared in this file should be used directly in user code.  Except
+  for historical reasons, these fields would not be exposed at all.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/* For evkeyvalq */
+#include <event2/keyvalq_struct.h>
+
+#define EVLIST_TIMEOUT 0x01
+#define EVLIST_INSERTED        0x02
+#define EVLIST_SIGNAL  0x04
+#define EVLIST_ACTIVE  0x08
+#define EVLIST_INTERNAL        0x10
+#define EVLIST_INIT    0x80
+
+/* EVLIST_X_ Private space: 0x1000-0xf000 */
+#define EVLIST_ALL     (0xf000 | 0x9f)
+
+/* Fix so that people don't have to run with <sys/queue.h> */
+#ifndef TAILQ_ENTRY
+#define _EVENT_DEFINED_TQENTRY
+#define TAILQ_ENTRY(type)                                              \
+struct {                                                               \
+       struct type *tqe_next;  /* next element */                      \
+       struct type **tqe_prev; /* address of previous next element */  \
+}
+#endif /* !TAILQ_ENTRY */
+
+#ifndef TAILQ_HEAD
+#define _EVENT_DEFINED_TQHEAD
+#define TAILQ_HEAD(name, type)                 \
+struct name {                                  \
+       struct type *tqh_first;                 \
+       struct type **tqh_last;                 \
+}
+#endif
+
+struct event_base;
+struct event {
+       TAILQ_ENTRY(event) ev_active_next;
+       TAILQ_ENTRY(event) ev_next;
+       /* for managing timeouts */
+       union {
+               TAILQ_ENTRY(event) ev_next_with_common_timeout;
+               int min_heap_idx;
+       } ev_timeout_pos;
+       evutil_socket_t ev_fd;
+
+       struct event_base *ev_base;
+
+       union {
+               /* used for io events */
+               struct {
+                       TAILQ_ENTRY(event) ev_io_next;
+                       struct timeval ev_timeout;
+               } ev_io;
+
+               /* used by signal events */
+               struct {
+                       TAILQ_ENTRY(event) ev_signal_next;
+                       short ev_ncalls;
+                       /* Allows deletes in callback */
+                       short *ev_pncalls;
+               } ev_signal;
+       } _ev;
+
+       short ev_events;
+       short ev_res;           /* result passed to event callback */
+       short ev_flags;
+       ev_uint8_t ev_pri;      /* smaller numbers are higher priority */
+       ev_uint8_t ev_closure;
+       struct timeval ev_timeout;
+
+       /* allows us to adopt for different types of events */
+       void (*ev_callback)(evutil_socket_t, short, void *arg);
+       void *ev_arg;
+};
+
+TAILQ_HEAD (event_list, event);
+
+#ifdef _EVENT_DEFINED_TQENTRY
+#undef TAILQ_ENTRY
+#endif
+
+#ifdef _EVENT_DEFINED_TQHEAD
+#undef TAILQ_HEAD
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_EVENT_STRUCT_H_ */
diff --git a/libevent/include/event2/http.h b/libevent/include/event2/http.h
new file mode 100644 (file)
index 0000000..c6ee1db
--- /dev/null
@@ -0,0 +1,863 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_HTTP_H_
+#define _EVENT2_HTTP_H_
+
+/* For int types. */
+#include <event2/util.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* In case we haven't included the right headers yet. */
+struct evbuffer;
+struct event_base;
+
+/** @file event2/http.h
+ *
+ * Basic support for HTTP serving.
+ *
+ * As Libevent is a library for dealing with event notification and most
+ * interesting applications are networked today, I have often found the
+ * need to write HTTP code.  The following prototypes and definitions provide
+ * an application with a minimal interface for making HTTP requests and for
+ * creating a very simple HTTP server.
+ */
+
+/* Response codes */
+#define HTTP_OK                        200     /**< request completed ok */
+#define HTTP_NOCONTENT         204     /**< request does not have content */
+#define HTTP_MOVEPERM          301     /**< the uri moved permanently */
+#define HTTP_MOVETEMP          302     /**< the uri moved temporarily */
+#define HTTP_NOTMODIFIED       304     /**< page was not modified from last */
+#define HTTP_BADREQUEST                400     /**< invalid http request was made */
+#define HTTP_NOTFOUND          404     /**< could not find content for uri */
+#define HTTP_BADMETHOD         405     /**< method not allowed for this uri */
+#define HTTP_ENTITYTOOLARGE    413     /**<  */
+#define HTTP_EXPECTATIONFAILED 417     /**< we can't handle this expectation */
+#define HTTP_INTERNAL           500     /**< internal error */
+#define HTTP_NOTIMPLEMENTED     501     /**< not implemented */
+#define HTTP_SERVUNAVAIL       503     /**< the server is not available */
+
+struct evhttp;
+struct evhttp_request;
+struct evkeyvalq;
+struct evhttp_bound_socket;
+struct evconnlistener;
+
+/**
+ * Create a new HTTP server.
+ *
+ * @param base (optional) the event base to receive the HTTP events
+ * @return a pointer to a newly initialized evhttp server structure
+ * @see evhttp_free()
+ */
+struct evhttp *evhttp_new(struct event_base *base);
+
+/**
+ * Binds an HTTP server on the specified address and port.
+ *
+ * Can be called multiple times to bind the same http server
+ * to multiple different ports.
+ *
+ * @param http a pointer to an evhttp object
+ * @param address a string containing the IP address to listen(2) on
+ * @param port the port number to listen on
+ * @return 0 on success, -1 on failure.
+ * @see evhttp_accept_socket()
+ */
+int evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port);
+
+/**
+ * Like evhttp_bind_socket(), but returns a handle for referencing the socket.
+ *
+ * The returned pointer is not valid after \a http is freed.
+ *
+ * @param http a pointer to an evhttp object
+ * @param address a string containing the IP address to listen(2) on
+ * @param port the port number to listen on
+ * @return Handle for the socket on success, NULL on failure.
+ * @see evhttp_bind_socket(), evhttp_del_accept_socket()
+ */
+struct evhttp_bound_socket *evhttp_bind_socket_with_handle(struct evhttp *http, const char *address, ev_uint16_t port);
+
+/**
+ * Makes an HTTP server accept connections on the specified socket.
+ *
+ * This may be useful to create a socket and then fork multiple instances
+ * of an http server, or when a socket has been communicated via file
+ * descriptor passing in situations where an http servers does not have
+ * permissions to bind to a low-numbered port.
+ *
+ * Can be called multiple times to have the http server listen to
+ * multiple different sockets.
+ *
+ * @param http a pointer to an evhttp object
+ * @param fd a socket fd that is ready for accepting connections
+ * @return 0 on success, -1 on failure.
+ * @see evhttp_bind_socket()
+ */
+int evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd);
+
+/**
+ * Like evhttp_accept_socket(), but returns a handle for referencing the socket.
+ *
+ * The returned pointer is not valid after \a http is freed.
+ *
+ * @param http a pointer to an evhttp object
+ * @param fd a socket fd that is ready for accepting connections
+ * @return Handle for the socket on success, NULL on failure.
+ * @see evhttp_accept_socket(), evhttp_del_accept_socket()
+ */
+struct evhttp_bound_socket *evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd);
+
+/**
+ * The most low-level evhttp_bind/accept method: takes an evconnlistener, and
+ * returns an evhttp_bound_socket.  The listener will be freed when the bound
+ * socket is freed.
+ */
+struct evhttp_bound_socket *evhttp_bind_listener(struct evhttp *http, struct evconnlistener *listener);
+
+/**
+ * Return the listener used to implement a bound socket.
+ */
+struct evconnlistener *evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound);
+
+/**
+ * Makes an HTTP server stop accepting connections on the specified socket
+ *
+ * This may be useful when a socket has been sent via file descriptor passing
+ * and is no longer needed by the current process.
+ *
+ * If you created this bound socket with evhttp_bind_socket_with_handle or
+ * evhttp_accept_socket_with_handle, this function closes the fd you provided.
+ * If you created this bound socket with evhttp_bind_listener, this function
+ * frees the listener you provided.
+ *
+ * \a bound_socket is an invalid pointer after this call returns.
+ *
+ * @param http a pointer to an evhttp object
+ * @param bound_socket a handle returned by evhttp_{bind,accept}_socket_with_handle
+ * @see evhttp_bind_socket_with_handle(), evhttp_accept_socket_with_handle()
+ */
+void evhttp_del_accept_socket(struct evhttp *http, struct evhttp_bound_socket *bound_socket);
+
+/**
+ * Get the raw file descriptor referenced by an evhttp_bound_socket.
+ *
+ * @param bound_socket a handle returned by evhttp_{bind,accept}_socket_with_handle
+ * @return the file descriptor used by the bound socket
+ * @see evhttp_bind_socket_with_handle(), evhttp_accept_socket_with_handle()
+ */
+evutil_socket_t evhttp_bound_socket_get_fd(struct evhttp_bound_socket *bound_socket);
+
+/**
+ * Free the previously created HTTP server.
+ *
+ * Works only if no requests are currently being served.
+ *
+ * @param http the evhttp server object to be freed
+ * @see evhttp_start()
+ */
+void evhttp_free(struct evhttp* http);
+
+/** XXX Document. */
+void evhttp_set_max_headers_size(struct evhttp* http, ev_ssize_t max_headers_size);
+/** XXX Document. */
+void evhttp_set_max_body_size(struct evhttp* http, ev_ssize_t max_body_size);
+
+/**
+  Sets the what HTTP methods are supported in requests accepted by this
+  server, and passed to user callbacks.
+
+  If not supported they will generate a "405 Method not allowed" response.
+
+  By default this includes the following methods: GET, POST, HEAD, PUT, DELETE
+
+  @param http the http server on which to set the methods
+  @param methods bit mask constructed from evhttp_cmd_type values
+*/
+void evhttp_set_allowed_methods(struct evhttp* http, ev_uint16_t methods);
+
+/**
+   Set a callback for a specified URI
+
+   @param http the http sever on which to set the callback
+   @param path the path for which to invoke the callback
+   @param cb the callback function that gets invoked on requesting path
+   @param cb_arg an additional context argument for the callback
+   @return 0 on success, -1 if the callback existed already, -2 on failure
+*/
+int evhttp_set_cb(struct evhttp *http, const char *path,
+    void (*cb)(struct evhttp_request *, void *), void *cb_arg);
+
+/** Removes the callback for a specified URI */
+int evhttp_del_cb(struct evhttp *, const char *);
+
+/**
+    Set a callback for all requests that are not caught by specific callbacks
+
+    Invokes the specified callback for all requests that do not match any of
+    the previously specified request paths.  This is catchall for requests not
+    specifically configured with evhttp_set_cb().
+
+    @param http the evhttp server object for which to set the callback
+    @param cb the callback to invoke for any unmatched requests
+    @param arg an context argument for the callback
+*/
+void evhttp_set_gencb(struct evhttp *http,
+    void (*cb)(struct evhttp_request *, void *), void *arg);
+
+/**
+   Adds a virtual host to the http server.
+
+   A virtual host is a newly initialized evhttp object that has request
+   callbacks set on it via evhttp_set_cb() or evhttp_set_gencb().  It
+   most not have any listing sockets associated with it.
+
+   If the virtual host has not been removed by the time that evhttp_free()
+   is called on the main http server, it will be automatically freed, too.
+
+   It is possible to have hierarchical vhosts.  For example: A vhost
+   with the pattern *.example.com may have other vhosts with patterns
+   foo.example.com and bar.example.com associated with it.
+
+   @param http the evhttp object to which to add a virtual host
+   @param pattern the glob pattern against which the hostname is matched.
+     The match is case insensitive and follows otherwise regular shell
+     matching.
+   @param vhost the virtual host to add the regular http server.
+   @return 0 on success, -1 on failure
+   @see evhttp_remove_virtual_host()
+*/
+int evhttp_add_virtual_host(struct evhttp* http, const char *pattern,
+    struct evhttp* vhost);
+
+/**
+   Removes a virtual host from the http server.
+
+   @param http the evhttp object from which to remove the virtual host
+   @param vhost the virtual host to remove from the regular http server.
+   @return 0 on success, -1 on failure
+   @see evhttp_add_virtual_host()
+*/
+int evhttp_remove_virtual_host(struct evhttp* http, struct evhttp* vhost);
+
+/**
+   Add a server alias to an http object. The http object can be a virtual
+   host or the main server.
+
+   @param http the evhttp object
+   @param alias the alias to add
+   @see evhttp_add_remove_alias()
+*/
+int evhttp_add_server_alias(struct evhttp *http, const char *alias);
+
+/**
+   Remove a server alias from an http object.
+
+   @param http the evhttp object
+   @param alias the alias to remove
+   @see evhttp_add_server_alias()
+*/
+int evhttp_remove_server_alias(struct evhttp *http, const char *alias);
+
+/**
+ * Set the timeout for an HTTP request.
+ *
+ * @param http an evhttp object
+ * @param timeout_in_secs the timeout, in seconds
+ */
+void evhttp_set_timeout(struct evhttp *http, int timeout_in_secs);
+
+/* Request/Response functionality */
+
+/**
+ * Send an HTML error message to the client.
+ *
+ * @param req a request object
+ * @param error the HTTP error code
+ * @param reason a brief explanation of the error.  If this is NULL, we'll
+ *    just use the standard meaning of the error code.
+ */
+void evhttp_send_error(struct evhttp_request *req, int error,
+    const char *reason);
+
+/**
+ * Send an HTML reply to the client.
+ *
+ * The body of the reply consists of the data in databuf.  After calling
+ * evhttp_send_reply() databuf will be empty, but the buffer is still
+ * owned by the caller and needs to be deallocated by the caller if
+ * necessary.
+ *
+ * @param req a request object
+ * @param code the HTTP response code to send
+ * @param reason a brief message to send with the response code
+ * @param databuf the body of the response
+ */
+void evhttp_send_reply(struct evhttp_request *req, int code,
+    const char *reason, struct evbuffer *databuf);
+
+/* Low-level response interface, for streaming/chunked replies */
+
+/**
+   Initiate a reply that uses Transfer-Encoding chunked.
+
+   This allows the caller to stream the reply back to the client and is
+   useful when either not all of the reply data is immediately available
+   or when sending very large replies.
+
+   The caller needs to supply data chunks with evhttp_send_reply_chunk()
+   and complete the reply by calling evhttp_send_reply_end().
+
+   @param req a request object
+   @param code the HTTP response code to send
+   @param reason a brief message to send with the response code
+*/
+void evhttp_send_reply_start(struct evhttp_request *req, int code,
+    const char *reason);
+
+/**
+   Send another data chunk as part of an ongoing chunked reply.
+
+   The reply chunk consists of the data in databuf.  After calling
+   evhttp_send_reply_chunk() databuf will be empty, but the buffer is
+   still owned by the caller and needs to be deallocated by the caller
+   if necessary.
+
+   @param req a request object
+   @param databuf the data chunk to send as part of the reply.
+*/
+void evhttp_send_reply_chunk(struct evhttp_request *req,
+    struct evbuffer *databuf);
+/**
+   Complete a chunked reply, freeing the request as appropriate.
+
+   @param req a request object
+*/
+void evhttp_send_reply_end(struct evhttp_request *req);
+
+/*
+ * Interfaces for making requests
+ */
+
+/** The different request types supported by evhttp.  These are as specified
+ * in RFC2616, except for PATCH which is specified by RFC5789.
+ *
+ * By default, only some of these methods are accepted and passed to user
+ * callbacks; use evhttp_set_allowed_methods() to change which methods
+ * are allowed.
+ */
+enum evhttp_cmd_type {
+       EVHTTP_REQ_GET     = 1 << 0,
+       EVHTTP_REQ_POST    = 1 << 1,
+       EVHTTP_REQ_HEAD    = 1 << 2,
+       EVHTTP_REQ_PUT     = 1 << 3,
+       EVHTTP_REQ_DELETE  = 1 << 4,
+       EVHTTP_REQ_OPTIONS = 1 << 5,
+       EVHTTP_REQ_TRACE   = 1 << 6,
+       EVHTTP_REQ_CONNECT = 1 << 7,
+       EVHTTP_REQ_PATCH   = 1 << 8
+};
+
+/** a request object can represent either a request or a reply */
+enum evhttp_request_kind { EVHTTP_REQUEST, EVHTTP_RESPONSE };
+
+/**
+ * Creates a new request object that needs to be filled in with the request
+ * parameters.  The callback is executed when the request completed or an
+ * error occurred.
+ */
+struct evhttp_request *evhttp_request_new(
+       void (*cb)(struct evhttp_request *, void *), void *arg);
+
+/**
+ * Enable delivery of chunks to requestor.
+ * @param cb will be called after every read of data with the same argument
+ *           as the completion callback. Will never be called on an empty
+ *           response. May drain the input buffer; it will be drained
+ *           automatically on return.
+ */
+void evhttp_request_set_chunked_cb(struct evhttp_request *,
+    void (*cb)(struct evhttp_request *, void *));
+
+/** Frees the request object and removes associated events. */
+void evhttp_request_free(struct evhttp_request *req);
+
+struct evdns_base;
+
+/**
+ * A connection object that can be used to for making HTTP requests.  The
+ * connection object tries to resolve address and establish the connection
+ * when it is given an http request object.
+ *
+ * @param base the event_base to use for handling the connection
+ * @param dnsbase the dns_base to use for resolving host names; if not
+ *     specified host name resolution will block.
+ * @param address the address to which to connect
+ * @param port the port to connect to
+ * @return an evhttp_connection object that can be used for making requests
+ */
+struct evhttp_connection *evhttp_connection_base_new(
+       struct event_base *base, struct evdns_base *dnsbase,
+       const char *address, unsigned short port);
+
+/**
+ * Return the bufferevent that an evhttp_connection is using.
+ */
+struct bufferevent *evhttp_connection_get_bufferevent(
+       struct evhttp_connection *evcon);
+
+/** Takes ownership of the request object
+ *
+ * Can be used in a request callback to keep onto the request until
+ * evhttp_request_free() is explicitly called by the user.
+ */
+void evhttp_request_own(struct evhttp_request *req);
+
+/** Returns 1 if the request is owned by the user */
+int evhttp_request_is_owned(struct evhttp_request *req);
+
+/**
+ * Returns the connection object associated with the request or NULL
+ *
+ * The user needs to either free the request explicitly or call
+ * evhttp_send_reply_end().
+ */
+struct evhttp_connection *evhttp_request_get_connection(struct evhttp_request *req);
+
+/**
+ * Returns the underlying event_base for this connection
+ */
+struct event_base *evhttp_connection_get_base(struct evhttp_connection *req);
+
+void evhttp_connection_set_max_headers_size(struct evhttp_connection *evcon,
+    ev_ssize_t new_max_headers_size);
+
+void evhttp_connection_set_max_body_size(struct evhttp_connection* evcon,
+    ev_ssize_t new_max_body_size);
+
+/** Frees an http connection */
+void evhttp_connection_free(struct evhttp_connection *evcon);
+
+/** sets the ip address from which http connections are made */
+void evhttp_connection_set_local_address(struct evhttp_connection *evcon,
+    const char *address);
+
+/** sets the local port from which http connections are made */
+void evhttp_connection_set_local_port(struct evhttp_connection *evcon,
+    ev_uint16_t port);
+
+/** Sets the timeout for events related to this connection */
+void evhttp_connection_set_timeout(struct evhttp_connection *evcon,
+    int timeout_in_secs);
+
+/** Sets the retry limit for this connection - -1 repeats indefinitely */
+void evhttp_connection_set_retries(struct evhttp_connection *evcon,
+    int retry_max);
+
+/** Set a callback for connection close. */
+void evhttp_connection_set_closecb(struct evhttp_connection *evcon,
+    void (*)(struct evhttp_connection *, void *), void *);
+
+/** Get the remote address and port associated with this connection. */
+void evhttp_connection_get_peer(struct evhttp_connection *evcon,
+    char **address, ev_uint16_t *port);
+
+/**
+    Make an HTTP request over the specified connection.
+
+    The connection gets ownership of the request.  On failure, the
+    request object is no longer valid as it has been freed.
+
+    @param evcon the evhttp_connection object over which to send the request
+    @param req the previously created and configured request object
+    @param type the request type EVHTTP_REQ_GET, EVHTTP_REQ_POST, etc.
+    @param uri the URI associated with the request
+    @return 0 on success, -1 on failure
+    @see evhttp_cancel_request()
+*/
+int evhttp_make_request(struct evhttp_connection *evcon,
+    struct evhttp_request *req,
+    enum evhttp_cmd_type type, const char *uri);
+
+/**
+   Cancels a pending HTTP request.
+
+   Cancels an ongoing HTTP request.  The callback associated with this request
+   is not executed and the request object is freed.  If the request is
+   currently being processed, e.g. it is ongoing, the corresponding
+   evhttp_connection object is going to get reset.
+
+   A request cannot be canceled if its callback has executed already. A request
+   may be canceled reentrantly from its chunked callback.
+
+   @param req the evhttp_request to cancel; req becomes invalid after this call.
+*/
+void evhttp_cancel_request(struct evhttp_request *req);
+
+/**
+ * A structure to hold a parsed URI or Relative-Ref conforming to RFC3986.
+ */
+struct evhttp_uri;
+
+/** Returns the request URI */
+const char *evhttp_request_get_uri(const struct evhttp_request *req);
+/** Returns the request URI (parsed) */
+const struct evhttp_uri *evhttp_request_get_evhttp_uri(const struct evhttp_request *req);
+/** Returns the request command */
+enum evhttp_cmd_type evhttp_request_get_command(const struct evhttp_request *req);
+
+int evhttp_request_get_response_code(const struct evhttp_request *req);
+
+/** Returns the input headers */
+struct evkeyvalq *evhttp_request_get_input_headers(struct evhttp_request *req);
+/** Returns the output headers */
+struct evkeyvalq *evhttp_request_get_output_headers(struct evhttp_request *req);
+/** Returns the input buffer */
+struct evbuffer *evhttp_request_get_input_buffer(struct evhttp_request *req);
+/** Returns the output buffer */
+struct evbuffer *evhttp_request_get_output_buffer(struct evhttp_request *req);
+/** Returns the host associated with the request. If a client sends an absolute
+    URI, the host part of that is preferred. Otherwise, the input headers are
+    searched for a Host: header. NULL is returned if no absolute URI or Host:
+    header is provided. */
+const char *evhttp_request_get_host(struct evhttp_request *req);
+
+/* Interfaces for dealing with HTTP headers */
+
+/**
+   Finds the value belonging to a header.
+
+   @param headers the evkeyvalq object in which to find the header
+   @param key the name of the header to find
+   @returns a pointer to the value for the header or NULL if the header
+     count not be found.
+   @see evhttp_add_header(), evhttp_remove_header()
+*/
+const char *evhttp_find_header(const struct evkeyvalq *headers,
+    const char *key);
+
+/**
+   Removes a header from a list of existing headers.
+
+   @param headers the evkeyvalq object from which to remove a header
+   @param key the name of the header to remove
+   @returns 0 if the header was removed, -1  otherwise.
+   @see evhttp_find_header(), evhttp_add_header()
+*/
+int evhttp_remove_header(struct evkeyvalq *headers, const char *key);
+
+/**
+   Adds a header to a list of existing headers.
+
+   @param headers the evkeyvalq object to which to add a header
+   @param key the name of the header
+   @param value the value belonging to the header
+   @returns 0 on success, -1  otherwise.
+   @see evhttp_find_header(), evhttp_clear_headers()
+*/
+int evhttp_add_header(struct evkeyvalq *headers, const char *key, const char *value);
+
+/**
+   Removes all headers from the header list.
+
+   @param headers the evkeyvalq object from which to remove all headers
+*/
+void evhttp_clear_headers(struct evkeyvalq *headers);
+
+/* Miscellaneous utility functions */
+
+
+/**
+   Helper function to encode a string for inclusion in a URI.  All
+   characters are replaced by their hex-escaped (%22) equivalents,
+   except for characters explicitly unreserved by RFC3986 -- that is,
+   ASCII alphanumeric characters, hyphen, dot, underscore, and tilde.
+
+   The returned string must be freed by the caller.
+
+   @param str an unencoded string
+   @return a newly allocated URI-encoded string or NULL on failure
+ */
+char *evhttp_encode_uri(const char *str);
+
+/**
+   As evhttp_encode_uri, but if 'size' is nonnegative, treat the string
+   as being 'size' bytes long.  This allows you to encode strings that
+   may contain 0-valued bytes.
+
+   The returned string must be freed by the caller.
+
+   @param str an unencoded string
+   @param size the length of the string to encode, or -1 if the string
+      is NUL-terminated
+   @param space_to_plus if true, space characters in 'str' are encoded
+      as +, not %20.
+   @return a newly allocate URI-encoded string, or NULL on failure.
+ */
+char *evhttp_uriencode(const char *str, ev_ssize_t size, int space_to_plus);
+
+/**
+  Helper function to sort of decode a URI-encoded string.  Unlike
+  evhttp_get_decoded_uri, it decodes all plus characters that appear
+  _after_ the first question mark character, but no plusses that occur
+  before.  This is not a good way to decode URIs in whole or in part.
+
+  The returned string must be freed by the caller
+
+  @deprecated  This function is deprecated; you probably want to use
+     evhttp_get_decoded_uri instead.
+
+  @param uri an encoded URI
+  @return a newly allocated unencoded URI or NULL on failure
+ */
+char *evhttp_decode_uri(const char *uri);
+
+/**
+  Helper function to decode a URI-escaped string or HTTP parameter.
+
+  If 'decode_plus' is 1, then we decode the string as an HTTP parameter
+  value, and convert all plus ('+') characters to spaces.  If
+  'decode_plus' is 0, we leave all plus characters unchanged.
+
+  The returned string must be freed by the caller.
+
+  @param uri a URI-encode encoded URI
+  @param decode_plus determines whether we convert '+' to sapce.
+  @param size_out if size_out is not NULL, *size_out is set to the size of the
+     returned string
+  @return a newly allocated unencoded URI or NULL on failure
+ */
+char *evhttp_uridecode(const char *uri, int decode_plus,
+    size_t *size_out);
+
+/**
+   Helper function to parse out arguments in a query.
+
+   Parsing a URI like
+
+      http://foo.com/?q=test&s=some+thing
+
+   will result in two entries in the key value queue.
+
+   The first entry is: key="q", value="test"
+   The second entry is: key="s", value="some thing"
+
+   @deprecated This function is deprecated as of Libevent 2.0.9.  Use
+     evhttp_uri_parse and evhttp_parse_query_str instead.
+
+   @param uri the request URI
+   @param headers the head of the evkeyval queue
+   @return 0 on success, -1 on failure
+ */
+int evhttp_parse_query(const char *uri, struct evkeyvalq *headers);
+
+/**
+   Helper function to parse out arguments from the query portion of an
+   HTTP URI.
+
+   Parsing a query string like
+
+     q=test&s=some+thing
+
+   will result in two entries in the key value queue.
+
+   The first entry is: key="q", value="test"
+   The second entry is: key="s", value="some thing"
+
+   @param query_parse the query portion of the URI
+   @param headers the head of the evkeyval queue
+   @return 0 on success, -1 on failure
+ */
+int evhttp_parse_query_str(const char *uri, struct evkeyvalq *headers);
+
+/**
+ * Escape HTML character entities in a string.
+ *
+ * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
+ * &#039; and &amp; correspondingly.
+ *
+ * The returned string needs to be freed by the caller.
+ *
+ * @param html an unescaped HTML string
+ * @return an escaped HTML string or NULL on error
+ */
+char *evhttp_htmlescape(const char *html);
+
+/**
+ * Return a new empty evhttp_uri with no fields set.
+ */
+struct evhttp_uri *evhttp_uri_new(void);
+
+/**
+ * Changes the flags set on a given URI.  See EVHTTP_URI_* for
+ * a list of flags.
+ **/
+void evhttp_uri_set_flags(struct evhttp_uri *uri, unsigned flags);
+
+/** Return the scheme of an evhttp_uri, or NULL if there is no scheme has
+ * been set and the evhttp_uri contains a Relative-Ref. */
+const char *evhttp_uri_get_scheme(const struct evhttp_uri *uri);
+/**
+ * Return the userinfo part of an evhttp_uri, or NULL if it has no userinfo
+ * set.
+ */
+const char *evhttp_uri_get_userinfo(const struct evhttp_uri *uri);
+/**
+ * Return the host part of an evhttp_uri, or NULL if it has no host set.
+ * The host may either be a regular hostname (conforming to the RFC 3986
+ * "regname" production), or an IPv4 address, or the empty string, or a
+ * bracketed IPv6 address, or a bracketed 'IP-Future' address.
+ *
+ * Note that having a NULL host means that the URI has no authority
+ * section, but having an empty-string host means that the URI has an
+ * authority section with no host part.  For example,
+ * "mailto:user@example.com" has a host of NULL, but "file:///etc/motd"
+ * has a host of "".
+ */
+const char *evhttp_uri_get_host(const struct evhttp_uri *uri);
+/** Return the port part of an evhttp_uri, or -1 if there is no port set. */
+int evhttp_uri_get_port(const struct evhttp_uri *uri);
+/** Return the path part of an evhttp_uri, or NULL if it has no path set */
+const char *evhttp_uri_get_path(const struct evhttp_uri *uri);
+/** Return the query part of an evhttp_uri (excluding the leading "?"), or
+ * NULL if it has no query set */
+const char *evhttp_uri_get_query(const struct evhttp_uri *uri);
+/** Return the fragment part of an evhttp_uri (excluding the leading "#"),
+ * or NULL if it has no fragment set */
+const char *evhttp_uri_get_fragment(const struct evhttp_uri *uri);
+
+/** Set the scheme of an evhttp_uri, or clear the scheme if scheme==NULL.
+ * Returns 0 on success, -1 if scheme is not well-formed. */
+int evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme);
+/** Set the userinfo of an evhttp_uri, or clear the userinfo if userinfo==NULL.
+ * Returns 0 on success, -1 if userinfo is not well-formed. */
+int evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo);
+/** Set the host of an evhttp_uri, or clear the host if host==NULL.
+ * Returns 0 on success, -1 if host is not well-formed. */
+int evhttp_uri_set_host(struct evhttp_uri *uri, const char *host);
+/** Set the port of an evhttp_uri, or clear the port if port==-1.
+ * Returns 0 on success, -1 if port is not well-formed. */
+int evhttp_uri_set_port(struct evhttp_uri *uri, int port);
+/** Set the path of an evhttp_uri, or clear the path if path==NULL.
+ * Returns 0 on success, -1 if path is not well-formed. */
+int evhttp_uri_set_path(struct evhttp_uri *uri, const char *path);
+/** Set the query of an evhttp_uri, or clear the query if query==NULL.
+ * The query should not include a leading "?".
+ * Returns 0 on success, -1 if query is not well-formed. */
+int evhttp_uri_set_query(struct evhttp_uri *uri, const char *query);
+/** Set the fragment of an evhttp_uri, or clear the fragment if fragment==NULL.
+ * The fragment should not include a leading "#".
+ * Returns 0 on success, -1 if fragment is not well-formed. */
+int evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment);
+
+/**
+ * Helper function to parse a URI-Reference as specified by RFC3986.
+ *
+ * This function matches the URI-Reference production from RFC3986,
+ * which includes both URIs like
+ *
+ *    scheme://[[userinfo]@]foo.com[:port]]/[path][?query][#fragment]
+ *
+ *  and relative-refs like
+ *
+ *    [path][?query][#fragment]
+ *
+ * Any optional elements portions not present in the original URI are
+ * left set to NULL in the resulting evhttp_uri.  If no port is
+ * specified, the port is set to -1.
+ *
+ * Note that no decoding is performed on percent-escaped characters in
+ * the string; if you want to parse them, use evhttp_uridecode or
+ * evhttp_parse_query_str as appropriate.
+ *
+ * Note also that most URI schemes will have additional constraints that
+ * this function does not know about, and cannot check.  For example,
+ * mailto://www.example.com/cgi-bin/fortune.pl is not a reasonable
+ * mailto url, http://www.example.com:99999/ is not a reasonable HTTP
+ * URL, and ftp:username@example.com is not a reasonable FTP URL.
+ * Nevertheless, all of these URLs conform to RFC3986, and this function
+ * accepts all of them as valid.
+ *
+ * @param source_uri the request URI
+ * @param flags Zero or more EVHTTP_URI_* flags to affect the behavior
+ *              of the parser.
+ * @return uri container to hold parsed data, or NULL if there is error
+ * @see evhttp_uri_free()
+ */
+struct evhttp_uri *evhttp_uri_parse_with_flags(const char *source_uri,
+    unsigned flags);
+
+/** Tolerate URIs that do not conform to RFC3986.
+ *
+ * Unfortunately, some HTTP clients generate URIs that, according to RFC3986,
+ * are not conformant URIs.  If you need to support these URIs, you can
+ * do so by passing this flag to evhttp_uri_parse_with_flags.
+ *
+ * Currently, these changes are:
+ * <ul>
+ *   <li> Nonconformant URIs are allowed to contain otherwise unreasonable
+ *        characters in their path, query, and fragment components.
+ * </ul>
+ */
+#define EVHTTP_URI_NONCONFORMANT 0x01
+
+/** Alias for evhttp_uri_parse_with_flags(source_uri, 0) */
+struct evhttp_uri *evhttp_uri_parse(const char *source_uri);
+
+/**
+ * Free all memory allocated for a parsed uri.  Only use this for URIs
+ * generated by evhttp_uri_parse.
+ *
+ * @param uri container with parsed data
+ * @see evhttp_uri_parse()
+ */
+void evhttp_uri_free(struct evhttp_uri *uri);
+
+/**
+ * Join together the uri parts from parsed data to form a URI-Reference.
+ *
+ * Note that no escaping of reserved characters is done on the members
+ * of the evhttp_uri, so the generated string might not be a valid URI
+ * unless the members of evhttp_uri are themselves valid.
+ *
+ * @param uri container with parsed data
+ * @param buf destination buffer
+ * @param limit destination buffer size
+ * @return an joined uri as string or NULL on error
+ * @see evhttp_uri_parse()
+ */
+char *evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_HTTP_H_ */
diff --git a/libevent/include/event2/http_compat.h b/libevent/include/event2/http_compat.h
new file mode 100644 (file)
index 0000000..9e902a4
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_HTTP_COMPAT_H_
+#define _EVENT2_HTTP_COMPAT_H_
+
+/** @file event2/http_compat.h
+
+  Potentially non-threadsafe versions of the functions in http.h: provided
+  only for backwards compatibility.
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+ * Start an HTTP server on the specified address and port
+ *
+ * @deprecated It does not allow an event base to be specified
+ *
+ * @param address the address to which the HTTP server should be bound
+ * @param port the port number on which the HTTP server should listen
+ * @return an struct evhttp object
+ */
+struct evhttp *evhttp_start(const char *address, unsigned short port);
+
+/**
+ * A connection object that can be used to for making HTTP requests.  The
+ * connection object tries to establish the connection when it is given an
+ * http request object.
+ *
+ * @deprecated It does not allow an event base to be specified
+ */
+struct evhttp_connection *evhttp_connection_new(
+       const char *address, unsigned short port);
+
+/**
+ * Associates an event base with the connection - can only be called
+ * on a freshly created connection object that has not been used yet.
+ *
+ * @deprecated XXXX Why?
+ */
+void evhttp_connection_set_base(struct evhttp_connection *evcon,
+    struct event_base *base);
+
+
+/** Returns the request URI */
+#define evhttp_request_uri evhttp_request_get_uri
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_EVENT_COMPAT_H_ */
diff --git a/libevent/include/event2/http_struct.h b/libevent/include/event2/http_struct.h
new file mode 100644 (file)
index 0000000..41a92a9
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_HTTP_STRUCT_H_
+#define _EVENT2_HTTP_STRUCT_H_
+
+/** @file event2/http_struct.h
+
+  Data structures for http.  Using these structures may hurt forward
+  compatibility with later versions of Libevent: be careful!
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+ * the request structure that a server receives.
+ * WARNING: expect this structure to change.  I will try to provide
+ * reasonable accessors.
+ */
+struct evhttp_request {
+#if defined(TAILQ_ENTRY)
+       TAILQ_ENTRY(evhttp_request) next;
+#else
+struct {
+       struct evhttp_request *tqe_next;
+       struct evhttp_request **tqe_prev;
+}       next;
+#endif
+
+       /* the connection object that this request belongs to */
+       struct evhttp_connection *evcon;
+       int flags;
+/** The request obj owns the evhttp connection and needs to free it */
+#define EVHTTP_REQ_OWN_CONNECTION      0x0001
+/** Request was made via a proxy */
+#define EVHTTP_PROXY_REQUEST           0x0002
+/** The request object is owned by the user; the user must free it */
+#define EVHTTP_USER_OWNED              0x0004
+/** The request will be used again upstack; freeing must be deferred */
+#define EVHTTP_REQ_DEFER_FREE          0x0008
+/** The request should be freed upstack */
+#define EVHTTP_REQ_NEEDS_FREE          0x0010
+
+       struct evkeyvalq *input_headers;
+       struct evkeyvalq *output_headers;
+
+       /* address of the remote host and the port connection came from */
+       char *remote_host;
+       ev_uint16_t remote_port;
+
+       /* cache of the hostname for evhttp_request_get_host */
+       char *host_cache;
+
+       enum evhttp_request_kind kind;
+       enum evhttp_cmd_type type;
+
+       size_t headers_size;
+       size_t body_size;
+
+       char *uri;                      /* uri after HTTP request was parsed */
+       struct evhttp_uri *uri_elems;   /* uri elements */
+
+       char major;                     /* HTTP Major number */
+       char minor;                     /* HTTP Minor number */
+
+       int response_code;              /* HTTP Response code */
+       char *response_code_line;       /* Readable response */
+
+       struct evbuffer *input_buffer;  /* read data */
+       ev_int64_t ntoread;
+       unsigned chunked:1,             /* a chunked request */
+           userdone:1;                 /* the user has sent all data */
+
+       struct evbuffer *output_buffer; /* outgoing post or data */
+
+       /* Callback */
+       void (*cb)(struct evhttp_request *, void *);
+       void *cb_arg;
+
+       /*
+        * Chunked data callback - call for each completed chunk if
+        * specified.  If not specified, all the data is delivered via
+        * the regular callback.
+        */
+       void (*chunk_cb)(struct evhttp_request *, void *);
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_HTTP_STRUCT_H_ */
+
diff --git a/libevent/include/event2/keyvalq_struct.h b/libevent/include/event2/keyvalq_struct.h
new file mode 100644 (file)
index 0000000..ab8040b
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_EVENT_KEYVALQ_STRUCT_H_
+#define _EVENT2_EVENT_KEYVALQ_STRUCT_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Fix so that people don't have to run with <sys/queue.h> */
+/* XXXX This code is duplicated with event_struct.h */
+#ifndef TAILQ_ENTRY
+#define _EVENT_DEFINED_TQENTRY
+#define TAILQ_ENTRY(type)                                              \
+struct {                                                               \
+       struct type *tqe_next;  /* next element */                      \
+       struct type **tqe_prev; /* address of previous next element */  \
+}
+#endif /* !TAILQ_ENTRY */
+
+#ifndef TAILQ_HEAD
+#define _EVENT_DEFINED_TQHEAD
+#define TAILQ_HEAD(name, type)                 \
+struct name {                                  \
+       struct type *tqh_first;                 \
+       struct type **tqh_last;                 \
+}
+#endif
+
+/*
+ * Key-Value pairs.  Can be used for HTTP headers but also for
+ * query argument parsing.
+ */
+struct evkeyval {
+       TAILQ_ENTRY(evkeyval) next;
+
+       char *key;
+       char *value;
+};
+
+TAILQ_HEAD (evkeyvalq, evkeyval);
+
+/* XXXX This code is duplicated with event_struct.h */
+#ifdef _EVENT_DEFINED_TQENTRY
+#undef TAILQ_ENTRY
+#endif
+
+#ifdef _EVENT_DEFINED_TQHEAD
+#undef TAILQ_HEAD
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libevent/include/event2/listener.h b/libevent/include/event2/listener.h
new file mode 100644 (file)
index 0000000..2dc64be
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_LISTENER_H_
+#define _EVENT2_LISTENER_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event.h>
+
+struct sockaddr;
+struct evconnlistener;
+
+/**
+   A callback that we invoke when a listener has a new connection.
+
+   @param listener The evconnlistener
+   @param fd The new file descriptor
+   @param addr The source address of the connection
+   @param socklen The length of addr
+   @param user_arg the pointer passed to evconnlistener_new()
+ */
+typedef void (*evconnlistener_cb)(struct evconnlistener *, evutil_socket_t, struct sockaddr *, int socklen, void *);
+
+/**
+   A callback that we invoke when a listener encounters a non-retriable error.
+
+   @param listener The evconnlistener
+   @param user_arg the pointer passed to evconnlistener_new()
+ */
+typedef void (*evconnlistener_errorcb)(struct evconnlistener *, void *);
+
+/** Flag: Indicates that we should not make incoming sockets nonblocking
+ * before passing them to the callback. */
+#define LEV_OPT_LEAVE_SOCKETS_BLOCKING (1u<<0)
+/** Flag: Indicates that freeing the listener should close the underlying
+ * socket. */
+#define LEV_OPT_CLOSE_ON_FREE          (1u<<1)
+/** Flag: Indicates that we should set the close-on-exec flag, if possible */
+#define LEV_OPT_CLOSE_ON_EXEC          (1u<<2)
+/** Flag: Indicates that we should disable the timeout (if any) between when
+ * this socket is closed and when we can listen again on the same port. */
+#define LEV_OPT_REUSEABLE              (1u<<3)
+/** Flag: Indicates that the listener should be locked so it's safe to use
+ * from multiple threadcs at once. */
+#define LEV_OPT_THREADSAFE             (1u<<4)
+
+/**
+   Allocate a new evconnlistener object to listen for incoming TCP connections
+   on a given file descriptor.
+
+   @param base The event base to associate the listener with.
+   @param cb A callback to be invoked when a new connection arrives.  If the
+      callback is NULL, the listener will be treated as disabled until the
+      callback is set.
+   @param ptr A user-supplied pointer to give to the callback.
+   @param flags Any number of LEV_OPT_* flags
+   @param backlog Passed to the listen() call to determine the length of the
+      acceptable connection backlog.  Set to -1 for a reasonable default.
+      Set to 0 if the socket is already listening.
+   @param fd The file descriptor to listen on.  It must be a nonblocking
+      file descriptor, and it should already be bound to an appropriate
+      port and address.
+*/
+struct evconnlistener *evconnlistener_new(struct event_base *base,
+    evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+    evutil_socket_t fd);
+/**
+   Allocate a new evconnlistener object to listen for incoming TCP connections
+   on a given address.
+
+   @param base The event base to associate the listener with.
+   @param cb A callback to be invoked when a new connection arrives. If the
+      callback is NULL, the listener will be treated as disabled until the
+      callback is set.
+   @param ptr A user-supplied pointer to give to the callback.
+   @param flags Any number of LEV_OPT_* flags
+   @param backlog Passed to the listen() call to determine the length of the
+      acceptable connection backlog.  Set to -1 for a reasonable default.
+   @param addr The address to listen for connections on.
+   @param socklen The length of the address.
+ */
+struct evconnlistener *evconnlistener_new_bind(struct event_base *base,
+    evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+    const struct sockaddr *sa, int socklen);
+/**
+   Disable and deallocate an evconnlistener.
+ */
+void evconnlistener_free(struct evconnlistener *lev);
+/**
+   Re-enable an evconnlistener that has been disabled.
+ */
+int evconnlistener_enable(struct evconnlistener *lev);
+/**
+   Stop listening for connections on an evconnlistener.
+ */
+int evconnlistener_disable(struct evconnlistener *lev);
+
+/** Return an evconnlistener's associated event_base. */
+struct event_base *evconnlistener_get_base(struct evconnlistener *lev);
+
+/** Return the socket that an evconnlistner is listening on. */
+evutil_socket_t evconnlistener_get_fd(struct evconnlistener *lev);
+
+/** Change the callback on the listener to cb and its user_data to arg.
+ */
+void evconnlistener_set_cb(struct evconnlistener *lev,
+    evconnlistener_cb cb, void *arg);
+
+/** Set an evconnlistener's error callback. */
+void evconnlistener_set_error_cb(struct evconnlistener *lev,
+    evconnlistener_errorcb errorcb);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libevent/include/event2/rpc.h b/libevent/include/event2/rpc.h
new file mode 100644 (file)
index 0000000..5272edc
--- /dev/null
@@ -0,0 +1,596 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_RPC_H_
+#define _EVENT2_RPC_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** @file rpc.h
+ *
+ * This header files provides basic support for an RPC server and client.
+ *
+ * To support RPCs in a server, every supported RPC command needs to be
+ * defined and registered.
+ *
+ * EVRPC_HEADER(SendCommand, Request, Reply);
+ *
+ *  SendCommand is the name of the RPC command.
+ *  Request is the name of a structure generated by event_rpcgen.py.
+ *    It contains all parameters relating to the SendCommand RPC.  The
+ *    server needs to fill in the Reply structure.
+ *  Reply is the name of a structure generated by event_rpcgen.py.  It
+ *    contains the answer to the RPC.
+ *
+ * To register an RPC with an HTTP server, you need to first create an RPC
+ * base with:
+ *
+ *   struct evrpc_base *base = evrpc_init(http);
+ *
+ * A specific RPC can then be registered with
+ *
+ * EVRPC_REGISTER(base, SendCommand, Request, Reply,  FunctionCB, arg);
+ *
+ * when the server receives an appropriately formatted RPC, the user callback
+ * is invoked.   The callback needs to fill in the reply structure.
+ *
+ * void FunctionCB(EVRPC_STRUCT(SendCommand)* rpc, void *arg);
+ *
+ * To send the reply, call EVRPC_REQUEST_DONE(rpc);
+ *
+ * See the regression test for an example.
+ */
+
+/**
+   Determines if the member has been set in the message
+
+   @param msg the message to inspect
+   @param member the member variable to test for presences
+   @return 1 if it's present or 0 otherwise.
+*/
+#define EVTAG_HAS(msg, member) \
+       ((msg)->member##_set == 1)
+
+#ifndef _EVENT2_RPC_COMPAT_H_
+
+/**
+   Assigns a value to the member in the message.
+
+   @param msg the message to which to assign a value
+   @param member the name of the member variable
+   @param value the value to assign
+*/
+#define EVTAG_ASSIGN(msg, member, value) \
+       (*(msg)->base->member##_assign)((msg), (value))
+/**
+   Assigns a value to the member in the message.
+
+   @param msg the message to which to assign a value
+   @param member the name of the member variable
+   @param value the value to assign
+   @param len the length of the value
+*/
+#define EVTAG_ASSIGN_WITH_LEN(msg, member, value, len) \
+       (*(msg)->base->member##_assign)((msg), (value), (len))
+/**
+   Returns the value for a member.
+
+   @param msg the message from which to get the value
+   @param member the name of the member variable
+   @param pvalue a pointer to the variable to hold the value
+   @return 0 on success, -1 otherwise.
+*/
+#define EVTAG_GET(msg, member, pvalue) \
+       (*(msg)->base->member##_get)((msg), (pvalue))
+/**
+   Returns the value for a member.
+
+   @param msg the message from which to get the value
+   @param member the name of the member variable
+   @param pvalue a pointer to the variable to hold the value
+   @param plen a pointer to the length of the value
+   @return 0 on success, -1 otherwise.
+*/
+#define EVTAG_GET_WITH_LEN(msg, member, pvalue, plen)  \
+       (*(msg)->base->member##_get)((msg), (pvalue), (plen))
+
+#endif  /* _EVENT2_RPC_COMPAT_H_ */
+
+/**
+   Adds a value to an array.
+*/
+#define EVTAG_ARRAY_ADD_VALUE(msg, member, value) \
+       (*(msg)->base->member##_add)((msg), (value))
+/**
+   Allocates a new entry in the array and returns it.
+*/
+#define EVTAG_ARRAY_ADD(msg, member) \
+       (*(msg)->base->member##_add)(msg)
+/**
+   Gets a variable at the specified offset from the array.
+*/
+#define EVTAG_ARRAY_GET(msg, member, offset, pvalue)   \
+       (*(msg)->base->member##_get)((msg), (offset), (pvalue))
+/**
+   Returns the number of entries in the array.
+*/
+#define EVTAG_ARRAY_LEN(msg, member) ((msg)->member##_length)
+
+
+struct evbuffer;
+struct event_base;
+struct evrpc_req_generic;
+struct evrpc_request_wrapper;
+struct evrpc;
+
+/** The type of a specific RPC Message
+ *
+ * @param rpcname the name of the RPC message
+ */
+#define EVRPC_STRUCT(rpcname) struct evrpc_req__##rpcname
+
+struct evhttp_request;
+struct evrpc_status;
+struct evrpc_hook_meta;
+
+/** Creates the definitions and prototypes for an RPC
+ *
+ * You need to use EVRPC_HEADER to create structures and function prototypes
+ * needed by the server and client implementation.  The structures have to be
+ * defined in an .rpc file and converted to source code via event_rpcgen.py
+ *
+ * @param rpcname the name of the RPC
+ * @param reqstruct the name of the RPC request structure
+ * @param replystruct the name of the RPC reply structure
+ * @see EVRPC_GENERATE()
+ */
+#define EVRPC_HEADER(rpcname, reqstruct, rplystruct) \
+EVRPC_STRUCT(rpcname) {        \
+       struct evrpc_hook_meta *hook_meta; \
+       struct reqstruct* request; \
+       struct rplystruct* reply; \
+       struct evrpc* rpc; \
+       struct evhttp_request* http_req; \
+       struct evbuffer* rpc_data; \
+};                                                                  \
+int evrpc_send_request_##rpcname(struct evrpc_pool *, \
+    struct reqstruct *, struct rplystruct *, \
+    void (*)(struct evrpc_status *, \
+       struct reqstruct *, struct rplystruct *, void *cbarg),  \
+    void *);
+
+struct evrpc_pool;
+
+/** use EVRPC_GENERATE instead */
+struct evrpc_request_wrapper *evrpc_make_request_ctx(
+       struct evrpc_pool *pool, void *request, void *reply,
+       const char *rpcname,
+       void (*req_marshal)(struct evbuffer*, void *),
+       void (*rpl_clear)(void *),
+       int (*rpl_unmarshal)(void *, struct evbuffer *),
+       void (*cb)(struct evrpc_status *, void *, void *, void *),
+       void *cbarg);
+
+/** Creates a context structure that contains rpc specific information.
+ *
+ * EVRPC_MAKE_CTX is used to populate a RPC specific context that
+ * contains information about marshaling the RPC data types.
+ *
+ * @param rpcname the name of the RPC
+ * @param reqstruct the name of the RPC request structure
+ * @param replystruct the name of the RPC reply structure
+ * @param pool the evrpc_pool over which to make the request
+ * @param request a pointer to the RPC request structure object
+ * @param reply a pointer to the RPC reply structure object
+ * @param cb the callback function to call when the RPC has completed
+ * @param cbarg the argument to supply to the callback
+ */
+#define EVRPC_MAKE_CTX(rpcname, reqstruct, rplystruct, \
+    pool, request, reply, cb, cbarg)                                   \
+       evrpc_make_request_ctx(pool, request, reply,                    \
+           #rpcname,                                                   \
+           (void (*)(struct evbuffer *, void *))reqstruct##_marshal,   \
+           (void (*)(void *))rplystruct##_clear,                       \
+           (int (*)(void *, struct evbuffer *))rplystruct##_unmarshal, \
+           (void (*)(struct evrpc_status *, void *, void *, void *))cb, \
+           cbarg)
+
+/** Generates the code for receiving and sending an RPC message
+ *
+ * EVRPC_GENERATE is used to create the code corresponding to sending
+ * and receiving a particular RPC message
+ *
+ * @param rpcname the name of the RPC
+ * @param reqstruct the name of the RPC request structure
+ * @param replystruct the name of the RPC reply structure
+ * @see EVRPC_HEADER()
+ */
+#define EVRPC_GENERATE(rpcname, reqstruct, rplystruct)                 \
+       int evrpc_send_request_##rpcname(struct evrpc_pool *pool,       \
+           struct reqstruct *request, struct rplystruct *reply,        \
+           void (*cb)(struct evrpc_status *,                           \
+               struct reqstruct *, struct rplystruct *, void *cbarg),  \
+           void *cbarg) {                                              \
+       return evrpc_send_request_generic(pool, request, reply, \
+           (void (*)(struct evrpc_status *, void *, void *, void *))cb, \
+           cbarg,                                                      \
+           #rpcname,                                                   \
+           (void (*)(struct evbuffer *, void *))reqstruct##_marshal,   \
+           (void (*)(void *))rplystruct##_clear,                       \
+           (int (*)(void *, struct evbuffer *))rplystruct##_unmarshal); \
+}
+
+/** Provides access to the HTTP request object underlying an RPC
+ *
+ * Access to the underlying http object; can be used to look at headers or
+ * for getting the remote ip address
+ *
+ * @param rpc_req the rpc request structure provided to the server callback
+ * @return an struct evhttp_request object that can be inspected for
+ * HTTP headers or sender information.
+ */
+#define EVRPC_REQUEST_HTTP(rpc_req) (rpc_req)->http_req
+
+/** completes the server response to an rpc request */
+void evrpc_request_done(struct evrpc_req_generic *req);
+
+/** accessors for request and reply */
+void *evrpc_get_request(struct evrpc_req_generic *req);
+void *evrpc_get_reply(struct evrpc_req_generic *req);
+
+/** Creates the reply to an RPC request
+ *
+ * EVRPC_REQUEST_DONE is used to answer a request; the reply is expected
+ * to have been filled in.  The request and reply pointers become invalid
+ * after this call has finished.
+ *
+ * @param rpc_req the rpc request structure provided to the server callback
+ */
+#define EVRPC_REQUEST_DONE(rpc_req) do { \
+  struct evrpc_req_generic *_req = (struct evrpc_req_generic *)(rpc_req); \
+  evrpc_request_done(_req);                                    \
+} while (0)
+
+
+struct evrpc_base;
+struct evhttp;
+
+/* functions to start up the rpc system */
+
+/** Creates a new rpc base from which RPC requests can be received
+ *
+ * @param server a pointer to an existing HTTP server
+ * @return a newly allocated evrpc_base struct
+ * @see evrpc_free()
+ */
+struct evrpc_base *evrpc_init(struct evhttp *server);
+
+/**
+ * Frees the evrpc base
+ *
+ * For now, you are responsible for making sure that no rpcs are ongoing.
+ *
+ * @param base the evrpc_base object to be freed
+ * @see evrpc_init
+ */
+void evrpc_free(struct evrpc_base *base);
+
+/** register RPCs with the HTTP Server
+ *
+ * registers a new RPC with the HTTP server, each RPC needs to have
+ * a unique name under which it can be identified.
+ *
+ * @param base the evrpc_base structure in which the RPC should be
+ *   registered.
+ * @param name the name of the RPC
+ * @param request the name of the RPC request structure
+ * @param reply the name of the RPC reply structure
+ * @param callback the callback that should be invoked when the RPC
+ * is received.  The callback has the following prototype
+ *   void (*callback)(EVRPC_STRUCT(Message)* rpc, void *arg)
+ * @param cbarg an additional parameter that can be passed to the callback.
+ *   The parameter can be used to carry around state.
+ */
+#define EVRPC_REGISTER(base, name, request, reply, callback, cbarg)    \
+       evrpc_register_generic(base, #name,                             \
+           (void (*)(struct evrpc_req_generic *, void *))callback, cbarg, \
+           (void *(*)(void *))request##_new, NULL,                     \
+           (void (*)(void *))request##_free,                           \
+           (int (*)(void *, struct evbuffer *))request##_unmarshal,    \
+           (void *(*)(void *))reply##_new, NULL,                       \
+           (void (*)(void *))reply##_free, \
+           (int (*)(void *))reply##_complete, \
+           (void (*)(struct evbuffer *, void *))reply##_marshal)
+
+/**
+   Low level function for registering an RPC with a server.
+
+   Use EVRPC_REGISTER() instead.
+
+   @see EVRPC_REGISTER()
+*/
+int evrpc_register_rpc(struct evrpc_base *, struct evrpc *,
+    void (*)(struct evrpc_req_generic*, void *), void *);
+
+/**
+ * Unregisters an already registered RPC
+ *
+ * @param base the evrpc_base object from which to unregister an RPC
+ * @param name the name of the rpc to unregister
+ * @return -1 on error or 0 when successful.
+ * @see EVRPC_REGISTER()
+ */
+#define EVRPC_UNREGISTER(base, name) evrpc_unregister_rpc((base), #name)
+
+int evrpc_unregister_rpc(struct evrpc_base *base, const char *name);
+
+/*
+ * Client-side RPC support
+ */
+
+struct evhttp_connection;
+struct evrpc_status;
+
+/** launches an RPC and sends it to the server
+ *
+ * EVRPC_MAKE_REQUEST() is used by the client to send an RPC to the server.
+ *
+ * @param name the name of the RPC
+ * @param pool the evrpc_pool that contains the connection objects over which
+ *   the request should be sent.
+ * @param request a pointer to the RPC request structure - it contains the
+ *   data to be sent to the server.
+ * @param reply a pointer to the RPC reply structure.  It is going to be filled
+ *   if the request was answered successfully
+ * @param cb the callback to invoke when the RPC request has been answered
+ * @param cbarg an additional argument to be passed to the client
+ * @return 0 on success, -1 on failure
+ */
+#define EVRPC_MAKE_REQUEST(name, pool, request, reply, cb, cbarg)      \
+       evrpc_send_request_##name((pool), (request), (reply), (cb), (cbarg))
+
+/**
+   Makes an RPC request based on the provided context.
+
+   This is a low-level function and should not be used directly
+   unless a custom context object is provided.  Use EVRPC_MAKE_REQUEST()
+   instead.
+
+   @param ctx a context from EVRPC_MAKE_CTX()
+   @returns 0 on success, -1 otherwise.
+   @see EVRPC_MAKE_REQUEST(), EVRPC_MAKE_CTX()
+*/
+int evrpc_make_request(struct evrpc_request_wrapper *ctx);
+
+/** creates an rpc connection pool
+ *
+ * a pool has a number of connections associated with it.
+ * rpc requests are always made via a pool.
+ *
+ * @param base a pointer to an struct event_based object; can be left NULL
+ *   in singled-threaded applications
+ * @return a newly allocated struct evrpc_pool object
+ * @see evrpc_pool_free()
+ */
+struct evrpc_pool *evrpc_pool_new(struct event_base *base);
+/** frees an rpc connection pool
+ *
+ * @param pool a pointer to an evrpc_pool allocated via evrpc_pool_new()
+ * @see evrpc_pool_new()
+ */
+void evrpc_pool_free(struct evrpc_pool *pool);
+
+/**
+ * Adds a connection over which rpc can be dispatched to the pool.
+ *
+ * The connection object must have been newly created.
+ *
+ * @param pool the pool to which to add the connection
+ * @param evcon the connection to add to the pool.
+ */
+void evrpc_pool_add_connection(struct evrpc_pool *pool,
+    struct evhttp_connection *evcon);
+
+/**
+ * Removes a connection from the pool.
+ *
+ * The connection object must have been newly created.
+ *
+ * @param pool the pool from which to remove the connection
+ * @param evcon the connection to remove from the pool.
+ */
+void evrpc_pool_remove_connection(struct evrpc_pool *pool,
+    struct evhttp_connection *evcon);
+
+/**
+ * Sets the timeout in secs after which a request has to complete.  The
+ * RPC is completely aborted if it does not complete by then.  Setting
+ * the timeout to 0 means that it never timeouts and can be used to
+ * implement callback type RPCs.
+ *
+ * Any connection already in the pool will be updated with the new
+ * timeout.  Connections added to the pool after set_timeout has be
+ * called receive the pool timeout only if no timeout has been set
+ * for the connection itself.
+ *
+ * @param pool a pointer to a struct evrpc_pool object
+ * @param timeout_in_secs the number of seconds after which a request should
+ *   timeout and a failure be returned to the callback.
+ */
+void evrpc_pool_set_timeout(struct evrpc_pool *pool, int timeout_in_secs);
+
+/**
+ * Hooks for changing the input and output of RPCs; this can be used to
+ * implement compression, authentication, encryption, ...
+ */
+
+enum EVRPC_HOOK_TYPE {
+       EVRPC_INPUT,            /**< apply the function to an input hook */
+       EVRPC_OUTPUT            /**< apply the function to an output hook */
+};
+
+#ifndef WIN32
+/** Deprecated alias for EVRPC_INPUT.  Not available on windows, where it
+ * conflicts with platform headers. */
+#define INPUT EVRPC_INPUT
+/** Deprecated alias for EVRPC_OUTPUT.  Not available on windows, where it
+ * conflicts with platform headers. */
+#define OUTPUT EVRPC_OUTPUT
+#endif
+
+/**
+ * Return value from hook processing functions
+ */
+
+enum EVRPC_HOOK_RESULT {
+       EVRPC_TERMINATE = -1,   /**< indicates the rpc should be terminated */
+       EVRPC_CONTINUE = 0,     /**< continue processing the rpc */
+       EVRPC_PAUSE = 1         /**< pause processing request until resumed */
+};
+
+/** adds a processing hook to either an rpc base or rpc pool
+ *
+ * If a hook returns TERMINATE, the processing is aborted. On CONTINUE,
+ * the request is immediately processed after the hook returns.  If the
+ * hook returns PAUSE, request processing stops until evrpc_resume_request()
+ * has been called.
+ *
+ * The add functions return handles that can be used for removing hooks.
+ *
+ * @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
+ * @param hook_type either INPUT or OUTPUT
+ * @param cb the callback to call when the hook is activated
+ * @param cb_arg an additional argument for the callback
+ * @return a handle to the hook so it can be removed later
+ * @see evrpc_remove_hook()
+ */
+void *evrpc_add_hook(void *vbase,
+    enum EVRPC_HOOK_TYPE hook_type,
+    int (*cb)(void *, struct evhttp_request *, struct evbuffer *, void *),
+    void *cb_arg);
+
+/** removes a previously added hook
+ *
+ * @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
+ * @param hook_type either INPUT or OUTPUT
+ * @param handle a handle returned by evrpc_add_hook()
+ * @return 1 on success or 0 on failure
+ * @see evrpc_add_hook()
+ */
+int evrpc_remove_hook(void *vbase,
+    enum EVRPC_HOOK_TYPE hook_type,
+    void *handle);
+
+/** resume a paused request
+ *
+ * @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
+ * @param ctx the context pointer provided to the original hook call
+ */
+int
+evrpc_resume_request(void *vbase, void *ctx, enum EVRPC_HOOK_RESULT res);
+
+/** adds meta data to request
+ *
+ * evrpc_hook_add_meta() allows hooks to add meta data to a request. for
+ * a client request, the meta data can be inserted by an outgoing request hook
+ * and retrieved by the incoming request hook.
+ *
+ * @param ctx the context provided to the hook call
+ * @param key a NUL-terminated c-string
+ * @param data the data to be associated with the key
+ * @param data_size the size of the data
+ */
+void evrpc_hook_add_meta(void *ctx, const char *key,
+    const void *data, size_t data_size);
+
+/** retrieves meta data previously associated
+ *
+ * evrpc_hook_find_meta() can be used to retrieve meta data associated to a
+ * request by a previous hook.
+ * @param ctx the context provided to the hook call
+ * @param key a NUL-terminated c-string
+ * @param data pointer to a data pointer that will contain the retrieved data
+ * @param data_size pointer to the size of the data
+ * @return 0 on success or -1 on failure
+ */
+int evrpc_hook_find_meta(void *ctx, const char *key,
+    void **data, size_t *data_size);
+
+/**
+ * returns the connection object associated with the request
+ *
+ * @param ctx the context provided to the hook call
+ * @return a pointer to the evhttp_connection object
+ */
+struct evhttp_connection *evrpc_hook_get_connection(void *ctx);
+
+/**
+   Function for sending a generic RPC request.
+
+   Do not call this function directly, use EVRPC_MAKE_REQUEST() instead.
+
+   @see EVRPC_MAKE_REQUEST()
+ */
+int evrpc_send_request_generic(struct evrpc_pool *pool,
+    void *request, void *reply,
+    void (*cb)(struct evrpc_status *, void *, void *, void *),
+    void *cb_arg,
+    const char *rpcname,
+    void (*req_marshal)(struct evbuffer *, void *),
+    void (*rpl_clear)(void *),
+    int (*rpl_unmarshal)(void *, struct evbuffer *));
+
+/**
+   Function for registering a generic RPC with the RPC base.
+
+   Do not call this function directly, use EVRPC_REGISTER() instead.
+
+   @see EVRPC_REGISTER()
+ */
+int
+evrpc_register_generic(struct evrpc_base *base, const char *name,
+    void (*callback)(struct evrpc_req_generic *, void *), void *cbarg,
+    void *(*req_new)(void *), void *req_new_arg, void (*req_free)(void *),
+    int (*req_unmarshal)(void *, struct evbuffer *),
+    void *(*rpl_new)(void *), void *rpl_new_arg, void (*rpl_free)(void *),
+    int (*rpl_complete)(void *),
+    void (*rpl_marshal)(struct evbuffer *, void *));
+
+/** accessors for obscure and undocumented functionality */
+struct evrpc_pool* evrpc_request_get_pool(struct evrpc_request_wrapper *ctx);
+void evrpc_request_set_pool(struct evrpc_request_wrapper *ctx,
+    struct evrpc_pool *pool);
+void evrpc_request_set_cb(struct evrpc_request_wrapper *ctx,
+    void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg),
+    void *cb_arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_RPC_H_ */
diff --git a/libevent/include/event2/rpc_compat.h b/libevent/include/event2/rpc_compat.h
new file mode 100644 (file)
index 0000000..a4e24bb
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_RPC_COMPAT_H_
+#define _EVENT2_RPC_COMPAT_H_
+
+/** @file event2/rpc_compat.h
+
+  Deprecated versions of the functions in rpc.h: provided only for
+  backwards compatibility.
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** backwards compatible accessors that work only with gcc */
+#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
+
+#undef EVTAG_ASSIGN
+#undef EVTAG_GET
+#undef EVTAG_ADD
+
+#define EVTAG_ASSIGN(msg, member, args...) \
+       (*(msg)->base->member##_assign)(msg, ## args)
+#define EVTAG_GET(msg, member, args...) \
+       (*(msg)->base->member##_get)(msg, ## args)
+#define EVTAG_ADD(msg, member, args...) \
+       (*(msg)->base->member##_add)(msg, ## args)
+#endif
+#define EVTAG_LEN(msg, member) ((msg)->member##_length)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_EVENT_COMPAT_H_ */
diff --git a/libevent/include/event2/rpc_struct.h b/libevent/include/event2/rpc_struct.h
new file mode 100644 (file)
index 0000000..c339ae5
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_RPC_STRUCT_H_
+#define _EVENT2_RPC_STRUCT_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** @file event2/rpc_struct.h
+
+  Structures used by rpc.h.  Using these structures directly may harm
+  forward compatibility: be careful!
+
+ */
+
+/**
+ * provides information about the completed RPC request.
+ */
+struct evrpc_status {
+#define EVRPC_STATUS_ERR_NONE          0
+#define EVRPC_STATUS_ERR_TIMEOUT       1
+#define EVRPC_STATUS_ERR_BADPAYLOAD    2
+#define EVRPC_STATUS_ERR_UNSTARTED     3
+#define EVRPC_STATUS_ERR_HOOKABORTED   4
+       int error;
+
+       /* for looking at headers or other information */
+       struct evhttp_request *http_req;
+};
+
+/* the structure below needs to be synchronized with evrpc_req_generic */
+
+/* Encapsulates a request */
+struct evrpc {
+       TAILQ_ENTRY(evrpc) next;
+
+       /* the URI at which the request handler lives */
+       const char* uri;
+
+       /* creates a new request structure */
+       void *(*request_new)(void *);
+       void *request_new_arg;
+
+       /* frees the request structure */
+       void (*request_free)(void *);
+
+       /* unmarshals the buffer into the proper request structure */
+       int (*request_unmarshal)(void *, struct evbuffer *);
+
+       /* creates a new reply structure */
+       void *(*reply_new)(void *);
+       void *reply_new_arg;
+
+       /* frees the reply structure */
+       void (*reply_free)(void *);
+
+       /* verifies that the reply is valid */
+       int (*reply_complete)(void *);
+
+       /* marshals the reply into a buffer */
+       void (*reply_marshal)(struct evbuffer*, void *);
+
+       /* the callback invoked for each received rpc */
+       void (*cb)(struct evrpc_req_generic *, void *);
+       void *cb_arg;
+
+       /* reference for further configuration */
+       struct evrpc_base *base;
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_RPC_STRUCT_H_ */
diff --git a/libevent/include/event2/tag.h b/libevent/include/event2/tag.h
new file mode 100644 (file)
index 0000000..9e51779
--- /dev/null
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_TAG_H_
+#define _EVENT2_TAG_H_
+
+/** @file event2/tag.h
+
+  Helper functions for reading and writing tagged data onto buffers.
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+struct evbuffer;
+
+/*
+ * Marshaling tagged data - We assume that all tags are inserted in their
+ * numeric order - so that unknown tags will always be higher than the
+ * known ones - and we can just ignore the end of an event buffer.
+ */
+
+void evtag_init(void);
+
+/**
+   Unmarshals the header and returns the length of the payload
+
+   @param evbuf the buffer from which to unmarshal data
+   @param ptag a pointer in which the tag id is being stored
+   @returns -1 on failure or the number of bytes in the remaining payload.
+*/
+int evtag_unmarshal_header(struct evbuffer *evbuf, ev_uint32_t *ptag);
+
+void evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag, const void *data,
+    ev_uint32_t len);
+void evtag_marshal_buffer(struct evbuffer *evbuf, ev_uint32_t tag,
+    struct evbuffer *data);
+
+/**
+  Encode an integer and store it in an evbuffer.
+
+  We encode integers by nybbles; the first nibble contains the number
+  of significant nibbles - 1;  this allows us to encode up to 64-bit
+  integers.  This function is byte-order independent.
+
+  @param evbuf evbuffer to store the encoded number
+  @param number a 32-bit integer
+ */
+void evtag_encode_int(struct evbuffer *evbuf, ev_uint32_t number);
+void evtag_encode_int64(struct evbuffer *evbuf, ev_uint64_t number);
+
+void evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag,
+    ev_uint32_t integer);
+void evtag_marshal_int64(struct evbuffer *evbuf, ev_uint32_t tag,
+    ev_uint64_t integer);
+
+void evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag,
+    const char *string);
+
+void evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag,
+    struct timeval *tv);
+
+int evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag,
+    struct evbuffer *dst);
+int evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag);
+int evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength);
+int evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength);
+int evtag_consume(struct evbuffer *evbuf);
+
+int evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
+    ev_uint32_t *pinteger);
+int evtag_unmarshal_int64(struct evbuffer *evbuf, ev_uint32_t need_tag,
+    ev_uint64_t *pinteger);
+
+int evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag,
+    void *data, size_t len);
+
+int evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
+    char **pstring);
+
+int evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
+    struct timeval *ptv);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_TAG_H_ */
diff --git a/libevent/include/event2/tag_compat.h b/libevent/include/event2/tag_compat.h
new file mode 100644 (file)
index 0000000..73c1933
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_TAG_COMPAT_H_
+#define _EVENT2_TAG_COMPAT_H_
+
+/** @file event2/tag_compat.h
+
+    Obsolete/deprecated functions from tag.h; provided only for backwards
+    compatibility.
+ */
+
+/**
+   @name Misnamed functions
+
+   @deprecated These macros are deprecated because their names don't follow
+     Libevent's naming conventions.  Use evtag_encode_int and
+     evtag_encode_int64 instead.
+
+   @{
+*/
+#define encode_int(evbuf, number) evtag_encode_int((evbuf), (number))
+#define encode_int64(evbuf, number) evtag_encode_int64((evbuf), (number))
+/**@}*/
+
+#endif /* _EVENT2_TAG_H_ */
diff --git a/libevent/include/event2/thread.h b/libevent/include/event2/thread.h
new file mode 100644 (file)
index 0000000..0b638f0
--- /dev/null
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_THREAD_H_
+#define _EVENT2_THREAD_H_
+
+/** @file event2/thread.h
+
+  Functions for multi-threaded applications using Libevent.
+
+  When using a multi-threaded application in which multiple threads
+  add and delete events from a single event base, Libevent needs to
+  lock its data structures.
+
+  Like the memory-management function hooks, all of the threading functions
+  _must_ be set up before an event_base is created if you want the base to
+  use them.
+
+  Most programs will either be using Windows threads or Posix threads.  You
+  can configure Libevent to use one of these event_use_windows_threads() or
+  event_use_pthreads() respectively.  If you're using another threading
+  library, you'll need to configure threading functions manually using
+  evthread_set_lock_callbacks() and evthread_set_condition_callbacks().
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+
+/**
+   @name Flags passed to lock functions
+
+   @{
+*/
+/** A flag passed to a locking callback when the lock was allocated as a
+ * read-write lock, and we want to acquire or release the lock for writing. */
+#define EVTHREAD_WRITE 0x04
+/** A flag passed to a locking callback when the lock was allocated as a
+ * read-write lock, and we want to acquire or release the lock for reading. */
+#define EVTHREAD_READ  0x08
+/** A flag passed to a locking callback when we don't want to block waiting
+ * for the lock; if we can't get the lock immediately, we will instead
+ * return nonzero from the locking callback. */
+#define EVTHREAD_TRY    0x10
+/**@}*/
+
+#if !defined(_EVENT_DISABLE_THREAD_SUPPORT) || defined(_EVENT_IN_DOXYGEN)
+
+#define EVTHREAD_LOCK_API_VERSION 1
+
+/**
+   @name Types of locks
+
+   @{*/
+/** A recursive lock is one that can be acquired multiple times at once by the
+ * same thread.  No other process can allocate the lock until the thread that
+ * has been holding it has unlocked it as many times as it locked it. */
+#define EVTHREAD_LOCKTYPE_RECURSIVE 1
+/* A read-write lock is one that allows multiple simultaneous readers, but
+ * where any one writer excludes all other writers and readers. */
+#define EVTHREAD_LOCKTYPE_READWRITE 2
+/**@}*/
+
+/** This structure describes the interface a threading library uses for
+ * locking.   It's used to tell evthread_set_lock_callbacks() how to use
+ * locking on this platform.
+ */
+struct evthread_lock_callbacks {
+       /** The current version of the locking API.  Set this to
+        * EVTHREAD_LOCK_API_VERSION */
+       int lock_api_version;
+       /** Which kinds of locks does this version of the locking API
+        * support?  A bitfield of EVTHREAD_LOCKTYPE_RECURSIVE and
+        * EVTHREAD_LOCKTYPE_READWRITE.
+        *
+        * (Note that RECURSIVE locks are currently mandatory, and
+        * READWRITE locks are not currently used.)
+        **/
+       unsigned supported_locktypes;
+       /** Function to allocate and initialize new lock of type 'locktype'.
+        * Returns NULL on failure. */
+       void *(*alloc)(unsigned locktype);
+       /** Funtion to release all storage held in 'lock', which was created
+        * with type 'locktype'. */
+       void (*free)(void *lock, unsigned locktype);
+       /** Acquire an already-allocated lock at 'lock' with mode 'mode'.
+        * Returns 0 on success, and nonzero on failure. */
+       int (*lock)(unsigned mode, void *lock);
+       /** Release a lock at 'lock' using mode 'mode'.  Returns 0 on success,
+        * and nonzero on failure. */
+       int (*unlock)(unsigned mode, void *lock);
+};
+
+/** Sets a group of functions that Libevent should use for locking.
+ * For full information on the required callback API, see the
+ * documentation for the individual members of evthread_lock_callbacks.
+ *
+ * Note that if you're using Windows or the Pthreads threading library, you
+ * probably shouldn't call this function; instead, use
+ * evthread_use_windows_threads() or evthread_use_posix_threads() if you can.
+ */
+int evthread_set_lock_callbacks(const struct evthread_lock_callbacks *);
+
+#define EVTHREAD_CONDITION_API_VERSION 1
+
+struct timeval;
+
+/** This structure describes the interface a threading library uses for
+ * condition variables.  It's used to tell evthread_set_condition_callbacks
+ * how to use locking on this platform.
+ */
+struct evthread_condition_callbacks {
+       /** The current version of the conditions API.  Set this to
+        * EVTHREAD_CONDITION_API_VERSION */
+       int condition_api_version;
+       /** Function to allocate and initialize a new condition variable.
+        * Returns the condition variable on success, and NULL on failure.
+        * The 'condtype' argument will be 0 with this API version.
+        */
+       void *(*alloc_condition)(unsigned condtype);
+       /** Function to free a condition variable. */
+       void (*free_condition)(void *cond);
+       /** Function to signal a condition variable.  If 'broadcast' is 1, all
+        * threads waiting on 'cond' should be woken; otherwise, only on one
+        * thread is worken.  Should return 0 on success, -1 on failure.
+        * This function will only be called while holding the associated
+        * lock for the condition.
+        */
+       int (*signal_condition)(void *cond, int broadcast);
+       /** Function to wait for a condition variable.  The lock 'lock'
+        * will be held when this function is called; should be released
+        * while waiting for the condition to be come signalled, and
+        * should be held again when this function returns.
+        * If timeout is provided, it is interval of seconds to wait for
+        * the event to become signalled; if it is NULL, the function
+        * should wait indefinitely.
+        *
+        * The function should return -1 on error; 0 if the condition
+        * was signalled, or 1 on a timeout. */
+       int (*wait_condition)(void *cond, void *lock,
+           const struct timeval *timeout);
+};
+
+/** Sets a group of functions that Libevent should use for condition variables.
+ * For full information on the required callback API, see the
+ * documentation for the individual members of evthread_condition_callbacks.
+ *
+ * Note that if you're using Windows or the Pthreads threading library, you
+ * probably shouldn't call this function; instead, use
+ * evthread_use_windows_threads() or evthread_use_pthreads() if you can.
+ */
+int evthread_set_condition_callbacks(
+       const struct evthread_condition_callbacks *);
+
+/**
+   Sets the function for determining the thread id.
+
+   @param base the event base for which to set the id function
+   @param id_fn the identify function Libevent should invoke to
+     determine the identity of a thread.
+*/
+void evthread_set_id_callback(
+    unsigned long (*id_fn)(void));
+
+#if (defined(WIN32) && !defined(_EVENT_DISABLE_THREAD_SUPPORT)) || defined(_EVENT_IN_DOXYGEN)
+/** Sets up Libevent for use with Windows builtin locking and thread ID
+    functions.  Unavailable if Libevent is not built for Windows.
+
+    @return 0 on success, -1 on failure. */
+int evthread_use_windows_threads(void);
+/**
+   Defined if Libevent was built with support for evthread_use_windows_threads()
+*/
+#define EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED 1
+#endif
+
+#if defined(_EVENT_HAVE_PTHREADS) || defined(_EVENT_IN_DOXYGEN)
+/** Sets up Libevent for use with Pthreads locking and thread ID functions.
+    Unavailable if Libevent is not build for use with pthreads.  Requires
+    libraries to link against Libevent_pthreads as well as Libevent.
+
+    @return 0 on success, -1 on failure. */
+int evthread_use_pthreads(void);
+/** Defined if Libevent was built with support for evthread_use_pthreads() */
+#define EVTHREAD_USE_PTHREADS_IMPLEMENTED 1
+
+#endif
+
+/** Enable debugging wrappers around the current lock callbacks.  If Libevent
+ * makes one of several common locking errors, exit with an assertion failure.
+ *
+ * If you're going to call this function, you must do so before any locks are
+ * allocated.
+ **/
+void evthread_enable_lock_debuging(void);
+
+#endif /* _EVENT_DISABLE_THREAD_SUPPORT */
+
+struct event_base;
+/** Make sure it's safe to tell an event base to wake up from another thread
+    or a signal handler.
+
+    @return 0 on success, -1 on failure.
+ */
+int evthread_make_base_notifiable(struct event_base *base);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVENT2_THREAD_H_ */
diff --git a/libevent/include/event2/util.h b/libevent/include/event2/util.h
new file mode 100644 (file)
index 0000000..45d8f1d
--- /dev/null
@@ -0,0 +1,691 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT2_UTIL_H_
+#define _EVENT2_UTIL_H_
+
+/** @file event2/util.h
+
+  Common convenience functions for cross-platform portability and
+  related socket manipulations.
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _EVENT_HAVE_STDINT_H
+#include <stdint.h>
+#elif defined(_EVENT_HAVE_INTTYPES_H)
+#include <inttypes.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef _EVENT_HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+#ifdef _MSC_VER
+#include <BaseTsd.h>
+#endif
+#include <stdarg.h>
+#ifdef _EVENT_HAVE_NETDB_H
+#if !defined(_GNU_SOURCE)
+#define _GNU_SOURCE
+#endif
+#include <netdb.h>
+#endif
+
+#ifdef WIN32
+#include <winsock2.h>
+#else
+#include <sys/socket.h>
+#endif
+
+/* Some openbsd autoconf versions get the name of this macro wrong. */
+#if defined(_EVENT_SIZEOF_VOID__) && !defined(_EVENT_SIZEOF_VOID_P)
+#define _EVENT_SIZEOF_VOID_P _EVENT_SIZEOF_VOID__
+#endif
+
+/**
+ * @name Standard integer types.
+ *
+ * Integer type definitions for types that are supposed to be defined in the
+ * C99-specified stdint.h.  Shamefully, some platforms do not include
+ * stdint.h, so we need to replace it.  (If you are on a platform like this,
+ * your C headers are now over 10 years out of date.  You should bug them to
+ * do something about this.)
+ *
+ * We define:
+ *
+ * <dl>
+ *   <dt>ev_uint64_t, ev_uint32_t, ev_uint16_t, ev_uint8_t</dt>
+ *      <dd>unsigned integer types of exactly 64, 32, 16, and 8 bits
+ *          respectively.</dd>
+ *    <dt>ev_int64_t, ev_int32_t, ev_int16_t, ev_int8_t</dt>
+ *      <dd>signed integer types of exactly 64, 32, 16, and 8 bits
+ *          respectively.</dd>
+ *    <dt>ev_uintptr_t, ev_intptr_t</dt>
+ *      <dd>unsigned/signed integers large enough
+ *      to hold a pointer without loss of bits.</dd>
+ *    <dt>ev_ssize_t</dt>
+ *      <dd>A signed type of the same size as size_t</dd>
+ *    <dt>ev_off_t</dt>
+ *      <dd>A signed type typically used to represent offsets within a
+ *      (potentially large) file</dd>
+ *
+ * @{
+ */
+#ifdef _EVENT_HAVE_UINT64_T
+#define ev_uint64_t uint64_t
+#define ev_int64_t int64_t
+#elif defined(WIN32)
+#define ev_uint64_t unsigned __int64
+#define ev_int64_t signed __int64
+#elif _EVENT_SIZEOF_LONG_LONG == 8
+#define ev_uint64_t unsigned long long
+#define ev_int64_t long long
+#elif _EVENT_SIZEOF_LONG == 8
+#define ev_uint64_t unsigned long
+#define ev_int64_t long
+#elif defined(_EVENT_IN_DOXYGEN)
+#define ev_uint64_t ...
+#define ev_int64_t ...
+#else
+#error "No way to define ev_uint64_t"
+#endif
+
+#ifdef _EVENT_HAVE_UINT32_T
+#define ev_uint32_t uint32_t
+#define ev_int32_t int32_t
+#elif defined(WIN32)
+#define ev_uint32_t unsigned int
+#define ev_int32_t signed int
+#elif _EVENT_SIZEOF_LONG == 4
+#define ev_uint32_t unsigned long
+#define ev_int32_t signed long
+#elif _EVENT_SIZEOF_INT == 4
+#define ev_uint32_t unsigned int
+#define ev_int32_t signed int
+#elif defined(_EVENT_IN_DOXYGEN)
+#define ev_uint32_t ...
+#define ev_int32_t ...
+#else
+#error "No way to define ev_uint32_t"
+#endif
+
+#ifdef _EVENT_HAVE_UINT16_T
+#define ev_uint16_t uint16_t
+#define ev_int16_t  int16_t
+#elif defined(WIN32)
+#define ev_uint16_t unsigned short
+#define ev_int16_t  signed short
+#elif _EVENT_SIZEOF_INT == 2
+#define ev_uint16_t unsigned int
+#define ev_int16_t  signed int
+#elif _EVENT_SIZEOF_SHORT == 2
+#define ev_uint16_t unsigned short
+#define ev_int16_t  signed short
+#elif defined(_EVENT_IN_DOXYGEN)
+#define ev_uint16_t ...
+#define ev_int16_t ...
+#else
+#error "No way to define ev_uint16_t"
+#endif
+
+#ifdef _EVENT_HAVE_UINT8_T
+#define ev_uint8_t uint8_t
+#define ev_int8_t int8_t
+#elif defined(_EVENT_IN_DOXYGEN)
+#define ev_uint8_t ...
+#define ev_int8_t ...
+#else
+#define ev_uint8_t unsigned char
+#define ev_int8_t signed char
+#endif
+
+#ifdef _EVENT_HAVE_UINTPTR_T
+#define ev_uintptr_t uintptr_t
+#define ev_intptr_t intptr_t
+#elif _EVENT_SIZEOF_VOID_P <= 4
+#define ev_uintptr_t ev_uint32_t
+#define ev_intptr_t ev_int32_t
+#elif _EVENT_SIZEOF_VOID_P <= 8
+#define ev_uintptr_t ev_uint64_t
+#define ev_intptr_t ev_int64_t
+#elif defined(_EVENT_IN_DOXYGEN)
+#define ev_uintptr_t ...
+#define ev_intptr_t ...
+#else
+#error "No way to define ev_uintptr_t"
+#endif
+
+#ifdef _EVENT_ssize_t
+#define ev_ssize_t _EVENT_ssize_t
+#else
+#define ev_ssize_t ssize_t
+#endif
+
+#ifdef WIN32
+#define ev_off_t ev_int64_t
+#else
+#define ev_off_t off_t
+#endif
+/**@}*/
+
+/* Limits for integer types.
+
+   We're making two assumptions here:
+     - The compiler does constant folding properly.
+     - The platform does signed arithmetic in two's complement.
+*/
+
+/**
+   @name Limits for integer types
+
+   These macros hold the largest or smallest values possible for the
+   ev_[u]int*_t types.
+
+   @{
+*/
+#define EV_UINT64_MAX ((((ev_uint64_t)0xffffffffUL) << 32) | 0xffffffffUL)
+#define EV_INT64_MAX  ((((ev_int64_t) 0x7fffffffL) << 32) | 0xffffffffL)
+#define EV_INT64_MIN  ((-EV_INT64_MAX) - 1)
+#define EV_UINT32_MAX ((ev_uint32_t)0xffffffffUL)
+#define EV_INT32_MAX  ((ev_int32_t) 0x7fffffffL)
+#define EV_INT32_MIN  ((-EV_INT32_MAX) - 1)
+#define EV_UINT16_MAX ((ev_uint16_t)0xffffUL)
+#define EV_INT16_MAX  ((ev_int16_t) 0x7fffL)
+#define EV_INT16_MIN  ((-EV_INT16_MAX) - 1)
+#define EV_UINT8_MAX  255
+#define EV_INT8_MAX   127
+#define EV_INT8_MIN   ((-EV_INT8_MAX) - 1)
+/** @} */
+
+/**
+   @name Limits for SIZE_T and SSIZE_T
+
+   @{
+*/
+#if _EVENT_SIZEOF_SIZE_T == 8
+#define EV_SIZE_MAX EV_UINT64_MAX
+#define EV_SSIZE_MAX EV_INT64_MAX
+#elif _EVENT_SIZEOF_SIZE_T == 4
+#define EV_SIZE_MAX EV_UINT32_MAX
+#define EV_SSIZE_MAX EV_INT32_MAX
+#elif defined(_EVENT_IN_DOXYGEN)
+#define EV_SIZE_MAX ...
+#define EV_SSIZE_MAX ...
+#else
+#error "No way to define SIZE_MAX"
+#endif
+
+#define EV_SSIZE_MIN ((-EV_SSIZE_MAX) - 1)
+/**@}*/
+
+#ifdef WIN32
+#define ev_socklen_t int
+#elif defined(_EVENT_socklen_t)
+#define ev_socklen_t _EVENT_socklen_t
+#else
+#define ev_socklen_t socklen_t
+#endif
+
+#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
+#if !defined(_EVENT_HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
+ && !defined(ss_family)
+#define ss_family __ss_family
+#endif
+#endif
+
+/**
+ * A type wide enough to hold the output of "socket()" or "accept()".  On
+ * Windows, this is an intptr_t; elsewhere, it is an int. */
+#ifdef WIN32
+#define evutil_socket_t intptr_t
+#else
+#define evutil_socket_t int
+#endif
+
+/** Create two new sockets that are connected to each other.
+
+    On Unix, this simply calls socketpair().  On Windows, it uses the
+    loopback network interface on 127.0.0.1, and only
+    AF_INET,SOCK_STREAM are supported.
+
+    (This may fail on some Windows hosts where firewall software has cleverly
+    decided to keep 127.0.0.1 from talking to itself.)
+
+    Parameters and return values are as for socketpair()
+*/
+int evutil_socketpair(int d, int type, int protocol, evutil_socket_t sv[2]);
+/** Do platform-specific operations as needed to make a socket nonblocking.
+
+    @param sock The socket to make nonblocking
+    @return 0 on success, -1 on failure
+ */
+int evutil_make_socket_nonblocking(evutil_socket_t sock);
+
+/** Do platform-specific operations to make a listener socket reusable.
+
+    Specifically, we want to make sure that another program will be able
+    to bind this address right after we've closed the listener.
+
+    This differs from Windows's interpretation of "reusable", which
+    allows multiple listeners to bind the same address at the same time.
+
+    @param sock The socket to make reusable
+    @return 0 on success, -1 on failure
+ */
+int evutil_make_listen_socket_reuseable(evutil_socket_t sock);
+
+/** Do platform-specific operations as needed to close a socket upon a
+    successful execution of one of the exec*() functions.
+
+    @param sock The socket to be closed
+    @return 0 on success, -1 on failure
+ */
+int evutil_make_socket_closeonexec(evutil_socket_t sock);
+
+/** Do the platform-specific call needed to close a socket returned from
+    socket() or accept().
+
+    @param sock The socket to be closed
+    @return 0 on success, -1 on failure
+ */
+int evutil_closesocket(evutil_socket_t sock);
+#define EVUTIL_CLOSESOCKET(s) evutil_closesocket(s)
+
+
+#ifdef WIN32
+/** Return the most recent socket error.  Not idempotent on all platforms. */
+#define EVUTIL_SOCKET_ERROR() WSAGetLastError()
+/** Replace the most recent socket error with errcode */
+#define EVUTIL_SET_SOCKET_ERROR(errcode)               \
+       do { WSASetLastError(errcode); } while (0)
+/** Return the most recent socket error to occur on sock. */
+int evutil_socket_geterror(evutil_socket_t sock);
+/** Convert a socket error to a string. */
+const char *evutil_socket_error_to_string(int errcode);
+#elif defined(_EVENT_IN_DOXYGEN)
+/**
+   @name Socket error functions
+
+   These functions are needed for making programs compatible between
+   Windows and Unix-like platforms.
+
+   You see, Winsock handles socket errors differently from the rest of
+   the world.  Elsewhere, a socket error is like any other error and is
+   stored in errno.  But winsock functions require you to retrieve the
+   error with a special function, and don't let you use strerror for
+   the error codes.  And handling EWOULDBLOCK is ... different.
+
+   @{
+*/
+/** Return the most recent socket error.  Not idempotent on all platforms. */
+#define EVUTIL_SOCKET_ERROR() ...
+/** Replace the most recent socket error with errcode */
+#define EVUTIL_SET_SOCKET_ERROR(errcode) ...
+/** Return the most recent socket error to occur on sock. */
+#define evutil_socket_geterror(sock) ...
+/** Convert a socket error to a string. */
+#define evutil_socket_error_to_string(errcode) ...
+/**@}*/
+#else
+#define EVUTIL_SOCKET_ERROR() (errno)
+#define EVUTIL_SET_SOCKET_ERROR(errcode)               \
+               do { errno = (errcode); } while (0)
+#define evutil_socket_geterror(sock) (errno)
+#define evutil_socket_error_to_string(errcode) (strerror(errcode))
+#endif
+
+
+/**
+ * @name Manipulation macros for struct timeval.
+ *
+ * We define replacements
+ * for timeradd, timersub, timerclear, timercmp, and timerisset.
+ *
+ * @{
+ */
+#ifdef _EVENT_HAVE_TIMERADD
+#define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
+#define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
+#else
+#define evutil_timeradd(tvp, uvp, vvp)                                 \
+       do {                                                            \
+               (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;          \
+               (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;       \
+               if ((vvp)->tv_usec >= 1000000) {                        \
+                       (vvp)->tv_sec++;                                \
+                       (vvp)->tv_usec -= 1000000;                      \
+               }                                                       \
+       } while (0)
+#define        evutil_timersub(tvp, uvp, vvp)                                  \
+       do {                                                            \
+               (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;          \
+               (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;       \
+               if ((vvp)->tv_usec < 0) {                               \
+                       (vvp)->tv_sec--;                                \
+                       (vvp)->tv_usec += 1000000;                      \
+               }                                                       \
+       } while (0)
+#endif /* !_EVENT_HAVE_HAVE_TIMERADD */
+
+#ifdef _EVENT_HAVE_TIMERCLEAR
+#define evutil_timerclear(tvp) timerclear(tvp)
+#else
+#define        evutil_timerclear(tvp)  (tvp)->tv_sec = (tvp)->tv_usec = 0
+#endif
+/**@}*/
+
+/** Return true iff the tvp is related to uvp according to the relational
+ * operator cmp.  Recognized values for cmp are ==, <=, <, >=, and >. */
+#define        evutil_timercmp(tvp, uvp, cmp)                                  \
+       (((tvp)->tv_sec == (uvp)->tv_sec) ?                             \
+        ((tvp)->tv_usec cmp (uvp)->tv_usec) :                          \
+        ((tvp)->tv_sec cmp (uvp)->tv_sec))
+
+#ifdef _EVENT_HAVE_TIMERISSET
+#define evutil_timerisset(tvp) timerisset(tvp)
+#else
+#define        evutil_timerisset(tvp)  ((tvp)->tv_sec || (tvp)->tv_usec)
+#endif
+
+/** Replacement for offsetof on platforms that don't define it. */
+#ifdef offsetof
+#define evutil_offsetof(type, field) offsetof(type, field)
+#else
+#define evutil_offsetof(type, field) ((off_t)(&((type *)0)->field))
+#endif
+
+/* big-int related functions */
+/** Parse a 64-bit value from a string.  Arguments are as for strtol. */
+ev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
+
+/** Replacement for gettimeofday on platforms that lack it. */
+#ifdef _EVENT_HAVE_GETTIMEOFDAY
+#define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
+#else
+struct timezone;
+int evutil_gettimeofday(struct timeval *tv, struct timezone *tz);
+#endif
+
+/** Replacement for snprintf to get consistent behavior on platforms for
+    which the return value of snprintf does not conform to C99.
+ */
+int evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
+#ifdef __GNUC__
+       __attribute__((format(printf, 3, 4)))
+#endif
+;
+/** Replacement for vsnprintf to get consistent behavior on platforms for
+    which the return value of snprintf does not conform to C99.
+ */
+int evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap);
+
+/** Replacement for inet_ntop for platforms which lack it. */
+const char *evutil_inet_ntop(int af, const void *src, char *dst, size_t len);
+/** Replacement for inet_pton for platforms which lack it. */
+int evutil_inet_pton(int af, const char *src, void *dst);
+struct sockaddr;
+
+/** Parse an IPv4 or IPv6 address, with optional port, from a string.
+
+    Recognized formats are:
+    - [IPv6Address]:port
+    - [IPv6Address]
+    - IPv6Address
+    - IPv4Address:port
+    - IPv4Address
+
+    If no port is specified, the port in the output is set to 0.
+
+    @param str The string to parse.
+    @param out A struct sockaddr to hold the result.  This should probably be
+       a struct sockaddr_storage.
+    @param outlen A pointer to the number of bytes that that 'out' can safely
+       hold.  Set to the number of bytes used in 'out' on success.
+    @return -1 if the address is not well-formed, if the port is out of range,
+       or if out is not large enough to hold the result.  Otherwise returns
+       0 on success.
+*/
+int evutil_parse_sockaddr_port(const char *str, struct sockaddr *out, int *outlen);
+
+/** Compare two sockaddrs; return 0 if they are equal, or less than 0 if sa1
+ * preceeds sa2, or greater than 0 if sa1 follows sa2.  If include_port is
+ * true, consider the port as well as the address.  Only implemented for
+ * AF_INET and AF_INET6 addresses. The ordering is not guaranteed to remain
+ * the same between Libevent versions. */
+int evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
+    int include_port);
+
+/** As strcasecmp, but always compares the characters in locale-independent
+    ASCII.  That's useful if you're handling data in ASCII-based protocols.
+ */
+int evutil_ascii_strcasecmp(const char *str1, const char *str2);
+/** As strncasecmp, but always compares the characters in locale-independent
+    ASCII.  That's useful if you're handling data in ASCII-based protocols.
+ */
+int evutil_ascii_strncasecmp(const char *str1, const char *str2, size_t n);
+
+/* Here we define evutil_addrinfo to the native addrinfo type, or redefine it
+ * if this system has no getaddrinfo(). */
+#ifdef _EVENT_HAVE_STRUCT_ADDRINFO
+#define evutil_addrinfo addrinfo
+#else
+/** A definition of struct addrinfo for systems that lack it.
+
+    (This is just an alias for struct addrinfo if the system defines
+    struct addrinfo.)
+*/
+struct evutil_addrinfo {
+       int     ai_flags;     /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
+       int     ai_family;    /* PF_xxx */
+       int     ai_socktype;  /* SOCK_xxx */
+       int     ai_protocol;  /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
+       size_t  ai_addrlen;   /* length of ai_addr */
+       char   *ai_canonname; /* canonical name for nodename */
+       struct sockaddr  *ai_addr; /* binary address */
+       struct evutil_addrinfo  *ai_next; /* next structure in linked list */
+};
+#endif
+/** @name evutil_getaddrinfo() error codes
+
+    These values are possible error codes for evutil_getaddrinfo() and
+    related functions.
+
+    @{
+*/
+#ifdef EAI_ADDRFAMILY
+#define EVUTIL_EAI_ADDRFAMILY EAI_ADDRFAMILY
+#else
+#define EVUTIL_EAI_ADDRFAMILY -901
+#endif
+#ifdef EAI_AGAIN
+#define EVUTIL_EAI_AGAIN EAI_AGAIN
+#else
+#define EVUTIL_EAI_AGAIN -902
+#endif
+#ifdef EAI_BADFLAGS
+#define EVUTIL_EAI_BADFLAGS EAI_BADFLAGS
+#else
+#define EVUTIL_EAI_BADFLAGS -903
+#endif
+#ifdef EAI_FAIL
+#define EVUTIL_EAI_FAIL EAI_FAIL
+#else
+#define EVUTIL_EAI_FAIL -904
+#endif
+#ifdef EAI_FAMILY
+#define EVUTIL_EAI_FAMILY EAI_FAMILY
+#else
+#define EVUTIL_EAI_FAMILY -905
+#endif
+#ifdef EAI_MEMORY
+#define EVUTIL_EAI_MEMORY EAI_MEMORY
+#else
+#define EVUTIL_EAI_MEMORY -906
+#endif
+/* This test is a bit complicated, since some MS SDKs decide to
+ * remove NODATA or redefine it to be the same as NONAME, in a
+ * fun interpretation of RFC 2553 and RFC 3493. */
+#if defined(EAI_NODATA) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
+#define EVUTIL_EAI_NODATA EAI_NODATA
+#else
+#define EVUTIL_EAI_NODATA -907
+#endif
+#ifdef EAI_NONAME
+#define EVUTIL_EAI_NONAME EAI_NONAME
+#else
+#define EVUTIL_EAI_NONAME -908
+#endif
+#ifdef EAI_SERVICE
+#define EVUTIL_EAI_SERVICE EAI_SERVICE
+#else
+#define EVUTIL_EAI_SERVICE -909
+#endif
+#ifdef EAI_SOCKTYPE
+#define EVUTIL_EAI_SOCKTYPE EAI_SOCKTYPE
+#else
+#define EVUTIL_EAI_SOCKTYPE -910
+#endif
+#ifdef EAI_SYSTEM
+#define EVUTIL_EAI_SYSTEM EAI_SYSTEM
+#else
+#define EVUTIL_EAI_SYSTEM -911
+#endif
+
+#define EVUTIL_EAI_CANCEL -90001
+
+#ifdef AI_PASSIVE
+#define EVUTIL_AI_PASSIVE AI_PASSIVE
+#else
+#define EVUTIL_AI_PASSIVE 0x1000
+#endif
+#ifdef AI_CANONNAME
+#define EVUTIL_AI_CANONNAME AI_CANONNAME
+#else
+#define EVUTIL_AI_CANONNAME 0x2000
+#endif
+#ifdef AI_NUMERICHOST
+#define EVUTIL_AI_NUMERICHOST AI_NUMERICHOST
+#else
+#define EVUTIL_AI_NUMERICHOST 0x4000
+#endif
+#ifdef AI_NUMERICSERV
+#define EVUTIL_AI_NUMERICSERV AI_NUMERICSERV
+#else
+#define EVUTIL_AI_NUMERICSERV 0x8000
+#endif
+#ifdef AI_V4MAPPED
+#define EVUTIL_AI_V4MAPPED AI_V4MAPPED
+#else
+#define EVUTIL_AI_V4MAPPED 0x10000
+#endif
+#ifdef AI_ALL
+#define EVUTIL_AI_ALL AI_ALL
+#else
+#define EVUTIL_AI_ALL 0x20000
+#endif
+#ifdef AI_ADDRCONFIG
+#define EVUTIL_AI_ADDRCONFIG AI_ADDRCONFIG
+#else
+#define EVUTIL_AI_ADDRCONFIG 0x40000
+#endif
+/**@}*/
+
+struct evutil_addrinfo;
+/**
+ * This function clones getaddrinfo for systems that don't have it.  For full
+ * details, see RFC 3493, section 6.1.
+ *
+ * Limitations:
+ * - When the system has no getaddrinfo, we fall back to gethostbyname_r or
+ *   gethostbyname, with their attendant issues.
+ * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
+ *
+ * For a nonblocking variant, see evdns_getaddrinfo.
+ */
+int evutil_getaddrinfo(const char *nodename, const char *servname,
+    const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res);
+
+/** Release storage allocated by evutil_getaddrinfo or evdns_getaddrinfo. */
+void evutil_freeaddrinfo(struct evutil_addrinfo *ai);
+
+const char *evutil_gai_strerror(int err);
+
+/** Generate n bytes of secure pseudorandom data, and store them in buf.
+ *
+ * By default, Libevent uses an ARC4-based random number generator, seeded
+ * using the platform's entropy source (/dev/urandom on Unix-like systems;
+ * CryptGenRandom on Windows).
+ */
+void evutil_secure_rng_get_bytes(void *buf, size_t n);
+
+/**
+ * Seed the secure random number generator if needed, and return 0 on
+ * success or -1 on failure.
+ *
+ * It is okay to call this function more than once; it will still return
+ * 0 if the RNG has been successfully seeded and -1 if it can't be
+ * seeded.
+ *
+ * Ordinarily you don't need to call this function from your own code;
+ * Libevent will seed the RNG itself the first time it needs good random
+ * numbers.  You only need to call it if (a) you want to double-check
+ * that one of the seeding methods did succeed, or (b) you plan to drop
+ * the capability to seed (by chrooting, or dropping capabilities, or
+ * whatever), and you want to make sure that seeding happens before your
+ * program loses the ability to do it.
+ */
+int evutil_secure_rng_init(void);
+
+/** Seed the random number generator with extra random bytes.
+
+    You should almost never need to call this function; it should be
+    sufficient to invoke evutil_secure_rng_init(), or let Libevent take
+    care of calling evutil_secure_rng_init() on its own.
+
+    If you call this function as a _replacement_ for the regular
+    entropy sources, then you need to be sure that your input
+    contains a fairly large amount of strong entropy.  Doing so is
+    notoriously hard: most people who try get it wrong.  Watch out!
+
+    @param dat a buffer full of a strong source of random numbers
+    @param datlen the number of bytes to read from datlen
+ */
+void evutil_secure_rng_add_bytes(const char *dat, size_t datlen);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _EVUTIL_H_ */
diff --git a/libevent/iocp-internal.h b/libevent/iocp-internal.h
new file mode 100644 (file)
index 0000000..ae79cbc
--- /dev/null
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _EVENT_IOCP_INTERNAL_H
+#define _EVENT_IOCP_INTERNAL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct event_overlapped;
+struct event_iocp_port;
+struct evbuffer;
+typedef void (*iocp_callback)(struct event_overlapped *, ev_uintptr_t, ev_ssize_t, int success);
+
+/* This whole file is actually win32 only. We wrap the structures in a win32
+ * ifdef so that we can test-compile code that uses these interfaces on
+ * non-win32 platforms. */
+#ifdef WIN32
+
+/**
+   Internal use only.  Wraps an OVERLAPPED that we're using for libevent
+   functionality.  Whenever an event_iocp_port gets an event for a given
+   OVERLAPPED*, it upcasts the pointer to an event_overlapped, and calls the
+   iocp_callback function with the event_overlapped, the iocp key, and the
+   number of bytes transferred as arguments.
+ */
+struct event_overlapped {
+       OVERLAPPED overlapped;
+       iocp_callback cb;
+};
+
+/* Mingw's headers don't define LPFN_ACCEPTEX. */
+
+typedef BOOL (WINAPI *AcceptExPtr)(SOCKET, SOCKET, PVOID, DWORD, DWORD, DWORD, LPDWORD, LPOVERLAPPED);
+typedef BOOL (WINAPI *ConnectExPtr)(SOCKET, const struct sockaddr *, int, PVOID, DWORD, LPDWORD, LPOVERLAPPED);
+typedef void (WINAPI *GetAcceptExSockaddrsPtr)(PVOID, DWORD, DWORD, DWORD, LPSOCKADDR *, LPINT, LPSOCKADDR *, LPINT);
+
+/** Internal use only. Holds pointers to functions that only some versions of
+    Windows provide.
+ */
+struct win32_extension_fns {
+       AcceptExPtr AcceptEx;
+       ConnectExPtr ConnectEx;
+       GetAcceptExSockaddrsPtr GetAcceptExSockaddrs;
+};
+
+/**
+    Internal use only. Stores a Windows IO Completion port, along with
+    related data.
+ */
+struct event_iocp_port {
+       /** The port itself */
+       HANDLE port;
+       /* A lock to cover internal structures. */
+       CRITICAL_SECTION lock;
+       /** Number of threads ever open on the port. */
+       short n_threads;
+       /** True iff we're shutting down all the threads on this port */
+       short shutdown;
+       /** How often the threads on this port check for shutdown and other
+        * conditions */
+       long ms;
+       /* The threads that are waiting for events. */
+       HANDLE *threads;
+       /** Number of threads currently open on this port. */
+       short n_live_threads;
+       /** A semaphore to signal when we are done shutting down. */
+       HANDLE *shutdownSemaphore;
+};
+
+const struct win32_extension_fns *event_get_win32_extension_fns(void);
+#else
+/* Dummy definition so we can test-compile more things on unix. */
+struct event_overlapped {
+       iocp_callback cb;
+};
+#endif
+
+/** Initialize the fields in an event_overlapped.
+
+    @param overlapped The struct event_overlapped to initialize
+    @param cb The callback that should be invoked once the IO operation has
+       finished.
+ */
+void event_overlapped_init(struct event_overlapped *, iocp_callback cb);
+
+/** Allocate and return a new evbuffer that supports overlapped IO on a given
+    socket.  The socket must be associated with an IO completion port using
+    event_iocp_port_associate.
+*/
+struct evbuffer *evbuffer_overlapped_new(evutil_socket_t fd);
+
+/** XXXX Document (nickm) */
+evutil_socket_t _evbuffer_overlapped_get_fd(struct evbuffer *buf);
+
+void _evbuffer_overlapped_set_fd(struct evbuffer *buf, evutil_socket_t fd);
+
+/** Start reading data onto the end of an overlapped evbuffer.
+
+    An evbuffer can only have one read pending at a time.  While the read
+    is in progress, no other data may be added to the end of the buffer.
+    The buffer must be created with event_overlapped_init().
+    evbuffer_commit_read() must be called in the completion callback.
+
+    @param buf The buffer to read onto
+    @param n The number of bytes to try to read.
+    @param ol Overlapped object with associated completion callback.
+    @return 0 on success, -1 on error.
+ */
+int evbuffer_launch_read(struct evbuffer *buf, size_t n, struct event_overlapped *ol);
+
+/** Start writing data from the start of an evbuffer.
+
+    An evbuffer can only have one write pending at a time.  While the write is
+    in progress, no other data may be removed from the front of the buffer.
+    The buffer must be created with event_overlapped_init().
+    evbuffer_commit_write() must be called in the completion callback.
+
+    @param buf The buffer to read onto
+    @param n The number of bytes to try to read.
+    @param ol Overlapped object with associated completion callback.
+    @return 0 on success, -1 on error.
+ */
+int evbuffer_launch_write(struct evbuffer *buf, ev_ssize_t n, struct event_overlapped *ol);
+
+/** XXX document */
+void evbuffer_commit_read(struct evbuffer *, ev_ssize_t);
+void evbuffer_commit_write(struct evbuffer *, ev_ssize_t);
+
+/** Create an IOCP, and launch its worker threads.  Internal use only.
+
+    This interface is unstable, and will change.
+ */
+struct event_iocp_port *event_iocp_port_launch(int n_cpus);
+
+/** Associate a file descriptor with an iocp, such that overlapped IO on the
+    fd will happen on one of the iocp's worker threads.
+*/
+int event_iocp_port_associate(struct event_iocp_port *port, evutil_socket_t fd,
+    ev_uintptr_t key);
+
+/** Tell all threads serving an iocp to stop.  Wait for up to waitMsec for all
+    the threads to finish whatever they're doing.  If waitMsec is -1, wait
+    as long as required.  If all the threads are done, free the port and return
+    0. Otherwise, return -1.  If you get a -1 return value, it is safe to call
+    this function again.
+*/
+int event_iocp_shutdown(struct event_iocp_port *port, long waitMsec);
+
+/* FIXME document. */
+int event_iocp_activate_overlapped(struct event_iocp_port *port,
+    struct event_overlapped *o,
+    ev_uintptr_t key, ev_uint32_t n_bytes);
+
+struct event_base;
+/* FIXME document. */
+struct event_iocp_port *event_base_get_iocp(struct event_base *base);
+
+/* FIXME document. */
+int event_base_start_iocp(struct event_base *base, int n_cpus);
+void event_base_stop_iocp(struct event_base *base);
+
+/* FIXME document. */
+struct bufferevent *bufferevent_async_new(struct event_base *base,
+    evutil_socket_t fd, int options);
+
+/* FIXME document. */
+void bufferevent_async_set_connected(struct bufferevent *bev);
+int bufferevent_async_can_connect(struct bufferevent *bev);
+int bufferevent_async_connect(struct bufferevent *bev, evutil_socket_t fd,
+       const struct sockaddr *sa, int socklen);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libevent/ipv6-internal.h b/libevent/ipv6-internal.h
new file mode 100644 (file)
index 0000000..e373711
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+/* Internal use only: Fake IPv6 structures and values on platforms that
+ * do not have them */
+
+#ifndef _EVENT_IPV6_INTERNAL_H
+#define _EVENT_IPV6_INTERNAL_H
+
+#include <sys/types.h>
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include "event2/event-config.h"
+#include "event2/util.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** @file ipv6-internal.h
+ *
+ * Replacement types and functions for platforms that don't support ipv6
+ * properly.
+ */
+
+#ifndef _EVENT_HAVE_STRUCT_IN6_ADDR
+struct in6_addr {
+       ev_uint8_t s6_addr[16];
+};
+#endif
+
+#ifndef _EVENT_HAVE_SA_FAMILY_T
+typedef int sa_family_t;
+#endif
+
+#ifndef _EVENT_HAVE_STRUCT_SOCKADDR_IN6
+struct sockaddr_in6 {
+       /* This will fail if we find a struct sockaddr that doesn't have
+        * sa_family as the first element. */
+       sa_family_t sin6_family;
+       ev_uint16_t sin6_port;
+       struct in6_addr sin6_addr;
+};
+#endif
+
+#ifndef AF_INET6
+#define AF_INET6 3333
+#endif
+#ifndef PF_INET6
+#define PF_INET6 AF_INET6
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libevent/kqueue.c b/libevent/kqueue.c
new file mode 100644 (file)
index 0000000..51984a4
--- /dev/null
@@ -0,0 +1,475 @@
+/*     $OpenBSD: kqueue.c,v 1.5 2002/07/10 14:41:31 art Exp $  */
+
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#define _GNU_SOURCE
+
+#include <sys/types.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <sys/event.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#ifdef _EVENT_HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif
+
+/* Some platforms apparently define the udata field of struct kevent as
+ * intptr_t, whereas others define it as void*.  There doesn't seem to be an
+ * easy way to tell them apart via autoconf, so we need to use OS macros. */
+#if defined(_EVENT_HAVE_INTTYPES_H) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__darwin__) && !defined(__APPLE__)
+#define PTR_TO_UDATA(x)        ((intptr_t)(x))
+#define INT_TO_UDATA(x) ((intptr_t)(x))
+#else
+#define PTR_TO_UDATA(x)        (x)
+#define INT_TO_UDATA(x) ((void*)(x))
+#endif
+
+#include "event-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+#include "changelist-internal.h"
+
+#define NEVENT         64
+
+struct kqop {
+       struct kevent *changes;
+       int changes_size;
+
+       struct kevent *events;
+       int events_size;
+       int kq;
+       pid_t pid;
+};
+
+static void kqop_free(struct kqop *kqop);
+
+static void *kq_init(struct event_base *);
+static int kq_sig_add(struct event_base *, int, short, short, void *);
+static int kq_sig_del(struct event_base *, int, short, short, void *);
+static int kq_dispatch(struct event_base *, struct timeval *);
+static void kq_dealloc(struct event_base *);
+
+const struct eventop kqops = {
+       "kqueue",
+       kq_init,
+       event_changelist_add,
+       event_changelist_del,
+       kq_dispatch,
+       kq_dealloc,
+       1 /* need reinit */,
+    EV_FEATURE_ET|EV_FEATURE_O1|EV_FEATURE_FDS,
+       EVENT_CHANGELIST_FDINFO_SIZE
+};
+
+static const struct eventop kqsigops = {
+       "kqueue_signal",
+       NULL,
+       kq_sig_add,
+       kq_sig_del,
+       NULL,
+       NULL,
+       1 /* need reinit */,
+       0,
+       0
+};
+
+static void *
+kq_init(struct event_base *base)
+{
+       int kq = -1;
+       struct kqop *kqueueop = NULL;
+
+       if (!(kqueueop = mm_calloc(1, sizeof(struct kqop))))
+               return (NULL);
+
+/* Initialize the kernel queue */
+
+       if ((kq = kqueue()) == -1) {
+               event_warn("kqueue");
+               goto err;
+       }
+
+       kqueueop->kq = kq;
+
+       kqueueop->pid = getpid();
+
+       /* Initialize fields */
+       kqueueop->changes = mm_calloc(NEVENT, sizeof(struct kevent));
+       if (kqueueop->changes == NULL)
+               goto err;
+       kqueueop->events = mm_calloc(NEVENT, sizeof(struct kevent));
+       if (kqueueop->events == NULL)
+               goto err;
+       kqueueop->events_size = kqueueop->changes_size = NEVENT;
+
+       /* Check for Mac OS X kqueue bug. */
+       memset(&kqueueop->changes[0], 0, sizeof kqueueop->changes[0]);
+       kqueueop->changes[0].ident = -1;
+       kqueueop->changes[0].filter = EVFILT_READ;
+       kqueueop->changes[0].flags = EV_ADD;
+       /*
+        * If kqueue works, then kevent will succeed, and it will
+        * stick an error in events[0].  If kqueue is broken, then
+        * kevent will fail.
+        */
+       if (kevent(kq,
+               kqueueop->changes, 1, kqueueop->events, NEVENT, NULL) != 1 ||
+           (int)kqueueop->events[0].ident != -1 ||
+           kqueueop->events[0].flags != EV_ERROR) {
+               event_warn("%s: detected broken kqueue; not using.", __func__);
+               goto err;
+       }
+
+       base->evsigsel = &kqsigops;
+
+       return (kqueueop);
+err:
+       if (kqueueop)
+               kqop_free(kqueueop);
+
+       return (NULL);
+}
+
+static void
+kq_sighandler(int sig)
+{
+       /* Do nothing here */
+}
+
+#define ADD_UDATA 0x30303
+
+static void
+kq_setup_kevent(struct kevent *out, evutil_socket_t fd, int filter, short change)
+{
+       memset(out, 0, sizeof(struct kevent));
+       out->ident = fd;
+       out->filter = filter;
+
+       if (change & EV_CHANGE_ADD) {
+               out->flags = EV_ADD;
+               /* We set a magic number here so that we can tell 'add'
+                * errors from 'del' errors. */
+               out->udata = INT_TO_UDATA(ADD_UDATA);
+               if (change & EV_ET)
+                       out->flags |= EV_CLEAR;
+#ifdef NOTE_EOF
+               /* Make it behave like select() and poll() */
+               if (filter == EVFILT_READ)
+                       out->fflags = NOTE_EOF;
+#endif
+       } else {
+               EVUTIL_ASSERT(change & EV_CHANGE_DEL);
+               out->flags = EV_DELETE;
+       }
+}
+
+static int
+kq_build_changes_list(const struct event_changelist *changelist,
+    struct kqop *kqop)
+{
+       int i;
+       int n_changes = 0;
+
+       for (i = 0; i < changelist->n_changes; ++i) {
+               struct event_change *in_ch = &changelist->changes[i];
+               struct kevent *out_ch;
+               if (n_changes >= kqop->changes_size - 1) {
+                       int newsize = kqop->changes_size * 2;
+                       struct kevent *newchanges;
+
+                       newchanges = mm_realloc(kqop->changes,
+                           newsize * sizeof(struct kevent));
+                       if (newchanges == NULL) {
+                               event_warn("%s: realloc", __func__);
+                               return (-1);
+                       }
+                       kqop->changes = newchanges;
+                       kqop->changes_size = newsize;
+               }
+               if (in_ch->read_change) {
+                       out_ch = &kqop->changes[n_changes++];
+                       kq_setup_kevent(out_ch, in_ch->fd, EVFILT_READ,
+                           in_ch->read_change);
+               }
+               if (in_ch->write_change) {
+                       out_ch = &kqop->changes[n_changes++];
+                       kq_setup_kevent(out_ch, in_ch->fd, EVFILT_WRITE,
+                           in_ch->write_change);
+               }
+       }
+       return n_changes;
+}
+
+static int
+kq_grow_events(struct kqop *kqop, size_t new_size)
+{
+       struct kevent *newresult;
+
+       newresult = mm_realloc(kqop->events,
+           new_size * sizeof(struct kevent));
+
+       if (newresult) {
+               kqop->events = newresult;
+               kqop->events_size = new_size;
+               return 0;
+       } else {
+               return -1;
+       }
+}
+
+static int
+kq_dispatch(struct event_base *base, struct timeval *tv)
+{
+       struct kqop *kqop = base->evbase;
+       struct kevent *events = kqop->events;
+       struct kevent *changes;
+       struct timespec ts, *ts_p = NULL;
+       int i, n_changes, res;
+
+       if (tv != NULL) {
+               TIMEVAL_TO_TIMESPEC(tv, &ts);
+               ts_p = &ts;
+       }
+
+       /* Build "changes" from "base->changes" */
+       EVUTIL_ASSERT(kqop->changes);
+       n_changes = kq_build_changes_list(&base->changelist, kqop);
+       if (n_changes < 0)
+               return -1;
+
+       event_changelist_remove_all(&base->changelist, base);
+
+       /* steal the changes array in case some broken code tries to call
+        * dispatch twice at once. */
+       changes = kqop->changes;
+       kqop->changes = NULL;
+
+       /* Make sure that 'events' is at least as long as the list of changes:
+        * otherwise errors in the changes can get reported as a -1 return
+        * value from kevent() rather than as EV_ERROR events in the events
+        * array.
+        *
+        * (We could instead handle -1 return values from kevent() by
+        * retrying with a smaller changes array or a larger events array,
+        * but this approach seems less risky for now.)
+        */
+       if (kqop->events_size < n_changes) {
+               int new_size = kqop->events_size;
+               do {
+                       new_size *= 2;
+               } while (new_size < n_changes);
+
+               kq_grow_events(kqop, new_size);
+               events = kqop->events;
+       }
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+       res = kevent(kqop->kq, changes, n_changes,
+           events, kqop->events_size, ts_p);
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       EVUTIL_ASSERT(kqop->changes == NULL);
+       kqop->changes = changes;
+
+       if (res == -1) {
+               if (errno != EINTR) {
+                       event_warn("kevent");
+                       return (-1);
+               }
+
+               return (0);
+       }
+
+       event_debug(("%s: kevent reports %d", __func__, res));
+
+       for (i = 0; i < res; i++) {
+               int which = 0;
+
+               if (events[i].flags & EV_ERROR) {
+                       switch (events[i].data) {
+
+                       /* Can occur on delete if we are not currently
+                        * watching any events on this fd.  That can
+                        * happen when the fd was closed and another
+                        * file was opened with that fd. */
+                       case ENOENT:
+                       /* Can occur for reasons not fully understood
+                        * on FreeBSD. */
+                       case EINVAL:
+                               continue;
+
+                       /* Can occur on a delete if the fd is closed. */
+                       case EBADF:
+                               /* XXXX On NetBSD, we can also get EBADF if we
+                                * try to add the write side of a pipe, but
+                                * the read side has already been closed.
+                                * Other BSDs call this situation 'EPIPE'. It
+                                * would be good if we had a way to report
+                                * this situation. */
+                               continue;
+                       /* These two can occur on an add if the fd was one side
+                        * of a pipe, and the other side was closed. */
+                       case EPERM:
+                       case EPIPE:
+                               /* Report read events, if we're listening for
+                                * them, so that the user can learn about any
+                                * add errors.  (If the operation was a
+                                * delete, then udata should be cleared.) */
+                               if (events[i].udata) {
+                                       /* The operation was an add:
+                                        * report the error as a read. */
+                                       which |= EV_READ;
+                                       break;
+                               } else {
+                                       /* The operation was a del:
+                                        * report nothing. */
+                                       continue;
+                               }
+
+                       /* Other errors shouldn't occur. */
+                       default:
+                               errno = events[i].data;
+                               return (-1);
+                       }
+               } else if (events[i].filter == EVFILT_READ) {
+                       which |= EV_READ;
+               } else if (events[i].filter == EVFILT_WRITE) {
+                       which |= EV_WRITE;
+               } else if (events[i].filter == EVFILT_SIGNAL) {
+                       which |= EV_SIGNAL;
+               }
+
+               if (!which)
+                       continue;
+
+               if (events[i].filter == EVFILT_SIGNAL) {
+                       evmap_signal_active(base, events[i].ident, 1);
+               } else {
+                       evmap_io_active(base, events[i].ident, which | EV_ET);
+               }
+       }
+
+       if (res == kqop->events_size) {
+               /* We used all the events space that we have. Maybe we should
+                  make it bigger. */
+               kq_grow_events(kqop, kqop->events_size * 2);
+       }
+
+       return (0);
+}
+
+static void
+kqop_free(struct kqop *kqop)
+{
+       if (kqop->changes)
+               mm_free(kqop->changes);
+       if (kqop->events)
+               mm_free(kqop->events);
+       if (kqop->kq >= 0 && kqop->pid == getpid())
+               close(kqop->kq);
+       memset(kqop, 0, sizeof(struct kqop));
+       mm_free(kqop);
+}
+
+static void
+kq_dealloc(struct event_base *base)
+{
+       struct kqop *kqop = base->evbase;
+       evsig_dealloc(base);
+       kqop_free(kqop);
+}
+
+/* signal handling */
+static int
+kq_sig_add(struct event_base *base, int nsignal, short old, short events, void *p)
+{
+       struct kqop *kqop = base->evbase;
+       struct kevent kev;
+       struct timespec timeout = { 0, 0 };
+       (void)p;
+
+       EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
+
+       memset(&kev, 0, sizeof(kev));
+       kev.ident = nsignal;
+       kev.filter = EVFILT_SIGNAL;
+       kev.flags = EV_ADD;
+
+       /* Be ready for the signal if it is sent any
+        * time between now and the next call to
+        * kq_dispatch. */
+       if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
+               return (-1);
+
+       /* XXXX The manpage suggest we could use SIG_IGN instead of a
+        * do-nothing handler */
+       if (_evsig_set_handler(base, nsignal, kq_sighandler) == -1)
+               return (-1);
+
+       return (0);
+}
+
+static int
+kq_sig_del(struct event_base *base, int nsignal, short old, short events, void *p)
+{
+       struct kqop *kqop = base->evbase;
+       struct kevent kev;
+
+       struct timespec timeout = { 0, 0 };
+       (void)p;
+
+       EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
+
+       memset(&kev, 0, sizeof(kev));
+       kev.ident = nsignal;
+       kev.filter = EVFILT_SIGNAL;
+       kev.flags = EV_DELETE;
+
+       /* Because we insert signal events
+        * immediately, we need to delete them
+        * immediately, too */
+       if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
+               return (-1);
+
+       if (_evsig_restore_handler(base, nsignal) == -1)
+               return (-1);
+
+       return (0);
+}
diff --git a/libevent/libevent.pc.in b/libevent/libevent.pc.in
new file mode 100644 (file)
index 0000000..7030884
--- /dev/null
@@ -0,0 +1,16 @@
+#libevent pkg-config source file
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libevent
+Description: libevent is an asynchronous notification event loop library
+Version: @VERSION@
+Requires:
+Conflicts:
+Libs: -L${libdir} -levent
+Libs.private: @LIBS@
+Cflags: -I${includedir}
+
diff --git a/libevent/libevent_openssl.pc.in b/libevent/libevent_openssl.pc.in
new file mode 100644 (file)
index 0000000..9624cf2
--- /dev/null
@@ -0,0 +1,16 @@
+#libevent pkg-config source file
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libevent_openssl
+Description: libevent_openssl adds openssl-based TLS support to libevent
+Version: @VERSION@
+Requires: libevent
+Conflicts:
+Libs: -L${libdir} -levent_openssl
+Libs.private: @LIBS@ -lssl -lcrypto
+Cflags: -I${includedir}
+
diff --git a/libevent/libevent_pthreads.pc.in b/libevent/libevent_pthreads.pc.in
new file mode 100644 (file)
index 0000000..9bc2392
--- /dev/null
@@ -0,0 +1,16 @@
+#libevent pkg-config source file
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libevent_pthreads
+Description: libevent_pthreads adds pthreads-based threading support to libevent
+Version: @VERSION@
+Requires: libevent
+Conflicts:
+Libs: -L${libdir} -levent_pthreads
+Libs.private: @LIBS@ @PTHREAD_LIBS@
+Cflags: -I${includedir} @PTHREAD_CFLAGS@
+
diff --git a/libevent/listener.c b/libevent/listener.c
new file mode 100644 (file)
index 0000000..9941e1d
--- /dev/null
@@ -0,0 +1,875 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+
+#include "event2/event-config.h"
+
+#ifdef WIN32
+#ifndef _WIN32_WINNT
+/* Minimum required for InitializeCriticalSectionAndSpinCount */
+#define _WIN32_WINNT 0x0403
+#endif
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <mswsock.h>
+#endif
+#include <errno.h>
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef _EVENT_HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#include "event2/listener.h"
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "evthread-internal.h"
+#ifdef WIN32
+#include "iocp-internal.h"
+#include "defer-internal.h"
+#include "event-internal.h"
+#endif
+
+struct evconnlistener_ops {
+       int (*enable)(struct evconnlistener *);
+       int (*disable)(struct evconnlistener *);
+       void (*destroy)(struct evconnlistener *);
+       void (*shutdown)(struct evconnlistener *);
+       evutil_socket_t (*getfd)(struct evconnlistener *);
+       struct event_base *(*getbase)(struct evconnlistener *);
+};
+
+struct evconnlistener {
+       const struct evconnlistener_ops *ops;
+       void *lock;
+       evconnlistener_cb cb;
+       evconnlistener_errorcb errorcb;
+       void *user_data;
+       unsigned flags;
+       short refcnt;
+       unsigned enabled : 1;
+};
+
+struct evconnlistener_event {
+       struct evconnlistener base;
+       struct event listener;
+};
+
+#ifdef WIN32
+struct evconnlistener_iocp {
+       struct evconnlistener base;
+       evutil_socket_t fd;
+       struct event_base *event_base;
+       struct event_iocp_port *port;
+       short n_accepting;
+       unsigned shutting_down : 1;
+       unsigned event_added : 1;
+       struct accepting_socket **accepting;
+};
+#endif
+
+#define LOCK(listener) EVLOCK_LOCK((listener)->lock, 0)
+#define UNLOCK(listener) EVLOCK_UNLOCK((listener)->lock, 0)
+
+struct evconnlistener *
+evconnlistener_new_async(struct event_base *base,
+    evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+    evutil_socket_t fd); /* XXXX export this? */
+
+static int event_listener_enable(struct evconnlistener *);
+static int event_listener_disable(struct evconnlistener *);
+static void event_listener_destroy(struct evconnlistener *);
+static evutil_socket_t event_listener_getfd(struct evconnlistener *);
+static struct event_base *event_listener_getbase(struct evconnlistener *);
+
+#if 0
+static void
+listener_incref_and_lock(struct evconnlistener *listener)
+{
+       LOCK(listener);
+       ++listener->refcnt;
+}
+#endif
+
+static int
+listener_decref_and_unlock(struct evconnlistener *listener)
+{
+       int refcnt = --listener->refcnt;
+       if (refcnt == 0) {
+               listener->ops->destroy(listener);
+               UNLOCK(listener);
+               EVTHREAD_FREE_LOCK(listener->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+               mm_free(listener);
+               return 1;
+       } else {
+               UNLOCK(listener);
+               return 0;
+       }
+}
+
+static const struct evconnlistener_ops evconnlistener_event_ops = {
+       event_listener_enable,
+       event_listener_disable,
+       event_listener_destroy,
+       NULL, /* shutdown */
+       event_listener_getfd,
+       event_listener_getbase
+};
+
+static void listener_read_cb(evutil_socket_t, short, void *);
+
+struct evconnlistener *
+evconnlistener_new(struct event_base *base,
+    evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+    evutil_socket_t fd)
+{
+       struct evconnlistener_event *lev;
+
+#ifdef WIN32
+       if (base && event_base_get_iocp(base)) {
+               const struct win32_extension_fns *ext =
+                       event_get_win32_extension_fns();
+               if (ext->AcceptEx && ext->GetAcceptExSockaddrs)
+                       return evconnlistener_new_async(base, cb, ptr, flags,
+                               backlog, fd);
+       }
+#endif
+
+       if (backlog > 0) {
+               if (listen(fd, backlog) < 0)
+                       return NULL;
+       } else if (backlog < 0) {
+               if (listen(fd, 128) < 0)
+                       return NULL;
+       }
+
+       lev = mm_calloc(1, sizeof(struct evconnlistener_event));
+       if (!lev)
+               return NULL;
+
+       lev->base.ops = &evconnlistener_event_ops;
+       lev->base.cb = cb;
+       lev->base.user_data = ptr;
+       lev->base.flags = flags;
+       lev->base.refcnt = 1;
+
+       if (flags & LEV_OPT_THREADSAFE) {
+               EVTHREAD_ALLOC_LOCK(lev->base.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       }
+
+       event_assign(&lev->listener, base, fd, EV_READ|EV_PERSIST,
+           listener_read_cb, lev);
+
+       evconnlistener_enable(&lev->base);
+
+       return &lev->base;
+}
+
+struct evconnlistener *
+evconnlistener_new_bind(struct event_base *base, evconnlistener_cb cb,
+    void *ptr, unsigned flags, int backlog, const struct sockaddr *sa,
+    int socklen)
+{
+       struct evconnlistener *listener;
+       evutil_socket_t fd;
+       int on = 1;
+       int family = sa ? sa->sa_family : AF_UNSPEC;
+
+       if (backlog == 0)
+               return NULL;
+
+       fd = socket(family, SOCK_STREAM, 0);
+       if (fd == -1)
+               return NULL;
+
+       if (evutil_make_socket_nonblocking(fd) < 0) {
+               evutil_closesocket(fd);
+               return NULL;
+       }
+
+       if (flags & LEV_OPT_CLOSE_ON_EXEC) {
+               if (evutil_make_socket_closeonexec(fd) < 0) {
+                       evutil_closesocket(fd);
+                       return NULL;
+               }
+       }
+
+       setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&on, sizeof(on));
+       if (flags & LEV_OPT_REUSEABLE) {
+               evutil_make_listen_socket_reuseable(fd);
+       }
+
+       if (sa) {
+               if (bind(fd, sa, socklen)<0) {
+                       evutil_closesocket(fd);
+                       return NULL;
+               }
+       }
+
+       listener = evconnlistener_new(base, cb, ptr, flags, backlog, fd);
+       if (!listener) {
+               evutil_closesocket(fd);
+               return NULL;
+       }
+
+       return listener;
+}
+
+void
+evconnlistener_free(struct evconnlistener *lev)
+{
+       LOCK(lev);
+       lev->cb = NULL;
+       lev->errorcb = NULL;
+       if (lev->ops->shutdown)
+               lev->ops->shutdown(lev);
+       listener_decref_and_unlock(lev);
+}
+
+static void
+event_listener_destroy(struct evconnlistener *lev)
+{
+       struct evconnlistener_event *lev_e =
+           EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+
+       event_del(&lev_e->listener);
+       if (lev->flags & LEV_OPT_CLOSE_ON_FREE)
+               evutil_closesocket(event_get_fd(&lev_e->listener));
+       event_debug_unassign(&lev_e->listener);
+}
+
+int
+evconnlistener_enable(struct evconnlistener *lev)
+{
+       int r;
+       LOCK(lev);
+       lev->enabled = 1;
+       if (lev->cb)
+               r = lev->ops->enable(lev);
+       else
+               r = 0;
+       UNLOCK(lev);
+       return r;
+}
+
+int
+evconnlistener_disable(struct evconnlistener *lev)
+{
+       int r;
+       LOCK(lev);
+       lev->enabled = 0;
+       r = lev->ops->disable(lev);
+       UNLOCK(lev);
+       return r;
+}
+
+static int
+event_listener_enable(struct evconnlistener *lev)
+{
+       struct evconnlistener_event *lev_e =
+           EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+       return event_add(&lev_e->listener, NULL);
+}
+
+static int
+event_listener_disable(struct evconnlistener *lev)
+{
+       struct evconnlistener_event *lev_e =
+           EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+       return event_del(&lev_e->listener);
+}
+
+evutil_socket_t
+evconnlistener_get_fd(struct evconnlistener *lev)
+{
+       evutil_socket_t fd;
+       LOCK(lev);
+       fd = lev->ops->getfd(lev);
+       UNLOCK(lev);
+       return fd;
+}
+
+static evutil_socket_t
+event_listener_getfd(struct evconnlistener *lev)
+{
+       struct evconnlistener_event *lev_e =
+           EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+       return event_get_fd(&lev_e->listener);
+}
+
+struct event_base *
+evconnlistener_get_base(struct evconnlistener *lev)
+{
+       struct event_base *base;
+       LOCK(lev);
+       base = lev->ops->getbase(lev);
+       UNLOCK(lev);
+       return base;
+}
+
+static struct event_base *
+event_listener_getbase(struct evconnlistener *lev)
+{
+       struct evconnlistener_event *lev_e =
+           EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+       return event_get_base(&lev_e->listener);
+}
+
+void
+evconnlistener_set_cb(struct evconnlistener *lev,
+    evconnlistener_cb cb, void *arg)
+{
+       int enable = 0;
+       LOCK(lev);
+       if (lev->enabled && !lev->cb)
+               enable = 1;
+       lev->cb = cb;
+       lev->user_data = arg;
+       if (enable)
+               evconnlistener_enable(lev);
+       UNLOCK(lev);
+}
+
+void
+evconnlistener_set_error_cb(struct evconnlistener *lev,
+    evconnlistener_errorcb errorcb)
+{
+       LOCK(lev);
+       lev->errorcb = errorcb;
+       UNLOCK(lev);
+}
+
+static void
+listener_read_cb(evutil_socket_t fd, short what, void *p)
+{
+       struct evconnlistener *lev = p;
+       int err;
+       evconnlistener_cb cb;
+       evconnlistener_errorcb errorcb;
+       void *user_data;
+       LOCK(lev);
+       while (1) {
+               struct sockaddr_storage ss;
+#ifdef WIN32
+               int socklen = sizeof(ss);
+#else
+               socklen_t socklen = sizeof(ss);
+#endif
+               evutil_socket_t new_fd = accept(fd, (struct sockaddr*)&ss, &socklen);
+               if (new_fd < 0)
+                       break;
+               if (socklen == 0) {
+                       /* This can happen with some older linux kernels in
+                        * response to nmap. */
+                       evutil_closesocket(new_fd);
+                       continue;
+               }
+
+               if (!(lev->flags & LEV_OPT_LEAVE_SOCKETS_BLOCKING))
+                       evutil_make_socket_nonblocking(new_fd);
+
+               if (lev->cb == NULL) {
+                       UNLOCK(lev);
+                       return;
+               }
+               ++lev->refcnt;
+               cb = lev->cb;
+               user_data = lev->user_data;
+               UNLOCK(lev);
+               cb(lev, new_fd, (struct sockaddr*)&ss, (int)socklen,
+                   user_data);
+               LOCK(lev);
+               if (lev->refcnt == 1) {
+                       int freed = listener_decref_and_unlock(lev);
+                       EVUTIL_ASSERT(freed);
+                       return;
+               }
+               --lev->refcnt;
+       }
+       err = evutil_socket_geterror(fd);
+       if (EVUTIL_ERR_ACCEPT_RETRIABLE(err)) {
+               UNLOCK(lev);
+               return;
+       }
+       if (lev->errorcb != NULL) {
+               ++lev->refcnt;
+               errorcb = lev->errorcb;
+               user_data = lev->user_data;
+               UNLOCK(lev);
+               errorcb(lev, user_data);
+               LOCK(lev);
+               listener_decref_and_unlock(lev);
+       } else {
+               event_sock_warn(fd, "Error from accept() call");
+       }
+}
+
+#ifdef WIN32
+struct accepting_socket {
+       CRITICAL_SECTION lock;
+       struct event_overlapped overlapped;
+       SOCKET s;
+       int error;
+       struct deferred_cb deferred;
+       struct evconnlistener_iocp *lev;
+       ev_uint8_t buflen;
+       ev_uint8_t family;
+       unsigned free_on_cb:1;
+       char addrbuf[1];
+};
+
+static void accepted_socket_cb(struct event_overlapped *o, ev_uintptr_t key,
+    ev_ssize_t n, int ok);
+static void accepted_socket_invoke_user_cb(struct deferred_cb *cb, void *arg);
+
+static void
+iocp_listener_event_add(struct evconnlistener_iocp *lev)
+{
+       if (lev->event_added)
+               return;
+
+       lev->event_added = 1;
+       event_base_add_virtual(lev->event_base);
+}
+
+static void
+iocp_listener_event_del(struct evconnlistener_iocp *lev)
+{
+       if (!lev->event_added)
+               return;
+
+       lev->event_added = 0;
+       event_base_del_virtual(lev->event_base);
+}
+
+static struct accepting_socket *
+new_accepting_socket(struct evconnlistener_iocp *lev, int family)
+{
+       struct accepting_socket *res;
+       int addrlen;
+       int buflen;
+
+       if (family == AF_INET)
+               addrlen = sizeof(struct sockaddr_in);
+       else if (family == AF_INET6)
+               addrlen = sizeof(struct sockaddr_in6);
+       else
+               return NULL;
+       buflen = (addrlen+16)*2;
+
+       res = mm_calloc(1,sizeof(struct accepting_socket)-1+buflen);
+       if (!res)
+               return NULL;
+
+       event_overlapped_init(&res->overlapped, accepted_socket_cb);
+       res->s = INVALID_SOCKET;
+       res->lev = lev;
+       res->buflen = buflen;
+       res->family = family;
+
+       event_deferred_cb_init(&res->deferred,
+               accepted_socket_invoke_user_cb, res);
+
+       InitializeCriticalSectionAndSpinCount(&res->lock, 1000);
+
+       return res;
+}
+
+static void
+free_and_unlock_accepting_socket(struct accepting_socket *as)
+{
+       /* requires lock. */
+       if (as->s != INVALID_SOCKET)
+               closesocket(as->s);
+
+       LeaveCriticalSection(&as->lock);
+       DeleteCriticalSection(&as->lock);
+       mm_free(as);
+}
+
+static int
+start_accepting(struct accepting_socket *as)
+{
+       /* requires lock */
+       const struct win32_extension_fns *ext = event_get_win32_extension_fns();
+       DWORD pending = 0;
+       SOCKET s = socket(as->family, SOCK_STREAM, 0);
+       int error = 0;
+
+       if (!as->lev->base.enabled)
+               return 0;
+
+       if (s == INVALID_SOCKET) {
+               error = WSAGetLastError();
+               goto report_err;
+       }
+
+       /* XXXX It turns out we need to do this again later.  Does this call
+        * have any effect? */
+       setsockopt(s, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
+           (char *)&as->lev->fd, sizeof(&as->lev->fd));
+
+       if (!(as->lev->base.flags & LEV_OPT_LEAVE_SOCKETS_BLOCKING))
+               evutil_make_socket_nonblocking(s);
+
+       if (event_iocp_port_associate(as->lev->port, s, 1) < 0) {
+               closesocket(s);
+               return -1;
+       }
+
+       as->s = s;
+
+       if (ext->AcceptEx(as->lev->fd, s, as->addrbuf, 0,
+               as->buflen/2, as->buflen/2, &pending, &as->overlapped.overlapped))
+       {
+               /* Immediate success! */
+               accepted_socket_cb(&as->overlapped, 1, 0, 1);
+       } else {
+               error = WSAGetLastError();
+               if (error != ERROR_IO_PENDING) {
+                       goto report_err;
+               }
+       }
+
+       return 0;
+
+report_err:
+       as->error = error;
+       event_deferred_cb_schedule(
+               event_base_get_deferred_cb_queue(as->lev->event_base),
+               &as->deferred);
+       return 0;
+}
+
+static void
+stop_accepting(struct accepting_socket *as)
+{
+       /* requires lock. */
+       SOCKET s = as->s;
+       as->s = INVALID_SOCKET;
+       closesocket(s);
+}
+
+static void
+accepted_socket_invoke_user_cb(struct deferred_cb *dcb, void *arg)
+{
+       struct accepting_socket *as = arg;
+
+       struct sockaddr *sa_local=NULL, *sa_remote=NULL;
+       int socklen_local=0, socklen_remote=0;
+       const struct win32_extension_fns *ext = event_get_win32_extension_fns();
+       struct evconnlistener *lev = &as->lev->base;
+       evutil_socket_t sock=-1;
+       void *data;
+       evconnlistener_cb cb=NULL;
+       evconnlistener_errorcb errorcb=NULL;
+       int error;
+
+       EVUTIL_ASSERT(ext->GetAcceptExSockaddrs);
+
+       LOCK(lev);
+       EnterCriticalSection(&as->lock);
+       if (as->free_on_cb) {
+               free_and_unlock_accepting_socket(as);
+               listener_decref_and_unlock(lev);
+               return;
+       }
+
+       ++lev->refcnt;
+
+       error = as->error;
+       if (error) {
+               as->error = 0;
+               errorcb = lev->errorcb;
+       } else {
+               ext->GetAcceptExSockaddrs(
+                       as->addrbuf, 0, as->buflen/2, as->buflen/2,
+                       &sa_local, &socklen_local, &sa_remote,
+                       &socklen_remote);
+               sock = as->s;
+               cb = lev->cb;
+               as->s = INVALID_SOCKET;
+
+               /* We need to call this so getsockname, getpeername, and
+                * shutdown work correctly on the accepted socket. */
+               /* XXXX handle error? */
+               setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
+                   (char *)&as->lev->fd, sizeof(&as->lev->fd));
+       }
+       data = lev->user_data;
+
+       LeaveCriticalSection(&as->lock);
+       UNLOCK(lev);
+
+       if (errorcb) {
+               WSASetLastError(error);
+               errorcb(lev, data);
+       } else if (cb) {
+               cb(lev, sock, sa_remote, socklen_remote, data);
+       }
+
+       LOCK(lev);
+       if (listener_decref_and_unlock(lev))
+               return;
+
+       EnterCriticalSection(&as->lock);
+       start_accepting(as);
+       LeaveCriticalSection(&as->lock);
+}
+
+static void
+accepted_socket_cb(struct event_overlapped *o, ev_uintptr_t key, ev_ssize_t n, int ok)
+{
+       struct accepting_socket *as =
+           EVUTIL_UPCAST(o, struct accepting_socket, overlapped);
+
+       LOCK(&as->lev->base);
+       EnterCriticalSection(&as->lock);
+       if (ok) {
+               /* XXXX Don't do this if some EV_MT flag is set. */
+               event_deferred_cb_schedule(
+                       event_base_get_deferred_cb_queue(as->lev->event_base),
+                       &as->deferred);
+               LeaveCriticalSection(&as->lock);
+       } else if (as->free_on_cb) {
+               struct evconnlistener *lev = &as->lev->base;
+               free_and_unlock_accepting_socket(as);
+               listener_decref_and_unlock(lev);
+               return;
+       } else if (as->s == INVALID_SOCKET) {
+               /* This is okay; we were disabled by iocp_listener_disable. */
+               LeaveCriticalSection(&as->lock);
+       } else {
+               /* Some error on accept that we couldn't actually handle. */
+               BOOL ok;
+               DWORD transfer = 0, flags=0;
+               event_sock_warn(as->s, "Unexpected error on AcceptEx");
+               ok = WSAGetOverlappedResult(as->s, &o->overlapped,
+                   &transfer, FALSE, &flags);
+               if (ok) {
+                       /* well, that was confusing! */
+                       as->error = 1;
+               } else {
+                       as->error = WSAGetLastError();
+               }
+               event_deferred_cb_schedule(
+                       event_base_get_deferred_cb_queue(as->lev->event_base),
+                       &as->deferred);
+               LeaveCriticalSection(&as->lock);
+       }
+       UNLOCK(&as->lev->base);
+}
+
+static int
+iocp_listener_enable(struct evconnlistener *lev)
+{
+       int i;
+       struct evconnlistener_iocp *lev_iocp =
+           EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+
+       LOCK(lev);
+       iocp_listener_event_add(lev_iocp);
+       for (i = 0; i < lev_iocp->n_accepting; ++i) {
+               struct accepting_socket *as = lev_iocp->accepting[i];
+               if (!as)
+                       continue;
+               EnterCriticalSection(&as->lock);
+               if (!as->free_on_cb && as->s == INVALID_SOCKET)
+                       start_accepting(as);
+               LeaveCriticalSection(&as->lock);
+       }
+       UNLOCK(lev);
+       return 0;
+}
+
+static int
+iocp_listener_disable_impl(struct evconnlistener *lev, int shutdown)
+{
+       int i;
+       struct evconnlistener_iocp *lev_iocp =
+           EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+
+       LOCK(lev);
+       iocp_listener_event_del(lev_iocp);
+       for (i = 0; i < lev_iocp->n_accepting; ++i) {
+               struct accepting_socket *as = lev_iocp->accepting[i];
+               if (!as)
+                       continue;
+               EnterCriticalSection(&as->lock);
+               if (!as->free_on_cb && as->s != INVALID_SOCKET) {
+                       if (shutdown)
+                               as->free_on_cb = 1;
+                       stop_accepting(as);
+               }
+               LeaveCriticalSection(&as->lock);
+       }
+       UNLOCK(lev);
+       return 0;
+}
+
+static int
+iocp_listener_disable(struct evconnlistener *lev)
+{
+       return iocp_listener_disable_impl(lev,0);
+}
+
+static void
+iocp_listener_destroy(struct evconnlistener *lev)
+{
+       struct evconnlistener_iocp *lev_iocp =
+           EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+
+       if (! lev_iocp->shutting_down) {
+               lev_iocp->shutting_down = 1;
+               iocp_listener_disable_impl(lev,1);
+       }
+
+}
+
+static evutil_socket_t
+iocp_listener_getfd(struct evconnlistener *lev)
+{
+       struct evconnlistener_iocp *lev_iocp =
+           EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+       return lev_iocp->fd;
+}
+static struct event_base *
+iocp_listener_getbase(struct evconnlistener *lev)
+{
+       struct evconnlistener_iocp *lev_iocp =
+           EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+       return lev_iocp->event_base;
+}
+
+static const struct evconnlistener_ops evconnlistener_iocp_ops = {
+       iocp_listener_enable,
+       iocp_listener_disable,
+       iocp_listener_destroy,
+       iocp_listener_destroy, /* shutdown */
+       iocp_listener_getfd,
+       iocp_listener_getbase
+};
+
+/* XXX define some way to override this. */
+#define N_SOCKETS_PER_LISTENER 4
+
+struct evconnlistener *
+evconnlistener_new_async(struct event_base *base,
+    evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+    evutil_socket_t fd)
+{
+       struct sockaddr_storage ss;
+       int socklen = sizeof(ss);
+       struct evconnlistener_iocp *lev;
+       int i;
+
+       flags |= LEV_OPT_THREADSAFE;
+
+       if (!base || !event_base_get_iocp(base))
+               goto err;
+
+       /* XXXX duplicate code */
+       if (backlog > 0) {
+               if (listen(fd, backlog) < 0)
+                       goto err;
+       } else if (backlog < 0) {
+               if (listen(fd, 128) < 0)
+                       goto err;
+       }
+       if (getsockname(fd, (struct sockaddr*)&ss, &socklen)) {
+               event_sock_warn(fd, "getsockname");
+               goto err;
+       }
+       lev = mm_calloc(1, sizeof(struct evconnlistener_iocp));
+       if (!lev) {
+               event_warn("calloc");
+               goto err;
+       }
+       lev->base.ops = &evconnlistener_iocp_ops;
+       lev->base.cb = cb;
+       lev->base.user_data = ptr;
+       lev->base.flags = flags;
+       lev->base.refcnt = 1;
+       lev->base.enabled = 1;
+
+       lev->port = event_base_get_iocp(base);
+       lev->fd = fd;
+       lev->event_base = base;
+
+
+       if (event_iocp_port_associate(lev->port, fd, 1) < 0)
+               goto err_free_lev;
+
+       EVTHREAD_ALLOC_LOCK(lev->base.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+
+       lev->n_accepting = N_SOCKETS_PER_LISTENER;
+       lev->accepting = mm_calloc(lev->n_accepting,
+           sizeof(struct accepting_socket *));
+       if (!lev->accepting) {
+               event_warn("calloc");
+               goto err_delete_lock;
+       }
+       for (i = 0; i < lev->n_accepting; ++i) {
+               lev->accepting[i] = new_accepting_socket(lev, ss.ss_family);
+               if (!lev->accepting[i]) {
+                       event_warnx("Couldn't create accepting socket");
+                       goto err_free_accepting;
+               }
+               if (cb && start_accepting(lev->accepting[i]) < 0) {
+                       event_warnx("Couldn't start accepting on socket");
+                       EnterCriticalSection(&lev->accepting[i]->lock);
+                       free_and_unlock_accepting_socket(lev->accepting[i]);
+                       goto err_free_accepting;
+               }
+               ++lev->base.refcnt;
+       }
+
+       iocp_listener_event_add(lev);
+
+       return &lev->base;
+
+err_free_accepting:
+       mm_free(lev->accepting);
+       /* XXXX free the other elements. */
+err_delete_lock:
+       EVTHREAD_FREE_LOCK(lev->base.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+err_free_lev:
+       mm_free(lev);
+err:
+       /* Don't close the fd, it is caller's responsibility. */
+       return NULL;
+}
+
+#endif
diff --git a/libevent/log-internal.h b/libevent/log-internal.h
new file mode 100644 (file)
index 0000000..211b3e1
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _LOG_H_
+#define _LOG_H_
+
+#include "event2/util.h"
+
+#ifdef __GNUC__
+#define EV_CHECK_FMT(a,b) __attribute__((format(printf, a, b)))
+#define EV_NORETURN __attribute__((noreturn))
+#else
+#define EV_CHECK_FMT(a,b)
+#define EV_NORETURN
+#endif
+
+#define _EVENT_ERR_ABORT ((int)0xdeaddead)
+
+void event_err(int eval, const char *fmt, ...) EV_CHECK_FMT(2,3) EV_NORETURN;
+void event_warn(const char *fmt, ...) EV_CHECK_FMT(1,2);
+void event_sock_err(int eval, evutil_socket_t sock, const char *fmt, ...) EV_CHECK_FMT(3,4) EV_NORETURN;
+void event_sock_warn(evutil_socket_t sock, const char *fmt, ...) EV_CHECK_FMT(2,3);
+void event_errx(int eval, const char *fmt, ...) EV_CHECK_FMT(2,3) EV_NORETURN;
+void event_warnx(const char *fmt, ...) EV_CHECK_FMT(1,2);
+void event_msgx(const char *fmt, ...) EV_CHECK_FMT(1,2);
+void _event_debugx(const char *fmt, ...) EV_CHECK_FMT(1,2);
+
+#ifdef USE_DEBUG
+#define event_debug(x) _event_debugx x
+#else
+#define event_debug(x) do {;} while (0)
+#endif
+
+#undef EV_CHECK_FMT
+
+#endif
diff --git a/libevent/log.c b/libevent/log.c
new file mode 100644 (file)
index 0000000..046e81f
--- /dev/null
@@ -0,0 +1,224 @@
+/*     $OpenBSD: err.c,v 1.2 2002/06/25 15:50:15 mickey Exp $  */
+
+/*
+ * log.c
+ *
+ * Based on err.c, which was adapted from OpenBSD libc *err* *warn* code.
+ *
+ * Copyright (c) 2005-2012 Niels Provos and Nick Mathewson
+ *
+ * Copyright (c) 2000 Dug Song <dugsong@monkey.org>
+ *
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+
+#ifdef WIN32
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+#include <sys/types.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <errno.h>
+#include "event2/event.h"
+#include "event2/util.h"
+
+#include "log-internal.h"
+
+static void _warn_helper(int severity, const char *errstr, const char *fmt,
+    va_list ap);
+static void event_log(int severity, const char *msg);
+static void event_exit(int errcode) EV_NORETURN;
+
+static event_fatal_cb fatal_fn = NULL;
+
+void
+event_set_fatal_callback(event_fatal_cb cb)
+{
+       fatal_fn = cb;
+}
+
+static void
+event_exit(int errcode)
+{
+       if (fatal_fn) {
+               fatal_fn(errcode);
+               exit(errcode); /* should never be reached */
+       } else if (errcode == _EVENT_ERR_ABORT)
+               abort();
+       else
+               exit(errcode);
+}
+
+void
+event_err(int eval, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _warn_helper(_EVENT_LOG_ERR, strerror(errno), fmt, ap);
+       va_end(ap);
+       event_exit(eval);
+}
+
+void
+event_warn(const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _warn_helper(_EVENT_LOG_WARN, strerror(errno), fmt, ap);
+       va_end(ap);
+}
+
+void
+event_sock_err(int eval, evutil_socket_t sock, const char *fmt, ...)
+{
+       va_list ap;
+       int err = evutil_socket_geterror(sock);
+
+       va_start(ap, fmt);
+       _warn_helper(_EVENT_LOG_ERR, evutil_socket_error_to_string(err), fmt, ap);
+       va_end(ap);
+       event_exit(eval);
+}
+
+void
+event_sock_warn(evutil_socket_t sock, const char *fmt, ...)
+{
+       va_list ap;
+       int err = evutil_socket_geterror(sock);
+
+       va_start(ap, fmt);
+       _warn_helper(_EVENT_LOG_WARN, evutil_socket_error_to_string(err), fmt, ap);
+       va_end(ap);
+}
+
+void
+event_errx(int eval, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _warn_helper(_EVENT_LOG_ERR, NULL, fmt, ap);
+       va_end(ap);
+       event_exit(eval);
+}
+
+void
+event_warnx(const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _warn_helper(_EVENT_LOG_WARN, NULL, fmt, ap);
+       va_end(ap);
+}
+
+void
+event_msgx(const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _warn_helper(_EVENT_LOG_MSG, NULL, fmt, ap);
+       va_end(ap);
+}
+
+void
+_event_debugx(const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _warn_helper(_EVENT_LOG_DEBUG, NULL, fmt, ap);
+       va_end(ap);
+}
+
+static void
+_warn_helper(int severity, const char *errstr, const char *fmt, va_list ap)
+{
+       char buf[1024];
+       size_t len;
+
+       if (fmt != NULL)
+               evutil_vsnprintf(buf, sizeof(buf), fmt, ap);
+       else
+               buf[0] = '\0';
+
+       if (errstr) {
+               len = strlen(buf);
+               if (len < sizeof(buf) - 3) {
+                       evutil_snprintf(buf + len, sizeof(buf) - len, ": %s", errstr);
+               }
+       }
+
+       event_log(severity, buf);
+}
+
+static event_log_cb log_fn = NULL;
+
+void
+event_set_log_callback(event_log_cb cb)
+{
+       log_fn = cb;
+}
+
+static void
+event_log(int severity, const char *msg)
+{
+       if (log_fn)
+               log_fn(severity, msg);
+       else {
+               const char *severity_str;
+               switch (severity) {
+               case _EVENT_LOG_DEBUG:
+                       severity_str = "debug";
+                       break;
+               case _EVENT_LOG_MSG:
+                       severity_str = "msg";
+                       break;
+               case _EVENT_LOG_WARN:
+                       severity_str = "warn";
+                       break;
+               case _EVENT_LOG_ERR:
+                       severity_str = "err";
+                       break;
+               default:
+                       severity_str = "???";
+                       break;
+               }
+               (void)fprintf(stderr, "[%s] %s\n", severity_str, msg);
+       }
+}
diff --git a/libevent/m4/acx_pthread.m4 b/libevent/m4/acx_pthread.m4
new file mode 100644 (file)
index 0000000..d2b1169
--- /dev/null
@@ -0,0 +1,279 @@
+##### http://autoconf-archive.cryp.to/acx_pthread.html
+#
+# SYNOPSIS
+#
+#   ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+#   This macro figures out how to build C programs using POSIX threads.
+#   It sets the PTHREAD_LIBS output variable to the threads library and
+#   linker flags, and the PTHREAD_CFLAGS output variable to any special
+#   C compiler flags that are needed. (The user can also force certain
+#   compiler flags/libs to be tested by setting these environment
+#   variables.)
+#
+#   Also sets PTHREAD_CC to any special C compiler that is needed for
+#   multi-threaded programs (defaults to the value of CC otherwise).
+#   (This is necessary on AIX to use the special cc_r compiler alias.)
+#
+#   NOTE: You are assumed to not only compile your program with these
+#   flags, but also link it with them as well. e.g. you should link
+#   with $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS
+#   $LIBS
+#
+#   If you are only building threads programs, you may wish to use
+#   these variables in your default LIBS, CFLAGS, and CC:
+#
+#          LIBS="$PTHREAD_LIBS $LIBS"
+#          CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+#          CC="$PTHREAD_CC"
+#
+#   In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute
+#   constant has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to
+#   that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
+#
+#   ACTION-IF-FOUND is a list of shell commands to run if a threads
+#   library is found, and ACTION-IF-NOT-FOUND is a list of commands to
+#   run it if it is not found. If ACTION-IF-FOUND is not specified, the
+#   default action will define HAVE_PTHREAD.
+#
+#   Please let the authors know if this macro fails on any platform, or
+#   if you have any other suggestions or comments. This macro was based
+#   on work by SGJ on autoconf scripts for FFTW (http://www.fftw.org/)
+#   (with help from M. Frigo), as well as ac_pthread and hb_pthread
+#   macros posted by Alejandro Forero Cuervo to the autoconf macro
+#   repository. We are also grateful for the helpful feedback of
+#   numerous users.
+#
+# LAST MODIFICATION
+#
+#   2007-07-29
+#
+# COPYLEFT
+#
+#   Copyright (c) 2007 Steven G. Johnson <stevenj@alum.mit.edu>
+#
+#   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 3 of the
+#   License, or (at your option) any later version.
+#
+#   This program is distributed in the hope that it will be useful, but
+#   WITHOUT ANY WARRANTY; without even the implied warranty of
+#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+#   General Public License for more details.
+#
+#   You should have received a copy of the GNU General Public License
+#   along with this program. If not, see
+#   <http://www.gnu.org/licenses/>.
+#
+#   As a special exception, the respective Autoconf Macro's copyright
+#   owner gives unlimited permission to copy, distribute and modify the
+#   configure scripts that are the output of Autoconf when processing
+#   the Macro. You need not follow the terms of the GNU General Public
+#   License when using or distributing such scripts, even though
+#   portions of the text of the Macro appear in them. The GNU General
+#   Public License (GPL) does govern all other use of the material that
+#   constitutes the Autoconf Macro.
+#
+#   This special exception to the GPL applies to versions of the
+#   Autoconf Macro released by the Autoconf Macro Archive. When you
+#   make and distribute a modified version of the Autoconf Macro, you
+#   may extend this special exception to the GPL to apply to your
+#   modified version as well.
+
+AC_DEFUN([ACX_PTHREAD], [
+AC_REQUIRE([AC_CANONICAL_HOST])
+AC_LANG_SAVE
+AC_LANG_C
+acx_pthread_ok=no
+
+# We used to check for pthread.h first, but this fails if pthread.h
+# requires special compiler flags (e.g. on True64 or Sequent).
+# It gets checked for in the link test anyway.
+
+# First of all, check if the user has set any of the PTHREAD_LIBS,
+# etcetera environment variables, and if threads linking works using
+# them:
+if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
+        save_CFLAGS="$CFLAGS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+        save_LIBS="$LIBS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+        AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
+        AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes)
+        AC_MSG_RESULT($acx_pthread_ok)
+        if test x"$acx_pthread_ok" = xno; then
+                PTHREAD_LIBS=""
+                PTHREAD_CFLAGS=""
+        fi
+        LIBS="$save_LIBS"
+        CFLAGS="$save_CFLAGS"
+fi
+
+# We must check for the threads library under a number of different
+# names; the ordering is very important because some systems
+# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
+# libraries is broken (non-POSIX).
+
+# Create a list of thread flags to try.  Items starting with a "-" are
+# C compiler flags, and other items are library names, except for "none"
+# which indicates that we try without any flags at all, and "pthread-config"
+# which is a program returning the flags for the Pth emulation library.
+
+acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
+
+# The ordering *is* (sometimes) important.  Some notes on the
+# individual items follow:
+
+# pthreads: AIX (must check this before -lpthread)
+# none: in case threads are in libc; should be tried before -Kthread and
+#       other compiler flags to prevent continual compiler warnings
+# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
+# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
+# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
+# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
+# -pthreads: Solaris/gcc
+# -mthreads: Mingw32/gcc, Lynx/gcc
+# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
+#      doesn't hurt to check since this sometimes defines pthreads too;
+#      also defines -D_REENTRANT)
+#      ... -mt is also the pthreads flag for HP/aCC
+# pthread: Linux, etcetera
+# --thread-safe: KAI C++
+# pthread-config: use pthread-config program (for GNU Pth library)
+
+case "${host_cpu}-${host_os}" in
+        *solaris*)
+
+        # On Solaris (at least, for some versions), libc contains stubbed
+        # (non-functional) versions of the pthreads routines, so link-based
+        # tests will erroneously succeed.  (We need to link with -pthreads/-mt/
+        # -lpthread.)  (The stubs are missing pthread_cleanup_push, or rather
+        # a function called by this macro, so we could check for that, but
+        # who knows whether they'll stub that too in a future libc.)  So,
+        # we'll just look for -pthreads and -lpthread first:
+
+        acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags"
+        ;;
+esac
+
+if test x"$acx_pthread_ok" = xno; then
+for flag in $acx_pthread_flags; do
+
+        case $flag in
+                none)
+                AC_MSG_CHECKING([whether pthreads work without any flags])
+                ;;
+
+                -*)
+                AC_MSG_CHECKING([whether pthreads work with $flag])
+                PTHREAD_CFLAGS="$flag"
+                ;;
+
+               pthread-config)
+               AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no)
+               if test x"$acx_pthread_config" = xno; then continue; fi
+               PTHREAD_CFLAGS="`pthread-config --cflags`"
+               PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
+               ;;
+
+                *)
+                AC_MSG_CHECKING([for the pthreads library -l$flag])
+                PTHREAD_LIBS="-l$flag"
+                ;;
+        esac
+
+        save_LIBS="$LIBS"
+        save_CFLAGS="$CFLAGS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+
+        # Check for various functions.  We must include pthread.h,
+        # since some functions may be macros.  (On the Sequent, we
+        # need a special flag -Kthread to make this header compile.)
+        # We check for pthread_join because it is in -lpthread on IRIX
+        # while pthread_create is in libc.  We check for pthread_attr_init
+        # due to DEC craziness with -lpthreads.  We check for
+        # pthread_cleanup_push because it is one of the few pthread
+        # functions on Solaris that doesn't have a non-functional libc stub.
+        # We try pthread_create on general principles.
+        AC_TRY_LINK([#include <pthread.h>],
+                    [pthread_t th; pthread_join(th, 0);
+                     pthread_attr_init(0); pthread_cleanup_push(0, 0);
+                     pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
+                    [acx_pthread_ok=yes])
+
+        LIBS="$save_LIBS"
+        CFLAGS="$save_CFLAGS"
+
+        AC_MSG_RESULT($acx_pthread_ok)
+        if test "x$acx_pthread_ok" = xyes; then
+                break;
+        fi
+
+        PTHREAD_LIBS=""
+        PTHREAD_CFLAGS=""
+done
+fi
+
+# Various other checks:
+if test "x$acx_pthread_ok" = xyes; then
+        save_LIBS="$LIBS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+        save_CFLAGS="$CFLAGS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+
+        # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
+       AC_MSG_CHECKING([for joinable pthread attribute])
+       attr_name=unknown
+       for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
+           AC_TRY_LINK([#include <pthread.h>], [int attr=$attr; return attr;],
+                        [attr_name=$attr; break])
+       done
+        AC_MSG_RESULT($attr_name)
+        if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
+            AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
+                               [Define to necessary symbol if this constant
+                                uses a non-standard name on your system.])
+        fi
+
+        AC_MSG_CHECKING([if more special flags are required for pthreads])
+        flag=no
+        case "${host_cpu}-${host_os}" in
+            *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";;
+            *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";;
+        esac
+        AC_MSG_RESULT(${flag})
+        if test "x$flag" != xno; then
+            PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
+        fi
+
+        LIBS="$save_LIBS"
+        CFLAGS="$save_CFLAGS"
+
+        # More AIX lossage: must compile with xlc_r or cc_r
+       if test x"$GCC" != xyes; then
+          AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC})
+        else
+          PTHREAD_CC=$CC
+       fi
+else
+        PTHREAD_CC="$CC"
+fi
+
+AC_SUBST(PTHREAD_LIBS)
+AC_SUBST(PTHREAD_CFLAGS)
+AC_SUBST(PTHREAD_CC)
+
+# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
+if test x"$acx_pthread_ok" = xyes; then
+        ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1])
+        :
+else
+        acx_pthread_ok=no
+        $2
+fi
+AC_LANG_RESTORE
+])dnl ACX_PTHREAD
diff --git a/libevent/minheap-internal.h b/libevent/minheap-internal.h
new file mode 100644 (file)
index 0000000..6d8e80a
--- /dev/null
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _MIN_HEAP_H_
+#define _MIN_HEAP_H_
+
+#include "event2/event-config.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/util.h"
+#include "util-internal.h"
+#include "mm-internal.h"
+
+typedef struct min_heap
+{
+       struct event** p;
+       unsigned n, a;
+} min_heap_t;
+
+static inline void          min_heap_ctor(min_heap_t* s);
+static inline void          min_heap_dtor(min_heap_t* s);
+static inline void          min_heap_elem_init(struct event* e);
+static inline int           min_heap_elt_is_top(const struct event *e);
+static inline int           min_heap_elem_greater(struct event *a, struct event *b);
+static inline int           min_heap_empty(min_heap_t* s);
+static inline unsigned      min_heap_size(min_heap_t* s);
+static inline struct event*  min_heap_top(min_heap_t* s);
+static inline int           min_heap_reserve(min_heap_t* s, unsigned n);
+static inline int           min_heap_push(min_heap_t* s, struct event* e);
+static inline struct event*  min_heap_pop(min_heap_t* s);
+static inline int           min_heap_erase(min_heap_t* s, struct event* e);
+static inline void          min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e);
+static inline void          min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e);
+
+int min_heap_elem_greater(struct event *a, struct event *b)
+{
+       return evutil_timercmp(&a->ev_timeout, &b->ev_timeout, >);
+}
+
+void min_heap_ctor(min_heap_t* s) { s->p = 0; s->n = 0; s->a = 0; }
+void min_heap_dtor(min_heap_t* s) { if (s->p) mm_free(s->p); }
+void min_heap_elem_init(struct event* e) { e->ev_timeout_pos.min_heap_idx = -1; }
+int min_heap_empty(min_heap_t* s) { return 0u == s->n; }
+unsigned min_heap_size(min_heap_t* s) { return s->n; }
+struct event* min_heap_top(min_heap_t* s) { return s->n ? *s->p : 0; }
+
+int min_heap_push(min_heap_t* s, struct event* e)
+{
+       if (min_heap_reserve(s, s->n + 1))
+               return -1;
+       min_heap_shift_up_(s, s->n++, e);
+       return 0;
+}
+
+struct event* min_heap_pop(min_heap_t* s)
+{
+       if (s->n)
+       {
+               struct event* e = *s->p;
+               min_heap_shift_down_(s, 0u, s->p[--s->n]);
+               e->ev_timeout_pos.min_heap_idx = -1;
+               return e;
+       }
+       return 0;
+}
+
+int min_heap_elt_is_top(const struct event *e)
+{
+       return e->ev_timeout_pos.min_heap_idx == 0;
+}
+
+int min_heap_erase(min_heap_t* s, struct event* e)
+{
+       if (-1 != e->ev_timeout_pos.min_heap_idx)
+       {
+               struct event *last = s->p[--s->n];
+               unsigned parent = (e->ev_timeout_pos.min_heap_idx - 1) / 2;
+               /* we replace e with the last element in the heap.  We might need to
+                  shift it upward if it is less than its parent, or downward if it is
+                  greater than one or both its children. Since the children are known
+                  to be less than the parent, it can't need to shift both up and
+                  down. */
+               if (e->ev_timeout_pos.min_heap_idx > 0 && min_heap_elem_greater(s->p[parent], last))
+                       min_heap_shift_up_(s, e->ev_timeout_pos.min_heap_idx, last);
+               else
+                       min_heap_shift_down_(s, e->ev_timeout_pos.min_heap_idx, last);
+               e->ev_timeout_pos.min_heap_idx = -1;
+               return 0;
+       }
+       return -1;
+}
+
+int min_heap_reserve(min_heap_t* s, unsigned n)
+{
+       if (s->a < n)
+       {
+               struct event** p;
+               unsigned a = s->a ? s->a * 2 : 8;
+               if (a < n)
+                       a = n;
+               if (!(p = (struct event**)mm_realloc(s->p, a * sizeof *p)))
+                       return -1;
+               s->p = p;
+               s->a = a;
+       }
+       return 0;
+}
+
+void min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e)
+{
+    unsigned parent = (hole_index - 1) / 2;
+    while (hole_index && min_heap_elem_greater(s->p[parent], e))
+    {
+       (s->p[hole_index] = s->p[parent])->ev_timeout_pos.min_heap_idx = hole_index;
+       hole_index = parent;
+       parent = (hole_index - 1) / 2;
+    }
+    (s->p[hole_index] = e)->ev_timeout_pos.min_heap_idx = hole_index;
+}
+
+void min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e)
+{
+    unsigned min_child = 2 * (hole_index + 1);
+    while (min_child <= s->n)
+       {
+       min_child -= min_child == s->n || min_heap_elem_greater(s->p[min_child], s->p[min_child - 1]);
+       if (!(min_heap_elem_greater(e, s->p[min_child])))
+           break;
+       (s->p[hole_index] = s->p[min_child])->ev_timeout_pos.min_heap_idx = hole_index;
+       hole_index = min_child;
+       min_child = 2 * (hole_index + 1);
+       }
+    (s->p[hole_index] = e)->ev_timeout_pos.min_heap_idx = hole_index;
+}
+
+#endif /* _MIN_HEAP_H_ */
diff --git a/libevent/mm-internal.h b/libevent/mm-internal.h
new file mode 100644 (file)
index 0000000..b375155
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT_MM_INTERNAL_H
+#define _EVENT_MM_INTERNAL_H
+
+#include <sys/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef _EVENT_DISABLE_MM_REPLACEMENT
+/* Internal use only: Memory allocation functions. We give them nice short
+ * mm_names for our own use, but make sure that the symbols have longer names
+ * so they don't conflict with other libraries (like, say, libmm). */
+void *event_mm_malloc_(size_t sz);
+void *event_mm_calloc_(size_t count, size_t size);
+char *event_mm_strdup_(const char *s);
+void *event_mm_realloc_(void *p, size_t sz);
+void event_mm_free_(void *p);
+#define mm_malloc(sz) event_mm_malloc_(sz)
+#define mm_calloc(count, size) event_mm_calloc_((count), (size))
+#define mm_strdup(s) event_mm_strdup_(s)
+#define mm_realloc(p, sz) event_mm_realloc_((p), (sz))
+#define mm_free(p) event_mm_free_(p)
+#else
+#define mm_malloc(sz) malloc(sz)
+#define mm_calloc(n, sz) calloc((n), (sz))
+#define mm_strdup(s) strdup(s)
+#define mm_realloc(p, sz) realloc((p), (sz))
+#define mm_free(p) free(p)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libevent/poll.c b/libevent/poll.c
new file mode 100644 (file)
index 0000000..04d311b
--- /dev/null
@@ -0,0 +1,333 @@
+/*     $OpenBSD: poll.c,v 1.2 2002/06/25 15:50:15 mickey Exp $ */
+
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#include <sys/types.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <poll.h>
+#include <signal.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "event-internal.h"
+#include "evsignal-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+
+struct pollidx {
+       int idxplus1;
+};
+
+struct pollop {
+       int event_count;                /* Highest number alloc */
+       int nfds;                       /* Highest number used */
+       int realloc_copy;               /* True iff we must realloc
+                                        * event_set_copy */
+       struct pollfd *event_set;
+       struct pollfd *event_set_copy;
+};
+
+static void *poll_init(struct event_base *);
+static int poll_add(struct event_base *, int, short old, short events, void *_idx);
+static int poll_del(struct event_base *, int, short old, short events, void *_idx);
+static int poll_dispatch(struct event_base *, struct timeval *);
+static void poll_dealloc(struct event_base *);
+
+const struct eventop pollops = {
+       "poll",
+       poll_init,
+       poll_add,
+       poll_del,
+       poll_dispatch,
+       poll_dealloc,
+       0, /* doesn't need_reinit */
+       EV_FEATURE_FDS,
+       sizeof(struct pollidx),
+};
+
+static void *
+poll_init(struct event_base *base)
+{
+       struct pollop *pollop;
+
+       if (!(pollop = mm_calloc(1, sizeof(struct pollop))))
+               return (NULL);
+
+       evsig_init(base);
+
+       return (pollop);
+}
+
+#ifdef CHECK_INVARIANTS
+static void
+poll_check_ok(struct pollop *pop)
+{
+       int i, idx;
+       struct event *ev;
+
+       for (i = 0; i < pop->fd_count; ++i) {
+               idx = pop->idxplus1_by_fd[i]-1;
+               if (idx < 0)
+                       continue;
+               EVUTIL_ASSERT(pop->event_set[idx].fd == i);
+       }
+       for (i = 0; i < pop->nfds; ++i) {
+               struct pollfd *pfd = &pop->event_set[i];
+               EVUTIL_ASSERT(pop->idxplus1_by_fd[pfd->fd] == i+1);
+       }
+}
+#else
+#define poll_check_ok(pop)
+#endif
+
+static int
+poll_dispatch(struct event_base *base, struct timeval *tv)
+{
+       int res, i, j, nfds;
+       long msec = -1;
+       struct pollop *pop = base->evbase;
+       struct pollfd *event_set;
+
+       poll_check_ok(pop);
+
+       nfds = pop->nfds;
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       if (base->th_base_lock) {
+               /* If we're using this backend in a multithreaded setting,
+                * then we need to work on a copy of event_set, so that we can
+                * let other threads modify the main event_set while we're
+                * polling. If we're not multithreaded, then we'll skip the
+                * copy step here to save memory and time. */
+               if (pop->realloc_copy) {
+                       struct pollfd *tmp = mm_realloc(pop->event_set_copy,
+                           pop->event_count * sizeof(struct pollfd));
+                       if (tmp == NULL) {
+                               event_warn("realloc");
+                               return -1;
+                       }
+                       pop->event_set_copy = tmp;
+                       pop->realloc_copy = 0;
+               }
+               memcpy(pop->event_set_copy, pop->event_set,
+                   sizeof(struct pollfd)*nfds);
+               event_set = pop->event_set_copy;
+       } else {
+               event_set = pop->event_set;
+       }
+#else
+       event_set = pop->event_set;
+#endif
+
+       if (tv != NULL) {
+               msec = evutil_tv_to_msec(tv);
+               if (msec < 0 || msec > INT_MAX)
+                       msec = INT_MAX;
+       }
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+       res = poll(event_set, nfds, msec);
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       if (res == -1) {
+               if (errno != EINTR) {
+                       event_warn("poll");
+                       return (-1);
+               }
+
+               return (0);
+       }
+
+       event_debug(("%s: poll reports %d", __func__, res));
+
+       if (res == 0 || nfds == 0)
+               return (0);
+
+       i = random() % nfds;
+       for (j = 0; j < nfds; j++) {
+               int what;
+               if (++i == nfds)
+                       i = 0;
+               what = event_set[i].revents;
+               if (!what)
+                       continue;
+
+               res = 0;
+
+               /* If the file gets closed notify */
+               if (what & (POLLHUP|POLLERR))
+                       what |= POLLIN|POLLOUT;
+               if (what & POLLIN)
+                       res |= EV_READ;
+               if (what & POLLOUT)
+                       res |= EV_WRITE;
+               if (res == 0)
+                       continue;
+
+               evmap_io_active(base, event_set[i].fd, res);
+       }
+
+       return (0);
+}
+
+static int
+poll_add(struct event_base *base, int fd, short old, short events, void *_idx)
+{
+       struct pollop *pop = base->evbase;
+       struct pollfd *pfd = NULL;
+       struct pollidx *idx = _idx;
+       int i;
+
+       EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
+       if (!(events & (EV_READ|EV_WRITE)))
+               return (0);
+
+       poll_check_ok(pop);
+       if (pop->nfds + 1 >= pop->event_count) {
+               struct pollfd *tmp_event_set;
+               int tmp_event_count;
+
+               if (pop->event_count < 32)
+                       tmp_event_count = 32;
+               else
+                       tmp_event_count = pop->event_count * 2;
+
+               /* We need more file descriptors */
+               tmp_event_set = mm_realloc(pop->event_set,
+                                tmp_event_count * sizeof(struct pollfd));
+               if (tmp_event_set == NULL) {
+                       event_warn("realloc");
+                       return (-1);
+               }
+               pop->event_set = tmp_event_set;
+
+               pop->event_count = tmp_event_count;
+               pop->realloc_copy = 1;
+       }
+
+       i = idx->idxplus1 - 1;
+
+       if (i >= 0) {
+               pfd = &pop->event_set[i];
+       } else {
+               i = pop->nfds++;
+               pfd = &pop->event_set[i];
+               pfd->events = 0;
+               pfd->fd = fd;
+               idx->idxplus1 = i + 1;
+       }
+
+       pfd->revents = 0;
+       if (events & EV_WRITE)
+               pfd->events |= POLLOUT;
+       if (events & EV_READ)
+               pfd->events |= POLLIN;
+       poll_check_ok(pop);
+
+       return (0);
+}
+
+/*
+ * Nothing to be done here.
+ */
+
+static int
+poll_del(struct event_base *base, int fd, short old, short events, void *_idx)
+{
+       struct pollop *pop = base->evbase;
+       struct pollfd *pfd = NULL;
+       struct pollidx *idx = _idx;
+       int i;
+
+       EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
+       if (!(events & (EV_READ|EV_WRITE)))
+               return (0);
+
+       poll_check_ok(pop);
+       i = idx->idxplus1 - 1;
+       if (i < 0)
+               return (-1);
+
+       /* Do we still want to read or write? */
+       pfd = &pop->event_set[i];
+       if (events & EV_READ)
+               pfd->events &= ~POLLIN;
+       if (events & EV_WRITE)
+               pfd->events &= ~POLLOUT;
+       poll_check_ok(pop);
+       if (pfd->events)
+               /* Another event cares about that fd. */
+               return (0);
+
+       /* Okay, so we aren't interested in that fd anymore. */
+       idx->idxplus1 = 0;
+
+       --pop->nfds;
+       if (i != pop->nfds) {
+               /*
+                * Shift the last pollfd down into the now-unoccupied
+                * position.
+                */
+               memcpy(&pop->event_set[i], &pop->event_set[pop->nfds],
+                      sizeof(struct pollfd));
+               idx = evmap_io_get_fdinfo(&base->io, pop->event_set[i].fd);
+               EVUTIL_ASSERT(idx);
+               EVUTIL_ASSERT(idx->idxplus1 == pop->nfds + 1);
+               idx->idxplus1 = i + 1;
+       }
+
+       poll_check_ok(pop);
+       return (0);
+}
+
+static void
+poll_dealloc(struct event_base *base)
+{
+       struct pollop *pop = base->evbase;
+
+       evsig_dealloc(base);
+       if (pop->event_set)
+               mm_free(pop->event_set);
+       if (pop->event_set_copy)
+               mm_free(pop->event_set_copy);
+
+       memset(pop, 0, sizeof(struct pollop));
+       mm_free(pop);
+}
diff --git a/libevent/ratelim-internal.h b/libevent/ratelim-internal.h
new file mode 100644 (file)
index 0000000..4e3f8c4
--- /dev/null
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _RATELIM_INTERNAL_H_
+#define _RATELIM_INTERNAL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/util.h"
+
+/** A token bucket is an internal structure that tracks how many bytes we are
+ * currently willing to read or write on a given bufferevent or group of
+ * bufferevents */
+struct ev_token_bucket {
+       /** How many bytes are we willing to read or write right now? These
+        * values are signed so that we can do "defecit spending" */
+       ev_ssize_t read_limit, write_limit;
+       /** When was this bucket last updated?  Measured in abstract 'ticks'
+        * relative to the token bucket configuration. */
+       ev_uint32_t last_updated;
+};
+
+/** Configuration info for a token bucket or set of token buckets. */
+struct ev_token_bucket_cfg {
+       /** How many bytes are we willing to read on average per tick? */
+       size_t read_rate;
+       /** How many bytes are we willing to read at most in any one tick? */
+       size_t read_maximum;
+       /** How many bytes are we willing to write on average per tick? */
+       size_t write_rate;
+       /** How many bytes are we willing to write at most in any one tick? */
+       size_t write_maximum;
+
+       /* How long is a tick?  Note that fractions of a millisecond are
+        * ignored. */
+       struct timeval tick_timeout;
+
+       /* How long is a tick, in milliseconds?  Derived from tick_timeout. */
+       unsigned msec_per_tick;
+};
+
+/** The current tick is 'current_tick': add bytes to 'bucket' as specified in
+ * 'cfg'. */
+int ev_token_bucket_update(struct ev_token_bucket *bucket,
+    const struct ev_token_bucket_cfg *cfg,
+    ev_uint32_t current_tick);
+
+/** In which tick does 'tv' fall according to 'cfg'?  Note that ticks can
+ * overflow easily; your code needs to handle this. */
+ev_uint32_t ev_token_bucket_get_tick(const struct timeval *tv,
+    const struct ev_token_bucket_cfg *cfg);
+
+/** Adjust 'bucket' to respect 'cfg', and note that it was last updated in
+ * 'current_tick'.  If 'reinitialize' is true, we are changing the
+ * configuration of 'bucket'; otherwise, we are setting it up for the first
+ * time.
+ */
+int ev_token_bucket_init(struct ev_token_bucket *bucket,
+    const struct ev_token_bucket_cfg *cfg,
+    ev_uint32_t current_tick,
+    int reinitialize);
+
+int bufferevent_remove_from_rate_limit_group_internal(struct bufferevent *bev,
+    int unsuspend);
+
+/** Decrease the read limit of 'b' by 'n' bytes */
+#define ev_token_bucket_decrement_read(b,n)    \
+       do {                                    \
+               (b)->read_limit -= (n);         \
+       } while (0)
+/** Decrease the write limit of 'b' by 'n' bytes */
+#define ev_token_bucket_decrement_write(b,n)   \
+       do {                                    \
+               (b)->write_limit -= (n);        \
+       } while (0)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libevent/sample/Makefile.am b/libevent/sample/Makefile.am
new file mode 100644 (file)
index 0000000..c926f4e
--- /dev/null
@@ -0,0 +1,29 @@
+# sample/Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+AUTOMAKE_OPTIONS = foreign no-dependencies
+
+LDADD = $(LIBEVENT_GC_SECTIONS) ../libevent.la
+AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/compat -I$(top_srcdir)/include -I../include
+
+noinst_PROGRAMS = event-test time-test signal-test dns-example hello-world http-server
+
+event_test_SOURCES = event-test.c
+time_test_SOURCES = time-test.c
+signal_test_SOURCES = signal-test.c
+dns_example_SOURCES = dns-example.c
+hello_world_SOURCES = hello-world.c
+http_server_SOURCES = http-server.c
+
+if OPENSSL
+noinst_PROGRAMS += le-proxy
+le_proxy_SOURCES = le-proxy.c
+le_proxy_LDADD = $(LDADD) ../libevent_openssl.la -lssl -lcrypto ${OPENSSL_LIBADD}
+endif
+
+verify:
+
+DISTCLEANFILES = *~
diff --git a/libevent/sample/dns-example.c b/libevent/sample/dns-example.c
new file mode 100644 (file)
index 0000000..f97a0c6
--- /dev/null
@@ -0,0 +1,239 @@
+/*
+  This example code shows how to use the high-level, low-level, and
+  server-level interfaces of evdns.
+
+  XXX It's pretty ugly and should probably be cleaned up.
+ */
+
+#include <event2/event-config.h>
+
+/* Compatibility for possible missing IPv6 declarations */
+#include "../ipv6-internal.h"
+
+#include <sys/types.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#endif
+
+#include <event2/event.h>
+#include <event2/dns.h>
+#include <event2/dns_struct.h>
+#include <event2/util.h>
+
+#ifdef _EVENT_HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define u32 ev_uint32_t
+#define u8 ev_uint8_t
+
+static const char *
+debug_ntoa(u32 address)
+{
+       static char buf[32];
+       u32 a = ntohl(address);
+       evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
+                                       (int)(u8)((a>>24)&0xff),
+                                       (int)(u8)((a>>16)&0xff),
+                                       (int)(u8)((a>>8 )&0xff),
+                                       (int)(u8)((a    )&0xff));
+       return buf;
+}
+
+static void
+main_callback(int result, char type, int count, int ttl,
+                         void *addrs, void *orig) {
+       char *n = (char*)orig;
+       int i;
+       for (i = 0; i < count; ++i) {
+               if (type == DNS_IPv4_A) {
+                       printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
+               } else if (type == DNS_PTR) {
+                       printf("%s: %s\n", n, ((char**)addrs)[i]);
+               }
+       }
+       if (!count) {
+               printf("%s: No answer (%d)\n", n, result);
+       }
+       fflush(stdout);
+}
+
+static void
+gai_callback(int err, struct evutil_addrinfo *ai, void *arg)
+{
+       const char *name = arg;
+       int i;
+       if (err) {
+               printf("%s: %s\n", name, evutil_gai_strerror(err));
+       }
+       if (ai && ai->ai_canonname)
+               printf("    %s ==> %s\n", name, ai->ai_canonname);
+       for (i=0; ai; ai = ai->ai_next, ++i) {
+               char buf[128];
+               if (ai->ai_family == PF_INET) {
+                       struct sockaddr_in *sin =
+                           (struct sockaddr_in*)ai->ai_addr;
+                       evutil_inet_ntop(AF_INET, &sin->sin_addr, buf,
+                           sizeof(buf));
+                       printf("[%d] %s: %s\n",i,name,buf);
+               } else {
+                       struct sockaddr_in6 *sin6 =
+                           (struct sockaddr_in6*)ai->ai_addr;
+                       evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,
+                           sizeof(buf));
+                       printf("[%d] %s: %s\n",i,name,buf);
+               }
+       }
+}
+
+static void
+evdns_server_callback(struct evdns_server_request *req, void *data)
+{
+       int i, r;
+       (void)data;
+       /* dummy; give 192.168.11.11 as an answer for all A questions,
+        *      give foo.bar.example.com as an answer for all PTR questions. */
+       for (i = 0; i < req->nquestions; ++i) {
+               u32 ans = htonl(0xc0a80b0bUL);
+               if (req->questions[i]->type == EVDNS_TYPE_A &&
+                   req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
+                       printf(" -- replying for %s (A)\n", req->questions[i]->name);
+                       r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
+                                                                                 1, &ans, 10);
+                       if (r<0)
+                               printf("eeep, didn't work.\n");
+               } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
+                   req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
+                       printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
+                       r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
+                                                                                       "foo.bar.example.com", 10);
+                       if (r<0)
+                               printf("ugh, no luck");
+               } else {
+                       printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
+                                  req->questions[i]->type, req->questions[i]->dns_question_class);
+               }
+       }
+
+       r = evdns_server_request_respond(req, 0);
+       if (r<0)
+               printf("eeek, couldn't send reply.\n");
+}
+
+static int verbose = 0;
+
+static void
+logfn(int is_warn, const char *msg) {
+       if (!is_warn && !verbose)
+               return;
+       fprintf(stderr, "%s: %s\n", is_warn?"WARN":"INFO", msg);
+}
+
+int
+main(int c, char **v) {
+       int idx;
+       int reverse = 0, servertest = 0, use_getaddrinfo = 0;
+       struct event_base *event_base = NULL;
+       struct evdns_base *evdns_base = NULL;
+       if (c<2) {
+               fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
+               fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
+               return 1;
+       }
+       idx = 1;
+       while (idx < c && v[idx][0] == '-') {
+               if (!strcmp(v[idx], "-x"))
+                       reverse = 1;
+               else if (!strcmp(v[idx], "-v"))
+                       verbose = 1;
+               else if (!strcmp(v[idx], "-g"))
+                       use_getaddrinfo = 1;
+               else if (!strcmp(v[idx], "-servertest"))
+                       servertest = 1;
+               else
+                       fprintf(stderr, "Unknown option %s\n", v[idx]);
+               ++idx;
+       }
+
+#ifdef WIN32
+       {
+               WSADATA WSAData;
+               WSAStartup(0x101, &WSAData);
+       }
+#endif
+
+       event_base = event_base_new();
+       evdns_base = evdns_base_new(event_base, 0);
+       evdns_set_log_fn(logfn);
+
+       if (servertest) {
+               evutil_socket_t sock;
+               struct sockaddr_in my_addr;
+               sock = socket(PF_INET, SOCK_DGRAM, 0);
+               if (sock == -1) {
+                       perror("socket");
+                       exit(1);
+               }
+               evutil_make_socket_nonblocking(sock);
+               my_addr.sin_family = AF_INET;
+               my_addr.sin_port = htons(10053);
+               my_addr.sin_addr.s_addr = INADDR_ANY;
+               if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
+                       perror("bind");
+                       exit(1);
+               }
+               evdns_add_server_port_with_base(event_base, sock, 0, evdns_server_callback, NULL);
+       }
+       if (idx < c) {
+               int res;
+#ifdef WIN32
+               res = evdns_base_config_windows_nameservers(evdns_base);
+#else
+               res = evdns_base_resolv_conf_parse(evdns_base, DNS_OPTION_NAMESERVERS,
+                   "/etc/resolv.conf");
+#endif
+               if (res < 0) {
+                       fprintf(stderr, "Couldn't configure nameservers");
+                       return 1;
+               }
+       }
+
+       printf("EVUTIL_AI_CANONNAME in example = %d\n", EVUTIL_AI_CANONNAME);
+       for (; idx < c; ++idx) {
+               if (reverse) {
+                       struct in_addr addr;
+                       if (evutil_inet_pton(AF_INET, v[idx], &addr)!=1) {
+                               fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
+                               continue;
+                       }
+                       fprintf(stderr, "resolving %s...\n",v[idx]);
+                       evdns_base_resolve_reverse(evdns_base, &addr, 0, main_callback, v[idx]);
+               } else if (use_getaddrinfo) {
+                       struct evutil_addrinfo hints;
+                       memset(&hints, 0, sizeof(hints));
+                       hints.ai_family = PF_UNSPEC;
+                       hints.ai_protocol = IPPROTO_TCP;
+                       hints.ai_flags = EVUTIL_AI_CANONNAME;
+                       fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
+                       evdns_getaddrinfo(evdns_base, v[idx], NULL, &hints,
+                           gai_callback, v[idx]);
+               } else {
+                       fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
+                       evdns_base_resolve_ipv4(evdns_base, v[idx], 0, main_callback, v[idx]);
+               }
+       }
+       fflush(stdout);
+       event_base_dispatch(event_base);
+       return 0;
+}
+
diff --git a/libevent/sample/event-test.c b/libevent/sample/event-test.c
new file mode 100644 (file)
index 0000000..e4d7a42
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * XXX This sample code was once meant to show how to use the basic Libevent
+ * interfaces, but it never worked on non-Unix platforms, and some of the
+ * interfaces have changed since it was first written.  It should probably
+ * be removed or replaced with something better.
+ *
+ * Compile with:
+ * cc -I/usr/local/include -o event-test event-test.c -L/usr/local/lib -levent
+ */
+
+#include <event2/event-config.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifndef WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#include <sys/time.h>
+#else
+#include <winsock2.h>
+#include <windows.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event.h>
+
+static void
+fifo_read(int fd, short event, void *arg)
+{
+       char buf[255];
+       int len;
+       struct event *ev = arg;
+#ifdef WIN32
+       DWORD dwBytesRead;
+#endif
+
+       /* Reschedule this event */
+       event_add(ev, NULL);
+
+       fprintf(stderr, "fifo_read called with fd: %d, event: %d, arg: %p\n",
+               fd, event, arg);
+#ifdef WIN32
+       len = ReadFile((HANDLE)fd, buf, sizeof(buf) - 1, &dwBytesRead, NULL);
+
+       /* Check for end of file. */
+       if (len && dwBytesRead == 0) {
+               fprintf(stderr, "End Of File");
+               event_del(ev);
+               return;
+       }
+
+       buf[dwBytesRead] = '\0';
+#else
+       len = read(fd, buf, sizeof(buf) - 1);
+
+       if (len == -1) {
+               perror("read");
+               return;
+       } else if (len == 0) {
+               fprintf(stderr, "Connection closed\n");
+               return;
+       }
+
+       buf[len] = '\0';
+#endif
+       fprintf(stdout, "Read: %s\n", buf);
+}
+
+int
+main(int argc, char **argv)
+{
+       struct event evfifo;
+#ifdef WIN32
+       HANDLE socket;
+       /* Open a file. */
+       socket = CreateFileA("test.txt",        /* open File */
+                       GENERIC_READ,           /* open for reading */
+                       0,                      /* do not share */
+                       NULL,                   /* no security */
+                       OPEN_EXISTING,          /* existing file only */
+                       FILE_ATTRIBUTE_NORMAL,  /* normal file */
+                       NULL);                  /* no attr. template */
+
+       if (socket == INVALID_HANDLE_VALUE)
+               return 1;
+
+#else
+       struct stat st;
+       const char *fifo = "event.fifo";
+       int socket;
+
+       if (lstat(fifo, &st) == 0) {
+               if ((st.st_mode & S_IFMT) == S_IFREG) {
+                       errno = EEXIST;
+                       perror("lstat");
+                       exit(1);
+               }
+       }
+
+       unlink(fifo);
+       if (mkfifo(fifo, 0600) == -1) {
+               perror("mkfifo");
+               exit(1);
+       }
+
+       /* Linux pipes are broken, we need O_RDWR instead of O_RDONLY */
+#ifdef __linux
+       socket = open(fifo, O_RDWR | O_NONBLOCK, 0);
+#else
+       socket = open(fifo, O_RDONLY | O_NONBLOCK, 0);
+#endif
+
+       if (socket == -1) {
+               perror("open");
+               exit(1);
+       }
+
+       fprintf(stderr, "Write data to %s\n", fifo);
+#endif
+       /* Initalize the event library */
+       event_init();
+
+       /* Initalize one event */
+#ifdef WIN32
+       event_set(&evfifo, (int)socket, EV_READ, fifo_read, &evfifo);
+#else
+       event_set(&evfifo, socket, EV_READ, fifo_read, &evfifo);
+#endif
+
+       /* Add it to the active events, without a timeout */
+       event_add(&evfifo, NULL);
+
+       event_dispatch();
+#ifdef WIN32
+       CloseHandle(socket);
+#endif
+       return (0);
+}
+
diff --git a/libevent/sample/hello-world.c b/libevent/sample/hello-world.c
new file mode 100644 (file)
index 0000000..d40af52
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+  This exmple program provides a trivial server program that listens for TCP
+  connections on port 9995.  When they arrive, it writes a short message to
+  each client connection, and closes each connection once it is flushed.
+
+  Where possible, it exits cleanly in response to a SIGINT (ctrl-c).
+*/
+
+
+#include <string.h>
+#include <errno.h>
+#include <stdio.h>
+#include <signal.h>
+#ifndef WIN32
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+#  include <arpa/inet.h>
+# endif
+#include <sys/socket.h>
+#endif
+
+#include <event2/bufferevent.h>
+#include <event2/buffer.h>
+#include <event2/listener.h>
+#include <event2/util.h>
+#include <event2/event.h>
+
+static const char MESSAGE[] = "Hello, World!\n";
+
+static const int PORT = 9995;
+
+static void listener_cb(struct evconnlistener *, evutil_socket_t,
+    struct sockaddr *, int socklen, void *);
+static void conn_writecb(struct bufferevent *, void *);
+static void conn_eventcb(struct bufferevent *, short, void *);
+static void signal_cb(evutil_socket_t, short, void *);
+
+int
+main(int argc, char **argv)
+{
+       struct event_base *base;
+       struct evconnlistener *listener;
+       struct event *signal_event;
+
+       struct sockaddr_in sin;
+#ifdef WIN32
+       WSADATA wsa_data;
+       WSAStartup(0x0201, &wsa_data);
+#endif
+
+       base = event_base_new();
+       if (!base) {
+               fprintf(stderr, "Could not initialize libevent!\n");
+               return 1;
+       }
+
+       memset(&sin, 0, sizeof(sin));
+       sin.sin_family = AF_INET;
+       sin.sin_port = htons(PORT);
+
+       listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
+           LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
+           (struct sockaddr*)&sin,
+           sizeof(sin));
+
+       if (!listener) {
+               fprintf(stderr, "Could not create a listener!\n");
+               return 1;
+       }
+
+       signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);
+
+       if (!signal_event || event_add(signal_event, NULL)<0) {
+               fprintf(stderr, "Could not create/add a signal event!\n");
+               return 1;
+       }
+
+       event_base_dispatch(base);
+
+       evconnlistener_free(listener);
+       event_free(signal_event);
+       event_base_free(base);
+
+       printf("done\n");
+       return 0;
+}
+
+static void
+listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
+    struct sockaddr *sa, int socklen, void *user_data)
+{
+       struct event_base *base = user_data;
+       struct bufferevent *bev;
+
+       bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
+       if (!bev) {
+               fprintf(stderr, "Error constructing bufferevent!");
+               event_base_loopbreak(base);
+               return;
+       }
+       bufferevent_setcb(bev, NULL, conn_writecb, conn_eventcb, NULL);
+       bufferevent_enable(bev, EV_WRITE);
+       bufferevent_disable(bev, EV_READ);
+
+       bufferevent_write(bev, MESSAGE, strlen(MESSAGE));
+}
+
+static void
+conn_writecb(struct bufferevent *bev, void *user_data)
+{
+       struct evbuffer *output = bufferevent_get_output(bev);
+       if (evbuffer_get_length(output) == 0) {
+               printf("flushed answer\n");
+               bufferevent_free(bev);
+       }
+}
+
+static void
+conn_eventcb(struct bufferevent *bev, short events, void *user_data)
+{
+       if (events & BEV_EVENT_EOF) {
+               printf("Connection closed.\n");
+       } else if (events & BEV_EVENT_ERROR) {
+               printf("Got an error on the connection: %s\n",
+                   strerror(errno));/*XXX win32*/
+       }
+       /* None of the other events can happen here, since we haven't enabled
+        * timeouts */
+       bufferevent_free(bev);
+}
+
+static void
+signal_cb(evutil_socket_t sig, short events, void *user_data)
+{
+       struct event_base *base = user_data;
+       struct timeval delay = { 2, 0 };
+
+       printf("Caught an interrupt signal; exiting cleanly in two seconds.\n");
+
+       event_base_loopexit(base, &delay);
+}
diff --git a/libevent/sample/http-server.c b/libevent/sample/http-server.c
new file mode 100644 (file)
index 0000000..fb45579
--- /dev/null
@@ -0,0 +1,405 @@
+/*
+  A trivial static http webserver using Libevent's evhttp.
+
+  This is not the best code in the world, and it does some fairly stupid stuff
+  that you would never want to do in a production webserver. Caveat hackor!
+
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <io.h>
+#include <fcntl.h>
+#ifndef S_ISDIR
+#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
+#endif
+#else
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <dirent.h>
+#endif
+
+#include <event2/event.h>
+#include <event2/http.h>
+#include <event2/buffer.h>
+#include <event2/util.h>
+#include <event2/keyvalq_struct.h>
+
+#ifdef _EVENT_HAVE_NETINET_IN_H
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+#  include <arpa/inet.h>
+# endif
+#endif
+
+/* Compatibility for possible missing IPv6 declarations */
+#include "../util-internal.h"
+
+#ifdef WIN32
+#define stat _stat
+#define fstat _fstat
+#define open _open
+#define close _close
+#define O_RDONLY _O_RDONLY
+#endif
+
+char uri_root[512];
+
+static const struct table_entry {
+       const char *extension;
+       const char *content_type;
+} content_type_table[] = {
+       { "txt", "text/plain" },
+       { "c", "text/plain" },
+       { "h", "text/plain" },
+       { "html", "text/html" },
+       { "htm", "text/htm" },
+       { "css", "text/css" },
+       { "gif", "image/gif" },
+       { "jpg", "image/jpeg" },
+       { "jpeg", "image/jpeg" },
+       { "png", "image/png" },
+       { "pdf", "application/pdf" },
+       { "ps", "application/postsript" },
+       { NULL, NULL },
+};
+
+/* Try to guess a good content-type for 'path' */
+static const char *
+guess_content_type(const char *path)
+{
+       const char *last_period, *extension;
+       const struct table_entry *ent;
+       last_period = strrchr(path, '.');
+       if (!last_period || strchr(last_period, '/'))
+               goto not_found; /* no exension */
+       extension = last_period + 1;
+       for (ent = &content_type_table[0]; ent->extension; ++ent) {
+               if (!evutil_ascii_strcasecmp(ent->extension, extension))
+                       return ent->content_type;
+       }
+
+not_found:
+       return "application/misc";
+}
+
+/* Callback used for the /dump URI, and for every non-GET request:
+ * dumps all information to stdout and gives back a trivial 200 ok */
+static void
+dump_request_cb(struct evhttp_request *req, void *arg)
+{
+       const char *cmdtype;
+       struct evkeyvalq *headers;
+       struct evkeyval *header;
+       struct evbuffer *buf;
+
+       switch (evhttp_request_get_command(req)) {
+       case EVHTTP_REQ_GET: cmdtype = "GET"; break;
+       case EVHTTP_REQ_POST: cmdtype = "POST"; break;
+       case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
+       case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
+       case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
+       case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
+       case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
+       case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
+       case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
+       default: cmdtype = "unknown"; break;
+       }
+
+       printf("Received a %s request for %s\nHeaders:\n",
+           cmdtype, evhttp_request_get_uri(req));
+
+       headers = evhttp_request_get_input_headers(req);
+       for (header = headers->tqh_first; header;
+           header = header->next.tqe_next) {
+               printf("  %s: %s\n", header->key, header->value);
+       }
+
+       buf = evhttp_request_get_input_buffer(req);
+       puts("Input data: <<<");
+       while (evbuffer_get_length(buf)) {
+               int n;
+               char cbuf[128];
+               n = evbuffer_remove(buf, cbuf, sizeof(buf)-1);
+               if (n > 0)
+                       (void) fwrite(cbuf, 1, n, stdout);
+       }
+       puts(">>>");
+
+       evhttp_send_reply(req, 200, "OK", NULL);
+}
+
+/* This callback gets invoked when we get any http request that doesn't match
+ * any other callback.  Like any evhttp server callback, it has a simple job:
+ * it must eventually call evhttp_send_error() or evhttp_send_reply().
+ */
+static void
+send_document_cb(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *evb = NULL;
+       const char *docroot = arg;
+       const char *uri = evhttp_request_get_uri(req);
+       struct evhttp_uri *decoded = NULL;
+       const char *path;
+       char *decoded_path;
+       char *whole_path = NULL;
+       size_t len;
+       int fd = -1;
+       struct stat st;
+
+       if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
+               dump_request_cb(req, arg);
+               return;
+       }
+
+       printf("Got a GET request for <%s>\n",  uri);
+
+       /* Decode the URI */
+       decoded = evhttp_uri_parse(uri);
+       if (!decoded) {
+               printf("It's not a good URI. Sending BADREQUEST\n");
+               evhttp_send_error(req, HTTP_BADREQUEST, 0);
+               return;
+       }
+
+       /* Let's see what path the user asked for. */
+       path = evhttp_uri_get_path(decoded);
+       if (!path) path = "/";
+
+       /* We need to decode it, to see what path the user really wanted. */
+       decoded_path = evhttp_uridecode(path, 0, NULL);
+       if (decoded_path == NULL)
+               goto err;
+       /* Don't allow any ".."s in the path, to avoid exposing stuff outside
+        * of the docroot.  This test is both overzealous and underzealous:
+        * it forbids aceptable paths like "/this/one..here", but it doesn't
+        * do anything to prevent symlink following." */
+       if (strstr(decoded_path, ".."))
+               goto err;
+
+       len = strlen(decoded_path)+strlen(docroot)+2;
+       if (!(whole_path = malloc(len))) {
+               perror("malloc");
+               goto err;
+       }
+       evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);
+
+       if (stat(whole_path, &st)<0) {
+               goto err;
+       }
+
+       /* This holds the content we're sending. */
+       evb = evbuffer_new();
+
+       if (S_ISDIR(st.st_mode)) {
+               /* If it's a directory, read the comments and make a little
+                * index page */
+#ifdef WIN32
+               HANDLE d;
+               WIN32_FIND_DATAA ent;
+               char *pattern;
+               size_t dirlen;
+#else
+               DIR *d;
+               struct dirent *ent;
+#endif
+               const char *trailing_slash = "";
+
+               if (!strlen(path) || path[strlen(path)-1] != '/')
+                       trailing_slash = "/";
+
+#ifdef WIN32
+               dirlen = strlen(whole_path);
+               pattern = malloc(dirlen+3);
+               memcpy(pattern, whole_path, dirlen);
+               pattern[dirlen] = '\\';
+               pattern[dirlen+1] = '*';
+               pattern[dirlen+2] = '\0';
+               d = FindFirstFileA(pattern, &ent);
+               free(pattern);
+               if (d == INVALID_HANDLE_VALUE)
+                       goto err;
+#else
+               if (!(d = opendir(whole_path)))
+                       goto err;
+#endif
+
+               evbuffer_add_printf(evb, "<html>\n <head>\n"
+                   "  <title>%s</title>\n"
+                   "  <base href='%s%s%s'>\n"
+                   " </head>\n"
+                   " <body>\n"
+                   "  <h1>%s</h1>\n"
+                   "  <ul>\n",
+                   decoded_path, /* XXX html-escape this. */
+                   uri_root, path, /* XXX html-escape this? */
+                   trailing_slash,
+                   decoded_path /* XXX html-escape this */);
+#ifdef WIN32
+               do {
+                       const char *name = ent.cFileName;
+#else
+               while ((ent = readdir(d))) {
+                       const char *name = ent->d_name;
+#endif
+                       evbuffer_add_printf(evb,
+                           "    <li><a href=\"%s\">%s</a>\n",
+                           name, name);/* XXX escape this */
+#ifdef WIN32
+               } while (FindNextFileA(d, &ent));
+#else
+               }
+#endif
+               evbuffer_add_printf(evb, "</ul></body></html>\n");
+#ifdef WIN32
+               CloseHandle(d);
+#else
+               closedir(d);
+#endif
+               evhttp_add_header(evhttp_request_get_output_headers(req),
+                   "Content-Type", "text/html");
+       } else {
+               /* Otherwise it's a file; add it to the buffer to get
+                * sent via sendfile */
+               const char *type = guess_content_type(decoded_path);
+               if ((fd = open(whole_path, O_RDONLY)) < 0) {
+                       perror("open");
+                       goto err;
+               }
+
+               if (fstat(fd, &st)<0) {
+                       /* Make sure the length still matches, now that we
+                        * opened the file :/ */
+                       perror("fstat");
+                       goto err;
+               }
+               evhttp_add_header(evhttp_request_get_output_headers(req),
+                   "Content-Type", type);
+               evbuffer_add_file(evb, fd, 0, st.st_size);
+       }
+
+       evhttp_send_reply(req, 200, "OK", evb);
+       goto done;
+err:
+       evhttp_send_error(req, 404, "Document was not found");
+       if (fd>=0)
+               close(fd);
+done:
+       if (decoded)
+               evhttp_uri_free(decoded);
+       if (decoded_path)
+               free(decoded_path);
+       if (whole_path)
+               free(whole_path);
+       if (evb)
+               evbuffer_free(evb);
+}
+
+static void
+syntax(void)
+{
+       fprintf(stdout, "Syntax: http-server <docroot>\n");
+}
+
+int
+main(int argc, char **argv)
+{
+       struct event_base *base;
+       struct evhttp *http;
+       struct evhttp_bound_socket *handle;
+
+       unsigned short port = 0;
+#ifdef WIN32
+       WSADATA WSAData;
+       WSAStartup(0x101, &WSAData);
+#else
+       if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+               return (1);
+#endif
+       if (argc < 2) {
+               syntax();
+               return 1;
+       }
+
+       base = event_base_new();
+       if (!base) {
+               fprintf(stderr, "Couldn't create an event_base: exiting\n");
+               return 1;
+       }
+
+       /* Create a new evhttp object to handle requests. */
+       http = evhttp_new(base);
+       if (!http) {
+               fprintf(stderr, "couldn't create evhttp. Exiting.\n");
+               return 1;
+       }
+
+       /* The /dump URI will dump all requests to stdout and say 200 ok. */
+       evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
+
+       /* We want to accept arbitrary requests, so we need to set a "generic"
+        * cb.  We can also add callbacks for specific paths. */
+       evhttp_set_gencb(http, send_document_cb, argv[1]);
+
+       /* Now we tell the evhttp what port to listen on */
+       handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
+       if (!handle) {
+               fprintf(stderr, "couldn't bind to port %d. Exiting.\n",
+                   (int)port);
+               return 1;
+       }
+
+       {
+               /* Extract and display the address we're listening on. */
+               struct sockaddr_storage ss;
+               evutil_socket_t fd;
+               ev_socklen_t socklen = sizeof(ss);
+               char addrbuf[128];
+               void *inaddr;
+               const char *addr;
+               int got_port = -1;
+               fd = evhttp_bound_socket_get_fd(handle);
+               memset(&ss, 0, sizeof(ss));
+               if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
+                       perror("getsockname() failed");
+                       return 1;
+               }
+               if (ss.ss_family == AF_INET) {
+                       got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
+                       inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
+               } else if (ss.ss_family == AF_INET6) {
+                       got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
+                       inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
+               } else {
+                       fprintf(stderr, "Weird address family %d\n",
+                           ss.ss_family);
+                       return 1;
+               }
+               addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
+                   sizeof(addrbuf));
+               if (addr) {
+                       printf("Listening on %s:%d\n", addr, got_port);
+                       evutil_snprintf(uri_root, sizeof(uri_root),
+                           "http://%s:%d",addr,got_port);
+               } else {
+                       fprintf(stderr, "evutil_inet_ntop failed\n");
+                       return 1;
+               }
+       }
+
+       event_base_dispatch(base);
+
+       return 0;
+}
diff --git a/libevent/sample/le-proxy.c b/libevent/sample/le-proxy.c
new file mode 100644 (file)
index 0000000..446bfb5
--- /dev/null
@@ -0,0 +1,278 @@
+/*
+  This example code shows how to write an (optionally encrypting) SSL proxy
+  with Libevent's bufferevent layer.
+
+  XXX It's a little ugly and should probably be cleaned up.
+ */
+
+#include <stdio.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#endif
+
+#include <event2/bufferevent_ssl.h>
+#include <event2/bufferevent.h>
+#include <event2/buffer.h>
+#include <event2/listener.h>
+#include <event2/util.h>
+
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <openssl/rand.h>
+
+static struct event_base *base;
+static struct sockaddr_storage listen_on_addr;
+static struct sockaddr_storage connect_to_addr;
+static int connect_to_addrlen;
+static int use_wrapper = 1;
+
+static SSL_CTX *ssl_ctx = NULL;
+
+#define MAX_OUTPUT (512*1024)
+
+static void drained_writecb(struct bufferevent *bev, void *ctx);
+static void eventcb(struct bufferevent *bev, short what, void *ctx);
+
+static void
+readcb(struct bufferevent *bev, void *ctx)
+{
+       struct bufferevent *partner = ctx;
+       struct evbuffer *src, *dst;
+       size_t len;
+       src = bufferevent_get_input(bev);
+       len = evbuffer_get_length(src);
+       if (!partner) {
+               evbuffer_drain(src, len);
+               return;
+       }
+       dst = bufferevent_get_output(partner);
+       evbuffer_add_buffer(dst, src);
+
+       if (evbuffer_get_length(dst) >= MAX_OUTPUT) {
+               /* We're giving the other side data faster than it can
+                * pass it on.  Stop reading here until we have drained the
+                * other side to MAX_OUTPUT/2 bytes. */
+               bufferevent_setcb(partner, readcb, drained_writecb,
+                   eventcb, bev);
+               bufferevent_setwatermark(partner, EV_WRITE, MAX_OUTPUT/2,
+                   MAX_OUTPUT);
+               bufferevent_disable(bev, EV_READ);
+       }
+}
+
+static void
+drained_writecb(struct bufferevent *bev, void *ctx)
+{
+       struct bufferevent *partner = ctx;
+
+       /* We were choking the other side until we drained our outbuf a bit.
+        * Now it seems drained. */
+       bufferevent_setcb(bev, readcb, NULL, eventcb, partner);
+       bufferevent_setwatermark(bev, EV_WRITE, 0, 0);
+       if (partner)
+               bufferevent_enable(partner, EV_READ);
+}
+
+static void
+close_on_finished_writecb(struct bufferevent *bev, void *ctx)
+{
+       struct evbuffer *b = bufferevent_get_output(bev);
+
+       if (evbuffer_get_length(b) == 0) {
+               bufferevent_free(bev);
+       }
+}
+
+static void
+eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+       struct bufferevent *partner = ctx;
+
+       if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
+               if (what & BEV_EVENT_ERROR) {
+                       unsigned long err;
+                       while ((err = (bufferevent_get_openssl_error(bev)))) {
+                               const char *msg = (const char*)
+                                   ERR_reason_error_string(err);
+                               const char *lib = (const char*)
+                                   ERR_lib_error_string(err);
+                               const char *func = (const char*)
+                                   ERR_func_error_string(err);
+                               fprintf(stderr,
+                                   "%s in %s %s\n", msg, lib, func);
+                       }
+                       if (errno)
+                               perror("connection error");
+               }
+
+               if (partner) {
+                       /* Flush all pending data */
+                       readcb(bev, ctx);
+
+                       if (evbuffer_get_length(
+                                   bufferevent_get_output(partner))) {
+                               /* We still have to flush data from the other
+                                * side, but when that's done, close the other
+                                * side. */
+                               bufferevent_setcb(partner,
+                                   NULL, close_on_finished_writecb,
+                                   eventcb, NULL);
+                               bufferevent_disable(partner, EV_READ);
+                       } else {
+                               /* We have nothing left to say to the other
+                                * side; close it. */
+                               bufferevent_free(partner);
+                       }
+               }
+               bufferevent_free(bev);
+       }
+}
+
+static void
+syntax(void)
+{
+       fputs("Syntax:\n", stderr);
+       fputs("   le-proxy [-s] [-W] <listen-on-addr> <connect-to-addr>\n", stderr);
+       fputs("Example:\n", stderr);
+       fputs("   le-proxy 127.0.0.1:8888 1.2.3.4:80\n", stderr);
+
+       exit(1);
+}
+
+static void
+accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
+    struct sockaddr *a, int slen, void *p)
+{
+       struct bufferevent *b_out, *b_in;
+       /* Create two linked bufferevent objects: one to connect, one for the
+        * new connection */
+       b_in = bufferevent_socket_new(base, fd,
+           BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+
+       if (!ssl_ctx || use_wrapper)
+               b_out = bufferevent_socket_new(base, -1,
+                   BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+       else {
+               SSL *ssl = SSL_new(ssl_ctx);
+               b_out = bufferevent_openssl_socket_new(base, -1, ssl,
+                   BUFFEREVENT_SSL_CONNECTING,
+                   BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+       }
+
+       assert(b_in && b_out);
+
+       if (bufferevent_socket_connect(b_out,
+               (struct sockaddr*)&connect_to_addr, connect_to_addrlen)<0) {
+               perror("bufferevent_socket_connect");
+               bufferevent_free(b_out);
+               bufferevent_free(b_in);
+               return;
+       }
+
+       if (ssl_ctx && use_wrapper) {
+               struct bufferevent *b_ssl;
+               SSL *ssl = SSL_new(ssl_ctx);
+               b_ssl = bufferevent_openssl_filter_new(base,
+                   b_out, ssl, BUFFEREVENT_SSL_CONNECTING,
+                   BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+               if (!b_ssl) {
+                       perror("Bufferevent_openssl_new");
+                       bufferevent_free(b_out);
+                       bufferevent_free(b_in);
+               }
+               b_out = b_ssl;
+       }
+
+       bufferevent_setcb(b_in, readcb, NULL, eventcb, b_out);
+       bufferevent_setcb(b_out, readcb, NULL, eventcb, b_in);
+
+       bufferevent_enable(b_in, EV_READ|EV_WRITE);
+       bufferevent_enable(b_out, EV_READ|EV_WRITE);
+}
+
+int
+main(int argc, char **argv)
+{
+       int i;
+       int socklen;
+
+       int use_ssl = 0;
+       struct evconnlistener *listener;
+
+       if (argc < 3)
+               syntax();
+
+       for (i=1; i < argc; ++i) {
+               if (!strcmp(argv[i], "-s")) {
+                       use_ssl = 1;
+               } else if (!strcmp(argv[i], "-W")) {
+                       use_wrapper = 0;
+               } else if (argv[i][0] == '-') {
+                       syntax();
+               } else
+                       break;
+       }
+
+       if (i+2 != argc)
+               syntax();
+
+       memset(&listen_on_addr, 0, sizeof(listen_on_addr));
+       socklen = sizeof(listen_on_addr);
+       if (evutil_parse_sockaddr_port(argv[i],
+               (struct sockaddr*)&listen_on_addr, &socklen)<0) {
+               int p = atoi(argv[i]);
+               struct sockaddr_in *sin = (struct sockaddr_in*)&listen_on_addr;
+               if (p < 1 || p > 65535)
+                       syntax();
+               sin->sin_port = htons(p);
+               sin->sin_addr.s_addr = htonl(0x7f000001);
+               sin->sin_family = AF_INET;
+               socklen = sizeof(struct sockaddr_in);
+       }
+
+       memset(&connect_to_addr, 0, sizeof(connect_to_addr));
+       connect_to_addrlen = sizeof(connect_to_addr);
+       if (evutil_parse_sockaddr_port(argv[i+1],
+               (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0)
+               syntax();
+
+       base = event_base_new();
+       if (!base) {
+               perror("event_base_new()");
+               return 1;
+       }
+
+       if (use_ssl) {
+               int r;
+               SSL_library_init();
+               ERR_load_crypto_strings();
+               SSL_load_error_strings();
+               OpenSSL_add_all_algorithms();
+               r = RAND_poll();
+               if (r == 0) {
+                       fprintf(stderr, "RAND_poll() failed.\n");
+                       return 1;
+               }
+               ssl_ctx = SSL_CTX_new(SSLv23_method());
+       }
+
+       listener = evconnlistener_new_bind(base, accept_cb, NULL,
+           LEV_OPT_CLOSE_ON_FREE|LEV_OPT_CLOSE_ON_EXEC|LEV_OPT_REUSEABLE,
+           -1, (struct sockaddr*)&listen_on_addr, socklen);
+
+       event_base_dispatch(base);
+
+       evconnlistener_free(listener);
+       event_base_free(base);
+
+       return 0;
+}
diff --git a/libevent/sample/signal-test.c b/libevent/sample/signal-test.c
new file mode 100644 (file)
index 0000000..53c025f
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Compile with:
+ * cc -I/usr/local/include -o signal-test \
+ *   signal-test.c -L/usr/local/lib -levent
+ */
+
+#include <sys/types.h>
+
+#include <event2/event-config.h>
+
+#include <sys/stat.h>
+#ifndef WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#include <sys/time.h>
+#else
+#include <winsock2.h>
+#include <windows.h>
+#endif
+#include <signal.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event.h>
+
+#ifdef _EVENT___func__
+#define __func__ _EVENT___func__
+#endif
+
+int called = 0;
+
+static void
+signal_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct event *signal = arg;
+
+       printf("%s: got signal %d\n", __func__, EVENT_SIGNAL(signal));
+
+       if (called >= 2)
+               event_del(signal);
+
+       called++;
+}
+
+int
+main(int argc, char **argv)
+{
+       struct event signal_int;
+       struct event_base* base;
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+       /* Initalize the event library */
+       base = event_base_new();
+
+       /* Initalize one event */
+       event_assign(&signal_int, base, SIGINT, EV_SIGNAL|EV_PERSIST, signal_cb,
+           &signal_int);
+
+       event_add(&signal_int, NULL);
+
+       event_base_dispatch(base);
+       event_base_free(base);
+
+       return (0);
+}
+
diff --git a/libevent/sample/time-test.c b/libevent/sample/time-test.c
new file mode 100644 (file)
index 0000000..61b4a6c
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * XXX This sample code was once meant to show how to use the basic Libevent
+ * interfaces, but it never worked on non-Unix platforms, and some of the
+ * interfaces have changed since it was first written.  It should probably
+ * be removed or replaced with something better.
+ *
+ * Compile with:
+ * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
+ */
+
+#include <sys/types.h>
+
+#include <event2/event-config.h>
+
+#include <sys/stat.h>
+#ifndef WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#endif
+#include <time.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event2/event.h>
+#include <event2/event_struct.h>
+#include <event2/util.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+
+struct timeval lasttime;
+
+int event_is_persistent;
+
+static void
+timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct timeval newtime, difference;
+       struct event *timeout = arg;
+       double elapsed;
+
+       evutil_gettimeofday(&newtime, NULL);
+       evutil_timersub(&newtime, &lasttime, &difference);
+       elapsed = difference.tv_sec +
+           (difference.tv_usec / 1.0e6);
+
+       printf("timeout_cb called at %d: %.3f seconds elapsed.\n",
+           (int)newtime.tv_sec, elapsed);
+       lasttime = newtime;
+
+       if (! event_is_persistent) {
+               struct timeval tv;
+               evutil_timerclear(&tv);
+               tv.tv_sec = 2;
+               event_add(timeout, &tv);
+       }
+}
+
+int
+main(int argc, char **argv)
+{
+       struct event timeout;
+       struct timeval tv;
+       struct event_base *base;
+       int flags;
+
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+       if (argc == 2 && !strcmp(argv[1], "-p")) {
+               event_is_persistent = 1;
+               flags = EV_PERSIST;
+       } else {
+               event_is_persistent = 0;
+               flags = 0;
+       }
+
+       /* Initalize the event library */
+       base = event_base_new();
+
+       /* Initalize one event */
+       event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout);
+
+       evutil_timerclear(&tv);
+       tv.tv_sec = 2;
+       event_add(&timeout, &tv);
+
+       evutil_gettimeofday(&lasttime, NULL);
+
+       event_base_dispatch(base);
+
+       return (0);
+}
+
diff --git a/libevent/select.c b/libevent/select.c
new file mode 100644 (file)
index 0000000..afba6d3
--- /dev/null
@@ -0,0 +1,333 @@
+/*     $OpenBSD: select.c,v 1.2 2002/06/25 15:50:15 mickey Exp $       */
+
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#include <sys/types.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+#include <sys/queue.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "event-internal.h"
+#include "evsignal-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+
+#ifndef _EVENT_HAVE_FD_MASK
+/* This type is mandatory, but Android doesn't define it. */
+typedef unsigned long fd_mask;
+#endif
+
+#ifndef NFDBITS
+#define NFDBITS (sizeof(fd_mask)*8)
+#endif
+
+/* Divide positive x by y, rounding up. */
+#define DIV_ROUNDUP(x, y)   (((x)+((y)-1))/(y))
+
+/* How many bytes to allocate for N fds? */
+#define SELECT_ALLOC_SIZE(n) \
+       (DIV_ROUNDUP(n, NFDBITS) * sizeof(fd_mask))
+
+struct selectop {
+       int event_fds;          /* Highest fd in fd set */
+       int event_fdsz;
+       int resize_out_sets;
+       fd_set *event_readset_in;
+       fd_set *event_writeset_in;
+       fd_set *event_readset_out;
+       fd_set *event_writeset_out;
+};
+
+static void *select_init(struct event_base *);
+static int select_add(struct event_base *, int, short old, short events, void*);
+static int select_del(struct event_base *, int, short old, short events, void*);
+static int select_dispatch(struct event_base *, struct timeval *);
+static void select_dealloc(struct event_base *);
+
+const struct eventop selectops = {
+       "select",
+       select_init,
+       select_add,
+       select_del,
+       select_dispatch,
+       select_dealloc,
+       0, /* doesn't need reinit. */
+       EV_FEATURE_FDS,
+       0,
+};
+
+static int select_resize(struct selectop *sop, int fdsz);
+static void select_free_selectop(struct selectop *sop);
+
+static void *
+select_init(struct event_base *base)
+{
+       struct selectop *sop;
+
+       if (!(sop = mm_calloc(1, sizeof(struct selectop))))
+               return (NULL);
+
+       if (select_resize(sop, SELECT_ALLOC_SIZE(32 + 1))) {
+               select_free_selectop(sop);
+               return (NULL);
+       }
+
+       evsig_init(base);
+
+       return (sop);
+}
+
+#ifdef CHECK_INVARIANTS
+static void
+check_selectop(struct selectop *sop)
+{
+       /* nothing to be done here */
+}
+#else
+#define check_selectop(sop) do { (void) sop; } while (0)
+#endif
+
+static int
+select_dispatch(struct event_base *base, struct timeval *tv)
+{
+       int res=0, i, j, nfds;
+       struct selectop *sop = base->evbase;
+
+       check_selectop(sop);
+       if (sop->resize_out_sets) {
+               fd_set *readset_out=NULL, *writeset_out=NULL;
+               size_t sz = sop->event_fdsz;
+               if (!(readset_out = mm_realloc(sop->event_readset_out, sz)))
+                       return (-1);
+               sop->event_readset_out = readset_out;
+               if (!(writeset_out = mm_realloc(sop->event_writeset_out, sz))) {
+                       /* We don't free readset_out here, since it was
+                        * already successfully reallocated. The next time
+                        * we call select_dispatch, the realloc will be a
+                        * no-op. */
+                       return (-1);
+               }
+               sop->event_writeset_out = writeset_out;
+               sop->resize_out_sets = 0;
+       }
+
+       memcpy(sop->event_readset_out, sop->event_readset_in,
+              sop->event_fdsz);
+       memcpy(sop->event_writeset_out, sop->event_writeset_in,
+              sop->event_fdsz);
+
+       nfds = sop->event_fds+1;
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+       res = select(nfds, sop->event_readset_out,
+           sop->event_writeset_out, NULL, tv);
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       check_selectop(sop);
+
+       if (res == -1) {
+               if (errno != EINTR) {
+                       event_warn("select");
+                       return (-1);
+               }
+
+               return (0);
+       }
+
+       event_debug(("%s: select reports %d", __func__, res));
+
+       check_selectop(sop);
+       i = random() % nfds;
+       for (j = 0; j < nfds; ++j) {
+               if (++i >= nfds)
+                       i = 0;
+               res = 0;
+               if (FD_ISSET(i, sop->event_readset_out))
+                       res |= EV_READ;
+               if (FD_ISSET(i, sop->event_writeset_out))
+                       res |= EV_WRITE;
+
+               if (res == 0)
+                       continue;
+
+               evmap_io_active(base, i, res);
+       }
+       check_selectop(sop);
+
+       return (0);
+}
+
+static int
+select_resize(struct selectop *sop, int fdsz)
+{
+       fd_set *readset_in = NULL;
+       fd_set *writeset_in = NULL;
+
+       if (sop->event_readset_in)
+               check_selectop(sop);
+
+       if ((readset_in = mm_realloc(sop->event_readset_in, fdsz)) == NULL)
+               goto error;
+       sop->event_readset_in = readset_in;
+       if ((writeset_in = mm_realloc(sop->event_writeset_in, fdsz)) == NULL) {
+               /* Note that this will leave event_readset_in expanded.
+                * That's okay; we wouldn't want to free it, since that would
+                * change the semantics of select_resize from "expand the
+                * readset_in and writeset_in, or return -1" to "expand the
+                * *set_in members, or trash them and return -1."
+                */
+               goto error;
+       }
+       sop->event_writeset_in = writeset_in;
+       sop->resize_out_sets = 1;
+
+       memset((char *)sop->event_readset_in + sop->event_fdsz, 0,
+           fdsz - sop->event_fdsz);
+       memset((char *)sop->event_writeset_in + sop->event_fdsz, 0,
+           fdsz - sop->event_fdsz);
+
+       sop->event_fdsz = fdsz;
+       check_selectop(sop);
+
+       return (0);
+
+ error:
+       event_warn("malloc");
+       return (-1);
+}
+
+
+static int
+select_add(struct event_base *base, int fd, short old, short events, void *p)
+{
+       struct selectop *sop = base->evbase;
+       (void) p;
+
+       EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
+       check_selectop(sop);
+       /*
+        * Keep track of the highest fd, so that we can calculate the size
+        * of the fd_sets for select(2)
+        */
+       if (sop->event_fds < fd) {
+               int fdsz = sop->event_fdsz;
+
+               if (fdsz < (int)sizeof(fd_mask))
+                       fdsz = (int)sizeof(fd_mask);
+
+               /* In theory we should worry about overflow here.  In
+                * reality, though, the highest fd on a unixy system will
+                * not overflow here. XXXX */
+               while (fdsz < (int) SELECT_ALLOC_SIZE(fd + 1))
+                       fdsz *= 2;
+
+               if (fdsz != sop->event_fdsz) {
+                       if (select_resize(sop, fdsz)) {
+                               check_selectop(sop);
+                               return (-1);
+                       }
+               }
+
+               sop->event_fds = fd;
+       }
+
+       if (events & EV_READ)
+               FD_SET(fd, sop->event_readset_in);
+       if (events & EV_WRITE)
+               FD_SET(fd, sop->event_writeset_in);
+       check_selectop(sop);
+
+       return (0);
+}
+
+/*
+ * Nothing to be done here.
+ */
+
+static int
+select_del(struct event_base *base, int fd, short old, short events, void *p)
+{
+       struct selectop *sop = base->evbase;
+       (void)p;
+
+       EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
+       check_selectop(sop);
+
+       if (sop->event_fds < fd) {
+               check_selectop(sop);
+               return (0);
+       }
+
+       if (events & EV_READ)
+               FD_CLR(fd, sop->event_readset_in);
+
+       if (events & EV_WRITE)
+               FD_CLR(fd, sop->event_writeset_in);
+
+       check_selectop(sop);
+       return (0);
+}
+
+static void
+select_free_selectop(struct selectop *sop)
+{
+       if (sop->event_readset_in)
+               mm_free(sop->event_readset_in);
+       if (sop->event_writeset_in)
+               mm_free(sop->event_writeset_in);
+       if (sop->event_readset_out)
+               mm_free(sop->event_readset_out);
+       if (sop->event_writeset_out)
+               mm_free(sop->event_writeset_out);
+
+       memset(sop, 0, sizeof(struct selectop));
+       mm_free(sop);
+}
+
+static void
+select_dealloc(struct event_base *base)
+{
+       evsig_dealloc(base);
+
+       select_free_selectop(base->evbase);
+}
diff --git a/libevent/signal.c b/libevent/signal.c
new file mode 100644 (file)
index 0000000..d40da0e
--- /dev/null
@@ -0,0 +1,444 @@
+/*     $OpenBSD: select.c,v 1.2 2002/06/25 15:50:15 mickey Exp $       */
+
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+#include <sys/types.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <errno.h>
+#ifdef _EVENT_HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event-internal.h"
+#include "event2/util.h"
+#include "evsignal-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "evthread-internal.h"
+
+/*
+  signal.c
+
+  This is the signal-handling implementation we use for backends that don't
+  have a better way to do signal handling.  It uses sigaction() or signal()
+  to set a signal handler, and a socket pair to tell the event base when
+
+  Note that I said "the event base" : only one event base can be set up to use
+  this at a time.  For historical reasons and backward compatibility, if you
+  add an event for a signal to event_base A, then add an event for a signal
+  (any signal!) to event_base B, event_base B will get informed about the
+  signal, but event_base A won't.
+
+  It would be neat to change this behavior in some future version of Libevent.
+  kqueue already does something far more sensible.  We can make all backends
+  on Linux do a reasonable thing using signalfd.
+*/
+
+#ifndef WIN32
+/* Windows wants us to call our signal handlers as __cdecl.  Nobody else
+ * expects you to do anything crazy like this. */
+#define __cdecl
+#endif
+
+static int evsig_add(struct event_base *, evutil_socket_t, short, short, void *);
+static int evsig_del(struct event_base *, evutil_socket_t, short, short, void *);
+
+static const struct eventop evsigops = {
+       "signal",
+       NULL,
+       evsig_add,
+       evsig_del,
+       NULL,
+       NULL,
+       0, 0, 0
+};
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+/* Lock for evsig_base and evsig_base_n_signals_added fields. */
+static void *evsig_base_lock = NULL;
+#endif
+/* The event base that's currently getting informed about signals. */
+static struct event_base *evsig_base = NULL;
+/* A copy of evsig_base->sigev_n_signals_added. */
+static int evsig_base_n_signals_added = 0;
+static evutil_socket_t evsig_base_fd = -1;
+
+static void __cdecl evsig_handler(int sig);
+
+#define EVSIGBASE_LOCK() EVLOCK_LOCK(evsig_base_lock, 0)
+#define EVSIGBASE_UNLOCK() EVLOCK_UNLOCK(evsig_base_lock, 0)
+
+void
+evsig_set_base(struct event_base *base)
+{
+       EVSIGBASE_LOCK();
+       evsig_base = base;
+       evsig_base_n_signals_added = base->sig.ev_n_signals_added;
+       evsig_base_fd = base->sig.ev_signal_pair[0];
+       EVSIGBASE_UNLOCK();
+}
+
+/* Callback for when the signal handler write a byte to our signaling socket */
+static void
+evsig_cb(evutil_socket_t fd, short what, void *arg)
+{
+       static char signals[1024];
+       ev_ssize_t n;
+       int i;
+       int ncaught[NSIG];
+       struct event_base *base;
+
+       base = arg;
+
+       memset(&ncaught, 0, sizeof(ncaught));
+
+       while (1) {
+               n = recv(fd, signals, sizeof(signals), 0);
+               if (n == -1) {
+                       int err = evutil_socket_geterror(fd);
+                       if (! EVUTIL_ERR_RW_RETRIABLE(err))
+                               event_sock_err(1, fd, "%s: recv", __func__);
+                       break;
+               } else if (n == 0) {
+                       /* XXX warn? */
+                       break;
+               }
+               for (i = 0; i < n; ++i) {
+                       ev_uint8_t sig = signals[i];
+                       if (sig < NSIG)
+                               ncaught[sig]++;
+               }
+       }
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       for (i = 0; i < NSIG; ++i) {
+               if (ncaught[i])
+                       evmap_signal_active(base, i, ncaught[i]);
+       }
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+int
+evsig_init(struct event_base *base)
+{
+       /*
+        * Our signal handler is going to write to one end of the socket
+        * pair to wake up our event loop.  The event loop then scans for
+        * signals that got delivered.
+        */
+       if (evutil_socketpair(
+                   AF_UNIX, SOCK_STREAM, 0, base->sig.ev_signal_pair) == -1) {
+#ifdef WIN32
+               /* Make this nonfatal on win32, where sometimes people
+                  have localhost firewalled. */
+               event_sock_warn(-1, "%s: socketpair", __func__);
+#else
+               event_sock_err(1, -1, "%s: socketpair", __func__);
+#endif
+               return -1;
+       }
+
+       evutil_make_socket_closeonexec(base->sig.ev_signal_pair[0]);
+       evutil_make_socket_closeonexec(base->sig.ev_signal_pair[1]);
+       base->sig.sh_old = NULL;
+       base->sig.sh_old_max = 0;
+
+       evutil_make_socket_nonblocking(base->sig.ev_signal_pair[0]);
+       evutil_make_socket_nonblocking(base->sig.ev_signal_pair[1]);
+
+       event_assign(&base->sig.ev_signal, base, base->sig.ev_signal_pair[1],
+               EV_READ | EV_PERSIST, evsig_cb, base);
+
+       base->sig.ev_signal.ev_flags |= EVLIST_INTERNAL;
+       event_priority_set(&base->sig.ev_signal, 0);
+
+       base->evsigsel = &evsigops;
+
+       return 0;
+}
+
+/* Helper: set the signal handler for evsignal to handler in base, so that
+ * we can restore the original handler when we clear the current one. */
+int
+_evsig_set_handler(struct event_base *base,
+    int evsignal, void (__cdecl *handler)(int))
+{
+#ifdef _EVENT_HAVE_SIGACTION
+       struct sigaction sa;
+#else
+       ev_sighandler_t sh;
+#endif
+       struct evsig_info *sig = &base->sig;
+       void *p;
+
+       /*
+        * resize saved signal handler array up to the highest signal number.
+        * a dynamic array is used to keep footprint on the low side.
+        */
+       if (evsignal >= sig->sh_old_max) {
+               int new_max = evsignal + 1;
+               event_debug(("%s: evsignal (%d) >= sh_old_max (%d), resizing",
+                           __func__, evsignal, sig->sh_old_max));
+               p = mm_realloc(sig->sh_old, new_max * sizeof(*sig->sh_old));
+               if (p == NULL) {
+                       event_warn("realloc");
+                       return (-1);
+               }
+
+               memset((char *)p + sig->sh_old_max * sizeof(*sig->sh_old),
+                   0, (new_max - sig->sh_old_max) * sizeof(*sig->sh_old));
+
+               sig->sh_old_max = new_max;
+               sig->sh_old = p;
+       }
+
+       /* allocate space for previous handler out of dynamic array */
+       sig->sh_old[evsignal] = mm_malloc(sizeof *sig->sh_old[evsignal]);
+       if (sig->sh_old[evsignal] == NULL) {
+               event_warn("malloc");
+               return (-1);
+       }
+
+       /* save previous handler and setup new handler */
+#ifdef _EVENT_HAVE_SIGACTION
+       memset(&sa, 0, sizeof(sa));
+       sa.sa_handler = handler;
+       sa.sa_flags |= SA_RESTART;
+       sigfillset(&sa.sa_mask);
+
+       if (sigaction(evsignal, &sa, sig->sh_old[evsignal]) == -1) {
+               event_warn("sigaction");
+               mm_free(sig->sh_old[evsignal]);
+               sig->sh_old[evsignal] = NULL;
+               return (-1);
+       }
+#else
+       if ((sh = signal(evsignal, handler)) == SIG_ERR) {
+               event_warn("signal");
+               mm_free(sig->sh_old[evsignal]);
+               sig->sh_old[evsignal] = NULL;
+               return (-1);
+       }
+       *sig->sh_old[evsignal] = sh;
+#endif
+
+       return (0);
+}
+
+static int
+evsig_add(struct event_base *base, evutil_socket_t evsignal, short old, short events, void *p)
+{
+       struct evsig_info *sig = &base->sig;
+       (void)p;
+
+       EVUTIL_ASSERT(evsignal >= 0 && evsignal < NSIG);
+
+       /* catch signals if they happen quickly */
+       EVSIGBASE_LOCK();
+       if (evsig_base != base && evsig_base_n_signals_added) {
+               event_warnx("Added a signal to event base %p with signals "
+                   "already added to event_base %p.  Only one can have "
+                   "signals at a time with the %s backend.  The base with "
+                   "the most recently added signal or the most recent "
+                   "event_base_loop() call gets preference; do "
+                   "not rely on this behavior in future Libevent versions.",
+                   base, evsig_base, base->evsel->name);
+       }
+       evsig_base = base;
+       evsig_base_n_signals_added = ++sig->ev_n_signals_added;
+       evsig_base_fd = base->sig.ev_signal_pair[0];
+       EVSIGBASE_UNLOCK();
+
+       event_debug(("%s: %d: changing signal handler", __func__, (int)evsignal));
+       if (_evsig_set_handler(base, (int)evsignal, evsig_handler) == -1) {
+               goto err;
+       }
+
+
+       if (!sig->ev_signal_added) {
+               if (event_add(&sig->ev_signal, NULL))
+                       goto err;
+               sig->ev_signal_added = 1;
+       }
+
+       return (0);
+
+err:
+       EVSIGBASE_LOCK();
+       --evsig_base_n_signals_added;
+       --sig->ev_n_signals_added;
+       EVSIGBASE_UNLOCK();
+       return (-1);
+}
+
+int
+_evsig_restore_handler(struct event_base *base, int evsignal)
+{
+       int ret = 0;
+       struct evsig_info *sig = &base->sig;
+#ifdef _EVENT_HAVE_SIGACTION
+       struct sigaction *sh;
+#else
+       ev_sighandler_t *sh;
+#endif
+
+       /* restore previous handler */
+       sh = sig->sh_old[evsignal];
+       sig->sh_old[evsignal] = NULL;
+#ifdef _EVENT_HAVE_SIGACTION
+       if (sigaction(evsignal, sh, NULL) == -1) {
+               event_warn("sigaction");
+               ret = -1;
+       }
+#else
+       if (signal(evsignal, *sh) == SIG_ERR) {
+               event_warn("signal");
+               ret = -1;
+       }
+#endif
+
+       mm_free(sh);
+
+       return ret;
+}
+
+static int
+evsig_del(struct event_base *base, evutil_socket_t evsignal, short old, short events, void *p)
+{
+       EVUTIL_ASSERT(evsignal >= 0 && evsignal < NSIG);
+
+       event_debug(("%s: %d: restoring signal handler", __func__, evsignal));
+
+       EVSIGBASE_LOCK();
+       --evsig_base_n_signals_added;
+       --base->sig.ev_n_signals_added;
+       EVSIGBASE_UNLOCK();
+
+       return (_evsig_restore_handler(base, (int)evsignal));
+}
+
+static void __cdecl
+evsig_handler(int sig)
+{
+       int save_errno = errno;
+#ifdef WIN32
+       int socket_errno = EVUTIL_SOCKET_ERROR();
+#endif
+       ev_uint8_t msg;
+
+       if (evsig_base == NULL) {
+               event_warnx(
+                       "%s: received signal %d, but have no base configured",
+                       __func__, sig);
+               return;
+       }
+
+#ifndef _EVENT_HAVE_SIGACTION
+       signal(sig, evsig_handler);
+#endif
+
+       /* Wake up our notification mechanism */
+       msg = sig;
+       send(evsig_base_fd, (char*)&msg, 1, 0);
+       errno = save_errno;
+#ifdef WIN32
+       EVUTIL_SET_SOCKET_ERROR(socket_errno);
+#endif
+}
+
+void
+evsig_dealloc(struct event_base *base)
+{
+       int i = 0;
+       if (base->sig.ev_signal_added) {
+               event_del(&base->sig.ev_signal);
+               base->sig.ev_signal_added = 0;
+       }
+       /* debug event is created in evsig_init/event_assign even when
+        * ev_signal_added == 0, so unassign is required */
+       event_debug_unassign(&base->sig.ev_signal);
+
+       for (i = 0; i < NSIG; ++i) {
+               if (i < base->sig.sh_old_max && base->sig.sh_old[i] != NULL)
+                       _evsig_restore_handler(base, i);
+       }
+       EVSIGBASE_LOCK();
+       if (base == evsig_base) {
+               evsig_base = NULL;
+               evsig_base_n_signals_added = 0;
+               evsig_base_fd = -1;
+       }
+       EVSIGBASE_UNLOCK();
+
+       if (base->sig.ev_signal_pair[0] != -1) {
+               evutil_closesocket(base->sig.ev_signal_pair[0]);
+               base->sig.ev_signal_pair[0] = -1;
+       }
+       if (base->sig.ev_signal_pair[1] != -1) {
+               evutil_closesocket(base->sig.ev_signal_pair[1]);
+               base->sig.ev_signal_pair[1] = -1;
+       }
+       base->sig.sh_old_max = 0;
+
+       /* per index frees are handled in evsig_del() */
+       if (base->sig.sh_old) {
+               mm_free(base->sig.sh_old);
+               base->sig.sh_old = NULL;
+       }
+}
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+int
+evsig_global_setup_locks_(const int enable_locks)
+{
+       EVTHREAD_SETUP_GLOBAL_LOCK(evsig_base_lock, 0);
+       return 0;
+}
+#endif
diff --git a/libevent/strlcpy-internal.h b/libevent/strlcpy-internal.h
new file mode 100644 (file)
index 0000000..1968c00
--- /dev/null
@@ -0,0 +1,21 @@
+#ifndef _STRLCPY_INTERNAL_H_
+#define _STRLCPY_INTERNAL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+
+#ifndef _EVENT_HAVE_STRLCPY
+#include <string.h>
+size_t _event_strlcpy(char *dst, const char *src, size_t siz);
+#define strlcpy _event_strlcpy
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/libevent/strlcpy.c b/libevent/strlcpy.c
new file mode 100644 (file)
index 0000000..11053c3
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $OpenBSD: strlcpy.c,v 1.5 2001/05/13 15:40:16 deraadt Exp $     */
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char *rcsid = "$OpenBSD: strlcpy.c,v 1.5 2001/05/13 15:40:16 deraadt Exp $";
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+
+#include "event2/event-config.h"
+
+#ifndef _EVENT_HAVE_STRLCPY
+#include "strlcpy-internal.h"
+
+/*
+ * Copy src to string dst of size siz.  At most siz-1 characters
+ * will be copied.  Always NUL terminates (unless siz == 0).
+ * Returns strlen(src); if retval >= siz, truncation occurred.
+ */
+size_t
+_event_strlcpy(dst, src, siz)
+       char *dst;
+       const char *src;
+       size_t siz;
+{
+       register char *d = dst;
+       register const char *s = src;
+       register size_t n = siz;
+
+       /* Copy as many bytes as will fit */
+       if (n != 0 && --n != 0) {
+               do {
+                       if ((*d++ = *s++) == 0)
+                               break;
+               } while (--n != 0);
+       }
+
+       /* Not enough room in dst, add NUL and traverse rest of src */
+       if (n == 0) {
+               if (siz != 0)
+                       *d = '\0';              /* NUL-terminate dst */
+               while (*s++)
+                       ;
+       }
+
+       return (s - src - 1);   /* count does not include NUL */
+}
+#endif
diff --git a/libevent/test/Makefile.am b/libevent/test/Makefile.am
new file mode 100644 (file)
index 0000000..5904b64
--- /dev/null
@@ -0,0 +1,98 @@
+# test/Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+AUTOMAKE_OPTIONS = foreign
+
+AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/compat -I$(top_srcdir)/include -I../include -DTINYTEST_LOCAL
+
+EXTRA_DIST = regress.rpc regress.gen.h regress.gen.c rpcgen_wrapper.sh test.sh
+
+noinst_PROGRAMS = test-init test-eof test-weof test-time \
+       bench bench_cascade bench_http bench_httpclient test-ratelim \
+       test-changelist
+if BUILD_REGRESS
+noinst_PROGRAMS += regress
+endif
+EXTRA_PROGRAMS = regress
+noinst_HEADERS = tinytest.h tinytest_macros.h regress.h tinytest_local.h
+
+# TESTS = $(top_srcdir)/test/test.sh
+
+BUILT_SOURCES =
+if BUILD_REGRESS
+BUILT_SOURCES += regress.gen.c regress.gen.h
+endif
+
+test_init_SOURCES = test-init.c
+test_init_LDADD = ../libevent_core.la
+test_eof_SOURCES = test-eof.c
+test_eof_LDADD = ../libevent_core.la
+test_changelist_SOURCES = test-changelist.c
+test_changelist_LDADD = ../libevent_core.la
+test_weof_SOURCES = test-weof.c
+test_weof_LDADD = ../libevent_core.la
+test_time_SOURCES = test-time.c
+test_time_LDADD = ../libevent_core.la
+test_ratelim_SOURCES = test-ratelim.c
+test_ratelim_LDADD = ../libevent_core.la -lm
+
+regress_SOURCES = regress.c regress_buffer.c regress_http.c regress_dns.c \
+       regress_testutils.c regress_testutils.h \
+       regress_rpc.c regress.gen.c regress.gen.h regress_et.c \
+       regress_bufferevent.c regress_listener.c \
+       regress_util.c tinytest.c regress_main.c regress_minheap.c \
+       $(regress_thread_SOURCES) $(regress_zlib_SOURCES)
+if PTHREADS
+regress_thread_SOURCES = regress_thread.c
+PTHREAD_LIBS += ../libevent_pthreads.la
+endif
+if BUILD_WIN32
+regress_thread_SOURCES = regress_thread.c
+endif
+if ZLIB_REGRESS
+regress_zlib_SOURCES = regress_zlib.c
+endif
+if BUILD_WIN32
+regress_SOURCES += regress_iocp.c
+endif
+
+regress_LDADD = $(LIBEVENT_GC_SECTIONS) ../libevent.la $(PTHREAD_LIBS) $(ZLIB_LIBS)
+regress_CPPFLAGS = $(AM_CPPFLAGS) $(PTHREAD_CFLAGS) $(ZLIB_CFLAGS)
+regress_LDFLAGS = $(PTHREAD_CFLAGS)
+
+if OPENSSL
+regress_SOURCES += regress_ssl.c
+regress_LDADD += ../libevent_openssl.la -lssl -lcrypto ${OPENSSL_LIBADD}
+endif
+
+bench_SOURCES = bench.c
+bench_LDADD = $(LIBEVENT_GC_SECTIONS) ../libevent.la
+bench_cascade_SOURCES = bench_cascade.c
+bench_cascade_LDADD = $(LIBEVENT_GC_SECTIONS) ../libevent.la
+bench_http_SOURCES = bench_http.c
+bench_http_LDADD = $(LIBEVENT_GC_SECTIONS) ../libevent.la
+bench_httpclient_SOURCES = bench_httpclient.c
+bench_httpclient_LDADD = $(LIBEVENT_GC_SECTIONS) ../libevent_core.la
+
+regress.gen.c regress.gen.h: rpcgen-attempted
+
+rpcgen-attempted: $(srcdir)/regress.rpc $(srcdir)/../event_rpcgen.py $(srcdir)/rpcgen_wrapper.sh
+       date -u > $@
+       if $(srcdir)/rpcgen_wrapper.sh $(srcdir); then \
+          echo "rpcgen okay"; \
+       else \
+          echo "No Python installed; stubbing out RPC test." >&2; \
+          echo " "> regress.gen.c; \
+          echo "#define NO_PYTHON_EXISTS" > regress.gen.h; \
+       fi
+
+CLEANFILES = rpcgen-attempted
+
+DISTCLEANFILES = *~
+
+verify: check
+
+bench test-init test-eof test-weof test-time test-changelist: ../libevent.la
diff --git a/libevent/test/Makefile.nmake b/libevent/test/Makefile.nmake
new file mode 100644 (file)
index 0000000..a899941
--- /dev/null
@@ -0,0 +1,61 @@
+
+CFLAGS=/I.. /I../WIN32-Code /I../include /I../compat /DWIN32 /DHAVE_CONFIG_H /DTINYTEST_LOCAL
+
+CFLAGS=$(CFLAGS) /Ox /W3 /wd4996 /nologo
+
+REGRESS_OBJS=regress.obj regress_buffer.obj regress_http.obj regress_dns.obj \
+       regress_testutils.obj \
+        regress_rpc.obj regress.gen.obj \
+       regress_et.obj regress_bufferevent.obj \
+       regress_listener.obj regress_util.obj tinytest.obj \
+       regress_main.obj regress_minheap.obj regress_iocp.obj \
+       regress_thread.obj
+
+OTHER_OBJS=test-init.obj test-eof.obj test-weof.obj test-time.obj \
+       bench.obj bench_cascade.obj bench_http.obj bench_httpclient.obj \
+       test-changelist.obj
+
+PROGRAMS=regress.exe \
+       test-init.exe test-eof.exe test-weof.exe test-time.exe \
+       test-changelist.exe
+
+# Disabled for now:
+#      bench.exe bench_cascade.exe bench_http.exe bench_httpclient.exe
+
+
+LIBS=..\libevent.lib ws2_32.lib shell32.lib advapi32.lib
+
+all: $(PROGRAMS)
+
+regress.exe: $(REGRESS_OBJS)
+       $(CC) $(CFLAGS) $(LIBS) $(REGRESS_OBJS)
+
+test-init.exe: test-init.obj
+       $(CC) $(CFLAGS) $(LIBS) test-init.obj
+test-eof.exe: test-eof.obj
+       $(CC) $(CFLAGS) $(LIBS) test-eof.obj
+test-changelist.exe: test-changelist.obj
+       $(CC) $(CFLAGS) $(LIBS) test-changelist.obj
+test-weof.exe: test-weof.obj
+       $(CC) $(CFLAGS) $(LIBS) test-weof.obj
+test-time.exe: test-time.obj
+       $(CC) $(CFLAGS) $(LIBS) test-time.obj
+
+bench.exe: bench.obj
+       $(CC) $(CFLAGS) $(LIBS) bench.obj
+bench_cascade.exe: bench_cascade.obj
+       $(CC) $(CFLAGS) $(LIBS) bench_cascade.obj
+bench_http.exe: bench_http.obj
+       $(CC) $(CFLAGS) $(LIBS) bench_http.obj
+bench_httpclient.exe: bench_httpclient.obj
+       $(CC) $(CFLAGS) $(LIBS) bench_httpclient.obj
+
+regress.gen.c regress.gen.h: regress.rpc ../event_rpcgen.py
+       echo // > regress.gen.c
+       echo #define NO_PYTHON_EXISTS > regress.gen.h
+       -python ..\event_rpcgen.py regress.rpc
+
+clean:
+       -del $(REGRESS_OBJS)
+       -del $(OTHER_OBJS)
+       -del regress.exe
diff --git a/libevent/test/bench.c b/libevent/test/bench.c
new file mode 100644 (file)
index 0000000..66b7d71
--- /dev/null
@@ -0,0 +1,196 @@
+/*
+ * Copyright 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * 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.
+ * 4. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ *
+ * Mon 03/10/2003 - Modified by Davide Libenzi <davidel@xmailserver.org>
+ *
+ *     Added chain event propagation to improve the sensitivity of
+ *     the measure respect to the event loop efficency.
+ *
+ *
+ */
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#else
+#include <sys/socket.h>
+#include <signal.h>
+#include <sys/resource.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+#include <event.h>
+#include <evutil.h>
+
+static int count, writes, fired;
+static int *pipes;
+static int num_pipes, num_active, num_writes;
+static struct event *events;
+
+
+static void
+read_cb(evutil_socket_t fd, short which, void *arg)
+{
+       long idx = (long) arg, widx = idx + 1;
+       u_char ch;
+
+       count += recv(fd, (char*)&ch, sizeof(ch), 0);
+       if (writes) {
+               if (widx >= num_pipes)
+                       widx -= num_pipes;
+               send(pipes[2 * widx + 1], "e", 1, 0);
+               writes--;
+               fired++;
+       }
+}
+
+static struct timeval *
+run_once(void)
+{
+       int *cp, space;
+       long i;
+       static struct timeval ts, te;
+
+       for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+               if (event_initialized(&events[i]))
+                       event_del(&events[i]);
+               event_set(&events[i], cp[0], EV_READ | EV_PERSIST, read_cb, (void *) i);
+               event_add(&events[i], NULL);
+       }
+
+       event_loop(EVLOOP_ONCE | EVLOOP_NONBLOCK);
+
+       fired = 0;
+       space = num_pipes / num_active;
+       space = space * 2;
+       for (i = 0; i < num_active; i++, fired++)
+               send(pipes[i * space + 1], "e", 1, 0);
+
+       count = 0;
+       writes = num_writes;
+       { int xcount = 0;
+       evutil_gettimeofday(&ts, NULL);
+       do {
+               event_loop(EVLOOP_ONCE | EVLOOP_NONBLOCK);
+               xcount++;
+       } while (count != fired);
+       evutil_gettimeofday(&te, NULL);
+
+       if (xcount != count) fprintf(stderr, "Xcount: %d, Rcount: %d\n", xcount, count);
+       }
+
+       evutil_timersub(&te, &ts, &te);
+
+       return (&te);
+}
+
+int
+main(int argc, char **argv)
+{
+#ifndef WIN32
+       struct rlimit rl;
+#endif
+       int i, c;
+       struct timeval *tv;
+       int *cp;
+
+#ifdef WIN32
+       WSADATA WSAData;
+       WSAStartup(0x101, &WSAData);
+#endif
+       num_pipes = 100;
+       num_active = 1;
+       num_writes = num_pipes;
+       while ((c = getopt(argc, argv, "n:a:w:")) != -1) {
+               switch (c) {
+               case 'n':
+                       num_pipes = atoi(optarg);
+                       break;
+               case 'a':
+                       num_active = atoi(optarg);
+                       break;
+               case 'w':
+                       num_writes = atoi(optarg);
+                       break;
+               default:
+                       fprintf(stderr, "Illegal argument \"%c\"\n", c);
+                       exit(1);
+               }
+       }
+
+#ifndef WIN32
+       rl.rlim_cur = rl.rlim_max = num_pipes * 2 + 50;
+       if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
+               perror("setrlimit");
+               exit(1);
+       }
+#endif
+
+       events = calloc(num_pipes, sizeof(struct event));
+       pipes = calloc(num_pipes * 2, sizeof(int));
+       if (events == NULL || pipes == NULL) {
+               perror("malloc");
+               exit(1);
+       }
+
+       event_init();
+
+       for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+#ifdef USE_PIPES
+               if (pipe(cp) == -1) {
+#else
+               if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, cp) == -1) {
+#endif
+                       perror("pipe");
+                       exit(1);
+               }
+       }
+
+       for (i = 0; i < 25; i++) {
+               tv = run_once();
+               if (tv == NULL)
+                       exit(1);
+               fprintf(stdout, "%ld\n",
+                       tv->tv_sec * 1000000L + tv->tv_usec);
+       }
+
+       exit(0);
+}
diff --git a/libevent/test/bench_cascade.c b/libevent/test/bench_cascade.c
new file mode 100644 (file)
index 0000000..08b7f94
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * 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.
+ * 4. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#else
+#include <sys/socket.h>
+#include <sys/resource.h>
+#endif
+#include <signal.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+#include <event.h>
+#include <evutil.h>
+
+/*
+ * This benchmark tests how quickly we can propagate a write down a chain
+ * of socket pairs.  We start by writing to the first socket pair and all
+ * events will fire subsequently until the last socket pair has been reached
+ * and the benchmark terminates.
+ */
+
+static int fired;
+static int *pipes;
+static struct event *events;
+
+static void
+read_cb(evutil_socket_t fd, short which, void *arg)
+{
+       char ch;
+       long idx = (long) arg;
+
+       recv(fd, &ch, sizeof(ch), 0);
+       if (idx >= 0)
+               send(idx, "e", 1, 0);
+       fired++;
+}
+
+static struct timeval *
+run_once(int num_pipes)
+{
+       int *cp, i;
+       static struct timeval ts, te, tv_timeout;
+
+       events = calloc(num_pipes, sizeof(struct event));
+       pipes = calloc(num_pipes * 2, sizeof(int));
+
+       if (events == NULL || pipes == NULL) {
+               perror("malloc");
+               exit(1);
+       }
+
+       for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+               if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, cp) == -1) {
+                       perror("socketpair");
+                       exit(1);
+               }
+       }
+
+       /* measurements includes event setup */
+       evutil_gettimeofday(&ts, NULL);
+
+       /* provide a default timeout for events */
+       evutil_timerclear(&tv_timeout);
+       tv_timeout.tv_sec = 60;
+
+       for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+               long fd = i < num_pipes - 1 ? cp[3] : -1;
+               event_set(&events[i], cp[0], EV_READ, read_cb, (void *) fd);
+               event_add(&events[i], &tv_timeout);
+       }
+
+       fired = 0;
+
+       /* kick everything off with a single write */
+       send(pipes[1], "e", 1, 0);
+
+       event_dispatch();
+
+       evutil_gettimeofday(&te, NULL);
+       evutil_timersub(&te, &ts, &te);
+
+       for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+               event_del(&events[i]);
+               close(cp[0]);
+               close(cp[1]);
+       }
+
+       free(pipes);
+       free(events);
+
+       return (&te);
+}
+
+int
+main(int argc, char **argv)
+{
+#ifndef WIN32
+       struct rlimit rl;
+#endif
+       int i, c;
+       struct timeval *tv;
+
+       int num_pipes = 100;
+       while ((c = getopt(argc, argv, "n:")) != -1) {
+               switch (c) {
+               case 'n':
+                       num_pipes = atoi(optarg);
+                       break;
+               default:
+                       fprintf(stderr, "Illegal argument \"%c\"\n", c);
+                       exit(1);
+               }
+       }
+
+#ifndef WIN32
+       rl.rlim_cur = rl.rlim_max = num_pipes * 2 + 50;
+       if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
+               perror("setrlimit");
+               exit(1);
+       }
+#endif
+
+       event_init();
+
+       for (i = 0; i < 25; i++) {
+               tv = run_once(num_pipes);
+               if (tv == NULL)
+                       exit(1);
+               fprintf(stdout, "%ld\n",
+                       tv->tv_sec * 1000000L + tv->tv_usec);
+       }
+
+       exit(0);
+}
diff --git a/libevent/test/bench_http.c b/libevent/test/bench_http.c
new file mode 100644 (file)
index 0000000..f6fd81b
--- /dev/null
@@ -0,0 +1,191 @@
+/*
+ * Copyright 2008-2012 Niels Provos and Nick Mathewson
+ *
+ * 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.
+ * 4. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+#include <sys/stat.h>
+#ifdef WIN32
+#include <winsock2.h>
+#else
+#include <sys/socket.h>
+#include <sys/resource.h>
+#include <sys/time.h>
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/buffer.h"
+#include "event2/util.h"
+#include "event2/http.h"
+#include "event2/thread.h"
+
+static void http_basic_cb(struct evhttp_request *req, void *arg);
+
+static char *content;
+static size_t content_len = 0;
+
+static void
+http_basic_cb(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *evb = evbuffer_new();
+
+       evbuffer_add(evb, content, content_len);
+
+       /* allow sending of an empty reply */
+       evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+       evbuffer_free(evb);
+}
+
+#if LIBEVENT_VERSION_NUMBER >= 0x02000200
+static void
+http_ref_cb(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *evb = evbuffer_new();
+
+       evbuffer_add_reference(evb, content, content_len, NULL, NULL);
+
+       /* allow sending of an empty reply */
+       evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+       evbuffer_free(evb);
+}
+#endif
+
+int
+main(int argc, char **argv)
+{
+       struct event_config *cfg = event_config_new();
+       struct event_base *base;
+       struct evhttp *http;
+       int i;
+       int c;
+       int use_iocp = 0;
+       unsigned short port = 8080;
+       char *endptr = NULL;
+
+#ifdef WIN32
+       WSADATA WSAData;
+       WSAStartup(0x101, &WSAData);
+#else
+       if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+               return (1);
+#endif
+
+       for (i = 1; i < argc; ++i) {
+               if (*argv[i] != '-')
+                       continue;
+
+               c = argv[i][1];
+
+               if ((c == 'p' || c == 'l') && i + 1 >= argc) {
+                       fprintf(stderr, "-%c requires argument.\n", c);
+                       exit(1);
+               }
+
+               switch (c) {
+               case 'p':
+                       if (i+1 >= argc || !argv[i+1]) {
+                               fprintf(stderr, "Missing port\n");
+                               exit(1);
+                       }
+                       port = (int)strtol(argv[i+1], &endptr, 10);
+                       if (*endptr != '\0') {
+                               fprintf(stderr, "Bad port\n");
+                               exit(1);
+                       }
+                       break;
+               case 'l':
+                       if (i+1 >= argc || !argv[i+1]) {
+                               fprintf(stderr, "Missing content length\n");
+                               exit(1);
+                       }
+                       content_len = (size_t)strtol(argv[i+1], &endptr, 10);
+                       if (*endptr != '\0' || content_len == 0) {
+                               fprintf(stderr, "Bad content length\n");
+                               exit(1);
+                       }
+                       break;
+#ifdef WIN32
+               case 'i':
+                       use_iocp = 1;
+                       evthread_use_windows_threads();
+                       event_config_set_flag(cfg,EVENT_BASE_FLAG_STARTUP_IOCP);
+                       break;
+#endif
+               default:
+                       fprintf(stderr, "Illegal argument \"%c\"\n", c);
+                       exit(1);
+               }
+       }
+
+       base = event_base_new_with_config(cfg);
+       if (!base) {
+               fprintf(stderr, "creating event_base failed. Exiting.\n");
+               return 1;
+       }
+
+       http = evhttp_new(base);
+
+       content = malloc(content_len);
+       if (content == NULL) {
+               fprintf(stderr, "Cannot allocate content\n");
+               exit(1);
+       } else {
+               int i = 0;
+               for (i = 0; i < (int)content_len; ++i)
+                       content[i] = (i & 255);
+       }
+
+       evhttp_set_cb(http, "/ind", http_basic_cb, NULL);
+       fprintf(stderr, "/ind - basic content (memory copy)\n");
+
+#ifdef _EVENT2_EVENT_H_
+       evhttp_set_cb(http, "/ref", http_ref_cb, NULL);
+       fprintf(stderr, "/ref - basic content (reference)\n");
+#endif
+
+       fprintf(stderr, "Serving %d bytes on port %d using %s\n",
+           (int)content_len, port,
+           use_iocp? "IOCP" : event_base_get_method(base));
+
+       evhttp_bind_socket(http, "0.0.0.0", port);
+
+       if (use_iocp) {
+               struct timeval tv={99999999,0};
+               event_base_loopexit(base, &tv);
+       }
+       event_base_dispatch(base);
+
+       /* NOTREACHED */
+       return (0);
+}
diff --git a/libevent/test/bench_httpclient.c b/libevent/test/bench_httpclient.c
new file mode 100644 (file)
index 0000000..cf66753
--- /dev/null
@@ -0,0 +1,222 @@
+/*
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * 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.
+ * 4. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/types.h>
+#ifdef WIN32
+#include <winsock2.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+#  include <arpa/inet.h>
+# endif
+#endif
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/util.h"
+
+/* for EVUTIL_ERR_CONNECT_RETRIABLE macro */
+#include "util-internal.h"
+
+const char *resource = NULL;
+struct event_base *base = NULL;
+
+int total_n_handled = 0;
+int total_n_errors = 0;
+int total_n_launched = 0;
+size_t total_n_bytes = 0;
+struct timeval total_time = {0,0};
+int n_errors = 0;
+
+const int PARALLELISM = 200;
+const int N_REQUESTS = 20000;
+
+struct request_info {
+       size_t n_read;
+       struct timeval started;
+};
+
+static int launch_request(void);
+static void readcb(struct bufferevent *b, void *arg);
+static void errorcb(struct bufferevent *b, short what, void *arg);
+
+static void
+readcb(struct bufferevent *b, void *arg)
+{
+       struct request_info *ri = arg;
+       struct evbuffer *input = bufferevent_get_input(b);
+       size_t n = evbuffer_get_length(input);
+
+       ri->n_read += n;
+       evbuffer_drain(input, n);
+}
+
+static void
+errorcb(struct bufferevent *b, short what, void *arg)
+{
+       struct request_info *ri = arg;
+       struct timeval now, diff;
+       if (what & BEV_EVENT_EOF) {
+               ++total_n_handled;
+               total_n_bytes += ri->n_read;
+               evutil_gettimeofday(&now, NULL);
+               evutil_timersub(&now, &ri->started, &diff);
+               evutil_timeradd(&diff, &total_time, &total_time);
+
+               if (total_n_handled && (total_n_handled%1000)==0)
+                       printf("%d requests done\n",total_n_handled);
+
+               if (total_n_launched < N_REQUESTS) {
+                       if (launch_request() < 0)
+                               perror("Can't launch");
+               }
+       } else {
+               ++total_n_errors;
+               perror("Unexpected error");
+       }
+
+       bufferevent_setcb(b, NULL, NULL, NULL, NULL);
+       free(ri);
+       bufferevent_disable(b, EV_READ|EV_WRITE);
+       bufferevent_free(b);
+}
+
+static void
+frob_socket(evutil_socket_t sock)
+{
+       struct linger l;
+       int one = 1;
+       setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&one, sizeof(one));
+       l.l_onoff = 1;
+       l.l_linger = 0;
+       if (setsockopt(sock, SOL_SOCKET, SO_LINGER, (void*)&l, sizeof(l))<0)
+               perror("setsockopt");
+}
+
+static int
+launch_request(void)
+{
+       evutil_socket_t sock;
+       struct sockaddr_in sin;
+       struct bufferevent *b;
+
+       struct request_info *ri;
+
+       memset(&sin, 0, sizeof(sin));
+
+       ++total_n_launched;
+
+       sin.sin_family = AF_INET;
+       sin.sin_addr.s_addr = htonl(0x7f000001);
+       sin.sin_port = htons(8080);
+       if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
+               return -1;
+       if (evutil_make_socket_nonblocking(sock) < 0)
+               return -1;
+       frob_socket(sock);
+       if (connect(sock, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
+               int e = errno;
+               if (! EVUTIL_ERR_CONNECT_RETRIABLE(e)) {
+                       return -1;
+               }
+       }
+
+       ri = malloc(sizeof(*ri));
+       ri->n_read = 0;
+       evutil_gettimeofday(&ri->started, NULL);
+
+       b = bufferevent_socket_new(base, sock, BEV_OPT_CLOSE_ON_FREE);
+
+       bufferevent_setcb(b, readcb, NULL, errorcb, ri);
+       bufferevent_enable(b, EV_READ|EV_WRITE);
+
+       evbuffer_add_printf(bufferevent_get_output(b),
+           "GET %s HTTP/1.0\r\n\r\n", resource);
+
+       return 0;
+}
+
+
+int
+main(int argc, char **argv)
+{
+       int i;
+       struct timeval start, end, total;
+       long long usec;
+       double throughput;
+       resource = "/ref";
+
+       setvbuf(stdout, NULL, _IONBF, 0);
+
+       base = event_base_new();
+
+       for (i=0; i < PARALLELISM; ++i) {
+               if (launch_request() < 0)
+                       perror("launch");
+       }
+
+       evutil_gettimeofday(&start, NULL);
+
+       event_base_dispatch(base);
+
+       evutil_gettimeofday(&end, NULL);
+       evutil_timersub(&end, &start, &total);
+       usec = total_time.tv_sec * 1000000 + total_time.tv_usec;
+
+       if (!total_n_handled) {
+               puts("Nothing worked.  You probably did something dumb.");
+               return 0;
+       }
+
+
+       throughput = total_n_handled /
+           (total.tv_sec+ ((double)total.tv_usec)/1000000.0);
+
+#ifdef WIN32
+#define I64_FMT "%I64d"
+#define I64_TYP __int64
+#else
+#define I64_FMT "%lld"
+#define I64_TYP long long int
+#endif
+
+       printf("\n%d requests in %d.%06d sec. (%.2f throughput)\n"
+           "Each took about %.02f msec latency\n"
+           I64_FMT "bytes read. %d errors.\n",
+           total_n_handled,
+           (int)total.tv_sec, (int)total.tv_usec,
+           throughput,
+           (double)(usec/1000) / total_n_handled,
+           (I64_TYP)total_n_bytes, n_errors);
+
+       return 0;
+}
diff --git a/libevent/test/regress.c b/libevent/test/regress.c
new file mode 100644 (file)
index 0000000..2d48583
--- /dev/null
@@ -0,0 +1,2406 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/event_compat.h"
+#include "event2/tag.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/util.h"
+#include "event-internal.h"
+#include "evthread-internal.h"
+#include "util-internal.h"
+#include "log-internal.h"
+
+#include "regress.h"
+
+#ifndef WIN32
+#include "regress.gen.h"
+#endif
+
+evutil_socket_t pair[2];
+int test_ok;
+int called;
+struct event_base *global_base;
+
+static char wbuf[4096];
+static char rbuf[4096];
+static int woff;
+static int roff;
+static int usepersist;
+static struct timeval tset;
+static struct timeval tcalled;
+
+
+#define TEST1  "this is a test"
+#define SECONDS        1
+
+#ifndef SHUT_WR
+#define SHUT_WR 1
+#endif
+
+#ifdef WIN32
+#define write(fd,buf,len) send((fd),(buf),(int)(len),0)
+#define read(fd,buf,len) recv((fd),(buf),(int)(len),0)
+#endif
+
+struct basic_cb_args
+{
+       struct event_base *eb;
+       struct event *ev;
+       unsigned int callcount;
+};
+
+static void
+simple_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+       char buf[256];
+       int len;
+
+       len = read(fd, buf, sizeof(buf));
+
+       if (len) {
+               if (!called) {
+                       if (event_add(arg, NULL) == -1)
+                               exit(1);
+               }
+       } else if (called == 1)
+               test_ok = 1;
+
+       called++;
+}
+
+static void
+basic_read_cb(evutil_socket_t fd, short event, void *data)
+{
+       char buf[256];
+       int len;
+       struct basic_cb_args *arg = data;
+
+       len = read(fd, buf, sizeof(buf));
+
+       if (len < 0) {
+               tt_fail_perror("read (callback)");
+       } else {
+               switch (arg->callcount++) {
+               case 0:  /* first call: expect to read data; cycle */
+                       if (len > 0)
+                               return;
+
+                       tt_fail_msg("EOF before data read");
+                       break;
+
+               case 1:  /* second call: expect EOF; stop */
+                       if (len > 0)
+                               tt_fail_msg("not all data read on first cycle");
+                       break;
+
+               default:  /* third call: should not happen */
+                       tt_fail_msg("too many cycles");
+               }
+       }
+
+       event_del(arg->ev);
+       event_base_loopexit(arg->eb, NULL);
+}
+
+static void
+dummy_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+}
+
+static void
+simple_write_cb(evutil_socket_t fd, short event, void *arg)
+{
+       int len;
+
+       len = write(fd, TEST1, strlen(TEST1) + 1);
+       if (len == -1)
+               test_ok = 0;
+       else
+               test_ok = 1;
+}
+
+static void
+multiple_write_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct event *ev = arg;
+       int len;
+
+       len = 128;
+       if (woff + len >= (int)sizeof(wbuf))
+               len = sizeof(wbuf) - woff;
+
+       len = write(fd, wbuf + woff, len);
+       if (len == -1) {
+               fprintf(stderr, "%s: write\n", __func__);
+               if (usepersist)
+                       event_del(ev);
+               return;
+       }
+
+       woff += len;
+
+       if (woff >= (int)sizeof(wbuf)) {
+               shutdown(fd, SHUT_WR);
+               if (usepersist)
+                       event_del(ev);
+               return;
+       }
+
+       if (!usepersist) {
+               if (event_add(ev, NULL) == -1)
+                       exit(1);
+       }
+}
+
+static void
+multiple_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct event *ev = arg;
+       int len;
+
+       len = read(fd, rbuf + roff, sizeof(rbuf) - roff);
+       if (len == -1)
+               fprintf(stderr, "%s: read\n", __func__);
+       if (len <= 0) {
+               if (usepersist)
+                       event_del(ev);
+               return;
+       }
+
+       roff += len;
+       if (!usepersist) {
+               if (event_add(ev, NULL) == -1)
+                       exit(1);
+       }
+}
+
+static void
+timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct timeval tv;
+       int diff;
+
+       evutil_gettimeofday(&tcalled, NULL);
+       if (evutil_timercmp(&tcalled, &tset, >))
+               evutil_timersub(&tcalled, &tset, &tv);
+       else
+               evutil_timersub(&tset, &tcalled, &tv);
+
+       diff = tv.tv_sec*1000 + tv.tv_usec/1000 - SECONDS * 1000;
+       if (diff < 0)
+               diff = -diff;
+
+       if (diff < 100)
+               test_ok = 1;
+}
+
+struct both {
+       struct event ev;
+       int nread;
+};
+
+static void
+combined_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct both *both = arg;
+       char buf[128];
+       int len;
+
+       len = read(fd, buf, sizeof(buf));
+       if (len == -1)
+               fprintf(stderr, "%s: read\n", __func__);
+       if (len <= 0)
+               return;
+
+       both->nread += len;
+       if (event_add(&both->ev, NULL) == -1)
+               exit(1);
+}
+
+static void
+combined_write_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct both *both = arg;
+       char buf[128];
+       int len;
+
+       len = sizeof(buf);
+       if (len > both->nread)
+               len = both->nread;
+
+       memset(buf, 'q', len);
+
+       len = write(fd, buf, len);
+       if (len == -1)
+               fprintf(stderr, "%s: write\n", __func__);
+       if (len <= 0) {
+               shutdown(fd, SHUT_WR);
+               return;
+       }
+
+       both->nread -= len;
+       if (event_add(&both->ev, NULL) == -1)
+               exit(1);
+}
+
+/* These macros used to replicate the work of the legacy test wrapper code */
+#define setup_test(x) do {                                             \
+       if (!in_legacy_test_wrapper) {                                  \
+               TT_FAIL(("Legacy test %s not wrapped properly", x));    \
+               return;                                                 \
+       }                                                               \
+       } while (0)
+#define cleanup_test() setup_test("cleanup")
+
+static void
+test_simpleread(void)
+{
+       struct event ev;
+
+       /* Very simple read test */
+       setup_test("Simple read: ");
+
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
+
+       shutdown(pair[0], SHUT_WR);
+
+       event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
+       if (event_add(&ev, NULL) == -1)
+               exit(1);
+       event_dispatch();
+
+       cleanup_test();
+}
+
+static void
+test_simplewrite(void)
+{
+       struct event ev;
+
+       /* Very simple write test */
+       setup_test("Simple write: ");
+
+       event_set(&ev, pair[0], EV_WRITE, simple_write_cb, &ev);
+       if (event_add(&ev, NULL) == -1)
+               exit(1);
+       event_dispatch();
+
+       cleanup_test();
+}
+
+static void
+simpleread_multiple_cb(evutil_socket_t fd, short event, void *arg)
+{
+       if (++called == 2)
+               test_ok = 1;
+}
+
+static void
+test_simpleread_multiple(void)
+{
+       struct event one, two;
+
+       /* Very simple read test */
+       setup_test("Simple read to multiple evens: ");
+
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
+
+       shutdown(pair[0], SHUT_WR);
+
+       event_set(&one, pair[1], EV_READ, simpleread_multiple_cb, NULL);
+       if (event_add(&one, NULL) == -1)
+               exit(1);
+       event_set(&two, pair[1], EV_READ, simpleread_multiple_cb, NULL);
+       if (event_add(&two, NULL) == -1)
+               exit(1);
+       event_dispatch();
+
+       cleanup_test();
+}
+
+static int have_closed = 0;
+static int premature_event = 0;
+static void
+simpleclose_close_fd_cb(evutil_socket_t s, short what, void *ptr)
+{
+       evutil_socket_t **fds = ptr;
+       TT_BLATHER(("Closing"));
+       evutil_closesocket(*fds[0]);
+       evutil_closesocket(*fds[1]);
+       *fds[0] = -1;
+       *fds[1] = -1;
+       have_closed = 1;
+}
+
+static void
+record_event_cb(evutil_socket_t s, short what, void *ptr)
+{
+       short *whatp = ptr;
+       if (!have_closed)
+               premature_event = 1;
+       *whatp = what;
+       TT_BLATHER(("Recorded %d on socket %d", (int)what, (int)s));
+}
+
+static void
+test_simpleclose(void *ptr)
+{
+       /* Test that a close of FD is detected as a read and as a write. */
+       struct event_base *base = event_base_new();
+       evutil_socket_t pair1[2]={-1,-1}, pair2[2] = {-1, -1};
+       evutil_socket_t *to_close[2];
+       struct event *rev=NULL, *wev=NULL, *closeev=NULL;
+       struct timeval tv;
+       short got_read_on_close = 0, got_write_on_close = 0;
+       char buf[1024];
+       memset(buf, 99, sizeof(buf));
+#ifdef WIN32
+#define LOCAL_SOCKETPAIR_AF AF_INET
+#else
+#define LOCAL_SOCKETPAIR_AF AF_UNIX
+#endif
+       if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, pair1)<0)
+               TT_DIE(("socketpair: %s", strerror(errno)));
+       if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, pair2)<0)
+               TT_DIE(("socketpair: %s", strerror(errno)));
+       if (evutil_make_socket_nonblocking(pair1[1]) < 0)
+               TT_DIE(("make_socket_nonblocking"));
+       if (evutil_make_socket_nonblocking(pair2[1]) < 0)
+               TT_DIE(("make_socket_nonblocking"));
+
+       /** Stuff pair2[1] full of data, until write fails */
+       while (1) {
+               int r = write(pair2[1], buf, sizeof(buf));
+               if (r<0) {
+                       int err = evutil_socket_geterror(pair2[1]);
+                       if (! EVUTIL_ERR_RW_RETRIABLE(err))
+                               TT_DIE(("write failed strangely: %s",
+                                       evutil_socket_error_to_string(err)));
+                       break;
+               }
+       }
+       to_close[0] = &pair1[0];
+       to_close[1] = &pair2[0];
+
+       closeev = event_new(base, -1, EV_TIMEOUT, simpleclose_close_fd_cb,
+           to_close);
+       rev = event_new(base, pair1[1], EV_READ, record_event_cb,
+           &got_read_on_close);
+       TT_BLATHER(("Waiting for read on %d", (int)pair1[1]));
+       wev = event_new(base, pair2[1], EV_WRITE, record_event_cb,
+           &got_write_on_close);
+       TT_BLATHER(("Waiting for write on %d", (int)pair2[1]));
+       tv.tv_sec = 0;
+       tv.tv_usec = 100*1000; /* Close pair1[0] after a little while, and make
+                              * sure we get a read event. */
+       event_add(closeev, &tv);
+       event_add(rev, NULL);
+       event_add(wev, NULL);
+       /* Don't let the test go on too long. */
+       tv.tv_sec = 0;
+       tv.tv_usec = 200*1000;
+       event_base_loopexit(base, &tv);
+       event_base_loop(base, 0);
+
+       tt_int_op(got_read_on_close, ==, EV_READ);
+       tt_int_op(got_write_on_close, ==, EV_WRITE);
+       tt_int_op(premature_event, ==, 0);
+
+end:
+       if (pair1[0] >= 0)
+               evutil_closesocket(pair1[0]);
+       if (pair1[1] >= 0)
+               evutil_closesocket(pair1[1]);
+       if (pair2[0] >= 0)
+               evutil_closesocket(pair2[0]);
+       if (pair2[1] >= 0)
+               evutil_closesocket(pair2[1]);
+       if (rev)
+               event_free(rev);
+       if (wev)
+               event_free(wev);
+       if (closeev)
+               event_free(closeev);
+       if (base)
+               event_base_free(base);
+}
+
+
+static void
+test_multiple(void)
+{
+       struct event ev, ev2;
+       int i;
+
+       /* Multiple read and write test */
+       setup_test("Multiple read/write: ");
+       memset(rbuf, 0, sizeof(rbuf));
+       for (i = 0; i < (int)sizeof(wbuf); i++)
+               wbuf[i] = i;
+
+       roff = woff = 0;
+       usepersist = 0;
+
+       event_set(&ev, pair[0], EV_WRITE, multiple_write_cb, &ev);
+       if (event_add(&ev, NULL) == -1)
+               exit(1);
+       event_set(&ev2, pair[1], EV_READ, multiple_read_cb, &ev2);
+       if (event_add(&ev2, NULL) == -1)
+               exit(1);
+       event_dispatch();
+
+       if (roff == woff)
+               test_ok = memcmp(rbuf, wbuf, sizeof(wbuf)) == 0;
+
+       cleanup_test();
+}
+
+static void
+test_persistent(void)
+{
+       struct event ev, ev2;
+       int i;
+
+       /* Multiple read and write test with persist */
+       setup_test("Persist read/write: ");
+       memset(rbuf, 0, sizeof(rbuf));
+       for (i = 0; i < (int)sizeof(wbuf); i++)
+               wbuf[i] = i;
+
+       roff = woff = 0;
+       usepersist = 1;
+
+       event_set(&ev, pair[0], EV_WRITE|EV_PERSIST, multiple_write_cb, &ev);
+       if (event_add(&ev, NULL) == -1)
+               exit(1);
+       event_set(&ev2, pair[1], EV_READ|EV_PERSIST, multiple_read_cb, &ev2);
+       if (event_add(&ev2, NULL) == -1)
+               exit(1);
+       event_dispatch();
+
+       if (roff == woff)
+               test_ok = memcmp(rbuf, wbuf, sizeof(wbuf)) == 0;
+
+       cleanup_test();
+}
+
+static void
+test_combined(void)
+{
+       struct both r1, r2, w1, w2;
+
+       setup_test("Combined read/write: ");
+       memset(&r1, 0, sizeof(r1));
+       memset(&r2, 0, sizeof(r2));
+       memset(&w1, 0, sizeof(w1));
+       memset(&w2, 0, sizeof(w2));
+
+       w1.nread = 4096;
+       w2.nread = 8192;
+
+       event_set(&r1.ev, pair[0], EV_READ, combined_read_cb, &r1);
+       event_set(&w1.ev, pair[0], EV_WRITE, combined_write_cb, &w1);
+       event_set(&r2.ev, pair[1], EV_READ, combined_read_cb, &r2);
+       event_set(&w2.ev, pair[1], EV_WRITE, combined_write_cb, &w2);
+       tt_assert(event_add(&r1.ev, NULL) != -1);
+       tt_assert(!event_add(&w1.ev, NULL));
+       tt_assert(!event_add(&r2.ev, NULL));
+       tt_assert(!event_add(&w2.ev, NULL));
+       event_dispatch();
+
+       if (r1.nread == 8192 && r2.nread == 4096)
+               test_ok = 1;
+
+end:
+       cleanup_test();
+}
+
+static void
+test_simpletimeout(void)
+{
+       struct timeval tv;
+       struct event ev;
+
+       setup_test("Simple timeout: ");
+
+       tv.tv_usec = 0;
+       tv.tv_sec = SECONDS;
+       evtimer_set(&ev, timeout_cb, NULL);
+       evtimer_add(&ev, &tv);
+
+       evutil_gettimeofday(&tset, NULL);
+       event_dispatch();
+
+       cleanup_test();
+}
+
+static void
+periodic_timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+       int *count = arg;
+
+       (*count)++;
+       if (*count == 6) {
+               /* call loopexit only once - on slow machines(?), it is
+                * apparently possible for this to get called twice. */
+               test_ok = 1;
+               event_base_loopexit(global_base, NULL);
+       }
+}
+
+static void
+test_persistent_timeout(void)
+{
+       struct timeval tv;
+       struct event ev;
+       int count = 0;
+
+       evutil_timerclear(&tv);
+       tv.tv_usec = 10000;
+
+       event_assign(&ev, global_base, -1, EV_TIMEOUT|EV_PERSIST,
+           periodic_timeout_cb, &count);
+       event_add(&ev, &tv);
+
+       event_dispatch();
+
+       event_del(&ev);
+}
+
+struct persist_active_timeout_called {
+       int n;
+       short events[16];
+       struct timeval tvs[16];
+};
+
+static void
+activate_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct event *ev = arg;
+       event_active(ev, EV_READ, 1);
+}
+
+static void
+persist_active_timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct persist_active_timeout_called *c = arg;
+       if (c->n < 15) {
+               c->events[c->n] = event;
+               evutil_gettimeofday(&c->tvs[c->n], NULL);
+               ++c->n;
+       }
+}
+
+static void
+test_persistent_active_timeout(void *ptr)
+{
+       struct timeval tv, tv2, tv_exit, start;
+       struct event ev;
+       struct persist_active_timeout_called res;
+
+       struct basic_test_data *data = ptr;
+       struct event_base *base = data->base;
+
+       memset(&res, 0, sizeof(res));
+
+       tv.tv_sec = 0;
+       tv.tv_usec = 200 * 1000;
+       event_assign(&ev, base, -1, EV_TIMEOUT|EV_PERSIST,
+           persist_active_timeout_cb, &res);
+       event_add(&ev, &tv);
+
+       tv2.tv_sec = 0;
+       tv2.tv_usec = 100 * 1000;
+       event_base_once(base, -1, EV_TIMEOUT, activate_cb, &ev, &tv2);
+
+       tv_exit.tv_sec = 0;
+       tv_exit.tv_usec = 600 * 1000;
+       event_base_loopexit(base, &tv_exit);
+
+       event_base_assert_ok(base);
+       evutil_gettimeofday(&start, NULL);
+
+       event_base_dispatch(base);
+       event_base_assert_ok(base);
+
+       tt_int_op(res.n, ==, 3);
+       tt_int_op(res.events[0], ==, EV_READ);
+       tt_int_op(res.events[1], ==, EV_TIMEOUT);
+       tt_int_op(res.events[2], ==, EV_TIMEOUT);
+       test_timeval_diff_eq(&start, &res.tvs[0], 100);
+       test_timeval_diff_eq(&start, &res.tvs[1], 300);
+       test_timeval_diff_eq(&start, &res.tvs[2], 500);
+end:
+       event_del(&ev);
+}
+
+struct common_timeout_info {
+       struct event ev;
+       struct timeval called_at;
+       int which;
+       int count;
+};
+
+static void
+common_timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct common_timeout_info *ti = arg;
+       ++ti->count;
+       evutil_gettimeofday(&ti->called_at, NULL);
+       if (ti->count >= 6)
+               event_del(&ti->ev);
+}
+
+static void
+test_common_timeout(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+
+       struct event_base *base = data->base;
+       int i;
+       struct common_timeout_info info[100];
+
+       struct timeval now;
+       struct timeval tmp_100_ms = { 0, 100*1000 };
+       struct timeval tmp_200_ms = { 0, 200*1000 };
+
+       const struct timeval *ms_100, *ms_200;
+
+       ms_100 = event_base_init_common_timeout(base, &tmp_100_ms);
+       ms_200 = event_base_init_common_timeout(base, &tmp_200_ms);
+       tt_assert(ms_100);
+       tt_assert(ms_200);
+       tt_ptr_op(event_base_init_common_timeout(base, &tmp_200_ms),
+           ==, ms_200);
+       tt_int_op(ms_100->tv_sec, ==, 0);
+       tt_int_op(ms_200->tv_sec, ==, 0);
+       tt_int_op(ms_100->tv_usec, ==, 100000|0x50000000);
+       tt_int_op(ms_200->tv_usec, ==, 200000|0x50100000);
+
+       memset(info, 0, sizeof(info));
+
+       for (i=0; i<100; ++i) {
+               info[i].which = i;
+               event_assign(&info[i].ev, base, -1, EV_TIMEOUT|EV_PERSIST,
+                   common_timeout_cb, &info[i]);
+               if (i % 2) {
+                       event_add(&info[i].ev, ms_100);
+               } else {
+                       event_add(&info[i].ev, ms_200);
+               }
+       }
+
+       event_base_assert_ok(base);
+       event_base_dispatch(base);
+
+       evutil_gettimeofday(&now, NULL);
+       event_base_assert_ok(base);
+
+       for (i=0; i<10; ++i) {
+               struct timeval tmp;
+               int ms_diff;
+               tt_int_op(info[i].count, ==, 6);
+               evutil_timersub(&now, &info[i].called_at, &tmp);
+               ms_diff = tmp.tv_usec/1000 + tmp.tv_sec*1000;
+               if (i % 2) {
+                       tt_int_op(ms_diff, >, 500);
+                       tt_int_op(ms_diff, <, 700);
+               } else {
+                       tt_int_op(ms_diff, >, -100);
+                       tt_int_op(ms_diff, <, 100);
+               }
+       }
+
+       /* Make sure we can free the base with some events in. */
+       for (i=0; i<100; ++i) {
+               if (i % 2) {
+                       event_add(&info[i].ev, ms_100);
+               } else {
+                       event_add(&info[i].ev, ms_200);
+               }
+       }
+
+end:
+       event_base_free(data->base); /* need to do this here before info is
+                                     * out-of-scope */
+       data->base = NULL;
+}
+
+#ifndef WIN32
+static void signal_cb(evutil_socket_t fd, short event, void *arg);
+
+#define current_base event_global_current_base_
+extern struct event_base *current_base;
+
+static void
+child_signal_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct timeval tv;
+       int *pint = arg;
+
+       *pint = 1;
+
+       tv.tv_usec = 500000;
+       tv.tv_sec = 0;
+       event_loopexit(&tv);
+}
+
+static void
+test_fork(void)
+{
+       int status, got_sigchld = 0;
+       struct event ev, sig_ev;
+       pid_t pid;
+
+       setup_test("After fork: ");
+
+       tt_assert(current_base);
+       evthread_make_base_notifiable(current_base);
+
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
+
+       event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
+       if (event_add(&ev, NULL) == -1)
+               exit(1);
+
+       evsignal_set(&sig_ev, SIGCHLD, child_signal_cb, &got_sigchld);
+       evsignal_add(&sig_ev, NULL);
+
+       event_base_assert_ok(current_base);
+       TT_BLATHER(("Before fork"));
+       if ((pid = fork()) == 0) {
+               /* in the child */
+               TT_BLATHER(("In child, before reinit"));
+               event_base_assert_ok(current_base);
+               if (event_reinit(current_base) == -1) {
+                       fprintf(stdout, "FAILED (reinit)\n");
+                       exit(1);
+               }
+               TT_BLATHER(("After reinit"));
+               event_base_assert_ok(current_base);
+               TT_BLATHER(("After assert-ok"));
+
+               evsignal_del(&sig_ev);
+
+               called = 0;
+
+               event_dispatch();
+
+               event_base_free(current_base);
+
+               /* we do not send an EOF; simple_read_cb requires an EOF
+                * to set test_ok.  we just verify that the callback was
+                * called. */
+               exit(test_ok != 0 || called != 2 ? -2 : 76);
+       }
+
+       /* wait for the child to read the data */
+       sleep(1);
+
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
+
+       TT_BLATHER(("Before waitpid"));
+       if (waitpid(pid, &status, 0) == -1) {
+               fprintf(stdout, "FAILED (fork)\n");
+               exit(1);
+       }
+       TT_BLATHER(("After waitpid"));
+
+       if (WEXITSTATUS(status) != 76) {
+               fprintf(stdout, "FAILED (exit): %d\n", WEXITSTATUS(status));
+               exit(1);
+       }
+
+       /* test that the current event loop still works */
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               fprintf(stderr, "%s: write\n", __func__);
+       }
+
+       shutdown(pair[0], SHUT_WR);
+
+       event_dispatch();
+
+       if (!got_sigchld) {
+               fprintf(stdout, "FAILED (sigchld)\n");
+               exit(1);
+       }
+
+       evsignal_del(&sig_ev);
+
+       end:
+       cleanup_test();
+}
+
+static void
+signal_cb_sa(int sig)
+{
+       test_ok = 2;
+}
+
+static void
+signal_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct event *ev = arg;
+
+       evsignal_del(ev);
+       test_ok = 1;
+}
+
+static void
+test_simplesignal(void)
+{
+       struct event ev;
+       struct itimerval itv;
+
+       setup_test("Simple signal: ");
+       evsignal_set(&ev, SIGALRM, signal_cb, &ev);
+       evsignal_add(&ev, NULL);
+       /* find bugs in which operations are re-ordered */
+       evsignal_del(&ev);
+       evsignal_add(&ev, NULL);
+
+       memset(&itv, 0, sizeof(itv));
+       itv.it_value.tv_sec = 1;
+       if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
+               goto skip_simplesignal;
+
+       event_dispatch();
+ skip_simplesignal:
+       if (evsignal_del(&ev) == -1)
+               test_ok = 0;
+
+       cleanup_test();
+}
+
+static void
+test_multiplesignal(void)
+{
+       struct event ev_one, ev_two;
+       struct itimerval itv;
+
+       setup_test("Multiple signal: ");
+
+       evsignal_set(&ev_one, SIGALRM, signal_cb, &ev_one);
+       evsignal_add(&ev_one, NULL);
+
+       evsignal_set(&ev_two, SIGALRM, signal_cb, &ev_two);
+       evsignal_add(&ev_two, NULL);
+
+       memset(&itv, 0, sizeof(itv));
+       itv.it_value.tv_sec = 1;
+       if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
+               goto skip_simplesignal;
+
+       event_dispatch();
+
+ skip_simplesignal:
+       if (evsignal_del(&ev_one) == -1)
+               test_ok = 0;
+       if (evsignal_del(&ev_two) == -1)
+               test_ok = 0;
+
+       cleanup_test();
+}
+
+static void
+test_immediatesignal(void)
+{
+       struct event ev;
+
+       test_ok = 0;
+       evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
+       evsignal_add(&ev, NULL);
+       raise(SIGUSR1);
+       event_loop(EVLOOP_NONBLOCK);
+       evsignal_del(&ev);
+       cleanup_test();
+}
+
+static void
+test_signal_dealloc(void)
+{
+       /* make sure that evsignal_event is event_del'ed and pipe closed */
+       struct event ev;
+       struct event_base *base = event_init();
+       evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
+       evsignal_add(&ev, NULL);
+       evsignal_del(&ev);
+       event_base_free(base);
+       /* If we got here without asserting, we're fine. */
+       test_ok = 1;
+       cleanup_test();
+}
+
+static void
+test_signal_pipeloss(void)
+{
+       /* make sure that the base1 pipe is closed correctly. */
+       struct event_base *base1, *base2;
+       int pipe1;
+       test_ok = 0;
+       base1 = event_init();
+       pipe1 = base1->sig.ev_signal_pair[0];
+       base2 = event_init();
+       event_base_free(base2);
+       event_base_free(base1);
+       if (close(pipe1) != -1 || errno!=EBADF) {
+               /* fd must be closed, so second close gives -1, EBADF */
+               printf("signal pipe not closed. ");
+               test_ok = 0;
+       } else {
+               test_ok = 1;
+       }
+       cleanup_test();
+}
+
+/*
+ * make two bases to catch signals, use both of them.  this only works
+ * for event mechanisms that use our signal pipe trick.         kqueue handles
+ * signals internally, and all interested kqueues get all the signals.
+ */
+static void
+test_signal_switchbase(void)
+{
+       struct event ev1, ev2;
+       struct event_base *base1, *base2;
+       int is_kqueue;
+       test_ok = 0;
+       base1 = event_init();
+       base2 = event_init();
+       is_kqueue = !strcmp(event_get_method(),"kqueue");
+       evsignal_set(&ev1, SIGUSR1, signal_cb, &ev1);
+       evsignal_set(&ev2, SIGUSR1, signal_cb, &ev2);
+       if (event_base_set(base1, &ev1) ||
+           event_base_set(base2, &ev2) ||
+           event_add(&ev1, NULL) ||
+           event_add(&ev2, NULL)) {
+               fprintf(stderr, "%s: cannot set base, add\n", __func__);
+               exit(1);
+       }
+
+       tt_ptr_op(event_get_base(&ev1), ==, base1);
+       tt_ptr_op(event_get_base(&ev2), ==, base2);
+
+       test_ok = 0;
+       /* can handle signal before loop is called */
+       raise(SIGUSR1);
+       event_base_loop(base2, EVLOOP_NONBLOCK);
+       if (is_kqueue) {
+               if (!test_ok)
+                       goto end;
+               test_ok = 0;
+       }
+       event_base_loop(base1, EVLOOP_NONBLOCK);
+       if (test_ok && !is_kqueue) {
+               test_ok = 0;
+
+               /* set base1 to handle signals */
+               event_base_loop(base1, EVLOOP_NONBLOCK);
+               raise(SIGUSR1);
+               event_base_loop(base1, EVLOOP_NONBLOCK);
+               event_base_loop(base2, EVLOOP_NONBLOCK);
+       }
+end:
+       event_base_free(base1);
+       event_base_free(base2);
+       cleanup_test();
+}
+
+/*
+ * assert that a signal event removed from the event queue really is
+ * removed - with no possibility of it's parent handler being fired.
+ */
+static void
+test_signal_assert(void)
+{
+       struct event ev;
+       struct event_base *base = event_init();
+       test_ok = 0;
+       /* use SIGCONT so we don't kill ourselves when we signal to nowhere */
+       evsignal_set(&ev, SIGCONT, signal_cb, &ev);
+       evsignal_add(&ev, NULL);
+       /*
+        * if evsignal_del() fails to reset the handler, it's current handler
+        * will still point to evsig_handler().
+        */
+       evsignal_del(&ev);
+
+       raise(SIGCONT);
+#if 0
+       /* only way to verify we were in evsig_handler() */
+       /* XXXX Now there's no longer a good way. */
+       if (base->sig.evsig_caught)
+               test_ok = 0;
+       else
+               test_ok = 1;
+#else
+       test_ok = 1;
+#endif
+
+       event_base_free(base);
+       cleanup_test();
+       return;
+}
+
+/*
+ * assert that we restore our previous signal handler properly.
+ */
+static void
+test_signal_restore(void)
+{
+       struct event ev;
+       struct event_base *base = event_init();
+#ifdef _EVENT_HAVE_SIGACTION
+       struct sigaction sa;
+#endif
+
+       test_ok = 0;
+#ifdef _EVENT_HAVE_SIGACTION
+       sa.sa_handler = signal_cb_sa;
+       sa.sa_flags = 0x0;
+       sigemptyset(&sa.sa_mask);
+       if (sigaction(SIGUSR1, &sa, NULL) == -1)
+               goto out;
+#else
+       if (signal(SIGUSR1, signal_cb_sa) == SIG_ERR)
+               goto out;
+#endif
+       evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
+       evsignal_add(&ev, NULL);
+       evsignal_del(&ev);
+
+       raise(SIGUSR1);
+       /* 1 == signal_cb, 2 == signal_cb_sa, we want our previous handler */
+       if (test_ok != 2)
+               test_ok = 0;
+out:
+       event_base_free(base);
+       cleanup_test();
+       return;
+}
+
+static void
+signal_cb_swp(int sig, short event, void *arg)
+{
+       called++;
+       if (called < 5)
+               raise(sig);
+       else
+               event_loopexit(NULL);
+}
+static void
+timeout_cb_swp(evutil_socket_t fd, short event, void *arg)
+{
+       if (called == -1) {
+               struct timeval tv = {5, 0};
+
+               called = 0;
+               evtimer_add((struct event *)arg, &tv);
+               raise(SIGUSR1);
+               return;
+       }
+       test_ok = 0;
+       event_loopexit(NULL);
+}
+
+static void
+test_signal_while_processing(void)
+{
+       struct event_base *base = event_init();
+       struct event ev, ev_timer;
+       struct timeval tv = {0, 0};
+
+       setup_test("Receiving a signal while processing other signal: ");
+
+       called = -1;
+       test_ok = 1;
+       signal_set(&ev, SIGUSR1, signal_cb_swp, NULL);
+       signal_add(&ev, NULL);
+       evtimer_set(&ev_timer, timeout_cb_swp, &ev_timer);
+       evtimer_add(&ev_timer, &tv);
+       event_dispatch();
+
+       event_base_free(base);
+       cleanup_test();
+       return;
+}
+#endif
+
+static void
+test_free_active_base(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event_base *base1;
+       struct event ev1;
+
+       base1 = event_init();
+       if (base1) {
+               event_assign(&ev1, base1, data->pair[1], EV_READ,
+                            dummy_read_cb, NULL);
+               event_add(&ev1, NULL);
+               event_base_free(base1);  /* should not crash */
+       } else {
+               tt_fail_msg("failed to create event_base for test");
+       }
+
+       base1 = event_init();
+       tt_assert(base1);
+       event_assign(&ev1, base1, 0, 0, dummy_read_cb, NULL);
+       event_active(&ev1, EV_READ, 1);
+       event_base_free(base1);
+end:
+       ;
+}
+
+static void
+test_manipulate_active_events(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event_base *base = data->base;
+       struct event ev1;
+
+       event_assign(&ev1, base, -1, EV_TIMEOUT, dummy_read_cb, NULL);
+
+       /* Make sure an active event is pending. */
+       event_active(&ev1, EV_READ, 1);
+       tt_int_op(event_pending(&ev1, EV_READ|EV_TIMEOUT|EV_WRITE, NULL),
+           ==, EV_READ);
+
+       /* Make sure that activating an event twice works. */
+       event_active(&ev1, EV_WRITE, 1);
+       tt_int_op(event_pending(&ev1, EV_READ|EV_TIMEOUT|EV_WRITE, NULL),
+           ==, EV_READ|EV_WRITE);
+
+end:
+       event_del(&ev1);
+}
+
+static void
+test_bad_assign(void *ptr)
+{
+       struct event ev;
+       int r;
+       /* READ|SIGNAL is not allowed */
+       r = event_assign(&ev, NULL, -1, EV_SIGNAL|EV_READ, dummy_read_cb, NULL);
+       tt_int_op(r,==,-1);
+
+end:
+       ;
+}
+
+static int reentrant_cb_run = 0;
+
+static void
+bad_reentrant_run_loop_cb(evutil_socket_t fd, short what, void *ptr)
+{
+       struct event_base *base = ptr;
+       int r;
+       reentrant_cb_run = 1;
+       /* This reentrant call to event_base_loop should be detected and
+        * should fail */
+       r = event_base_loop(base, 0);
+       tt_int_op(r, ==, -1);
+end:
+       ;
+}
+
+static void
+test_bad_reentrant(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event_base *base = data->base;
+       struct event ev;
+       int r;
+       event_assign(&ev, base, -1,
+           0, bad_reentrant_run_loop_cb, base);
+
+       event_active(&ev, EV_WRITE, 1);
+       r = event_base_loop(base, 0);
+       tt_int_op(r, ==, 1);
+       tt_int_op(reentrant_cb_run, ==, 1);
+end:
+       ;
+}
+
+static void
+test_event_base_new(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event_base *base = 0;
+       struct event ev1;
+       struct basic_cb_args args;
+
+       int towrite = (int)strlen(TEST1)+1;
+       int len = write(data->pair[0], TEST1, towrite);
+
+       if (len < 0)
+               tt_abort_perror("initial write");
+       else if (len != towrite)
+               tt_abort_printf(("initial write fell short (%d of %d bytes)",
+                                len, towrite));
+
+       if (shutdown(data->pair[0], SHUT_WR))
+               tt_abort_perror("initial write shutdown");
+
+       base = event_base_new();
+       if (!base)
+               tt_abort_msg("failed to create event base");
+
+       args.eb = base;
+       args.ev = &ev1;
+       args.callcount = 0;
+       event_assign(&ev1, base, data->pair[1],
+                    EV_READ|EV_PERSIST, basic_read_cb, &args);
+
+       if (event_add(&ev1, NULL))
+               tt_abort_perror("initial event_add");
+
+       if (event_base_loop(base, 0))
+               tt_abort_msg("unsuccessful exit from event loop");
+
+end:
+       if (base)
+               event_base_free(base);
+}
+
+static void
+test_loopexit(void)
+{
+       struct timeval tv, tv_start, tv_end;
+       struct event ev;
+
+       setup_test("Loop exit: ");
+
+       tv.tv_usec = 0;
+       tv.tv_sec = 60*60*24;
+       evtimer_set(&ev, timeout_cb, NULL);
+       evtimer_add(&ev, &tv);
+
+       tv.tv_usec = 0;
+       tv.tv_sec = 1;
+       event_loopexit(&tv);
+
+       evutil_gettimeofday(&tv_start, NULL);
+       event_dispatch();
+       evutil_gettimeofday(&tv_end, NULL);
+       evutil_timersub(&tv_end, &tv_start, &tv_end);
+
+       evtimer_del(&ev);
+
+       tt_assert(event_base_got_exit(global_base));
+       tt_assert(!event_base_got_break(global_base));
+
+       if (tv.tv_sec < 2)
+               test_ok = 1;
+
+end:
+       cleanup_test();
+}
+
+static void
+test_loopexit_multiple(void)
+{
+       struct timeval tv;
+       struct event_base *base;
+
+       setup_test("Loop Multiple exit: ");
+
+       base = event_base_new();
+
+       tv.tv_usec = 0;
+       tv.tv_sec = 1;
+       event_base_loopexit(base, &tv);
+
+       tv.tv_usec = 0;
+       tv.tv_sec = 2;
+       event_base_loopexit(base, &tv);
+
+       event_base_dispatch(base);
+
+       tt_assert(event_base_got_exit(base));
+       tt_assert(!event_base_got_break(base));
+
+       event_base_free(base);
+
+       test_ok = 1;
+
+end:
+       cleanup_test();
+}
+
+static void
+break_cb(evutil_socket_t fd, short events, void *arg)
+{
+       test_ok = 1;
+       event_loopbreak();
+}
+
+static void
+fail_cb(evutil_socket_t fd, short events, void *arg)
+{
+       test_ok = 0;
+}
+
+static void
+test_loopbreak(void)
+{
+       struct event ev1, ev2;
+       struct timeval tv;
+
+       setup_test("Loop break: ");
+
+       tv.tv_sec = 0;
+       tv.tv_usec = 0;
+       evtimer_set(&ev1, break_cb, NULL);
+       evtimer_add(&ev1, &tv);
+       evtimer_set(&ev2, fail_cb, NULL);
+       evtimer_add(&ev2, &tv);
+
+       event_dispatch();
+
+       tt_assert(!event_base_got_exit(global_base));
+       tt_assert(event_base_got_break(global_base));
+
+       evtimer_del(&ev1);
+       evtimer_del(&ev2);
+
+end:
+       cleanup_test();
+}
+
+static struct event *readd_test_event_last_added = NULL;
+static void
+re_add_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+       char buf[256];
+       struct event *ev_other = arg;
+       readd_test_event_last_added = ev_other;
+
+       if (read(fd, buf, sizeof(buf)) < 0) {
+               tt_fail_perror("read");
+       }
+
+       event_add(ev_other, NULL);
+       ++test_ok;
+}
+
+static void
+test_nonpersist_readd(void)
+{
+       struct event ev1, ev2;
+
+       setup_test("Re-add nonpersistent events: ");
+       event_set(&ev1, pair[0], EV_READ, re_add_read_cb, &ev2);
+       event_set(&ev2, pair[1], EV_READ, re_add_read_cb, &ev1);
+
+       if (write(pair[0], "Hello", 5) < 0) {
+               tt_fail_perror("write(pair[0])");
+       }
+
+       if (write(pair[1], "Hello", 5) < 0) {
+               tt_fail_perror("write(pair[1])\n");
+       }
+
+       if (event_add(&ev1, NULL) == -1 ||
+           event_add(&ev2, NULL) == -1) {
+               test_ok = 0;
+       }
+       if (test_ok != 0)
+               exit(1);
+       event_loop(EVLOOP_ONCE);
+       if (test_ok != 2)
+               exit(1);
+       /* At this point, we executed both callbacks.  Whichever one got
+        * called first added the second, but the second then immediately got
+        * deleted before its callback was called.  At this point, though, it
+        * re-added the first.
+        */
+       if (!readd_test_event_last_added) {
+               test_ok = 0;
+       } else if (readd_test_event_last_added == &ev1) {
+               if (!event_pending(&ev1, EV_READ, NULL) ||
+                   event_pending(&ev2, EV_READ, NULL))
+                       test_ok = 0;
+       } else {
+               if (event_pending(&ev1, EV_READ, NULL) ||
+                   !event_pending(&ev2, EV_READ, NULL))
+                       test_ok = 0;
+       }
+
+       event_del(&ev1);
+       event_del(&ev2);
+
+       cleanup_test();
+}
+
+struct test_pri_event {
+       struct event ev;
+       int count;
+};
+
+static void
+test_priorities_cb(evutil_socket_t fd, short what, void *arg)
+{
+       struct test_pri_event *pri = arg;
+       struct timeval tv;
+
+       if (pri->count == 3) {
+               event_loopexit(NULL);
+               return;
+       }
+
+       pri->count++;
+
+       evutil_timerclear(&tv);
+       event_add(&pri->ev, &tv);
+}
+
+static void
+test_priorities_impl(int npriorities)
+{
+       struct test_pri_event one, two;
+       struct timeval tv;
+
+       TT_BLATHER(("Testing Priorities %d: ", npriorities));
+
+       event_base_priority_init(global_base, npriorities);
+
+       memset(&one, 0, sizeof(one));
+       memset(&two, 0, sizeof(two));
+
+       timeout_set(&one.ev, test_priorities_cb, &one);
+       if (event_priority_set(&one.ev, 0) == -1) {
+               fprintf(stderr, "%s: failed to set priority", __func__);
+               exit(1);
+       }
+
+       timeout_set(&two.ev, test_priorities_cb, &two);
+       if (event_priority_set(&two.ev, npriorities - 1) == -1) {
+               fprintf(stderr, "%s: failed to set priority", __func__);
+               exit(1);
+       }
+
+       evutil_timerclear(&tv);
+
+       if (event_add(&one.ev, &tv) == -1)
+               exit(1);
+       if (event_add(&two.ev, &tv) == -1)
+               exit(1);
+
+       event_dispatch();
+
+       event_del(&one.ev);
+       event_del(&two.ev);
+
+       if (npriorities == 1) {
+               if (one.count == 3 && two.count == 3)
+                       test_ok = 1;
+       } else if (npriorities == 2) {
+               /* Two is called once because event_loopexit is priority 1 */
+               if (one.count == 3 && two.count == 1)
+                       test_ok = 1;
+       } else {
+               if (one.count == 3 && two.count == 0)
+                       test_ok = 1;
+       }
+}
+
+static void
+test_priorities(void)
+{
+       test_priorities_impl(1);
+       if (test_ok)
+               test_priorities_impl(2);
+       if (test_ok)
+               test_priorities_impl(3);
+}
+
+
+static void
+test_multiple_cb(evutil_socket_t fd, short event, void *arg)
+{
+       if (event & EV_READ)
+               test_ok |= 1;
+       else if (event & EV_WRITE)
+               test_ok |= 2;
+}
+
+static void
+test_multiple_events_for_same_fd(void)
+{
+   struct event e1, e2;
+
+   setup_test("Multiple events for same fd: ");
+
+   event_set(&e1, pair[0], EV_READ, test_multiple_cb, NULL);
+   event_add(&e1, NULL);
+   event_set(&e2, pair[0], EV_WRITE, test_multiple_cb, NULL);
+   event_add(&e2, NULL);
+   event_loop(EVLOOP_ONCE);
+   event_del(&e2);
+
+   if (write(pair[1], TEST1, strlen(TEST1)+1) < 0) {
+          tt_fail_perror("write");
+   }
+
+   event_loop(EVLOOP_ONCE);
+   event_del(&e1);
+
+   if (test_ok != 3)
+          test_ok = 0;
+
+   cleanup_test();
+}
+
+int evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf);
+int evtag_decode_int64(ev_uint64_t *pnumber, struct evbuffer *evbuf);
+int evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t number);
+int evtag_decode_tag(ev_uint32_t *pnumber, struct evbuffer *evbuf);
+
+static void
+read_once_cb(evutil_socket_t fd, short event, void *arg)
+{
+       char buf[256];
+       int len;
+
+       len = read(fd, buf, sizeof(buf));
+
+       if (called) {
+               test_ok = 0;
+       } else if (len) {
+               /* Assumes global pair[0] can be used for writing */
+               if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+                       tt_fail_perror("write");
+                       test_ok = 0;
+               } else {
+                       test_ok = 1;
+               }
+       }
+
+       called++;
+}
+
+static void
+test_want_only_once(void)
+{
+       struct event ev;
+       struct timeval tv;
+
+       /* Very simple read test */
+       setup_test("Want read only once: ");
+
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
+
+       /* Setup the loop termination */
+       evutil_timerclear(&tv);
+       tv.tv_sec = 1;
+       event_loopexit(&tv);
+
+       event_set(&ev, pair[1], EV_READ, read_once_cb, &ev);
+       if (event_add(&ev, NULL) == -1)
+               exit(1);
+       event_dispatch();
+
+       cleanup_test();
+}
+
+#define TEST_MAX_INT   6
+
+static void
+evtag_int_test(void *ptr)
+{
+       struct evbuffer *tmp = evbuffer_new();
+       ev_uint32_t integers[TEST_MAX_INT] = {
+               0xaf0, 0x1000, 0x1, 0xdeadbeef, 0x00, 0xbef000
+       };
+       ev_uint32_t integer;
+       ev_uint64_t big_int;
+       int i;
+
+       evtag_init();
+
+       for (i = 0; i < TEST_MAX_INT; i++) {
+               int oldlen, newlen;
+               oldlen = (int)EVBUFFER_LENGTH(tmp);
+               evtag_encode_int(tmp, integers[i]);
+               newlen = (int)EVBUFFER_LENGTH(tmp);
+               TT_BLATHER(("encoded 0x%08x with %d bytes",
+                       (unsigned)integers[i], newlen - oldlen));
+               big_int = integers[i];
+               big_int *= 1000000000; /* 1 billion */
+               evtag_encode_int64(tmp, big_int);
+       }
+
+       for (i = 0; i < TEST_MAX_INT; i++) {
+               tt_int_op(evtag_decode_int(&integer, tmp), !=, -1);
+               tt_uint_op(integer, ==, integers[i]);
+               tt_int_op(evtag_decode_int64(&big_int, tmp), !=, -1);
+               tt_assert((big_int / 1000000000) == integers[i]);
+       }
+
+       tt_uint_op(EVBUFFER_LENGTH(tmp), ==, 0);
+end:
+       evbuffer_free(tmp);
+}
+
+static void
+evtag_fuzz(void *ptr)
+{
+       u_char buffer[4096];
+       struct evbuffer *tmp = evbuffer_new();
+       struct timeval tv;
+       int i, j;
+
+       int not_failed = 0;
+
+       evtag_init();
+
+       for (j = 0; j < 100; j++) {
+               for (i = 0; i < (int)sizeof(buffer); i++)
+                       buffer[i] = rand();
+               evbuffer_drain(tmp, -1);
+               evbuffer_add(tmp, buffer, sizeof(buffer));
+
+               if (evtag_unmarshal_timeval(tmp, 0, &tv) != -1)
+                       not_failed++;
+       }
+
+       /* The majority of decodes should fail */
+       tt_int_op(not_failed, <, 10);
+
+       /* Now insert some corruption into the tag length field */
+       evbuffer_drain(tmp, -1);
+       evutil_timerclear(&tv);
+       tv.tv_sec = 1;
+       evtag_marshal_timeval(tmp, 0, &tv);
+       evbuffer_add(tmp, buffer, sizeof(buffer));
+
+       ((char *)EVBUFFER_DATA(tmp))[1] = '\xff';
+       if (evtag_unmarshal_timeval(tmp, 0, &tv) != -1) {
+               tt_abort_msg("evtag_unmarshal_timeval should have failed");
+       }
+
+end:
+       evbuffer_free(tmp);
+}
+
+static void
+evtag_tag_encoding(void *ptr)
+{
+       struct evbuffer *tmp = evbuffer_new();
+       ev_uint32_t integers[TEST_MAX_INT] = {
+               0xaf0, 0x1000, 0x1, 0xdeadbeef, 0x00, 0xbef000
+       };
+       ev_uint32_t integer;
+       int i;
+
+       evtag_init();
+
+       for (i = 0; i < TEST_MAX_INT; i++) {
+               int oldlen, newlen;
+               oldlen = (int)EVBUFFER_LENGTH(tmp);
+               evtag_encode_tag(tmp, integers[i]);
+               newlen = (int)EVBUFFER_LENGTH(tmp);
+               TT_BLATHER(("encoded 0x%08x with %d bytes",
+                       (unsigned)integers[i], newlen - oldlen));
+       }
+
+       for (i = 0; i < TEST_MAX_INT; i++) {
+               tt_int_op(evtag_decode_tag(&integer, tmp), !=, -1);
+               tt_uint_op(integer, ==, integers[i]);
+       }
+
+       tt_uint_op(EVBUFFER_LENGTH(tmp), ==, 0);
+
+end:
+       evbuffer_free(tmp);
+}
+
+static void
+evtag_test_peek(void *ptr)
+{
+       struct evbuffer *tmp = evbuffer_new();
+       ev_uint32_t u32;
+
+       evtag_marshal_int(tmp, 30, 0);
+       evtag_marshal_string(tmp, 40, "Hello world");
+
+       tt_int_op(evtag_peek(tmp, &u32), ==, 1);
+       tt_int_op(u32, ==, 30);
+       tt_int_op(evtag_peek_length(tmp, &u32), ==, 0);
+       tt_int_op(u32, ==, 1+1+1);
+       tt_int_op(evtag_consume(tmp), ==, 0);
+
+       tt_int_op(evtag_peek(tmp, &u32), ==, 1);
+       tt_int_op(u32, ==, 40);
+       tt_int_op(evtag_peek_length(tmp, &u32), ==, 0);
+       tt_int_op(u32, ==, 1+1+11);
+       tt_int_op(evtag_payload_length(tmp, &u32), ==, 0);
+       tt_int_op(u32, ==, 11);
+
+end:
+       evbuffer_free(tmp);
+}
+
+
+static void
+test_methods(void *ptr)
+{
+       const char **methods = event_get_supported_methods();
+       struct event_config *cfg = NULL;
+       struct event_base *base = NULL;
+       const char *backend;
+       int n_methods = 0;
+
+       tt_assert(methods);
+
+       backend = methods[0];
+       while (*methods != NULL) {
+               TT_BLATHER(("Support method: %s", *methods));
+               ++methods;
+               ++n_methods;
+       }
+
+       cfg = event_config_new();
+       assert(cfg != NULL);
+
+       tt_int_op(event_config_avoid_method(cfg, backend), ==, 0);
+       event_config_set_flag(cfg, EVENT_BASE_FLAG_IGNORE_ENV);
+
+       base = event_base_new_with_config(cfg);
+       if (n_methods > 1) {
+               tt_assert(base);
+               tt_str_op(backend, !=, event_base_get_method(base));
+       } else {
+               tt_assert(base == NULL);
+       }
+
+end:
+       if (base)
+               event_base_free(base);
+       if (cfg)
+               event_config_free(cfg);
+}
+
+static void
+test_version(void *arg)
+{
+       const char *vstr;
+       ev_uint32_t vint;
+       int major, minor, patch, n;
+
+       vstr = event_get_version();
+       vint = event_get_version_number();
+
+       tt_assert(vstr);
+       tt_assert(vint);
+
+       tt_str_op(vstr, ==, LIBEVENT_VERSION);
+       tt_int_op(vint, ==, LIBEVENT_VERSION_NUMBER);
+
+       n = sscanf(vstr, "%d.%d.%d", &major, &minor, &patch);
+       tt_assert(3 == n);
+       tt_int_op((vint&0xffffff00), ==, ((major<<24)|(minor<<16)|(patch<<8)));
+end:
+       ;
+}
+
+static void
+test_base_features(void *arg)
+{
+       struct event_base *base = NULL;
+       struct event_config *cfg = NULL;
+
+       cfg = event_config_new();
+
+       tt_assert(0 == event_config_require_features(cfg, EV_FEATURE_ET));
+
+       base = event_base_new_with_config(cfg);
+       if (base) {
+               tt_int_op(EV_FEATURE_ET, ==,
+                   event_base_get_features(base) & EV_FEATURE_ET);
+       } else {
+               base = event_base_new();
+               tt_int_op(0, ==, event_base_get_features(base) & EV_FEATURE_ET);
+       }
+
+end:
+       if (base)
+               event_base_free(base);
+       if (cfg)
+               event_config_free(cfg);
+}
+
+#ifdef _EVENT_HAVE_SETENV
+#define SETENV_OK
+#elif !defined(_EVENT_HAVE_SETENV) && defined(_EVENT_HAVE_PUTENV)
+static void setenv(const char *k, const char *v, int _o)
+{
+       char b[256];
+       evutil_snprintf(b, sizeof(b), "%s=%s",k,v);
+       putenv(b);
+}
+#define SETENV_OK
+#endif
+
+#ifdef _EVENT_HAVE_UNSETENV
+#define UNSETENV_OK
+#elif !defined(_EVENT_HAVE_UNSETENV) && defined(_EVENT_HAVE_PUTENV)
+static void unsetenv(const char *k)
+{
+       char b[256];
+       evutil_snprintf(b, sizeof(b), "%s=",k);
+       putenv(b);
+}
+#define UNSETENV_OK
+#endif
+
+#if defined(SETENV_OK) && defined(UNSETENV_OK)
+static void
+methodname_to_envvar(const char *mname, char *buf, size_t buflen)
+{
+       char *cp;
+       evutil_snprintf(buf, buflen, "EVENT_NO%s", mname);
+       for (cp = buf; *cp; ++cp) {
+               *cp = EVUTIL_TOUPPER(*cp);
+       }
+}
+#endif
+
+static void
+test_base_environ(void *arg)
+{
+       struct event_base *base = NULL;
+       struct event_config *cfg = NULL;
+
+#if defined(SETENV_OK) && defined(UNSETENV_OK)
+       const char **basenames;
+       int i, n_methods=0;
+       char varbuf[128];
+       const char *defaultname, *ignoreenvname;
+
+       /* See if unsetenv works before we rely on it. */
+       setenv("EVENT_NOWAFFLES", "1", 1);
+       unsetenv("EVENT_NOWAFFLES");
+       if (getenv("EVENT_NOWAFFLES") != NULL) {
+#ifndef _EVENT_HAVE_UNSETENV
+               TT_DECLARE("NOTE", ("Can't fake unsetenv; skipping test"));
+#else
+               TT_DECLARE("NOTE", ("unsetenv doesn't work; skipping test"));
+#endif
+               tt_skip();
+       }
+
+       basenames = event_get_supported_methods();
+       for (i = 0; basenames[i]; ++i) {
+               methodname_to_envvar(basenames[i], varbuf, sizeof(varbuf));
+               unsetenv(varbuf);
+               ++n_methods;
+       }
+
+       base = event_base_new();
+       tt_assert(base);
+
+       defaultname = event_base_get_method(base);
+       TT_BLATHER(("default is <%s>", defaultname));
+       event_base_free(base);
+       base = NULL;
+
+       /* Can we disable the method with EVENT_NOfoo ? */
+       if (!strcmp(defaultname, "epoll (with changelist)")) {
+               setenv("EVENT_NOEPOLL", "1", 1);
+               ignoreenvname = "epoll";
+       } else {
+               methodname_to_envvar(defaultname, varbuf, sizeof(varbuf));
+               setenv(varbuf, "1", 1);
+               ignoreenvname = defaultname;
+       }
+
+       /* Use an empty cfg rather than NULL so a failure doesn't exit() */
+       cfg = event_config_new();
+       base = event_base_new_with_config(cfg);
+       event_config_free(cfg);
+       cfg = NULL;
+       if (n_methods == 1) {
+               tt_assert(!base);
+       } else {
+               tt_assert(base);
+               tt_str_op(defaultname, !=, event_base_get_method(base));
+               event_base_free(base);
+               base = NULL;
+       }
+
+       /* Can we disable looking at the environment with IGNORE_ENV ? */
+       cfg = event_config_new();
+       event_config_set_flag(cfg, EVENT_BASE_FLAG_IGNORE_ENV);
+       base = event_base_new_with_config(cfg);
+       tt_assert(base);
+       tt_str_op(ignoreenvname, ==, event_base_get_method(base));
+#else
+       tt_skip();
+#endif
+
+end:
+       if (base)
+               event_base_free(base);
+       if (cfg)
+               event_config_free(cfg);
+}
+
+static void
+read_called_once_cb(evutil_socket_t fd, short event, void *arg)
+{
+       tt_int_op(event, ==, EV_READ);
+       called += 1;
+end:
+       ;
+}
+
+static void
+timeout_called_once_cb(evutil_socket_t fd, short event, void *arg)
+{
+       tt_int_op(event, ==, EV_TIMEOUT);
+       called += 100;
+end:
+       ;
+}
+
+static void
+test_event_once(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct timeval tv;
+       int r;
+
+       tv.tv_sec = 0;
+       tv.tv_usec = 50*1000;
+       called = 0;
+       r = event_base_once(data->base, data->pair[0], EV_READ,
+           read_called_once_cb, NULL, NULL);
+       tt_int_op(r, ==, 0);
+       r = event_base_once(data->base, -1, EV_TIMEOUT,
+           timeout_called_once_cb, NULL, &tv);
+       tt_int_op(r, ==, 0);
+       r = event_base_once(data->base, -1, 0, NULL, NULL, NULL);
+       tt_int_op(r, <, 0);
+
+       if (write(data->pair[1], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
+
+       shutdown(data->pair[1], SHUT_WR);
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(called, ==, 101);
+end:
+       ;
+}
+
+static void
+test_event_pending(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event *r=NULL, *w=NULL, *t=NULL;
+       struct timeval tv, now, tv2, diff;
+
+       tv.tv_sec = 0;
+       tv.tv_usec = 500 * 1000;
+       r = event_new(data->base, data->pair[0], EV_READ, simple_read_cb,
+           NULL);
+       w = event_new(data->base, data->pair[1], EV_WRITE, simple_write_cb,
+           NULL);
+       t = evtimer_new(data->base, timeout_cb, NULL);
+
+       evutil_gettimeofday(&now, NULL);
+       event_add(r, NULL);
+       event_add(t, &tv);
+
+       tt_assert( event_pending(r, EV_READ, NULL));
+       tt_assert(!event_pending(w, EV_WRITE, NULL));
+       tt_assert(!event_pending(r, EV_WRITE, NULL));
+       tt_assert( event_pending(r, EV_READ|EV_WRITE, NULL));
+       tt_assert(!event_pending(r, EV_TIMEOUT, NULL));
+       tt_assert( event_pending(t, EV_TIMEOUT, NULL));
+       tt_assert( event_pending(t, EV_TIMEOUT, &tv2));
+
+       tt_assert(evutil_timercmp(&tv2, &now, >));
+       evutil_timeradd(&now, &tv, &tv);
+       evutil_timersub(&tv2, &tv, &diff);
+       tt_int_op(diff.tv_sec, ==, 0);
+       tt_int_op(labs(diff.tv_usec), <, 1000);
+
+end:
+       if (r) {
+               event_del(r);
+               event_free(r);
+       }
+       if (w) {
+               event_del(w);
+               event_free(w);
+       }
+       if (t) {
+               event_del(t);
+               event_free(t);
+       }
+}
+
+#ifndef WIN32
+/* You can't do this test on windows, since dup2 doesn't work on sockets */
+
+static void
+dfd_cb(evutil_socket_t fd, short e, void *data)
+{
+       *(int*)data = (int)e;
+}
+
+/* Regression test for our workaround for a fun epoll/linux related bug
+ * where fd2 = dup(fd1); add(fd2); close(fd2); dup2(fd1,fd2); add(fd2)
+ * will get you an EEXIST */
+static void
+test_dup_fd(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       struct event *ev1=NULL, *ev2=NULL;
+       int fd, dfd=-1;
+       int ev1_got, ev2_got;
+
+       tt_int_op(write(data->pair[0], "Hello world",
+               strlen("Hello world")), >, 0);
+       fd = data->pair[1];
+
+       dfd = dup(fd);
+       tt_int_op(dfd, >=, 0);
+
+       ev1 = event_new(base, fd, EV_READ|EV_PERSIST, dfd_cb, &ev1_got);
+       ev2 = event_new(base, dfd, EV_READ|EV_PERSIST, dfd_cb, &ev2_got);
+       ev1_got = ev2_got = 0;
+       event_add(ev1, NULL);
+       event_add(ev2, NULL);
+       event_base_loop(base, EVLOOP_ONCE);
+       tt_int_op(ev1_got, ==, EV_READ);
+       tt_int_op(ev2_got, ==, EV_READ);
+
+       /* Now close and delete dfd then dispatch.  We need to do the
+        * dispatch here so that when we add it later, we think there
+        * was an intermediate delete. */
+       close(dfd);
+       event_del(ev2);
+       ev1_got = ev2_got = 0;
+       event_base_loop(base, EVLOOP_ONCE);
+       tt_want_int_op(ev1_got, ==, EV_READ);
+       tt_int_op(ev2_got, ==, 0);
+
+       /* Re-duplicate the fd.  We need to get the same duplicated
+        * value that we closed to provoke the epoll quirk.  Also, we
+        * need to change the events to write, or else the old lingering
+        * read event will make the test pass whether the change was
+        * successful or not. */
+       tt_int_op(dup2(fd, dfd), ==, dfd);
+       event_free(ev2);
+       ev2 = event_new(base, dfd, EV_WRITE|EV_PERSIST, dfd_cb, &ev2_got);
+       event_add(ev2, NULL);
+       ev1_got = ev2_got = 0;
+       event_base_loop(base, EVLOOP_ONCE);
+       tt_want_int_op(ev1_got, ==, EV_READ);
+       tt_int_op(ev2_got, ==, EV_WRITE);
+
+end:
+       if (ev1)
+               event_free(ev1);
+       if (ev2)
+               event_free(ev2);
+       close(dfd);
+}
+#endif
+
+#ifdef _EVENT_DISABLE_MM_REPLACEMENT
+static void
+test_mm_functions(void *arg)
+{
+       _tinytest_set_test_skipped();
+}
+#else
+static int
+check_dummy_mem_ok(void *_mem)
+{
+       char *mem = _mem;
+       mem -= 16;
+       return !memcmp(mem, "{[<guardedram>]}", 16);
+}
+
+static void *
+dummy_malloc(size_t len)
+{
+       char *mem = malloc(len+16);
+       memcpy(mem, "{[<guardedram>]}", 16);
+       return mem+16;
+}
+
+static void *
+dummy_realloc(void *_mem, size_t len)
+{
+       char *mem = _mem;
+       if (!mem)
+               return dummy_malloc(len);
+       tt_want(check_dummy_mem_ok(_mem));
+       mem -= 16;
+       mem = realloc(mem, len+16);
+       return mem+16;
+}
+
+static void
+dummy_free(void *_mem)
+{
+       char *mem = _mem;
+       tt_want(check_dummy_mem_ok(_mem));
+       mem -= 16;
+       free(mem);
+}
+
+static void
+test_mm_functions(void *arg)
+{
+       struct event_base *b = NULL;
+       struct event_config *cfg = NULL;
+       event_set_mem_functions(dummy_malloc, dummy_realloc, dummy_free);
+       cfg = event_config_new();
+       event_config_avoid_method(cfg, "Nonesuch");
+       b = event_base_new_with_config(cfg);
+       tt_assert(b);
+       tt_assert(check_dummy_mem_ok(b));
+end:
+       if (cfg)
+               event_config_free(cfg);
+       if (b)
+               event_base_free(b);
+}
+#endif
+
+static void
+many_event_cb(evutil_socket_t fd, short event, void *arg)
+{
+       int *calledp = arg;
+       *calledp += 1;
+}
+
+static void
+test_many_events(void *arg)
+{
+       /* Try 70 events that should all be ready at once.  This will
+        * exercise the "resize" code on most of the backends, and will make
+        * sure that we can get past the 64-handle limit of some windows
+        * functions. */
+#define MANY 70
+
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       int one_at_a_time = data->setup_data != NULL;
+       evutil_socket_t sock[MANY];
+       struct event *ev[MANY];
+       int called[MANY];
+       int i;
+       int loopflags = EVLOOP_NONBLOCK, evflags=0;
+       const int is_evport = !strcmp(event_base_get_method(base),"evport");
+       if (one_at_a_time) {
+               loopflags |= EVLOOP_ONCE;
+               evflags = EV_PERSIST;
+       }
+
+       memset(sock, 0xff, sizeof(sock));
+       memset(ev, 0, sizeof(ev));
+       memset(called, 0, sizeof(called));
+       if (is_evport && one_at_a_time) {
+               TT_DECLARE("NOTE", ("evport can't pass this in 2.0; skipping\n"));
+               tt_skip();
+       }
+
+       for (i = 0; i < MANY; ++i) {
+               /* We need an event that will hit the backend, and that will
+                * be ready immediately.  "Send a datagram" is an easy
+                * instance of that. */
+               sock[i] = socket(AF_INET, SOCK_DGRAM, 0);
+               tt_assert(sock[i] >= 0);
+               called[i] = 0;
+               ev[i] = event_new(base, sock[i], EV_WRITE|evflags,
+                   many_event_cb, &called[i]);
+               event_add(ev[i], NULL);
+               if (one_at_a_time)
+                       event_base_loop(base, EVLOOP_NONBLOCK|EVLOOP_ONCE);
+       }
+
+       event_base_loop(base, loopflags);
+
+       for (i = 0; i < MANY; ++i) {
+               if (one_at_a_time)
+                       tt_int_op(called[i], ==, MANY - i + 1);
+               else
+                       tt_int_op(called[i], ==, 1);
+       }
+
+end:
+       for (i = 0; i < MANY; ++i) {
+               if (ev[i])
+                       event_free(ev[i]);
+               if (sock[i] >= 0)
+                       evutil_closesocket(sock[i]);
+       }
+#undef MANY
+}
+
+static void
+test_struct_event_size(void *arg)
+{
+       tt_int_op(event_get_struct_event_size(), <=, sizeof(struct event));
+end:
+       ;
+}
+
+struct testcase_t main_testcases[] = {
+       /* Some converted-over tests */
+       { "methods", test_methods, TT_FORK, NULL, NULL },
+       { "version", test_version, 0, NULL, NULL },
+       BASIC(base_features, TT_FORK|TT_NO_LOGS),
+       { "base_environ", test_base_environ, TT_FORK, NULL, NULL },
+
+       BASIC(event_base_new, TT_FORK|TT_NEED_SOCKETPAIR),
+       BASIC(free_active_base, TT_FORK|TT_NEED_SOCKETPAIR),
+
+       BASIC(manipulate_active_events, TT_FORK|TT_NEED_BASE),
+
+       BASIC(bad_assign, TT_FORK|TT_NEED_BASE|TT_NO_LOGS),
+       BASIC(bad_reentrant, TT_FORK|TT_NEED_BASE|TT_NO_LOGS),
+
+       /* These are still using the old API */
+       LEGACY(persistent_timeout, TT_FORK|TT_NEED_BASE),
+       { "persistent_active_timeout", test_persistent_active_timeout,
+         TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+       LEGACY(priorities, TT_FORK|TT_NEED_BASE),
+       { "common_timeout", test_common_timeout, TT_FORK|TT_NEED_BASE,
+         &basic_setup, NULL },
+
+       /* These legacy tests may not all need all of these flags. */
+       LEGACY(simpleread, TT_ISOLATED),
+       LEGACY(simpleread_multiple, TT_ISOLATED),
+       LEGACY(simplewrite, TT_ISOLATED),
+       { "simpleclose", test_simpleclose, TT_FORK, &basic_setup,
+         NULL },
+       LEGACY(multiple, TT_ISOLATED),
+       LEGACY(persistent, TT_ISOLATED),
+       LEGACY(combined, TT_ISOLATED),
+       LEGACY(simpletimeout, TT_ISOLATED),
+       LEGACY(loopbreak, TT_ISOLATED),
+       LEGACY(loopexit, TT_ISOLATED),
+       LEGACY(loopexit_multiple, TT_ISOLATED),
+       LEGACY(nonpersist_readd, TT_ISOLATED),
+       LEGACY(multiple_events_for_same_fd, TT_ISOLATED),
+       LEGACY(want_only_once, TT_ISOLATED),
+       { "event_once", test_event_once, TT_ISOLATED, &basic_setup, NULL },
+       { "event_pending", test_event_pending, TT_ISOLATED, &basic_setup,
+         NULL },
+#ifndef WIN32
+       { "dup_fd", test_dup_fd, TT_ISOLATED, &basic_setup, NULL },
+#endif
+       { "mm_functions", test_mm_functions, TT_FORK, NULL, NULL },
+       { "many_events", test_many_events, TT_ISOLATED, &basic_setup, NULL },
+       { "many_events_slow_add", test_many_events, TT_ISOLATED, &basic_setup, (void*)1 },
+
+       { "struct_event_size", test_struct_event_size, 0, NULL, NULL },
+
+#ifndef WIN32
+       LEGACY(fork, TT_ISOLATED),
+#endif
+       END_OF_TESTCASES
+};
+
+struct testcase_t evtag_testcases[] = {
+       { "int", evtag_int_test, TT_FORK, NULL, NULL },
+       { "fuzz", evtag_fuzz, TT_FORK, NULL, NULL },
+       { "encoding", evtag_tag_encoding, TT_FORK, NULL, NULL },
+       { "peek", evtag_test_peek, 0, NULL, NULL },
+
+       END_OF_TESTCASES
+};
+
+struct testcase_t signal_testcases[] = {
+#ifndef WIN32
+       LEGACY(simplesignal, TT_ISOLATED),
+       LEGACY(multiplesignal, TT_ISOLATED),
+       LEGACY(immediatesignal, TT_ISOLATED),
+       LEGACY(signal_dealloc, TT_ISOLATED),
+       LEGACY(signal_pipeloss, TT_ISOLATED),
+       LEGACY(signal_switchbase, TT_ISOLATED|TT_NO_LOGS),
+       LEGACY(signal_restore, TT_ISOLATED),
+       LEGACY(signal_assert, TT_ISOLATED),
+       LEGACY(signal_while_processing, TT_ISOLATED),
+#endif
+       END_OF_TESTCASES
+};
+
diff --git a/libevent/test/regress.h b/libevent/test/regress.h
new file mode 100644 (file)
index 0000000..32adccd
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _REGRESS_H_
+#define _REGRESS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+extern struct testcase_t main_testcases[];
+extern struct testcase_t evtag_testcases[];
+extern struct testcase_t evbuffer_testcases[];
+extern struct testcase_t bufferevent_testcases[];
+extern struct testcase_t bufferevent_iocp_testcases[];
+extern struct testcase_t util_testcases[];
+extern struct testcase_t signal_testcases[];
+extern struct testcase_t http_testcases[];
+extern struct testcase_t dns_testcases[];
+extern struct testcase_t rpc_testcases[];
+extern struct testcase_t edgetriggered_testcases[];
+extern struct testcase_t minheap_testcases[];
+extern struct testcase_t iocp_testcases[];
+extern struct testcase_t ssl_testcases[];
+extern struct testcase_t listener_testcases[];
+extern struct testcase_t listener_iocp_testcases[];
+extern struct testcase_t thread_testcases[];
+
+void regress_threads(void *);
+void test_bufferevent_zlib(void *);
+
+/* Helpers to wrap old testcases */
+extern evutil_socket_t pair[2];
+extern int test_ok;
+extern int called;
+extern struct event_base *global_base;
+extern int in_legacy_test_wrapper;
+
+int regress_make_tmpfile(const void *data, size_t datalen);
+
+struct basic_test_data {
+       struct event_base *base;
+       evutil_socket_t pair[2];
+
+       void (*legacy_test_fn)(void);
+
+       void *setup_data;
+};
+extern const struct testcase_setup_t basic_setup;
+
+
+extern const struct testcase_setup_t legacy_setup;
+void run_legacy_test_fn(void *ptr);
+
+/* A couple of flags that basic/legacy_setup can support. */
+#define TT_NEED_SOCKETPAIR     TT_FIRST_USER_FLAG
+#define TT_NEED_BASE           (TT_FIRST_USER_FLAG<<1)
+#define TT_NEED_DNS            (TT_FIRST_USER_FLAG<<2)
+#define TT_LEGACY              (TT_FIRST_USER_FLAG<<3)
+#define TT_NEED_THREADS                (TT_FIRST_USER_FLAG<<4)
+#define TT_NO_LOGS             (TT_FIRST_USER_FLAG<<5)
+#define TT_ENABLE_IOCP_FLAG    (TT_FIRST_USER_FLAG<<6)
+#define TT_ENABLE_IOCP         (TT_ENABLE_IOCP_FLAG|TT_NEED_THREADS)
+
+/* All the flags that a legacy test needs. */
+#define TT_ISOLATED TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE
+
+
+#define BASIC(name,flags)                                              \
+       { #name, test_## name, flags, &basic_setup, NULL }
+
+#define LEGACY(name,flags)                                             \
+       { #name, run_legacy_test_fn, flags|TT_LEGACY, &legacy_setup,    \
+         test_## name }
+
+struct evutil_addrinfo;
+struct evutil_addrinfo *ai_find_by_family(struct evutil_addrinfo *ai, int f);
+struct evutil_addrinfo *ai_find_by_protocol(struct evutil_addrinfo *ai, int p);
+int _test_ai_eq(const struct evutil_addrinfo *ai, const char *sockaddr_port,
+    int socktype, int protocol, int line);
+
+#define test_ai_eq(ai, str, s, p) do {                                 \
+               if (_test_ai_eq((ai), (str), (s), (p), __LINE__)<0)     \
+                       goto end;                                       \
+       } while (0)
+
+#define test_timeval_diff_leq(tv1, tv2, diff, tolerance)               \
+       tt_int_op(abs(timeval_msec_diff((tv1), (tv2)) - diff), <=, tolerance)
+
+#define test_timeval_diff_eq(tv1, tv2, diff)                           \
+       test_timeval_diff_leq((tv1), (tv2), (diff), 50)
+
+long timeval_msec_diff(const struct timeval *start, const struct timeval *end);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _REGRESS_H_ */
diff --git a/libevent/test/regress.rpc b/libevent/test/regress.rpc
new file mode 100644 (file)
index 0000000..0ee904e
--- /dev/null
@@ -0,0 +1,25 @@
+/* tests data packing and unpacking */
+
+struct msg {
+       string /* sender */ from_name = 1; /* be verbose */
+       string to_name = 2;
+       optional struct[kill] attack = 3;
+       array struct[run] run = 4;
+}
+
+struct kill {
+       string weapon = 0x10121;
+       string action = 2;
+       array int how_often = 3;
+}
+
+struct run {
+       string how = 1;
+       optional bytes some_bytes = 2;
+
+       bytes fixed_bytes[24] = 3;
+       array string notes = 4;
+
+       optional int64 large_number = 5;
+       array int other_numbers = 6;
+}
diff --git a/libevent/test/regress_buffer.c b/libevent/test/regress_buffer.c
new file mode 100644 (file)
index 0000000..6a2b6fc
--- /dev/null
@@ -0,0 +1,1666 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+
+#include "event2/event.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/util.h"
+
+#include "evbuffer-internal.h"
+#include "log-internal.h"
+
+#include "regress.h"
+
+/* Validates that an evbuffer is good. Returns false if it isn't, true if it
+ * is*/
+static int
+_evbuffer_validate(struct evbuffer *buf)
+{
+       struct evbuffer_chain *chain;
+       size_t sum = 0;
+       int found_last_with_datap = 0;
+
+       if (buf->first == NULL) {
+               tt_assert(buf->last == NULL);
+               tt_assert(buf->total_len == 0);
+       }
+
+       chain = buf->first;
+
+       tt_assert(buf->last_with_datap);
+       if (buf->last_with_datap == &buf->first)
+               found_last_with_datap = 1;
+
+       while (chain != NULL) {
+               if (&chain->next == buf->last_with_datap)
+                       found_last_with_datap = 1;
+               sum += chain->off;
+               if (chain->next == NULL) {
+                       tt_assert(buf->last == chain);
+               }
+               tt_assert(chain->buffer_len >= chain->misalign + chain->off);
+               chain = chain->next;
+       }
+
+       if (buf->first)
+               tt_assert(*buf->last_with_datap);
+
+       if (*buf->last_with_datap) {
+               chain = *buf->last_with_datap;
+               if (chain->off == 0 || buf->total_len == 0) {
+                       tt_assert(chain->off == 0)
+                       tt_assert(chain == buf->first);
+                       tt_assert(buf->total_len == 0);
+               }
+               chain = chain->next;
+               while (chain != NULL) {
+                       tt_assert(chain->off == 0);
+                       chain = chain->next;
+               }
+       } else {
+               tt_assert(buf->last_with_datap == &buf->first);
+       }
+       tt_assert(found_last_with_datap);
+
+       tt_assert(sum == buf->total_len);
+       return 1;
+ end:
+       return 0;
+}
+
+static void
+evbuffer_get_waste(struct evbuffer *buf, size_t *allocatedp, size_t *wastedp, size_t *usedp)
+{
+       struct evbuffer_chain *chain;
+       size_t a, w, u;
+       int n = 0;
+       u = a = w = 0;
+
+       chain = buf->first;
+       /* skip empty at start */
+       while (chain && chain->off==0) {
+               ++n;
+               a += chain->buffer_len;
+               chain = chain->next;
+       }
+       /* first nonempty chain: stuff at the end only is wasted. */
+       if (chain) {
+               ++n;
+               a += chain->buffer_len;
+               u += chain->off;
+               if (chain->next && chain->next->off)
+                       w += (size_t)(chain->buffer_len - (chain->misalign + chain->off));
+               chain = chain->next;
+       }
+       /* subsequent nonempty chains */
+       while (chain && chain->off) {
+               ++n;
+               a += chain->buffer_len;
+               w += (size_t)chain->misalign;
+               u += chain->off;
+               if (chain->next && chain->next->off)
+                       w += (size_t) (chain->buffer_len - (chain->misalign + chain->off));
+               chain = chain->next;
+       }
+       /* subsequent empty chains */
+       while (chain) {
+               ++n;
+               a += chain->buffer_len;
+       }
+       *allocatedp = a;
+       *wastedp = w;
+       *usedp = u;
+}
+
+#define evbuffer_validate(buf)                 \
+       TT_STMT_BEGIN if (!_evbuffer_validate(buf)) TT_DIE(("Buffer format invalid")); TT_STMT_END
+
+static void
+test_evbuffer(void *ptr)
+{
+       static char buffer[512], *tmp;
+       struct evbuffer *evb = evbuffer_new();
+       struct evbuffer *evb_two = evbuffer_new();
+       size_t sz_tmp;
+       int i;
+
+       evbuffer_validate(evb);
+       evbuffer_add_printf(evb, "%s/%d", "hello", 1);
+       evbuffer_validate(evb);
+
+       tt_assert(evbuffer_get_length(evb) == 7);
+       tt_assert(!memcmp((char*)EVBUFFER_DATA(evb), "hello/1", 1));
+
+       evbuffer_add_buffer(evb, evb_two);
+       evbuffer_validate(evb);
+
+       evbuffer_drain(evb, strlen("hello/"));
+       evbuffer_validate(evb);
+       tt_assert(evbuffer_get_length(evb) == 1);
+       tt_assert(!memcmp((char*)EVBUFFER_DATA(evb), "1", 1));
+
+       evbuffer_add_printf(evb_two, "%s", "/hello");
+       evbuffer_validate(evb);
+       evbuffer_add_buffer(evb, evb_two);
+       evbuffer_validate(evb);
+
+       tt_assert(evbuffer_get_length(evb_two) == 0);
+       tt_assert(evbuffer_get_length(evb) == 7);
+       tt_assert(!memcmp((char*)EVBUFFER_DATA(evb), "1/hello", 7) != 0);
+
+       memset(buffer, 0, sizeof(buffer));
+       evbuffer_add(evb, buffer, sizeof(buffer));
+       evbuffer_validate(evb);
+       tt_assert(evbuffer_get_length(evb) == 7 + 512);
+
+       tmp = (char *)evbuffer_pullup(evb, 7 + 512);
+       tt_assert(tmp);
+       tt_assert(!strncmp(tmp, "1/hello", 7));
+       tt_assert(!memcmp(tmp + 7, buffer, sizeof(buffer)));
+       evbuffer_validate(evb);
+
+       evbuffer_prepend(evb, "something", 9);
+       evbuffer_validate(evb);
+       evbuffer_prepend(evb, "else", 4);
+       evbuffer_validate(evb);
+
+       tmp = (char *)evbuffer_pullup(evb, 4 + 9 + 7);
+       tt_assert(!strncmp(tmp, "elsesomething1/hello", 4 + 9 + 7));
+       evbuffer_validate(evb);
+
+       evbuffer_drain(evb, -1);
+       evbuffer_validate(evb);
+       evbuffer_drain(evb_two, -1);
+       evbuffer_validate(evb);
+
+       for (i = 0; i < 3; ++i) {
+               evbuffer_add(evb_two, buffer, sizeof(buffer));
+               evbuffer_validate(evb_two);
+               evbuffer_add_buffer(evb, evb_two);
+               evbuffer_validate(evb);
+               evbuffer_validate(evb_two);
+       }
+
+       tt_assert(evbuffer_get_length(evb_two) == 0);
+       tt_assert(evbuffer_get_length(evb) == i * sizeof(buffer));
+
+       /* test remove buffer */
+       sz_tmp = (size_t)(sizeof(buffer)*2.5);
+       evbuffer_remove_buffer(evb, evb_two, sz_tmp);
+       tt_assert(evbuffer_get_length(evb_two) == sz_tmp);
+       tt_assert(evbuffer_get_length(evb) == sizeof(buffer) / 2);
+       evbuffer_validate(evb);
+
+       if (memcmp(evbuffer_pullup(
+                          evb, -1), buffer, sizeof(buffer) / 2) != 0 ||
+           memcmp(evbuffer_pullup(
+                          evb_two, -1), buffer, sizeof(buffer) != 0))
+               tt_abort_msg("Pullup did not preserve content");
+
+       evbuffer_validate(evb);
+
+
+       /* testing one-vector reserve and commit */
+       {
+               struct evbuffer_iovec v[1];
+               char *buf;
+               int i, j, r;
+
+               for (i = 0; i < 3; ++i) {
+                       r = evbuffer_reserve_space(evb, 10000, v, 1);
+                       tt_int_op(r, ==, 1);
+                       tt_assert(v[0].iov_len >= 10000);
+                       tt_assert(v[0].iov_base != NULL);
+
+                       evbuffer_validate(evb);
+                       buf = v[0].iov_base;
+                       for (j = 0; j < 10000; ++j) {
+                               buf[j] = j;
+                       }
+                       evbuffer_validate(evb);
+
+                       tt_int_op(evbuffer_commit_space(evb, v, 1), ==, 0);
+                       evbuffer_validate(evb);
+
+                       tt_assert(evbuffer_get_length(evb) >= 10000);
+
+                       evbuffer_drain(evb, j * 5000);
+                       evbuffer_validate(evb);
+               }
+       }
+
+ end:
+       evbuffer_free(evb);
+       evbuffer_free(evb_two);
+}
+
+static void
+no_cleanup(const void *data, size_t datalen, void *extra)
+{
+}
+
+static void
+test_evbuffer_remove_buffer_with_empty(void *ptr)
+{
+    struct evbuffer *src = evbuffer_new();
+    struct evbuffer *dst = evbuffer_new();
+    char buf[2];
+
+    evbuffer_validate(src);
+    evbuffer_validate(dst);
+
+    /* setup the buffers */
+    /* we need more data in src than we will move later */
+    evbuffer_add_reference(src, buf, sizeof(buf), no_cleanup, NULL);
+    evbuffer_add_reference(src, buf, sizeof(buf), no_cleanup, NULL);
+    /* we need one buffer in dst and one empty buffer at the end */
+    evbuffer_add(dst, buf, sizeof(buf));
+    evbuffer_add_reference(dst, buf, 0, no_cleanup, NULL);
+
+    evbuffer_validate(src);
+    evbuffer_validate(dst);
+
+    /* move three bytes over */
+    evbuffer_remove_buffer(src, dst, 3);
+
+    evbuffer_validate(src);
+    evbuffer_validate(dst);
+
+end:
+    evbuffer_free(src);
+    evbuffer_free(dst);
+}
+
+static void
+test_evbuffer_reserve2(void *ptr)
+{
+       /* Test the two-vector cases of reserve/commit. */
+       struct evbuffer *buf = evbuffer_new();
+       int n, i;
+       struct evbuffer_iovec v[2];
+       size_t remaining;
+       char *cp, *cp2;
+
+       /* First chunk will necessarily be one chunk. Use 512 bytes of it.*/
+       n = evbuffer_reserve_space(buf, 1024, v, 2);
+       tt_int_op(n, ==, 1);
+       tt_int_op(evbuffer_get_length(buf), ==, 0);
+       tt_assert(v[0].iov_base != NULL);
+       tt_int_op(v[0].iov_len, >=, 1024);
+       memset(v[0].iov_base, 'X', 512);
+       cp = v[0].iov_base;
+       remaining = v[0].iov_len - 512;
+       v[0].iov_len = 512;
+       evbuffer_validate(buf);
+       tt_int_op(0, ==, evbuffer_commit_space(buf, v, 1));
+       tt_int_op(evbuffer_get_length(buf), ==, 512);
+       evbuffer_validate(buf);
+
+       /* Ask for another same-chunk request, in an existing chunk. Use 8
+        * bytes of it. */
+       n = evbuffer_reserve_space(buf, 32, v, 2);
+       tt_int_op(n, ==, 1);
+       tt_assert(cp + 512 == v[0].iov_base);
+       tt_int_op(remaining, ==, v[0].iov_len);
+       memset(v[0].iov_base, 'Y', 8);
+       v[0].iov_len = 8;
+       tt_int_op(0, ==, evbuffer_commit_space(buf, v, 1));
+       tt_int_op(evbuffer_get_length(buf), ==, 520);
+       remaining -= 8;
+       evbuffer_validate(buf);
+
+       /* Now ask for a request that will be split. Use only one byte of it,
+          though. */
+       n = evbuffer_reserve_space(buf, remaining+64, v, 2);
+       tt_int_op(n, ==, 2);
+       tt_assert(cp + 520 == v[0].iov_base);
+       tt_int_op(remaining, ==, v[0].iov_len);
+       tt_assert(v[1].iov_base);
+       tt_assert(v[1].iov_len >= 64);
+       cp2 = v[1].iov_base;
+       memset(v[0].iov_base, 'Z', 1);
+       v[0].iov_len = 1;
+       tt_int_op(0, ==, evbuffer_commit_space(buf, v, 1));
+       tt_int_op(evbuffer_get_length(buf), ==, 521);
+       remaining -= 1;
+       evbuffer_validate(buf);
+
+       /* Now ask for a request that will be split. Use some of the first
+        * part and some of the second. */
+       n = evbuffer_reserve_space(buf, remaining+64, v, 2);
+       evbuffer_validate(buf);
+       tt_int_op(n, ==, 2);
+       tt_assert(cp + 521 == v[0].iov_base);
+       tt_int_op(remaining, ==, v[0].iov_len);
+       tt_assert(v[1].iov_base == cp2);
+       tt_assert(v[1].iov_len >= 64);
+       memset(v[0].iov_base, 'W', 400);
+       v[0].iov_len = 400;
+       memset(v[1].iov_base, 'x', 60);
+       v[1].iov_len = 60;
+       tt_int_op(0, ==, evbuffer_commit_space(buf, v, 2));
+       tt_int_op(evbuffer_get_length(buf), ==, 981);
+       evbuffer_validate(buf);
+
+       /* Now peek to make sure stuff got made how we like. */
+       memset(v,0,sizeof(v));
+       n = evbuffer_peek(buf, -1, NULL, v, 2);
+       tt_int_op(n, ==, 2);
+       tt_int_op(v[0].iov_len, ==, 921);
+       tt_int_op(v[1].iov_len, ==, 60);
+
+       cp = v[0].iov_base;
+       for (i=0; i<512; ++i)
+               tt_int_op(cp[i], ==, 'X');
+       for (i=512; i<520; ++i)
+               tt_int_op(cp[i], ==, 'Y');
+       for (i=520; i<521; ++i)
+               tt_int_op(cp[i], ==, 'Z');
+       for (i=521; i<921; ++i)
+               tt_int_op(cp[i], ==, 'W');
+
+       cp = v[1].iov_base;
+       for (i=0; i<60; ++i)
+               tt_int_op(cp[i], ==, 'x');
+
+end:
+       evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_reserve_many(void *ptr)
+{
+       /* This is a glass-box test to handle expanding a buffer with more
+        * chunks and reallocating chunks as needed */
+       struct evbuffer *buf = evbuffer_new();
+       struct evbuffer_iovec v[8];
+       int n;
+       size_t sz;
+       int add_data = ptr && !strcmp(ptr, "add");
+       int fill_first = ptr && !strcmp(ptr, "fill");
+       char *cp1, *cp2;
+
+       /* When reserving the the first chunk, we just allocate it */
+       n = evbuffer_reserve_space(buf, 128, v, 2);
+       evbuffer_validate(buf);
+       tt_int_op(n, ==, 1);
+       tt_assert(v[0].iov_len >= 128);
+       sz = v[0].iov_len;
+       cp1 = v[0].iov_base;
+       if (add_data) {
+               *(char*)v[0].iov_base = 'X';
+               v[0].iov_len = 1;
+               n = evbuffer_commit_space(buf, v, 1);
+               tt_int_op(n, ==, 0);
+       } else if (fill_first) {
+               memset(v[0].iov_base, 'X', v[0].iov_len);
+               n = evbuffer_commit_space(buf, v, 1);
+               tt_int_op(n, ==, 0);
+               n = evbuffer_reserve_space(buf, 128, v, 2);
+               tt_int_op(n, ==, 1);
+               sz = v[0].iov_len;
+               tt_assert(v[0].iov_base != cp1);
+               cp1 = v[0].iov_base;
+       }
+
+       /* Make another chunk get added. */
+       n = evbuffer_reserve_space(buf, sz+128, v, 2);
+       evbuffer_validate(buf);
+       tt_int_op(n, ==, 2);
+       sz = v[0].iov_len + v[1].iov_len;
+       tt_int_op(sz, >=, v[0].iov_len+128);
+       if (add_data) {
+               tt_assert(v[0].iov_base == cp1 + 1);
+       } else {
+               tt_assert(v[0].iov_base == cp1);
+       }
+       cp1 = v[0].iov_base;
+       cp2 = v[1].iov_base;
+
+       /* And a third chunk. */
+       n = evbuffer_reserve_space(buf, sz+128, v, 3);
+       evbuffer_validate(buf);
+       tt_int_op(n, ==, 3);
+       tt_assert(cp1 == v[0].iov_base);
+       tt_assert(cp2 == v[1].iov_base);
+       sz = v[0].iov_len + v[1].iov_len + v[2].iov_len;
+
+       /* Now force a reallocation by asking for more space in only 2
+        * buffers. */
+       n = evbuffer_reserve_space(buf, sz+128, v, 2);
+       evbuffer_validate(buf);
+       if (add_data) {
+               tt_int_op(n, ==, 2);
+               tt_assert(cp1 == v[0].iov_base);
+       } else {
+               tt_int_op(n, ==, 1);
+       }
+
+end:
+       evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_expand(void *ptr)
+{
+       char data[4096];
+       struct evbuffer *buf;
+       size_t a,w,u;
+       void *buffer;
+
+       memset(data, 'X', sizeof(data));
+
+       /* Make sure that expand() works on an empty buffer */
+       buf = evbuffer_new();
+       tt_int_op(evbuffer_expand(buf, 20000), ==, 0);
+       evbuffer_validate(buf);
+       a=w=u=0;
+       evbuffer_get_waste(buf, &a,&w,&u);
+       tt_assert(w == 0);
+       tt_assert(u == 0);
+       tt_assert(a >= 20000);
+       tt_assert(buf->first);
+       tt_assert(buf->first == buf->last);
+       tt_assert(buf->first->off == 0);
+       tt_assert(buf->first->buffer_len >= 20000);
+
+       /* Make sure that expand() works as a no-op when there's enough
+        * contiguous space already. */
+       buffer = buf->first->buffer;
+       evbuffer_add(buf, data, 1024);
+       tt_int_op(evbuffer_expand(buf, 1024), ==, 0);
+       tt_assert(buf->first->buffer == buffer);
+       evbuffer_validate(buf);
+       evbuffer_free(buf);
+
+       /* Make sure that expand() can work by moving misaligned data
+        * when it makes sense to do so. */
+       buf = evbuffer_new();
+       evbuffer_add(buf, data, 400);
+       {
+               int n = (int)(buf->first->buffer_len - buf->first->off - 1);
+               tt_assert(n < (int)sizeof(data));
+               evbuffer_add(buf, data, n);
+       }
+       tt_assert(buf->first == buf->last);
+       tt_assert(buf->first->off == buf->first->buffer_len - 1);
+       evbuffer_drain(buf, buf->first->off - 1);
+       tt_assert(1 == evbuffer_get_length(buf));
+       tt_assert(buf->first->misalign > 0);
+       tt_assert(buf->first->off == 1);
+       buffer = buf->first->buffer;
+       tt_assert(evbuffer_expand(buf, 40) == 0);
+       tt_assert(buf->first == buf->last);
+       tt_assert(buf->first->off == 1);
+       tt_assert(buf->first->buffer == buffer);
+       tt_assert(buf->first->misalign == 0);
+       evbuffer_validate(buf);
+       evbuffer_free(buf);
+
+       /* add, expand, pull-up: This used to crash libevent. */
+       buf = evbuffer_new();
+
+       evbuffer_add(buf, data, sizeof(data));
+       evbuffer_add(buf, data, sizeof(data));
+       evbuffer_add(buf, data, sizeof(data));
+
+       evbuffer_validate(buf);
+       evbuffer_expand(buf, 1024);
+       evbuffer_validate(buf);
+       evbuffer_pullup(buf, -1);
+       evbuffer_validate(buf);
+
+end:
+       evbuffer_free(buf);
+}
+
+
+static int reference_cb_called;
+static void
+reference_cb(const void *data, size_t len, void *extra)
+{
+       tt_str_op(data, ==, "this is what we add as read-only memory.");
+       tt_int_op(len, ==, strlen(data));
+       tt_want(extra == (void *)0xdeadaffe);
+       ++reference_cb_called;
+end:
+       ;
+}
+
+static void
+test_evbuffer_reference(void *ptr)
+{
+       struct evbuffer *src = evbuffer_new();
+       struct evbuffer *dst = evbuffer_new();
+       struct evbuffer_iovec v[1];
+       const char *data = "this is what we add as read-only memory.";
+       reference_cb_called = 0;
+
+       tt_assert(evbuffer_add_reference(src, data, strlen(data),
+                reference_cb, (void *)0xdeadaffe) != -1);
+
+       evbuffer_reserve_space(dst, strlen(data), v, 1);
+       tt_assert(evbuffer_remove(src, v[0].iov_base, 10) != -1);
+
+       evbuffer_validate(src);
+       evbuffer_validate(dst);
+
+       /* make sure that we don't write data at the beginning */
+       evbuffer_prepend(src, "aaaaa", 5);
+       evbuffer_validate(src);
+       evbuffer_drain(src, 5);
+
+       tt_assert(evbuffer_remove(src, ((char*)(v[0].iov_base)) + 10,
+               strlen(data) - 10) != -1);
+
+       v[0].iov_len = strlen(data);
+
+       evbuffer_commit_space(dst, v, 1);
+       evbuffer_validate(src);
+       evbuffer_validate(dst);
+
+       tt_int_op(reference_cb_called, ==, 1);
+
+       tt_assert(!memcmp(evbuffer_pullup(dst, strlen(data)),
+                         data, strlen(data)));
+       evbuffer_validate(dst);
+
+ end:
+       evbuffer_free(dst);
+       evbuffer_free(src);
+}
+
+int _evbuffer_testing_use_sendfile(void);
+int _evbuffer_testing_use_mmap(void);
+int _evbuffer_testing_use_linear_file_access(void);
+
+static void
+test_evbuffer_add_file(void *ptr)
+{
+       const char *impl = ptr;
+       struct evbuffer *src = evbuffer_new();
+       const char *data = "this is what we add as file system data.";
+       size_t datalen;
+       const char *compare;
+       int fd = -1;
+       evutil_socket_t pair[2] = {-1, -1};
+       int r=0, n_written=0;
+
+       /* Add a test for a big file. XXXX */
+
+       tt_assert(impl);
+       if (!strcmp(impl, "sendfile")) {
+               if (!_evbuffer_testing_use_sendfile())
+                       tt_skip();
+               TT_BLATHER(("Using sendfile-based implementaion"));
+       } else if (!strcmp(impl, "mmap")) {
+               if (!_evbuffer_testing_use_mmap())
+                       tt_skip();
+               TT_BLATHER(("Using mmap-based implementaion"));
+       } else if (!strcmp(impl, "linear")) {
+               if (!_evbuffer_testing_use_linear_file_access())
+                       tt_skip();
+               TT_BLATHER(("Using read-based implementaion"));
+       } else {
+               TT_DIE(("Didn't recognize the implementation"));
+       }
+
+       /* Say that it drains to a fd so that we can use sendfile. */
+       evbuffer_set_flags(src, EVBUFFER_FLAG_DRAINS_TO_FD);
+
+#if defined(_EVENT_HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
+       /* We need to use a pair of AF_INET sockets, since Solaris
+          doesn't support sendfile() over AF_UNIX. */
+       if (evutil_ersatz_socketpair(AF_INET, SOCK_STREAM, 0, pair) == -1)
+               tt_abort_msg("ersatz_socketpair failed");
+#else
+       if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+               tt_abort_msg("socketpair failed");
+#endif
+
+       datalen = strlen(data);
+       fd = regress_make_tmpfile(data, datalen);
+
+       tt_assert(fd != -1);
+
+       tt_assert(evbuffer_add_file(src, fd, 0, datalen) != -1);
+
+       evbuffer_validate(src);
+
+       while (evbuffer_get_length(src) &&
+           (r = evbuffer_write(src, pair[0])) > 0) {
+               evbuffer_validate(src);
+               n_written += r;
+       }
+       tt_int_op(r, !=, -1);
+       tt_int_op(n_written, ==, datalen);
+
+       evbuffer_validate(src);
+       tt_int_op(evbuffer_read(src, pair[1], (int)strlen(data)), ==, datalen);
+       evbuffer_validate(src);
+       compare = (char *)evbuffer_pullup(src, datalen);
+       tt_assert(compare != NULL);
+       if (memcmp(compare, data, datalen))
+               tt_abort_msg("Data from add_file differs.");
+
+       evbuffer_validate(src);
+ end:
+       if (pair[0] >= 0)
+               evutil_closesocket(pair[0]);
+       if (pair[1] >= 0)
+               evutil_closesocket(pair[1]);
+       evbuffer_free(src);
+}
+
+#ifndef _EVENT_DISABLE_MM_REPLACEMENT
+static void *
+failing_malloc(size_t how_much)
+{
+       errno = ENOMEM;
+       return NULL;
+}
+#endif
+
+static void
+test_evbuffer_readln(void *ptr)
+{
+       struct evbuffer *evb = evbuffer_new();
+       struct evbuffer *evb_tmp = evbuffer_new();
+       const char *s;
+       char *cp = NULL;
+       size_t sz;
+
+#define tt_line_eq(content)                                            \
+       TT_STMT_BEGIN                                                   \
+       if (!cp || sz != strlen(content) || strcmp(cp, content)) {      \
+               TT_DIE(("Wanted %s; got %s [%d]", content, cp, (int)sz)); \
+       }                                                               \
+       TT_STMT_END
+
+       /* Test EOL_ANY. */
+       s = "complex silly newline\r\n\n\r\n\n\rmore\0\n";
+       evbuffer_add(evb, s, strlen(s)+2);
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
+       tt_line_eq("complex silly newline");
+       free(cp);
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
+       if (!cp || sz != 5 || memcmp(cp, "more\0\0", 6))
+               tt_abort_msg("Not as expected");
+       tt_uint_op(evbuffer_get_length(evb), ==, 0);
+       evbuffer_validate(evb);
+       s = "\nno newline";
+       evbuffer_add(evb, s, strlen(s));
+       free(cp);
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
+       tt_line_eq("");
+       free(cp);
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
+       tt_assert(!cp);
+       evbuffer_validate(evb);
+       evbuffer_drain(evb, evbuffer_get_length(evb));
+       tt_assert(evbuffer_get_length(evb) == 0);
+       evbuffer_validate(evb);
+
+       /* Test EOL_CRLF */
+       s = "Line with\rin the middle\nLine with good crlf\r\n\nfinal\n";
+       evbuffer_add(evb, s, strlen(s));
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+       tt_line_eq("Line with\rin the middle");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+       tt_line_eq("Line with good crlf");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+       tt_line_eq("");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+       tt_line_eq("final");
+       s = "x";
+       evbuffer_validate(evb);
+       evbuffer_add(evb, s, 1);
+       evbuffer_validate(evb);
+       free(cp);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+       tt_assert(!cp);
+       evbuffer_validate(evb);
+
+       /* Test CRLF_STRICT */
+       s = " and a bad crlf\nand a good one\r\n\r\nMore\r";
+       evbuffer_add(evb, s, strlen(s));
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_line_eq("x and a bad crlf\nand a good one");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_line_eq("");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_assert(!cp);
+       evbuffer_validate(evb);
+       evbuffer_add(evb, "\n", 1);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_line_eq("More");
+       free(cp);
+       tt_assert(evbuffer_get_length(evb) == 0);
+       evbuffer_validate(evb);
+
+       s = "An internal CR\r is not an eol\r\nNor is a lack of one";
+       evbuffer_add(evb, s, strlen(s));
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_line_eq("An internal CR\r is not an eol");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_assert(!cp);
+       evbuffer_validate(evb);
+
+       evbuffer_add(evb, "\r\n", 2);
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_line_eq("Nor is a lack of one");
+       free(cp);
+       tt_assert(evbuffer_get_length(evb) == 0);
+       evbuffer_validate(evb);
+
+       /* Test LF */
+       s = "An\rand a nl\n\nText";
+       evbuffer_add(evb, s, strlen(s));
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+       tt_line_eq("An\rand a nl");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+       tt_line_eq("");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+       tt_assert(!cp);
+       free(cp);
+       evbuffer_add(evb, "\n", 1);
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+       tt_line_eq("Text");
+       free(cp);
+       evbuffer_validate(evb);
+
+       /* Test CRLF_STRICT - across boundaries*/
+       s = " and a bad crlf\nand a good one\r";
+       evbuffer_add(evb_tmp, s, strlen(s));
+       evbuffer_validate(evb);
+       evbuffer_add_buffer(evb, evb_tmp);
+       evbuffer_validate(evb);
+       s = "\n\r";
+       evbuffer_add(evb_tmp, s, strlen(s));
+       evbuffer_validate(evb);
+       evbuffer_add_buffer(evb, evb_tmp);
+       evbuffer_validate(evb);
+       s = "\nMore\r";
+       evbuffer_add(evb_tmp, s, strlen(s));
+       evbuffer_validate(evb);
+       evbuffer_add_buffer(evb, evb_tmp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_line_eq(" and a bad crlf\nand a good one");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_line_eq("");
+       free(cp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_assert(!cp);
+       free(cp);
+       evbuffer_validate(evb);
+       evbuffer_add(evb, "\n", 1);
+       evbuffer_validate(evb);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+       tt_line_eq("More");
+       free(cp); cp = NULL;
+       evbuffer_validate(evb);
+       tt_assert(evbuffer_get_length(evb) == 0);
+
+       /* Test memory problem*/
+       s = "one line\ntwo line\nblue line";
+       evbuffer_add(evb_tmp, s, strlen(s));
+       evbuffer_validate(evb);
+       evbuffer_add_buffer(evb, evb_tmp);
+       evbuffer_validate(evb);
+
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+       tt_line_eq("one line");
+       free(cp); cp = NULL;
+       evbuffer_validate(evb);
+
+       /* the next call to readline should fail */
+#ifndef _EVENT_DISABLE_MM_REPLACEMENT
+       event_set_mem_functions(failing_malloc, realloc, free);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+       tt_assert(cp == NULL);
+       evbuffer_validate(evb);
+
+       /* now we should get the next line back */
+       event_set_mem_functions(malloc, realloc, free);
+#endif
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+       tt_line_eq("two line");
+       free(cp); cp = NULL;
+       evbuffer_validate(evb);
+
+ end:
+       evbuffer_free(evb);
+       evbuffer_free(evb_tmp);
+       if (cp) free(cp);
+}
+
+static void
+test_evbuffer_search_eol(void *ptr)
+{
+       struct evbuffer *buf = evbuffer_new();
+       struct evbuffer_ptr ptr1, ptr2;
+       const char *s;
+       size_t eol_len;
+
+       s = "string! \r\n\r\nx\n";
+       evbuffer_add(buf, s, strlen(s));
+       eol_len = -1;
+       ptr1 = evbuffer_search_eol(buf, NULL, &eol_len, EVBUFFER_EOL_CRLF);
+       tt_int_op(ptr1.pos, ==, 8);
+       tt_int_op(eol_len, ==, 2);
+
+       eol_len = -1;
+       ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_CRLF);
+       tt_int_op(ptr2.pos, ==, 8);
+       tt_int_op(eol_len, ==, 2);
+
+       evbuffer_ptr_set(buf, &ptr1, 1, EVBUFFER_PTR_ADD);
+       eol_len = -1;
+       ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_CRLF);
+       tt_int_op(ptr2.pos, ==, 9);
+       tt_int_op(eol_len, ==, 1);
+
+       eol_len = -1;
+       ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_CRLF_STRICT);
+       tt_int_op(ptr2.pos, ==, 10);
+       tt_int_op(eol_len, ==, 2);
+
+       eol_len = -1;
+       ptr1 = evbuffer_search_eol(buf, NULL, &eol_len, EVBUFFER_EOL_LF);
+       tt_int_op(ptr1.pos, ==, 9);
+       tt_int_op(eol_len, ==, 1);
+
+       eol_len = -1;
+       ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_LF);
+       tt_int_op(ptr2.pos, ==, 9);
+       tt_int_op(eol_len, ==, 1);
+
+       evbuffer_ptr_set(buf, &ptr1, 1, EVBUFFER_PTR_ADD);
+       eol_len = -1;
+       ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_LF);
+       tt_int_op(ptr2.pos, ==, 11);
+       tt_int_op(eol_len, ==, 1);
+
+end:
+       evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_iterative(void *ptr)
+{
+       struct evbuffer *buf = evbuffer_new();
+       const char *abc = "abcdefghijklmnopqrstvuwxyzabcdefghijklmnopqrstvuwxyzabcdefghijklmnopqrstvuwxyzabcdefghijklmnopqrstvuwxyz";
+       unsigned i, j, sum, n;
+
+       sum = 0;
+       n = 0;
+       for (i = 0; i < 1000; ++i) {
+               for (j = 1; j < strlen(abc); ++j) {
+                       char format[32];
+                       evutil_snprintf(format, sizeof(format), "%%%u.%us", j, j);
+                       evbuffer_add_printf(buf, format, abc);
+
+                       /* Only check for rep violations every so often.
+                          Walking over the whole list of chains can get
+                          pretty expensive as it gets long.
+                        */
+                       if ((n % 337) == 0)
+                               evbuffer_validate(buf);
+
+                       sum += j;
+                       n++;
+               }
+       }
+       evbuffer_validate(buf);
+
+       tt_uint_op(sum, ==, evbuffer_get_length(buf));
+
+       {
+               size_t a,w,u;
+               a=w=u=0;
+               evbuffer_get_waste(buf, &a, &w, &u);
+               if (0)
+                       printf("Allocated: %u.\nWasted: %u.\nUsed: %u.",
+                           (unsigned)a, (unsigned)w, (unsigned)u);
+               tt_assert( ((double)w)/a < .125);
+       }
+ end:
+       evbuffer_free(buf);
+
+}
+
+static void
+test_evbuffer_find(void *ptr)
+{
+       u_char* p;
+       const char* test1 = "1234567890\r\n";
+       const char* test2 = "1234567890\r";
+#define EVBUFFER_INITIAL_LENGTH 256
+       char test3[EVBUFFER_INITIAL_LENGTH];
+       unsigned int i;
+       struct evbuffer * buf = evbuffer_new();
+
+       /* make sure evbuffer_find doesn't match past the end of the buffer */
+       evbuffer_add(buf, (u_char*)test1, strlen(test1));
+       evbuffer_validate(buf);
+       evbuffer_drain(buf, strlen(test1));
+       evbuffer_validate(buf);
+       evbuffer_add(buf, (u_char*)test2, strlen(test2));
+       evbuffer_validate(buf);
+       p = evbuffer_find(buf, (u_char*)"\r\n", 2);
+       tt_want(p == NULL);
+
+       /*
+        * drain the buffer and do another find; in r309 this would
+        * read past the allocated buffer causing a valgrind error.
+        */
+       evbuffer_drain(buf, strlen(test2));
+       evbuffer_validate(buf);
+       for (i = 0; i < EVBUFFER_INITIAL_LENGTH; ++i)
+               test3[i] = 'a';
+       test3[EVBUFFER_INITIAL_LENGTH - 1] = 'x';
+       evbuffer_add(buf, (u_char *)test3, EVBUFFER_INITIAL_LENGTH);
+       evbuffer_validate(buf);
+       p = evbuffer_find(buf, (u_char *)"xy", 2);
+       tt_want(p == NULL);
+
+       /* simple test for match at end of allocated buffer */
+       p = evbuffer_find(buf, (u_char *)"ax", 2);
+       tt_assert(p != NULL);
+       tt_want(strncmp((char*)p, "ax", 2) == 0);
+
+end:
+       if (buf)
+               evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_ptr_set(void *ptr)
+{
+       struct evbuffer *buf = evbuffer_new();
+       struct evbuffer_ptr pos;
+       struct evbuffer_iovec v[1];
+
+       /* create some chains */
+       evbuffer_reserve_space(buf, 5000, v, 1);
+       v[0].iov_len = 5000;
+       memset(v[0].iov_base, 1, v[0].iov_len);
+       evbuffer_commit_space(buf, v, 1);
+       evbuffer_validate(buf);
+
+       evbuffer_reserve_space(buf, 4000, v, 1);
+       v[0].iov_len = 4000;
+       memset(v[0].iov_base, 2, v[0].iov_len);
+       evbuffer_commit_space(buf, v, 1);
+
+       evbuffer_reserve_space(buf, 3000, v, 1);
+       v[0].iov_len = 3000;
+       memset(v[0].iov_base, 3, v[0].iov_len);
+       evbuffer_commit_space(buf, v, 1);
+       evbuffer_validate(buf);
+
+       tt_int_op(evbuffer_get_length(buf), ==, 12000);
+
+       tt_assert(evbuffer_ptr_set(buf, &pos, 13000, EVBUFFER_PTR_SET) == -1);
+       tt_assert(pos.pos == -1);
+       tt_assert(evbuffer_ptr_set(buf, &pos, 0, EVBUFFER_PTR_SET) == 0);
+       tt_assert(pos.pos == 0);
+       tt_assert(evbuffer_ptr_set(buf, &pos, 13000, EVBUFFER_PTR_ADD) == -1);
+
+       tt_assert(evbuffer_ptr_set(buf, &pos, 0, EVBUFFER_PTR_SET) == 0);
+       tt_assert(pos.pos == 0);
+       tt_assert(evbuffer_ptr_set(buf, &pos, 10000, EVBUFFER_PTR_ADD) == 0);
+       tt_assert(pos.pos == 10000);
+       tt_assert(evbuffer_ptr_set(buf, &pos, 1000, EVBUFFER_PTR_ADD) == 0);
+       tt_assert(pos.pos == 11000);
+       tt_assert(evbuffer_ptr_set(buf, &pos, 1000, EVBUFFER_PTR_ADD) == -1);
+       tt_assert(pos.pos == -1);
+
+end:
+       if (buf)
+               evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_search(void *ptr)
+{
+       struct evbuffer *buf = evbuffer_new();
+       struct evbuffer *tmp = evbuffer_new();
+       struct evbuffer_ptr pos, end;
+
+       /* set up our chains */
+       evbuffer_add_printf(tmp, "hello");  /* 5 chars */
+       evbuffer_add_buffer(buf, tmp);
+       evbuffer_add_printf(tmp, "foo");    /* 3 chars */
+       evbuffer_add_buffer(buf, tmp);
+       evbuffer_add_printf(tmp, "cat");    /* 3 chars */
+       evbuffer_add_buffer(buf, tmp);
+       evbuffer_add_printf(tmp, "attack");
+       evbuffer_add_buffer(buf, tmp);
+
+       pos = evbuffer_search(buf, "attack", 6, NULL);
+       tt_int_op(pos.pos, ==, 11);
+       pos = evbuffer_search(buf, "attacker", 8, NULL);
+       tt_int_op(pos.pos, ==, -1);
+
+       /* test continuing search */
+       pos = evbuffer_search(buf, "oc", 2, NULL);
+       tt_int_op(pos.pos, ==, 7);
+       pos = evbuffer_search(buf, "cat", 3, &pos);
+       tt_int_op(pos.pos, ==, 8);
+       pos = evbuffer_search(buf, "tacking", 7, &pos);
+       tt_int_op(pos.pos, ==, -1);
+
+       evbuffer_ptr_set(buf, &pos, 5, EVBUFFER_PTR_SET);
+       pos = evbuffer_search(buf, "foo", 3, &pos);
+       tt_int_op(pos.pos, ==, 5);
+
+       evbuffer_ptr_set(buf, &pos, 2, EVBUFFER_PTR_ADD);
+       pos = evbuffer_search(buf, "tat", 3, &pos);
+       tt_int_op(pos.pos, ==, 10);
+
+       /* test bounded search. */
+       /* Set "end" to the first t in "attack". */
+       evbuffer_ptr_set(buf, &end, 12, EVBUFFER_PTR_SET);
+       pos = evbuffer_search_range(buf, "foo", 3, NULL, &end);
+       tt_int_op(pos.pos, ==, 5);
+       pos = evbuffer_search_range(buf, "foocata", 7, NULL, &end);
+       tt_int_op(pos.pos, ==, 5);
+       pos = evbuffer_search_range(buf, "foocatat", 8, NULL, &end);
+       tt_int_op(pos.pos, ==, -1);
+       pos = evbuffer_search_range(buf, "ack", 3, NULL, &end);
+       tt_int_op(pos.pos, ==, -1);
+
+
+end:
+       if (buf)
+               evbuffer_free(buf);
+       if (tmp)
+               evbuffer_free(tmp);
+}
+
+static void
+log_change_callback(struct evbuffer *buffer,
+    const struct evbuffer_cb_info *cbinfo,
+    void *arg)
+{
+
+       size_t old_len = cbinfo->orig_size;
+       size_t new_len = old_len + cbinfo->n_added - cbinfo->n_deleted;
+       struct evbuffer *out = arg;
+       evbuffer_add_printf(out, "%lu->%lu; ", (unsigned long)old_len,
+                           (unsigned long)new_len);
+}
+static void
+self_draining_callback(struct evbuffer *evbuffer, size_t old_len,
+               size_t new_len, void *arg)
+{
+       if (new_len > old_len)
+               evbuffer_drain(evbuffer, new_len);
+}
+
+static void
+test_evbuffer_callbacks(void *ptr)
+{
+       struct evbuffer *buf = evbuffer_new();
+       struct evbuffer *buf_out1 = evbuffer_new();
+       struct evbuffer *buf_out2 = evbuffer_new();
+       struct evbuffer_cb_entry *cb1, *cb2;
+
+       cb1 = evbuffer_add_cb(buf, log_change_callback, buf_out1);
+       cb2 = evbuffer_add_cb(buf, log_change_callback, buf_out2);
+
+       /* Let's run through adding and deleting some stuff from the buffer
+        * and turning the callbacks on and off and removing them.  The callback
+        * adds a summary of length changes to buf_out1/buf_out2 when called. */
+       /* size: 0-> 36. */
+       evbuffer_add_printf(buf, "The %d magic words are spotty pudding", 2);
+       evbuffer_validate(buf);
+       evbuffer_cb_clear_flags(buf, cb2, EVBUFFER_CB_ENABLED);
+       evbuffer_drain(buf, 10); /*36->26*/
+       evbuffer_validate(buf);
+       evbuffer_prepend(buf, "Hello", 5);/*26->31*/
+       evbuffer_cb_set_flags(buf, cb2, EVBUFFER_CB_ENABLED);
+       evbuffer_add_reference(buf, "Goodbye", 7, NULL, NULL); /*31->38*/
+       evbuffer_remove_cb_entry(buf, cb1);
+       evbuffer_validate(buf);
+       evbuffer_drain(buf, evbuffer_get_length(buf)); /*38->0*/;
+       tt_assert(-1 == evbuffer_remove_cb(buf, log_change_callback, NULL));
+       evbuffer_add(buf, "X", 1); /* 0->1 */
+       tt_assert(!evbuffer_remove_cb(buf, log_change_callback, buf_out2));
+       evbuffer_validate(buf);
+
+       tt_str_op(evbuffer_pullup(buf_out1, -1), ==,
+                 "0->36; 36->26; 26->31; 31->38; ");
+       tt_str_op(evbuffer_pullup(buf_out2, -1), ==,
+                 "0->36; 31->38; 38->0; 0->1; ");
+       evbuffer_drain(buf_out1, evbuffer_get_length(buf_out1));
+       evbuffer_drain(buf_out2, evbuffer_get_length(buf_out2));
+       /* Let's test the obsolete buffer_setcb function too. */
+       cb1 = evbuffer_add_cb(buf, log_change_callback, buf_out1);
+       tt_assert(cb1 != NULL);
+       cb2 = evbuffer_add_cb(buf, log_change_callback, buf_out2);
+       tt_assert(cb2 != NULL);
+       evbuffer_setcb(buf, self_draining_callback, NULL);
+       evbuffer_add_printf(buf, "This should get drained right away.");
+       tt_uint_op(evbuffer_get_length(buf), ==, 0);
+       tt_uint_op(evbuffer_get_length(buf_out1), ==, 0);
+       tt_uint_op(evbuffer_get_length(buf_out2), ==, 0);
+       evbuffer_setcb(buf, NULL, NULL);
+       evbuffer_add_printf(buf, "This will not.");
+       tt_str_op(evbuffer_pullup(buf, -1), ==, "This will not.");
+       evbuffer_validate(buf);
+       evbuffer_drain(buf, evbuffer_get_length(buf));
+       evbuffer_validate(buf);
+#if 0
+       /* Now let's try a suspended callback. */
+       cb1 = evbuffer_add_cb(buf, log_change_callback, buf_out1);
+       cb2 = evbuffer_add_cb(buf, log_change_callback, buf_out2);
+       evbuffer_cb_suspend(buf,cb2);
+       evbuffer_prepend(buf,"Hello world",11); /*0->11*/
+       evbuffer_validate(buf);
+       evbuffer_cb_suspend(buf,cb1);
+       evbuffer_add(buf,"more",4); /* 11->15 */
+       evbuffer_cb_unsuspend(buf,cb2);
+       evbuffer_drain(buf, 4); /* 15->11 */
+       evbuffer_cb_unsuspend(buf,cb1);
+       evbuffer_drain(buf, evbuffer_get_length(buf)); /* 11->0 */
+
+       tt_str_op(evbuffer_pullup(buf_out1, -1), ==,
+                 "0->11; 11->11; 11->0; ");
+       tt_str_op(evbuffer_pullup(buf_out2, -1), ==,
+                 "0->15; 15->11; 11->0; ");
+#endif
+
+ end:
+       if (buf)
+               evbuffer_free(buf);
+       if (buf_out1)
+               evbuffer_free(buf_out1);
+       if (buf_out2)
+               evbuffer_free(buf_out2);
+}
+
+static int ref_done_cb_called_count = 0;
+static void *ref_done_cb_called_with = NULL;
+static const void *ref_done_cb_called_with_data = NULL;
+static size_t ref_done_cb_called_with_len = 0;
+static void ref_done_cb(const void *data, size_t len, void *info)
+{
+       ++ref_done_cb_called_count;
+       ref_done_cb_called_with = info;
+       ref_done_cb_called_with_data = data;
+       ref_done_cb_called_with_len = len;
+}
+
+static void
+test_evbuffer_add_reference(void *ptr)
+{
+       const char chunk1[] = "If you have found the answer to such a problem";
+       const char chunk2[] = "you ought to write it up for publication";
+                         /* -- Knuth's "Notes on the Exercises" from TAOCP */
+       char tmp[16];
+       size_t len1 = strlen(chunk1), len2=strlen(chunk2);
+
+       struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+       buf1 = evbuffer_new();
+       tt_assert(buf1);
+
+       evbuffer_add_reference(buf1, chunk1, len1, ref_done_cb, (void*)111);
+       evbuffer_add(buf1, ", ", 2);
+       evbuffer_add_reference(buf1, chunk2, len2, ref_done_cb, (void*)222);
+       tt_int_op(evbuffer_get_length(buf1), ==, len1+len2+2);
+
+       /* Make sure we can drain a little from a reference. */
+       tt_int_op(evbuffer_remove(buf1, tmp, 6), ==, 6);
+       tt_int_op(memcmp(tmp, "If you", 6), ==, 0);
+       tt_int_op(evbuffer_remove(buf1, tmp, 5), ==, 5);
+       tt_int_op(memcmp(tmp, " have", 5), ==, 0);
+
+       /* Make sure that prepending does not meddle with immutable data */
+       tt_int_op(evbuffer_prepend(buf1, "I have ", 7), ==, 0);
+       tt_int_op(memcmp(chunk1, "If you", 6), ==, 0);
+       evbuffer_validate(buf1);
+
+       /* Make sure that when the chunk is over, the callback is invoked. */
+       evbuffer_drain(buf1, 7); /* Remove prepended stuff. */
+       evbuffer_drain(buf1, len1-11-1); /* remove all but one byte of chunk1 */
+       tt_int_op(ref_done_cb_called_count, ==, 0);
+       evbuffer_remove(buf1, tmp, 1);
+       tt_int_op(tmp[0], ==, 'm');
+       tt_assert(ref_done_cb_called_with == (void*)111);
+       tt_assert(ref_done_cb_called_with_data == chunk1);
+       tt_assert(ref_done_cb_called_with_len == len1);
+       tt_int_op(ref_done_cb_called_count, ==, 1);
+       evbuffer_validate(buf1);
+
+       /* Drain some of the remaining chunk, then add it to another buffer */
+       evbuffer_drain(buf1, 6); /* Remove the ", you ". */
+       buf2 = evbuffer_new();
+       tt_assert(buf2);
+       tt_int_op(ref_done_cb_called_count, ==, 1);
+       evbuffer_add(buf2, "I ", 2);
+
+       evbuffer_add_buffer(buf2, buf1);
+       tt_int_op(ref_done_cb_called_count, ==, 1);
+       evbuffer_remove(buf2, tmp, 16);
+       tt_int_op(memcmp("I ought to write", tmp, 16), ==, 0);
+       evbuffer_drain(buf2, evbuffer_get_length(buf2));
+       tt_int_op(ref_done_cb_called_count, ==, 2);
+       tt_assert(ref_done_cb_called_with == (void*)222);
+       evbuffer_validate(buf2);
+
+       /* Now add more stuff to buf1 and make sure that it gets removed on
+        * free. */
+       evbuffer_add(buf1, "You shake and shake the ", 24);
+       evbuffer_add_reference(buf1, "ketchup bottle", 14, ref_done_cb,
+           (void*)3333);
+       evbuffer_add(buf1, ". Nothing comes and then a lot'll.", 42);
+       evbuffer_free(buf1);
+       buf1 = NULL;
+       tt_int_op(ref_done_cb_called_count, ==, 3);
+       tt_assert(ref_done_cb_called_with == (void*)3333);
+
+end:
+       if (buf1)
+               evbuffer_free(buf1);
+       if (buf2)
+               evbuffer_free(buf2);
+}
+
+/* Some cases that we didn't get in test_evbuffer() above, for more coverage. */
+static void
+test_evbuffer_prepend(void *ptr)
+{
+       struct evbuffer *buf1 = NULL, *buf2 = NULL;
+       char tmp[128];
+       int n;
+
+       buf1 = evbuffer_new();
+       tt_assert(buf1);
+
+       /* Case 0: The evbuffer is entirely empty. */
+       evbuffer_prepend(buf1, "This string has 29 characters", 29);
+       evbuffer_validate(buf1);
+
+       /* Case 1: Prepend goes entirely in new chunk. */
+       evbuffer_prepend(buf1, "Short.", 6);
+       evbuffer_validate(buf1);
+
+       /* Case 2: prepend goes entirely in first chunk. */
+       evbuffer_drain(buf1, 6+11);
+       evbuffer_prepend(buf1, "it", 2);
+       evbuffer_validate(buf1);
+       tt_assert(!memcmp(buf1->first->buffer+buf1->first->misalign,
+               "it has", 6));
+
+       /* Case 3: prepend is split over multiple chunks. */
+       evbuffer_prepend(buf1, "It is no longer true to say ", 28);
+       evbuffer_validate(buf1);
+       n = evbuffer_remove(buf1, tmp, sizeof(tmp)-1);
+       tmp[n]='\0';
+       tt_str_op(tmp,==,"It is no longer true to say it has 29 characters");
+
+       buf2 = evbuffer_new();
+       tt_assert(buf2);
+
+       /* Case 4: prepend a buffer to an empty buffer. */
+       n = 999;
+       evbuffer_add_printf(buf1, "Here is string %d. ", n++);
+       evbuffer_prepend_buffer(buf2, buf1);
+       evbuffer_validate(buf2);
+
+       /* Case 5: prepend a buffer to a nonempty buffer. */
+       evbuffer_add_printf(buf1, "Here is string %d. ", n++);
+       evbuffer_prepend_buffer(buf2, buf1);
+       evbuffer_validate(buf2);
+       evbuffer_validate(buf1);
+       n = evbuffer_remove(buf2, tmp, sizeof(tmp)-1);
+       tmp[n]='\0';
+       tt_str_op(tmp,==,"Here is string 1000. Here is string 999. ");
+
+end:
+       if (buf1)
+               evbuffer_free(buf1);
+       if (buf2)
+               evbuffer_free(buf2);
+
+}
+
+static void
+test_evbuffer_peek(void *info)
+{
+       struct evbuffer *buf = NULL, *tmp_buf = NULL;
+       int i;
+       struct evbuffer_iovec v[20];
+       struct evbuffer_ptr ptr;
+
+#define tt_iov_eq(v, s)                                                \
+       tt_int_op((v)->iov_len, ==, strlen(s));                 \
+       tt_assert(!memcmp((v)->iov_base, (s), strlen(s)))
+
+       /* Let's make a very fragmented buffer. */
+       buf = evbuffer_new();
+       tmp_buf = evbuffer_new();
+       for (i = 0; i < 16; ++i) {
+               evbuffer_add_printf(tmp_buf, "Contents of chunk [%d]\n", i);
+               evbuffer_add_buffer(buf, tmp_buf);
+       }
+
+       /* How many chunks do we need for everything? */
+       i = evbuffer_peek(buf, -1, NULL, NULL, 0);
+       tt_int_op(i, ==, 16);
+
+       /* Simple peek: get everything. */
+       i = evbuffer_peek(buf, -1, NULL, v, 20);
+       tt_int_op(i, ==, 16); /* we used only 16 chunks. */
+       tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+       tt_iov_eq(&v[3], "Contents of chunk [3]\n");
+       tt_iov_eq(&v[12], "Contents of chunk [12]\n");
+       tt_iov_eq(&v[15], "Contents of chunk [15]\n");
+
+       /* Just get one chunk worth. */
+       memset(v, 0, sizeof(v));
+       i = evbuffer_peek(buf, -1, NULL, v, 1);
+       tt_int_op(i, ==, 1);
+       tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+       tt_assert(v[1].iov_base == NULL);
+
+       /* Suppose we want at least the first 40 bytes. */
+       memset(v, 0, sizeof(v));
+       i = evbuffer_peek(buf, 40, NULL, v, 16);
+       tt_int_op(i, ==, 2);
+       tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+       tt_iov_eq(&v[1], "Contents of chunk [1]\n");
+       tt_assert(v[2].iov_base == NULL);
+
+       /* How many chunks do we need for 100 bytes? */
+       memset(v, 0, sizeof(v));
+       i = evbuffer_peek(buf, 100, NULL, NULL, 0);
+       tt_int_op(i, ==, 5);
+       tt_assert(v[0].iov_base == NULL);
+
+       /* Now we ask for more bytes than we provide chunks for */
+       memset(v, 0, sizeof(v));
+       i = evbuffer_peek(buf, 60, NULL, v, 1);
+       tt_int_op(i, ==, 3);
+       tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+       tt_assert(v[1].iov_base == NULL);
+
+       /* Now we ask for more bytes than the buffer has. */
+       memset(v, 0, sizeof(v));
+       i = evbuffer_peek(buf, 65536, NULL, v, 20);
+       tt_int_op(i, ==, 16); /* we used only 16 chunks. */
+       tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+       tt_iov_eq(&v[3], "Contents of chunk [3]\n");
+       tt_iov_eq(&v[12], "Contents of chunk [12]\n");
+       tt_iov_eq(&v[15], "Contents of chunk [15]\n");
+       tt_assert(v[16].iov_base == NULL);
+
+       /* What happens if we try an empty buffer? */
+       memset(v, 0, sizeof(v));
+       i = evbuffer_peek(tmp_buf, -1, NULL, v, 20);
+       tt_int_op(i, ==, 0);
+       tt_assert(v[0].iov_base == NULL);
+       memset(v, 0, sizeof(v));
+       i = evbuffer_peek(tmp_buf, 50, NULL, v, 20);
+       tt_int_op(i, ==, 0);
+       tt_assert(v[0].iov_base == NULL);
+
+       /* Okay, now time to have fun with pointers. */
+       memset(v, 0, sizeof(v));
+       evbuffer_ptr_set(buf, &ptr, 30, EVBUFFER_PTR_SET);
+       i = evbuffer_peek(buf, 50, &ptr, v, 20);
+       tt_int_op(i, ==, 3);
+       tt_iov_eq(&v[0], " of chunk [1]\n");
+       tt_iov_eq(&v[1], "Contents of chunk [2]\n");
+       tt_iov_eq(&v[2], "Contents of chunk [3]\n"); /*more than we asked for*/
+
+       /* advance to the start of another chain. */
+       memset(v, 0, sizeof(v));
+       evbuffer_ptr_set(buf, &ptr, 14, EVBUFFER_PTR_ADD);
+       i = evbuffer_peek(buf, 44, &ptr, v, 20);
+       tt_int_op(i, ==, 2);
+       tt_iov_eq(&v[0], "Contents of chunk [2]\n");
+       tt_iov_eq(&v[1], "Contents of chunk [3]\n"); /*more than we asked for*/
+
+end:
+       if (buf)
+               evbuffer_free(buf);
+       if (tmp_buf)
+               evbuffer_free(tmp_buf);
+}
+
+/* Check whether evbuffer freezing works right.  This is called twice,
+   once with the argument "start" and once with the argument "end".
+   When we test "start", we freeze the start of an evbuffer and make sure
+   that modifying the start of the buffer doesn't work.  When we test
+   "end", we freeze the end of an evbuffer and make sure that modifying
+   the end of the buffer doesn't work.
+ */
+static void
+test_evbuffer_freeze(void *ptr)
+{
+       struct evbuffer *buf = NULL, *tmp_buf=NULL;
+       const char string[] = /* Year's End, Richard Wilbur */
+           "I've known the wind by water banks to shake\n"
+           "The late leaves down, which frozen where they fell\n"
+           "And held in ice as dancers in a spell\n"
+           "Fluttered all winter long into a lake...";
+       const int start = !strcmp(ptr, "start");
+       char *cp;
+       char charbuf[128];
+       int r;
+       size_t orig_length;
+       struct evbuffer_iovec v[1];
+
+       if (!start)
+               tt_str_op(ptr, ==, "end");
+
+       buf = evbuffer_new();
+       tmp_buf = evbuffer_new();
+       tt_assert(tmp_buf);
+
+       evbuffer_add(buf, string, strlen(string));
+       evbuffer_freeze(buf, start); /* Freeze the start or the end.*/
+
+#define FREEZE_EQ(a, startcase, endcase)               \
+       do {                                            \
+           if (start) {                                \
+                   tt_int_op((a), ==, (startcase));    \
+           } else {                                    \
+                   tt_int_op((a), ==, (endcase));      \
+           }                                           \
+       } while (0)
+
+
+       orig_length = evbuffer_get_length(buf);
+
+       /* These functions all manipulate the end of buf. */
+       r = evbuffer_add(buf, "abc", 0);
+       FREEZE_EQ(r, 0, -1);
+       r = evbuffer_reserve_space(buf, 10, v, 1);
+       FREEZE_EQ(r, 1, -1);
+       if (r == 0) {
+               memset(v[0].iov_base, 'X', 10);
+               v[0].iov_len = 10;
+       }
+       r = evbuffer_commit_space(buf, v, 1);
+       FREEZE_EQ(r, 0, -1);
+       r = evbuffer_add_reference(buf, string, 5, NULL, NULL);
+       FREEZE_EQ(r, 0, -1);
+       r = evbuffer_add_printf(buf, "Hello %s", "world");
+       FREEZE_EQ(r, 11, -1);
+       /* TODO: test add_buffer, add_file, read */
+
+       if (!start)
+               tt_int_op(orig_length, ==, evbuffer_get_length(buf));
+
+       orig_length = evbuffer_get_length(buf);
+
+       /* These functions all manipulate the start of buf. */
+       r = evbuffer_remove(buf, charbuf, 1);
+       FREEZE_EQ(r, -1, 1);
+       r = evbuffer_drain(buf, 3);
+       FREEZE_EQ(r, -1, 0);
+       r = evbuffer_prepend(buf, "dummy", 5);
+       FREEZE_EQ(r, -1, 0);
+       cp = evbuffer_readln(buf, NULL, EVBUFFER_EOL_LF);
+       FREEZE_EQ(cp==NULL, 1, 0);
+       if (cp)
+               free(cp);
+       /* TODO: Test remove_buffer, add_buffer, write, prepend_buffer */
+
+       if (start)
+               tt_int_op(orig_length, ==, evbuffer_get_length(buf));
+
+end:
+       if (buf)
+               evbuffer_free(buf);
+
+       if (tmp_buf)
+               evbuffer_free(tmp_buf);
+}
+
+static void *
+setup_passthrough(const struct testcase_t *testcase)
+{
+       return testcase->setup_data;
+}
+static int
+cleanup_passthrough(const struct testcase_t *testcase, void *ptr)
+{
+       (void) ptr;
+       return 1;
+}
+
+static const struct testcase_setup_t nil_setup = {
+       setup_passthrough,
+       cleanup_passthrough
+};
+
+struct testcase_t evbuffer_testcases[] = {
+       { "evbuffer", test_evbuffer, 0, NULL, NULL },
+       { "remove_buffer_with_empty", test_evbuffer_remove_buffer_with_empty, 0, NULL, NULL },
+       { "reserve2", test_evbuffer_reserve2, 0, NULL, NULL },
+       { "reserve_many", test_evbuffer_reserve_many, 0, NULL, NULL },
+       { "reserve_many2", test_evbuffer_reserve_many, 0, &nil_setup, (void*)"add" },
+       { "reserve_many3", test_evbuffer_reserve_many, 0, &nil_setup, (void*)"fill" },
+       { "expand", test_evbuffer_expand, 0, NULL, NULL },
+       { "reference", test_evbuffer_reference, 0, NULL, NULL },
+       { "iterative", test_evbuffer_iterative, 0, NULL, NULL },
+       { "readln", test_evbuffer_readln, TT_NO_LOGS, &basic_setup, NULL },
+       { "search_eol", test_evbuffer_search_eol, 0, NULL, NULL },
+       { "find", test_evbuffer_find, 0, NULL, NULL },
+       { "ptr_set", test_evbuffer_ptr_set, 0, NULL, NULL },
+       { "search", test_evbuffer_search, 0, NULL, NULL },
+       { "callbacks", test_evbuffer_callbacks, 0, NULL, NULL },
+       { "add_reference", test_evbuffer_add_reference, 0, NULL, NULL },
+       { "prepend", test_evbuffer_prepend, TT_FORK, NULL, NULL },
+       { "peek", test_evbuffer_peek, 0, NULL, NULL },
+       { "freeze_start", test_evbuffer_freeze, 0, &nil_setup, (void*)"start" },
+       { "freeze_end", test_evbuffer_freeze, 0, &nil_setup, (void*)"end" },
+       /* TODO: need a temp file implementation for Windows */
+       { "add_file_sendfile", test_evbuffer_add_file, TT_FORK, &nil_setup,
+         (void*)"sendfile" },
+       { "add_file_mmap", test_evbuffer_add_file, TT_FORK, &nil_setup,
+         (void*)"mmap" },
+       { "add_file_linear", test_evbuffer_add_file, TT_FORK, &nil_setup,
+         (void*)"linear" },
+
+       END_OF_TESTCASES
+};
diff --git a/libevent/test/regress_bufferevent.c b/libevent/test/regress_bufferevent.c
new file mode 100644 (file)
index 0000000..2a7097c
--- /dev/null
@@ -0,0 +1,835 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+/* The old tests here need assertions to work. */
+#undef NDEBUG
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#endif
+#include <fcntl.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+
+#ifdef _EVENT_HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+
+#include "event2/event-config.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/event_compat.h"
+#include "event2/tag.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/listener.h"
+#include "event2/util.h"
+
+#include "bufferevent-internal.h"
+#ifdef WIN32
+#include "iocp-internal.h"
+#endif
+
+#include "regress.h"
+#include "regress_testutils.h"
+
+/*
+ * simple bufferevent test
+ */
+
+static void
+readcb(struct bufferevent *bev, void *arg)
+{
+       if (evbuffer_get_length(bev->input) == 8333) {
+               struct evbuffer *evbuf = evbuffer_new();
+               assert(evbuf != NULL);
+
+               /* gratuitous test of bufferevent_read_buffer */
+               bufferevent_read_buffer(bev, evbuf);
+
+               bufferevent_disable(bev, EV_READ);
+
+               if (evbuffer_get_length(evbuf) == 8333) {
+                       test_ok++;
+               }
+
+               evbuffer_free(evbuf);
+       }
+}
+
+static void
+writecb(struct bufferevent *bev, void *arg)
+{
+       if (evbuffer_get_length(bev->output) == 0) {
+               test_ok++;
+       }
+}
+
+static void
+errorcb(struct bufferevent *bev, short what, void *arg)
+{
+       test_ok = -2;
+}
+
+static void
+test_bufferevent_impl(int use_pair)
+{
+       struct bufferevent *bev1 = NULL, *bev2 = NULL;
+       char buffer[8333];
+       int i;
+
+       if (use_pair) {
+               struct bufferevent *pair[2];
+               tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
+               bev1 = pair[0];
+               bev2 = pair[1];
+               bufferevent_setcb(bev1, readcb, writecb, errorcb, NULL);
+               bufferevent_setcb(bev2, readcb, writecb, errorcb, NULL);
+               tt_int_op(bufferevent_getfd(bev1), ==, -1);
+               tt_ptr_op(bufferevent_get_underlying(bev1), ==, NULL);
+               tt_ptr_op(bufferevent_pair_get_partner(bev1), ==, bev2);
+               tt_ptr_op(bufferevent_pair_get_partner(bev2), ==, bev1);
+       } else {
+               bev1 = bufferevent_new(pair[0], readcb, writecb, errorcb, NULL);
+               bev2 = bufferevent_new(pair[1], readcb, writecb, errorcb, NULL);
+               tt_int_op(bufferevent_getfd(bev1), ==, pair[0]);
+               tt_ptr_op(bufferevent_get_underlying(bev1), ==, NULL);
+               tt_ptr_op(bufferevent_pair_get_partner(bev1), ==, NULL);
+               tt_ptr_op(bufferevent_pair_get_partner(bev2), ==, NULL);
+       }
+
+       bufferevent_disable(bev1, EV_READ);
+       bufferevent_enable(bev2, EV_READ);
+
+       tt_int_op(bufferevent_get_enabled(bev1), ==, EV_WRITE);
+       tt_int_op(bufferevent_get_enabled(bev2), ==, EV_WRITE|EV_READ);
+
+       for (i = 0; i < (int)sizeof(buffer); i++)
+               buffer[i] = i;
+
+       bufferevent_write(bev1, buffer, sizeof(buffer));
+
+       event_dispatch();
+
+       bufferevent_free(bev1);
+       tt_ptr_op(bufferevent_pair_get_partner(bev2), ==, NULL);
+       bufferevent_free(bev2);
+
+       if (test_ok != 2)
+               test_ok = 0;
+end:
+       ;
+}
+
+static void
+test_bufferevent(void)
+{
+       test_bufferevent_impl(0);
+}
+
+static void
+test_bufferevent_pair(void)
+{
+       test_bufferevent_impl(1);
+}
+
+/*
+ * test watermarks and bufferevent
+ */
+
+static void
+wm_readcb(struct bufferevent *bev, void *arg)
+{
+       struct evbuffer *evbuf = evbuffer_new();
+       int len = (int)evbuffer_get_length(bev->input);
+       static int nread;
+
+       assert(len >= 10 && len <= 20);
+
+       assert(evbuf != NULL);
+
+       /* gratuitous test of bufferevent_read_buffer */
+       bufferevent_read_buffer(bev, evbuf);
+
+       nread += len;
+       if (nread == 65000) {
+               bufferevent_disable(bev, EV_READ);
+               test_ok++;
+       }
+
+       evbuffer_free(evbuf);
+}
+
+static void
+wm_writecb(struct bufferevent *bev, void *arg)
+{
+       assert(evbuffer_get_length(bev->output) <= 100);
+       if (evbuffer_get_length(bev->output) == 0) {
+               evbuffer_drain(bev->output, evbuffer_get_length(bev->output));
+               test_ok++;
+       }
+}
+
+static void
+wm_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+       test_ok = -2;
+}
+
+static void
+test_bufferevent_watermarks_impl(int use_pair)
+{
+       struct bufferevent *bev1 = NULL, *bev2 = NULL;
+       char buffer[65000];
+       int i;
+       test_ok = 0;
+
+       if (use_pair) {
+               struct bufferevent *pair[2];
+               tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
+               bev1 = pair[0];
+               bev2 = pair[1];
+               bufferevent_setcb(bev1, NULL, wm_writecb, errorcb, NULL);
+               bufferevent_setcb(bev2, wm_readcb, NULL, errorcb, NULL);
+       } else {
+               bev1 = bufferevent_new(pair[0], NULL, wm_writecb, wm_errorcb, NULL);
+               bev2 = bufferevent_new(pair[1], wm_readcb, NULL, wm_errorcb, NULL);
+       }
+       bufferevent_disable(bev1, EV_READ);
+       bufferevent_enable(bev2, EV_READ);
+
+       for (i = 0; i < (int)sizeof(buffer); i++)
+               buffer[i] = (char)i;
+
+       /* limit the reading on the receiving bufferevent */
+       bufferevent_setwatermark(bev2, EV_READ, 10, 20);
+
+       /* Tell the sending bufferevent not to notify us till it's down to
+          100 bytes. */
+       bufferevent_setwatermark(bev1, EV_WRITE, 100, 2000);
+
+       bufferevent_write(bev1, buffer, sizeof(buffer));
+
+       event_dispatch();
+
+       tt_int_op(test_ok, ==, 2);
+
+       /* The write callback drained all the data from outbuf, so we
+        * should have removed the write event... */
+       tt_assert(!event_pending(&bev2->ev_write, EV_WRITE, NULL));
+
+end:
+       bufferevent_free(bev1);
+       bufferevent_free(bev2);
+}
+
+static void
+test_bufferevent_watermarks(void)
+{
+       test_bufferevent_watermarks_impl(0);
+}
+
+static void
+test_bufferevent_pair_watermarks(void)
+{
+       test_bufferevent_watermarks_impl(1);
+}
+
+/*
+ * Test bufferevent filters
+ */
+
+/* strip an 'x' from each byte */
+
+static enum bufferevent_filter_result
+bufferevent_input_filter(struct evbuffer *src, struct evbuffer *dst,
+    ev_ssize_t lim, enum bufferevent_flush_mode state, void *ctx)
+{
+       const unsigned char *buffer;
+       unsigned i;
+
+       buffer = evbuffer_pullup(src, evbuffer_get_length(src));
+       for (i = 0; i < evbuffer_get_length(src); i += 2) {
+               assert(buffer[i] == 'x');
+               evbuffer_add(dst, buffer + i + 1, 1);
+
+               if (i + 2 > evbuffer_get_length(src))
+                       break;
+       }
+
+       evbuffer_drain(src, i);
+       return (BEV_OK);
+}
+
+/* add an 'x' before each byte */
+
+static enum bufferevent_filter_result
+bufferevent_output_filter(struct evbuffer *src, struct evbuffer *dst,
+    ev_ssize_t lim, enum bufferevent_flush_mode state, void *ctx)
+{
+       const unsigned char *buffer;
+       unsigned i;
+
+       buffer = evbuffer_pullup(src, evbuffer_get_length(src));
+       for (i = 0; i < evbuffer_get_length(src); ++i) {
+               evbuffer_add(dst, "x", 1);
+               evbuffer_add(dst, buffer + i, 1);
+       }
+
+       evbuffer_drain(src, evbuffer_get_length(src));
+       return (BEV_OK);
+}
+
+static void
+test_bufferevent_filters_impl(int use_pair)
+{
+       struct bufferevent *bev1 = NULL, *bev2 = NULL;
+       struct bufferevent *bev1_base = NULL, *bev2_base = NULL;
+       char buffer[8333];
+       int i;
+
+       test_ok = 0;
+
+       if (use_pair) {
+               struct bufferevent *pair[2];
+               tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
+               bev1 = pair[0];
+               bev2 = pair[1];
+       } else {
+               bev1 = bufferevent_socket_new(NULL, pair[0], 0);
+               bev2 = bufferevent_socket_new(NULL, pair[1], 0);
+       }
+       bev1_base = bev1;
+       bev2_base = bev2;
+
+       for (i = 0; i < (int)sizeof(buffer); i++)
+               buffer[i] = i;
+
+       bev1 = bufferevent_filter_new(bev1, NULL, bufferevent_output_filter,
+                                     BEV_OPT_CLOSE_ON_FREE, NULL, NULL);
+
+       bev2 = bufferevent_filter_new(bev2, bufferevent_input_filter,
+                                     NULL, BEV_OPT_CLOSE_ON_FREE, NULL, NULL);
+       bufferevent_setcb(bev1, NULL, writecb, errorcb, NULL);
+       bufferevent_setcb(bev2, readcb, NULL, errorcb, NULL);
+
+       tt_ptr_op(bufferevent_get_underlying(bev1), ==, bev1_base);
+       tt_ptr_op(bufferevent_get_underlying(bev2), ==, bev2_base);
+       tt_int_op(bufferevent_getfd(bev1), ==, -1);
+       tt_int_op(bufferevent_getfd(bev2), ==, -1);
+
+       bufferevent_disable(bev1, EV_READ);
+       bufferevent_enable(bev2, EV_READ);
+       /* insert some filters */
+       bufferevent_write(bev1, buffer, sizeof(buffer));
+
+       event_dispatch();
+
+       if (test_ok != 2)
+               test_ok = 0;
+
+end:
+       bufferevent_free(bev1);
+       bufferevent_free(bev2);
+
+}
+
+static void
+test_bufferevent_filters(void)
+{
+       test_bufferevent_filters_impl(0);
+}
+
+static void
+test_bufferevent_pair_filters(void)
+{
+       test_bufferevent_filters_impl(1);
+}
+
+
+static void
+sender_writecb(struct bufferevent *bev, void *ctx)
+{
+       if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+               bufferevent_disable(bev,EV_READ|EV_WRITE);
+               bufferevent_free(bev);
+       }
+}
+
+static void
+sender_errorcb(struct bufferevent *bev, short what, void *ctx)
+{
+       TT_FAIL(("Got sender error %d",(int)what));
+}
+
+static int bufferevent_connect_test_flags = 0;
+static int n_strings_read = 0;
+static int n_reads_invoked = 0;
+
+#define TEST_STR "Now is the time for all good events to signal for " \
+       "the good of their protocol"
+static void
+listen_cb(struct evconnlistener *listener, evutil_socket_t fd,
+    struct sockaddr *sa, int socklen, void *arg)
+{
+       struct event_base *base = arg;
+       struct bufferevent *bev;
+       const char s[] = TEST_STR;
+       TT_BLATHER(("Got a request on socket %d", (int)fd ));
+       bev = bufferevent_socket_new(base, fd, bufferevent_connect_test_flags);
+       tt_assert(bev);
+       bufferevent_setcb(bev, NULL, sender_writecb, sender_errorcb, NULL);
+       bufferevent_write(bev, s, sizeof(s));
+end:
+       ;
+}
+
+static void
+reader_eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+       struct event_base *base = ctx;
+       if (what & BEV_EVENT_ERROR) {
+               perror("foobar");
+               TT_FAIL(("got connector error %d", (int)what));
+               return;
+       }
+       if (what & BEV_EVENT_CONNECTED) {
+               bufferevent_enable(bev, EV_READ);
+       }
+       if (what & BEV_EVENT_EOF) {
+               char buf[512];
+               size_t n;
+               n = bufferevent_read(bev, buf, sizeof(buf)-1);
+               buf[n] = '\0';
+               tt_str_op(buf, ==, TEST_STR);
+               if (++n_strings_read == 2)
+                       event_base_loopexit(base, NULL);
+       }
+end:
+       ;
+}
+
+static void
+reader_readcb(struct bufferevent *bev, void *ctx)
+{
+       n_reads_invoked++;
+}
+
+static void
+test_bufferevent_connect(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct evconnlistener *lev=NULL;
+       struct bufferevent *bev1=NULL, *bev2=NULL;
+       struct sockaddr_in localhost;
+       struct sockaddr_storage ss;
+       struct sockaddr *sa;
+       ev_socklen_t slen;
+
+       int be_flags=BEV_OPT_CLOSE_ON_FREE;
+
+       if (strstr((char*)data->setup_data, "defer")) {
+               be_flags |= BEV_OPT_DEFER_CALLBACKS;
+       }
+       if (strstr((char*)data->setup_data, "unlocked")) {
+               be_flags |= BEV_OPT_UNLOCK_CALLBACKS;
+       }
+       if (strstr((char*)data->setup_data, "lock")) {
+               be_flags |= BEV_OPT_THREADSAFE;
+       }
+       bufferevent_connect_test_flags = be_flags;
+#ifdef WIN32
+       if (!strcmp((char*)data->setup_data, "unset_connectex")) {
+               struct win32_extension_fns *ext =
+                   (struct win32_extension_fns *)
+                   event_get_win32_extension_fns();
+               ext->ConnectEx = NULL;
+       }
+#endif
+
+       memset(&localhost, 0, sizeof(localhost));
+
+       localhost.sin_port = 0; /* pick-a-port */
+       localhost.sin_addr.s_addr = htonl(0x7f000001L);
+       localhost.sin_family = AF_INET;
+       sa = (struct sockaddr *)&localhost;
+       lev = evconnlistener_new_bind(data->base, listen_cb, data->base,
+           LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
+           16, sa, sizeof(localhost));
+       tt_assert(lev);
+
+       sa = (struct sockaddr *)&ss;
+       slen = sizeof(ss);
+       if (regress_get_listener_addr(lev, sa, &slen) < 0) {
+               tt_abort_perror("getsockname");
+       }
+
+       tt_assert(!evconnlistener_enable(lev));
+       bev1 = bufferevent_socket_new(data->base, -1, be_flags);
+       bev2 = bufferevent_socket_new(data->base, -1, be_flags);
+       tt_assert(bev1);
+       tt_assert(bev2);
+       bufferevent_setcb(bev1, reader_readcb,NULL, reader_eventcb, data->base);
+       bufferevent_setcb(bev2, reader_readcb,NULL, reader_eventcb, data->base);
+
+       bufferevent_enable(bev1, EV_READ);
+       bufferevent_enable(bev2, EV_READ);
+
+       tt_want(!bufferevent_socket_connect(bev1, sa, sizeof(localhost)));
+       tt_want(!bufferevent_socket_connect(bev2, sa, sizeof(localhost)));
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(n_strings_read, ==, 2);
+       tt_int_op(n_reads_invoked, >=, 2);
+end:
+       if (lev)
+               evconnlistener_free(lev);
+
+       if (bev1)
+               bufferevent_free(bev1);
+
+       if (bev2)
+               bufferevent_free(bev2);
+}
+
+static void
+want_fail_eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+       struct event_base *base = ctx;
+       const char *err;
+       evutil_socket_t s;
+
+       if (what & BEV_EVENT_ERROR) {
+               s = bufferevent_getfd(bev);
+               err = evutil_socket_error_to_string(evutil_socket_geterror(s));
+               TT_BLATHER(("connection failure on %d: %s", s, err));
+               test_ok = 1;
+       } else {
+               TT_FAIL(("didn't fail? what %hd", what));
+       }
+
+       event_base_loopexit(base, NULL);
+}
+
+static void
+close_socket_cb(evutil_socket_t fd, short what, void *arg)
+{
+       evutil_socket_t *fdp = arg;
+       if (*fdp >= 0) {
+               evutil_closesocket(*fdp);
+               *fdp = -1;
+       }
+}
+
+static void
+test_bufferevent_connect_fail(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct bufferevent *bev=NULL;
+       struct sockaddr_in localhost;
+       struct sockaddr *sa = (struct sockaddr*)&localhost;
+       evutil_socket_t fake_listener = -1;
+       ev_socklen_t slen = sizeof(localhost);
+       struct event close_listener_event;
+       int close_listener_event_added = 0;
+       struct timeval one_second = { 1, 0 };
+       int r;
+
+       test_ok = 0;
+
+       memset(&localhost, 0, sizeof(localhost));
+       localhost.sin_port = 0; /* have the kernel pick a port */
+       localhost.sin_addr.s_addr = htonl(0x7f000001L);
+       localhost.sin_family = AF_INET;
+
+       /* bind, but don't listen or accept. should trigger
+          "Connection refused" reliably on most platforms. */
+       fake_listener = socket(localhost.sin_family, SOCK_STREAM, 0);
+       tt_assert(fake_listener >= 0);
+       tt_assert(bind(fake_listener, sa, slen) == 0);
+       tt_assert(getsockname(fake_listener, sa, &slen) == 0);
+       bev = bufferevent_socket_new(data->base, -1,
+               BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
+       tt_assert(bev);
+       bufferevent_setcb(bev, NULL, NULL, want_fail_eventcb, data->base);
+
+       r = bufferevent_socket_connect(bev, sa, slen);
+       /* XXXX we'd like to test the '0' case everywhere, but FreeBSD tells
+        * detects the error immediately, which is not really wrong of it. */
+       tt_want(r == 0 || r == -1);
+
+       /* Close the listener socket after a second. This should trigger
+          "connection refused" on some other platforms, including OSX. */
+       evtimer_assign(&close_listener_event, data->base, close_socket_cb,
+           &fake_listener);
+       event_add(&close_listener_event, &one_second);
+       close_listener_event_added = 1;
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(test_ok, ==, 1);
+
+end:
+       if (fake_listener >= 0)
+               evutil_closesocket(fake_listener);
+
+       if (bev)
+               bufferevent_free(bev);
+
+       if (close_listener_event_added)
+               event_del(&close_listener_event);
+}
+
+struct timeout_cb_result {
+       struct timeval read_timeout_at;
+       struct timeval write_timeout_at;
+       struct timeval last_wrote_at;
+       int n_read_timeouts;
+       int n_write_timeouts;
+       int total_calls;
+};
+
+static void
+bev_timeout_write_cb(struct bufferevent *bev, void *arg)
+{
+       struct timeout_cb_result *res = arg;
+       evutil_gettimeofday(&res->last_wrote_at, NULL);
+}
+
+static void
+bev_timeout_event_cb(struct bufferevent *bev, short what, void *arg)
+{
+       struct timeout_cb_result *res = arg;
+       ++res->total_calls;
+
+       if ((what & (BEV_EVENT_READING|BEV_EVENT_TIMEOUT))
+           == (BEV_EVENT_READING|BEV_EVENT_TIMEOUT)) {
+               evutil_gettimeofday(&res->read_timeout_at, NULL);
+               ++res->n_read_timeouts;
+       }
+       if ((what & (BEV_EVENT_WRITING|BEV_EVENT_TIMEOUT))
+           == (BEV_EVENT_WRITING|BEV_EVENT_TIMEOUT)) {
+               evutil_gettimeofday(&res->write_timeout_at, NULL);
+               ++res->n_write_timeouts;
+       }
+}
+
+static void
+test_bufferevent_timeouts(void *arg)
+{
+       /* "arg" is a string containing "pair" and/or "filter". */
+       struct bufferevent *bev1 = NULL, *bev2 = NULL;
+       struct basic_test_data *data = arg;
+       int use_pair = 0, use_filter = 0;
+       struct timeval tv_w, tv_r, started_at;
+       struct timeout_cb_result res1, res2;
+       char buf[1024];
+
+       memset(&res1, 0, sizeof(res1));
+       memset(&res2, 0, sizeof(res2));
+
+       if (strstr((char*)data->setup_data, "pair"))
+               use_pair = 1;
+       if (strstr((char*)data->setup_data, "filter"))
+               use_filter = 1;
+
+       if (use_pair) {
+               struct bufferevent *p[2];
+               tt_int_op(0, ==, bufferevent_pair_new(data->base, 0, p));
+               bev1 = p[0];
+               bev2 = p[1];
+       } else {
+               bev1 = bufferevent_socket_new(data->base, data->pair[0], 0);
+               bev2 = bufferevent_socket_new(data->base, data->pair[1], 0);
+       }
+
+       tt_assert(bev1);
+       tt_assert(bev2);
+
+       if (use_filter) {
+               struct bufferevent *bevf1, *bevf2;
+               bevf1 = bufferevent_filter_new(bev1, NULL, NULL,
+                   BEV_OPT_CLOSE_ON_FREE, NULL, NULL);
+               bevf2 = bufferevent_filter_new(bev2, NULL, NULL,
+                   BEV_OPT_CLOSE_ON_FREE, NULL, NULL);
+               tt_assert(bevf1);
+               tt_assert(bevf2);
+               bev1 = bevf1;
+               bev2 = bevf2;
+       }
+
+       /* Do this nice and early. */
+       bufferevent_disable(bev2, EV_READ);
+
+       /* bev1 will try to write and read.  Both will time out. */
+       evutil_gettimeofday(&started_at, NULL);
+       tv_w.tv_sec = tv_r.tv_sec = 0;
+       tv_w.tv_usec = 100*1000;
+       tv_r.tv_usec = 150*1000;
+       bufferevent_setcb(bev1, NULL, bev_timeout_write_cb,
+           bev_timeout_event_cb, &res1);
+       bufferevent_setwatermark(bev1, EV_WRITE, 1024*1024+10, 0);
+       bufferevent_set_timeouts(bev1, &tv_r, &tv_w);
+       if (use_pair) {
+               /* For a pair, the fact that the other side isn't reading
+                * makes the writer stall */
+               bufferevent_write(bev1, "ABCDEFG", 7);
+       } else {
+               /* For a real socket, the kernel's TCP buffers can eat a
+                * fair number of bytes; make sure that at some point we
+                * have some bytes that will stall. */
+               struct evbuffer *output = bufferevent_get_output(bev1);
+               int i;
+               memset(buf, 0xbb, sizeof(buf));
+               for (i=0;i<1024;++i) {
+                       evbuffer_add_reference(output, buf, sizeof(buf),
+                           NULL, NULL);
+               }
+       }
+       bufferevent_enable(bev1, EV_READ|EV_WRITE);
+
+       /* bev2 has nothing to say, and isn't listening. */
+       bufferevent_setcb(bev2, NULL,  bev_timeout_write_cb,
+           bev_timeout_event_cb, &res2);
+       tv_w.tv_sec = tv_r.tv_sec = 0;
+       tv_w.tv_usec = 200*1000;
+       tv_r.tv_usec = 100*1000;
+       bufferevent_set_timeouts(bev2, &tv_r, &tv_w);
+       bufferevent_enable(bev2, EV_WRITE);
+
+       tv_r.tv_sec = 1;
+       tv_r.tv_usec = 0;
+
+       event_base_loopexit(data->base, &tv_r);
+       event_base_dispatch(data->base);
+
+       /* XXXX Test that actually reading or writing a little resets the
+        * timeouts. */
+
+       /* Each buf1 timeout happens, and happens only once. */
+       tt_want(res1.n_read_timeouts);
+       tt_want(res1.n_write_timeouts);
+       tt_want(res1.n_read_timeouts == 1);
+       tt_want(res1.n_write_timeouts == 1);
+
+       test_timeval_diff_eq(&started_at, &res1.read_timeout_at, 150);
+       test_timeval_diff_eq(&started_at, &res1.write_timeout_at, 100);
+
+end:
+       if (bev1)
+               bufferevent_free(bev1);
+       if (bev2)
+               bufferevent_free(bev2);
+}
+
+struct testcase_t bufferevent_testcases[] = {
+
+       LEGACY(bufferevent, TT_ISOLATED),
+       LEGACY(bufferevent_pair, TT_ISOLATED),
+       LEGACY(bufferevent_watermarks, TT_ISOLATED),
+       LEGACY(bufferevent_pair_watermarks, TT_ISOLATED),
+       LEGACY(bufferevent_filters, TT_ISOLATED),
+       LEGACY(bufferevent_pair_filters, TT_ISOLATED),
+       { "bufferevent_connect", test_bufferevent_connect, TT_FORK|TT_NEED_BASE,
+         &basic_setup, (void*)"" },
+       { "bufferevent_connect_defer", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"defer" },
+       { "bufferevent_connect_lock", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE|TT_NEED_THREADS, &basic_setup, (void*)"lock" },
+       { "bufferevent_connect_lock_defer", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE|TT_NEED_THREADS, &basic_setup,
+         (void*)"defer lock" },
+       { "bufferevent_connect_unlocked_cbs", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE|TT_NEED_THREADS, &basic_setup,
+         (void*)"lock defer unlocked" },
+       { "bufferevent_connect_fail", test_bufferevent_connect_fail,
+         TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+       { "bufferevent_timeout", test_bufferevent_timeouts,
+         TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR, &basic_setup, (void*)"" },
+       { "bufferevent_timeout_pair", test_bufferevent_timeouts,
+         TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"pair" },
+       { "bufferevent_timeout_filter", test_bufferevent_timeouts,
+         TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"filter" },
+       { "bufferevent_timeout_filter_pair", test_bufferevent_timeouts,
+         TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"filter pair" },
+#ifdef _EVENT_HAVE_LIBZ
+       LEGACY(bufferevent_zlib, TT_ISOLATED),
+#else
+       { "bufferevent_zlib", NULL, TT_SKIP, NULL, NULL },
+#endif
+
+       END_OF_TESTCASES,
+};
+
+struct testcase_t bufferevent_iocp_testcases[] = {
+
+       LEGACY(bufferevent, TT_ISOLATED|TT_ENABLE_IOCP),
+       LEGACY(bufferevent_watermarks, TT_ISOLATED|TT_ENABLE_IOCP),
+       LEGACY(bufferevent_filters, TT_ISOLATED|TT_ENABLE_IOCP),
+       { "bufferevent_connect", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP, &basic_setup, (void*)"" },
+       { "bufferevent_connect_defer", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP, &basic_setup, (void*)"defer" },
+       { "bufferevent_connect_lock", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE|TT_NEED_THREADS|TT_ENABLE_IOCP, &basic_setup,
+         (void*)"lock" },
+       { "bufferevent_connect_lock_defer", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE|TT_NEED_THREADS|TT_ENABLE_IOCP, &basic_setup,
+         (void*)"defer lock" },
+       { "bufferevent_connect_fail", test_bufferevent_connect_fail,
+         TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP, &basic_setup, NULL },
+       { "bufferevent_connect_nonblocking", test_bufferevent_connect,
+         TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP, &basic_setup,
+         (void*)"unset_connectex" },
+
+       END_OF_TESTCASES,
+};
diff --git a/libevent/test/regress_dns.c b/libevent/test/regress_dns.c
new file mode 100644 (file)
index 0000000..a566469
--- /dev/null
@@ -0,0 +1,1853 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <ws2tcpip.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#include <signal.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#endif
+#ifdef _EVENT_HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/dns.h"
+#include "event2/dns_compat.h"
+#include "event2/dns_struct.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/event_struct.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "event2/bufferevent.h"
+#include "log-internal.h"
+#include "regress.h"
+#include "regress_testutils.h"
+
+#include "../util-internal.h"
+
+static int dns_ok = 0;
+static int dns_got_cancel = 0;
+static int dns_err = 0;
+
+
+static void
+dns_gethostbyname_cb(int result, char type, int count, int ttl,
+    void *addresses, void *arg)
+{
+       dns_ok = dns_err = 0;
+
+       if (result == DNS_ERR_TIMEOUT) {
+               printf("[Timed out] ");
+               dns_err = result;
+               goto out;
+       }
+
+       if (result != DNS_ERR_NONE) {
+               printf("[Error code %d] ", result);
+               goto out;
+       }
+
+       TT_BLATHER(("type: %d, count: %d, ttl: %d: ", type, count, ttl));
+
+       switch (type) {
+       case DNS_IPv6_AAAA: {
+#if defined(_EVENT_HAVE_STRUCT_IN6_ADDR) && defined(_EVENT_HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
+               struct in6_addr *in6_addrs = addresses;
+               char buf[INET6_ADDRSTRLEN+1];
+               int i;
+               /* a resolution that's not valid does not help */
+               if (ttl < 0)
+                       goto out;
+               for (i = 0; i < count; ++i) {
+                       const char *b = inet_ntop(AF_INET6, &in6_addrs[i], buf,sizeof(buf));
+                       if (b)
+                               TT_BLATHER(("%s ", b));
+                       else
+                               TT_BLATHER(("%s ", strerror(errno)));
+               }
+#endif
+               break;
+       }
+       case DNS_IPv4_A: {
+               struct in_addr *in_addrs = addresses;
+               int i;
+               /* a resolution that's not valid does not help */
+               if (ttl < 0)
+                       goto out;
+               for (i = 0; i < count; ++i)
+                       TT_BLATHER(("%s ", inet_ntoa(in_addrs[i])));
+               break;
+       }
+       case DNS_PTR:
+               /* may get at most one PTR */
+               if (count != 1)
+                       goto out;
+
+               TT_BLATHER(("%s ", *(char **)addresses));
+               break;
+       default:
+               goto out;
+       }
+
+       dns_ok = type;
+
+out:
+       if (arg == NULL)
+               event_loopexit(NULL);
+       else
+               event_base_loopexit((struct event_base *)arg, NULL);
+}
+
+static void
+dns_gethostbyname(void)
+{
+       dns_ok = 0;
+       evdns_resolve_ipv4("www.monkey.org", 0, dns_gethostbyname_cb, NULL);
+       event_dispatch();
+
+       tt_int_op(dns_ok, ==, DNS_IPv4_A);
+       test_ok = dns_ok;
+end:
+       ;
+}
+
+static void
+dns_gethostbyname6(void)
+{
+       dns_ok = 0;
+       evdns_resolve_ipv6("www.ietf.org", 0, dns_gethostbyname_cb, NULL);
+       event_dispatch();
+
+       if (!dns_ok && dns_err == DNS_ERR_TIMEOUT) {
+               tt_skip();
+       }
+
+       tt_int_op(dns_ok, ==, DNS_IPv6_AAAA);
+       test_ok = 1;
+end:
+       ;
+}
+
+static void
+dns_gethostbyaddr(void)
+{
+       struct in_addr in;
+       in.s_addr = htonl(0x7f000001ul); /* 127.0.0.1 */
+       dns_ok = 0;
+       evdns_resolve_reverse(&in, 0, dns_gethostbyname_cb, NULL);
+       event_dispatch();
+
+       tt_int_op(dns_ok, ==, DNS_PTR);
+       test_ok = dns_ok;
+end:
+       ;
+}
+
+static void
+dns_resolve_reverse(void *ptr)
+{
+       struct in_addr in;
+       struct event_base *base = event_base_new();
+       struct evdns_base *dns = evdns_base_new(base, 1/* init name servers */);
+       struct evdns_request *req = NULL;
+
+       tt_assert(base);
+       tt_assert(dns);
+       in.s_addr = htonl(0x7f000001ul); /* 127.0.0.1 */
+       dns_ok = 0;
+
+       req = evdns_base_resolve_reverse(
+               dns, &in, 0, dns_gethostbyname_cb, base);
+       tt_assert(req);
+
+       event_base_dispatch(base);
+
+       tt_int_op(dns_ok, ==, DNS_PTR);
+
+end:
+       if (dns)
+               evdns_base_free(dns, 0);
+       if (base)
+               event_base_free(base);
+}
+
+static int n_server_responses = 0;
+
+static void
+dns_server_request_cb(struct evdns_server_request *req, void *data)
+{
+       int i, r;
+       const char TEST_ARPA[] = "11.11.168.192.in-addr.arpa";
+       const char TEST_IN6[] =
+           "f.e.f.e." "0.0.0.0." "0.0.0.0." "1.1.1.1."
+           "a.a.a.a." "0.0.0.0." "0.0.0.0." "0.f.f.f.ip6.arpa";
+
+       for (i = 0; i < req->nquestions; ++i) {
+               const int qtype = req->questions[i]->type;
+               const int qclass = req->questions[i]->dns_question_class;
+               const char *qname = req->questions[i]->name;
+
+               struct in_addr ans;
+               ans.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
+               if (qtype == EVDNS_TYPE_A &&
+                   qclass == EVDNS_CLASS_INET &&
+                   !evutil_ascii_strcasecmp(qname, "zz.example.com")) {
+                       r = evdns_server_request_add_a_reply(req, qname,
+                           1, &ans.s_addr, 12345);
+                       if (r<0)
+                               dns_ok = 0;
+               } else if (qtype == EVDNS_TYPE_AAAA &&
+                   qclass == EVDNS_CLASS_INET &&
+                   !evutil_ascii_strcasecmp(qname, "zz.example.com")) {
+                       char addr6[17] = "abcdefghijklmnop";
+                       r = evdns_server_request_add_aaaa_reply(req,
+                           qname, 1, addr6, 123);
+                       if (r<0)
+                               dns_ok = 0;
+               } else if (qtype == EVDNS_TYPE_PTR &&
+                   qclass == EVDNS_CLASS_INET &&
+                   !evutil_ascii_strcasecmp(qname, TEST_ARPA)) {
+                       r = evdns_server_request_add_ptr_reply(req, NULL,
+                           qname, "ZZ.EXAMPLE.COM", 54321);
+                       if (r<0)
+                               dns_ok = 0;
+               } else if (qtype == EVDNS_TYPE_PTR &&
+                   qclass == EVDNS_CLASS_INET &&
+                   !evutil_ascii_strcasecmp(qname, TEST_IN6)){
+                       r = evdns_server_request_add_ptr_reply(req, NULL,
+                           qname,
+                           "ZZ-INET6.EXAMPLE.COM", 54322);
+                       if (r<0)
+                               dns_ok = 0;
+               } else if (qtype == EVDNS_TYPE_A &&
+                   qclass == EVDNS_CLASS_INET &&
+                   !evutil_ascii_strcasecmp(qname, "drop.example.com")) {
+                       if (evdns_server_request_drop(req)<0)
+                               dns_ok = 0;
+                       return;
+               } else {
+                       printf("Unexpected question %d %d \"%s\" ",
+                           qtype, qclass, qname);
+                       dns_ok = 0;
+               }
+       }
+       r = evdns_server_request_respond(req, 0);
+       if (r<0) {
+               printf("Couldn't send reply. ");
+               dns_ok = 0;
+       }
+}
+
+static void
+dns_server_gethostbyname_cb(int result, char type, int count, int ttl,
+    void *addresses, void *arg)
+{
+       if (result == DNS_ERR_CANCEL) {
+               if (arg != (void*)(char*)90909) {
+                       printf("Unexpected cancelation");
+                       dns_ok = 0;
+               }
+               dns_got_cancel = 1;
+               goto out;
+       }
+       if (result != DNS_ERR_NONE) {
+               printf("Unexpected result %d. ", result);
+               dns_ok = 0;
+               goto out;
+       }
+       if (count != 1) {
+               printf("Unexpected answer count %d. ", count);
+               dns_ok = 0;
+               goto out;
+       }
+       switch (type) {
+       case DNS_IPv4_A: {
+               struct in_addr *in_addrs = addresses;
+               if (in_addrs[0].s_addr != htonl(0xc0a80b0bUL) || ttl != 12345) {
+                       printf("Bad IPv4 response \"%s\" %d. ",
+                                       inet_ntoa(in_addrs[0]), ttl);
+                       dns_ok = 0;
+                       goto out;
+               }
+               break;
+       }
+       case DNS_IPv6_AAAA: {
+#if defined (_EVENT_HAVE_STRUCT_IN6_ADDR) && defined(_EVENT_HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
+               struct in6_addr *in6_addrs = addresses;
+               char buf[INET6_ADDRSTRLEN+1];
+               if (memcmp(&in6_addrs[0].s6_addr, "abcdefghijklmnop", 16)
+                   || ttl != 123) {
+                       const char *b = inet_ntop(AF_INET6, &in6_addrs[0],buf,sizeof(buf));
+                       printf("Bad IPv6 response \"%s\" %d. ", b, ttl);
+                       dns_ok = 0;
+                       goto out;
+               }
+#endif
+               break;
+       }
+       case DNS_PTR: {
+               char **addrs = addresses;
+               if (arg != (void*)6) {
+                       if (strcmp(addrs[0], "ZZ.EXAMPLE.COM") ||
+                           ttl != 54321) {
+                               printf("Bad PTR response \"%s\" %d. ",
+                                   addrs[0], ttl);
+                               dns_ok = 0;
+                               goto out;
+                       }
+               } else {
+                       if (strcmp(addrs[0], "ZZ-INET6.EXAMPLE.COM") ||
+                           ttl != 54322) {
+                               printf("Bad ipv6 PTR response \"%s\" %d. ",
+                                   addrs[0], ttl);
+                               dns_ok = 0;
+                               goto out;
+                       }
+               }
+               break;
+       }
+       default:
+               printf("Bad response type %d. ", type);
+               dns_ok = 0;
+       }
+ out:
+       if (++n_server_responses == 3) {
+               event_loopexit(NULL);
+       }
+}
+
+static void
+dns_server(void)
+{
+       evutil_socket_t sock=-1;
+       struct sockaddr_in my_addr;
+       struct sockaddr_storage ss;
+       ev_socklen_t slen;
+       struct evdns_server_port *port=NULL;
+       struct in_addr resolve_addr;
+       struct in6_addr resolve_addr6;
+       struct evdns_base *base=NULL;
+       struct evdns_request *req=NULL;
+
+       dns_ok = 1;
+
+       base = evdns_base_new(NULL, 0);
+
+       /* Now configure a nameserver port. */
+       sock = socket(AF_INET, SOCK_DGRAM, 0);
+       if (sock<0) {
+               tt_abort_perror("socket");
+       }
+
+       evutil_make_socket_nonblocking(sock);
+
+       memset(&my_addr, 0, sizeof(my_addr));
+       my_addr.sin_family = AF_INET;
+       my_addr.sin_port = 0; /* kernel picks */
+       my_addr.sin_addr.s_addr = htonl(0x7f000001UL);
+       if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) < 0) {
+               tt_abort_perror("bind");
+       }
+       slen = sizeof(ss);
+       if (getsockname(sock, (struct sockaddr*)&ss, &slen) < 0) {
+               tt_abort_perror("getsockname");
+       }
+
+       port = evdns_add_server_port(sock, 0, dns_server_request_cb, NULL);
+
+       /* Add ourself as the only nameserver, and make sure we really are
+        * the only nameserver. */
+       evdns_base_nameserver_sockaddr_add(base, (struct sockaddr*)&ss, slen, 0);
+       tt_int_op(evdns_base_count_nameservers(base), ==, 1);
+
+       /* Send some queries. */
+       evdns_base_resolve_ipv4(base, "zz.example.com", DNS_QUERY_NO_SEARCH,
+                                          dns_server_gethostbyname_cb, NULL);
+       evdns_base_resolve_ipv6(base, "zz.example.com", DNS_QUERY_NO_SEARCH,
+                                          dns_server_gethostbyname_cb, NULL);
+       resolve_addr.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
+       evdns_base_resolve_reverse(base, &resolve_addr, 0,
+           dns_server_gethostbyname_cb, NULL);
+       memcpy(resolve_addr6.s6_addr,
+           "\xff\xf0\x00\x00\x00\x00\xaa\xaa"
+           "\x11\x11\x00\x00\x00\x00\xef\xef", 16);
+       evdns_base_resolve_reverse_ipv6(base, &resolve_addr6, 0,
+           dns_server_gethostbyname_cb, (void*)6);
+
+       req = evdns_base_resolve_ipv4(base,
+           "drop.example.com", DNS_QUERY_NO_SEARCH,
+           dns_server_gethostbyname_cb, (void*)(char*)90909);
+
+       evdns_cancel_request(base, req);
+
+       event_dispatch();
+
+       tt_assert(dns_got_cancel);
+       test_ok = dns_ok;
+
+end:
+       if (port)
+               evdns_close_server_port(port);
+       if (sock >= 0)
+               evutil_closesocket(sock);
+       if (base)
+               evdns_base_free(base, 0);
+}
+
+static int n_replies_left;
+static struct event_base *exit_base;
+
+struct generic_dns_callback_result {
+       int result;
+       char type;
+       int count;
+       int ttl;
+       size_t addrs_len;
+       void *addrs;
+       char addrs_buf[256];
+};
+
+static void
+generic_dns_callback(int result, char type, int count, int ttl, void *addresses,
+    void *arg)
+{
+       size_t len;
+       struct generic_dns_callback_result *res = arg;
+       res->result = result;
+       res->type = type;
+       res->count = count;
+       res->ttl = ttl;
+
+       if (type == DNS_IPv4_A)
+               len = count * 4;
+       else if (type == DNS_IPv6_AAAA)
+               len = count * 16;
+       else if (type == DNS_PTR)
+               len = strlen(addresses)+1;
+       else {
+               res->addrs_len = len = 0;
+               res->addrs = NULL;
+       }
+       if (len) {
+               res->addrs_len = len;
+               if (len > 256)
+                       len = 256;
+               memcpy(res->addrs_buf, addresses, len);
+               res->addrs = res->addrs_buf;
+       }
+
+       if (--n_replies_left == 0)
+               event_base_loopexit(exit_base, NULL);
+}
+
+static struct regress_dns_server_table search_table[] = {
+       { "host.a.example.com", "err", "3", 0 },
+       { "host.b.example.com", "err", "3", 0 },
+       { "host.c.example.com", "A", "11.22.33.44", 0 },
+       { "host2.a.example.com", "err", "3", 0 },
+       { "host2.b.example.com", "A", "200.100.0.100", 0 },
+       { "host2.c.example.com", "err", "3", 0 },
+       { "hostn.a.example.com", "errsoa", "0", 0 },
+       { "hostn.b.example.com", "errsoa", "3", 0 },
+       { "hostn.c.example.com", "err", "0", 0 },
+
+       { "host", "err", "3", 0 },
+       { "host2", "err", "3", 0 },
+       { "*", "err", "3", 0 },
+       { NULL, NULL, NULL, 0 }
+};
+
+static void
+dns_search_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       struct evdns_base *dns = NULL;
+       ev_uint16_t portnum = 0;
+       char buf[64];
+
+       struct generic_dns_callback_result r[8];
+
+       tt_assert(regress_dnsserver(base, &portnum, search_table));
+       evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+       dns = evdns_base_new(base, 0);
+       tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+
+       evdns_base_search_add(dns, "a.example.com");
+       evdns_base_search_add(dns, "b.example.com");
+       evdns_base_search_add(dns, "c.example.com");
+
+       n_replies_left = sizeof(r)/sizeof(r[0]);
+       exit_base = base;
+
+       evdns_base_resolve_ipv4(dns, "host", 0, generic_dns_callback, &r[0]);
+       evdns_base_resolve_ipv4(dns, "host2", 0, generic_dns_callback, &r[1]);
+       evdns_base_resolve_ipv4(dns, "host", DNS_NO_SEARCH, generic_dns_callback, &r[2]);
+       evdns_base_resolve_ipv4(dns, "host2", DNS_NO_SEARCH, generic_dns_callback, &r[3]);
+       evdns_base_resolve_ipv4(dns, "host3", 0, generic_dns_callback, &r[4]);
+       evdns_base_resolve_ipv4(dns, "hostn.a.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[5]);
+       evdns_base_resolve_ipv4(dns, "hostn.b.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[6]);
+       evdns_base_resolve_ipv4(dns, "hostn.c.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[7]);
+
+       event_base_dispatch(base);
+
+       tt_int_op(r[0].type, ==, DNS_IPv4_A);
+       tt_int_op(r[0].count, ==, 1);
+       tt_int_op(((ev_uint32_t*)r[0].addrs)[0], ==, htonl(0x0b16212c));
+       tt_int_op(r[1].type, ==, DNS_IPv4_A);
+       tt_int_op(r[1].count, ==, 1);
+       tt_int_op(((ev_uint32_t*)r[1].addrs)[0], ==, htonl(0xc8640064));
+       tt_int_op(r[2].result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[3].result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[4].result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[5].result, ==, DNS_ERR_NODATA);
+       tt_int_op(r[5].ttl, ==, 42);
+       tt_int_op(r[6].result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[6].ttl, ==, 42);
+       tt_int_op(r[7].result, ==, DNS_ERR_NODATA);
+       tt_int_op(r[7].ttl, ==, 0);
+
+end:
+       if (dns)
+               evdns_base_free(dns, 0);
+
+       regress_clean_dnsserver();
+}
+
+static int request_count = 0;
+static struct evdns_request *current_req = NULL;
+
+static void
+search_cancel_server_cb(struct evdns_server_request *req, void *data)
+{
+       const char *question;
+
+       if (req->nquestions != 1)
+               TT_DIE(("Only handling one question at a time; got %d",
+                       req->nquestions));
+
+       question = req->questions[0]->name;
+
+       TT_BLATHER(("got question, %s", question));
+
+       tt_assert(request_count > 0);
+       tt_assert(!evdns_server_request_respond(req, 3));
+
+       if (!--request_count)
+               evdns_cancel_request(NULL, current_req);
+
+end:
+       ;
+}
+
+static void
+dns_search_cancel_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       struct evdns_base *dns = NULL;
+       struct evdns_server_port *port = NULL;
+       ev_uint16_t portnum = 0;
+       struct generic_dns_callback_result r1;
+       char buf[64];
+
+       port = regress_get_dnsserver(base, &portnum, NULL,
+           search_cancel_server_cb, NULL);
+       tt_assert(port);
+       evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+       dns = evdns_base_new(base, 0);
+       tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+
+       evdns_base_search_add(dns, "a.example.com");
+       evdns_base_search_add(dns, "b.example.com");
+       evdns_base_search_add(dns, "c.example.com");
+       evdns_base_search_add(dns, "d.example.com");
+
+       exit_base = base;
+       request_count = 3;
+       n_replies_left = 1;
+
+       current_req = evdns_base_resolve_ipv4(dns, "host", 0,
+                                       generic_dns_callback, &r1);
+       event_base_dispatch(base);
+
+       tt_int_op(r1.result, ==, DNS_ERR_CANCEL);
+
+end:
+       if (port)
+               evdns_close_server_port(port);
+       if (dns)
+               evdns_base_free(dns, 0);
+}
+
+static void
+fail_server_cb(struct evdns_server_request *req, void *data)
+{
+       const char *question;
+       int *count = data;
+       struct in_addr in;
+
+       /* Drop the first N requests that we get. */
+       if (*count > 0) {
+               --*count;
+               tt_want(! evdns_server_request_drop(req));
+               return;
+       }
+
+       if (req->nquestions != 1)
+               TT_DIE(("Only handling one question at a time; got %d",
+                       req->nquestions));
+
+       question = req->questions[0]->name;
+
+       if (!evutil_ascii_strcasecmp(question, "google.com")) {
+               /* Detect a probe, and get out of the loop. */
+               event_base_loopexit(exit_base, NULL);
+       }
+
+       evutil_inet_pton(AF_INET, "16.32.64.128", &in);
+       evdns_server_request_add_a_reply(req, question, 1, &in.s_addr,
+           100);
+       tt_assert(! evdns_server_request_respond(req, 0))
+       return;
+end:
+       tt_want(! evdns_server_request_drop(req));
+}
+
+static void
+dns_retry_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       struct evdns_server_port *port = NULL;
+       struct evdns_base *dns = NULL;
+       int drop_count = 2;
+       ev_uint16_t portnum = 0;
+       char buf[64];
+
+       struct generic_dns_callback_result r1;
+
+       port = regress_get_dnsserver(base, &portnum, NULL,
+           fail_server_cb, &drop_count);
+       tt_assert(port);
+       evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+       dns = evdns_base_new(base, 0);
+       tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+       tt_assert(! evdns_base_set_option(dns, "timeout", "0.3"));
+       tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "10"));
+       tt_assert(! evdns_base_set_option(dns, "initial-probe-timeout", "0.5"));
+
+       evdns_base_resolve_ipv4(dns, "host.example.com", 0,
+           generic_dns_callback, &r1);
+
+       n_replies_left = 1;
+       exit_base = base;
+
+       event_base_dispatch(base);
+
+       tt_int_op(drop_count, ==, 0);
+
+       tt_int_op(r1.type, ==, DNS_IPv4_A);
+       tt_int_op(r1.count, ==, 1);
+       tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0x10204080));
+
+       /* Now try again, but this time have the server get treated as
+        * failed, so we can send it a test probe. */
+       drop_count = 4;
+       tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "3"));
+       tt_assert(! evdns_base_set_option(dns, "attempts:", "4"));
+       memset(&r1, 0, sizeof(r1));
+
+       evdns_base_resolve_ipv4(dns, "host.example.com", 0,
+           generic_dns_callback, &r1);
+
+       n_replies_left = 2;
+
+       /* This will run until it answers the "google.com" probe request. */
+       event_base_dispatch(base);
+
+       /* We'll treat the server as failed here. */
+       tt_int_op(r1.result, ==, DNS_ERR_TIMEOUT);
+
+       /* It should work this time. */
+       tt_int_op(drop_count, ==, 0);
+       evdns_base_resolve_ipv4(dns, "host.example.com", 0,
+           generic_dns_callback, &r1);
+
+       event_base_dispatch(base);
+       tt_int_op(r1.result, ==, DNS_ERR_NONE);
+       tt_int_op(r1.type, ==, DNS_IPv4_A);
+       tt_int_op(r1.count, ==, 1);
+       tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0x10204080));
+
+end:
+       if (dns)
+               evdns_base_free(dns, 0);
+       if (port)
+               evdns_close_server_port(port);
+}
+
+static struct regress_dns_server_table internal_error_table[] = {
+       /* Error 4 (NOTIMPL) makes us reissue the request to another server
+          if we can.
+
+          XXXX we should reissue under a much wider set of circumstances!
+        */
+       { "foof.example.com", "err", "4", 0 },
+       { NULL, NULL, NULL, 0 }
+};
+
+static struct regress_dns_server_table reissue_table[] = {
+       { "foof.example.com", "A", "240.15.240.15", 0 },
+       { NULL, NULL, NULL, 0 }
+};
+
+static void
+dns_reissue_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       struct evdns_server_port *port1 = NULL, *port2 = NULL;
+       struct evdns_base *dns = NULL;
+       struct generic_dns_callback_result r1;
+       ev_uint16_t portnum1 = 0, portnum2=0;
+       char buf1[64], buf2[64];
+
+       port1 = regress_get_dnsserver(base, &portnum1, NULL,
+           regress_dns_server_cb, internal_error_table);
+       tt_assert(port1);
+       port2 = regress_get_dnsserver(base, &portnum2, NULL,
+           regress_dns_server_cb, reissue_table);
+       tt_assert(port2);
+       evutil_snprintf(buf1, sizeof(buf1), "127.0.0.1:%d", (int)portnum1);
+       evutil_snprintf(buf2, sizeof(buf2), "127.0.0.1:%d", (int)portnum2);
+
+       dns = evdns_base_new(base, 0);
+       tt_assert(!evdns_base_nameserver_ip_add(dns, buf1));
+       tt_assert(! evdns_base_set_option(dns, "timeout:", "0.3"));
+       tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "2"));
+       tt_assert(! evdns_base_set_option(dns, "attempts:", "5"));
+
+       memset(&r1, 0, sizeof(r1));
+       evdns_base_resolve_ipv4(dns, "foof.example.com", 0,
+           generic_dns_callback, &r1);
+
+       /* Add this after, so that we are sure to get a reissue. */
+       tt_assert(!evdns_base_nameserver_ip_add(dns, buf2));
+
+       n_replies_left = 1;
+       exit_base = base;
+
+       event_base_dispatch(base);
+       tt_int_op(r1.result, ==, DNS_ERR_NONE);
+       tt_int_op(r1.type, ==, DNS_IPv4_A);
+       tt_int_op(r1.count, ==, 1);
+       tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0xf00ff00f));
+
+       /* Make sure we dropped at least once. */
+       tt_int_op(internal_error_table[0].seen, >, 0);
+
+end:
+       if (dns)
+               evdns_base_free(dns, 0);
+       if (port1)
+               evdns_close_server_port(port1);
+       if (port2)
+               evdns_close_server_port(port2);
+}
+
+#if 0
+static void
+dumb_bytes_fn(char *p, size_t n)
+{
+       unsigned i;
+       /* This gets us 6 bits of entropy per transaction ID, which means we
+        * will have probably have collisions and need to pick again. */
+       for (i=0;i<n;++i)
+               p[i] = (char)(rand() & 7);
+}
+#endif
+
+static void
+dns_inflight_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       struct evdns_base *dns = NULL;
+       ev_uint16_t portnum = 0;
+       char buf[64];
+
+       struct generic_dns_callback_result r[20];
+       int i;
+
+       tt_assert(regress_dnsserver(base, &portnum, reissue_table));
+       evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+       dns = evdns_base_new(base, 0);
+       tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+       tt_assert(! evdns_base_set_option(dns, "max-inflight:", "3"));
+       tt_assert(! evdns_base_set_option(dns, "randomize-case:", "0"));
+
+       for (i=0;i<20;++i)
+               evdns_base_resolve_ipv4(dns, "foof.example.com", 0, generic_dns_callback, &r[i]);
+
+       n_replies_left = 20;
+       exit_base = base;
+
+       event_base_dispatch(base);
+
+       for (i=0;i<20;++i) {
+               tt_int_op(r[i].type, ==, DNS_IPv4_A);
+               tt_int_op(r[i].count, ==, 1);
+               tt_int_op(((ev_uint32_t*)r[i].addrs)[0], ==, htonl(0xf00ff00f));
+       }
+
+end:
+       if (dns)
+               evdns_base_free(dns, 0);
+       regress_clean_dnsserver();
+}
+
+/* === Test for bufferevent_socket_connect_hostname */
+
+static int total_connected_or_failed = 0;
+static int total_n_accepted = 0;
+static struct event_base *be_connect_hostname_base = NULL;
+
+/* Implements a DNS server for the connect_hostname test and the
+ * getaddrinfo_async test */
+static void
+be_getaddrinfo_server_cb(struct evdns_server_request *req, void *data)
+{
+       int i;
+       int *n_got_p=data;
+       int added_any=0;
+       ++*n_got_p;
+
+       for (i=0;i<req->nquestions;++i) {
+               const int qtype = req->questions[i]->type;
+               const int qclass = req->questions[i]->dns_question_class;
+               const char *qname = req->questions[i]->name;
+               struct in_addr ans;
+               struct in6_addr ans6;
+               memset(&ans6, 0, sizeof(ans6));
+
+               if (qtype == EVDNS_TYPE_A &&
+                   qclass == EVDNS_CLASS_INET &&
+                   !evutil_ascii_strcasecmp(qname, "nobodaddy.example.com")) {
+                       ans.s_addr = htonl(0x7f000001);
+                       evdns_server_request_add_a_reply(req, qname,
+                           1, &ans.s_addr, 2000);
+                       added_any = 1;
+               } else if (!evutil_ascii_strcasecmp(qname,
+                       "nosuchplace.example.com")) {
+                       /* ok, just say notfound. */
+               } else if (!evutil_ascii_strcasecmp(qname,
+                       "both.example.com")) {
+                       if (qtype == EVDNS_TYPE_A) {
+                               ans.s_addr = htonl(0x50502020);
+                               evdns_server_request_add_a_reply(req, qname,
+                                   1, &ans.s_addr, 2000);
+                               added_any = 1;
+                       } else if (qtype == EVDNS_TYPE_AAAA) {
+                               ans6.s6_addr[0] = 0x80;
+                               ans6.s6_addr[1] = 0xff;
+                               ans6.s6_addr[14] = 0xbb;
+                               ans6.s6_addr[15] = 0xbb;
+                               evdns_server_request_add_aaaa_reply(req, qname,
+                                   1, &ans6.s6_addr, 2000);
+                               added_any = 1;
+                       }
+                       evdns_server_request_add_cname_reply(req, qname,
+                           "both-canonical.example.com", 1000);
+               } else if (!evutil_ascii_strcasecmp(qname,
+                       "v4only.example.com") ||
+                   !evutil_ascii_strcasecmp(qname, "v4assert.example.com")) {
+                       if (qtype == EVDNS_TYPE_A) {
+                               ans.s_addr = htonl(0x12345678);
+                               evdns_server_request_add_a_reply(req, qname,
+                                   1, &ans.s_addr, 2000);
+                               added_any = 1;
+                       } else if (!evutil_ascii_strcasecmp(qname,
+                               "v4assert.example.com")) {
+                               TT_FAIL(("Got an AAAA request for v4assert"));
+                       }
+               } else if (!evutil_ascii_strcasecmp(qname,
+                       "v6only.example.com") ||
+                   !evutil_ascii_strcasecmp(qname, "v6assert.example.com")) {
+                       if (qtype == EVDNS_TYPE_AAAA) {
+                               ans6.s6_addr[0] = 0x0b;
+                               ans6.s6_addr[1] = 0x0b;
+                               ans6.s6_addr[14] = 0xf0;
+                               ans6.s6_addr[15] = 0x0d;
+                               evdns_server_request_add_aaaa_reply(req, qname,
+                                   1, &ans6.s6_addr, 2000);
+                               added_any = 1;
+                       }  else if (!evutil_ascii_strcasecmp(qname,
+                               "v6assert.example.com")) {
+                               TT_FAIL(("Got a A request for v6assert"));
+                       }
+               } else if (!evutil_ascii_strcasecmp(qname,
+                       "v6timeout.example.com")) {
+                       if (qtype == EVDNS_TYPE_A) {
+                               ans.s_addr = htonl(0xabcdef01);
+                               evdns_server_request_add_a_reply(req, qname,
+                                   1, &ans.s_addr, 2000);
+                               added_any = 1;
+                       } else if (qtype == EVDNS_TYPE_AAAA) {
+                               /* Let the v6 request time out.*/
+                               evdns_server_request_drop(req);
+                               return;
+                       }
+               } else if (!evutil_ascii_strcasecmp(qname,
+                       "v4timeout.example.com")) {
+                       if (qtype == EVDNS_TYPE_AAAA) {
+                               ans6.s6_addr[0] = 0x0a;
+                               ans6.s6_addr[1] = 0x0a;
+                               ans6.s6_addr[14] = 0xff;
+                               ans6.s6_addr[15] = 0x01;
+                               evdns_server_request_add_aaaa_reply(req, qname,
+                                   1, &ans6.s6_addr, 2000);
+                               added_any = 1;
+                       } else if (qtype == EVDNS_TYPE_A) {
+                               /* Let the v4 request time out.*/
+                               evdns_server_request_drop(req);
+                               return;
+                       }
+               } else if (!evutil_ascii_strcasecmp(qname,
+                       "v6timeout-nonexist.example.com")) {
+                       if (qtype == EVDNS_TYPE_A) {
+                               /* Fall through, give an nexist. */
+                       } else if (qtype == EVDNS_TYPE_AAAA) {
+                               /* Let the v6 request time out.*/
+                               evdns_server_request_drop(req);
+                               return;
+                       }
+               } else if (!evutil_ascii_strcasecmp(qname,
+                       "all-timeout.example.com")) {
+                       /* drop all requests */
+                       evdns_server_request_drop(req);
+                       return;
+               } else {
+                       TT_GRIPE(("Got weird request for %s",qname));
+               }
+       }
+       if (added_any)
+               evdns_server_request_respond(req, 0);
+       else
+               evdns_server_request_respond(req, 3);
+}
+
+/* Implements a listener for connect_hostname test. */
+static void
+nil_accept_cb(struct evconnlistener *l, evutil_socket_t fd, struct sockaddr *s,
+    int socklen, void *arg)
+{
+       int *p = arg;
+       (*p)++;
+       ++total_n_accepted;
+       /* don't do anything with the socket; let it close when we exit() */
+       if (total_n_accepted >= 3 && total_connected_or_failed >= 5)
+               event_base_loopexit(be_connect_hostname_base,
+                   NULL);
+}
+
+struct be_conn_hostname_result {
+       int dnserr;
+       int what;
+};
+
+/* Bufferevent event callback for the connect_hostname test: remembers what
+ * event we got. */
+static void
+be_connect_hostname_event_cb(struct bufferevent *bev, short what, void *ctx)
+{
+       struct be_conn_hostname_result *got = ctx;
+       if (!got->what) {
+               TT_BLATHER(("Got a bufferevent event %d", what));
+               got->what = what;
+
+               if ((what & BEV_EVENT_CONNECTED) || (what & BEV_EVENT_ERROR)) {
+                       int r;
+                       if ((r = bufferevent_socket_get_dns_error(bev))) {
+                               got->dnserr = r;
+                               TT_BLATHER(("DNS error %d: %s", r,
+                                          evutil_gai_strerror(r)));
+                       }                       ++total_connected_or_failed;
+                       TT_BLATHER(("Got %d connections or errors.", total_connected_or_failed));
+
+                       if (total_n_accepted >= 3 && total_connected_or_failed >= 5)
+                               event_base_loopexit(be_connect_hostname_base,
+                                   NULL);
+               }
+       } else {
+               TT_FAIL(("Two events on one bufferevent. %d,%d",
+                       got->what, (int)what));
+       }
+}
+
+static void
+test_bufferevent_connect_hostname(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct evconnlistener *listener = NULL;
+       struct bufferevent *be1=NULL, *be2=NULL, *be3=NULL, *be4=NULL, *be5=NULL;
+       struct be_conn_hostname_result be1_outcome={0,0}, be2_outcome={0,0},
+              be3_outcome={0,0}, be4_outcome={0,0}, be5_outcome={0,0};
+       int expect_err5;
+       struct evdns_base *dns=NULL;
+       struct evdns_server_port *port=NULL;
+       evutil_socket_t server_fd=-1;
+       struct sockaddr_in sin;
+       int listener_port=-1;
+       ev_uint16_t dns_port=0;
+       int n_accept=0, n_dns=0;
+       char buf[128];
+
+       be_connect_hostname_base = data->base;
+
+       /* Bind an address and figure out what port it's on. */
+       memset(&sin, 0, sizeof(sin));
+       sin.sin_family = AF_INET;
+       sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+       sin.sin_port = 0;
+       listener = evconnlistener_new_bind(data->base, nil_accept_cb,
+           &n_accept,
+           LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC,
+           -1, (struct sockaddr *)&sin, sizeof(sin));
+       listener_port = regress_get_socket_port(
+               evconnlistener_get_fd(listener));
+
+       port = regress_get_dnsserver(data->base, &dns_port, NULL,
+           be_getaddrinfo_server_cb, &n_dns);
+       tt_assert(port);
+       tt_int_op(dns_port, >=, 0);
+
+       /* Start an evdns_base that uses the server as its resolver. */
+       dns = evdns_base_new(data->base, 0);
+       evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)dns_port);
+       evdns_base_nameserver_ip_add(dns, buf);
+
+       /* Now, finally, at long last, launch the bufferevents.  One should do
+        * a failing lookup IP, one should do a successful lookup by IP,
+        * and one should do a successful lookup by hostname. */
+       be1 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
+       be2 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
+       be3 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
+       be4 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
+       be5 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
+
+       bufferevent_setcb(be1, NULL, NULL, be_connect_hostname_event_cb,
+           &be1_outcome);
+       bufferevent_setcb(be2, NULL, NULL, be_connect_hostname_event_cb,
+           &be2_outcome);
+       bufferevent_setcb(be3, NULL, NULL, be_connect_hostname_event_cb,
+           &be3_outcome);
+       bufferevent_setcb(be4, NULL, NULL, be_connect_hostname_event_cb,
+           &be4_outcome);
+       bufferevent_setcb(be5, NULL, NULL, be_connect_hostname_event_cb,
+           &be5_outcome);
+
+       /* Launch an async resolve that will fail. */
+       tt_assert(!bufferevent_socket_connect_hostname(be1, dns, AF_INET,
+               "nosuchplace.example.com", listener_port));
+       /* Connect to the IP without resolving. */
+       tt_assert(!bufferevent_socket_connect_hostname(be2, dns, AF_INET,
+               "127.0.0.1", listener_port));
+       /* Launch an async resolve that will succeed. */
+       tt_assert(!bufferevent_socket_connect_hostname(be3, dns, AF_INET,
+               "nobodaddy.example.com", listener_port));
+       /* Use the blocking resolver.  This one will fail if your resolver
+        * can't resolve localhost to 127.0.0.1 */
+       tt_assert(!bufferevent_socket_connect_hostname(be4, NULL, AF_INET,
+               "localhost", listener_port));
+       /* Use the blocking resolver with a nonexistent hostname. */
+       tt_assert(!bufferevent_socket_connect_hostname(be5, NULL, AF_INET,
+               "nonesuch.nowhere.example.com", 80));
+       {
+               /* The blocking resolver will use the system nameserver, which
+                * might tell us anything.  (Yes, some twits even pretend that
+                * example.com is real.) Let's see what answer to expect. */
+               struct evutil_addrinfo hints, *ai = NULL;
+               memset(&hints, 0, sizeof(hints));
+               hints.ai_family = AF_INET;
+               hints.ai_socktype = SOCK_STREAM;
+               hints.ai_protocol = IPPROTO_TCP;
+               expect_err5 = evutil_getaddrinfo(
+                       "nonesuch.nowhere.example.com", "80", &hints, &ai);
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(be1_outcome.what, ==, BEV_EVENT_ERROR);
+       tt_int_op(be1_outcome.dnserr, ==, EVUTIL_EAI_NONAME);
+       tt_int_op(be2_outcome.what, ==, BEV_EVENT_CONNECTED);
+       tt_int_op(be2_outcome.dnserr, ==, 0);
+       tt_int_op(be3_outcome.what, ==, BEV_EVENT_CONNECTED);
+       tt_int_op(be3_outcome.dnserr, ==, 0);
+       tt_int_op(be4_outcome.what, ==, BEV_EVENT_CONNECTED);
+       tt_int_op(be4_outcome.dnserr, ==, 0);
+       if (expect_err5) {
+               tt_int_op(be5_outcome.what, ==, BEV_EVENT_ERROR);
+               tt_int_op(be5_outcome.dnserr, ==, expect_err5);
+       }
+
+       tt_int_op(n_accept, ==, 3);
+       tt_int_op(n_dns, ==, 2);
+
+end:
+       if (listener)
+               evconnlistener_free(listener);
+       if (server_fd>=0)
+               evutil_closesocket(server_fd);
+       if (port)
+               evdns_close_server_port(port);
+       if (dns)
+               evdns_base_free(dns, 0);
+       if (be1)
+               bufferevent_free(be1);
+       if (be2)
+               bufferevent_free(be2);
+       if (be3)
+               bufferevent_free(be3);
+       if (be4)
+               bufferevent_free(be4);
+       if (be5)
+               bufferevent_free(be5);
+}
+
+
+struct gai_outcome {
+       int err;
+       struct evutil_addrinfo *ai;
+};
+
+static int n_gai_results_pending = 0;
+static struct event_base *exit_base_on_no_pending_results = NULL;
+
+static void
+gai_cb(int err, struct evutil_addrinfo *res, void *ptr)
+{
+       struct gai_outcome *go = ptr;
+       go->err = err;
+       go->ai = res;
+       if (--n_gai_results_pending <= 0 && exit_base_on_no_pending_results)
+               event_base_loopexit(exit_base_on_no_pending_results, NULL);
+       if (n_gai_results_pending < 900)
+               TT_BLATHER(("Got an answer; expecting %d more.",
+                       n_gai_results_pending));
+}
+
+static void
+cancel_gai_cb(evutil_socket_t fd, short what, void *ptr)
+{
+       struct evdns_getaddrinfo_request *r = ptr;
+       evdns_getaddrinfo_cancel(r);
+}
+
+static void
+test_getaddrinfo_async(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct evutil_addrinfo hints, *a;
+       struct gai_outcome local_outcome;
+       struct gai_outcome a_out[12];
+       int i;
+       struct evdns_getaddrinfo_request *r;
+       char buf[128];
+       struct evdns_server_port *port = NULL;
+       ev_uint16_t dns_port = 0;
+       int n_dns_questions = 0;
+
+       struct evdns_base *dns_base = evdns_base_new(data->base, 0);
+
+       /* for localhost */
+       evdns_base_load_hosts(dns_base, NULL);
+
+       memset(a_out, 0, sizeof(a_out));
+
+       n_gai_results_pending = 10000; /* don't think about exiting yet. */
+
+       /* 1. Try some cases that will never hit the asynchronous resolver. */
+       /* 1a. Simple case with a symbolic service name */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_STREAM;
+       memset(&local_outcome, 0, sizeof(local_outcome));
+       r = evdns_getaddrinfo(dns_base, "1.2.3.4", "http",
+           &hints, gai_cb, &local_outcome);
+       tt_assert(! r);
+       if (!local_outcome.err) {
+               tt_ptr_op(local_outcome.ai,!=,NULL);
+               test_ai_eq(local_outcome.ai, "1.2.3.4:80", SOCK_STREAM, IPPROTO_TCP);
+               evutil_freeaddrinfo(local_outcome.ai);
+               local_outcome.ai = NULL;
+       } else {
+               TT_BLATHER(("Apparently we have no getservbyname."));
+       }
+
+       /* 1b. EVUTIL_AI_NUMERICHOST is set */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_flags = EVUTIL_AI_NUMERICHOST;
+       memset(&local_outcome, 0, sizeof(local_outcome));
+       r = evdns_getaddrinfo(dns_base, "www.google.com", "80",
+           &hints, gai_cb, &local_outcome);
+       tt_int_op(r,==,0);
+       tt_int_op(local_outcome.err,==,EVUTIL_EAI_NONAME);
+       tt_ptr_op(local_outcome.ai,==,NULL);
+
+       /* 1c. We give a numeric address (ipv6) */
+       memset(&hints, 0, sizeof(hints));
+       memset(&local_outcome, 0, sizeof(local_outcome));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_protocol = IPPROTO_TCP;
+       r = evdns_getaddrinfo(dns_base, "f::f", "8008",
+           &hints, gai_cb, &local_outcome);
+       tt_assert(!r);
+       tt_int_op(local_outcome.err,==,0);
+       tt_assert(local_outcome.ai);
+       tt_ptr_op(local_outcome.ai->ai_next,==,NULL);
+       test_ai_eq(local_outcome.ai, "[f::f]:8008", SOCK_STREAM, IPPROTO_TCP);
+       evutil_freeaddrinfo(local_outcome.ai);
+       local_outcome.ai = NULL;
+
+       /* 1d. We give a numeric address (ipv4) */
+       memset(&hints, 0, sizeof(hints));
+       memset(&local_outcome, 0, sizeof(local_outcome));
+       hints.ai_family = PF_UNSPEC;
+       r = evdns_getaddrinfo(dns_base, "5.6.7.8", NULL,
+           &hints, gai_cb, &local_outcome);
+       tt_assert(!r);
+       tt_int_op(local_outcome.err,==,0);
+       tt_assert(local_outcome.ai);
+       a = ai_find_by_protocol(local_outcome.ai, IPPROTO_TCP);
+       tt_assert(a);
+       test_ai_eq(a, "5.6.7.8", SOCK_STREAM, IPPROTO_TCP);
+       a = ai_find_by_protocol(local_outcome.ai, IPPROTO_UDP);
+       tt_assert(a);
+       test_ai_eq(a, "5.6.7.8", SOCK_DGRAM, IPPROTO_UDP);
+       evutil_freeaddrinfo(local_outcome.ai);
+       local_outcome.ai = NULL;
+
+       /* 1e. nodename is NULL (bind) */
+       memset(&hints, 0, sizeof(hints));
+       memset(&local_outcome, 0, sizeof(local_outcome));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_DGRAM;
+       hints.ai_flags = EVUTIL_AI_PASSIVE;
+       r = evdns_getaddrinfo(dns_base, NULL, "9090",
+           &hints, gai_cb, &local_outcome);
+       tt_assert(!r);
+       tt_int_op(local_outcome.err,==,0);
+       tt_assert(local_outcome.ai);
+       /* we should get a v4 address of 0.0.0.0... */
+       a = ai_find_by_family(local_outcome.ai, PF_INET);
+       tt_assert(a);
+       test_ai_eq(a, "0.0.0.0:9090", SOCK_DGRAM, IPPROTO_UDP);
+       /* ... and a v6 address of ::0 */
+       a = ai_find_by_family(local_outcome.ai, PF_INET6);
+       tt_assert(a);
+       test_ai_eq(a, "[::]:9090", SOCK_DGRAM, IPPROTO_UDP);
+       evutil_freeaddrinfo(local_outcome.ai);
+       local_outcome.ai = NULL;
+
+       /* 1f. nodename is NULL (connect) */
+       memset(&hints, 0, sizeof(hints));
+       memset(&local_outcome, 0, sizeof(local_outcome));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_STREAM;
+       r = evdns_getaddrinfo(dns_base, NULL, "2",
+           &hints, gai_cb, &local_outcome);
+       tt_assert(!r);
+       tt_int_op(local_outcome.err,==,0);
+       tt_assert(local_outcome.ai);
+       /* we should get a v4 address of 127.0.0.1 .... */
+       a = ai_find_by_family(local_outcome.ai, PF_INET);
+       tt_assert(a);
+       test_ai_eq(a, "127.0.0.1:2", SOCK_STREAM, IPPROTO_TCP);
+       /* ... and a v6 address of ::1 */
+       a = ai_find_by_family(local_outcome.ai, PF_INET6);
+       tt_assert(a);
+       test_ai_eq(a, "[::1]:2", SOCK_STREAM, IPPROTO_TCP);
+       evutil_freeaddrinfo(local_outcome.ai);
+       local_outcome.ai = NULL;
+
+       /* 1g. We find localhost immediately. (pf_unspec) */
+       memset(&hints, 0, sizeof(hints));
+       memset(&local_outcome, 0, sizeof(local_outcome));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_STREAM;
+       r = evdns_getaddrinfo(dns_base, "LOCALHOST", "80",
+           &hints, gai_cb, &local_outcome);
+       tt_assert(!r);
+       tt_int_op(local_outcome.err,==,0);
+       tt_assert(local_outcome.ai);
+       /* we should get a v4 address of 127.0.0.1 .... */
+       a = ai_find_by_family(local_outcome.ai, PF_INET);
+       tt_assert(a);
+       test_ai_eq(a, "127.0.0.1:80", SOCK_STREAM, IPPROTO_TCP);
+       /* ... and a v6 address of ::1 */
+       a = ai_find_by_family(local_outcome.ai, PF_INET6);
+       tt_assert(a);
+       test_ai_eq(a, "[::1]:80", SOCK_STREAM, IPPROTO_TCP);
+       evutil_freeaddrinfo(local_outcome.ai);
+       local_outcome.ai = NULL;
+
+       /* 1g. We find localhost immediately. (pf_inet6) */
+       memset(&hints, 0, sizeof(hints));
+       memset(&local_outcome, 0, sizeof(local_outcome));
+       hints.ai_family = PF_INET6;
+       hints.ai_socktype = SOCK_STREAM;
+       r = evdns_getaddrinfo(dns_base, "LOCALHOST", "9999",
+           &hints, gai_cb, &local_outcome);
+       tt_assert(! r);
+       tt_int_op(local_outcome.err,==,0);
+       tt_assert(local_outcome.ai);
+       a = local_outcome.ai;
+       test_ai_eq(a, "[::1]:9999", SOCK_STREAM, IPPROTO_TCP);
+       tt_ptr_op(a->ai_next, ==, NULL);
+       evutil_freeaddrinfo(local_outcome.ai);
+       local_outcome.ai = NULL;
+
+       /* 2. Okay, now we can actually test the asynchronous resolver. */
+       /* Start a dummy local dns server... */
+       port = regress_get_dnsserver(data->base, &dns_port, NULL,
+           be_getaddrinfo_server_cb, &n_dns_questions);
+       tt_assert(port);
+       tt_int_op(dns_port, >=, 0);
+       /* ... and tell the evdns_base about it. */
+       evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", dns_port);
+       evdns_base_nameserver_ip_add(dns_base, buf);
+
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_STREAM;
+       hints.ai_flags = EVUTIL_AI_CANONNAME;
+       /* 0: Request for both.example.com should return both addresses. */
+       r = evdns_getaddrinfo(dns_base, "both.example.com", "8000",
+           &hints, gai_cb, &a_out[0]);
+       tt_assert(r);
+
+       /* 1: Request for v4only.example.com should return one address. */
+       r = evdns_getaddrinfo(dns_base, "v4only.example.com", "8001",
+           &hints, gai_cb, &a_out[1]);
+       tt_assert(r);
+
+       /* 2: Request for v6only.example.com should return one address. */
+       hints.ai_flags = 0;
+       r = evdns_getaddrinfo(dns_base, "v6only.example.com", "8002",
+           &hints, gai_cb, &a_out[2]);
+       tt_assert(r);
+
+       /* 3: PF_INET request for v4assert.example.com should not generate a
+        * v6 request.  The server will fail the test if it does. */
+       hints.ai_family = PF_INET;
+       r = evdns_getaddrinfo(dns_base, "v4assert.example.com", "8003",
+           &hints, gai_cb, &a_out[3]);
+       tt_assert(r);
+
+       /* 4: PF_INET6 request for v6assert.example.com should not generate a
+        * v4 request.  The server will fail the test if it does. */
+       hints.ai_family = PF_INET6;
+       r = evdns_getaddrinfo(dns_base, "v6assert.example.com", "8004",
+           &hints, gai_cb, &a_out[4]);
+       tt_assert(r);
+
+       /* 5: PF_INET request for nosuchplace.example.com should give NEXIST. */
+       hints.ai_family = PF_INET;
+       r = evdns_getaddrinfo(dns_base, "nosuchplace.example.com", "8005",
+           &hints, gai_cb, &a_out[5]);
+       tt_assert(r);
+
+       /* 6: PF_UNSPEC request for nosuchplace.example.com should give NEXIST.
+        */
+       hints.ai_family = PF_UNSPEC;
+       r = evdns_getaddrinfo(dns_base, "nosuchplace.example.com", "8006",
+           &hints, gai_cb, &a_out[6]);
+       tt_assert(r);
+
+       /* 7: PF_UNSPEC request for v6timeout.example.com should give an ipv4
+        * address only. */
+       hints.ai_family = PF_UNSPEC;
+       r = evdns_getaddrinfo(dns_base, "v6timeout.example.com", "8007",
+           &hints, gai_cb, &a_out[7]);
+       tt_assert(r);
+
+       /* 8: PF_UNSPEC request for v6timeout-nonexist.example.com should give
+        * a NEXIST */
+       hints.ai_family = PF_UNSPEC;
+       r = evdns_getaddrinfo(dns_base, "v6timeout-nonexist.example.com",
+           "8008", &hints, gai_cb, &a_out[8]);
+       tt_assert(r);
+
+       /* 9: AI_ADDRCONFIG should at least not crash.  Can't test it more
+        * without knowing what kind of internet we have. */
+       hints.ai_flags |= EVUTIL_AI_ADDRCONFIG;
+       r = evdns_getaddrinfo(dns_base, "both.example.com",
+           "8009", &hints, gai_cb, &a_out[9]);
+       tt_assert(r);
+
+       /* 10: PF_UNSPEC for v4timeout.example.com should give an ipv6 address
+        * only. */
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_flags = 0;
+       r = evdns_getaddrinfo(dns_base, "v4timeout.example.com", "8010",
+           &hints, gai_cb, &a_out[10]);
+       tt_assert(r);
+
+       /* 11: timeout.example.com: cancel it after 100 msec. */
+       r = evdns_getaddrinfo(dns_base, "all-timeout.example.com", "8011",
+           &hints, gai_cb, &a_out[11]);
+       tt_assert(r);
+       {
+               struct timeval tv;
+               tv.tv_sec = 0;
+               tv.tv_usec = 100*1000; /* 100 msec */
+               event_base_once(data->base, -1, EV_TIMEOUT, cancel_gai_cb,
+                   r, &tv);
+       }
+
+       /* XXXXX There are more tests we could do, including:
+
+          - A test to elicit NODATA.
+
+        */
+
+       n_gai_results_pending = 12;
+       exit_base_on_no_pending_results = data->base;
+
+       event_base_dispatch(data->base);
+
+       /* 0: both.example.com */
+       tt_int_op(a_out[0].err, ==, 0);
+       tt_assert(a_out[0].ai);
+       tt_assert(a_out[0].ai->ai_next);
+       tt_assert(!a_out[0].ai->ai_next->ai_next);
+       a = ai_find_by_family(a_out[0].ai, PF_INET);
+       tt_assert(a);
+       test_ai_eq(a, "80.80.32.32:8000", SOCK_STREAM, IPPROTO_TCP);
+       a = ai_find_by_family(a_out[0].ai, PF_INET6);
+       tt_assert(a);
+       test_ai_eq(a, "[80ff::bbbb]:8000", SOCK_STREAM, IPPROTO_TCP);
+       tt_assert(a_out[0].ai->ai_canonname);
+       tt_str_op(a_out[0].ai->ai_canonname, ==, "both-canonical.example.com");
+
+       /* 1: v4only.example.com */
+       tt_int_op(a_out[1].err, ==, 0);
+       tt_assert(a_out[1].ai);
+       tt_assert(! a_out[1].ai->ai_next);
+       test_ai_eq(a_out[1].ai, "18.52.86.120:8001", SOCK_STREAM, IPPROTO_TCP);
+       tt_assert(a_out[1].ai->ai_canonname == NULL);
+
+
+       /* 2: v6only.example.com */
+       tt_int_op(a_out[2].err, ==, 0);
+       tt_assert(a_out[2].ai);
+       tt_assert(! a_out[2].ai->ai_next);
+       test_ai_eq(a_out[2].ai, "[b0b::f00d]:8002", SOCK_STREAM, IPPROTO_TCP);
+
+       /* 3: v4assert.example.com */
+       tt_int_op(a_out[3].err, ==, 0);
+       tt_assert(a_out[3].ai);
+       tt_assert(! a_out[3].ai->ai_next);
+       test_ai_eq(a_out[3].ai, "18.52.86.120:8003", SOCK_STREAM, IPPROTO_TCP);
+
+       /* 4: v6assert.example.com */
+       tt_int_op(a_out[4].err, ==, 0);
+       tt_assert(a_out[4].ai);
+       tt_assert(! a_out[4].ai->ai_next);
+       test_ai_eq(a_out[4].ai, "[b0b::f00d]:8004", SOCK_STREAM, IPPROTO_TCP);
+
+       /* 5: nosuchplace.example.com (inet) */
+       tt_int_op(a_out[5].err, ==, EVUTIL_EAI_NONAME);
+       tt_assert(! a_out[5].ai);
+
+       /* 6: nosuchplace.example.com (unspec) */
+       tt_int_op(a_out[6].err, ==, EVUTIL_EAI_NONAME);
+       tt_assert(! a_out[6].ai);
+
+       /* 7: v6timeout.example.com */
+       tt_int_op(a_out[7].err, ==, 0);
+       tt_assert(a_out[7].ai);
+       tt_assert(! a_out[7].ai->ai_next);
+       test_ai_eq(a_out[7].ai, "171.205.239.1:8007", SOCK_STREAM, IPPROTO_TCP);
+
+       /* 8: v6timeout-nonexist.example.com */
+       tt_int_op(a_out[8].err, ==, EVUTIL_EAI_NONAME);
+       tt_assert(! a_out[8].ai);
+
+       /* 9: both (ADDRCONFIG) */
+       tt_int_op(a_out[9].err, ==, 0);
+       tt_assert(a_out[9].ai);
+       a = ai_find_by_family(a_out[9].ai, PF_INET);
+       if (a)
+               test_ai_eq(a, "80.80.32.32:8009", SOCK_STREAM, IPPROTO_TCP);
+       else
+               tt_assert(ai_find_by_family(a_out[9].ai, PF_INET6));
+       a = ai_find_by_family(a_out[9].ai, PF_INET6);
+       if (a)
+               test_ai_eq(a, "[80ff::bbbb]:8009", SOCK_STREAM, IPPROTO_TCP);
+       else
+               tt_assert(ai_find_by_family(a_out[9].ai, PF_INET));
+
+       /* 10: v4timeout.example.com */
+       tt_int_op(a_out[10].err, ==, 0);
+       tt_assert(a_out[10].ai);
+       tt_assert(! a_out[10].ai->ai_next);
+       test_ai_eq(a_out[10].ai, "[a0a::ff01]:8010", SOCK_STREAM, IPPROTO_TCP);
+
+       /* 11: cancelled request. */
+       tt_int_op(a_out[11].err, ==, EVUTIL_EAI_CANCEL);
+       tt_assert(a_out[11].ai == NULL);
+
+end:
+       if (local_outcome.ai)
+               evutil_freeaddrinfo(local_outcome.ai);
+       for (i=0;i<10;++i) {
+               if (a_out[i].ai)
+                       evutil_freeaddrinfo(a_out[i].ai);
+       }
+       if (port)
+               evdns_close_server_port(port);
+       if (dns_base)
+               evdns_base_free(dns_base, 0);
+}
+
+struct gaic_request_status {
+       int magic;
+       struct event_base *base;
+       struct evdns_base *dns_base;
+       struct evdns_getaddrinfo_request *request;
+       struct event cancel_event;
+       int canceled;
+};
+
+#define GAIC_MAGIC 0x1234abcd
+
+static int pending = 0;
+
+static void
+gaic_cancel_request_cb(evutil_socket_t fd, short what, void *arg)
+{
+       struct gaic_request_status *status = arg;
+
+       tt_assert(status->magic == GAIC_MAGIC);
+       status->canceled = 1;
+       evdns_getaddrinfo_cancel(status->request);
+       return;
+end:
+       event_base_loopexit(status->base, NULL);
+}
+
+static void
+gaic_server_cb(struct evdns_server_request *req, void *arg)
+{
+       ev_uint32_t answer = 0x7f000001;
+       tt_assert(req->nquestions);
+       evdns_server_request_add_a_reply(req, req->questions[0]->name, 1,
+           &answer, 100);
+       evdns_server_request_respond(req, 0);
+       return;
+end:
+       evdns_server_request_respond(req, DNS_ERR_REFUSED);
+}
+
+
+static void
+gaic_getaddrinfo_cb(int result, struct evutil_addrinfo *res, void *arg)
+{
+       struct gaic_request_status *status = arg;
+       struct event_base *base = status->base;
+       tt_assert(status->magic == GAIC_MAGIC);
+
+       if (result == EVUTIL_EAI_CANCEL) {
+               tt_assert(status->canceled);
+       }
+       event_del(&status->cancel_event);
+
+       memset(status, 0xf0, sizeof(*status));
+       free(status);
+
+end:
+       if (--pending <= 0)
+               event_base_loopexit(base, NULL);
+}
+
+static void
+gaic_launch(struct event_base *base, struct evdns_base *dns_base)
+{
+       struct gaic_request_status *status = calloc(1,sizeof(*status));
+       struct timeval tv = { 0, 10000 };
+       status->magic = GAIC_MAGIC;
+       status->base = base;
+       status->dns_base = dns_base;
+       event_assign(&status->cancel_event, base, -1, 0, gaic_cancel_request_cb,
+           status);
+       status->request = evdns_getaddrinfo(dns_base,
+           "foobar.bazquux.example.com", "80", NULL, gaic_getaddrinfo_cb,
+           status);
+       event_add(&status->cancel_event, &tv);
+       ++pending;
+}
+
+#ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
+/* FIXME: We should move this to regress_main.c if anything else needs it.*/
+
+/* Trivial replacements for malloc/free/realloc to check for memory leaks.
+ * Not threadsafe. */
+static int allocated_chunks = 0;
+
+static void *
+cnt_malloc(size_t sz)
+{
+       allocated_chunks += 1;
+       return malloc(sz);
+}
+
+static void *
+cnt_realloc(void *old, size_t sz)
+{
+       if (!old)
+               allocated_chunks += 1;
+       if (!sz)
+               allocated_chunks -= 1;
+       return realloc(old, sz);
+}
+
+static void
+cnt_free(void *ptr)
+{
+       allocated_chunks -= 1;
+       free(ptr);
+}
+
+struct testleak_env_t {
+       struct event_base *base;
+       struct evdns_base *dns_base;
+       struct evdns_request *req;
+       struct generic_dns_callback_result r;
+};
+
+static void *
+testleak_setup(const struct testcase_t *testcase)
+{
+       struct testleak_env_t *env;
+
+       allocated_chunks = 0;
+       event_set_mem_functions(cnt_malloc, cnt_realloc, cnt_free);
+       event_enable_debug_mode();
+
+       /* not mm_calloc: we don't want to mess with the count. */
+       env = calloc(1, sizeof(struct testleak_env_t));
+       env->base = event_base_new();
+       env->dns_base = evdns_base_new(env->base, 0);
+       env->req = evdns_base_resolve_ipv4(
+               env->dns_base, "example.com", DNS_QUERY_NO_SEARCH,
+               generic_dns_callback, &env->r);
+       return env;
+}
+
+static int
+testleak_cleanup(const struct testcase_t *testcase, void *env_)
+{
+       int ok = 0;
+       struct testleak_env_t *env = env_;
+#ifdef _EVENT_DISABLE_DEBUG_MODE
+       tt_int_op(allocated_chunks, ==, 0);
+#else
+       /* FIXME: that's `1' because of event_debug_map_HT_GROW */
+       tt_int_op(allocated_chunks, ==, 1);
+#endif
+       ok = 1;
+end:
+       if (env->dns_base)
+               evdns_base_free(env->dns_base, 0);
+       if (env->base)
+               event_base_free(env->base);
+       if (env)
+               free(env);
+       return ok;
+}
+
+static struct testcase_setup_t testleak_funcs = {
+       testleak_setup, testleak_cleanup
+};
+
+static void
+test_dbg_leak_cancel(void *env_)
+{
+       /* cancel, loop, free/dns, free/base */
+       struct testleak_env_t *env = env_;
+       int send_err_shutdown = 1;
+       evdns_cancel_request(env->dns_base, env->req);
+       env->req = 0;
+
+       /* `req` is freed in callback, that's why one loop is required. */
+       event_base_loop(env->base, EVLOOP_NONBLOCK);
+
+       /* send_err_shutdown means nothing as soon as our request is
+        * already canceled */
+       evdns_base_free(env->dns_base, send_err_shutdown);
+       env->dns_base = 0;
+       event_base_free(env->base);
+       env->base = 0;
+}
+
+static void
+test_dbg_leak_shutdown(void *env_)
+{
+       /* free/dns, loop, free/base */
+       struct testleak_env_t *env = env_;
+       int send_err_shutdown = 1;
+
+       /* `req` is freed both with `send_err_shutdown` and without it,
+        * the only difference is `evdns_callback` call */
+       env->req = 0;
+
+       evdns_base_free(env->dns_base, send_err_shutdown);
+       env->dns_base = 0;
+
+       /* `req` is freed in callback, that's why one loop is required */
+       event_base_loop(env->base, EVLOOP_NONBLOCK);
+       event_base_free(env->base);
+       env->base = 0;
+}
+#endif
+
+static void
+test_getaddrinfo_async_cancel_stress(void *ptr)
+{
+       struct event_base *base;
+       struct evdns_base *dns_base = NULL;
+       struct evdns_server_port *server = NULL;
+       evutil_socket_t fd = -1;
+       struct sockaddr_in sin;
+       struct sockaddr_storage ss;
+       ev_socklen_t slen;
+       int i;
+
+       base = event_base_new();
+       dns_base = evdns_base_new(base, 0);
+
+       memset(&sin, 0, sizeof(sin));
+       sin.sin_family = AF_INET;
+       sin.sin_port = 0;
+       sin.sin_addr.s_addr = htonl(0x7f000001);
+       if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+               tt_abort_perror("socket");
+       }
+       evutil_make_socket_nonblocking(fd);
+       if (bind(fd, (struct sockaddr*)&sin, sizeof(sin))<0) {
+               tt_abort_perror("bind");
+       }
+       server = evdns_add_server_port_with_base(base, fd, 0, gaic_server_cb,
+           base);
+
+       memset(&ss, 0, sizeof(ss));
+       slen = sizeof(ss);
+       if (getsockname(fd, (struct sockaddr*)&ss, &slen)<0) {
+               tt_abort_perror("getsockname");
+       }
+       evdns_base_nameserver_sockaddr_add(dns_base,
+           (struct sockaddr*)&ss, slen, 0);
+
+       for (i = 0; i < 1000; ++i) {
+               gaic_launch(base, dns_base);
+       }
+
+       event_base_dispatch(base);
+
+end:
+       if (dns_base)
+               evdns_base_free(dns_base, 1);
+       if (server)
+               evdns_close_server_port(server);
+       if (fd >= 0)
+               evutil_closesocket(fd);
+}
+
+
+#define DNS_LEGACY(name, flags)                                               \
+       { #name, run_legacy_test_fn, flags|TT_LEGACY, &legacy_setup,   \
+                   dns_##name }
+
+struct testcase_t dns_testcases[] = {
+       DNS_LEGACY(server, TT_FORK|TT_NEED_BASE),
+       DNS_LEGACY(gethostbyname, TT_FORK|TT_NEED_BASE|TT_NEED_DNS),
+       DNS_LEGACY(gethostbyname6, TT_FORK|TT_NEED_BASE|TT_NEED_DNS),
+       DNS_LEGACY(gethostbyaddr, TT_FORK|TT_NEED_BASE|TT_NEED_DNS),
+       { "resolve_reverse", dns_resolve_reverse, TT_FORK, NULL, NULL },
+       { "search", dns_search_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+       { "search_cancel", dns_search_cancel_test,
+         TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+       { "retry", dns_retry_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+       { "reissue", dns_reissue_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+       { "inflight", dns_inflight_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+       { "bufferevent_connect_hostname", test_bufferevent_connect_hostname,
+         TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+
+       { "getaddrinfo_async", test_getaddrinfo_async,
+         TT_FORK|TT_NEED_BASE, &basic_setup, (char*)"" },
+       { "getaddrinfo_cancel_stress", test_getaddrinfo_async_cancel_stress,
+         TT_FORK, NULL, NULL },
+
+#ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
+       { "leak_shutdown", test_dbg_leak_shutdown, TT_FORK, &testleak_funcs, NULL },
+       { "leak_cancel", test_dbg_leak_cancel, TT_FORK, &testleak_funcs, NULL },
+#endif
+
+       END_OF_TESTCASES
+};
+
diff --git a/libevent/test/regress_et.c b/libevent/test/regress_et.c
new file mode 100644 (file)
index 0000000..dee7b93
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "../util-internal.h"
+#include "event2/event-config.h"
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifndef WIN32
+#include <sys/time.h>
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/util.h"
+
+#include "regress.h"
+
+static int was_et = 0;
+
+static void
+read_cb(evutil_socket_t fd, short event, void *arg)
+{
+       char buf;
+       int len;
+
+       len = recv(fd, &buf, sizeof(buf), 0);
+
+       called++;
+       if (event & EV_ET)
+               was_et = 1;
+
+       if (!len)
+               event_del(arg);
+}
+
+#ifndef SHUT_WR
+#define SHUT_WR 1
+#endif
+
+#ifdef WIN32
+#define LOCAL_SOCKETPAIR_AF AF_INET
+#else
+#define LOCAL_SOCKETPAIR_AF AF_UNIX
+#endif
+
+static void
+test_edgetriggered(void *et)
+{
+       struct event *ev = NULL;
+       struct event_base *base = NULL;
+       const char *test = "test string";
+       evutil_socket_t pair[2] = {-1,-1};
+       int supports_et;
+
+       /* On Linux 3.2.1 (at least, as patched by Fedora and tested by Nick),
+        * doing a "recv" on an AF_UNIX socket resets the readability of the
+        * socket, even though there is no state change, so we don't actually
+        * get edge-triggered behavior.  Yuck!  Linux 3.1.9 didn't have this
+        * problem.
+        */
+#ifdef __linux__
+       if (evutil_ersatz_socketpair(AF_INET, SOCK_STREAM, 0, pair) == -1) {
+               tt_abort_perror("socketpair");
+       }
+#else
+       if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, pair) == -1) {
+               tt_abort_perror("socketpair");
+       }
+#endif
+
+       called = was_et = 0;
+
+       send(pair[0], test, (int)strlen(test)+1, 0);
+       shutdown(pair[0], SHUT_WR);
+
+       /* Initalize the event library */
+       base = event_base_new();
+
+       if (!strcmp(event_base_get_method(base), "epoll") ||
+           !strcmp(event_base_get_method(base), "epoll (with changelist)") ||
+           !strcmp(event_base_get_method(base), "kqueue"))
+               supports_et = 1;
+       else
+               supports_et = 0;
+
+       TT_BLATHER(("Checking for edge-triggered events with %s, which should %s"
+                               "support edge-triggering", event_base_get_method(base),
+                               supports_et?"":"not "));
+
+       /* Initalize one event */
+       ev = event_new(base, pair[1], EV_READ|EV_ET|EV_PERSIST, read_cb, &ev);
+
+       event_add(ev, NULL);
+
+       /* We're going to call the dispatch function twice.  The first invocation
+        * will read a single byte from pair[1] in either case.  If we're edge
+        * triggered, we'll only see the event once (since we only see transitions
+        * from no data to data), so the second invocation of event_base_loop will
+        * do nothing.  If we're level triggered, the second invocation of
+        * event_base_loop will also activate the event (because there's still
+        * data to read). */
+       event_base_loop(base,EVLOOP_NONBLOCK|EVLOOP_ONCE);
+       event_base_loop(base,EVLOOP_NONBLOCK|EVLOOP_ONCE);
+
+       if (supports_et) {
+               tt_int_op(called, ==, 1);
+               tt_assert(was_et);
+       } else {
+               tt_int_op(called, ==, 2);
+               tt_assert(!was_et);
+       }
+
+ end:
+       if (ev) {
+               event_del(ev);
+               event_free(ev);
+       }
+       if (base)
+               event_base_free(base);
+       evutil_closesocket(pair[0]);
+       evutil_closesocket(pair[1]);
+}
+
+static void
+test_edgetriggered_mix_error(void *data_)
+{
+       struct basic_test_data *data = data_;
+       struct event_base *base = NULL;
+       struct event *ev_et=NULL, *ev_lt=NULL;
+
+#ifdef _EVENT_DISABLE_DEBUG_MODE
+       if (1)
+               tt_skip();
+#endif
+
+       event_enable_debug_mode();
+
+       base = event_base_new();
+
+       /* try mixing edge-triggered and level-triggered to make sure it fails*/
+       ev_et = event_new(base, data->pair[0], EV_READ|EV_ET, read_cb, ev_et);
+       ev_lt = event_new(base, data->pair[0], EV_READ, read_cb, ev_lt);
+
+       /* Add edge-triggered, then level-triggered.  Get an error. */
+       tt_int_op(0, ==, event_add(ev_et, NULL));
+       tt_int_op(-1, ==, event_add(ev_lt, NULL));
+       tt_int_op(EV_READ, ==, event_pending(ev_et, EV_READ, NULL));
+       tt_int_op(0, ==, event_pending(ev_lt, EV_READ, NULL));
+
+       tt_int_op(0, ==, event_del(ev_et));
+       /* Add level-triggered, then edge-triggered.  Get an error. */
+       tt_int_op(0, ==, event_add(ev_lt, NULL));
+       tt_int_op(-1, ==, event_add(ev_et, NULL));
+       tt_int_op(EV_READ, ==, event_pending(ev_lt, EV_READ, NULL));
+       tt_int_op(0, ==, event_pending(ev_et, EV_READ, NULL));
+
+end:
+       if (ev_et)
+               event_free(ev_et);
+       if (ev_lt)
+               event_free(ev_lt);
+       if (base)
+               event_base_free(base);
+}
+
+struct testcase_t edgetriggered_testcases[] = {
+       { "et", test_edgetriggered, TT_FORK, NULL, NULL },
+       { "et_mix_error", test_edgetriggered_mix_error,
+         TT_FORK|TT_NEED_SOCKETPAIR|TT_NO_LOGS, &basic_setup, NULL },
+       END_OF_TESTCASES
+};
diff --git a/libevent/test/regress_http.c b/libevent/test/regress_http.c
new file mode 100644 (file)
index 0000000..aea318f
--- /dev/null
@@ -0,0 +1,3614 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/dns.h"
+
+#include "event2/event.h"
+#include "event2/http.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+#include "event2/util.h"
+#include "log-internal.h"
+#include "util-internal.h"
+#include "http-internal.h"
+#include "regress.h"
+#include "regress_testutils.h"
+
+static struct evhttp *http;
+/* set if a test needs to call loopexit on a base */
+static struct event_base *exit_base;
+
+static char const BASIC_REQUEST_BODY[] = "This is funny";
+
+static void http_basic_cb(struct evhttp_request *req, void *arg);
+static void http_chunked_cb(struct evhttp_request *req, void *arg);
+static void http_post_cb(struct evhttp_request *req, void *arg);
+static void http_put_cb(struct evhttp_request *req, void *arg);
+static void http_delete_cb(struct evhttp_request *req, void *arg);
+static void http_delay_cb(struct evhttp_request *req, void *arg);
+static void http_large_delay_cb(struct evhttp_request *req, void *arg);
+static void http_badreq_cb(struct evhttp_request *req, void *arg);
+static void http_dispatcher_cb(struct evhttp_request *req, void *arg);
+static int
+http_bind(struct evhttp *myhttp, ev_uint16_t *pport)
+{
+       int port;
+       struct evhttp_bound_socket *sock;
+
+       sock = evhttp_bind_socket_with_handle(myhttp, "127.0.0.1", *pport);
+       if (sock == NULL)
+               event_errx(1, "Could not start web server");
+
+       port = regress_get_socket_port(evhttp_bound_socket_get_fd(sock));
+       if (port < 0)
+               return -1;
+       *pport = (ev_uint16_t) port;
+
+       return 0;
+}
+
+static struct evhttp *
+http_setup(ev_uint16_t *pport, struct event_base *base)
+{
+       struct evhttp *myhttp;
+
+       /* Try a few different ports */
+       myhttp = evhttp_new(base);
+
+       if (http_bind(myhttp, pport) < 0)
+               return NULL;
+
+       /* Register a callback for certain types of requests */
+       evhttp_set_cb(myhttp, "/test", http_basic_cb, base);
+       evhttp_set_cb(myhttp, "/chunked", http_chunked_cb, base);
+       evhttp_set_cb(myhttp, "/streamed", http_chunked_cb, base);
+       evhttp_set_cb(myhttp, "/postit", http_post_cb, base);
+       evhttp_set_cb(myhttp, "/putit", http_put_cb, base);
+       evhttp_set_cb(myhttp, "/deleteit", http_delete_cb, base);
+       evhttp_set_cb(myhttp, "/delay", http_delay_cb, base);
+       evhttp_set_cb(myhttp, "/largedelay", http_large_delay_cb, base);
+       evhttp_set_cb(myhttp, "/badrequest", http_badreq_cb, base);
+       evhttp_set_cb(myhttp, "/", http_dispatcher_cb, base);
+       return (myhttp);
+}
+
+#ifndef NI_MAXSERV
+#define NI_MAXSERV 1024
+#endif
+
+static evutil_socket_t
+http_connect(const char *address, u_short port)
+{
+       /* Stupid code for connecting */
+       struct evutil_addrinfo ai, *aitop;
+       char strport[NI_MAXSERV];
+
+       struct sockaddr *sa;
+       int slen;
+       evutil_socket_t fd;
+
+       memset(&ai, 0, sizeof(ai));
+       ai.ai_family = AF_INET;
+       ai.ai_socktype = SOCK_STREAM;
+       evutil_snprintf(strport, sizeof(strport), "%d", port);
+       if (evutil_getaddrinfo(address, strport, &ai, &aitop) != 0) {
+               event_warn("getaddrinfo");
+               return (-1);
+       }
+       sa = aitop->ai_addr;
+       slen = aitop->ai_addrlen;
+
+       fd = socket(AF_INET, SOCK_STREAM, 0);
+       if (fd == -1)
+               event_err(1, "socket failed");
+
+       evutil_make_socket_nonblocking(fd);
+       if (connect(fd, sa, slen) == -1) {
+#ifdef WIN32
+               int tmp_err = WSAGetLastError();
+               if (tmp_err != WSAEINPROGRESS && tmp_err != WSAEINVAL &&
+                   tmp_err != WSAEWOULDBLOCK)
+                       event_err(1, "connect failed");
+#else
+               if (errno != EINPROGRESS)
+                       event_err(1, "connect failed");
+#endif
+       }
+
+       evutil_freeaddrinfo(aitop);
+
+       return (fd);
+}
+
+/* Helper: do a strcmp on the contents of buf and the string s. */
+static int
+evbuffer_datacmp(struct evbuffer *buf, const char *s)
+{
+       size_t b_sz = evbuffer_get_length(buf);
+       size_t s_sz = strlen(s);
+       unsigned char *d;
+       int r;
+
+       if (b_sz < s_sz)
+               return -1;
+
+       d = evbuffer_pullup(buf, s_sz);
+       if ((r = memcmp(d, s, s_sz)))
+               return r;
+
+       if (b_sz > s_sz)
+               return 1;
+       else
+               return 0;
+}
+
+/* Helper: Return true iff buf contains s */
+static int
+evbuffer_contains(struct evbuffer *buf, const char *s)
+{
+       struct evbuffer_ptr ptr;
+       ptr = evbuffer_search(buf, s, strlen(s), NULL);
+       return ptr.pos != -1;
+}
+
+static void
+http_readcb(struct bufferevent *bev, void *arg)
+{
+       const char *what = BASIC_REQUEST_BODY;
+       struct event_base *my_base = arg;
+
+       if (evbuffer_contains(bufferevent_get_input(bev), what)) {
+               struct evhttp_request *req = evhttp_request_new(NULL, NULL);
+               enum message_read_status done;
+
+               /* req->kind = EVHTTP_RESPONSE; */
+               done = evhttp_parse_firstline(req, bufferevent_get_input(bev));
+               if (done != ALL_DATA_READ)
+                       goto out;
+
+               done = evhttp_parse_headers(req, bufferevent_get_input(bev));
+               if (done != ALL_DATA_READ)
+                       goto out;
+
+               if (done == 1 &&
+                   evhttp_find_header(evhttp_request_get_input_headers(req),
+                       "Content-Type") != NULL)
+                       test_ok++;
+
+        out:
+               evhttp_request_free(req);
+               bufferevent_disable(bev, EV_READ);
+               if (exit_base)
+                       event_base_loopexit(exit_base, NULL);
+               else if (my_base)
+                       event_base_loopexit(my_base, NULL);
+               else {
+                       fprintf(stderr, "No way to exit loop!\n");
+                       exit(1);
+               }
+       }
+}
+
+static void
+http_writecb(struct bufferevent *bev, void *arg)
+{
+       if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+               /* enable reading of the reply */
+               bufferevent_enable(bev, EV_READ);
+               test_ok++;
+       }
+}
+
+static void
+http_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+       test_ok = -2;
+       event_base_loopexit(arg, NULL);
+}
+
+static void
+http_basic_cb(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *evb = evbuffer_new();
+       int empty = evhttp_find_header(evhttp_request_get_input_headers(req), "Empty") != NULL;
+       event_debug(("%s: called\n", __func__));
+       evbuffer_add_printf(evb, BASIC_REQUEST_BODY);
+
+       /* For multi-line headers test */
+       {
+               const char *multi =
+                   evhttp_find_header(evhttp_request_get_input_headers(req),"X-multi");
+               if (multi) {
+                       if (strcmp("END", multi + strlen(multi) - 3) == 0)
+                               test_ok++;
+                       if (evhttp_find_header(evhttp_request_get_input_headers(req), "X-Last"))
+                               test_ok++;
+               }
+       }
+
+       /* injecting a bad content-length */
+       if (evhttp_find_header(evhttp_request_get_input_headers(req), "X-Negative"))
+               evhttp_add_header(evhttp_request_get_output_headers(req),
+                   "Content-Length", "-100");
+
+       /* allow sending of an empty reply */
+       evhttp_send_reply(req, HTTP_OK, "Everything is fine",
+           !empty ? evb : NULL);
+
+       evbuffer_free(evb);
+}
+
+static char const* const CHUNKS[] = {
+       "This is funny",
+       "but not hilarious.",
+       "bwv 1052"
+};
+
+struct chunk_req_state {
+       struct event_base *base;
+       struct evhttp_request *req;
+       int i;
+};
+
+static void
+http_chunked_trickle_cb(evutil_socket_t fd, short events, void *arg)
+{
+       struct evbuffer *evb = evbuffer_new();
+       struct chunk_req_state *state = arg;
+       struct timeval when = { 0, 0 };
+
+       evbuffer_add_printf(evb, "%s", CHUNKS[state->i]);
+       evhttp_send_reply_chunk(state->req, evb);
+       evbuffer_free(evb);
+
+       if (++state->i < (int) (sizeof(CHUNKS)/sizeof(CHUNKS[0]))) {
+               event_base_once(state->base, -1, EV_TIMEOUT,
+                   http_chunked_trickle_cb, state, &when);
+       } else {
+               evhttp_send_reply_end(state->req);
+               free(state);
+       }
+}
+
+static void
+http_chunked_cb(struct evhttp_request *req, void *arg)
+{
+       struct timeval when = { 0, 0 };
+       struct chunk_req_state *state = malloc(sizeof(struct chunk_req_state));
+       event_debug(("%s: called\n", __func__));
+
+       memset(state, 0, sizeof(struct chunk_req_state));
+       state->req = req;
+       state->base = arg;
+
+       if (strcmp(evhttp_request_get_uri(req), "/streamed") == 0) {
+               evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Length", "39");
+       }
+
+       /* generate a chunked/streamed reply */
+       evhttp_send_reply_start(req, HTTP_OK, "Everything is fine");
+
+       /* but trickle it across several iterations to ensure we're not
+        * assuming it comes all at once */
+       event_base_once(arg, -1, EV_TIMEOUT, http_chunked_trickle_cb, state, &when);
+}
+
+static void
+http_complete_write(evutil_socket_t fd, short what, void *arg)
+{
+       struct bufferevent *bev = arg;
+       const char *http_request = "host\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+       bufferevent_write(bev, http_request, strlen(http_request));
+}
+
+static void
+http_basic_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct timeval tv;
+       struct bufferevent *bev;
+       evutil_socket_t fd;
+       const char *http_request;
+       ev_uint16_t port = 0, port2 = 0;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       /* bind to a second socket */
+       if (http_bind(http, &port2) == -1) {
+               fprintf(stdout, "FAILED (bind)\n");
+               exit(1);
+       }
+
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_readcb, http_writecb,
+           http_errorcb, data->base);
+
+       /* first half of the http request */
+       http_request =
+           "GET /test HTTP/1.1\r\n"
+           "Host: some";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+       evutil_timerclear(&tv);
+       tv.tv_usec = 10000;
+       event_base_once(data->base,
+           -1, EV_TIMEOUT, http_complete_write, bev, &tv);
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok == 3);
+
+       /* connect to the second port */
+       bufferevent_free(bev);
+       evutil_closesocket(fd);
+
+       fd = http_connect("127.0.0.1", port2);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_readcb, http_writecb,
+           http_errorcb, data->base);
+
+       http_request =
+           "GET /test HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok == 5);
+
+       /* Connect to the second port again. This time, send an absolute uri. */
+       bufferevent_free(bev);
+       evutil_closesocket(fd);
+
+       fd = http_connect("127.0.0.1", port2);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_readcb, http_writecb,
+           http_errorcb, data->base);
+
+       http_request =
+           "GET http://somehost.net/test HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok == 7);
+
+       evhttp_free(http);
+ end:
+       ;
+}
+
+static void
+http_delay_reply(evutil_socket_t fd, short what, void *arg)
+{
+       struct evhttp_request *req = arg;
+
+       evhttp_send_reply(req, HTTP_OK, "Everything is fine", NULL);
+
+       ++test_ok;
+}
+
+static void
+http_delay_cb(struct evhttp_request *req, void *arg)
+{
+       struct timeval tv;
+       evutil_timerclear(&tv);
+       tv.tv_sec = 0;
+       tv.tv_usec = 200 * 1000;
+
+       event_base_once(arg, -1, EV_TIMEOUT, http_delay_reply, req, &tv);
+}
+
+static void
+http_badreq_cb(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *buf = evbuffer_new();
+
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/xml; charset=UTF-8");
+       evbuffer_add_printf(buf, "Hello, %s!", "127.0.0.1");
+
+       evhttp_send_reply(req, HTTP_OK, "OK", buf);
+       evbuffer_free(buf);
+}
+
+static void
+http_badreq_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+       event_debug(("%s: called (what=%04x, arg=%p)", __func__, what, arg));
+       /* ignore */
+}
+
+#ifndef SHUT_WR
+#ifdef WIN32
+#define SHUT_WR SD_SEND
+#else
+#define SHUT_WR 1
+#endif
+#endif
+
+static void
+http_badreq_readcb(struct bufferevent *bev, void *arg)
+{
+       const char *what = "Hello, 127.0.0.1";
+       const char *bad_request = "400 Bad Request";
+
+       if (evbuffer_contains(bufferevent_get_input(bev), bad_request)) {
+               TT_FAIL(("%s:bad request detected", __func__));
+               bufferevent_disable(bev, EV_READ);
+               event_base_loopexit(arg, NULL);
+               return;
+       }
+
+       if (evbuffer_contains(bufferevent_get_input(bev), what)) {
+               struct evhttp_request *req = evhttp_request_new(NULL, NULL);
+               enum message_read_status done;
+
+               /* req->kind = EVHTTP_RESPONSE; */
+               done = evhttp_parse_firstline(req, bufferevent_get_input(bev));
+               if (done != ALL_DATA_READ)
+                       goto out;
+
+               done = evhttp_parse_headers(req, bufferevent_get_input(bev));
+               if (done != ALL_DATA_READ)
+                       goto out;
+
+               if (done == 1 &&
+                   evhttp_find_header(evhttp_request_get_input_headers(req),
+                       "Content-Type") != NULL)
+                       test_ok++;
+
+       out:
+               evhttp_request_free(req);
+               evbuffer_drain(bufferevent_get_input(bev), evbuffer_get_length(bufferevent_get_input(bev)));
+       }
+
+       shutdown(bufferevent_getfd(bev), SHUT_WR);
+}
+
+static void
+http_badreq_successcb(evutil_socket_t fd, short what, void *arg)
+{
+       event_debug(("%s: called (what=%04x, arg=%p)", __func__, what, arg));
+       event_base_loopexit(exit_base, NULL);
+}
+
+static void
+http_bad_request_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct timeval tv;
+       struct bufferevent *bev = NULL;
+       evutil_socket_t fd;
+       const char *http_request;
+       ev_uint16_t port=0, port2=0;
+
+       test_ok = 0;
+       exit_base = data->base;
+
+       http = http_setup(&port, data->base);
+
+       /* bind to a second socket */
+       if (http_bind(http, &port2) == -1)
+               TT_DIE(("Bind socket failed"));
+
+       /* NULL request test */
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_badreq_readcb, http_writecb,
+           http_badreq_errorcb, data->base);
+       bufferevent_enable(bev, EV_READ);
+
+       /* real NULL request */
+       http_request = "";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       shutdown(fd, SHUT_WR);
+       timerclear(&tv);
+       tv.tv_usec = 10000;
+       event_base_once(data->base, -1, EV_TIMEOUT, http_badreq_successcb, bev, &tv);
+
+       event_base_dispatch(data->base);
+
+       bufferevent_free(bev);
+       evutil_closesocket(fd);
+
+       if (test_ok != 0) {
+               fprintf(stdout, "FAILED\n");
+               exit(1);
+       }
+
+       /* Second answer (BAD REQUEST) on connection close */
+
+       /* connect to the second port */
+       fd = http_connect("127.0.0.1", port2);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_badreq_readcb, http_writecb,
+           http_badreq_errorcb, data->base);
+       bufferevent_enable(bev, EV_READ);
+
+       /* first half of the http request */
+       http_request =
+               "GET /badrequest HTTP/1.0\r\n"  \
+               "Connection: Keep-Alive\r\n"    \
+               "\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       timerclear(&tv);
+       tv.tv_usec = 10000;
+       event_base_once(data->base, -1, EV_TIMEOUT, http_badreq_successcb, bev, &tv);
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(test_ok, ==, 2);
+
+end:
+       evhttp_free(http);
+       if (bev)
+               bufferevent_free(bev);
+}
+
+static struct evhttp_connection *delayed_client;
+
+static void
+http_large_delay_cb(struct evhttp_request *req, void *arg)
+{
+       struct timeval tv;
+       evutil_timerclear(&tv);
+       tv.tv_sec = 3;
+
+       event_base_once(arg, -1, EV_TIMEOUT, http_delay_reply, req, &tv);
+       evhttp_connection_fail(delayed_client, EVCON_HTTP_EOF);
+}
+
+/*
+ * HTTP DELETE test,  just piggyback on the basic test
+ */
+
+static void
+http_delete_cb(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *evb = evbuffer_new();
+       int empty = evhttp_find_header(evhttp_request_get_input_headers(req), "Empty") != NULL;
+
+       /* Expecting a DELETE request */
+       if (evhttp_request_get_command(req) != EVHTTP_REQ_DELETE) {
+               fprintf(stdout, "FAILED (delete type)\n");
+               exit(1);
+       }
+
+       event_debug(("%s: called\n", __func__));
+       evbuffer_add_printf(evb, BASIC_REQUEST_BODY);
+
+       /* allow sending of an empty reply */
+       evhttp_send_reply(req, HTTP_OK, "Everything is fine",
+           !empty ? evb : NULL);
+
+       evbuffer_free(evb);
+}
+
+static void
+http_delete_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct bufferevent *bev;
+       evutil_socket_t fd;
+       const char *http_request;
+       ev_uint16_t port = 0;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_readcb, http_writecb,
+           http_errorcb, data->base);
+
+       http_request =
+           "DELETE /deleteit HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       event_base_dispatch(data->base);
+
+       bufferevent_free(bev);
+       evutil_closesocket(fd);
+
+       evhttp_free(http);
+
+       tt_int_op(test_ok, ==, 2);
+ end:
+       ;
+}
+
+static void
+http_allowed_methods_eventcb(struct bufferevent *bev, short what, void *arg)
+{
+       char **output = arg;
+       if ((what & (BEV_EVENT_ERROR|BEV_EVENT_EOF))) {
+               char buf[4096];
+               int n;
+               n = evbuffer_remove(bufferevent_get_input(bev), buf,
+                   sizeof(buf)-1);
+               if (n >= 0) {
+                       buf[n]='\0';
+                       if (*output)
+                               free(*output);
+                       *output = strdup(buf);
+               }
+               event_base_loopexit(exit_base, NULL);
+       }
+}
+
+static void
+http_allowed_methods_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct bufferevent *bev1, *bev2, *bev3;
+       evutil_socket_t fd1, fd2, fd3;
+       const char *http_request;
+       char *result1=NULL, *result2=NULL, *result3=NULL;
+       ev_uint16_t port = 0;
+
+       exit_base = data->base;
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       fd1 = http_connect("127.0.0.1", port);
+
+       /* GET is out; PATCH is in. */
+       evhttp_set_allowed_methods(http, EVHTTP_REQ_PATCH);
+
+       /* Stupid thing to send a request */
+       bev1 = bufferevent_socket_new(data->base, fd1, 0);
+       bufferevent_enable(bev1, EV_READ|EV_WRITE);
+       bufferevent_setcb(bev1, NULL, NULL,
+           http_allowed_methods_eventcb, &result1);
+
+       http_request =
+           "GET /index.html HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev1, http_request, strlen(http_request));
+
+       event_base_dispatch(data->base);
+
+       fd2 = http_connect("127.0.0.1", port);
+
+       bev2 = bufferevent_socket_new(data->base, fd2, 0);
+       bufferevent_enable(bev2, EV_READ|EV_WRITE);
+       bufferevent_setcb(bev2, NULL, NULL,
+           http_allowed_methods_eventcb, &result2);
+
+       http_request =
+           "PATCH /test HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev2, http_request, strlen(http_request));
+
+       event_base_dispatch(data->base);
+
+       fd3 = http_connect("127.0.0.1", port);
+
+       bev3 = bufferevent_socket_new(data->base, fd3, 0);
+       bufferevent_enable(bev3, EV_READ|EV_WRITE);
+       bufferevent_setcb(bev3, NULL, NULL,
+           http_allowed_methods_eventcb, &result3);
+
+       http_request =
+           "FLOOP /test HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev3, http_request, strlen(http_request));
+
+       event_base_dispatch(data->base);
+
+       bufferevent_free(bev1);
+       bufferevent_free(bev2);
+       bufferevent_free(bev3);
+       evutil_closesocket(fd1);
+       evutil_closesocket(fd2);
+       evutil_closesocket(fd3);
+
+       evhttp_free(http);
+
+       /* Method known but disallowed */
+       tt_assert(result1);
+       tt_assert(!strncmp(result1, "HTTP/1.1 501 ", strlen("HTTP/1.1 501 ")));
+
+       /* Method known and allowed */
+       tt_assert(result2);
+       tt_assert(!strncmp(result2, "HTTP/1.1 200 ", strlen("HTTP/1.1 200 ")));
+
+       /* Method unknown */
+       tt_assert(result3);
+       tt_assert(!strncmp(result3, "HTTP/1.1 501 ", strlen("HTTP/1.1 501 ")));
+
+ end:
+       if (result1)
+               free(result1);
+       if (result2)
+               free(result2);
+       if (result3)
+               free(result3);
+}
+
+static void http_request_done(struct evhttp_request *, void *);
+static void http_request_empty_done(struct evhttp_request *, void *);
+
+static void
+_http_connection_test(struct basic_test_data *data, int persistent)
+{
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       tt_assert(evhttp_connection_get_base(evcon) == data->base);
+
+       exit_base = data->base;
+       /*
+        * At this point, we want to schedule a request to the HTTP
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+               fprintf(stdout, "FAILED\n");
+               exit(1);
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok);
+
+       /* try to make another request over the same connection */
+       test_ok = 0;
+
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /*
+        * if our connections are not supposed to be persistent; request
+        * a close from the server.
+        */
+       if (!persistent)
+               evhttp_add_header(evhttp_request_get_output_headers(req), "Connection", "close");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+               tt_abort_msg("couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       /* make another request: request empty reply */
+       test_ok = 0;
+
+       req = evhttp_request_new(http_request_empty_done, data->base);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Empty", "itis");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+               tt_abort_msg("Couldn't make request");
+               exit(1);
+       }
+
+       event_base_dispatch(data->base);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+http_connection_test(void *arg)
+{
+       _http_connection_test(arg, 0);
+}
+static void
+http_persist_connection_test(void *arg)
+{
+       _http_connection_test(arg, 1);
+}
+
+static struct regress_dns_server_table search_table[] = {
+       { "localhost", "A", "127.0.0.1", 0 },
+       { NULL, NULL, NULL, 0 }
+};
+
+static void
+http_connection_async_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+       struct evdns_base *dns_base = NULL;
+       ev_uint16_t portnum = 0;
+       char address[64];
+
+       exit_base = data->base;
+       tt_assert(regress_dnsserver(data->base, &portnum, search_table));
+
+       dns_base = evdns_base_new(data->base, 0/* init name servers */);
+       tt_assert(dns_base);
+
+       /* Add ourself as the only nameserver, and make sure we really are
+        * the only nameserver. */
+       evutil_snprintf(address, sizeof(address), "127.0.0.1:%d", portnum);
+       evdns_base_nameserver_ip_add(dns_base, address);
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, dns_base, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /*
+        * At this point, we want to schedule a request to the HTTP
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+               fprintf(stdout, "FAILED\n");
+               exit(1);
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok);
+
+       /* try to make another request over the same connection */
+       test_ok = 0;
+
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /*
+        * if our connections are not supposed to be persistent; request
+        * a close from the server.
+        */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Connection", "close");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+               tt_abort_msg("couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       /* make another request: request empty reply */
+       test_ok = 0;
+
+       req = evhttp_request_new(http_request_empty_done, data->base);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Empty", "itis");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+               tt_abort_msg("Couldn't make request");
+               exit(1);
+       }
+
+       event_base_dispatch(data->base);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+       if (dns_base)
+               evdns_base_free(dns_base, 0);
+       regress_clean_dnsserver();
+}
+
+static void
+http_request_never_call(struct evhttp_request *req, void *arg)
+{
+       fprintf(stdout, "FAILED\n");
+       exit(1);
+}
+
+static void
+http_do_cancel(evutil_socket_t fd, short what, void *arg)
+{
+       struct evhttp_request *req = arg;
+       struct timeval tv;
+       struct event_base *base;
+       evutil_timerclear(&tv);
+       tv.tv_sec = 0;
+       tv.tv_usec = 500 * 1000;
+
+       base = evhttp_connection_get_base(evhttp_request_get_connection(req));
+       evhttp_cancel_request(req);
+
+       event_base_loopexit(base, &tv);
+
+       ++test_ok;
+}
+
+static void
+http_cancel_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+       struct timeval tv;
+
+       exit_base = data->base;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /*
+        * At this point, we want to schedule a request to the HTTP
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_request_never_call, NULL);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* We give ownership of the request to the connection */
+       tt_int_op(evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/delay"),
+                 !=, -1);
+
+       evutil_timerclear(&tv);
+       tv.tv_sec = 0;
+       tv.tv_usec = 100 * 1000;
+
+       event_base_once(data->base, -1, EV_TIMEOUT, http_do_cancel, req, &tv);
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(test_ok, ==, 2);
+
+       /* try to make another request over the same connection */
+       test_ok = 0;
+
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* We give ownership of the request to the connection */
+       tt_int_op(evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test"),
+                 !=, -1);
+
+       event_base_dispatch(data->base);
+
+       /* make another request: request empty reply */
+       test_ok = 0;
+
+       req = evhttp_request_new(http_request_empty_done, data->base);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Empty", "itis");
+
+       /* We give ownership of the request to the connection */
+       tt_int_op(evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test"),
+                 !=, -1);
+
+       event_base_dispatch(data->base);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+http_request_done(struct evhttp_request *req, void *arg)
+{
+       const char *what = arg;
+
+       if (evhttp_request_get_response_code(req) != HTTP_OK) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") == NULL) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(what)) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), what) != 0) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       EVUTIL_ASSERT(exit_base);
+       event_base_loopexit(exit_base, NULL);
+}
+
+static void
+http_request_expect_error(struct evhttp_request *req, void *arg)
+{
+       if (evhttp_request_get_response_code(req) == HTTP_OK) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       EVUTIL_ASSERT(arg);
+       event_base_loopexit(arg, NULL);
+}
+
+/* test virtual hosts */
+static void
+http_virtual_host_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+       struct evhttp *second = NULL, *third = NULL;
+       evutil_socket_t fd;
+       struct bufferevent *bev;
+       const char *http_request;
+
+       exit_base = data->base;
+
+       http = http_setup(&port, data->base);
+
+       /* virtual host */
+       second = evhttp_new(NULL);
+       evhttp_set_cb(second, "/funnybunny", http_basic_cb, NULL);
+       third = evhttp_new(NULL);
+       evhttp_set_cb(third, "/blackcoffee", http_basic_cb, NULL);
+
+       if (evhttp_add_virtual_host(http, "foo.com", second) == -1) {
+               tt_abort_msg("Couldn't add vhost");
+       }
+
+       if (evhttp_add_virtual_host(http, "bar.*.foo.com", third) == -1) {
+               tt_abort_msg("Couldn't add wildcarded vhost");
+       }
+
+       /* add some aliases to the vhosts */
+       tt_assert(evhttp_add_server_alias(second, "manolito.info") == 0);
+       tt_assert(evhttp_add_server_alias(third, "bonkers.org") == 0);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /* make a request with a different host and expect an error */
+       req = evhttp_request_new(http_request_expect_error, data->base);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+               "/funnybunny") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok == 1);
+
+       test_ok = 0;
+
+       /* make a request with the right host and expect a response */
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "foo.com");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+               "/funnybunny") == -1) {
+               fprintf(stdout, "FAILED\n");
+               exit(1);
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok == 1);
+
+       test_ok = 0;
+
+       /* make a request with the right host and expect a response */
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "bar.magic.foo.com");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+               "/blackcoffee") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok == 1)
+
+       test_ok = 0;
+
+       /* make a request with the right host and expect a response */
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "manolito.info");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+               "/funnybunny") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok == 1)
+
+       test_ok = 0;
+
+       /* make a request with the right host and expect a response */
+       req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+       /* Add the Host header. This time with the optional port. */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "bonkers.org:8000");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+               "/blackcoffee") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_ok == 1)
+
+       test_ok = 0;
+
+       /* Now make a raw request with an absolute URI. */
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_readcb, http_writecb,
+           http_errorcb, NULL);
+
+       /* The host in the URI should override the Host: header */
+       http_request =
+           "GET http://manolito.info/funnybunny HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(test_ok, ==, 2);
+
+       bufferevent_free(bev);
+       evutil_closesocket(fd);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+
+/* test date header and content length */
+
+static void
+http_request_empty_done(struct evhttp_request *req, void *arg)
+{
+       if (evhttp_request_get_response_code(req) != HTTP_OK) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (evhttp_find_header(evhttp_request_get_input_headers(req), "Date") == NULL) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+
+       if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Length") == NULL) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (strcmp(evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Length"),
+               "0")) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != 0) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       EVUTIL_ASSERT(arg);
+       event_base_loopexit(arg, NULL);
+}
+
+/*
+ * HTTP DISPATCHER test
+ */
+
+void
+http_dispatcher_cb(struct evhttp_request *req, void *arg)
+{
+
+       struct evbuffer *evb = evbuffer_new();
+       event_debug(("%s: called\n", __func__));
+       evbuffer_add_printf(evb, "DISPATCHER_TEST");
+
+       evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+       evbuffer_free(evb);
+}
+
+static void
+http_dispatcher_test_done(struct evhttp_request *req, void *arg)
+{
+       struct event_base *base = arg;
+       const char *what = "DISPATCHER_TEST";
+
+       if (evhttp_request_get_response_code(req) != HTTP_OK) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") == NULL) {
+               fprintf(stderr, "FAILED (content type)\n");
+               exit(1);
+       }
+
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(what)) {
+               fprintf(stderr, "FAILED (length %lu vs %lu)\n",
+                   (unsigned long)evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long)strlen(what));
+               exit(1);
+       }
+
+       if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), what) != 0) {
+               fprintf(stderr, "FAILED (data)\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       event_base_loopexit(base, NULL);
+}
+
+static void
+http_dispatcher_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /* also bind to local host */
+       evhttp_connection_set_local_address(evcon, "127.0.0.1");
+
+       /*
+        * At this point, we want to schedule an HTTP GET request
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_dispatcher_test_done, data->base);
+       tt_assert(req);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/?arg=val") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+/*
+ * HTTP POST test.
+ */
+
+void http_postrequest_done(struct evhttp_request *, void *);
+
+#define POST_DATA "Okay.  Not really printf"
+
+static void
+http_post_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /*
+        * At this point, we want to schedule an HTTP POST request
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_postrequest_done, data->base);
+       tt_assert(req);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+       evbuffer_add_printf(evhttp_request_get_output_buffer(req), POST_DATA);
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/postit") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(test_ok, ==, 1);
+
+       test_ok = 0;
+
+       req = evhttp_request_new(http_postrequest_done, data->base);
+       tt_assert(req);
+
+       /* Now try with 100-continue. */
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Expect", "100-continue");
+       evbuffer_add_printf(evhttp_request_get_output_buffer(req), POST_DATA);
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/postit") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(test_ok, ==, 1);
+
+       evhttp_connection_free(evcon);
+       evhttp_free(http);
+
+ end:
+       ;
+}
+
+void
+http_post_cb(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *evb;
+       event_debug(("%s: called\n", __func__));
+
+       /* Yes, we are expecting a post request */
+       if (evhttp_request_get_command(req) != EVHTTP_REQ_POST) {
+               fprintf(stdout, "FAILED (post type)\n");
+               exit(1);
+       }
+
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(POST_DATA)) {
+               fprintf(stdout, "FAILED (length: %lu vs %lu)\n",
+                   (unsigned long) evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long) strlen(POST_DATA));
+               exit(1);
+       }
+
+       if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), POST_DATA) != 0) {
+               fprintf(stdout, "FAILED (data)\n");
+               fprintf(stdout, "Got :%s\n", evbuffer_pullup(evhttp_request_get_input_buffer(req),-1));
+               fprintf(stdout, "Want:%s\n", POST_DATA);
+               exit(1);
+       }
+
+       evb = evbuffer_new();
+       evbuffer_add_printf(evb, BASIC_REQUEST_BODY);
+
+       evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+       evbuffer_free(evb);
+}
+
+void
+http_postrequest_done(struct evhttp_request *req, void *arg)
+{
+       const char *what = BASIC_REQUEST_BODY;
+       struct event_base *base = arg;
+
+       if (req == NULL) {
+               fprintf(stderr, "FAILED (timeout)\n");
+               exit(1);
+       }
+
+       if (evhttp_request_get_response_code(req) != HTTP_OK) {
+
+               fprintf(stderr, "FAILED (response code)\n");
+               exit(1);
+       }
+
+       if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") == NULL) {
+               fprintf(stderr, "FAILED (content type)\n");
+               exit(1);
+       }
+
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(what)) {
+               fprintf(stderr, "FAILED (length %lu vs %lu)\n",
+                   (unsigned long)evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long)strlen(what));
+               exit(1);
+       }
+
+       if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), what) != 0) {
+               fprintf(stderr, "FAILED (data)\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       event_base_loopexit(base, NULL);
+}
+
+/*
+ * HTTP PUT test, basically just like POST, but ...
+ */
+
+void http_putrequest_done(struct evhttp_request *, void *);
+
+#define PUT_DATA "Hi, I'm some PUT data"
+
+static void
+http_put_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /*
+        * Schedule the HTTP PUT request
+        */
+
+       req = evhttp_request_new(http_putrequest_done, data->base);
+       tt_assert(req);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "someotherhost");
+       evbuffer_add_printf(evhttp_request_get_output_buffer(req), PUT_DATA);
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_PUT, "/putit") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       evhttp_connection_free(evcon);
+       evhttp_free(http);
+
+       tt_int_op(test_ok, ==, 1);
+ end:
+       ;
+}
+
+void
+http_put_cb(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *evb;
+       event_debug(("%s: called\n", __func__));
+
+       /* Expecting a PUT request */
+       if (evhttp_request_get_command(req) != EVHTTP_REQ_PUT) {
+               fprintf(stdout, "FAILED (put type)\n");
+               exit(1);
+       }
+
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(PUT_DATA)) {
+               fprintf(stdout, "FAILED (length: %lu vs %lu)\n",
+                   (unsigned long)evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long)strlen(PUT_DATA));
+               exit(1);
+       }
+
+       if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), PUT_DATA) != 0) {
+               fprintf(stdout, "FAILED (data)\n");
+               fprintf(stdout, "Got :%s\n", evbuffer_pullup(evhttp_request_get_input_buffer(req),-1));
+               fprintf(stdout, "Want:%s\n", PUT_DATA);
+               exit(1);
+       }
+
+       evb = evbuffer_new();
+       evbuffer_add_printf(evb, "That ain't funny");
+
+       evhttp_send_reply(req, HTTP_OK, "Everything is great", evb);
+
+       evbuffer_free(evb);
+}
+
+void
+http_putrequest_done(struct evhttp_request *req, void *arg)
+{
+       struct event_base *base = arg;
+       const char *what = "That ain't funny";
+
+       if (req == NULL) {
+               fprintf(stderr, "FAILED (timeout)\n");
+               exit(1);
+       }
+
+       if (evhttp_request_get_response_code(req) != HTTP_OK) {
+
+               fprintf(stderr, "FAILED (response code)\n");
+               exit(1);
+       }
+
+       if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") == NULL) {
+               fprintf(stderr, "FAILED (content type)\n");
+               exit(1);
+       }
+
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(what)) {
+               fprintf(stderr, "FAILED (length %lu vs %lu)\n",
+                   (unsigned long)evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long)strlen(what));
+               exit(1);
+       }
+
+
+       if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), what) != 0) {
+               fprintf(stderr, "FAILED (data)\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       event_base_loopexit(base, NULL);
+}
+
+static void
+http_failure_readcb(struct bufferevent *bev, void *arg)
+{
+       const char *what = "400 Bad Request";
+       if (evbuffer_contains(bufferevent_get_input(bev), what)) {
+               test_ok = 2;
+               bufferevent_disable(bev, EV_READ);
+               event_base_loopexit(arg, NULL);
+       }
+}
+
+/*
+ * Testing that the HTTP server can deal with a malformed request.
+ */
+static void
+http_failure_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct bufferevent *bev;
+       evutil_socket_t fd;
+       const char *http_request;
+       ev_uint16_t port = 0;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_failure_readcb, http_writecb,
+           http_errorcb, data->base);
+
+       http_request = "illegal request\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       event_base_dispatch(data->base);
+
+       bufferevent_free(bev);
+       evutil_closesocket(fd);
+
+       evhttp_free(http);
+
+       tt_int_op(test_ok, ==, 2);
+ end:
+       ;
+}
+
+static void
+close_detect_done(struct evhttp_request *req, void *arg)
+{
+       struct timeval tv;
+       tt_assert(req);
+       tt_assert(evhttp_request_get_response_code(req) == HTTP_OK);
+
+       test_ok = 1;
+
+ end:
+       evutil_timerclear(&tv);
+       tv.tv_sec = 3;
+       event_base_loopexit(arg, &tv);
+}
+
+static void
+close_detect_launch(evutil_socket_t fd, short what, void *arg)
+{
+       struct evhttp_connection *evcon = arg;
+       struct event_base *base = evhttp_connection_get_base(evcon);
+       struct evhttp_request *req;
+
+       req = evhttp_request_new(close_detect_done, base);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+               tt_fail_msg("Couldn't make request");
+       }
+}
+
+static void
+close_detect_cb(struct evhttp_request *req, void *arg)
+{
+       struct evhttp_connection *evcon = arg;
+       struct event_base *base = evhttp_connection_get_base(evcon);
+       struct timeval tv;
+
+       if (req != NULL && evhttp_request_get_response_code(req) != HTTP_OK) {
+               tt_abort_msg("Failed");
+       }
+
+       evutil_timerclear(&tv);
+       tv.tv_sec = 3;   /* longer than the http time out */
+
+       /* launch a new request on the persistent connection in 3 seconds */
+       event_base_once(base, -1, EV_TIMEOUT, close_detect_launch, evcon, &tv);
+ end:
+       ;
+}
+
+
+static void
+_http_close_detection(struct basic_test_data *data, int with_delay)
+{
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       test_ok = 0;
+       http = http_setup(&port, data->base);
+
+       /* 2 second timeout */
+       evhttp_set_timeout(http, 1);
+
+       evcon = evhttp_connection_base_new(data->base, NULL,
+           "127.0.0.1", port);
+       tt_assert(evcon);
+       delayed_client = evcon;
+
+       /*
+        * At this point, we want to schedule a request to the HTTP
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(close_detect_cb, evcon);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon,
+           req, EVHTTP_REQ_GET, with_delay ? "/largedelay" : "/test") == -1) {
+               tt_abort_msg("couldn't make request");
+               exit(1);
+       }
+
+       event_base_dispatch(data->base);
+
+       /* at this point, the http server should have no connection */
+       tt_assert(TAILQ_FIRST(&http->connections) == NULL);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+static void
+http_close_detection_test(void *arg)
+{
+       _http_close_detection(arg, 0);
+}
+static void
+http_close_detection_delay_test(void *arg)
+{
+       _http_close_detection(arg, 1);
+}
+
+static void
+http_highport_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       int i = -1;
+       struct evhttp *myhttp = NULL;
+
+       /* Try a few different ports */
+       for (i = 0; i < 50; ++i) {
+               myhttp = evhttp_new(data->base);
+               if (evhttp_bind_socket(myhttp, "127.0.0.1", 65535 - i) == 0) {
+                       test_ok = 1;
+                       evhttp_free(myhttp);
+                       return;
+               }
+               evhttp_free(myhttp);
+       }
+
+       tt_fail_msg("Couldn't get a high port");
+}
+
+static void
+http_bad_header_test(void *ptr)
+{
+       struct evkeyvalq headers;
+
+       TAILQ_INIT(&headers);
+
+       tt_want(evhttp_add_header(&headers, "One", "Two") == 0);
+       tt_want(evhttp_add_header(&headers, "One", "Two\r\n Three") == 0);
+       tt_want(evhttp_add_header(&headers, "One\r", "Two") == -1);
+       tt_want(evhttp_add_header(&headers, "One\n", "Two") == -1);
+       tt_want(evhttp_add_header(&headers, "One", "Two\r") == -1);
+       tt_want(evhttp_add_header(&headers, "One", "Two\n") == -1);
+
+       evhttp_clear_headers(&headers);
+}
+
+static int validate_header(
+       const struct evkeyvalq* headers,
+       const char *key, const char *value)
+{
+       const char *real_val = evhttp_find_header(headers, key);
+       tt_assert(real_val != NULL);
+       tt_want(strcmp(real_val, value) == 0);
+end:
+       return (0);
+}
+
+static void
+http_parse_query_test(void *ptr)
+{
+       struct evkeyvalq headers;
+       int r;
+
+       TAILQ_INIT(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=test", &headers);
+       tt_want(validate_header(&headers, "q", "test") == 0);
+       tt_int_op(r, ==, 0);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=test&foo=bar", &headers);
+       tt_want(validate_header(&headers, "q", "test") == 0);
+       tt_want(validate_header(&headers, "foo", "bar") == 0);
+       tt_int_op(r, ==, 0);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=test+foo", &headers);
+       tt_want(validate_header(&headers, "q", "test foo") == 0);
+       tt_int_op(r, ==, 0);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=test%0Afoo", &headers);
+       tt_want(validate_header(&headers, "q", "test\nfoo") == 0);
+       tt_int_op(r, ==, 0);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=test%0Dfoo", &headers);
+       tt_want(validate_header(&headers, "q", "test\rfoo") == 0);
+       tt_int_op(r, ==, 0);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=test&&q2", &headers);
+       tt_int_op(r, ==, -1);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=test+this", &headers);
+       tt_want(validate_header(&headers, "q", "test this") == 0);
+       tt_int_op(r, ==, 0);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=test&q2=foo", &headers);
+       tt_int_op(r, ==, 0);
+       tt_want(validate_header(&headers, "q", "test") == 0);
+       tt_want(validate_header(&headers, "q2", "foo") == 0);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q&q2=foo", &headers);
+       tt_int_op(r, ==, -1);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=foo&q2", &headers);
+       tt_int_op(r, ==, -1);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=foo&q2&q3=x", &headers);
+       tt_int_op(r, ==, -1);
+       evhttp_clear_headers(&headers);
+
+       r = evhttp_parse_query("http://www.test.com/?q=&q2=&q3=", &headers);
+       tt_int_op(r, ==, 0);
+       tt_want(validate_header(&headers, "q", "") == 0);
+       tt_want(validate_header(&headers, "q2", "") == 0);
+       tt_want(validate_header(&headers, "q3", "") == 0);
+       evhttp_clear_headers(&headers);
+
+end:
+       evhttp_clear_headers(&headers);
+}
+
+static void
+http_parse_uri_test(void *ptr)
+{
+       const int nonconform = (ptr != NULL);
+       const unsigned parse_flags =
+           nonconform ? EVHTTP_URI_NONCONFORMANT : 0;
+       struct evhttp_uri *uri = NULL;
+       char url_tmp[4096];
+#define URI_PARSE(uri) \
+       evhttp_uri_parse_with_flags((uri), parse_flags)
+
+#define TT_URI(want) do {                                              \
+       char *ret = evhttp_uri_join(uri, url_tmp, sizeof(url_tmp));     \
+       tt_want(ret != NULL);                                           \
+       tt_want(ret == url_tmp);                                        \
+       if (strcmp(ret,want) != 0)                                      \
+               TT_FAIL(("\"%s\" != \"%s\"",ret,want));                 \
+       } while(0)
+
+       tt_want(evhttp_uri_join(NULL, 0, 0) == NULL);
+       tt_want(evhttp_uri_join(NULL, url_tmp, 0) == NULL);
+       tt_want(evhttp_uri_join(NULL, url_tmp, sizeof(url_tmp)) == NULL);
+
+       /* bad URIs: parsing */
+#define BAD(s) do {                                                    \
+               if (URI_PARSE(s) != NULL)                               \
+                       TT_FAIL(("Expected error parsing \"%s\"",s));   \
+       } while(0)
+       /* Nonconformant URIs we can parse: parsing */
+#define NCF(s) do {                                                    \
+               uri = URI_PARSE(s);                                     \
+               if (uri != NULL && !nonconform) {                       \
+                       TT_FAIL(("Expected error parsing \"%s\"",s));   \
+               } else if (uri == NULL && nonconform) {                 \
+                       TT_FAIL(("Couldn't parse nonconformant URI \"%s\"", \
+                               s));                                    \
+               }                                                       \
+               if (uri) {                                              \
+                       tt_want(evhttp_uri_join(uri, url_tmp,           \
+                               sizeof(url_tmp)));                      \
+                       evhttp_uri_free(uri);                           \
+               }                                                       \
+       } while(0)
+
+       NCF("http://www.test.com/ why hello");
+       NCF("http://www.test.com/why-hello\x01");
+       NCF("http://www.test.com/why-hello?\x01");
+       NCF("http://www.test.com/why-hello#\x01");
+       BAD("http://www.\x01.test.com/why-hello");
+       BAD("http://www.%7test.com/why-hello");
+       NCF("http://www.test.com/why-hell%7o");
+       BAD("h%3ttp://www.test.com/why-hello");
+       NCF("http://www.test.com/why-hello%7");
+       NCF("http://www.test.com/why-hell%7o");
+       NCF("http://www.test.com/foo?ba%r");
+       NCF("http://www.test.com/foo#ba%r");
+       BAD("99:99/foo");
+       BAD("http://www.test.com:999x/");
+       BAD("http://www.test.com:x/");
+       BAD("http://[hello-there]/");
+       BAD("http://[::1]]/");
+       BAD("http://[::1/");
+       BAD("http://[foob/");
+       BAD("http://[/");
+       BAD("http://[ffff:ffff:ffff:ffff:Ffff:ffff:ffff:"
+                   "ffff:ffff:ffff:ffff:ffff:ffff:ffff]/");
+       BAD("http://[vX.foo]/");
+       BAD("http://[vX.foo]/");
+       BAD("http://[v.foo]/");
+       BAD("http://[v5.fo%o]/");
+       BAD("http://[v5X]/");
+       BAD("http://[v5]/");
+       BAD("http://[]/");
+       BAD("http://f\x01red@www.example.com/");
+       BAD("http://f%0red@www.example.com/");
+       BAD("http://www.example.com:9999999999999999999999999999999999999/");
+       BAD("http://www.example.com:hihi/");
+       BAD("://www.example.com/");
+
+       /* bad URIs: joining */
+       uri = evhttp_uri_new();
+       tt_want(0==evhttp_uri_set_host(uri, "www.example.com"));
+       tt_want(evhttp_uri_join(uri, url_tmp, sizeof(url_tmp)) != NULL);
+       /* not enough space: */
+       tt_want(evhttp_uri_join(uri, url_tmp, 3) == NULL);
+       /* host is set, but path doesn't start with "/": */
+       tt_want(0==evhttp_uri_set_path(uri, "hi_mom"));
+       tt_want(evhttp_uri_join(uri, url_tmp, sizeof(url_tmp)) == NULL);
+       tt_want(evhttp_uri_join(uri, NULL, sizeof(url_tmp))==NULL);
+       tt_want(evhttp_uri_join(uri, url_tmp, 0)==NULL);
+       evhttp_uri_free(uri);
+       uri = URI_PARSE("mailto:foo@bar");
+       tt_want(uri != NULL);
+       tt_want(evhttp_uri_get_host(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(!strcmp(evhttp_uri_get_scheme(uri), "mailto"));
+       tt_want(!strcmp(evhttp_uri_get_path(uri), "foo@bar"));
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("mailto:foo@bar");
+       evhttp_uri_free(uri);
+
+       uri = evhttp_uri_new();
+       /* Bad URI usage: setting invalid values */
+       tt_want(-1 == evhttp_uri_set_scheme(uri,""));
+       tt_want(-1 == evhttp_uri_set_scheme(uri,"33"));
+       tt_want(-1 == evhttp_uri_set_scheme(uri,"hi!"));
+       tt_want(-1 == evhttp_uri_set_userinfo(uri,"hello@"));
+       tt_want(-1 == evhttp_uri_set_host(uri,"[1.2.3.4]"));
+       tt_want(-1 == evhttp_uri_set_host(uri,"["));
+       tt_want(-1 == evhttp_uri_set_host(uri,"www.[foo].com"));
+       tt_want(-1 == evhttp_uri_set_port(uri,-3));
+       tt_want(-1 == evhttp_uri_set_path(uri,"hello?world"));
+       tt_want(-1 == evhttp_uri_set_query(uri,"hello#world"));
+       tt_want(-1 == evhttp_uri_set_fragment(uri,"hello#world"));
+       /* Valid URI usage: setting valid values */
+       tt_want(0 == evhttp_uri_set_scheme(uri,"http"));
+       tt_want(0 == evhttp_uri_set_scheme(uri,NULL));
+       tt_want(0 == evhttp_uri_set_userinfo(uri,"username:pass"));
+       tt_want(0 == evhttp_uri_set_userinfo(uri,NULL));
+       tt_want(0 == evhttp_uri_set_host(uri,"www.example.com"));
+       tt_want(0 == evhttp_uri_set_host(uri,"1.2.3.4"));
+       tt_want(0 == evhttp_uri_set_host(uri,"[1:2:3:4::]"));
+       tt_want(0 == evhttp_uri_set_host(uri,"[v7.wobblewobble]"));
+       tt_want(0 == evhttp_uri_set_host(uri,NULL));
+       tt_want(0 == evhttp_uri_set_host(uri,""));
+       tt_want(0 == evhttp_uri_set_port(uri, -1));
+       tt_want(0 == evhttp_uri_set_port(uri, 80));
+       tt_want(0 == evhttp_uri_set_port(uri, 65535));
+       tt_want(0 == evhttp_uri_set_path(uri, ""));
+       tt_want(0 == evhttp_uri_set_path(uri, "/documents/public/index.html"));
+       tt_want(0 == evhttp_uri_set_path(uri, NULL));
+       tt_want(0 == evhttp_uri_set_query(uri, "key=val&key2=val2"));
+       tt_want(0 == evhttp_uri_set_query(uri, "keyvalblarg"));
+       tt_want(0 == evhttp_uri_set_query(uri, ""));
+       tt_want(0 == evhttp_uri_set_query(uri, NULL));
+       tt_want(0 == evhttp_uri_set_fragment(uri, ""));
+       tt_want(0 == evhttp_uri_set_fragment(uri, "here?i?am"));
+       tt_want(0 == evhttp_uri_set_fragment(uri, NULL));
+       evhttp_uri_free(uri);
+
+       /* Valid parsing */
+       uri = URI_PARSE("http://www.test.com/?q=t%33est");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=t%33est") == 0);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("http://www.test.com/?q=t%33est");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("http://%77ww.test.com");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "%77ww.test.com") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("http://%77ww.test.com");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("http://www.test.com?q=test");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("http://www.test.com?q=test");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("http://www.test.com#fragment");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want_str_op(evhttp_uri_get_fragment(uri), ==, "fragment");
+       TT_URI("http://www.test.com#fragment");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("http://8000/");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "8000") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("http://8000/");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("http://:8000/");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == 8000);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("http://:8000/");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("http://www.test.com:/"); /* empty port */
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+       tt_want_str_op(evhttp_uri_get_path(uri), ==, "/");
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("http://www.test.com/");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("http://www.test.com:"); /* empty port 2 */
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("http://www.test.com");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("ftp://www.test.com/?q=test");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "ftp") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("ftp://www.test.com/?q=test");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("ftp://[::1]:999/?q=test");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "ftp") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "[::1]") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == 999);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("ftp://[::1]:999/?q=test");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("ftp://[ff00::127.0.0.1]/?q=test");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "ftp") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "[ff00::127.0.0.1]") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("ftp://[ff00::127.0.0.1]/?q=test");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("ftp://[v99.not_(any:time)_soon]/?q=test");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "ftp") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "[v99.not_(any:time)_soon]") == 0);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("ftp://[v99.not_(any:time)_soon]/?q=test");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("scheme://user:pass@foo.com:42/?q=test&s=some+thing#fragment");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "scheme") == 0);
+       tt_want(strcmp(evhttp_uri_get_userinfo(uri), "user:pass") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "foo.com") == 0);
+       tt_want(evhttp_uri_get_port(uri) == 42);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=test&s=some+thing") == 0);
+       tt_want(strcmp(evhttp_uri_get_fragment(uri), "fragment") == 0);
+       TT_URI("scheme://user:pass@foo.com:42/?q=test&s=some+thing#fragment");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("scheme://user@foo.com/#fragment");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "scheme") == 0);
+       tt_want(strcmp(evhttp_uri_get_userinfo(uri), "user") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "foo.com") == 0);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(strcmp(evhttp_uri_get_fragment(uri), "fragment") == 0);
+       TT_URI("scheme://user@foo.com/#fragment");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("scheme://%75ser@foo.com/#frag@ment");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "scheme") == 0);
+       tt_want(strcmp(evhttp_uri_get_userinfo(uri), "%75ser") == 0);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "foo.com") == 0);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(strcmp(evhttp_uri_get_fragment(uri), "frag@ment") == 0);
+       TT_URI("scheme://%75ser@foo.com/#frag@ment");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("file:///some/path/to/the/file");
+       tt_want(strcmp(evhttp_uri_get_scheme(uri), "file") == 0);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "") == 0);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/some/path/to/the/file") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("file:///some/path/to/the/file");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("///some/path/to/the-file");
+       tt_want(uri != NULL);
+       tt_want(evhttp_uri_get_scheme(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(strcmp(evhttp_uri_get_host(uri), "") == 0);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/some/path/to/the-file") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("///some/path/to/the-file");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("/s:ome/path/to/the-file?q=99#fred");
+       tt_want(uri != NULL);
+       tt_want(evhttp_uri_get_scheme(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_host(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "/s:ome/path/to/the-file") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=99") == 0);
+       tt_want(strcmp(evhttp_uri_get_fragment(uri), "fred") == 0);
+       TT_URI("/s:ome/path/to/the-file?q=99#fred");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("relative/path/with/co:lon");
+       tt_want(uri != NULL);
+       tt_want(evhttp_uri_get_scheme(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_host(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "relative/path/with/co:lon") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(evhttp_uri_get_fragment(uri) == NULL);
+       TT_URI("relative/path/with/co:lon");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("bob?q=99&q2=q?33#fr?ed");
+       tt_want(uri != NULL);
+       tt_want(evhttp_uri_get_scheme(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_host(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "bob") == 0);
+       tt_want(strcmp(evhttp_uri_get_query(uri), "q=99&q2=q?33") == 0);
+       tt_want(strcmp(evhttp_uri_get_fragment(uri), "fr?ed") == 0);
+       TT_URI("bob?q=99&q2=q?33#fr?ed");
+       evhttp_uri_free(uri);
+
+       uri = URI_PARSE("#fr?ed");
+       tt_want(uri != NULL);
+       tt_want(evhttp_uri_get_scheme(uri) == NULL);
+       tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+       tt_want(evhttp_uri_get_host(uri) == NULL);
+       tt_want(evhttp_uri_get_port(uri) == -1);
+       tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+       tt_want(evhttp_uri_get_query(uri) == NULL);
+       tt_want(strcmp(evhttp_uri_get_fragment(uri), "fr?ed") == 0);
+       TT_URI("#fr?ed");
+       evhttp_uri_free(uri);
+#undef URI_PARSE
+#undef TT_URI
+#undef BAD
+}
+
+static void
+http_uriencode_test(void *ptr)
+{
+       char *s=NULL, *s2=NULL;
+       size_t sz;
+
+#define ENC(from,want,plus) do {                               \
+               s = evhttp_uriencode((from), -1, (plus));       \
+               tt_assert(s);                                   \
+               tt_str_op(s,==,(want));                         \
+               sz = -1;                                        \
+               s2 = evhttp_uridecode((s), (plus), &sz);        \
+               tt_assert(s2);                                  \
+               tt_str_op(s2,==,(from));                        \
+               tt_int_op(sz,==,strlen(from));                  \
+               free(s);                                        \
+               free(s2);                                       \
+               s = s2 = NULL;                                  \
+       } while (0)
+
+#define DEC(from,want,dp) do {                                 \
+               s = evhttp_uridecode((from),(dp),&sz);          \
+               tt_assert(s);                                   \
+               tt_str_op(s,==,(want));                         \
+               tt_int_op(sz,==,strlen(want));                  \
+               free(s);                                        \
+               s = NULL;                                       \
+       } while (0)
+
+#define OLD_DEC(from,want)  do {                               \
+               s = evhttp_decode_uri((from));                  \
+               tt_assert(s);                                   \
+               tt_str_op(s,==,(want));                         \
+               free(s);                                        \
+               s = NULL;                                       \
+       } while (0)
+
+
+       ENC("Hello", "Hello",0);
+       ENC("99", "99",0);
+       ENC("", "",0);
+       ENC(
+        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789-.~_",
+        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789-.~_",0);
+       ENC(" ", "%20",0);
+       ENC(" ", "+",1);
+       ENC("\xff\xf0\xe0", "%FF%F0%E0",0);
+       ENC("\x01\x19", "%01%19",1);
+       ENC("http://www.ietf.org/rfc/rfc3986.txt",
+           "http%3A%2F%2Fwww.ietf.org%2Frfc%2Frfc3986.txt",1);
+
+       ENC("1+2=3", "1%2B2%3D3",1);
+       ENC("1+2=3", "1%2B2%3D3",0);
+
+       /* Now try encoding with internal NULs. */
+       s = evhttp_uriencode("hello\0world", 11, 0);
+       tt_assert(s);
+       tt_str_op(s,==,"hello%00world");
+       free(s);
+       s = NULL;
+
+       /* Now try out some decoding cases that we don't generate with
+        * encode_uri: Make sure that malformed stuff doesn't crash... */
+       DEC("%%xhello th+ere \xff",
+           "%%xhello th+ere \xff", 0);
+       /* Make sure plus decoding works */
+       DEC("plus+should%20work+", "plus should work ",1);
+       /* Try some lowercase hex */
+       DEC("%f0%a0%b0", "\xf0\xa0\xb0",1);
+
+       /* Try an internal NUL. */
+       sz = 0;
+       s = evhttp_uridecode("%00%00x%00%00", 1, &sz);
+       tt_int_op(sz,==,5);
+       tt_assert(!memcmp(s, "\0\0x\0\0", 5));
+       free(s);
+       s = NULL;
+
+       /* Try with size == NULL */
+       sz = 0;
+       s = evhttp_uridecode("%00%00x%00%00", 1, NULL);
+       tt_assert(!memcmp(s, "\0\0x\0\0", 5));
+       free(s);
+       s = NULL;
+
+       /* Test out the crazy old behavior of the deprecated
+        * evhttp_decode_uri */
+       OLD_DEC("http://example.com/normal+path/?key=val+with+spaces",
+               "http://example.com/normal+path/?key=val with spaces");
+
+end:
+       if (s)
+               free(s);
+       if (s2)
+               free(s2);
+#undef ENC
+#undef DEC
+#undef OLD_DEC
+}
+
+static void
+http_base_test(void *ptr)
+{
+       struct event_base *base = NULL;
+       struct bufferevent *bev;
+       evutil_socket_t fd;
+       const char *http_request;
+       ev_uint16_t port = 0;
+
+       test_ok = 0;
+       base = event_base_new();
+       http = http_setup(&port, base);
+
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(base, fd, 0);
+       bufferevent_setcb(bev, http_readcb, http_writecb,
+           http_errorcb, base);
+       bufferevent_base_set(base, bev);
+
+       http_request =
+           "GET /test HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       event_base_dispatch(base);
+
+       bufferevent_free(bev);
+       evutil_closesocket(fd);
+
+       evhttp_free(http);
+
+       tt_int_op(test_ok, ==, 2);
+
+end:
+       if (base)
+               event_base_free(base);
+}
+
+/*
+ * the server is just going to close the connection if it times out during
+ * reading the headers.
+ */
+
+static void
+http_incomplete_readcb(struct bufferevent *bev, void *arg)
+{
+       test_ok = -1;
+       event_base_loopexit(exit_base,NULL);
+}
+
+static void
+http_incomplete_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+       if (what == (BEV_EVENT_READING|BEV_EVENT_EOF))
+               test_ok++;
+       else
+               test_ok = -2;
+       event_base_loopexit(exit_base,NULL);
+}
+
+static void
+http_incomplete_writecb(struct bufferevent *bev, void *arg)
+{
+       if (arg != NULL) {
+               evutil_socket_t fd = *(evutil_socket_t *)arg;
+               /* terminate the write side to simulate EOF */
+               shutdown(fd, SHUT_WR);
+       }
+       if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+               /* enable reading of the reply */
+               bufferevent_enable(bev, EV_READ);
+               test_ok++;
+       }
+}
+
+static void
+_http_incomplete_test(struct basic_test_data *data, int use_timeout)
+{
+       struct bufferevent *bev;
+       evutil_socket_t fd;
+       const char *http_request;
+       ev_uint16_t port = 0;
+       struct timeval tv_start, tv_end;
+
+       exit_base = data->base;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+       evhttp_set_timeout(http, 1);
+
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev,
+           http_incomplete_readcb, http_incomplete_writecb,
+           http_incomplete_errorcb, use_timeout ? NULL : &fd);
+
+       http_request =
+           "GET /test HTTP/1.1\r\n"
+           "Host: somehost\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       evutil_gettimeofday(&tv_start, NULL);
+
+       event_base_dispatch(data->base);
+
+       evutil_gettimeofday(&tv_end, NULL);
+       evutil_timersub(&tv_end, &tv_start, &tv_end);
+
+       bufferevent_free(bev);
+       if (use_timeout) {
+               evutil_closesocket(fd);
+       }
+
+       evhttp_free(http);
+
+       if (use_timeout && tv_end.tv_sec >= 3) {
+               tt_abort_msg("time");
+       } else if (!use_timeout && tv_end.tv_sec >= 1) {
+               /* we should be done immediately */
+               tt_abort_msg("time");
+       }
+
+       tt_int_op(test_ok, ==, 2);
+ end:
+       ;
+}
+static void
+http_incomplete_test(void *arg)
+{
+       _http_incomplete_test(arg, 0);
+}
+static void
+http_incomplete_timeout_test(void *arg)
+{
+       _http_incomplete_test(arg, 1);
+}
+
+/*
+ * the server is going to reply with chunked data.
+ */
+
+static void
+http_chunked_readcb(struct bufferevent *bev, void *arg)
+{
+       /* nothing here */
+}
+
+static void
+http_chunked_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+       if (!test_ok)
+               goto out;
+
+       test_ok = -1;
+
+       if ((what & BEV_EVENT_EOF) != 0) {
+               struct evhttp_request *req = evhttp_request_new(NULL, NULL);
+               const char *header;
+               enum message_read_status done;
+
+               /* req->kind = EVHTTP_RESPONSE; */
+               done = evhttp_parse_firstline(req, bufferevent_get_input(bev));
+               if (done != ALL_DATA_READ)
+                       goto out;
+
+               done = evhttp_parse_headers(req, bufferevent_get_input(bev));
+               if (done != ALL_DATA_READ)
+                       goto out;
+
+               header = evhttp_find_header(evhttp_request_get_input_headers(req), "Transfer-Encoding");
+               if (header == NULL || strcmp(header, "chunked"))
+                       goto out;
+
+               header = evhttp_find_header(evhttp_request_get_input_headers(req), "Connection");
+               if (header == NULL || strcmp(header, "close"))
+                       goto out;
+
+               header = evbuffer_readln(bufferevent_get_input(bev), NULL, EVBUFFER_EOL_CRLF);
+               if (header == NULL)
+                       goto out;
+               /* 13 chars */
+               if (strcmp(header, "d"))
+                       goto out;
+               free((char*)header);
+
+               if (strncmp((char *)evbuffer_pullup(bufferevent_get_input(bev), 13),
+                       "This is funny", 13))
+                       goto out;
+
+               evbuffer_drain(bufferevent_get_input(bev), 13 + 2);
+
+               header = evbuffer_readln(bufferevent_get_input(bev), NULL, EVBUFFER_EOL_CRLF);
+               if (header == NULL)
+                       goto out;
+               /* 18 chars */
+               if (strcmp(header, "12"))
+                       goto out;
+               free((char *)header);
+
+               if (strncmp((char *)evbuffer_pullup(bufferevent_get_input(bev), 18),
+                       "but not hilarious.", 18))
+                       goto out;
+
+               evbuffer_drain(bufferevent_get_input(bev), 18 + 2);
+
+               header = evbuffer_readln(bufferevent_get_input(bev), NULL, EVBUFFER_EOL_CRLF);
+               if (header == NULL)
+                       goto out;
+               /* 8 chars */
+               if (strcmp(header, "8"))
+                       goto out;
+               free((char *)header);
+
+               if (strncmp((char *)evbuffer_pullup(bufferevent_get_input(bev), 8),
+                       "bwv 1052.", 8))
+                       goto out;
+
+               evbuffer_drain(bufferevent_get_input(bev), 8 + 2);
+
+               header = evbuffer_readln(bufferevent_get_input(bev), NULL, EVBUFFER_EOL_CRLF);
+               if (header == NULL)
+                       goto out;
+               /* 0 chars */
+               if (strcmp(header, "0"))
+                       goto out;
+               free((char *)header);
+
+               test_ok = 2;
+
+               evhttp_request_free(req);
+       }
+
+out:
+       event_base_loopexit(arg, NULL);
+}
+
+static void
+http_chunked_writecb(struct bufferevent *bev, void *arg)
+{
+       if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+               /* enable reading of the reply */
+               bufferevent_enable(bev, EV_READ);
+               test_ok++;
+       }
+}
+
+static void
+http_chunked_request_done(struct evhttp_request *req, void *arg)
+{
+       if (evhttp_request_get_response_code(req) != HTTP_OK) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (evhttp_find_header(evhttp_request_get_input_headers(req),
+               "Transfer-Encoding") == NULL) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != 13 + 18 + 8) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       if (strncmp((char *)evbuffer_pullup(evhttp_request_get_input_buffer(req), 13 + 18 + 8),
+               "This is funnybut not hilarious.bwv 1052",
+               13 + 18 + 8)) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       event_base_loopexit(arg, NULL);
+}
+
+static void
+http_chunk_out_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct bufferevent *bev;
+       evutil_socket_t fd;
+       const char *http_request;
+       ev_uint16_t port = 0;
+       struct timeval tv_start, tv_end;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+       int i;
+
+       exit_base = data->base;
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev,
+           http_chunked_readcb, http_chunked_writecb,
+           http_chunked_errorcb, data->base);
+
+       http_request =
+           "GET /chunked HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+
+       evutil_gettimeofday(&tv_start, NULL);
+
+       event_base_dispatch(data->base);
+
+       bufferevent_free(bev);
+
+       evutil_gettimeofday(&tv_end, NULL);
+       evutil_timersub(&tv_end, &tv_start, &tv_end);
+
+       tt_int_op(tv_end.tv_sec, <, 1);
+
+       tt_int_op(test_ok, ==, 2);
+
+       /* now try again with the regular connection object */
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /* make two requests to check the keepalive behavior */
+       for (i = 0; i < 2; i++) {
+               test_ok = 0;
+               req = evhttp_request_new(http_chunked_request_done,data->base);
+
+               /* Add the information that we care about */
+               evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+               /* We give ownership of the request to the connection */
+               if (evhttp_make_request(evcon, req,
+                       EVHTTP_REQ_GET, "/chunked") == -1) {
+                       tt_abort_msg("Couldn't make request");
+               }
+
+               event_base_dispatch(data->base);
+
+               tt_assert(test_ok == 1);
+       }
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+http_stream_out_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       test_ok = 0;
+       exit_base = data->base;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /*
+        * At this point, we want to schedule a request to the HTTP
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_request_done,
+           (void *)"This is funnybut not hilarious.bwv 1052");
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/streamed")
+           == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+http_stream_in_chunk(struct evhttp_request *req, void *arg)
+{
+       struct evbuffer *reply = arg;
+
+       if (evhttp_request_get_response_code(req) != HTTP_OK) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       evbuffer_add_buffer(reply, evhttp_request_get_input_buffer(req));
+}
+
+static void
+http_stream_in_done(struct evhttp_request *req, void *arg)
+{
+       if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != 0) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       event_base_loopexit(exit_base, NULL);
+}
+
+/**
+ * Makes a request and reads the response in chunks.
+ */
+static void
+_http_stream_in_test(struct basic_test_data *data, char const *url,
+    size_t expected_len, char const *expected)
+{
+       struct evhttp_connection *evcon;
+       struct evbuffer *reply = evbuffer_new();
+       struct evhttp_request *req = NULL;
+       ev_uint16_t port = 0;
+
+       exit_base = data->base;
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL,"127.0.0.1", port);
+       tt_assert(evcon);
+
+       req = evhttp_request_new(http_stream_in_done, reply);
+       evhttp_request_set_chunked_cb(req, http_stream_in_chunk);
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, url) == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       if (evbuffer_get_length(reply) != expected_len) {
+               TT_DIE(("reply length %lu; expected %lu; FAILED (%s)\n",
+                               (unsigned long)evbuffer_get_length(reply),
+                               (unsigned long)expected_len,
+                               (char*)evbuffer_pullup(reply, -1)));
+       }
+
+       if (memcmp(evbuffer_pullup(reply, -1), expected, expected_len) != 0) {
+               tt_abort_msg("Memory mismatch");
+       }
+
+       test_ok = 1;
+ end:
+       if (reply)
+               evbuffer_free(reply);
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+http_stream_in_test(void *arg)
+{
+       _http_stream_in_test(arg, "/chunked", 13 + 18 + 8,
+           "This is funnybut not hilarious.bwv 1052");
+
+       _http_stream_in_test(arg, "/test", strlen(BASIC_REQUEST_BODY),
+           BASIC_REQUEST_BODY);
+}
+
+static void
+http_stream_in_cancel_chunk(struct evhttp_request *req, void *arg)
+{
+       tt_int_op(evhttp_request_get_response_code(req), ==, HTTP_OK);
+
+ end:
+       evhttp_cancel_request(req);
+       event_base_loopexit(arg, NULL);
+}
+
+static void
+http_stream_in_cancel_done(struct evhttp_request *req, void *arg)
+{
+       /* should never be called */
+       tt_fail_msg("In cancel done");
+}
+
+static void
+http_stream_in_cancel_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct evhttp_connection *evcon;
+       struct evhttp_request *req = NULL;
+       ev_uint16_t port = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       req = evhttp_request_new(http_stream_in_cancel_done, data->base);
+       evhttp_request_set_chunked_cb(req, http_stream_in_cancel_chunk);
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/chunked") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       test_ok = 1;
+ end:
+       evhttp_connection_free(evcon);
+       evhttp_free(http);
+
+}
+
+static void
+http_connection_fail_done(struct evhttp_request *req, void *arg)
+{
+       /* An ENETUNREACH error results in an unrecoverable
+        * evhttp_connection error (see evhttp_connection_fail()).  The
+        * connection will be reset, and the user will be notified with a NULL
+        * req parameter. */
+       tt_assert(!req);
+
+       test_ok = 1;
+
+ end:
+       event_base_loopexit(arg, NULL);
+}
+
+/* Test unrecoverable evhttp_connection errors by generating an ENETUNREACH
+ * error on connection. */
+static void
+http_connection_fail_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       exit_base = data->base;
+       test_ok = 0;
+
+       /* auto detect a port */
+       http = http_setup(&port, data->base);
+       evhttp_free(http);
+       http = NULL;
+
+       /* Pick an unroutable address.  This administratively scoped multicast
+       * address should do when working with TCP. */
+       evcon = evhttp_connection_base_new(data->base, NULL, "239.10.20.30", 80);
+       tt_assert(evcon);
+
+       /*
+        * At this point, we want to schedule an HTTP GET request
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_connection_fail_done, data->base);
+       tt_assert(req);
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(test_ok, ==, 1);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+}
+
+static void
+http_connection_retry_done(struct evhttp_request *req, void *arg)
+{
+       tt_assert(req);
+       tt_int_op(evhttp_request_get_response_code(req), !=, HTTP_OK);
+       if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") != NULL) {
+               tt_abort_msg("(content type)\n");
+       }
+
+       tt_uint_op(evbuffer_get_length(evhttp_request_get_input_buffer(req)), ==, 0);
+
+       test_ok = 1;
+ end:
+       event_base_loopexit(arg,NULL);
+}
+
+static struct event_base *http_make_web_server_base=NULL;
+static void
+http_make_web_server(evutil_socket_t fd, short what, void *arg)
+{
+       ev_uint16_t port = *(ev_uint16_t*)arg;
+       http = http_setup(&port, http_make_web_server_base);
+}
+
+static void
+http_connection_retry_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+       struct timeval tv, tv_start, tv_end;
+
+       exit_base = data->base;
+       test_ok = 0;
+
+       /* auto detect a port */
+       http = http_setup(&port, data->base);
+       evhttp_free(http);
+       http = NULL;
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       evhttp_connection_set_timeout(evcon, 1);
+       /* also bind to local host */
+       evhttp_connection_set_local_address(evcon, "127.0.0.1");
+
+       /*
+        * At this point, we want to schedule an HTTP GET request
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_connection_retry_done, data->base);
+       tt_assert(req);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+               "/?arg=val") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       evutil_gettimeofday(&tv_start, NULL);
+       event_base_dispatch(data->base);
+       evutil_gettimeofday(&tv_end, NULL);
+       evutil_timersub(&tv_end, &tv_start, &tv_end);
+       tt_int_op(tv_end.tv_sec, <, 1);
+
+       tt_int_op(test_ok, ==, 1);
+
+       /*
+        * now test the same but with retries
+        */
+       test_ok = 0;
+
+       evhttp_connection_set_timeout(evcon, 1);
+       evhttp_connection_set_retries(evcon, 1);
+
+       req = evhttp_request_new(http_connection_retry_done, data->base);
+       tt_assert(req);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+               "/?arg=val") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       evutil_gettimeofday(&tv_start, NULL);
+       event_base_dispatch(data->base);
+       evutil_gettimeofday(&tv_end, NULL);
+       evutil_timersub(&tv_end, &tv_start, &tv_end);
+       tt_int_op(tv_end.tv_sec, >, 1);
+       tt_int_op(tv_end.tv_sec, <, 6);
+
+       tt_assert(test_ok == 1);
+
+       /*
+        * now test the same but with retries and give it a web server
+        * at the end
+        */
+       test_ok = 0;
+
+       evhttp_connection_set_timeout(evcon, 1);
+       evhttp_connection_set_retries(evcon, 3);
+
+       req = evhttp_request_new(http_dispatcher_test_done, data->base);
+       tt_assert(req);
+
+       /* Add the information that we care about */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+               "/?arg=val") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       /* start up a web server one second after the connection tried
+        * to send a request
+        */
+       evutil_timerclear(&tv);
+       tv.tv_sec = 1;
+       http_make_web_server_base = data->base;
+       event_base_once(data->base, -1, EV_TIMEOUT, http_make_web_server, &port, &tv);
+
+       evutil_gettimeofday(&tv_start, NULL);
+       event_base_dispatch(data->base);
+       evutil_gettimeofday(&tv_end, NULL);
+
+       evutil_timersub(&tv_end, &tv_start, &tv_end);
+
+       tt_int_op(tv_end.tv_sec, >, 1);
+       tt_int_op(tv_end.tv_sec, <, 6);
+
+       tt_int_op(test_ok, ==, 1);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+http_primitives(void *ptr)
+{
+       char *escaped = NULL;
+       struct evhttp *http;
+
+       escaped = evhttp_htmlescape("<script>");
+       tt_str_op(escaped, ==, "&lt;script&gt;");
+       free(escaped);
+
+       escaped = evhttp_htmlescape("\"\'&");
+       tt_str_op(escaped, ==, "&quot;&#039;&amp;");
+
+       http = evhttp_new(NULL);
+       tt_int_op(evhttp_set_cb(http, "/test", http_basic_cb, NULL), ==, 0);
+       tt_int_op(evhttp_set_cb(http, "/test", http_basic_cb, NULL), ==, -1);
+       tt_int_op(evhttp_del_cb(http, "/test"), ==, 0);
+       tt_int_op(evhttp_del_cb(http, "/test"), ==, -1);
+       tt_int_op(evhttp_set_cb(http, "/test", http_basic_cb, NULL), ==, 0);
+       evhttp_free(http);
+
+ end:
+       if (escaped)
+               free(escaped);
+}
+
+static void
+http_multi_line_header_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct bufferevent *bev= NULL;
+       evutil_socket_t fd = -1;
+       const char *http_start_request;
+       ev_uint16_t port = 0;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, http_readcb, http_writecb,
+           http_errorcb, data->base);
+
+       http_start_request =
+           "GET /test HTTP/1.1\r\n"
+           "Host: somehost\r\n"
+           "Connection: close\r\n"
+           "X-Multi:  aaaaaaaa\r\n"
+           " a\r\n"
+           "\tEND\r\n"
+           "X-Last: last\r\n"
+           "\r\n";
+
+       bufferevent_write(bev, http_start_request, strlen(http_start_request));
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(test_ok, ==, 4);
+ end:
+       if (bev)
+               bufferevent_free(bev);
+       if (fd >= 0)
+               evutil_closesocket(fd);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+http_request_bad(struct evhttp_request *req, void *arg)
+{
+       if (req != NULL) {
+               fprintf(stderr, "FAILED\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       event_base_loopexit(arg, NULL);
+}
+
+static void
+http_negative_content_length_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /*
+        * At this point, we want to schedule a request to the HTTP
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_request_bad, data->base);
+
+       /* Cause the response to have a negative content-length */
+       evhttp_add_header(evhttp_request_get_output_headers(req), "X-Negative", "makeitso");
+
+       /* We give ownership of the request to the connection */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+
+       event_base_dispatch(data->base);
+
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+
+static void
+http_data_length_constraints_test_done(struct evhttp_request *req, void *arg)
+{
+       tt_assert(req);
+       tt_int_op(evhttp_request_get_response_code(req), ==, HTTP_BADREQUEST);
+end:
+       event_base_loopexit(arg, NULL);
+}
+
+static void
+http_large_entity_test_done(struct evhttp_request *req, void *arg)
+{
+       tt_assert(req);
+       tt_int_op(evhttp_request_get_response_code(req), ==, HTTP_ENTITYTOOLARGE);
+end:
+       event_base_loopexit(arg, NULL);
+}
+
+static void
+http_data_length_constraints_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       ev_uint16_t port = 0;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+       char long_str[8192];
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+
+       evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+       tt_assert(evcon);
+
+       /* also bind to local host */
+       evhttp_connection_set_local_address(evcon, "127.0.0.1");
+
+       /*
+        * At this point, we want to schedule an HTTP GET request
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(http_data_length_constraints_test_done, data->base);
+       tt_assert(req);
+
+       memset(long_str, 'a', 8192);
+       long_str[8191] = '\0';
+       /* Add the information that we care about */
+       evhttp_set_max_headers_size(http, 8191);
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Longheader", long_str);
+
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/?arg=val") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+       event_base_dispatch(data->base);
+
+       req = evhttp_request_new(http_data_length_constraints_test_done, data->base);
+       tt_assert(req);
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+       /* GET /?arg=verylongvalue HTTP/1.1 */
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, long_str) == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+       event_base_dispatch(data->base);
+
+       evhttp_set_max_body_size(http, 8190);
+       req = evhttp_request_new(http_data_length_constraints_test_done, data->base);
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+       evbuffer_add_printf(evhttp_request_get_output_buffer(req), "%s", long_str);
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+       event_base_dispatch(data->base);
+
+       req = evhttp_request_new(http_large_entity_test_done, data->base);
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+       evhttp_add_header(evhttp_request_get_output_headers(req), "Expect", "100-continue");
+       evbuffer_add_printf(evhttp_request_get_output_buffer(req), "%s", long_str);
+       if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/") == -1) {
+               tt_abort_msg("Couldn't make request");
+       }
+       event_base_dispatch(data->base);
+
+       test_ok = 1;
+ end:
+       if (evcon)
+               evhttp_connection_free(evcon);
+       if (http)
+               evhttp_free(http);
+}
+
+/*
+ * Testing client reset of server chunked connections
+ */
+
+struct terminate_state {
+       struct event_base *base;
+       struct evhttp_request *req;
+       struct bufferevent *bev;
+       evutil_socket_t fd;
+       int gotclosecb: 1;
+};
+
+static void
+terminate_chunked_trickle_cb(evutil_socket_t fd, short events, void *arg)
+{
+       struct terminate_state *state = arg;
+       struct evbuffer *evb;
+       struct timeval tv;
+
+       if (evhttp_request_get_connection(state->req) == NULL) {
+               test_ok = 1;
+               evhttp_request_free(state->req);
+               event_base_loopexit(state->base,NULL);
+               return;
+       }
+
+       evb = evbuffer_new();
+       evbuffer_add_printf(evb, "%p", evb);
+       evhttp_send_reply_chunk(state->req, evb);
+       evbuffer_free(evb);
+
+       tv.tv_sec = 0;
+       tv.tv_usec = 3000;
+       EVUTIL_ASSERT(state);
+       EVUTIL_ASSERT(state->base);
+       event_base_once(state->base, -1, EV_TIMEOUT, terminate_chunked_trickle_cb, arg, &tv);
+}
+
+static void
+terminate_chunked_close_cb(struct evhttp_connection *evcon, void *arg)
+{
+       struct terminate_state *state = arg;
+       state->gotclosecb = 1;
+}
+
+static void
+terminate_chunked_cb(struct evhttp_request *req, void *arg)
+{
+       struct terminate_state *state = arg;
+       struct timeval tv;
+
+       /* we want to know if this connection closes on us */
+       evhttp_connection_set_closecb(
+               evhttp_request_get_connection(req),
+               terminate_chunked_close_cb, arg);
+
+       state->req = req;
+
+       evhttp_send_reply_start(req, HTTP_OK, "OK");
+
+       tv.tv_sec = 0;
+       tv.tv_usec = 3000;
+       event_base_once(state->base, -1, EV_TIMEOUT, terminate_chunked_trickle_cb, arg, &tv);
+}
+
+static void
+terminate_chunked_client(evutil_socket_t fd, short event, void *arg)
+{
+       struct terminate_state *state = arg;
+       bufferevent_free(state->bev);
+       evutil_closesocket(state->fd);
+}
+
+static void
+terminate_readcb(struct bufferevent *bev, void *arg)
+{
+       /* just drop the data */
+       evbuffer_drain(bufferevent_get_input(bev), -1);
+}
+
+
+static void
+http_terminate_chunked_test(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct bufferevent *bev = NULL;
+       struct timeval tv;
+       const char *http_request;
+       ev_uint16_t port = 0;
+       evutil_socket_t fd = -1;
+       struct terminate_state terminate_state;
+
+       test_ok = 0;
+
+       http = http_setup(&port, data->base);
+       evhttp_del_cb(http, "/test");
+       tt_assert(evhttp_set_cb(http, "/test",
+               terminate_chunked_cb, &terminate_state) == 0);
+
+       fd = http_connect("127.0.0.1", port);
+
+       /* Stupid thing to send a request */
+       bev = bufferevent_socket_new(data->base, fd, 0);
+       bufferevent_setcb(bev, terminate_readcb, http_writecb,
+           http_errorcb, data->base);
+
+       memset(&terminate_state, 0, sizeof(terminate_state));
+       terminate_state.base = data->base;
+       terminate_state.fd = fd;
+       terminate_state.bev = bev;
+       terminate_state.gotclosecb = 0;
+
+       /* first half of the http request */
+       http_request =
+           "GET /test HTTP/1.1\r\n"
+           "Host: some\r\n\r\n";
+
+       bufferevent_write(bev, http_request, strlen(http_request));
+       evutil_timerclear(&tv);
+       tv.tv_usec = 10000;
+       event_base_once(data->base, -1, EV_TIMEOUT, terminate_chunked_client, &terminate_state,
+           &tv);
+
+       event_base_dispatch(data->base);
+
+       if (terminate_state.gotclosecb == 0)
+               test_ok = 0;
+
+ end:
+       if (fd >= 0)
+               evutil_closesocket(fd);
+       if (http)
+               evhttp_free(http);
+}
+
+#define HTTP_LEGACY(name)                                              \
+       { #name, run_legacy_test_fn, TT_ISOLATED|TT_LEGACY, &legacy_setup, \
+                   http_##name##_test }
+
+#define HTTP(name) \
+       { #name, http_##name##_test, TT_ISOLATED, &basic_setup, NULL }
+
+struct testcase_t http_testcases[] = {
+       { "primitives", http_primitives, 0, NULL, NULL },
+       { "base", http_base_test, TT_FORK, NULL, NULL },
+       { "bad_headers", http_bad_header_test, 0, NULL, NULL },
+       { "parse_query", http_parse_query_test, 0, NULL, NULL },
+       { "parse_uri", http_parse_uri_test, 0, NULL, NULL },
+       { "parse_uri_nc", http_parse_uri_test, 0, &basic_setup, (void*)"nc" },
+       { "uriencode", http_uriencode_test, 0, NULL, NULL },
+       HTTP(basic),
+       HTTP(cancel),
+       HTTP(virtual_host),
+       HTTP(post),
+       HTTP(put),
+       HTTP(delete),
+       HTTP(allowed_methods),
+       HTTP(failure),
+       HTTP(connection),
+       HTTP(persist_connection),
+       HTTP(connection_async),
+       HTTP(close_detection),
+       HTTP(close_detection_delay),
+       HTTP(bad_request),
+       HTTP(incomplete),
+       HTTP(incomplete_timeout),
+       HTTP(terminate_chunked),
+
+       HTTP(highport),
+       HTTP(dispatcher),
+       HTTP(multi_line_header),
+       HTTP(negative_content_length),
+       HTTP(chunk_out),
+       HTTP(stream_out),
+
+       HTTP(stream_in),
+       HTTP(stream_in_cancel),
+
+       HTTP(connection_fail),
+       HTTP(connection_retry),
+       HTTP(data_length_constraints),
+
+       END_OF_TESTCASES
+};
+
diff --git a/libevent/test/regress_iocp.c b/libevent/test/regress_iocp.c
new file mode 100644 (file)
index 0000000..916d322
--- /dev/null
@@ -0,0 +1,352 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <stdlib.h>
+#include <string.h>
+#include "event2/event.h"
+#include "event2/thread.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/bufferevent.h"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+#include "regress.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <winsock2.h>
+#undef WIN32_LEAN_AND_MEAN
+
+#include "iocp-internal.h"
+#include "evbuffer-internal.h"
+#include "evthread-internal.h"
+
+/* FIXME remove these ones */
+#include <sys/queue.h>
+#include "event2/event_struct.h"
+#include "event-internal.h"
+
+#define MAX_CALLS 16
+
+static void *count_lock = NULL, *count_cond = NULL;
+static int count = 0;
+
+static void
+count_init(void)
+{
+       EVTHREAD_ALLOC_LOCK(count_lock, 0);
+       EVTHREAD_ALLOC_COND(count_cond);
+
+       tt_assert(count_lock);
+       tt_assert(count_cond);
+
+end:
+       ;
+}
+
+static void
+count_free(void)
+{
+       EVTHREAD_FREE_LOCK(count_lock, 0);
+       EVTHREAD_FREE_COND(count_cond);
+}
+
+static void
+count_incr(void)
+{
+       EVLOCK_LOCK(count_lock, 0);
+       count++;
+       EVTHREAD_COND_BROADCAST(count_cond);
+       EVLOCK_UNLOCK(count_lock, 0);
+}
+
+static int
+count_wait_for(int i, int ms)
+{
+       struct timeval tv;
+       DWORD elapsed;
+       int rv = -1;
+
+       EVLOCK_LOCK(count_lock, 0);
+       while (ms > 0 && count != i) {
+               tv.tv_sec = 0;
+               tv.tv_usec = ms * 1000;
+               elapsed = GetTickCount();
+               EVTHREAD_COND_WAIT_TIMED(count_cond, count_lock, &tv);
+               elapsed = GetTickCount() - elapsed;
+               ms -= elapsed;
+       }
+       if (count == i)
+               rv = 0;
+       EVLOCK_UNLOCK(count_lock, 0);
+
+       return rv;
+}
+
+struct dummy_overlapped {
+       struct event_overlapped eo;
+       void *lock;
+       int call_count;
+       uintptr_t keys[MAX_CALLS];
+       ev_ssize_t sizes[MAX_CALLS];
+};
+
+static void
+dummy_cb(struct event_overlapped *o, uintptr_t key, ev_ssize_t n, int ok)
+{
+       struct dummy_overlapped *d_o =
+           EVUTIL_UPCAST(o, struct dummy_overlapped, eo);
+
+       EVLOCK_LOCK(d_o->lock, 0);
+       if (d_o->call_count < MAX_CALLS) {
+               d_o->keys[d_o->call_count] = key;
+               d_o->sizes[d_o->call_count] = n;
+       }
+       d_o->call_count++;
+       EVLOCK_UNLOCK(d_o->lock, 0);
+
+       count_incr();
+}
+
+static int
+pair_is_in(struct dummy_overlapped *o, uintptr_t key, ev_ssize_t n)
+{
+       int i;
+       int result = 0;
+       EVLOCK_LOCK(o->lock, 0);
+       for (i=0; i < o->call_count; ++i) {
+               if (o->keys[i] == key && o->sizes[i] == n) {
+                       result = 1;
+                       break;
+               }
+       }
+       EVLOCK_UNLOCK(o->lock, 0);
+       return result;
+}
+
+static void
+test_iocp_port(void *ptr)
+{
+       struct event_iocp_port *port = NULL;
+       struct dummy_overlapped o1, o2;
+
+       memset(&o1, 0, sizeof(o1));
+       memset(&o2, 0, sizeof(o2));
+
+       count_init();
+       EVTHREAD_ALLOC_LOCK(o1.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       EVTHREAD_ALLOC_LOCK(o2.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+
+       tt_assert(o1.lock);
+       tt_assert(o2.lock);
+
+       event_overlapped_init(&o1.eo, dummy_cb);
+       event_overlapped_init(&o2.eo, dummy_cb);
+
+       port = event_iocp_port_launch(0);
+       tt_assert(port);
+
+       tt_assert(!event_iocp_activate_overlapped(port, &o1.eo, 10, 100));
+       tt_assert(!event_iocp_activate_overlapped(port, &o2.eo, 20, 200));
+
+       tt_assert(!event_iocp_activate_overlapped(port, &o1.eo, 11, 101));
+       tt_assert(!event_iocp_activate_overlapped(port, &o2.eo, 21, 201));
+
+       tt_assert(!event_iocp_activate_overlapped(port, &o1.eo, 12, 102));
+       tt_assert(!event_iocp_activate_overlapped(port, &o2.eo, 22, 202));
+
+       tt_assert(!event_iocp_activate_overlapped(port, &o1.eo, 13, 103));
+       tt_assert(!event_iocp_activate_overlapped(port, &o2.eo, 23, 203));
+
+       tt_int_op(count_wait_for(8, 2000), ==, 0);
+
+       tt_want(!event_iocp_shutdown(port, 2000));
+
+       tt_int_op(o1.call_count, ==, 4);
+       tt_int_op(o2.call_count, ==, 4);
+
+       tt_want(pair_is_in(&o1, 10, 100));
+       tt_want(pair_is_in(&o1, 11, 101));
+       tt_want(pair_is_in(&o1, 12, 102));
+       tt_want(pair_is_in(&o1, 13, 103));
+
+       tt_want(pair_is_in(&o2, 20, 200));
+       tt_want(pair_is_in(&o2, 21, 201));
+       tt_want(pair_is_in(&o2, 22, 202));
+       tt_want(pair_is_in(&o2, 23, 203));
+
+end:
+       EVTHREAD_FREE_LOCK(o1.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       EVTHREAD_FREE_LOCK(o2.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       count_free();
+}
+
+static struct evbuffer *rbuf = NULL, *wbuf = NULL;
+
+static void
+read_complete(struct event_overlapped *eo, uintptr_t key,
+    ev_ssize_t nbytes, int ok)
+{
+       tt_assert(ok);
+       evbuffer_commit_read(rbuf, nbytes);
+       count_incr();
+end:
+       ;
+}
+
+static void
+write_complete(struct event_overlapped *eo, uintptr_t key,
+    ev_ssize_t nbytes, int ok)
+{
+       tt_assert(ok);
+       evbuffer_commit_write(wbuf, nbytes);
+       count_incr();
+end:
+       ;
+}
+
+static void
+test_iocp_evbuffer(void *ptr)
+{
+       struct event_overlapped rol, wol;
+       struct basic_test_data *data = ptr;
+       struct event_iocp_port *port = NULL;
+       struct evbuffer *buf=NULL;
+       struct evbuffer_chain *chain;
+       char junk[1024];
+       int i;
+
+       count_init();
+       event_overlapped_init(&rol, read_complete);
+       event_overlapped_init(&wol, write_complete);
+
+       for (i = 0; i < (int)sizeof(junk); ++i)
+               junk[i] = (char)(i);
+
+       rbuf = evbuffer_overlapped_new(data->pair[0]);
+       wbuf = evbuffer_overlapped_new(data->pair[1]);
+       evbuffer_enable_locking(rbuf, NULL);
+       evbuffer_enable_locking(wbuf, NULL);
+
+       port = event_iocp_port_launch(0);
+       tt_assert(port);
+       tt_assert(rbuf);
+       tt_assert(wbuf);
+
+       tt_assert(!event_iocp_port_associate(port, data->pair[0], 100));
+       tt_assert(!event_iocp_port_associate(port, data->pair[1], 100));
+
+       for (i=0;i<10;++i)
+               evbuffer_add(wbuf, junk, sizeof(junk));
+
+       buf = evbuffer_new();
+       tt_assert(buf != NULL);
+       evbuffer_add(rbuf, junk, sizeof(junk));
+       tt_assert(!evbuffer_launch_read(rbuf, 2048, &rol));
+       evbuffer_add_buffer(buf, rbuf);
+       tt_int_op(evbuffer_get_length(buf), ==, sizeof(junk));
+       for (chain = buf->first; chain; chain = chain->next)
+               tt_int_op(chain->flags & EVBUFFER_MEM_PINNED_ANY, ==, 0);
+       tt_assert(!evbuffer_get_length(rbuf));
+       tt_assert(!evbuffer_launch_write(wbuf, 512, &wol));
+
+       tt_int_op(count_wait_for(2, 2000), ==, 0);
+
+       tt_int_op(evbuffer_get_length(rbuf),==,512);
+
+       /* FIXME Actually test some stuff here. */
+
+       tt_want(!event_iocp_shutdown(port, 2000));
+end:
+       count_free();
+       evbuffer_free(rbuf);
+       evbuffer_free(wbuf);
+       if (buf) evbuffer_free(buf);
+}
+
+static int got_readcb = 0;
+
+static void
+async_readcb(struct bufferevent *bev, void *arg)
+{
+       /* Disabling read should cause the loop to quit */
+       bufferevent_disable(bev, EV_READ);
+       got_readcb++;
+}
+
+static void
+test_iocp_bufferevent_async(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event_iocp_port *port = NULL;
+       struct bufferevent *bea1=NULL, *bea2=NULL;
+       char buf[128];
+       size_t n;
+
+       event_base_start_iocp(data->base, 0);
+       port = event_base_get_iocp(data->base);
+       tt_assert(port);
+
+       bea1 = bufferevent_async_new(data->base, data->pair[0],
+           BEV_OPT_DEFER_CALLBACKS);
+       bea2 = bufferevent_async_new(data->base, data->pair[1],
+           BEV_OPT_DEFER_CALLBACKS);
+       tt_assert(bea1);
+       tt_assert(bea2);
+
+       bufferevent_setcb(bea2, async_readcb, NULL, NULL, NULL);
+       bufferevent_enable(bea1, EV_WRITE);
+       bufferevent_enable(bea2, EV_READ);
+
+       bufferevent_write(bea1, "Hello world", strlen("Hello world")+1);
+
+       event_base_dispatch(data->base);
+
+       tt_int_op(got_readcb, ==, 1);
+       n = bufferevent_read(bea2, buf, sizeof(buf)-1);
+       buf[n]='\0';
+       tt_str_op(buf, ==, "Hello world");
+
+end:
+       bufferevent_free(bea1);
+       bufferevent_free(bea2);
+}
+
+
+struct testcase_t iocp_testcases[] = {
+       { "port", test_iocp_port, TT_FORK|TT_NEED_THREADS, &basic_setup, NULL },
+       { "evbuffer", test_iocp_evbuffer,
+         TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_THREADS,
+         &basic_setup, NULL },
+       { "bufferevent_async", test_iocp_bufferevent_async,
+         TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_THREADS|TT_NEED_BASE,
+         &basic_setup, NULL },
+       END_OF_TESTCASES
+};
diff --git a/libevent/test/regress_listener.c b/libevent/test/regress_listener.c
new file mode 100644 (file)
index 0000000..f6c22cb
--- /dev/null
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include <sys/types.h>
+
+#ifndef WIN32
+#include <sys/socket.h>
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+#  include <arpa/inet.h>
+# endif
+#include <unistd.h>
+#endif
+
+#include <string.h>
+
+#include "event2/listener.h"
+#include "event2/event.h"
+#include "event2/util.h"
+
+#include "regress.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+#include "util-internal.h"
+
+static void
+acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
+    struct sockaddr *addr, int socklen, void *arg)
+{
+       int *ptr = arg;
+       --*ptr;
+       TT_BLATHER(("Got one for %p", ptr));
+       evutil_closesocket(fd);
+
+       if (! *ptr)
+               evconnlistener_disable(listener);
+}
+
+static void
+regress_pick_a_port(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       struct evconnlistener *listener1 = NULL, *listener2 = NULL;
+       struct sockaddr_in sin;
+       int count1 = 2, count2 = 1;
+       struct sockaddr_storage ss1, ss2;
+       struct sockaddr_in *sin1, *sin2;
+       ev_socklen_t slen1 = sizeof(ss1), slen2 = sizeof(ss2);
+       unsigned int flags =
+           LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC;
+
+       evutil_socket_t fd1 = -1, fd2 = -1, fd3 = -1;
+
+       if (data->setup_data && strstr((char*)data->setup_data, "ts")) {
+               flags |= LEV_OPT_THREADSAFE;
+       }
+
+       memset(&sin, 0, sizeof(sin));
+       sin.sin_family = AF_INET;
+       sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+       sin.sin_port = 0; /* "You pick!" */
+
+       listener1 = evconnlistener_new_bind(base, acceptcb, &count1,
+           flags, -1, (struct sockaddr *)&sin, sizeof(sin));
+       tt_assert(listener1);
+       listener2 = evconnlistener_new_bind(base, acceptcb, &count2,
+           flags, -1, (struct sockaddr *)&sin, sizeof(sin));
+       tt_assert(listener2);
+
+       tt_int_op(evconnlistener_get_fd(listener1), >=, 0);
+       tt_int_op(evconnlistener_get_fd(listener2), >=, 0);
+       tt_assert(getsockname(evconnlistener_get_fd(listener1),
+               (struct sockaddr*)&ss1, &slen1) == 0);
+       tt_assert(getsockname(evconnlistener_get_fd(listener2),
+               (struct sockaddr*)&ss2, &slen2) == 0);
+       tt_int_op(ss1.ss_family, ==, AF_INET);
+       tt_int_op(ss2.ss_family, ==, AF_INET);
+
+       sin1 = (struct sockaddr_in*)&ss1;
+       sin2 = (struct sockaddr_in*)&ss2;
+       tt_int_op(ntohl(sin1->sin_addr.s_addr), ==, 0x7f000001);
+       tt_int_op(ntohl(sin2->sin_addr.s_addr), ==, 0x7f000001);
+       tt_int_op(sin1->sin_port, !=, sin2->sin_port);
+
+       tt_ptr_op(evconnlistener_get_base(listener1), ==, base);
+       tt_ptr_op(evconnlistener_get_base(listener2), ==, base);
+
+       fd1 = fd2 = fd3 = -1;
+       evutil_socket_connect(&fd1, (struct sockaddr*)&ss1, slen1);
+       evutil_socket_connect(&fd2, (struct sockaddr*)&ss1, slen1);
+       evutil_socket_connect(&fd3, (struct sockaddr*)&ss2, slen2);
+
+#ifdef WIN32
+       Sleep(100); /* XXXX this is a stupid stopgap. */
+#endif
+       event_base_dispatch(base);
+
+       tt_int_op(count1, ==, 0);
+       tt_int_op(count2, ==, 0);
+
+end:
+       if (fd1>=0)
+               EVUTIL_CLOSESOCKET(fd1);
+       if (fd2>=0)
+               EVUTIL_CLOSESOCKET(fd2);
+       if (fd3>=0)
+               EVUTIL_CLOSESOCKET(fd3);
+       if (listener1)
+               evconnlistener_free(listener1);
+       if (listener2)
+               evconnlistener_free(listener2);
+}
+
+static void
+errorcb(struct evconnlistener *lis, void *data_)
+{
+       int *data = data_;
+       *data = 1000;
+       evconnlistener_disable(lis);
+}
+
+static void
+regress_listener_error(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       struct evconnlistener *listener = NULL;
+       int count = 1;
+       unsigned int flags = LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE;
+
+       if (data->setup_data && strstr((char*)data->setup_data, "ts")) {
+               flags |= LEV_OPT_THREADSAFE;
+       }
+
+       /* send, so that pair[0] will look 'readable'*/
+       send(data->pair[1], "hello", 5, 0);
+
+       /* Start a listener with a bogus socket. */
+       listener = evconnlistener_new(base, acceptcb, &count,
+           flags, 0,
+           data->pair[0]);
+       tt_assert(listener);
+
+       evconnlistener_set_error_cb(listener, errorcb);
+
+       tt_assert(listener);
+
+       event_base_dispatch(base);
+       tt_int_op(count,==,1000); /* set by error cb */
+
+end:
+       if (listener)
+               evconnlistener_free(listener);
+}
+
+struct testcase_t listener_testcases[] = {
+
+       { "randport", regress_pick_a_port, TT_FORK|TT_NEED_BASE,
+         &basic_setup, NULL},
+
+       { "randport_ts", regress_pick_a_port, TT_FORK|TT_NEED_BASE,
+         &basic_setup, (char*)"ts"},
+
+       { "error", regress_listener_error,
+         TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR,
+         &basic_setup, NULL},
+
+       { "error_ts", regress_listener_error,
+         TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR,
+         &basic_setup, (char*)"ts"},
+
+       END_OF_TESTCASES,
+};
+
+struct testcase_t listener_iocp_testcases[] = {
+       { "randport", regress_pick_a_port,
+         TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP,
+         &basic_setup, NULL},
+
+       { "error", regress_listener_error,
+         TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR|TT_ENABLE_IOCP,
+         &basic_setup, NULL},
+
+       END_OF_TESTCASES,
+};
diff --git a/libevent/test/regress_main.c b/libevent/test/regress_main.c
new file mode 100644 (file)
index 0000000..42a0366
--- /dev/null
@@ -0,0 +1,395 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <io.h>
+#include <fcntl.h>
+#endif
+
+#include "event2/event-config.h"
+
+#ifdef _EVENT___func__
+#define __func__ _EVENT___func__
+#endif
+
+#if 0
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <signal.h>
+#include <errno.h>
+#endif
+
+#include <sys/types.h>
+
+#ifndef WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/dns.h"
+#include "event2/dns_compat.h"
+#include "event2/thread.h"
+
+#include "event2/event-config.h"
+#include "regress.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+#include "../iocp-internal.h"
+#include "../event-internal.h"
+
+long
+timeval_msec_diff(const struct timeval *start, const struct timeval *end)
+{
+       long ms = end->tv_sec - start->tv_sec;
+       ms *= 1000;
+       ms += ((end->tv_usec - start->tv_usec)+500) / 1000;
+       return ms;
+
+}
+
+/* ============================================================ */
+/* Code to wrap up old legacy test cases that used setup() and cleanup().
+ *
+ * Not all of the tests designated "legacy" are ones that used setup() and
+ * cleanup(), of course.  A test is legacy it it uses setup()/cleanup(), OR
+ * if it wants to find its event base/socketpair in global variables (ugh),
+ * OR if it wants to communicate success/failure through test_ok.
+ */
+
+/* This is set to true if we're inside a legacy test wrapper.  It lets the
+   setup() and cleanup() functions in regress.c know they're not needed.
+ */
+int in_legacy_test_wrapper = 0;
+
+static void dnslogcb(int w, const char *m)
+{
+       TT_BLATHER(("%s", m));
+}
+
+/* creates a temporary file with the data in it */
+int
+regress_make_tmpfile(const void *data, size_t datalen)
+{
+#ifndef WIN32
+       char tmpfilename[32];
+       int fd;
+       strcpy(tmpfilename, "/tmp/eventtmp.XXXXXX");
+       fd = mkstemp(tmpfilename);
+       if (fd == -1)
+               return (-1);
+       if (write(fd, data, datalen) != (int)datalen) {
+               close(fd);
+               return (-1);
+       }
+       lseek(fd, 0, SEEK_SET);
+       /* remove it from the file system */
+       unlink(tmpfilename);
+       return (fd);
+#else
+       /* XXXX actually delete the file later */
+       char tmpfilepath[MAX_PATH];
+       char tmpfilename[MAX_PATH];
+       DWORD r, written;
+       int tries = 16;
+       HANDLE h;
+       r = GetTempPathA(MAX_PATH, tmpfilepath);
+       if (r > MAX_PATH || r == 0)
+               return (-1);
+       for (; tries > 0; --tries) {
+               r = GetTempFileNameA(tmpfilepath, "LIBEVENT", 0, tmpfilename);
+               if (r == 0)
+                       return (-1);
+               h = CreateFileA(tmpfilename, GENERIC_READ|GENERIC_WRITE,
+                   0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+               if (h != INVALID_HANDLE_VALUE)
+                       break;
+       }
+       if (tries == 0)
+               return (-1);
+       written = 0;
+       WriteFile(h, data, (DWORD)datalen, &written, NULL);
+       /* Closing the fd returned by this function will indeed close h. */
+       return _open_osfhandle((intptr_t)h,_O_RDONLY);
+#endif
+}
+
+static void
+ignore_log_cb(int s, const char *msg)
+{
+}
+
+static void *
+basic_test_setup(const struct testcase_t *testcase)
+{
+       struct event_base *base = NULL;
+       evutil_socket_t spair[2] = { -1, -1 };
+       struct basic_test_data *data = NULL;
+
+#ifndef WIN32
+       if (testcase->flags & TT_ENABLE_IOCP_FLAG)
+               return (void*)TT_SKIP;
+#endif
+
+       if (testcase->flags & TT_NEED_THREADS) {
+               if (!(testcase->flags & TT_FORK))
+                       return NULL;
+#if defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
+               if (evthread_use_pthreads())
+                       exit(1);
+#elif defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
+               if (evthread_use_windows_threads())
+                       exit(1);
+#else
+               return (void*)TT_SKIP;
+#endif
+       }
+
+       if (testcase->flags & TT_NEED_SOCKETPAIR) {
+               if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, spair) == -1) {
+                       fprintf(stderr, "%s: socketpair\n", __func__);
+                       exit(1);
+               }
+
+               if (evutil_make_socket_nonblocking(spair[0]) == -1) {
+                       fprintf(stderr, "fcntl(O_NONBLOCK)");
+                       exit(1);
+               }
+
+               if (evutil_make_socket_nonblocking(spair[1]) == -1) {
+                       fprintf(stderr, "fcntl(O_NONBLOCK)");
+                       exit(1);
+               }
+       }
+       if (testcase->flags & TT_NEED_BASE) {
+               if (testcase->flags & TT_LEGACY)
+                       base = event_init();
+               else
+                       base = event_base_new();
+               if (!base)
+                       exit(1);
+       }
+       if (testcase->flags & TT_ENABLE_IOCP_FLAG) {
+               if (event_base_start_iocp(base, 0)<0) {
+                       event_base_free(base);
+                       return (void*)TT_SKIP;
+               }
+       }
+
+       if (testcase->flags & TT_NEED_DNS) {
+               evdns_set_log_fn(dnslogcb);
+               if (evdns_init())
+                       return NULL; /* fast failure */ /*XXX asserts. */
+       }
+
+       if (testcase->flags & TT_NO_LOGS)
+               event_set_log_callback(ignore_log_cb);
+
+       data = calloc(1, sizeof(*data));
+       if (!data)
+               exit(1);
+       data->base = base;
+       data->pair[0] = spair[0];
+       data->pair[1] = spair[1];
+       data->setup_data = testcase->setup_data;
+       return data;
+}
+
+static int
+basic_test_cleanup(const struct testcase_t *testcase, void *ptr)
+{
+       struct basic_test_data *data = ptr;
+
+       if (testcase->flags & TT_NO_LOGS)
+               event_set_log_callback(NULL);
+
+       if (testcase->flags & TT_NEED_SOCKETPAIR) {
+               if (data->pair[0] != -1)
+                       evutil_closesocket(data->pair[0]);
+               if (data->pair[1] != -1)
+                       evutil_closesocket(data->pair[1]);
+       }
+
+       if (testcase->flags & TT_NEED_DNS) {
+               evdns_shutdown(0);
+       }
+
+       if (testcase->flags & TT_NEED_BASE) {
+               if (data->base) {
+                       event_base_assert_ok(data->base);
+                       event_base_free(data->base);
+               }
+       }
+
+       free(data);
+
+       return 1;
+}
+
+const struct testcase_setup_t basic_setup = {
+       basic_test_setup, basic_test_cleanup
+};
+
+/* The "data" for a legacy test is just a pointer to the void fn(void)
+   function implementing the test case.  We need to set up some globals,
+   though, since that's where legacy tests expect to find a socketpair
+   (sometimes) and a global event_base (sometimes).
+ */
+static void *
+legacy_test_setup(const struct testcase_t *testcase)
+{
+       struct basic_test_data *data = basic_test_setup(testcase);
+       if (data == (void*)TT_SKIP)
+               return data;
+       global_base = data->base;
+       pair[0] = data->pair[0];
+       pair[1] = data->pair[1];
+       data->legacy_test_fn = testcase->setup_data;
+       return data;
+}
+
+/* This function is the implementation of every legacy test case.  It
+   sets test_ok to 0, invokes the test function, and tells tinytest that
+   the test failed if the test didn't set test_ok to 1.
+ */
+void
+run_legacy_test_fn(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       test_ok = called = 0;
+
+       in_legacy_test_wrapper = 1;
+       data->legacy_test_fn(); /* This part actually calls the test */
+       in_legacy_test_wrapper = 0;
+
+       if (!test_ok)
+               tt_abort_msg("Legacy unit test failed");
+
+end:
+       test_ok = 0;
+}
+
+/* This function doesn't have to clean up ptr (which is just a pointer
+   to the test function), but it may need to close the socketpair or
+   free the event_base.
+ */
+static int
+legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
+{
+       int r = basic_test_cleanup(testcase, ptr);
+       pair[0] = pair[1] = -1;
+       global_base = NULL;
+       return r;
+}
+
+const struct testcase_setup_t legacy_setup = {
+       legacy_test_setup, legacy_test_cleanup
+};
+
+/* ============================================================ */
+
+#if (!defined(_EVENT_HAVE_PTHREADS) && !defined(WIN32)) || defined(_EVENT_DISABLE_THREAD_SUPPORT)
+struct testcase_t thread_testcases[] = {
+       { "basic", NULL, TT_SKIP, NULL, NULL },
+       END_OF_TESTCASES
+};
+#endif
+
+struct testgroup_t testgroups[] = {
+       { "main/", main_testcases },
+       { "heap/", minheap_testcases },
+       { "et/", edgetriggered_testcases },
+       { "evbuffer/", evbuffer_testcases },
+       { "signal/", signal_testcases },
+       { "util/", util_testcases },
+       { "bufferevent/", bufferevent_testcases },
+       { "http/", http_testcases },
+       { "dns/", dns_testcases },
+       { "evtag/", evtag_testcases },
+       { "rpc/", rpc_testcases },
+       { "thread/", thread_testcases },
+       { "listener/", listener_testcases },
+#ifdef WIN32
+       { "iocp/", iocp_testcases },
+       { "iocp/bufferevent/", bufferevent_iocp_testcases },
+       { "iocp/listener/", listener_iocp_testcases },
+#endif
+#ifdef _EVENT_HAVE_OPENSSL
+       { "ssl/", ssl_testcases },
+#endif
+       END_OF_GROUPS
+};
+
+int
+main(int argc, const char **argv)
+{
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+#ifndef WIN32
+       if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+               return 1;
+#endif
+
+#ifdef WIN32
+       tinytest_skip(testgroups, "http/connection_retry");
+#endif
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       if (!getenv("EVENT_NO_DEBUG_LOCKS"))
+               evthread_enable_lock_debuging();
+#endif
+
+       if (tinytest_main(argc,argv,testgroups))
+               return 1;
+
+       return 0;
+}
+
diff --git a/libevent/test/regress_minheap.c b/libevent/test/regress_minheap.c
new file mode 100644 (file)
index 0000000..049d22a
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <stdlib.h>
+#include "event2/event_struct.h"
+
+#include "tinytest.h"
+#include "tinytest_macros.h"
+#include "../minheap-internal.h"
+
+static void
+set_random_timeout(struct event *ev)
+{
+       ev->ev_timeout.tv_sec = rand();
+       ev->ev_timeout.tv_usec = rand() & 0xfffff;
+       ev->ev_timeout_pos.min_heap_idx = -1;
+}
+
+static void
+check_heap(struct min_heap *heap)
+{
+       unsigned i;
+       for (i = 1; i < heap->n; ++i) {
+               unsigned parent_idx = (i-1)/2;
+               tt_want(evutil_timercmp(&heap->p[i]->ev_timeout,
+                       &heap->p[parent_idx]->ev_timeout, >=));
+       }
+}
+
+static void
+test_heap_randomized(void *ptr)
+{
+       struct min_heap heap;
+       struct event *inserted[1024];
+       struct event *e, *last_e;
+       int i;
+
+       min_heap_ctor(&heap);
+
+       for (i = 0; i < 1024; ++i) {
+               inserted[i] = malloc(sizeof(struct event));
+               set_random_timeout(inserted[i]);
+               min_heap_push(&heap, inserted[i]);
+       }
+       check_heap(&heap);
+
+       tt_assert(min_heap_size(&heap) == 1024);
+
+       for (i = 0; i < 512; ++i) {
+               min_heap_erase(&heap, inserted[i]);
+               if (0 == (i % 32))
+                       check_heap(&heap);
+       }
+       tt_assert(min_heap_size(&heap) == 512);
+
+       last_e = min_heap_pop(&heap);
+       while (1) {
+               e = min_heap_pop(&heap);
+               if (!e)
+                       break;
+               tt_want(evutil_timercmp(&last_e->ev_timeout,
+                       &e->ev_timeout, <=));
+       }
+       tt_assert(min_heap_size(&heap) == 0);
+end:
+       for (i = 0; i < 1024; ++i)
+               free(inserted[i]);
+
+       min_heap_dtor(&heap);
+}
+
+struct testcase_t minheap_testcases[] = {
+       { "randomized", test_heap_randomized, 0, NULL, NULL },
+       END_OF_TESTCASES
+};
diff --git a/libevent/test/regress_rpc.c b/libevent/test/regress_rpc.c
new file mode 100644 (file)
index 0000000..922fdc1
--- /dev/null
@@ -0,0 +1,893 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+/* The old tests here need assertions to work. */
+#undef NDEBUG
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+
+#include "event2/buffer.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/http.h"
+#include "event2/http_compat.h"
+#include "event2/http_struct.h"
+#include "event2/rpc.h"
+#include "event2/rpc.h"
+#include "event2/rpc_struct.h"
+#include "event2/tag.h"
+#include "log-internal.h"
+
+#include "regress.gen.h"
+
+#include "regress.h"
+#include "regress_testutils.h"
+
+#ifndef NO_PYTHON_EXISTS
+
+static struct evhttp *
+http_setup(ev_uint16_t *pport)
+{
+       struct evhttp *myhttp;
+       ev_uint16_t port;
+       struct evhttp_bound_socket *sock;
+
+       myhttp = evhttp_new(NULL);
+       if (!myhttp)
+               event_errx(1, "Could not start web server");
+
+       /* Try a few different ports */
+       sock = evhttp_bind_socket_with_handle(myhttp, "127.0.0.1", 0);
+       if (!sock)
+               event_errx(1, "Couldn't open web port");
+
+       port = regress_get_socket_port(evhttp_bound_socket_get_fd(sock));
+
+       *pport = port;
+       return (myhttp);
+}
+
+EVRPC_HEADER(Message, msg, kill)
+EVRPC_HEADER(NeverReply, msg, kill)
+
+EVRPC_GENERATE(Message, msg, kill)
+EVRPC_GENERATE(NeverReply, msg, kill)
+
+static int need_input_hook = 0;
+static int need_output_hook = 0;
+
+static void
+MessageCb(EVRPC_STRUCT(Message)* rpc, void *arg)
+{
+       struct kill* kill_reply = rpc->reply;
+
+       if (need_input_hook) {
+               struct evhttp_request* req = EVRPC_REQUEST_HTTP(rpc);
+               const char *header = evhttp_find_header(
+                       req->input_headers, "X-Hook");
+               assert(strcmp(header, "input") == 0);
+       }
+
+       /* we just want to fill in some non-sense */
+       EVTAG_ASSIGN(kill_reply, weapon, "dagger");
+       EVTAG_ASSIGN(kill_reply, action, "wave around like an idiot");
+
+       /* no reply to the RPC */
+       EVRPC_REQUEST_DONE(rpc);
+}
+
+static EVRPC_STRUCT(NeverReply) *saved_rpc;
+
+static void
+NeverReplyCb(EVRPC_STRUCT(NeverReply)* rpc, void *arg)
+{
+       test_ok += 1;
+       saved_rpc = rpc;
+}
+
+static void
+rpc_setup(struct evhttp **phttp, ev_uint16_t *pport, struct evrpc_base **pbase)
+{
+       ev_uint16_t port;
+       struct evhttp *http = NULL;
+       struct evrpc_base *base = NULL;
+
+       http = http_setup(&port);
+       base = evrpc_init(http);
+
+       EVRPC_REGISTER(base, Message, msg, kill, MessageCb, NULL);
+       EVRPC_REGISTER(base, NeverReply, msg, kill, NeverReplyCb, NULL);
+
+       *phttp = http;
+       *pport = port;
+       *pbase = base;
+
+       need_input_hook = 0;
+       need_output_hook = 0;
+}
+
+static void
+rpc_teardown(struct evrpc_base *base)
+{
+       assert(EVRPC_UNREGISTER(base, Message) == 0);
+       assert(EVRPC_UNREGISTER(base, NeverReply) == 0);
+
+       evrpc_free(base);
+}
+
+static void
+rpc_postrequest_failure(struct evhttp_request *req, void *arg)
+{
+       if (req->response_code != HTTP_SERVUNAVAIL) {
+
+               fprintf(stderr, "FAILED (response code)\n");
+               exit(1);
+       }
+
+       test_ok = 1;
+       event_loopexit(NULL);
+}
+
+/*
+ * Test a malformed payload submitted as an RPC
+ */
+
+static void
+rpc_basic_test(void)
+{
+       ev_uint16_t port;
+       struct evhttp *http = NULL;
+       struct evrpc_base *base = NULL;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+
+       rpc_setup(&http, &port, &base);
+
+       evcon = evhttp_connection_new("127.0.0.1", port);
+       tt_assert(evcon);
+
+       /*
+        * At this point, we want to schedule an HTTP POST request
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(rpc_postrequest_failure, NULL);
+       tt_assert(req);
+
+       /* Add the information that we care about */
+       evhttp_add_header(req->output_headers, "Host", "somehost");
+       evbuffer_add_printf(req->output_buffer, "Some Nonsense");
+
+       if (evhttp_make_request(evcon, req,
+               EVHTTP_REQ_POST,
+               "/.rpc.Message") == -1) {
+               tt_abort();
+       }
+
+       test_ok = 0;
+
+       event_dispatch();
+
+       evhttp_connection_free(evcon);
+
+       rpc_teardown(base);
+
+       tt_assert(test_ok == 1);
+
+end:
+       evhttp_free(http);
+}
+
+static void
+rpc_postrequest_done(struct evhttp_request *req, void *arg)
+{
+       struct kill* kill_reply = NULL;
+
+       if (req->response_code != HTTP_OK) {
+               fprintf(stderr, "FAILED (response code)\n");
+               exit(1);
+       }
+
+       kill_reply = kill_new();
+
+       if ((kill_unmarshal(kill_reply, req->input_buffer)) == -1) {
+               fprintf(stderr, "FAILED (unmarshal)\n");
+               exit(1);
+       }
+
+       kill_free(kill_reply);
+
+       test_ok = 1;
+       event_loopexit(NULL);
+}
+
+static void
+rpc_basic_message(void)
+{
+       ev_uint16_t port;
+       struct evhttp *http = NULL;
+       struct evrpc_base *base = NULL;
+       struct evhttp_connection *evcon = NULL;
+       struct evhttp_request *req = NULL;
+       struct msg *msg;
+
+       rpc_setup(&http, &port, &base);
+
+       evcon = evhttp_connection_new("127.0.0.1", port);
+       tt_assert(evcon);
+
+       /*
+        * At this point, we want to schedule an HTTP POST request
+        * server using our make request method.
+        */
+
+       req = evhttp_request_new(rpc_postrequest_done, NULL);
+       if (req == NULL) {
+               fprintf(stdout, "FAILED\n");
+               exit(1);
+       }
+
+       /* Add the information that we care about */
+       evhttp_add_header(req->output_headers, "Host", "somehost");
+
+       /* set up the basic message */
+       msg = msg_new();
+       EVTAG_ASSIGN(msg, from_name, "niels");
+       EVTAG_ASSIGN(msg, to_name, "tester");
+       msg_marshal(req->output_buffer, msg);
+       msg_free(msg);
+
+       if (evhttp_make_request(evcon, req,
+               EVHTTP_REQ_POST,
+               "/.rpc.Message") == -1) {
+               fprintf(stdout, "FAILED\n");
+               exit(1);
+       }
+
+       test_ok = 0;
+
+       event_dispatch();
+
+       evhttp_connection_free(evcon);
+
+       rpc_teardown(base);
+
+end:
+       evhttp_free(http);
+}
+
+static struct evrpc_pool *
+rpc_pool_with_connection(ev_uint16_t port)
+{
+       struct evhttp_connection *evcon;
+       struct evrpc_pool *pool;
+
+       pool = evrpc_pool_new(NULL);
+       assert(pool != NULL);
+
+       evcon = evhttp_connection_new("127.0.0.1", port);
+       assert(evcon != NULL);
+
+       evrpc_pool_add_connection(pool, evcon);
+
+       return (pool);
+}
+
+static void
+GotKillCb(struct evrpc_status *status,
+    struct msg *msg, struct kill *kill, void *arg)
+{
+       char *weapon;
+       char *action;
+
+       if (need_output_hook) {
+               struct evhttp_request *req = status->http_req;
+               const char *header = evhttp_find_header(
+                       req->input_headers, "X-Pool-Hook");
+               assert(strcmp(header, "ran") == 0);
+       }
+
+       if (status->error != EVRPC_STATUS_ERR_NONE)
+               goto done;
+
+       if (EVTAG_GET(kill, weapon, &weapon) == -1) {
+               fprintf(stderr, "get weapon\n");
+               goto done;
+       }
+       if (EVTAG_GET(kill, action, &action) == -1) {
+               fprintf(stderr, "get action\n");
+               goto done;
+       }
+
+       if (strcmp(weapon, "dagger"))
+               goto done;
+
+       if (strcmp(action, "wave around like an idiot"))
+               goto done;
+
+       test_ok += 1;
+
+done:
+       event_loopexit(NULL);
+}
+
+static void
+GotKillCbTwo(struct evrpc_status *status,
+    struct msg *msg, struct kill *kill, void *arg)
+{
+       char *weapon;
+       char *action;
+
+       if (status->error != EVRPC_STATUS_ERR_NONE)
+               goto done;
+
+       if (EVTAG_GET(kill, weapon, &weapon) == -1) {
+               fprintf(stderr, "get weapon\n");
+               goto done;
+       }
+       if (EVTAG_GET(kill, action, &action) == -1) {
+               fprintf(stderr, "get action\n");
+               goto done;
+       }
+
+       if (strcmp(weapon, "dagger"))
+               goto done;
+
+       if (strcmp(action, "wave around like an idiot"))
+               goto done;
+
+       test_ok += 1;
+
+done:
+       if (test_ok == 2)
+               event_loopexit(NULL);
+}
+
+static int
+rpc_hook_add_header(void *ctx, struct evhttp_request *req,
+    struct evbuffer *evbuf, void *arg)
+{
+       const char *hook_type = arg;
+       if (strcmp("input", hook_type) == 0)
+               evhttp_add_header(req->input_headers, "X-Hook", hook_type);
+       else
+               evhttp_add_header(req->output_headers, "X-Hook", hook_type);
+
+       assert(evrpc_hook_get_connection(ctx) != NULL);
+
+       return (EVRPC_CONTINUE);
+}
+
+static int
+rpc_hook_add_meta(void *ctx, struct evhttp_request *req,
+    struct evbuffer *evbuf, void *arg)
+{
+       evrpc_hook_add_meta(ctx, "meta", "test", 5);
+
+       assert(evrpc_hook_get_connection(ctx) != NULL);
+
+       return (EVRPC_CONTINUE);
+}
+
+static int
+rpc_hook_remove_header(void *ctx, struct evhttp_request *req,
+    struct evbuffer *evbuf, void *arg)
+{
+       const char *header = evhttp_find_header(req->input_headers, "X-Hook");
+       void *data = NULL;
+       size_t data_len = 0;
+
+       assert(header != NULL);
+       assert(strcmp(header, arg) == 0);
+
+       evhttp_remove_header(req->input_headers, "X-Hook");
+       evhttp_add_header(req->input_headers, "X-Pool-Hook", "ran");
+
+       assert(evrpc_hook_find_meta(ctx, "meta", &data, &data_len) == 0);
+       assert(data != NULL);
+       assert(data_len == 5);
+
+       assert(evrpc_hook_get_connection(ctx) != NULL);
+
+       return (EVRPC_CONTINUE);
+}
+
+static void
+rpc_basic_client(void)
+{
+       ev_uint16_t port;
+       struct evhttp *http = NULL;
+       struct evrpc_base *base = NULL;
+       struct evrpc_pool *pool = NULL;
+       struct msg *msg = NULL;
+       struct kill *kill = NULL;
+
+       rpc_setup(&http, &port, &base);
+
+       need_input_hook = 1;
+       need_output_hook = 1;
+
+       assert(evrpc_add_hook(base, EVRPC_INPUT, rpc_hook_add_header, (void*)"input")
+           != NULL);
+       assert(evrpc_add_hook(base, EVRPC_OUTPUT, rpc_hook_add_header, (void*)"output")
+           != NULL);
+
+       pool = rpc_pool_with_connection(port);
+
+       assert(evrpc_add_hook(pool, EVRPC_OUTPUT, rpc_hook_add_meta, NULL));
+       assert(evrpc_add_hook(pool, EVRPC_INPUT, rpc_hook_remove_header, (void*)"output"));
+
+       /* set up the basic message */
+       msg = msg_new();
+       EVTAG_ASSIGN(msg, from_name, "niels");
+       EVTAG_ASSIGN(msg, to_name, "tester");
+
+       kill = kill_new();
+
+       EVRPC_MAKE_REQUEST(Message, pool, msg, kill,  GotKillCb, NULL);
+
+       test_ok = 0;
+
+       event_dispatch();
+
+       tt_assert(test_ok == 1);
+
+       /* we do it twice to make sure that reuse works correctly */
+       kill_clear(kill);
+
+       EVRPC_MAKE_REQUEST(Message, pool, msg, kill,  GotKillCb, NULL);
+
+       event_dispatch();
+
+       tt_assert(test_ok == 2);
+
+       /* we do it trice to make sure other stuff works, too */
+       kill_clear(kill);
+
+       {
+               struct evrpc_request_wrapper *ctx =
+                   EVRPC_MAKE_CTX(Message, msg, kill,
+                       pool, msg, kill, GotKillCb, NULL);
+               evrpc_make_request(ctx);
+       }
+
+       event_dispatch();
+
+       rpc_teardown(base);
+
+       tt_assert(test_ok == 3);
+
+end:
+       if (msg)
+               msg_free(msg);
+       if (kill)
+               kill_free(kill);
+
+       if (pool)
+               evrpc_pool_free(pool);
+       if (http)
+               evhttp_free(http);
+
+       need_input_hook = 0;
+       need_output_hook = 0;
+}
+
+/*
+ * We are testing that the second requests gets send over the same
+ * connection after the first RPCs completes.
+ */
+static void
+rpc_basic_queued_client(void)
+{
+       ev_uint16_t port;
+       struct evhttp *http = NULL;
+       struct evrpc_base *base = NULL;
+       struct evrpc_pool *pool = NULL;
+       struct msg *msg=NULL;
+       struct kill *kill_one=NULL, *kill_two=NULL;
+
+       rpc_setup(&http, &port, &base);
+
+       pool = rpc_pool_with_connection(port);
+
+       /* set up the basic message */
+       msg = msg_new();
+       EVTAG_ASSIGN(msg, from_name, "niels");
+       EVTAG_ASSIGN(msg, to_name, "tester");
+
+       kill_one = kill_new();
+       kill_two = kill_new();
+
+       EVRPC_MAKE_REQUEST(Message, pool, msg, kill_one,  GotKillCbTwo, NULL);
+       EVRPC_MAKE_REQUEST(Message, pool, msg, kill_two,  GotKillCb, NULL);
+
+       test_ok = 0;
+
+       event_dispatch();
+
+       rpc_teardown(base);
+
+       tt_assert(test_ok == 2);
+
+end:
+       if (msg)
+               msg_free(msg);
+       if (kill_one)
+               kill_free(kill_one);
+       if (kill_two)
+               kill_free(kill_two);
+
+       if (pool)
+               evrpc_pool_free(pool);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+GotErrorCb(struct evrpc_status *status,
+    struct msg *msg, struct kill *kill, void *arg)
+{
+       if (status->error != EVRPC_STATUS_ERR_TIMEOUT)
+               goto done;
+
+       /* should never be complete but just to check */
+       if (kill_complete(kill) == 0)
+               goto done;
+
+       test_ok += 1;
+
+done:
+       event_loopexit(NULL);
+}
+
+/* we just pause the rpc and continue it in the next callback */
+
+struct _rpc_hook_ctx {
+       void *vbase;
+       void *ctx;
+};
+
+static int hook_pause_cb_called=0;
+
+static void
+rpc_hook_pause_cb(evutil_socket_t fd, short what, void *arg)
+{
+       struct _rpc_hook_ctx *ctx = arg;
+       ++hook_pause_cb_called;
+       evrpc_resume_request(ctx->vbase, ctx->ctx, EVRPC_CONTINUE);
+       free(arg);
+}
+
+static int
+rpc_hook_pause(void *ctx, struct evhttp_request *req, struct evbuffer *evbuf,
+    void *arg)
+{
+       struct _rpc_hook_ctx *tmp = malloc(sizeof(*tmp));
+       struct timeval tv;
+
+       assert(tmp != NULL);
+       tmp->vbase = arg;
+       tmp->ctx = ctx;
+
+       memset(&tv, 0, sizeof(tv));
+       event_once(-1, EV_TIMEOUT, rpc_hook_pause_cb, tmp, &tv);
+       return EVRPC_PAUSE;
+}
+
+static void
+rpc_basic_client_with_pause(void)
+{
+       ev_uint16_t port;
+       struct evhttp *http = NULL;
+       struct evrpc_base *base = NULL;
+       struct evrpc_pool *pool = NULL;
+       struct msg *msg = NULL;
+       struct kill *kill= NULL;
+
+       rpc_setup(&http, &port, &base);
+
+       assert(evrpc_add_hook(base, EVRPC_INPUT, rpc_hook_pause, base));
+       assert(evrpc_add_hook(base, EVRPC_OUTPUT, rpc_hook_pause, base));
+
+       pool = rpc_pool_with_connection(port);
+
+       assert(evrpc_add_hook(pool, EVRPC_INPUT, rpc_hook_pause, pool));
+       assert(evrpc_add_hook(pool, EVRPC_OUTPUT, rpc_hook_pause, pool));
+
+       /* set up the basic message */
+       msg = msg_new();
+       EVTAG_ASSIGN(msg, from_name, "niels");
+       EVTAG_ASSIGN(msg, to_name, "tester");
+
+       kill = kill_new();
+
+       EVRPC_MAKE_REQUEST(Message, pool, msg, kill, GotKillCb, NULL);
+
+       test_ok = 0;
+
+       event_dispatch();
+
+       tt_int_op(test_ok, ==, 1);
+       tt_int_op(hook_pause_cb_called, ==, 4);
+
+end:
+       if (base)
+               rpc_teardown(base);
+
+       if (msg)
+               msg_free(msg);
+       if (kill)
+               kill_free(kill);
+
+       if (pool)
+               evrpc_pool_free(pool);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+rpc_client_timeout(void)
+{
+       ev_uint16_t port;
+       struct evhttp *http = NULL;
+       struct evrpc_base *base = NULL;
+       struct evrpc_pool *pool = NULL;
+       struct msg *msg = NULL;
+       struct kill *kill = NULL;
+
+       rpc_setup(&http, &port, &base);
+
+       pool = rpc_pool_with_connection(port);
+
+       /* set the timeout to 5 seconds */
+       evrpc_pool_set_timeout(pool, 5);
+
+       /* set up the basic message */
+       msg = msg_new();
+       EVTAG_ASSIGN(msg, from_name, "niels");
+       EVTAG_ASSIGN(msg, to_name, "tester");
+
+       kill = kill_new();
+
+       EVRPC_MAKE_REQUEST(NeverReply, pool, msg, kill, GotErrorCb, NULL);
+
+       test_ok = 0;
+
+       event_dispatch();
+
+       /* free the saved RPC structure up */
+       EVRPC_REQUEST_DONE(saved_rpc);
+
+       rpc_teardown(base);
+
+       tt_assert(test_ok == 2);
+
+end:
+       if (msg)
+               msg_free(msg);
+       if (kill)
+               kill_free(kill);
+
+       if (pool)
+               evrpc_pool_free(pool);
+       if (http)
+               evhttp_free(http);
+}
+
+static void
+rpc_test(void)
+{
+       struct msg *msg = NULL, *msg2 = NULL;
+       struct kill *attack = NULL;
+       struct run *run = NULL;
+       struct evbuffer *tmp = evbuffer_new();
+       struct timeval tv_start, tv_end;
+       ev_uint32_t tag;
+       int i;
+
+       msg = msg_new();
+       EVTAG_ASSIGN(msg, from_name, "niels");
+       EVTAG_ASSIGN(msg, to_name, "phoenix");
+
+       if (EVTAG_GET(msg, attack, &attack) == -1) {
+               tt_abort_msg("Failed to set kill message.");
+       }
+
+       EVTAG_ASSIGN(attack, weapon, "feather");
+       EVTAG_ASSIGN(attack, action, "tickle");
+       for (i = 0; i < 3; ++i) {
+               if (EVTAG_ARRAY_ADD_VALUE(attack, how_often, i) == NULL) {
+                       tt_abort_msg("Failed to add how_often.");
+               }
+       }
+
+       evutil_gettimeofday(&tv_start, NULL);
+       for (i = 0; i < 1000; ++i) {
+               run = EVTAG_ARRAY_ADD(msg, run);
+               if (run == NULL) {
+                       tt_abort_msg("Failed to add run message.");
+               }
+               EVTAG_ASSIGN(run, how, "very fast but with some data in it");
+               EVTAG_ASSIGN(run, fixed_bytes,
+                   (ev_uint8_t*)"012345678901234567890123");
+
+               if (EVTAG_ARRAY_ADD_VALUE(
+                           run, notes, "this is my note") == NULL) {
+                       tt_abort_msg("Failed to add note.");
+               }
+               if (EVTAG_ARRAY_ADD_VALUE(run, notes, "pps") == NULL) {
+                       tt_abort_msg("Failed to add note");
+               }
+
+               EVTAG_ASSIGN(run, large_number, 0xdead0a0bcafebeefLL);
+               EVTAG_ARRAY_ADD_VALUE(run, other_numbers, 0xdead0a0b);
+               EVTAG_ARRAY_ADD_VALUE(run, other_numbers, 0xbeefcafe);
+       }
+
+       if (msg_complete(msg) == -1)
+               tt_abort_msg("Failed to make complete message.");
+
+       evtag_marshal_msg(tmp, 0xdeaf, msg);
+
+       if (evtag_peek(tmp, &tag) == -1)
+               tt_abort_msg("Failed to peak tag.");
+
+       if (tag != 0xdeaf)
+               TT_DIE(("Got incorrect tag: %0x.", (unsigned)tag));
+
+       msg2 = msg_new();
+       if (evtag_unmarshal_msg(tmp, 0xdeaf, msg2) == -1)
+               tt_abort_msg("Failed to unmarshal message.");
+
+       evutil_gettimeofday(&tv_end, NULL);
+       evutil_timersub(&tv_end, &tv_start, &tv_end);
+       TT_BLATHER(("(%.1f us/add) ",
+               (float)tv_end.tv_sec/(float)i * 1000000.0 +
+               tv_end.tv_usec / (float)i));
+
+       if (!EVTAG_HAS(msg2, from_name) ||
+           !EVTAG_HAS(msg2, to_name) ||
+           !EVTAG_HAS(msg2, attack)) {
+               tt_abort_msg("Missing data structures.");
+       }
+
+       if (EVTAG_GET(msg2, attack, &attack) == -1) {
+               tt_abort_msg("Could not get attack.");
+       }
+
+       if (EVTAG_ARRAY_LEN(msg2, run) != i) {
+               tt_abort_msg("Wrong number of run messages.");
+       }
+
+       /* get the very first run message */
+       if (EVTAG_ARRAY_GET(msg2, run, 0, &run) == -1) {
+               tt_abort_msg("Failed to get run msg.");
+       } else {
+               /* verify the notes */
+               char *note_one, *note_two;
+               ev_uint64_t large_number;
+               ev_uint32_t short_number;
+
+               if (EVTAG_ARRAY_LEN(run, notes) != 2) {
+                       tt_abort_msg("Wrong number of note strings.");
+               }
+
+               if (EVTAG_ARRAY_GET(run, notes, 0, &note_one) == -1 ||
+                   EVTAG_ARRAY_GET(run, notes, 1, &note_two) == -1) {
+                       tt_abort_msg("Could not get note strings.");
+               }
+
+               if (strcmp(note_one, "this is my note") ||
+                   strcmp(note_two, "pps")) {
+                       tt_abort_msg("Incorrect note strings encoded.");
+               }
+
+               if (EVTAG_GET(run, large_number, &large_number) == -1 ||
+                   large_number != 0xdead0a0bcafebeefLL) {
+                       tt_abort_msg("Incorrrect large_number.");
+               }
+
+               if (EVTAG_ARRAY_LEN(run, other_numbers) != 2) {
+                       tt_abort_msg("Wrong number of other_numbers.");
+               }
+
+               if (EVTAG_ARRAY_GET(
+                           run, other_numbers, 0, &short_number) == -1) {
+                       tt_abort_msg("Could not get short number.");
+               }
+               tt_uint_op(short_number, ==, 0xdead0a0b);
+
+       }
+       tt_int_op(EVTAG_ARRAY_LEN(attack, how_often), ==, 3);
+
+       for (i = 0; i < 3; ++i) {
+               ev_uint32_t res;
+               if (EVTAG_ARRAY_GET(attack, how_often, i, &res) == -1) {
+                       TT_DIE(("Cannot get %dth how_often msg.", i));
+               }
+               if ((int)res != i) {
+                       TT_DIE(("Wrong message encoded %d != %d", i, res));
+               }
+       }
+
+       test_ok = 1;
+end:
+       if (msg)
+               msg_free(msg);
+       if (msg2)
+               msg_free(msg2);
+       if (tmp)
+               evbuffer_free(tmp);
+}
+
+#define RPC_LEGACY(name)                                               \
+       { #name, run_legacy_test_fn, TT_FORK|TT_NEED_BASE|TT_LEGACY,    \
+                   &legacy_setup,                                      \
+                   rpc_##name }
+#else
+/* NO_PYTHON_EXISTS */
+
+#define RPC_LEGACY(name) \
+       { #name, NULL, TT_SKIP, NULL, NULL }
+
+#endif
+
+struct testcase_t rpc_testcases[] = {
+       RPC_LEGACY(basic_test),
+       RPC_LEGACY(basic_message),
+       RPC_LEGACY(basic_client),
+       RPC_LEGACY(basic_queued_client),
+       RPC_LEGACY(basic_client_with_pause),
+       RPC_LEGACY(client_timeout),
+       RPC_LEGACY(test),
+
+       END_OF_TESTCASES,
+};
diff --git a/libevent/test/regress_ssl.c b/libevent/test/regress_ssl.c
new file mode 100644 (file)
index 0000000..a2b7f05
--- /dev/null
@@ -0,0 +1,449 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#ifndef WIN32
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#endif
+
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/bufferevent_ssl.h"
+#include "event2/buffer.h"
+#include "event2/listener.h"
+
+#include "regress.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+#include <openssl/ssl.h>
+#include <openssl/bio.h>
+#include <openssl/err.h>
+#include <openssl/pem.h>
+
+#include <string.h>
+
+/* A short pre-generated key, to save the cost of doing an RSA key generation
+ * step during the unit tests.  It's only 512 bits long, and it is published
+ * in this file, so you would have to be very foolish to consider using it in
+ * your own code. */
+static const char KEY[] =
+    "-----BEGIN RSA PRIVATE KEY-----\n"
+    "MIIBOgIBAAJBAKibTEzXjj+sqpipePX1lEk5BNFuL/dDBbw8QCXgaJWikOiKHeJq\n"
+    "3FQ0OmCnmpkdsPFE4x3ojYmmdgE2i0dJwq0CAwEAAQJAZ08gpUS+qE1IClps/2gG\n"
+    "AAer6Bc31K2AaiIQvCSQcH440cp062QtWMC3V5sEoWmdLsbAHFH26/9ZHn5zAflp\n"
+    "gQIhANWOx/UYeR8HD0WREU5kcuSzgzNLwUErHLzxP7U6aojpAiEAyh2H35CjN/P7\n"
+    "NhcZ4QYw3PeUWpqgJnaE/4i80BSYkSUCIQDLHFhLYLJZ80HwHTADif/ISn9/Ow6b\n"
+    "p6BWh3DbMar/eQIgBPS6azH5vpp983KXkNv9AL4VZi9ac/b+BeINdzC6GP0CIDmB\n"
+    "U6GFEQTZ3IfuiVabG5pummdC4DNbcdI+WKrSFNmQ\n"
+    "-----END RSA PRIVATE KEY-----\n";
+
+static EVP_PKEY *
+getkey(void)
+{
+       EVP_PKEY *key;
+       BIO *bio;
+
+       /* new read-only BIO backed by KEY. */
+       bio = BIO_new_mem_buf((char*)KEY, -1);
+       tt_assert(bio);
+
+       key = PEM_read_bio_PrivateKey(bio,NULL,NULL,NULL);
+       BIO_free(bio);
+       tt_assert(key);
+
+       return key;
+end:
+       return NULL;
+}
+
+static X509 *
+getcert(void)
+{
+       /* Dummy code to make a quick-and-dirty valid certificate with
+          OpenSSL.  Don't copy this code into your own program! It does a
+          number of things in a stupid and insecure way. */
+       X509 *x509 = NULL;
+       X509_NAME *name = NULL;
+       EVP_PKEY *key = getkey();
+       int nid;
+       time_t now = time(NULL);
+
+       tt_assert(key);
+
+       x509 = X509_new();
+       tt_assert(x509);
+       tt_assert(0 != X509_set_version(x509, 2));
+       tt_assert(0 != ASN1_INTEGER_set(X509_get_serialNumber(x509),
+               (long)now));
+
+       name = X509_NAME_new();
+       tt_assert(name);
+       tt_assert(NID_undef != (nid = OBJ_txt2nid("commonName")));
+       tt_assert(0 != X509_NAME_add_entry_by_NID(
+                   name, nid, MBSTRING_ASC, (unsigned char*)"example.com",
+                   -1, -1, 0));
+
+       X509_set_subject_name(x509, name);
+       X509_set_issuer_name(x509, name);
+
+       X509_time_adj(X509_get_notBefore(x509), 0, &now);
+       now += 3600;
+       X509_time_adj(X509_get_notAfter(x509), 0, &now);
+       X509_set_pubkey(x509, key);
+       tt_assert(0 != X509_sign(x509, key, EVP_sha1()));
+
+       return x509;
+end:
+       X509_free(x509);
+       return NULL;
+}
+
+static SSL_CTX *the_ssl_ctx = NULL;
+
+static SSL_CTX *
+get_ssl_ctx(void)
+{
+       if (the_ssl_ctx)
+               return the_ssl_ctx;
+       return (the_ssl_ctx = SSL_CTX_new(SSLv23_method()));
+}
+
+static void
+init_ssl(void)
+{
+       SSL_library_init();
+       ERR_load_crypto_strings();
+       SSL_load_error_strings();
+       OpenSSL_add_all_algorithms();
+}
+
+/* ====================
+   Here's a simple test: we read a number from the input, increment it, and
+   reply, until we get to 1001.
+*/
+
+static int test_is_done = 0;
+static int n_connected = 0;
+static int got_close = 0;
+static int got_error = 0;
+static int renegotiate_at = -1;
+static int stop_when_connected = 0;
+static int pending_connect_events = 0;
+static struct event_base *exit_base = NULL;
+
+static void
+respond_to_number(struct bufferevent *bev, void *ctx)
+{
+       struct evbuffer *b = bufferevent_get_input(bev);
+       char *line;
+       int n;
+       line = evbuffer_readln(b, NULL, EVBUFFER_EOL_LF);
+       if (! line)
+               return;
+       n = atoi(line);
+       if (n <= 0)
+               TT_FAIL(("Bad number: %s", line));
+       TT_BLATHER(("The number was %d", n));
+       if (n == 1001) {
+               ++test_is_done;
+               bufferevent_free(bev); /* Should trigger close on other side. */
+               return;
+       }
+       if (!strcmp(ctx, "client") && n == renegotiate_at) {
+               SSL_renegotiate(bufferevent_openssl_get_ssl(bev));
+       }
+       ++n;
+       evbuffer_add_printf(bufferevent_get_output(bev),
+           "%d\n", n);
+       TT_BLATHER(("Done reading; now writing."));
+       bufferevent_enable(bev, EV_WRITE);
+       bufferevent_disable(bev, EV_READ);
+}
+
+static void
+done_writing_cb(struct bufferevent *bev, void *ctx)
+{
+       struct evbuffer *b = bufferevent_get_output(bev);
+       if (evbuffer_get_length(b))
+               return;
+       TT_BLATHER(("Done writing."));
+       bufferevent_disable(bev, EV_WRITE);
+       bufferevent_enable(bev, EV_READ);
+}
+
+static void
+eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+       TT_BLATHER(("Got event %d", (int)what));
+       if (what & BEV_EVENT_CONNECTED) {
+               SSL *ssl;
+               X509 *peer_cert;
+               ++n_connected;
+               ssl = bufferevent_openssl_get_ssl(bev);
+               tt_assert(ssl);
+               peer_cert = SSL_get_peer_certificate(ssl);
+               if (0==strcmp(ctx, "server")) {
+                       tt_assert(peer_cert == NULL);
+               } else {
+                       tt_assert(peer_cert != NULL);
+               }
+               if (stop_when_connected) {
+                       if (--pending_connect_events == 0)
+                               event_base_loopexit(exit_base, NULL);
+               }
+       } else if (what & BEV_EVENT_EOF) {
+               TT_BLATHER(("Got a good EOF"));
+               ++got_close;
+               bufferevent_free(bev);
+       } else if (what & BEV_EVENT_ERROR) {
+               TT_BLATHER(("Got an error."));
+               ++got_error;
+               bufferevent_free(bev);
+       }
+end:
+       ;
+}
+
+static void
+open_ssl_bufevs(struct bufferevent **bev1_out, struct bufferevent **bev2_out,
+    struct event_base *base, int is_open, int flags, SSL *ssl1, SSL *ssl2,
+    int *fd_pair, struct bufferevent **underlying_pair)
+{
+       int state1 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_CONNECTING;
+       int state2 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_ACCEPTING;
+       if (fd_pair) {
+               *bev1_out = bufferevent_openssl_socket_new(
+                       base, fd_pair[0], ssl1, state1, flags);
+               *bev2_out = bufferevent_openssl_socket_new(
+                       base, fd_pair[1], ssl2, state2, flags);
+       } else {
+               *bev1_out = bufferevent_openssl_filter_new(
+                       base, underlying_pair[0], ssl1, state1, flags);
+               *bev2_out = bufferevent_openssl_filter_new(
+                       base, underlying_pair[1], ssl2, state2, flags);
+
+       }
+       bufferevent_setcb(*bev1_out, respond_to_number, done_writing_cb,
+           eventcb, (void*)"client");
+       bufferevent_setcb(*bev2_out, respond_to_number, done_writing_cb,
+           eventcb, (void*)"server");
+}
+
+static void
+regress_bufferevent_openssl(void *arg)
+{
+       struct basic_test_data *data = arg;
+
+       struct bufferevent *bev1, *bev2;
+       SSL *ssl1, *ssl2;
+       X509 *cert = getcert();
+       EVP_PKEY *key = getkey();
+       const int start_open = strstr((char*)data->setup_data, "open")!=NULL;
+       const int filter = strstr((char*)data->setup_data, "filter")!=NULL;
+       int flags = BEV_OPT_DEFER_CALLBACKS;
+       struct bufferevent *bev_ll[2] = { NULL, NULL };
+       int *fd_pair = NULL;
+
+       tt_assert(cert);
+       tt_assert(key);
+
+       init_ssl();
+
+       ssl1 = SSL_new(get_ssl_ctx());
+       ssl2 = SSL_new(get_ssl_ctx());
+
+       SSL_use_certificate(ssl2, cert);
+       SSL_use_PrivateKey(ssl2, key);
+
+       if (! start_open)
+               flags |= BEV_OPT_CLOSE_ON_FREE;
+
+       if (strstr((char*)data->setup_data, "renegotiate"))
+               renegotiate_at = 600;
+
+       if (!filter) {
+               tt_assert(strstr((char*)data->setup_data, "socketpair"));
+               fd_pair = data->pair;
+       } else {
+               bev_ll[0] = bufferevent_socket_new(data->base, data->pair[0],
+                   BEV_OPT_CLOSE_ON_FREE);
+               bev_ll[1] = bufferevent_socket_new(data->base, data->pair[1],
+                   BEV_OPT_CLOSE_ON_FREE);
+       }
+
+       open_ssl_bufevs(&bev1, &bev2, data->base, 0, flags, ssl1, ssl2,
+           fd_pair, bev_ll);
+
+       if (!filter) {
+               tt_int_op(bufferevent_getfd(bev1), ==, data->pair[0]);
+       } else {
+               tt_ptr_op(bufferevent_get_underlying(bev1), ==, bev_ll[0]);
+       }
+
+       if (start_open) {
+               pending_connect_events = 2;
+               stop_when_connected = 1;
+               exit_base = data->base;
+               event_base_dispatch(data->base);
+               /* Okay, now the renegotiation is done.  Make new
+                * bufferevents to test opening in BUFFEREVENT_SSL_OPEN */
+               flags |= BEV_OPT_CLOSE_ON_FREE;
+               bufferevent_free(bev1);
+               bufferevent_free(bev2);
+               bev1 = bev2 = NULL;
+               open_ssl_bufevs(&bev1, &bev2, data->base, 1, flags, ssl1, ssl2,
+                   fd_pair, bev_ll);
+       }
+
+       bufferevent_enable(bev1, EV_READ|EV_WRITE);
+       bufferevent_enable(bev2, EV_READ|EV_WRITE);
+
+       evbuffer_add_printf(bufferevent_get_output(bev1), "1\n");
+
+       event_base_dispatch(data->base);
+
+       tt_assert(test_is_done == 1);
+       tt_assert(n_connected == 2);
+
+       /* We don't handle shutdown properly yet.
+          tt_int_op(got_close, ==, 1);
+          tt_int_op(got_error, ==, 0);
+       */
+end:
+       return;
+}
+
+static void
+acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
+    struct sockaddr *addr, int socklen, void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct bufferevent *bev;
+       SSL *ssl = SSL_new(get_ssl_ctx());
+
+       SSL_use_certificate(ssl, getcert());
+       SSL_use_PrivateKey(ssl, getkey());
+
+       bev = bufferevent_openssl_socket_new(
+               data->base,
+               fd,
+               ssl,
+               BUFFEREVENT_SSL_ACCEPTING,
+               BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+
+       bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
+           (void*)"server");
+
+       bufferevent_enable(bev, EV_READ|EV_WRITE);
+
+       /* Only accept once, then disable ourself. */
+       evconnlistener_disable(listener);
+}
+
+static void
+regress_bufferevent_openssl_connect(void *arg)
+{
+       struct basic_test_data *data = arg;
+
+       struct event_base *base = data->base;
+
+       struct evconnlistener *listener;
+       struct bufferevent *bev;
+       struct sockaddr_in sin;
+       struct sockaddr_storage ss;
+       ev_socklen_t slen;
+
+       init_ssl();
+
+       memset(&sin, 0, sizeof(sin));
+       sin.sin_family = AF_INET;
+       sin.sin_addr.s_addr = htonl(0x7f000001);
+
+       memset(&ss, 0, sizeof(ss));
+       slen = sizeof(ss);
+
+       listener = evconnlistener_new_bind(base, acceptcb, data,
+           LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
+           -1, (struct sockaddr *)&sin, sizeof(sin));
+
+       tt_assert(listener);
+       tt_assert(evconnlistener_get_fd(listener) >= 0);
+
+       bev = bufferevent_openssl_socket_new(
+               data->base, -1, SSL_new(get_ssl_ctx()),
+               BUFFEREVENT_SSL_CONNECTING,
+               BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+       tt_assert(bev);
+
+       bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
+           (void*)"client");
+
+       tt_assert(getsockname(evconnlistener_get_fd(listener),
+               (struct sockaddr*)&ss, &slen) == 0);
+       tt_assert(slen == sizeof(struct sockaddr_in));
+       tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
+       tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
+
+       tt_assert(0 ==
+           bufferevent_socket_connect(bev, (struct sockaddr*)&ss, slen));
+       evbuffer_add_printf(bufferevent_get_output(bev), "1\n");
+       bufferevent_enable(bev, EV_READ|EV_WRITE);
+
+       event_base_dispatch(base);
+end:
+       ;
+}
+
+struct testcase_t ssl_testcases[] = {
+
+       { "bufferevent_socketpair", regress_bufferevent_openssl, TT_ISOLATED,
+         &basic_setup, (void*)"socketpair" },
+       { "bufferevent_filter", regress_bufferevent_openssl,
+         TT_ISOLATED,
+         &basic_setup, (void*)"filter" },
+       { "bufferevent_renegotiate_socketpair", regress_bufferevent_openssl,
+         TT_ISOLATED,
+         &basic_setup, (void*)"socketpair renegotiate" },
+       { "bufferevent_renegotiate_filter", regress_bufferevent_openssl,
+         TT_ISOLATED,
+         &basic_setup, (void*)"filter renegotiate" },
+       { "bufferevent_socketpair_startopen", regress_bufferevent_openssl,
+         TT_ISOLATED, &basic_setup, (void*)"socketpair open" },
+       { "bufferevent_filter_startopen", regress_bufferevent_openssl,
+         TT_ISOLATED, &basic_setup, (void*)"filter open" },
+
+       { "bufferevent_connect", regress_bufferevent_openssl_connect,
+         TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+
+       END_OF_TESTCASES,
+};
diff --git a/libevent/test/regress_testutils.c b/libevent/test/regress_testutils.c
new file mode 100644 (file)
index 0000000..9b3046e
--- /dev/null
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <ws2tcpip.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#include <signal.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#endif
+#ifdef _EVENT_HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/dns.h"
+#include "event2/dns_struct.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "event2/bufferevent.h"
+#include "log-internal.h"
+#include "regress.h"
+#include "regress_testutils.h"
+
+#include "../util-internal.h"
+
+/* globals */
+static struct evdns_server_port *dns_port;
+evutil_socket_t dns_sock = -1;
+
+/* Helper: return the port that a socket is bound on, in host order. */
+int
+regress_get_socket_port(evutil_socket_t fd)
+{
+       struct sockaddr_storage ss;
+       ev_socklen_t socklen = sizeof(ss);
+       if (getsockname(fd, (struct sockaddr*)&ss, &socklen) != 0)
+               return -1;
+       if (ss.ss_family == AF_INET)
+               return ntohs( ((struct sockaddr_in*)&ss)->sin_port);
+       else if (ss.ss_family == AF_INET6)
+               return ntohs( ((struct sockaddr_in6*)&ss)->sin6_port);
+       else
+               return -1;
+}
+
+struct evdns_server_port *
+regress_get_dnsserver(struct event_base *base,
+    ev_uint16_t *portnum,
+    evutil_socket_t *psock,
+    evdns_request_callback_fn_type cb,
+    void *arg)
+{
+       struct evdns_server_port *port = NULL;
+       evutil_socket_t sock;
+       struct sockaddr_in my_addr;
+
+       sock = socket(AF_INET, SOCK_DGRAM, 0);
+       if (sock <= 0) {
+               tt_abort_perror("socket");
+       }
+
+       evutil_make_socket_nonblocking(sock);
+
+       memset(&my_addr, 0, sizeof(my_addr));
+       my_addr.sin_family = AF_INET;
+       my_addr.sin_port = htons(*portnum);
+       my_addr.sin_addr.s_addr = htonl(0x7f000001UL);
+       if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) < 0) {
+               tt_abort_perror("bind");
+       }
+       port = evdns_add_server_port_with_base(base, sock, 0, cb, arg);
+       if (!*portnum)
+               *portnum = regress_get_socket_port(sock);
+       if (psock)
+               *psock = sock;
+
+       return port;
+end:
+       return NULL;
+}
+
+void
+regress_clean_dnsserver(void)
+{
+       if (dns_port)
+               evdns_close_server_port(dns_port);
+       if (dns_sock >= 0)
+               evutil_closesocket(dns_sock);
+}
+
+void
+regress_dns_server_cb(struct evdns_server_request *req, void *data)
+{
+       struct regress_dns_server_table *tab = data;
+       const char *question;
+
+       if (req->nquestions != 1)
+               TT_DIE(("Only handling one question at a time; got %d",
+                       req->nquestions));
+
+       question = req->questions[0]->name;
+
+       while (tab->q && evutil_ascii_strcasecmp(question, tab->q) &&
+           strcmp("*", tab->q))
+               ++tab;
+       if (tab->q == NULL)
+               TT_DIE(("Unexpected question: '%s'", question));
+
+       ++tab->seen;
+
+       if (!strcmp(tab->anstype, "err")) {
+               int err = atoi(tab->ans);
+               tt_assert(! evdns_server_request_respond(req, err));
+               return;
+       } else if (!strcmp(tab->anstype, "errsoa")) {
+               int err = atoi(tab->ans);
+               char soa_record[] =
+                       "\x04" "dns1" "\x05" "icann" "\x03" "org" "\0"
+                       "\x0a" "hostmaster" "\x05" "icann" "\x03" "org" "\0"
+                       "\x77\xde\x5e\xba" /* serial */
+                       "\x00\x00\x1c\x20" /* refreshtime = 2h */
+                       "\x00\x00\x0e\x10" /* retry = 1h */
+                       "\x00\x12\x75\x00" /* expiration = 14d */
+                       "\x00\x00\x0e\x10" /* min.ttl = 1h */
+                       ;
+               evdns_server_request_add_reply(
+                       req, EVDNS_AUTHORITY_SECTION,
+                       "example.com", EVDNS_TYPE_SOA, EVDNS_CLASS_INET,
+                       42, sizeof(soa_record) - 1, 0, soa_record);
+               tt_assert(! evdns_server_request_respond(req, err));
+               return;
+       } else if (!strcmp(tab->anstype, "A")) {
+               struct in_addr in;
+               evutil_inet_pton(AF_INET, tab->ans, &in);
+               evdns_server_request_add_a_reply(req, question, 1, &in.s_addr,
+                   100);
+       } else if (!strcmp(tab->anstype, "AAAA")) {
+               struct in6_addr in6;
+               evutil_inet_pton(AF_INET6, tab->ans, &in6);
+               evdns_server_request_add_aaaa_reply(req,
+                   question, 1, &in6.s6_addr, 100);
+       } else {
+               TT_DIE(("Weird table entry with type '%s'", tab->anstype));
+       }
+       tt_assert(! evdns_server_request_respond(req, 0))
+       return;
+end:
+       tt_want(! evdns_server_request_drop(req));
+}
+
+int
+regress_dnsserver(struct event_base *base, ev_uint16_t *port,
+    struct regress_dns_server_table *search_table)
+{
+       dns_port = regress_get_dnsserver(base, port, &dns_sock,
+           regress_dns_server_cb, search_table);
+       return dns_port != NULL;
+}
+
+int
+regress_get_listener_addr(struct evconnlistener *lev,
+    struct sockaddr *sa, ev_socklen_t *socklen)
+{
+       evutil_socket_t s = evconnlistener_get_fd(lev);
+       if (s <= 0)
+               return -1;
+       return getsockname(s, sa, socklen);
+}
diff --git a/libevent/test/regress_testutils.h b/libevent/test/regress_testutils.h
new file mode 100644 (file)
index 0000000..1f09427
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _TESTUTILS_H
+#define _TESTUTILS_H
+
+#include "event2/dns.h"
+
+struct regress_dns_server_table {
+       const char *q;
+       const char *anstype;
+       const char *ans;
+       int seen;
+};
+
+struct evdns_server_port *
+regress_get_dnsserver(struct event_base *base,
+    ev_uint16_t *portnum,
+    evutil_socket_t *psock,
+    evdns_request_callback_fn_type cb,
+    void *arg);
+
+/* Helper: return the port that a socket is bound on, in host order. */
+int regress_get_socket_port(evutil_socket_t fd);
+
+/* used to look up pre-canned responses in a search table */
+void regress_dns_server_cb(
+       struct evdns_server_request *req, void *data);
+
+/* globally allocates a dns server that serves from a search table */
+int regress_dnsserver(struct event_base *base, ev_uint16_t *port,
+    struct regress_dns_server_table *seach_table);
+
+/* clean up the global dns server resources */
+void regress_clean_dnsserver(void);
+
+struct evconnlistener;
+struct sockaddr;
+int regress_get_listener_addr(struct evconnlistener *lev,
+    struct sockaddr *sa, ev_socklen_t *socklen);
+
+#endif /* _TESTUTILS_H */
+
diff --git a/libevent/test/regress_thread.c b/libevent/test/regress_thread.c
new file mode 100644 (file)
index 0000000..1acf682
--- /dev/null
@@ -0,0 +1,511 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+/* The old tests here need assertions to work. */
+#undef NDEBUG
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+
+#ifdef _EVENT_HAVE_PTHREADS
+#include <pthread.h>
+#elif defined(WIN32)
+#include <process.h>
+#endif
+#include <assert.h>
+#ifdef _EVENT_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <time.h>
+
+#include "sys/queue.h"
+
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+#include "event-internal.h"
+#include "defer-internal.h"
+#include "regress.h"
+#include "tinytest_macros.h"
+
+#ifdef _EVENT_HAVE_PTHREADS
+#define THREAD_T pthread_t
+#define THREAD_FN void *
+#define THREAD_RETURN() return (NULL)
+#define THREAD_START(threadvar, fn, arg) \
+       pthread_create(&(threadvar), NULL, fn, arg)
+#define THREAD_JOIN(th) pthread_join(th, NULL)
+#else
+#define THREAD_T HANDLE
+#define THREAD_FN unsigned __stdcall
+#define THREAD_RETURN() return (0)
+#define THREAD_START(threadvar, fn, arg) do {          \
+       uintptr_t threadhandle = _beginthreadex(NULL,0,fn,(arg),0,NULL); \
+       (threadvar) = (HANDLE) threadhandle; \
+       } while (0)
+#define THREAD_JOIN(th) WaitForSingleObject(th, INFINITE)
+#endif
+
+struct cond_wait {
+       void *lock;
+       void *cond;
+};
+
+static void
+wake_all_timeout(evutil_socket_t fd, short what, void *arg)
+{
+       struct cond_wait *cw = arg;
+       EVLOCK_LOCK(cw->lock, 0);
+       EVTHREAD_COND_BROADCAST(cw->cond);
+       EVLOCK_UNLOCK(cw->lock, 0);
+
+}
+
+static void
+wake_one_timeout(evutil_socket_t fd, short what, void *arg)
+{
+       struct cond_wait *cw = arg;
+       EVLOCK_LOCK(cw->lock, 0);
+       EVTHREAD_COND_SIGNAL(cw->cond);
+       EVLOCK_UNLOCK(cw->lock, 0);
+}
+
+#define NUM_THREADS    100
+#define NUM_ITERATIONS  100
+void *count_lock;
+static int count;
+
+static THREAD_FN
+basic_thread(void *arg)
+{
+       struct cond_wait cw;
+       struct event_base *base = arg;
+       struct event ev;
+       int i = 0;
+
+       EVTHREAD_ALLOC_LOCK(cw.lock, 0);
+       EVTHREAD_ALLOC_COND(cw.cond);
+       assert(cw.lock);
+       assert(cw.cond);
+
+       evtimer_assign(&ev, base, wake_all_timeout, &cw);
+       for (i = 0; i < NUM_ITERATIONS; i++) {
+               struct timeval tv;
+               evutil_timerclear(&tv);
+               tv.tv_sec = 0;
+               tv.tv_usec = 3000;
+
+               EVLOCK_LOCK(cw.lock, 0);
+               /* we need to make sure that event does not happen before
+                * we get to wait on the conditional variable */
+               assert(evtimer_add(&ev, &tv) == 0);
+
+               assert(EVTHREAD_COND_WAIT(cw.cond, cw.lock) == 0);
+               EVLOCK_UNLOCK(cw.lock, 0);
+
+               EVLOCK_LOCK(count_lock, 0);
+               ++count;
+               EVLOCK_UNLOCK(count_lock, 0);
+       }
+
+       /* exit the loop only if all threads fired all timeouts */
+       EVLOCK_LOCK(count_lock, 0);
+       if (count >= NUM_THREADS * NUM_ITERATIONS)
+               event_base_loopexit(base, NULL);
+       EVLOCK_UNLOCK(count_lock, 0);
+
+       EVTHREAD_FREE_LOCK(cw.lock, 0);
+       EVTHREAD_FREE_COND(cw.cond);
+
+       THREAD_RETURN();
+}
+
+static int notification_fd_used = 0;
+#ifndef WIN32
+static int got_sigchld = 0;
+static void
+sigchld_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct timeval tv;
+       struct event_base *base = arg;
+
+       got_sigchld++;
+       tv.tv_usec = 100000;
+       tv.tv_sec = 0;
+       event_base_loopexit(base, &tv);
+}
+
+
+static void
+notify_fd_cb(evutil_socket_t fd, short event, void *arg)
+{
+       ++notification_fd_used;
+}
+#endif
+
+static void
+thread_basic(void *arg)
+{
+       THREAD_T threads[NUM_THREADS];
+       struct event ev;
+       struct timeval tv;
+       int i;
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+
+       struct event *notification_event = NULL;
+       struct event *sigchld_event = NULL;
+
+       EVTHREAD_ALLOC_LOCK(count_lock, 0);
+       tt_assert(count_lock);
+
+       tt_assert(base);
+       if (evthread_make_base_notifiable(base)<0) {
+               tt_abort_msg("Couldn't make base notifiable!");
+       }
+
+#ifndef WIN32
+       if (data->setup_data && !strcmp(data->setup_data, "forking")) {
+               pid_t pid;
+               int status;
+               sigchld_event = evsignal_new(base, SIGCHLD, sigchld_cb, base);
+               /* This piggybacks on the th_notify_fd weirdly, and looks
+                * inside libevent internals.  Not a good idea in non-testing
+                * code! */
+               notification_event = event_new(base,
+                   base->th_notify_fd[0], EV_READ|EV_PERSIST, notify_fd_cb,
+                   NULL);
+               event_add(sigchld_event, NULL);
+               event_add(notification_event, NULL);
+
+               if ((pid = fork()) == 0) {
+                       event_del(notification_event);
+                       if (event_reinit(base) < 0) {
+                               TT_FAIL(("reinit"));
+                               exit(1);
+                       }
+                       event_assign(notification_event, base,
+                           base->th_notify_fd[0], EV_READ|EV_PERSIST,
+                           notify_fd_cb, NULL);
+                       event_add(notification_event, NULL);
+                       goto child;
+               }
+
+               event_base_dispatch(base);
+
+               if (waitpid(pid, &status, 0) == -1)
+                       tt_abort_perror("waitpid");
+               TT_BLATHER(("Waitpid okay\n"));
+
+               tt_assert(got_sigchld);
+               tt_int_op(notification_fd_used, ==, 0);
+
+               goto end;
+       }
+
+child:
+#endif
+       for (i = 0; i < NUM_THREADS; ++i)
+               THREAD_START(threads[i], basic_thread, base);
+
+       evtimer_assign(&ev, base, NULL, NULL);
+       evutil_timerclear(&tv);
+       tv.tv_sec = 1000;
+       event_add(&ev, &tv);
+
+       event_base_dispatch(base);
+
+       for (i = 0; i < NUM_THREADS; ++i)
+               THREAD_JOIN(threads[i]);
+
+       event_del(&ev);
+
+       tt_int_op(count, ==, NUM_THREADS * NUM_ITERATIONS);
+
+       EVTHREAD_FREE_LOCK(count_lock, 0);
+
+       TT_BLATHER(("notifiations==%d", notification_fd_used));
+
+end:
+
+       if (notification_event)
+               event_free(notification_event);
+       if (sigchld_event)
+               event_free(sigchld_event);
+}
+
+#undef NUM_THREADS
+#define NUM_THREADS 10
+
+struct alerted_record {
+       struct cond_wait *cond;
+       struct timeval delay;
+       struct timeval alerted_at;
+       int timed_out;
+};
+
+static THREAD_FN
+wait_for_condition(void *arg)
+{
+       struct alerted_record *rec = arg;
+       int r;
+
+       EVLOCK_LOCK(rec->cond->lock, 0);
+       if (rec->delay.tv_sec || rec->delay.tv_usec) {
+               r = EVTHREAD_COND_WAIT_TIMED(rec->cond->cond, rec->cond->lock,
+                   &rec->delay);
+       } else {
+               r = EVTHREAD_COND_WAIT(rec->cond->cond, rec->cond->lock);
+       }
+       EVLOCK_UNLOCK(rec->cond->lock, 0);
+
+       evutil_gettimeofday(&rec->alerted_at, NULL);
+       if (r == 1)
+               rec->timed_out = 1;
+
+       THREAD_RETURN();
+}
+
+static void
+thread_conditions_simple(void *arg)
+{
+       struct timeval tv_signal, tv_timeout, tv_broadcast;
+       struct alerted_record alerted[NUM_THREADS];
+       THREAD_T threads[NUM_THREADS];
+       struct cond_wait cond;
+       int i;
+       struct timeval launched_at;
+       struct event wake_one;
+       struct event wake_all;
+       struct basic_test_data *data = arg;
+       struct event_base *base = data->base;
+       int n_timed_out=0, n_signal=0, n_broadcast=0;
+
+       tv_signal.tv_sec = tv_timeout.tv_sec = tv_broadcast.tv_sec = 0;
+       tv_signal.tv_usec = 30*1000;
+       tv_timeout.tv_usec = 150*1000;
+       tv_broadcast.tv_usec = 500*1000;
+
+       EVTHREAD_ALLOC_LOCK(cond.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+       EVTHREAD_ALLOC_COND(cond.cond);
+       tt_assert(cond.lock);
+       tt_assert(cond.cond);
+       for (i = 0; i < NUM_THREADS; ++i) {
+               memset(&alerted[i], 0, sizeof(struct alerted_record));
+               alerted[i].cond = &cond;
+       }
+
+       /* Threads 5 and 6 will be allowed to time out */
+       memcpy(&alerted[5].delay, &tv_timeout, sizeof(tv_timeout));
+       memcpy(&alerted[6].delay, &tv_timeout, sizeof(tv_timeout));
+
+       evtimer_assign(&wake_one, base, wake_one_timeout, &cond);
+       evtimer_assign(&wake_all, base, wake_all_timeout, &cond);
+
+       evutil_gettimeofday(&launched_at, NULL);
+
+       /* Launch the threads... */
+       for (i = 0; i < NUM_THREADS; ++i) {
+               THREAD_START(threads[i], wait_for_condition, &alerted[i]);
+       }
+
+       /* Start the timers... */
+       tt_int_op(event_add(&wake_one, &tv_signal), ==, 0);
+       tt_int_op(event_add(&wake_all, &tv_broadcast), ==, 0);
+
+       /* And run for a bit... */
+       event_base_dispatch(base);
+
+       /* And wait till the threads are done. */
+       for (i = 0; i < NUM_THREADS; ++i)
+               THREAD_JOIN(threads[i]);
+
+       /* Now, let's see what happened. At least one of 5 or 6 should
+        * have timed out. */
+       n_timed_out = alerted[5].timed_out + alerted[6].timed_out;
+       tt_int_op(n_timed_out, >=, 1);
+       tt_int_op(n_timed_out, <=, 2);
+
+       for (i = 0; i < NUM_THREADS; ++i) {
+               const struct timeval *target_delay;
+               struct timeval target_time, actual_delay;
+               if (alerted[i].timed_out) {
+                       TT_BLATHER(("%d looks like a timeout\n", i));
+                       target_delay = &tv_timeout;
+                       tt_assert(i == 5 || i == 6);
+               } else if (evutil_timerisset(&alerted[i].alerted_at)) {
+                       long diff1,diff2;
+                       evutil_timersub(&alerted[i].alerted_at,
+                           &launched_at, &actual_delay);
+                       diff1 = timeval_msec_diff(&actual_delay,
+                           &tv_signal);
+                       diff2 = timeval_msec_diff(&actual_delay,
+                           &tv_broadcast);
+                       if (abs(diff1) < abs(diff2)) {
+                               TT_BLATHER(("%d looks like a signal\n", i));
+                               target_delay = &tv_signal;
+                               ++n_signal;
+                       } else {
+                               TT_BLATHER(("%d looks like a broadcast\n", i));
+                               target_delay = &tv_broadcast;
+                               ++n_broadcast;
+                       }
+               } else {
+                       TT_FAIL(("Thread %d never got woken", i));
+                       continue;
+               }
+               evutil_timeradd(target_delay, &launched_at, &target_time);
+               test_timeval_diff_leq(&target_time, &alerted[i].alerted_at,
+                   0, 50);
+       }
+       tt_int_op(n_broadcast + n_signal + n_timed_out, ==, NUM_THREADS);
+       tt_int_op(n_signal, ==, 1);
+
+end:
+       ;
+}
+
+#define CB_COUNT 128
+#define QUEUE_THREAD_COUNT 8
+
+#ifdef WIN32
+#define SLEEP_MS(ms) Sleep(ms)
+#else
+#define SLEEP_MS(ms) usleep((ms) * 1000)
+#endif
+
+struct deferred_test_data {
+       struct deferred_cb cbs[CB_COUNT];
+       struct deferred_cb_queue *queue;
+};
+
+static time_t timer_start = 0;
+static time_t timer_end = 0;
+static unsigned callback_count = 0;
+static THREAD_T load_threads[QUEUE_THREAD_COUNT];
+static struct deferred_test_data deferred_data[QUEUE_THREAD_COUNT];
+
+static void
+deferred_callback(struct deferred_cb *cb, void *arg)
+{
+       SLEEP_MS(1);
+       callback_count += 1;
+}
+
+static THREAD_FN
+load_deferred_queue(void *arg)
+{
+       struct deferred_test_data *data = arg;
+       size_t i;
+
+       for (i = 0; i < CB_COUNT; ++i) {
+               event_deferred_cb_init(&data->cbs[i], deferred_callback, NULL);
+               event_deferred_cb_schedule(data->queue, &data->cbs[i]);
+               SLEEP_MS(1);
+       }
+
+       THREAD_RETURN();
+}
+
+static void
+timer_callback(evutil_socket_t fd, short what, void *arg)
+{
+       timer_end = time(NULL);
+}
+
+static void
+start_threads_callback(evutil_socket_t fd, short what, void *arg)
+{
+       int i;
+
+       for (i = 0; i < QUEUE_THREAD_COUNT; ++i) {
+               THREAD_START(load_threads[i], load_deferred_queue,
+                               &deferred_data[i]);
+       }
+}
+
+static void
+thread_deferred_cb_skew(void *arg)
+{
+       struct basic_test_data *data = arg;
+       struct timeval tv_timer = {4, 0};
+       struct deferred_cb_queue *queue;
+       time_t elapsed;
+       int i;
+
+       queue = event_base_get_deferred_cb_queue(data->base);
+       tt_assert(queue);
+
+       for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
+               deferred_data[i].queue = queue;
+
+       timer_start = time(NULL);
+       event_base_once(data->base, -1, EV_TIMEOUT, timer_callback, NULL,
+                       &tv_timer);
+       event_base_once(data->base, -1, EV_TIMEOUT, start_threads_callback,
+                       NULL, NULL);
+       event_base_dispatch(data->base);
+
+       elapsed = timer_end - timer_start;
+       TT_BLATHER(("callback count, %u", callback_count));
+       TT_BLATHER(("elapsed time, %u", (unsigned)elapsed));
+       /* XXX be more intelligent here.  just make sure skew is
+        * within 2 seconds for now. */
+       tt_assert(elapsed >= 4 && elapsed <= 6);
+
+end:
+       for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
+               THREAD_JOIN(load_threads[i]);
+}
+
+#define TEST(name)                                                     \
+       { #name, thread_##name, TT_FORK|TT_NEED_THREADS|TT_NEED_BASE,   \
+         &basic_setup, NULL }
+
+struct testcase_t thread_testcases[] = {
+       { "basic", thread_basic, TT_FORK|TT_NEED_THREADS|TT_NEED_BASE,
+         &basic_setup, NULL },
+#ifndef WIN32
+       { "forking", thread_basic, TT_FORK|TT_NEED_THREADS|TT_NEED_BASE,
+         &basic_setup, (char*)"forking" },
+#endif
+       TEST(conditions_simple),
+       TEST(deferred_cb_skew),
+       END_OF_TESTCASES
+};
+
diff --git a/libevent/test/regress_util.c b/libevent/test/regress_util.c
new file mode 100644 (file)
index 0000000..88d8057
--- /dev/null
@@ -0,0 +1,1094 @@
+/*
+ * Copyright (c) 2009-2012 Nick Mathewson and Niels Provos
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <ws2tcpip.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+
+#ifndef WIN32
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#endif
+#ifdef _EVENT_HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "event2/event.h"
+#include "event2/util.h"
+#include "../ipv6-internal.h"
+#include "../util-internal.h"
+#include "../log-internal.h"
+#include "../strlcpy-internal.h"
+
+#include "regress.h"
+
+enum entry_status { NORMAL, CANONICAL, BAD };
+
+/* This is a big table of results we expect from generating and parsing */
+static struct ipv4_entry {
+       const char *addr;
+       ev_uint32_t res;
+       enum entry_status status;
+} ipv4_entries[] = {
+       { "1.2.3.4", 0x01020304u, CANONICAL },
+       { "255.255.255.255", 0xffffffffu, CANONICAL },
+       { "256.0.0.0", 0, BAD },
+       { "ABC", 0, BAD },
+       { "1.2.3.4.5", 0, BAD },
+       { "176.192.208.244", 0xb0c0d0f4, CANONICAL },
+       { NULL, 0, BAD },
+};
+
+static struct ipv6_entry {
+       const char *addr;
+       ev_uint32_t res[4];
+       enum entry_status status;
+} ipv6_entries[] = {
+       { "::", { 0, 0, 0, 0, }, CANONICAL },
+       { "0:0:0:0:0:0:0:0", { 0, 0, 0, 0, }, NORMAL },
+       { "::1", { 0, 0, 0, 1, }, CANONICAL },
+       { "::1.2.3.4", { 0, 0, 0, 0x01020304, }, CANONICAL },
+       { "ffff:1::", { 0xffff0001u, 0, 0, 0, }, CANONICAL },
+       { "ffff:0000::", { 0xffff0000u, 0, 0, 0, }, NORMAL },
+       { "ffff::1234", { 0xffff0000u, 0, 0, 0x1234, }, CANONICAL },
+       { "0102::1.2.3.4", {0x01020000u, 0, 0, 0x01020304u }, NORMAL },
+       { "::9:c0a8:1:1", { 0, 0, 0x0009c0a8u, 0x00010001u }, CANONICAL },
+       { "::ffff:1.2.3.4", { 0, 0, 0x000ffffu, 0x01020304u }, CANONICAL },
+       { "FFFF::", { 0xffff0000u, 0, 0, 0 }, NORMAL },
+       { "foobar.", { 0, 0, 0, 0 }, BAD },
+       { "foobar", { 0, 0, 0, 0 }, BAD },
+       { "fo:obar", { 0, 0, 0, 0 }, BAD },
+       { "ffff", { 0, 0, 0, 0 }, BAD },
+       { "fffff::", { 0, 0, 0, 0 }, BAD },
+       { "fffff::", { 0, 0, 0, 0 }, BAD },
+       { "::1.0.1.1000", { 0, 0, 0, 0 }, BAD },
+       { "1:2:33333:4::", { 0, 0, 0, 0 }, BAD },
+       { "1:2:3:4:5:6:7:8:9", { 0, 0, 0, 0 }, BAD },
+       { "1::2::3", { 0, 0, 0, 0 }, BAD },
+       { ":::1", { 0, 0, 0, 0 }, BAD },
+       { NULL, { 0, 0, 0, 0,  }, BAD },
+};
+
+static void
+regress_ipv4_parse(void *ptr)
+{
+       int i;
+       for (i = 0; ipv4_entries[i].addr; ++i) {
+               char written[128];
+               struct ipv4_entry *ent = &ipv4_entries[i];
+               struct in_addr in;
+               int r;
+               r = evutil_inet_pton(AF_INET, ent->addr, &in);
+               if (r == 0) {
+                       if (ent->status != BAD) {
+                               TT_FAIL(("%s did not parse, but it's a good address!",
+                                       ent->addr));
+                       }
+                       continue;
+               }
+               if (ent->status == BAD) {
+                       TT_FAIL(("%s parsed, but we expected an error", ent->addr));
+                       continue;
+               }
+               if (ntohl(in.s_addr) != ent->res) {
+                       TT_FAIL(("%s parsed to %lx, but we expected %lx", ent->addr,
+                               (unsigned long)ntohl(in.s_addr),
+                               (unsigned long)ent->res));
+                       continue;
+               }
+               if (ent->status == CANONICAL) {
+                       const char *w = evutil_inet_ntop(AF_INET, &in, written,
+                                                                                        sizeof(written));
+                       if (!w) {
+                               TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
+                               continue;
+                       }
+                       if (strcmp(written, ent->addr)) {
+                               TT_FAIL(("Tried to write out %s; got %s",
+                                       ent->addr, written));
+                               continue;
+                       }
+               }
+
+       }
+
+}
+
+static void
+regress_ipv6_parse(void *ptr)
+{
+#ifdef AF_INET6
+       int i, j;
+
+       for (i = 0; ipv6_entries[i].addr; ++i) {
+               char written[128];
+               struct ipv6_entry *ent = &ipv6_entries[i];
+               struct in6_addr in6;
+               int r;
+               r = evutil_inet_pton(AF_INET6, ent->addr, &in6);
+               if (r == 0) {
+                       if (ent->status != BAD)
+                               TT_FAIL(("%s did not parse, but it's a good address!",
+                                       ent->addr));
+                       continue;
+               }
+               if (ent->status == BAD) {
+                       TT_FAIL(("%s parsed, but we expected an error", ent->addr));
+                       continue;
+               }
+               for (j = 0; j < 4; ++j) {
+                       /* Can't use s6_addr32 here; some don't have it. */
+                       ev_uint32_t u =
+                               (in6.s6_addr[j*4  ] << 24) |
+                               (in6.s6_addr[j*4+1] << 16) |
+                               (in6.s6_addr[j*4+2] << 8) |
+                               (in6.s6_addr[j*4+3]);
+                       if (u != ent->res[j]) {
+                               TT_FAIL(("%s did not parse as expected.", ent->addr));
+                               continue;
+                       }
+               }
+               if (ent->status == CANONICAL) {
+                       const char *w = evutil_inet_ntop(AF_INET6, &in6, written,
+                                                                                        sizeof(written));
+                       if (!w) {
+                               TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
+                               continue;
+                       }
+                       if (strcmp(written, ent->addr)) {
+                               TT_FAIL(("Tried to write out %s; got %s", ent->addr, written));
+                               continue;
+                       }
+               }
+
+       }
+#else
+       TT_BLATHER(("Skipping IPv6 address parsing."));
+#endif
+}
+
+static struct sa_port_ent {
+       const char *parse;
+       int safamily;
+       const char *addr;
+       int port;
+} sa_port_ents[] = {
+       { "[ffff::1]:1000", AF_INET6, "ffff::1", 1000 },
+       { "[ffff::1]", AF_INET6, "ffff::1", 0 },
+       { "[ffff::1", 0, NULL, 0 },
+       { "[ffff::1]:65599", 0, NULL, 0 },
+       { "[ffff::1]:0", 0, NULL, 0 },
+       { "[ffff::1]:-1", 0, NULL, 0 },
+       { "::1", AF_INET6, "::1", 0 },
+       { "1:2::1", AF_INET6, "1:2::1", 0 },
+       { "192.168.0.1:50", AF_INET, "192.168.0.1", 50 },
+       { "1.2.3.4", AF_INET, "1.2.3.4", 0 },
+       { NULL, 0, NULL, 0 },
+};
+
+static void
+regress_sockaddr_port_parse(void *ptr)
+{
+       struct sockaddr_storage ss;
+       int i, r;
+
+       for (i = 0; sa_port_ents[i].parse; ++i) {
+               struct sa_port_ent *ent = &sa_port_ents[i];
+               int len = sizeof(ss);
+               memset(&ss, 0, sizeof(ss));
+               r = evutil_parse_sockaddr_port(ent->parse, (struct sockaddr*)&ss, &len);
+               if (r < 0) {
+                       if (ent->safamily)
+                               TT_FAIL(("Couldn't parse %s!", ent->parse));
+                       continue;
+               } else if (! ent->safamily) {
+                       TT_FAIL(("Shouldn't have been able to parse %s!", ent->parse));
+                       continue;
+               }
+               if (ent->safamily == AF_INET) {
+                       struct sockaddr_in sin;
+                       memset(&sin, 0, sizeof(sin));
+#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+                       sin.sin_len = sizeof(sin);
+#endif
+                       sin.sin_family = AF_INET;
+                       sin.sin_port = htons(ent->port);
+                       r = evutil_inet_pton(AF_INET, ent->addr, &sin.sin_addr);
+                       if (1 != r) {
+                               TT_FAIL(("Couldn't parse ipv4 target %s.", ent->addr));
+                       } else if (memcmp(&sin, &ss, sizeof(sin))) {
+                               TT_FAIL(("Parse for %s was not as expected.", ent->parse));
+                       } else if (len != sizeof(sin)) {
+                               TT_FAIL(("Length for %s not as expected.",ent->parse));
+                       }
+               } else {
+                       struct sockaddr_in6 sin6;
+                       memset(&sin6, 0, sizeof(sin6));
+#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+                       sin6.sin6_len = sizeof(sin6);
+#endif
+                       sin6.sin6_family = AF_INET6;
+                       sin6.sin6_port = htons(ent->port);
+                       r = evutil_inet_pton(AF_INET6, ent->addr, &sin6.sin6_addr);
+                       if (1 != r) {
+                               TT_FAIL(("Couldn't parse ipv6 target %s.", ent->addr));
+                       } else if (memcmp(&sin6, &ss, sizeof(sin6))) {
+                               TT_FAIL(("Parse for %s was not as expected.", ent->parse));
+                       } else if (len != sizeof(sin6)) {
+                               TT_FAIL(("Length for %s not as expected.",ent->parse));
+                       }
+               }
+       }
+}
+
+
+static void
+regress_sockaddr_port_format(void *ptr)
+{
+       struct sockaddr_storage ss;
+       int len;
+       const char *cp;
+       char cbuf[128];
+       int r;
+
+       len = sizeof(ss);
+       r = evutil_parse_sockaddr_port("192.168.1.1:80",
+           (struct sockaddr*)&ss, &len);
+       tt_int_op(r,==,0);
+       cp = evutil_format_sockaddr_port(
+               (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
+       tt_ptr_op(cp,==,cbuf);
+       tt_str_op(cp,==,"192.168.1.1:80");
+
+       len = sizeof(ss);
+       r = evutil_parse_sockaddr_port("[ff00::8010]:999",
+           (struct sockaddr*)&ss, &len);
+       tt_int_op(r,==,0);
+       cp = evutil_format_sockaddr_port(
+               (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
+       tt_ptr_op(cp,==,cbuf);
+       tt_str_op(cp,==,"[ff00::8010]:999");
+
+       ss.ss_family=99;
+       cp = evutil_format_sockaddr_port(
+               (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
+       tt_ptr_op(cp,==,cbuf);
+       tt_str_op(cp,==,"<addr with socktype 99>");
+end:
+       ;
+}
+
+static struct sa_pred_ent {
+       const char *parse;
+
+       int is_loopback;
+} sa_pred_entries[] = {
+       { "127.0.0.1",   1 },
+       { "127.0.3.2",   1 },
+       { "128.1.2.3",   0 },
+       { "18.0.0.1",    0 },
+       { "129.168.1.1", 0 },
+
+       { "::1",         1 },
+       { "::0",         0 },
+       { "f::1",        0 },
+       { "::501",       0 },
+       { NULL,          0 },
+
+};
+
+static void
+test_evutil_sockaddr_predicates(void *ptr)
+{
+       struct sockaddr_storage ss;
+       int r, i;
+
+       for (i=0; sa_pred_entries[i].parse; ++i) {
+               struct sa_pred_ent *ent = &sa_pred_entries[i];
+               int len = sizeof(ss);
+
+               r = evutil_parse_sockaddr_port(ent->parse, (struct sockaddr*)&ss, &len);
+
+               if (r<0) {
+                       TT_FAIL(("Couldn't parse %s!", ent->parse));
+                       continue;
+               }
+
+               /* sockaddr_is_loopback */
+               if (ent->is_loopback != evutil_sockaddr_is_loopback((struct sockaddr*)&ss)) {
+                       TT_FAIL(("evutil_sockaddr_loopback(%s) not as expected",
+                               ent->parse));
+               }
+       }
+}
+
+static void
+test_evutil_strtoll(void *ptr)
+{
+       const char *s;
+       char *endptr;
+
+       tt_want(evutil_strtoll("5000000000", NULL, 10) ==
+               ((ev_int64_t)5000000)*1000);
+       tt_want(evutil_strtoll("-5000000000", NULL, 10) ==
+               ((ev_int64_t)5000000)*-1000);
+       s = " 99999stuff";
+       tt_want(evutil_strtoll(s, &endptr, 10) == (ev_int64_t)99999);
+       tt_want(endptr == s+6);
+       tt_want(evutil_strtoll("foo", NULL, 10) == 0);
+ }
+
+static void
+test_evutil_snprintf(void *ptr)
+{
+       char buf[16];
+       int r;
+       ev_uint64_t u64 = ((ev_uint64_t)1000000000)*200;
+       ev_int64_t i64 = -1 * (ev_int64_t) u64;
+       size_t size = 8000;
+       ev_ssize_t ssize = -9000;
+
+       r = evutil_snprintf(buf, sizeof(buf), "%d %d", 50, 100);
+       tt_str_op(buf, ==, "50 100");
+       tt_int_op(r, ==, 6);
+
+       r = evutil_snprintf(buf, sizeof(buf), "longish %d", 1234567890);
+       tt_str_op(buf, ==, "longish 1234567");
+       tt_int_op(r, ==, 18);
+
+       r = evutil_snprintf(buf, sizeof(buf), EV_U64_FMT, EV_U64_ARG(u64));
+       tt_str_op(buf, ==, "200000000000");
+       tt_int_op(r, ==, 12);
+
+       r = evutil_snprintf(buf, sizeof(buf), EV_I64_FMT, EV_I64_ARG(i64));
+       tt_str_op(buf, ==, "-200000000000");
+       tt_int_op(r, ==, 13);
+
+       r = evutil_snprintf(buf, sizeof(buf), EV_SIZE_FMT" "EV_SSIZE_FMT,
+           EV_SIZE_ARG(size), EV_SSIZE_ARG(ssize));
+       tt_str_op(buf, ==, "8000 -9000");
+       tt_int_op(r, ==, 10);
+
+      end:
+       ;
+}
+
+static void
+test_evutil_casecmp(void *ptr)
+{
+       tt_int_op(evutil_ascii_strcasecmp("ABC", "ABC"), ==, 0);
+       tt_int_op(evutil_ascii_strcasecmp("ABC", "abc"), ==, 0);
+       tt_int_op(evutil_ascii_strcasecmp("ABC", "abcd"), <, 0);
+       tt_int_op(evutil_ascii_strcasecmp("ABC", "abb"), >, 0);
+       tt_int_op(evutil_ascii_strcasecmp("ABCd", "abc"), >, 0);
+
+       tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEvEnT", 100), ==, 0);
+       tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEvEnT", 4), ==, 0);
+       tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEXXXX", 4), ==, 0);
+       tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibE", 4), ==, 0);
+       tt_int_op(evutil_ascii_strncasecmp("Libe", "LibEvEnT", 4), ==, 0);
+       tt_int_op(evutil_ascii_strncasecmp("Lib", "LibEvEnT", 4), <, 0);
+       tt_int_op(evutil_ascii_strncasecmp("abc", "def", 99), <, 0);
+       tt_int_op(evutil_ascii_strncasecmp("Z", "qrst", 1), >, 0);
+end:
+       ;
+}
+
+static int logsev = 0;
+static char *logmsg = NULL;
+
+static void
+logfn(int severity, const char *msg)
+{
+       logsev = severity;
+       tt_want(msg);
+       if (msg) {
+               if (logmsg)
+                       free(logmsg);
+               logmsg = strdup(msg);
+       }
+}
+
+static int fatal_want_severity = 0;
+static const char *fatal_want_message = NULL;
+static void
+fatalfn(int exitcode)
+{
+       if (logsev != fatal_want_severity ||
+           !logmsg ||
+           strcmp(logmsg, fatal_want_message))
+               exit(0);
+       else
+               exit(exitcode);
+}
+
+#ifndef WIN32
+#define CAN_CHECK_ERR
+static void
+check_error_logging(void (*fn)(void), int wantexitcode,
+    int wantseverity, const char *wantmsg)
+{
+       pid_t pid;
+       int status = 0, exitcode;
+       fatal_want_severity = wantseverity;
+       fatal_want_message = wantmsg;
+       if ((pid = fork()) == 0) {
+               /* child process */
+               fn();
+               exit(0); /* should be unreachable. */
+       } else {
+               wait(&status);
+               exitcode = WEXITSTATUS(status);
+               tt_int_op(wantexitcode, ==, exitcode);
+       }
+end:
+       ;
+}
+
+static void
+errx_fn(void)
+{
+       event_errx(2, "Fatal error; too many kumquats (%d)", 5);
+}
+
+static void
+err_fn(void)
+{
+       errno = ENOENT;
+       event_err(5,"Couldn't open %s", "/very/bad/file");
+}
+
+static void
+sock_err_fn(void)
+{
+       evutil_socket_t fd = socket(AF_INET, SOCK_STREAM, 0);
+#ifdef WIN32
+       EVUTIL_SET_SOCKET_ERROR(WSAEWOULDBLOCK);
+#else
+       errno = EAGAIN;
+#endif
+       event_sock_err(20, fd, "Unhappy socket");
+}
+#endif
+
+static void
+test_evutil_log(void *ptr)
+{
+       evutil_socket_t fd = -1;
+       char buf[128];
+
+       event_set_log_callback(logfn);
+       event_set_fatal_callback(fatalfn);
+#define RESET() do {                           \
+               logsev = 0;     \
+               if (logmsg) free(logmsg);       \
+               logmsg = NULL;                  \
+       } while (0)
+#define LOGEQ(sev,msg) do {                    \
+               tt_int_op(logsev,==,sev);       \
+               tt_assert(logmsg != NULL);      \
+               tt_str_op(logmsg,==,msg);       \
+       } while (0)
+
+#ifdef CAN_CHECK_ERR
+       /* We need to disable these tests for now.  Previously, the logging
+        * module didn't enforce the requirement that a fatal callback
+        * actually exit.  Now, it exits no matter what, so if we wan to
+        * reinstate these tests, we'll need to fork for each one. */
+       check_error_logging(errx_fn, 2, _EVENT_LOG_ERR,
+           "Fatal error; too many kumquats (5)");
+       RESET();
+#endif
+
+       event_warnx("Far too many %s (%d)", "wombats", 99);
+       LOGEQ(_EVENT_LOG_WARN, "Far too many wombats (99)");
+       RESET();
+
+       event_msgx("Connecting lime to coconut");
+       LOGEQ(_EVENT_LOG_MSG, "Connecting lime to coconut");
+       RESET();
+
+       event_debug(("A millisecond passed! We should log that!"));
+#ifdef USE_DEBUG
+       LOGEQ(_EVENT_LOG_DEBUG, "A millisecond passed! We should log that!");
+#else
+       tt_int_op(logsev,==,0);
+       tt_ptr_op(logmsg,==,NULL);
+#endif
+       RESET();
+
+       /* Try with an errno. */
+       errno = ENOENT;
+       event_warn("Couldn't open %s", "/bad/file");
+       evutil_snprintf(buf, sizeof(buf),
+           "Couldn't open /bad/file: %s",strerror(ENOENT));
+       LOGEQ(_EVENT_LOG_WARN,buf);
+       RESET();
+
+#ifdef CAN_CHECK_ERR
+       evutil_snprintf(buf, sizeof(buf),
+           "Couldn't open /very/bad/file: %s",strerror(ENOENT));
+       check_error_logging(err_fn, 5, _EVENT_LOG_ERR, buf);
+       RESET();
+#endif
+
+       /* Try with a socket errno. */
+       fd = socket(AF_INET, SOCK_STREAM, 0);
+#ifdef WIN32
+       evutil_snprintf(buf, sizeof(buf),
+           "Unhappy socket: %s",
+           evutil_socket_error_to_string(WSAEWOULDBLOCK));
+       EVUTIL_SET_SOCKET_ERROR(WSAEWOULDBLOCK);
+#else
+       evutil_snprintf(buf, sizeof(buf),
+           "Unhappy socket: %s", strerror(EAGAIN));
+       errno = EAGAIN;
+#endif
+       event_sock_warn(fd, "Unhappy socket");
+       LOGEQ(_EVENT_LOG_WARN, buf);
+       RESET();
+
+#ifdef CAN_CHECK_ERR
+       check_error_logging(sock_err_fn, 20, _EVENT_LOG_ERR, buf);
+       RESET();
+#endif
+
+#undef RESET
+#undef LOGEQ
+end:
+       if (logmsg)
+               free(logmsg);
+       if (fd >= 0)
+               evutil_closesocket(fd);
+}
+
+static void
+test_evutil_strlcpy(void *arg)
+{
+       char buf[8];
+
+       /* Successful case. */
+       tt_int_op(5, ==, strlcpy(buf, "Hello", sizeof(buf)));
+       tt_str_op(buf, ==, "Hello");
+
+       /* Overflow by a lot. */
+       tt_int_op(13, ==, strlcpy(buf, "pentasyllabic", sizeof(buf)));
+       tt_str_op(buf, ==, "pentasy");
+
+       /* Overflow by exactly one. */
+       tt_int_op(8, ==, strlcpy(buf, "overlong", sizeof(buf)));
+       tt_str_op(buf, ==, "overlon");
+end:
+       ;
+}
+
+struct example_struct {
+       const char *a;
+       const char *b;
+       long c;
+};
+
+static void
+test_evutil_upcast(void *arg)
+{
+       struct example_struct es1;
+       const char **cp;
+       es1.a = "World";
+       es1.b = "Hello";
+       es1.c = -99;
+
+       tt_int_op(evutil_offsetof(struct example_struct, b), ==, sizeof(char*));
+
+       cp = &es1.b;
+       tt_ptr_op(EVUTIL_UPCAST(cp, struct example_struct, b), ==, &es1);
+
+end:
+       ;
+}
+
+static void
+test_evutil_integers(void *arg)
+{
+       ev_int64_t i64;
+       ev_uint64_t u64;
+       ev_int32_t i32;
+       ev_uint32_t u32;
+       ev_int16_t i16;
+       ev_uint16_t u16;
+       ev_int8_t  i8;
+       ev_uint8_t  u8;
+
+       void *ptr;
+       ev_intptr_t iptr;
+       ev_uintptr_t uptr;
+
+       ev_ssize_t ssize;
+
+       tt_int_op(sizeof(u64), ==, 8);
+       tt_int_op(sizeof(i64), ==, 8);
+       tt_int_op(sizeof(u32), ==, 4);
+       tt_int_op(sizeof(i32), ==, 4);
+       tt_int_op(sizeof(u16), ==, 2);
+       tt_int_op(sizeof(i16), ==, 2);
+       tt_int_op(sizeof(u8), ==,  1);
+       tt_int_op(sizeof(i8), ==,  1);
+
+       tt_int_op(sizeof(ev_ssize_t), ==, sizeof(size_t));
+       tt_int_op(sizeof(ev_intptr_t), >=, sizeof(void *));
+       tt_int_op(sizeof(ev_uintptr_t), ==, sizeof(intptr_t));
+
+       u64 = 1000000000;
+       u64 *= 1000000000;
+       tt_assert(u64 / 1000000000 == 1000000000);
+       i64 = -1000000000;
+       i64 *= 1000000000;
+       tt_assert(i64 / 1000000000 == -1000000000);
+
+       u64 = EV_UINT64_MAX;
+       i64 = EV_INT64_MAX;
+       tt_assert(u64 > 0);
+       tt_assert(i64 > 0);
+       u64++;
+       i64++;
+       tt_assert(u64 == 0);
+       tt_assert(i64 == EV_INT64_MIN);
+       tt_assert(i64 < 0);
+
+       u32 = EV_UINT32_MAX;
+       i32 = EV_INT32_MAX;
+       tt_assert(u32 > 0);
+       tt_assert(i32 > 0);
+       u32++;
+       i32++;
+       tt_assert(u32 == 0);
+       tt_assert(i32 == EV_INT32_MIN);
+       tt_assert(i32 < 0);
+
+       u16 = EV_UINT16_MAX;
+       i16 = EV_INT16_MAX;
+       tt_assert(u16 > 0);
+       tt_assert(i16 > 0);
+       u16++;
+       i16++;
+       tt_assert(u16 == 0);
+       tt_assert(i16 == EV_INT16_MIN);
+       tt_assert(i16 < 0);
+
+       u8 = EV_UINT8_MAX;
+       i8 = EV_INT8_MAX;
+       tt_assert(u8 > 0);
+       tt_assert(i8 > 0);
+       u8++;
+       i8++;
+       tt_assert(u8 == 0);
+       tt_assert(i8 == EV_INT8_MIN);
+       tt_assert(i8 < 0);
+
+       ssize = EV_SSIZE_MAX;
+       tt_assert(ssize > 0);
+       ssize++;
+       tt_assert(ssize < 0);
+       tt_assert(ssize == EV_SSIZE_MIN);
+
+       ptr = &ssize;
+       iptr = (ev_intptr_t)ptr;
+       uptr = (ev_uintptr_t)ptr;
+       ptr = (void *)iptr;
+       tt_assert(ptr == &ssize);
+       ptr = (void *)uptr;
+       tt_assert(ptr == &ssize);
+
+       iptr = -1;
+       tt_assert(iptr < 0);
+end:
+       ;
+}
+
+struct evutil_addrinfo *
+ai_find_by_family(struct evutil_addrinfo *ai, int family)
+{
+       while (ai) {
+               if (ai->ai_family == family)
+                       return ai;
+               ai = ai->ai_next;
+       }
+       return NULL;
+}
+
+struct evutil_addrinfo *
+ai_find_by_protocol(struct evutil_addrinfo *ai, int protocol)
+{
+       while (ai) {
+               if (ai->ai_protocol == protocol)
+                       return ai;
+               ai = ai->ai_next;
+       }
+       return NULL;
+}
+
+
+int
+_test_ai_eq(const struct evutil_addrinfo *ai, const char *sockaddr_port,
+    int socktype, int protocol, int line)
+{
+       struct sockaddr_storage ss;
+       int slen = sizeof(ss);
+       int gotport;
+       char buf[128];
+       memset(&ss, 0, sizeof(ss));
+       if (socktype > 0)
+               tt_int_op(ai->ai_socktype, ==, socktype);
+       if (protocol > 0)
+               tt_int_op(ai->ai_protocol, ==, protocol);
+
+       if (evutil_parse_sockaddr_port(
+                   sockaddr_port, (struct sockaddr*)&ss, &slen)<0) {
+               TT_FAIL(("Couldn't parse expected address %s on line %d",
+                       sockaddr_port, line));
+               return -1;
+       }
+       if (ai->ai_family != ss.ss_family) {
+               TT_FAIL(("Address family %d did not match %d on line %d",
+                       ai->ai_family, ss.ss_family, line));
+               return -1;
+       }
+       if (ai->ai_addr->sa_family == AF_INET) {
+               struct sockaddr_in *sin = (struct sockaddr_in*)ai->ai_addr;
+               evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
+               gotport = ntohs(sin->sin_port);
+               if (ai->ai_addrlen != sizeof(struct sockaddr_in)) {
+                       TT_FAIL(("Addr size mismatch on line %d", line));
+                       return -1;
+               }
+       } else {
+               struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)ai->ai_addr;
+               evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, sizeof(buf));
+               gotport = ntohs(sin6->sin6_port);
+               if (ai->ai_addrlen != sizeof(struct sockaddr_in6)) {
+                       TT_FAIL(("Addr size mismatch on line %d", line));
+                       return -1;
+               }
+       }
+       if (evutil_sockaddr_cmp(ai->ai_addr, (struct sockaddr*)&ss, 1)) {
+               TT_FAIL(("Wanted %s, got %s:%d on line %d", sockaddr_port,
+                       buf, gotport, line));
+               return -1;
+       } else {
+               TT_BLATHER(("Wanted %s, got %s:%d on line %d", sockaddr_port,
+                       buf, gotport, line));
+       }
+       return 0;
+end:
+       TT_FAIL(("Test failed on line %d", line));
+       return -1;
+}
+
+static void
+test_evutil_rand(void *arg)
+{
+       char buf1[32];
+       char buf2[32];
+       int counts[256];
+       int i, j, k, n=0;
+
+       memset(buf2, 0, sizeof(buf2));
+       memset(counts, 0, sizeof(counts));
+
+       for (k=0;k<32;++k) {
+               /* Try a few different start and end points; try to catch
+                * the various misaligned cases of arc4random_buf */
+               int startpoint = _evutil_weakrand() % 4;
+               int endpoint = 32 - (_evutil_weakrand() % 4);
+
+               memset(buf2, 0, sizeof(buf2));
+
+               /* Do 6 runs over buf1, or-ing the result into buf2 each
+                * time, to make sure we're setting each byte that we mean
+                * to set. */
+               for (i=0;i<8;++i) {
+                       memset(buf1, 0, sizeof(buf1));
+                       evutil_secure_rng_get_bytes(buf1 + startpoint,
+                           endpoint-startpoint);
+                       n += endpoint - startpoint;
+                       for (j=0; j<32; ++j) {
+                               if (j >= startpoint && j < endpoint) {
+                                       buf2[j] |= buf1[j];
+                                       ++counts[(unsigned char)buf1[j]];
+                               } else {
+                                       tt_assert(buf1[j] == 0);
+                                       tt_int_op(buf1[j], ==, 0);
+
+                               }
+                       }
+               }
+
+               /* This will give a false positive with P=(256**8)==(2**64)
+                * for each character. */
+               for (j=startpoint;j<endpoint;++j) {
+                       tt_int_op(buf2[j], !=, 0);
+               }
+       }
+
+       /* for (i=0;i<256;++i) { printf("%3d %2d\n", i, counts[i]); } */
+end:
+       ;
+}
+
+static void
+test_evutil_getaddrinfo(void *arg)
+{
+       struct evutil_addrinfo *ai = NULL, *a;
+       struct evutil_addrinfo hints;
+
+       struct sockaddr_in6 *sin6;
+       struct sockaddr_in *sin;
+       char buf[128];
+       const char *cp;
+       int r;
+
+       /* Try using it as a pton. */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_STREAM;
+       r = evutil_getaddrinfo("1.2.3.4", "8080", &hints, &ai);
+       tt_int_op(r, ==, 0);
+       tt_assert(ai);
+       tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
+       test_ai_eq(ai, "1.2.3.4:8080", SOCK_STREAM, IPPROTO_TCP);
+       evutil_freeaddrinfo(ai);
+       ai = NULL;
+
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_protocol = IPPROTO_UDP;
+       r = evutil_getaddrinfo("1001:b0b::f00f", "4321", &hints, &ai);
+       tt_int_op(r, ==, 0);
+       tt_assert(ai);
+       tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
+       test_ai_eq(ai, "[1001:b0b::f00f]:4321", SOCK_DGRAM, IPPROTO_UDP);
+       evutil_freeaddrinfo(ai);
+       ai = NULL;
+
+       /* Try out the behavior of nodename=NULL */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_INET;
+       hints.ai_protocol = IPPROTO_TCP;
+       hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind */
+       r = evutil_getaddrinfo(NULL, "9999", &hints, &ai);
+       tt_int_op(r,==,0);
+       tt_assert(ai);
+       tt_ptr_op(ai->ai_next, ==, NULL);
+       test_ai_eq(ai, "0.0.0.0:9999", SOCK_STREAM, IPPROTO_TCP);
+       evutil_freeaddrinfo(ai);
+       ai = NULL;
+       hints.ai_flags = 0; /* as if for connect */
+       r = evutil_getaddrinfo(NULL, "9998", &hints, &ai);
+       tt_assert(ai);
+       tt_int_op(r,==,0);
+       test_ai_eq(ai, "127.0.0.1:9998", SOCK_STREAM, IPPROTO_TCP);
+       tt_ptr_op(ai->ai_next, ==, NULL);
+       evutil_freeaddrinfo(ai);
+       ai = NULL;
+
+       hints.ai_flags = 0; /* as if for connect */
+       hints.ai_family = PF_INET6;
+       r = evutil_getaddrinfo(NULL, "9997", &hints, &ai);
+       tt_assert(ai);
+       tt_int_op(r,==,0);
+       tt_ptr_op(ai->ai_next, ==, NULL);
+       test_ai_eq(ai, "[::1]:9997", SOCK_STREAM, IPPROTO_TCP);
+       evutil_freeaddrinfo(ai);
+       ai = NULL;
+
+       hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind. */
+       hints.ai_family = PF_INET6;
+       r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
+       tt_assert(ai);
+       tt_int_op(r,==,0);
+       tt_ptr_op(ai->ai_next, ==, NULL);
+       test_ai_eq(ai, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
+       evutil_freeaddrinfo(ai);
+       ai = NULL;
+
+       /* Now try an unspec one. We should get a v6 and a v4. */
+       hints.ai_family = PF_UNSPEC;
+       r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
+       tt_assert(ai);
+       tt_int_op(r,==,0);
+       a = ai_find_by_family(ai, PF_INET6);
+       tt_assert(a);
+       test_ai_eq(a, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
+       a = ai_find_by_family(ai, PF_INET);
+       tt_assert(a);
+       test_ai_eq(a, "0.0.0.0:9996", SOCK_STREAM, IPPROTO_TCP);
+       evutil_freeaddrinfo(ai);
+       ai = NULL;
+
+       /* Try out AI_NUMERICHOST: successful case.  Also try
+        * multiprotocol. */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_flags = EVUTIL_AI_NUMERICHOST;
+       r = evutil_getaddrinfo("1.2.3.4", NULL, &hints, &ai);
+       tt_int_op(r, ==, 0);
+       a = ai_find_by_protocol(ai, IPPROTO_TCP);
+       tt_assert(a);
+       test_ai_eq(a, "1.2.3.4", SOCK_STREAM, IPPROTO_TCP);
+       a = ai_find_by_protocol(ai, IPPROTO_UDP);
+       tt_assert(a);
+       test_ai_eq(a, "1.2.3.4", SOCK_DGRAM, IPPROTO_UDP);
+       evutil_freeaddrinfo(ai);
+       ai = NULL;
+
+       /* Try the failing case of AI_NUMERICHOST */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_flags = EVUTIL_AI_NUMERICHOST;
+       r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
+       tt_int_op(r, ==, EVUTIL_EAI_NONAME);
+       tt_int_op(ai, ==, NULL);
+
+       /* Try symbolic service names wit AI_NUMERICSERV */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_STREAM;
+       hints.ai_flags = EVUTIL_AI_NUMERICSERV;
+       r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
+       tt_int_op(r,==,EVUTIL_EAI_NONAME);
+
+       /* Try symbolic service names */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_STREAM;
+       r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
+       if (r!=0) {
+               TT_DECLARE("SKIP", ("Symbolic service names seem broken."));
+       } else {
+               tt_assert(ai);
+               test_ai_eq(ai, "1.2.3.4:80", SOCK_STREAM, IPPROTO_TCP);
+               evutil_freeaddrinfo(ai);
+               ai = NULL;
+       }
+
+       /* Now do some actual lookups. */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_INET;
+       hints.ai_protocol = IPPROTO_TCP;
+       hints.ai_socktype = SOCK_STREAM;
+       r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
+       if (r != 0) {
+               TT_DECLARE("SKIP", ("Couldn't resolve www.google.com"));
+       } else {
+               tt_assert(ai);
+               tt_int_op(ai->ai_family, ==, PF_INET);
+               tt_int_op(ai->ai_protocol, ==, IPPROTO_TCP);
+               tt_int_op(ai->ai_socktype, ==, SOCK_STREAM);
+               tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in));
+               sin = (struct sockaddr_in*)ai->ai_addr;
+               tt_int_op(sin->sin_family, ==, AF_INET);
+               tt_int_op(sin->sin_port, ==, htons(80));
+               tt_int_op(sin->sin_addr.s_addr, !=, 0xffffffff);
+
+               cp = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
+               TT_BLATHER(("www.google.com resolved to %s",
+                       cp?cp:"<unwriteable>"));
+               evutil_freeaddrinfo(ai);
+               ai = NULL;
+       }
+
+       hints.ai_family = PF_INET6;
+       r = evutil_getaddrinfo("ipv6.google.com", "80", &hints, &ai);
+       if (r != 0) {
+               TT_BLATHER(("Couldn't do an ipv6 lookup for ipv6.google.com"));
+       } else {
+               tt_assert(ai);
+               tt_int_op(ai->ai_family, ==, PF_INET6);
+               tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in6));
+               sin6 = (struct sockaddr_in6*)ai->ai_addr;
+               tt_int_op(sin6->sin6_port, ==, htons(80));
+
+               cp = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,
+                   sizeof(buf));
+               TT_BLATHER(("ipv6.google.com resolved to %s",
+                       cp?cp:"<unwriteable>"));
+       }
+
+end:
+       if (ai)
+               evutil_freeaddrinfo(ai);
+}
+
+#ifdef WIN32
+static void
+test_evutil_loadsyslib(void *arg)
+{
+       HANDLE h=NULL;
+
+       h = evutil_load_windows_system_library(TEXT("kernel32.dll"));
+       tt_assert(h);
+
+end:
+       if (h)
+               CloseHandle(h);
+
+}
+#endif
+
+struct testcase_t util_testcases[] = {
+       { "ipv4_parse", regress_ipv4_parse, 0, NULL, NULL },
+       { "ipv6_parse", regress_ipv6_parse, 0, NULL, NULL },
+       { "sockaddr_port_parse", regress_sockaddr_port_parse, 0, NULL, NULL },
+       { "sockaddr_port_format", regress_sockaddr_port_format, 0, NULL, NULL },
+       { "sockaddr_predicates", test_evutil_sockaddr_predicates, 0,NULL,NULL },
+       { "evutil_snprintf", test_evutil_snprintf, 0, NULL, NULL },
+       { "evutil_strtoll", test_evutil_strtoll, 0, NULL, NULL },
+       { "evutil_casecmp", test_evutil_casecmp, 0, NULL, NULL },
+       { "strlcpy", test_evutil_strlcpy, 0, NULL, NULL },
+       { "log", test_evutil_log, TT_FORK, NULL, NULL },
+       { "upcast", test_evutil_upcast, 0, NULL, NULL },
+       { "integers", test_evutil_integers, 0, NULL, NULL },
+       { "rand", test_evutil_rand, TT_FORK, NULL, NULL },
+       { "getaddrinfo", test_evutil_getaddrinfo, TT_FORK, NULL, NULL },
+#ifdef WIN32
+       { "loadsyslib", test_evutil_loadsyslib, TT_FORK, NULL, NULL },
+#endif
+       END_OF_TESTCASES,
+};
+
diff --git a/libevent/test/regress_zlib.c b/libevent/test/regress_zlib.c
new file mode 100644 (file)
index 0000000..887a685
--- /dev/null
@@ -0,0 +1,344 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+/* The old tests here need assertions to work. */
+#undef NDEBUG
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#ifndef WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <assert.h>
+#include <errno.h>
+
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+
+#include "regress.h"
+
+/* zlib 1.2.4 and 1.2.5 do some "clever" things with macros.  Instead of
+   saying "(defined(FOO) ? FOO : 0)" they like to say "FOO-0", on the theory
+   that nobody will care if the compile outputs a no-such-identifier warning.
+
+   Sorry, but we like -Werror over here, so I guess we need to define these.
+   I hope that zlib 1.2.6 doesn't break these too.
+*/
+#ifndef _LARGEFILE64_SOURCE
+#define _LARGEFILE64_SOURCE 0
+#endif
+#ifndef _LFS64_LARGEFILE
+#define _LFS64_LARGEFILE 0
+#endif
+#ifndef _FILE_OFFSET_BITS
+#define _FILE_OFFSET_BITS 0
+#endif
+#ifndef off64_t
+#define off64_t ev_int64_t
+#endif
+
+#include <zlib.h>
+
+static int infilter_calls;
+static int outfilter_calls;
+static int readcb_finished;
+static int writecb_finished;
+static int errorcb_invoked;
+
+/*
+ * Zlib filters
+ */
+
+static void
+zlib_deflate_free(void *ctx)
+{
+       z_streamp p = ctx;
+
+       assert(deflateEnd(p) == Z_OK);
+}
+
+static void
+zlib_inflate_free(void *ctx)
+{
+       z_streamp p = ctx;
+
+       assert(inflateEnd(p) == Z_OK);
+}
+
+static int
+getstate(enum bufferevent_flush_mode state)
+{
+       switch (state) {
+       case BEV_FINISHED:
+               return Z_FINISH;
+       case BEV_FLUSH:
+               return Z_SYNC_FLUSH;
+       case BEV_NORMAL:
+       default:
+               return Z_NO_FLUSH;
+       }
+}
+
+/*
+ * The input filter is triggered only on new input read from the network.
+ * That means all input data needs to be consumed or the filter needs to
+ * initiate its own triggering via a timeout.
+ */
+static enum bufferevent_filter_result
+zlib_input_filter(struct evbuffer *src, struct evbuffer *dst,
+    ev_ssize_t lim, enum bufferevent_flush_mode state, void *ctx)
+{
+       struct evbuffer_iovec v_in[1];
+       struct evbuffer_iovec v_out[1];
+       int nread, nwrite;
+       int res, n;
+
+       z_streamp p = ctx;
+
+       do {
+               /* let's do some decompression */
+               n = evbuffer_peek(src, -1, NULL, v_in, 1);
+               if (n) {
+                       p->avail_in = v_in[0].iov_len;
+                       p->next_in = v_in[0].iov_base;
+               } else {
+                       p->avail_in = 0;
+                       p->next_in = 0;
+               }
+
+               evbuffer_reserve_space(dst, 4096, v_out, 1);
+               p->next_out = v_out[0].iov_base;
+               p->avail_out = v_out[0].iov_len;
+
+               /* we need to flush zlib if we got a flush */
+               res = inflate(p, getstate(state));
+
+               /* let's figure out how much was compressed */
+               nread = v_in[0].iov_len - p->avail_in;
+               nwrite = v_out[0].iov_len - p->avail_out;
+
+               evbuffer_drain(src, nread);
+               v_out[0].iov_len = nwrite;
+               evbuffer_commit_space(dst, v_out, 1);
+
+               if (res==Z_BUF_ERROR) {
+                       /* We're out of space, or out of decodeable input.
+                          Only if nwrite == 0 assume the latter.
+                        */
+                       if (nwrite == 0)
+                               return BEV_NEED_MORE;
+               } else {
+                       assert(res == Z_OK || res == Z_STREAM_END);
+               }
+
+       } while (evbuffer_get_length(src) > 0);
+
+       ++infilter_calls;
+
+       return (BEV_OK);
+}
+
+static enum bufferevent_filter_result
+zlib_output_filter(struct evbuffer *src, struct evbuffer *dst,
+    ev_ssize_t lim, enum bufferevent_flush_mode state, void *ctx)
+{
+       struct evbuffer_iovec v_in[1];
+       struct evbuffer_iovec v_out[1];
+       int nread, nwrite;
+       int res, n;
+
+       z_streamp p = ctx;
+
+       do {
+               /* let's do some compression */
+               n = evbuffer_peek(src, -1, NULL, v_in, 1);
+               if (n) {
+                       p->avail_in = v_in[0].iov_len;
+                       p->next_in = v_in[0].iov_base;
+               } else {
+                       p->avail_in = 0;
+                       p->next_in = 0;
+               }
+
+               evbuffer_reserve_space(dst, 4096, v_out, 1);
+               p->next_out = v_out[0].iov_base;
+               p->avail_out = v_out[0].iov_len;
+
+               /* we need to flush zlib if we got a flush */
+               res = deflate(p, getstate(state));
+
+               /* let's figure out how much was decompressed */
+               nread = v_in[0].iov_len - p->avail_in;
+               nwrite = v_out[0].iov_len - p->avail_out;
+
+               evbuffer_drain(src, nread);
+               v_out[0].iov_len = nwrite;
+               evbuffer_commit_space(dst, v_out, 1);
+
+               if (res==Z_BUF_ERROR) {
+                       /* We're out of space, or out of decodeable input.
+                          Only if nwrite == 0 assume the latter.
+                        */
+                       if (nwrite == 0)
+                               return BEV_NEED_MORE;
+               } else {
+                       assert(res == Z_OK || res == Z_STREAM_END);
+               }
+
+       } while (evbuffer_get_length(src) > 0);
+
+       ++outfilter_calls;
+
+       return (BEV_OK);
+}
+
+/*
+ * simple bufferevent test (over transparent zlib treatment)
+ */
+
+static void
+readcb(struct bufferevent *bev, void *arg)
+{
+       if (evbuffer_get_length(bufferevent_get_input(bev)) == 8333) {
+               struct evbuffer *evbuf = evbuffer_new();
+               assert(evbuf != NULL);
+
+               /* gratuitous test of bufferevent_read_buffer */
+               bufferevent_read_buffer(bev, evbuf);
+
+               bufferevent_disable(bev, EV_READ);
+
+               if (evbuffer_get_length(evbuf) == 8333) {
+                       ++readcb_finished;
+               }
+
+               evbuffer_free(evbuf);
+       }
+}
+
+static void
+writecb(struct bufferevent *bev, void *arg)
+{
+       if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+               ++writecb_finished;
+       }
+}
+
+static void
+errorcb(struct bufferevent *bev, short what, void *arg)
+{
+       errorcb_invoked = 1;
+}
+
+void
+test_bufferevent_zlib(void *arg)
+{
+       struct bufferevent *bev1=NULL, *bev2=NULL;
+       char buffer[8333];
+       z_stream z_input, z_output;
+       int i, pair[2]={-1,-1}, r;
+       (void)arg;
+
+       infilter_calls = outfilter_calls = readcb_finished = writecb_finished
+           = errorcb_invoked = 0;
+
+       if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) {
+               tt_abort_perror("socketpair");
+       }
+
+       evutil_make_socket_nonblocking(pair[0]);
+       evutil_make_socket_nonblocking(pair[1]);
+
+       bev1 = bufferevent_socket_new(NULL, pair[0], 0);
+       bev2 = bufferevent_socket_new(NULL, pair[1], 0);
+
+       memset(&z_output, 0, sizeof(z_output));
+       r = deflateInit(&z_output, Z_DEFAULT_COMPRESSION);
+       tt_int_op(r, ==, Z_OK);
+       memset(&z_input, 0, sizeof(z_input));
+       r = inflateInit(&z_input);
+       tt_int_op(r, ==, Z_OK);
+
+       /* initialize filters */
+       bev1 = bufferevent_filter_new(bev1, NULL, zlib_output_filter,
+           BEV_OPT_CLOSE_ON_FREE, zlib_deflate_free, &z_output);
+       bev2 = bufferevent_filter_new(bev2, zlib_input_filter,
+           NULL, BEV_OPT_CLOSE_ON_FREE, zlib_inflate_free, &z_input);
+       bufferevent_setcb(bev1, readcb, writecb, errorcb, NULL);
+       bufferevent_setcb(bev2, readcb, writecb, errorcb, NULL);
+
+       bufferevent_disable(bev1, EV_READ);
+       bufferevent_enable(bev1, EV_WRITE);
+
+       bufferevent_enable(bev2, EV_READ);
+
+       for (i = 0; i < (int)sizeof(buffer); i++)
+               buffer[i] = i;
+
+       /* break it up into multiple buffer chains */
+       bufferevent_write(bev1, buffer, 1800);
+       bufferevent_write(bev1, buffer + 1800, sizeof(buffer) - 1800);
+
+       /* we are done writing - we need to flush everything */
+       bufferevent_flush(bev1, EV_WRITE, BEV_FINISHED);
+
+       event_dispatch();
+
+       tt_want(infilter_calls);
+       tt_want(outfilter_calls);
+       tt_want(readcb_finished);
+       tt_want(writecb_finished);
+       tt_want(!errorcb_invoked);
+
+       test_ok = 1;
+end:
+       if (bev1)
+               bufferevent_free(bev1);
+       if (bev2)
+               bufferevent_free(bev2);
+
+       if (pair[0] >= 0)
+               evutil_closesocket(pair[0]);
+       if (pair[1] >= 0)
+               evutil_closesocket(pair[1]);
+}
diff --git a/libevent/test/rpcgen_wrapper.sh b/libevent/test/rpcgen_wrapper.sh
new file mode 100755 (executable)
index 0000000..a60331c
--- /dev/null
@@ -0,0 +1,41 @@
+#!/bin/sh
+# libevent rpcgen_wrapper.sh
+# Transforms event_rpcgen.py failure into success for make, only if
+# regress.gen.c and regress.gen.h already exist in $srcdir.  This
+# is needed for "make distcheck" to pass the read-only $srcdir build,
+# as with read-only sources fresh from tarball, regress.gen.[ch] will
+# be correct in $srcdir but unwritable.  This previously triggered
+# Makefile.am to create stub regress.gen.c and regress.gen.h in the
+# distcheck _build directory, which were then detected as leftover
+# files in the build tree after distclean, breaking distcheck.
+# Note that regress.gen.[ch] are not in fresh git clones, making
+# working Python a requirement for make distcheck of a git tree.
+
+exit_updated() {
+    echo "Updated ${srcdir}\regress.gen.c and ${srcdir}\regress.gen.h"
+    exit 0
+}
+
+exit_reuse() {
+    echo "event_rpcgen.py failed, ${srcdir}\regress.gen.\[ch\] will be reused." >&2
+    exit 0
+}
+
+exit_failed() {
+    echo "Could not generate regress.gen.\[ch\] using event_rpcgen.sh" >&2
+    exit 1
+}
+
+srcdir=$1
+srcdir=${srcdir:-.}
+${srcdir}/../event_rpcgen.py ${srcdir}/regress.rpc
+case "$?" in
+ 0)
+    exit_updated
+    ;;
+ *)
+    test -r ${srcdir}/regress.gen.c -a -r ${srcdir}/regress.gen.h && \
+       exit_reuse
+    exit_failed
+    ;;
+esac
diff --git a/libevent/test/test-changelist.c b/libevent/test/test-changelist.c
new file mode 100644 (file)
index 0000000..fae099c
--- /dev/null
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <windows.h>
+#else
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/util.h"
+#include <time.h>
+
+struct cpu_usage_timer {
+#ifdef WIN32
+       HANDLE thread;
+       FILETIME usertimeBegin;
+       FILETIME kerneltimeBegin;
+#else
+       clock_t ticksBegin;
+#endif
+       struct timeval timeBegin;
+};
+static void
+start_cpu_usage_timer(struct cpu_usage_timer *timer)
+{
+#ifdef WIN32
+       int r;
+       FILETIME createtime, exittime;
+       timer->thread = GetCurrentThread();
+       r = GetThreadTimes(timer->thread, &createtime, &exittime,
+           &timer->usertimeBegin, &timer->kerneltimeBegin);
+       if (r==0) printf("GetThreadTimes failed.");
+#else
+       timer->ticksBegin = clock();
+#endif
+
+       evutil_gettimeofday(&timer->timeBegin, NULL);
+}
+#ifdef WIN32
+static ev_int64_t
+filetime_to_100nsec(const FILETIME *ft)
+{
+       /* Number of 100-nanosecond units */
+       ev_int64_t n = ft->dwHighDateTime;
+       n <<= 32;
+       n += ft->dwLowDateTime;
+       return n;
+}
+static double
+filetime_diff(const FILETIME *ftStart, const FILETIME *ftEnd)
+{
+       ev_int64_t s, e, diff;
+       double r;
+       s = filetime_to_100nsec(ftStart);
+       e = filetime_to_100nsec(ftEnd);
+       diff = e - s;
+       r = (double) diff;
+       return r / 1.0e7;
+}
+#endif
+
+static void
+get_cpu_usage(struct cpu_usage_timer *timer, double *secElapsedOut,
+    double *secUsedOut, double *usageOut)
+{
+#ifdef WIN32
+       double usertime_seconds, kerneltime_seconds;
+       FILETIME createtime, exittime, usertimeEnd, kerneltimeEnd;
+       int r;
+#else
+       clock_t ticksEnd;
+#endif
+       struct timeval timeEnd, timeDiff;
+       double secondsPassed, secondsUsed;
+
+#ifdef WIN32
+       r = GetThreadTimes(timer->thread, &createtime, &exittime,
+           &usertimeEnd, &kerneltimeEnd);
+       if (r==0) printf("GetThreadTimes failed.");
+       usertime_seconds = filetime_diff(&timer->usertimeBegin, &usertimeEnd);
+       kerneltime_seconds = filetime_diff(&timer->kerneltimeBegin, &kerneltimeEnd);
+       secondsUsed = kerneltime_seconds + usertime_seconds;
+#else
+       ticksEnd = clock();
+       secondsUsed = (ticksEnd - timer->ticksBegin) / (double)CLOCKS_PER_SEC;
+#endif
+       evutil_gettimeofday(&timeEnd, NULL);
+       evutil_timersub(&timeEnd, &timer->timeBegin, &timeDiff);
+       secondsPassed = timeDiff.tv_sec + (timeDiff.tv_usec / 1.0e6);
+
+       *secElapsedOut = secondsPassed;
+       *secUsedOut = secondsUsed;
+       *usageOut = secondsUsed / secondsPassed;
+}
+
+static void
+write_cb(evutil_socket_t fd, short event, void *arg)
+{
+       printf("write callback. should only see this once\n");
+
+       /* got what we want remove the event */
+       event_del(*(struct event**)arg);
+
+       /* opps changed my mind add it back again */
+       event_add(*(struct event**)arg,NULL);
+
+       /* not a good day for decisiveness, I really didn't want it after all */
+       event_del(*(struct event**)arg);
+
+}
+
+static void
+timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+       printf("timeout fired, time to end test\n");
+       event_del(*(struct event**)arg);
+       return;
+}
+
+int
+main(int argc, char **argv)
+{
+       struct event* ev;
+       struct event* timeout;
+       struct event_base* base;
+
+       evutil_socket_t pair[2];
+       struct timeval tv;
+       struct cpu_usage_timer timer;
+
+       double usage, secPassed, secUsed;
+
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+       if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+               return (1);
+
+       /* Initalize the event library */
+       base = event_base_new();
+
+       /* Initalize a timeout to terminate the test */
+       timeout = evtimer_new(base,timeout_cb,&timeout);
+       /* and watch for writability on one end of the pipe */
+       ev = event_new(base,pair[1],EV_WRITE | EV_PERSIST, write_cb, &ev);
+
+       tv.tv_sec  = 5;
+       tv.tv_usec = 0;
+
+       evtimer_add(timeout, &tv);
+
+       event_add(ev, NULL);
+
+       start_cpu_usage_timer(&timer);
+
+       event_base_dispatch(base);
+
+       get_cpu_usage(&timer, &secPassed, &secUsed, &usage);
+
+       /* attempt to calculate our cpu usage over the test should be
+          virtually nil */
+
+       printf("usec used=%d, usec passed=%d, cpu usage=%.2f%%\n",
+           (int)(secUsed*1e6),
+           (int)(secPassed*1e6),
+           usage*100);
+
+       if (usage > 50.0) /* way too high */
+         return 1;
+
+       return 0;
+}
+
diff --git a/libevent/test/test-eof.c b/libevent/test/test-eof.c
new file mode 100644 (file)
index 0000000..3f470ce
--- /dev/null
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#include <winsock2.h>
+#else
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event.h>
+#include <evutil.h>
+
+#ifdef _EVENT___func__
+#define __func__ _EVENT___func__
+#endif
+
+int test_okay = 1;
+int called = 0;
+struct timeval timeout = {60, 0};
+
+static void
+read_cb(evutil_socket_t fd, short event, void *arg)
+{
+       char buf[256];
+       int len;
+
+       if (EV_TIMEOUT & event) {
+               printf("%s: Timeout!\n", __func__);
+               exit(1);
+       }
+
+       len = recv(fd, buf, sizeof(buf), 0);
+
+       printf("%s: read %d%s\n", __func__,
+           len, len ? "" : " - means EOF");
+
+       if (len) {
+               if (!called)
+                       event_add(arg, &timeout);
+       } else if (called == 1)
+               test_okay = 0;
+
+       called++;
+}
+
+#ifndef SHUT_WR
+#define SHUT_WR 1
+#endif
+
+int
+main(int argc, char **argv)
+{
+       struct event ev;
+       const char *test = "test string";
+       evutil_socket_t pair[2];
+
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+       if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+               return (1);
+
+
+       send(pair[0], test, (int)strlen(test)+1, 0);
+       shutdown(pair[0], SHUT_WR);
+
+       /* Initalize the event library */
+       event_init();
+
+       /* Initalize one event */
+       event_set(&ev, pair[1], EV_READ | EV_TIMEOUT, read_cb, &ev);
+
+       event_add(&ev, &timeout);
+
+       event_dispatch();
+
+       return (test_okay);
+}
+
diff --git a/libevent/test/test-init.c b/libevent/test/test-init.c
new file mode 100644 (file)
index 0000000..2dfa865
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifndef WIN32
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+#include <event.h>
+
+int
+main(int argc, char **argv)
+{
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+       /* Initalize the event library */
+       event_init();
+
+       return (0);
+}
+
diff --git a/libevent/test/test-ratelim.c b/libevent/test/test-ratelim.c
new file mode 100644 (file)
index 0000000..eb0b165
--- /dev/null
@@ -0,0 +1,478 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <math.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+#  include <arpa/inet.h>
+# endif
+#endif
+#include <signal.h>
+
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/event.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "event2/thread.h"
+
+#include "../util-internal.h"
+
+static int cfg_verbose = 0;
+static int cfg_help = 0;
+
+static int cfg_n_connections = 30;
+static int cfg_duration = 5;
+static int cfg_connlimit = 0;
+static int cfg_grouplimit = 0;
+static int cfg_tick_msec = 1000;
+static int cfg_min_share = -1;
+
+static int cfg_connlimit_tolerance = -1;
+static int cfg_grouplimit_tolerance = -1;
+static int cfg_stddev_tolerance = -1;
+
+#ifdef _WIN32
+static int cfg_enable_iocp = 0;
+#endif
+
+static struct timeval cfg_tick = { 0, 500*1000 };
+
+static struct ev_token_bucket_cfg *conn_bucket_cfg = NULL;
+static struct ev_token_bucket_cfg *group_bucket_cfg = NULL;
+struct bufferevent_rate_limit_group *ratelim_group = NULL;
+static double seconds_per_tick = 0.0;
+
+struct client_state {
+       size_t queued;
+       ev_uint64_t received;
+};
+
+static int n_echo_conns_open = 0;
+
+static void
+loud_writecb(struct bufferevent *bev, void *ctx)
+{
+       struct client_state *cs = ctx;
+       struct evbuffer *output = bufferevent_get_output(bev);
+       char buf[1024];
+#ifdef WIN32
+       int r = rand() % 256;
+#else
+       int r = random() % 256;
+#endif
+       memset(buf, r, sizeof(buf));
+       while (evbuffer_get_length(output) < 8192) {
+               evbuffer_add(output, buf, sizeof(buf));
+               cs->queued += sizeof(buf);
+       }
+}
+
+static void
+discard_readcb(struct bufferevent *bev, void *ctx)
+{
+       struct client_state *cs = ctx;
+       struct evbuffer *input = bufferevent_get_input(bev);
+       size_t len = evbuffer_get_length(input);
+       evbuffer_drain(input, len);
+       cs->received += len;
+}
+
+static void
+write_on_connectedcb(struct bufferevent *bev, short what, void *ctx)
+{
+       if (what & BEV_EVENT_CONNECTED) {
+               loud_writecb(bev, ctx);
+               /* XXXX this shouldn't be needed. */
+               bufferevent_enable(bev, EV_READ|EV_WRITE);
+       }
+}
+
+static void
+echo_readcb(struct bufferevent *bev, void *ctx)
+{
+       struct evbuffer *input = bufferevent_get_input(bev);
+       struct evbuffer *output = bufferevent_get_output(bev);
+
+       evbuffer_add_buffer(output, input);
+       if (evbuffer_get_length(output) > 1024000)
+               bufferevent_disable(bev, EV_READ);
+}
+
+static void
+echo_writecb(struct bufferevent *bev, void *ctx)
+{
+       struct evbuffer *output = bufferevent_get_output(bev);
+       if (evbuffer_get_length(output) < 512000)
+               bufferevent_enable(bev, EV_READ);
+}
+
+static void
+echo_eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+       if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
+               --n_echo_conns_open;
+               bufferevent_free(bev);
+       }
+}
+
+static void
+echo_listenercb(struct evconnlistener *listener, evutil_socket_t newsock,
+    struct sockaddr *sourceaddr, int socklen, void *ctx)
+{
+       struct event_base *base = ctx;
+       int flags = BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE;
+       struct bufferevent *bev;
+
+       bev = bufferevent_socket_new(base, newsock, flags);
+       bufferevent_setcb(bev, echo_readcb, echo_writecb, echo_eventcb, NULL);
+       if (conn_bucket_cfg)
+               bufferevent_set_rate_limit(bev, conn_bucket_cfg);
+       if (ratelim_group)
+               bufferevent_add_to_rate_limit_group(bev, ratelim_group);
+       ++n_echo_conns_open;
+       bufferevent_enable(bev, EV_READ|EV_WRITE);
+}
+
+static int
+test_ratelimiting(void)
+{
+       struct event_base *base;
+       struct sockaddr_in sin;
+       struct evconnlistener *listener;
+
+       struct sockaddr_storage ss;
+       ev_socklen_t slen;
+
+       struct bufferevent **bevs;
+       struct client_state *states;
+       struct bufferevent_rate_limit_group *group = NULL;
+
+       int i;
+
+       struct timeval tv;
+
+       ev_uint64_t total_received;
+       double total_sq_persec, total_persec;
+       double variance;
+       double expected_total_persec = -1.0, expected_avg_persec = -1.0;
+       int ok = 1;
+       struct event_config *base_cfg;
+
+       memset(&sin, 0, sizeof(sin));
+       sin.sin_family = AF_INET;
+       sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+       sin.sin_port = 0; /* unspecified port */
+
+       if (0)
+               event_enable_debug_mode();
+
+       base_cfg = event_config_new();
+
+#ifdef _WIN32
+       if (cfg_enable_iocp) {
+               evthread_use_windows_threads();
+               event_config_set_flag(base_cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
+       }
+#endif
+
+       base = event_base_new_with_config(base_cfg);
+
+       listener = evconnlistener_new_bind(base, echo_listenercb, base,
+           LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
+           (struct sockaddr *)&sin, sizeof(sin));
+
+       slen = sizeof(ss);
+       if (getsockname(evconnlistener_get_fd(listener), (struct sockaddr *)&ss,
+               &slen) < 0) {
+               perror("getsockname");
+               return 1;
+       }
+
+       if (cfg_connlimit > 0) {
+               conn_bucket_cfg = ev_token_bucket_cfg_new(
+                       cfg_connlimit, cfg_connlimit * 4,
+                       cfg_connlimit, cfg_connlimit * 4,
+                       &cfg_tick);
+               assert(conn_bucket_cfg);
+       }
+
+       if (cfg_grouplimit > 0) {
+               group_bucket_cfg = ev_token_bucket_cfg_new(
+                       cfg_grouplimit, cfg_grouplimit * 4,
+                       cfg_grouplimit, cfg_grouplimit * 4,
+                       &cfg_tick);
+               group = ratelim_group = bufferevent_rate_limit_group_new(
+                       base, group_bucket_cfg);
+               expected_total_persec = cfg_grouplimit;
+               expected_avg_persec = cfg_grouplimit / cfg_n_connections;
+               if (cfg_connlimit > 0 && expected_avg_persec > cfg_connlimit)
+                       expected_avg_persec = cfg_connlimit;
+               if (cfg_min_share >= 0)
+                       bufferevent_rate_limit_group_set_min_share(
+                               ratelim_group, cfg_min_share);
+       }
+
+       if (expected_avg_persec < 0 && cfg_connlimit > 0)
+               expected_avg_persec = cfg_connlimit;
+
+       if (expected_avg_persec > 0)
+               expected_avg_persec /= seconds_per_tick;
+       if (expected_total_persec > 0)
+               expected_total_persec /= seconds_per_tick;
+
+       bevs = calloc(cfg_n_connections, sizeof(struct bufferevent *));
+       states = calloc(cfg_n_connections, sizeof(struct client_state));
+
+       for (i = 0; i < cfg_n_connections; ++i) {
+               bevs[i] = bufferevent_socket_new(base, -1,
+                   BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE);
+               assert(bevs[i]);
+               bufferevent_setcb(bevs[i], discard_readcb, loud_writecb,
+                   write_on_connectedcb, &states[i]);
+               bufferevent_enable(bevs[i], EV_READ|EV_WRITE);
+               bufferevent_socket_connect(bevs[i], (struct sockaddr *)&ss,
+                   slen);
+       }
+
+       tv.tv_sec = cfg_duration - 1;
+       tv.tv_usec = 995000;
+
+       event_base_loopexit(base, &tv);
+
+       event_base_dispatch(base);
+
+       ratelim_group = NULL; /* So no more responders get added */
+
+       for (i = 0; i < cfg_n_connections; ++i) {
+               bufferevent_free(bevs[i]);
+       }
+       evconnlistener_free(listener);
+
+       /* Make sure no new echo_conns get added to the group. */
+       ratelim_group = NULL;
+
+       /* This should get _everybody_ freed */
+       while (n_echo_conns_open) {
+               printf("waiting for %d conns\n", n_echo_conns_open);
+               tv.tv_sec = 0;
+               tv.tv_usec = 300000;
+               event_base_loopexit(base, &tv);
+               event_base_dispatch(base);
+       }
+
+       if (group)
+               bufferevent_rate_limit_group_free(group);
+
+       total_received = 0;
+       total_persec = 0.0;
+       total_sq_persec = 0.0;
+       for (i=0; i < cfg_n_connections; ++i) {
+               double persec = states[i].received;
+               persec /= cfg_duration;
+               total_received += states[i].received;
+               total_persec += persec;
+               total_sq_persec += persec*persec;
+               printf("%d: %f per second\n", i+1, persec);
+       }
+       printf("   total: %f per second\n",
+           ((double)total_received)/cfg_duration);
+       if (expected_total_persec > 0) {
+               double diff = expected_total_persec -
+                   ((double)total_received/cfg_duration);
+               printf("  [Off by %lf]\n", diff);
+               if (cfg_grouplimit_tolerance > 0 &&
+                   fabs(diff) > cfg_grouplimit_tolerance) {
+                       fprintf(stderr, "Group bandwidth out of bounds\n");
+                       ok = 0;
+               }
+       }
+
+       printf(" average: %f per second\n",
+           (((double)total_received)/cfg_duration)/cfg_n_connections);
+       if (expected_avg_persec > 0) {
+               double diff = expected_avg_persec - (((double)total_received)/cfg_duration)/cfg_n_connections;
+               printf("  [Off by %lf]\n", diff);
+               if (cfg_connlimit_tolerance > 0 &&
+                   fabs(diff) > cfg_connlimit_tolerance) {
+                       fprintf(stderr, "Connection bandwidth out of bounds\n");
+                       ok = 0;
+               }
+       }
+
+       variance = total_sq_persec/cfg_n_connections - total_persec*total_persec/(cfg_n_connections*cfg_n_connections);
+
+       printf("  stddev: %f per second\n", sqrt(variance));
+       if (cfg_stddev_tolerance > 0 &&
+           sqrt(variance) > cfg_stddev_tolerance) {
+               fprintf(stderr, "Connection variance out of bounds\n");
+               ok = 0;
+       }
+
+       event_base_free(base);
+       free(bevs);
+       free(states);
+
+       return ok ? 0 : 1;
+}
+
+static struct option {
+       const char *name; int *ptr; int min; int isbool;
+} options[] = {
+       { "-v", &cfg_verbose, 0, 1 },
+       { "-h", &cfg_help, 0, 1 },
+       { "-n", &cfg_n_connections, 1, 0 },
+       { "-d", &cfg_duration, 1, 0 },
+       { "-c", &cfg_connlimit, 0, 0 },
+       { "-g", &cfg_grouplimit, 0, 0 },
+       { "-t", &cfg_tick_msec, 10, 0 },
+       { "--min-share", &cfg_min_share, 0, 0 },
+       { "--check-connlimit", &cfg_connlimit_tolerance, 0, 0 },
+       { "--check-grouplimit", &cfg_grouplimit_tolerance, 0, 0 },
+       { "--check-stddev", &cfg_stddev_tolerance, 0, 0 },
+#ifdef _WIN32
+       { "--iocp", &cfg_enable_iocp, 0, 1 },
+#endif
+       { NULL, NULL, -1, 0 },
+};
+
+static int
+handle_option(int argc, char **argv, int *i, const struct option *opt)
+{
+       long val;
+       char *endptr = NULL;
+       if (opt->isbool) {
+               *opt->ptr = 1;
+               return 0;
+       }
+       if (*i + 1 == argc) {
+               fprintf(stderr, "Too few arguments to '%s'\n",argv[*i]);
+               return -1;
+       }
+       val = strtol(argv[*i+1], &endptr, 10);
+       if (*argv[*i+1] == '\0' || !endptr || *endptr != '\0') {
+               fprintf(stderr, "Couldn't parse numeric value '%s'\n",
+                   argv[*i+1]);
+               return -1;
+       }
+       if (val < opt->min || val > 0x7fffffff) {
+               fprintf(stderr, "Value '%s' is out-of-range'\n",
+                   argv[*i+1]);
+               return -1;
+       }
+       *opt->ptr = (int)val;
+       ++*i;
+       return 0;
+}
+
+static void
+usage(void)
+{
+       fprintf(stderr,
+"test-ratelim [-v] [-n INT] [-d INT] [-c INT] [-g INT] [-t INT]\n\n"
+"Pushes bytes through a number of possibly rate-limited connections, and\n"
+"displays average throughput.\n\n"
+"  -n INT: Number of connections to open (default: 30)\n"
+"  -d INT: Duration of the test in seconds (default: 5 sec)\n");
+       fprintf(stderr,
+"  -c INT: Connection-rate limit applied to each connection in bytes per second\n"
+"         (default: None.)\n"
+"  -g INT: Group-rate limit applied to sum of all usage in bytes per second\n"
+"         (default: None.)\n"
+"  -t INT: Granularity of timing, in milliseconds (default: 1000 msec)\n");
+}
+
+int
+main(int argc, char **argv)
+{
+       int i,j;
+       double ratio;
+
+#ifdef WIN32
+       WORD wVersionRequested = MAKEWORD(2,2);
+       WSADATA wsaData;
+       int err;
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+#ifndef WIN32
+       if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+               return 1;
+#endif
+       for (i = 1; i < argc; ++i) {
+               for (j = 0; options[j].name; ++j) {
+                       if (!strcmp(argv[i],options[j].name)) {
+                               if (handle_option(argc,argv,&i,&options[j])<0)
+                                       return 1;
+                               goto again;
+                       }
+               }
+               fprintf(stderr, "Unknown option '%s'\n", argv[i]);
+               usage();
+               return 1;
+       again:
+               ;
+       }
+       if (cfg_help) {
+               usage();
+               return 0;
+       }
+
+       cfg_tick.tv_sec = cfg_tick_msec / 1000;
+       cfg_tick.tv_usec = (cfg_tick_msec % 1000)*1000;
+
+       seconds_per_tick = ratio = cfg_tick_msec / 1000.0;
+
+       cfg_connlimit *= ratio;
+       cfg_grouplimit *= ratio;
+
+       {
+               struct timeval tv;
+               evutil_gettimeofday(&tv, NULL);
+#ifdef WIN32
+               srand(tv.tv_usec);
+#else
+               srandom(tv.tv_usec);
+#endif
+       }
+
+#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+       evthread_enable_lock_debuging();
+#endif
+
+       return test_ratelimiting();
+}
diff --git a/libevent/test/test-ratelim.sh b/libevent/test/test-ratelim.sh
new file mode 100755 (executable)
index 0000000..229cba5
--- /dev/null
@@ -0,0 +1,77 @@
+#!/bin/sh
+
+FAILED=no
+
+if test "x$TEST_OUTPUT_FILE" = "x"
+then
+       TEST_OUTPUT_FILE=/dev/null
+fi
+
+# /bin/echo is a little more likely to support -n than sh's builtin echo.
+if test -x /bin/echo
+then
+       ECHO=/bin/echo
+else
+       ECHO=echo
+fi
+
+if test "$TEST_OUTPUT_FILE" != "/dev/null"
+then
+       touch "$TEST_OUTPUT_FILE" || exit 1
+fi
+
+TEST_DIR=.
+
+T=`echo "$0" | sed -e 's/test-ratelim.sh$//'`
+if test -x "$T/test-ratelim"
+then
+       TEST_DIR="$T"
+fi
+
+announce () {
+       echo $@
+       echo $@ >>"$TEST_OUTPUT_FILE"
+}
+
+announce_n () {
+       $ECHO -n $@
+       echo $@ >>"$TEST_OUTPUT_FILE"
+}
+
+
+run_tests () {
+       announce_n "  Group limits, no connection limit:"
+       if $TEST_DIR/test-ratelim -g 30000 -n 30 -t 100 --check-grouplimit 1000 --check-stddev 100 >>"$TEST_OUTPUT_FILE"
+       then
+               announce OKAY
+       else
+               announce FAILED
+               FAILED=yes
+       fi
+
+       announce_n "  Connection limit, no group limit:"
+       if $TEST_DIR/test-ratelim -c 1000 -n 30 -t 100 --check-connlimit 50 --check-stddev 50 >>"$TEST_OUTPUT_FILE"
+       then
+               announce OKAY ;
+       else
+               announce FAILED ;
+               FAILED=yes
+       fi
+
+       announce_n "  Connection limit and group limit:"
+       if $TEST_DIR/test-ratelim -c 1000 -g 30000 -n 30 -t 100 --check-grouplimit 1000 --check-connlimit 50 --check-stddev 50 >>"$TEST_OUTPUT_FILE"
+       then
+               announce OKAY ;
+       else
+               announce FAILED ;
+               FAILED=yes
+       fi
+}
+
+announce "Running rate-limiting tests:"
+
+run_tests
+
+if test "$FAILED" = "yes"; then
+       exit 1
+fi
diff --git a/libevent/test/test-time.c b/libevent/test/test-time.c
new file mode 100644 (file)
index 0000000..8f0bd62
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifndef WIN32
+#include <unistd.h>
+#include <sys/time.h>
+#endif
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/event_struct.h"
+
+int called = 0;
+
+#define NEVENT 20000
+
+struct event *ev[NEVENT];
+
+static int
+rand_int(int n)
+{
+#ifdef WIN32
+       return (int)(rand() % n);
+#else
+       return (int)(random() % n);
+#endif
+}
+
+static void
+time_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct timeval tv;
+       int i, j;
+
+       called++;
+
+       if (called < 10*NEVENT) {
+               for (i = 0; i < 10; i++) {
+                       j = rand_int(NEVENT);
+                       tv.tv_sec = 0;
+                       tv.tv_usec = rand_int(50000);
+                       if (tv.tv_usec % 2)
+                               evtimer_add(ev[j], &tv);
+                       else
+                               evtimer_del(ev[j]);
+               }
+       }
+}
+
+int
+main(int argc, char **argv)
+{
+       struct timeval tv;
+       int i;
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+       /* Initalize the event library */
+       event_init();
+
+       for (i = 0; i < NEVENT; i++) {
+               ev[i] = malloc(sizeof(struct event));
+
+               /* Initalize one event */
+               evtimer_set(ev[i], time_cb, ev[i]);
+               tv.tv_sec = 0;
+               tv.tv_usec = rand_int(50000);
+               evtimer_add(ev[i], &tv);
+       }
+
+       event_dispatch();
+
+       return (called < NEVENT);
+}
+
diff --git a/libevent/test/test-weof.c b/libevent/test/test-weof.c
new file mode 100644 (file)
index 0000000..dfdd3f0
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "event2/event-config.h"
+
+#ifdef WIN32
+#include <winsock2.h>
+#else
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/event_compat.h"
+#include "event2/util.h"
+
+#ifdef _EVENT___func__
+#define __func__ _EVENT___func__
+#endif
+
+evutil_socket_t pair[2];
+int test_okay = 1;
+int called = 0;
+
+static void
+write_cb(evutil_socket_t fd, short event, void *arg)
+{
+       const char *test = "test string";
+       int len;
+
+       len = send(fd, test, (int)strlen(test) + 1, 0);
+
+       printf("%s: write %d%s\n", __func__,
+           len, len ? "" : " - means EOF");
+
+       if (len > 0) {
+               if (!called)
+                       event_add(arg, NULL);
+               evutil_closesocket(pair[0]);
+       } else if (called == 1)
+               test_okay = 0;
+
+       called++;
+}
+
+int
+main(int argc, char **argv)
+{
+       struct event ev;
+
+#ifdef WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+#ifndef WIN32
+       if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+               return (1);
+#endif
+
+       if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+               return (1);
+
+       /* Initalize the event library */
+       event_init();
+
+       /* Initalize one event */
+       event_set(&ev, pair[1], EV_WRITE, write_cb, &ev);
+
+       event_add(&ev, NULL);
+
+       event_dispatch();
+
+       return (test_okay);
+}
+
diff --git a/libevent/test/test.sh b/libevent/test/test.sh
new file mode 100755 (executable)
index 0000000..08a4cdd
--- /dev/null
@@ -0,0 +1,163 @@
+#!/bin/sh
+
+FAILED=no
+
+if test "x$TEST_OUTPUT_FILE" = "x"
+then
+       TEST_OUTPUT_FILE=/dev/null
+fi
+
+# /bin/echo is a little more likely to support -n than sh's builtin echo,
+# printf is even more likely
+if test "`printf %s hello 2>&1`" = "hello"
+then
+       ECHO_N="printf %s"
+else
+       if test -x /bin/echo
+       then
+               ECHO_N="/bin/echo -n"
+       else
+               ECHO_N="echo -n"
+       fi
+fi
+
+if test "$TEST_OUTPUT_FILE" != "/dev/null"
+then
+       touch "$TEST_OUTPUT_FILE" || exit 1
+fi
+
+TEST_DIR=.
+
+T=`echo "$0" | sed -e 's/test.sh$//'`
+if test -x "$T/test-init"
+then
+       TEST_DIR="$T"
+fi
+
+setup () {
+       EVENT_NOKQUEUE=yes; export EVENT_NOKQUEUE
+       EVENT_NODEVPOLL=yes; export EVENT_NODEVPOLL
+       EVENT_NOPOLL=yes; export EVENT_NOPOLL
+       EVENT_NOSELECT=yes; export EVENT_NOSELECT
+       EVENT_NOEPOLL=yes; export EVENT_NOEPOLL
+       unset EVENT_EPOLL_USE_CHANGELIST
+       EVENT_NOEVPORT=yes; export EVENT_NOEVPORT
+       EVENT_NOWIN32=yes; export EVENT_NOWIN32
+}
+
+announce () {
+       echo "$@"
+       echo "$@" >>"$TEST_OUTPUT_FILE"
+}
+
+announce_n () {
+       $ECHO_N "$@"
+       echo "$@" >>"$TEST_OUTPUT_FILE"
+}
+
+
+run_tests () {
+       if $TEST_DIR/test-init 2>>"$TEST_OUTPUT_FILE" ;
+       then
+               true
+       else
+               announce Skipping test
+               return
+       fi
+
+       announce_n " test-eof: "
+       if $TEST_DIR/test-eof >>"$TEST_OUTPUT_FILE" ;
+       then
+               announce OKAY ;
+       else
+               announce FAILED ;
+               FAILED=yes
+       fi
+       announce_n " test-weof: "
+       if $TEST_DIR/test-weof >>"$TEST_OUTPUT_FILE" ;
+       then
+               announce OKAY ;
+       else
+               announce FAILED ;
+               FAILED=yes
+       fi
+       announce_n " test-time: "
+       if $TEST_DIR/test-time >>"$TEST_OUTPUT_FILE" ;
+       then
+               announce OKAY ;
+       else
+               announce FAILED ;
+               FAILED=yes
+       fi
+       announce_n " test-changelist: "
+       if $TEST_DIR/test-changelist >>"$TEST_OUTPUT_FILE" ;
+       then
+               announce OKAY ;
+       else
+               announce FAILED ;
+               FAILED=yes
+       fi
+       test -x $TEST_DIR/regress || return
+       announce_n " regress: "
+       if test "$TEST_OUTPUT_FILE" = "/dev/null" ;
+       then
+               $TEST_DIR/regress --quiet
+       else
+               $TEST_DIR/regress >>"$TEST_OUTPUT_FILE"
+       fi
+       if test "$?" = "0" ;
+       then
+               announce OKAY ;
+       else
+               announce FAILED ;
+               FAILED=yes
+       fi
+}
+
+announce "Running tests:"
+
+# Need to do this by hand?
+setup
+unset EVENT_NOEVPORT
+announce "EVPORT"
+run_tests
+
+setup
+unset EVENT_NOKQUEUE
+announce "KQUEUE"
+run_tests
+
+setup
+unset EVENT_NOEPOLL
+announce "EPOLL"
+run_tests
+
+setup
+unset EVENT_NOEPOLL
+EVENT_EPOLL_USE_CHANGELIST=yes; export EVENT_EPOLL_USE_CHANGELIST
+announce "EPOLL (changelist)"
+run_tests
+
+setup
+unset EVENT_NODEVPOLL
+announce "DEVPOLL"
+run_tests
+
+setup
+unset EVENT_NOPOLL
+announce "POLL"
+run_tests
+
+setup
+unset EVENT_NOSELECT
+announce "SELECT"
+run_tests
+
+setup
+unset EVENT_NOWIN32
+announce "WIN32"
+run_tests
+
+if test "$FAILED" = "yes"; then
+       exit 1
+fi
diff --git a/libevent/test/tinytest.c b/libevent/test/tinytest.c
new file mode 100644 (file)
index 0000000..91cd8cb
--- /dev/null
@@ -0,0 +1,388 @@
+/* tinytest.c -- Copyright 2009-2012 Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#ifdef TINYTEST_LOCAL
+#include "tinytest_local.h"
+#endif
+
+#ifdef WIN32
+#include <windows.h>
+#else
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#endif
+
+#ifndef __GNUC__
+#define __attribute__(x)
+#endif
+
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+#define LONGEST_TEST_NAME 16384
+
+static int in_tinytest_main = 0; /**< true if we're in tinytest_main().*/
+static int n_ok = 0; /**< Number of tests that have passed */
+static int n_bad = 0; /**< Number of tests that have failed. */
+static int n_skipped = 0; /**< Number of tests that have been skipped. */
+
+static int opt_forked = 0; /**< True iff we're called from inside a win32 fork*/
+static int opt_nofork = 0; /**< Suppress calls to fork() for debugging. */
+static int opt_verbosity = 1; /**< -==quiet,0==terse,1==normal,2==verbose */
+const char *verbosity_flag = "";
+
+enum outcome { SKIP=2, OK=1, FAIL=0 };
+static enum outcome cur_test_outcome = 0;
+const char *cur_test_prefix = NULL; /**< prefix of the current test group */
+/** Name of the current test, if we haven't logged is yet. Used for --quiet */
+const char *cur_test_name = NULL;
+
+#ifdef WIN32
+/* Copy of argv[0] for win32. */
+static char commandname[MAX_PATH+1];
+#endif
+
+static void usage(struct testgroup_t *groups, int list_groups)
+  __attribute__((noreturn));
+
+static enum outcome
+_testcase_run_bare(const struct testcase_t *testcase)
+{
+       void *env = NULL;
+       int outcome;
+       if (testcase->setup) {
+               env = testcase->setup->setup_fn(testcase);
+               if (!env)
+                       return FAIL;
+               else if (env == (void*)TT_SKIP)
+                       return SKIP;
+       }
+
+       cur_test_outcome = OK;
+       testcase->fn(env);
+       outcome = cur_test_outcome;
+
+       if (testcase->setup) {
+               if (testcase->setup->cleanup_fn(testcase, env) == 0)
+                       outcome = FAIL;
+       }
+
+       return outcome;
+}
+
+#define MAGIC_EXITCODE 42
+
+static enum outcome
+_testcase_run_forked(const struct testgroup_t *group,
+                    const struct testcase_t *testcase)
+{
+#ifdef WIN32
+       /* Fork? On Win32?  How primitive!  We'll do what the smart kids do:
+          we'll invoke our own exe (whose name we recall from the command
+          line) with a command line that tells it to run just the test we
+          want, and this time without forking.
+
+          (No, threads aren't an option.  The whole point of forking is to
+          share no state between tests.)
+        */
+       int ok;
+       char buffer[LONGEST_TEST_NAME+256];
+       STARTUPINFOA si;
+       PROCESS_INFORMATION info;
+       DWORD exitcode;
+
+       if (!in_tinytest_main) {
+               printf("\nERROR.  On Windows, _testcase_run_forked must be"
+                      " called from within tinytest_main.\n");
+               abort();
+       }
+       if (opt_verbosity>0)
+               printf("[forking] ");
+
+       snprintf(buffer, sizeof(buffer), "%s --RUNNING-FORKED %s %s%s",
+                commandname, verbosity_flag, group->prefix, testcase->name);
+
+       memset(&si, 0, sizeof(si));
+       memset(&info, 0, sizeof(info));
+       si.cb = sizeof(si);
+
+       ok = CreateProcessA(commandname, buffer, NULL, NULL, 0,
+                          0, NULL, NULL, &si, &info);
+       if (!ok) {
+               printf("CreateProcess failed!\n");
+               return 0;
+       }
+       WaitForSingleObject(info.hProcess, INFINITE);
+       GetExitCodeProcess(info.hProcess, &exitcode);
+       CloseHandle(info.hProcess);
+       CloseHandle(info.hThread);
+       if (exitcode == 0)
+               return OK;
+       else if (exitcode == MAGIC_EXITCODE)
+               return SKIP;
+       else
+               return FAIL;
+#else
+       int outcome_pipe[2];
+       pid_t pid;
+       (void)group;
+
+       if (pipe(outcome_pipe))
+               perror("opening pipe");
+
+       if (opt_verbosity>0)
+               printf("[forking] ");
+       pid = fork();
+       if (!pid) {
+               /* child. */
+               int test_r, write_r;
+               char b[1];
+               close(outcome_pipe[0]);
+               test_r = _testcase_run_bare(testcase);
+               assert(0<=(int)test_r && (int)test_r<=2);
+               b[0] = "NYS"[test_r];
+               write_r = (int)write(outcome_pipe[1], b, 1);
+               if (write_r != 1) {
+                       perror("write outcome to pipe");
+                       exit(1);
+               }
+               exit(0);
+               return FAIL; /* unreachable */
+       } else {
+               /* parent */
+               int status, r;
+               char b[1];
+               /* Close this now, so that if the other side closes it,
+                * our read fails. */
+               close(outcome_pipe[1]);
+               r = (int)read(outcome_pipe[0], b, 1);
+               if (r == 0) {
+                       printf("[Lost connection!] ");
+                       return 0;
+               } else if (r != 1) {
+                       perror("read outcome from pipe");
+               }
+               waitpid(pid, &status, 0);
+               close(outcome_pipe[0]);
+               return b[0]=='Y' ? OK : (b[0]=='S' ? SKIP : FAIL);
+       }
+#endif
+}
+
+int
+testcase_run_one(const struct testgroup_t *group,
+                const struct testcase_t *testcase)
+{
+       enum outcome outcome;
+
+       if (testcase->flags & TT_SKIP) {
+               if (opt_verbosity>0)
+                       printf("%s%s: SKIPPED\n",
+                           group->prefix, testcase->name);
+               ++n_skipped;
+               return SKIP;
+       }
+
+       if (opt_verbosity>0 && !opt_forked) {
+               printf("%s%s: ", group->prefix, testcase->name);
+       } else {
+               if (opt_verbosity==0) printf(".");
+               cur_test_prefix = group->prefix;
+               cur_test_name = testcase->name;
+       }
+
+       if ((testcase->flags & TT_FORK) && !(opt_forked||opt_nofork)) {
+               outcome = _testcase_run_forked(group, testcase);
+       } else {
+               outcome = _testcase_run_bare(testcase);
+       }
+
+       if (outcome == OK) {
+               ++n_ok;
+               if (opt_verbosity>0 && !opt_forked)
+                       puts(opt_verbosity==1?"OK":"");
+       } else if (outcome == SKIP) {
+               ++n_skipped;
+               if (opt_verbosity>0 && !opt_forked)
+                       puts("SKIPPED");
+       } else {
+               ++n_bad;
+               if (!opt_forked)
+                       printf("\n  [%s FAILED]\n", testcase->name);
+       }
+
+       if (opt_forked) {
+               exit(outcome==OK ? 0 : (outcome==SKIP?MAGIC_EXITCODE : 1));
+               return 1; /* unreachable */
+       } else {
+               return (int)outcome;
+       }
+}
+
+int
+_tinytest_set_flag(struct testgroup_t *groups, const char *arg, unsigned long flag)
+{
+       int i, j;
+       size_t length = LONGEST_TEST_NAME;
+       char fullname[LONGEST_TEST_NAME];
+       int found=0;
+       if (strstr(arg, ".."))
+               length = strstr(arg,"..")-arg;
+       for (i=0; groups[i].prefix; ++i) {
+               for (j=0; groups[i].cases[j].name; ++j) {
+                       snprintf(fullname, sizeof(fullname), "%s%s",
+                                groups[i].prefix, groups[i].cases[j].name);
+                       if (!flag) /* Hack! */
+                               printf("    %s\n", fullname);
+                       if (!strncmp(fullname, arg, length)) {
+                               groups[i].cases[j].flags |= flag;
+                               ++found;
+                       }
+               }
+       }
+       return found;
+}
+
+static void
+usage(struct testgroup_t *groups, int list_groups)
+{
+       puts("Options are: [--verbose|--quiet|--terse] [--no-fork]");
+       puts("  Specify tests by name, or using a prefix ending with '..'");
+       puts("  To skip a test, list give its name prefixed with a colon.");
+       puts("  Use --list-tests for a list of tests.");
+       if (list_groups) {
+               puts("Known tests are:");
+               _tinytest_set_flag(groups, "..", 0);
+       }
+       exit(0);
+}
+
+int
+tinytest_main(int c, const char **v, struct testgroup_t *groups)
+{
+       int i, j, n=0;
+
+#ifdef WIN32
+       const char *sp = strrchr(v[0], '.');
+       const char *extension = "";
+       if (!sp || stricmp(sp, ".exe"))
+               extension = ".exe"; /* Add an exe so CreateProcess will work */
+       snprintf(commandname, sizeof(commandname), "%s%s", v[0], extension);
+       commandname[MAX_PATH]='\0';
+#endif
+       for (i=1; i<c; ++i) {
+               if (v[i][0] == '-') {
+                       if (!strcmp(v[i], "--RUNNING-FORKED")) {
+                               opt_forked = 1;
+                       } else if (!strcmp(v[i], "--no-fork")) {
+                               opt_nofork = 1;
+                       } else if (!strcmp(v[i], "--quiet")) {
+                               opt_verbosity = -1;
+                               verbosity_flag = "--quiet";
+                       } else if (!strcmp(v[i], "--verbose")) {
+                               opt_verbosity = 2;
+                               verbosity_flag = "--verbose";
+                       } else if (!strcmp(v[i], "--terse")) {
+                               opt_verbosity = 0;
+                               verbosity_flag = "--terse";
+                       } else if (!strcmp(v[i], "--help")) {
+                               usage(groups, 0);
+                       } else if (!strcmp(v[i], "--list-tests")) {
+                               usage(groups, 1);
+                       } else {
+                               printf("Unknown option %s.  Try --help\n",v[i]);
+                               return -1;
+                       }
+               } else {
+                       const char *test = v[i];
+                       int flag = _TT_ENABLED;
+                       if (test[0] == ':') {
+                               ++test;
+                               flag = TT_SKIP;
+                       } else {
+                               ++n;
+                       }
+                       if (!_tinytest_set_flag(groups, test, flag)) {
+                               printf("No such test as %s!\n", v[i]);
+                               return -1;
+                       }
+               }
+       }
+       if (!n)
+               _tinytest_set_flag(groups, "..", _TT_ENABLED);
+
+       setvbuf(stdout, NULL, _IONBF, 0);
+
+       ++in_tinytest_main;
+       for (i=0; groups[i].prefix; ++i)
+               for (j=0; groups[i].cases[j].name; ++j)
+                       if (groups[i].cases[j].flags & _TT_ENABLED)
+                               testcase_run_one(&groups[i],
+                                                &groups[i].cases[j]);
+
+       --in_tinytest_main;
+
+       if (opt_verbosity==0)
+               puts("");
+
+       if (n_bad)
+               printf("%d/%d TESTS FAILED. (%d skipped)\n", n_bad,
+                      n_bad+n_ok,n_skipped);
+       else if (opt_verbosity >= 1)
+               printf("%d tests ok.  (%d skipped)\n", n_ok, n_skipped);
+
+       return (n_bad == 0) ? 0 : 1;
+}
+
+int
+_tinytest_get_verbosity(void)
+{
+       return opt_verbosity;
+}
+
+void
+_tinytest_set_test_failed(void)
+{
+       if (opt_verbosity <= 0 && cur_test_name) {
+               if (opt_verbosity==0) puts("");
+               printf("%s%s: ", cur_test_prefix, cur_test_name);
+               cur_test_name = NULL;
+       }
+       cur_test_outcome = 0;
+}
+
+void
+_tinytest_set_test_skipped(void)
+{
+       if (cur_test_outcome==OK)
+               cur_test_outcome = SKIP;
+}
+
diff --git a/libevent/test/tinytest.h b/libevent/test/tinytest.h
new file mode 100644 (file)
index 0000000..7ce7858
--- /dev/null
@@ -0,0 +1,87 @@
+/* tinytest.h -- Copyright 2009-2012 Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _TINYTEST_H
+#define _TINYTEST_H
+
+/** Flag for a test that needs to run in a subprocess. */
+#define TT_FORK  (1<<0)
+/** Runtime flag for a test we've decided to skip. */
+#define TT_SKIP  (1<<1)
+/** Internal runtime flag for a test we've decided to run. */
+#define _TT_ENABLED  (1<<2)
+/** If you add your own flags, make them start at this point. */
+#define TT_FIRST_USER_FLAG (1<<3)
+
+typedef void (*testcase_fn)(void *);
+
+struct testcase_t;
+
+/** Functions to initialize/teardown a structure for a testcase. */
+struct testcase_setup_t {
+       /** Return a new structure for use by a given testcase. */
+       void *(*setup_fn)(const struct testcase_t *);
+       /** Clean/free a structure from setup_fn. Return 1 if ok, 0 on err. */
+       int (*cleanup_fn)(const struct testcase_t *, void *);
+};
+
+/** A single test-case that you can run. */
+struct testcase_t {
+       const char *name; /**< An identifier for this case. */
+       testcase_fn fn; /**< The function to run to implement this case. */
+       unsigned long flags; /**< Bitfield of TT_* flags. */
+       const struct testcase_setup_t *setup; /**< Optional setup/cleanup fns*/
+       void *setup_data; /**< Extra data usable by setup function */
+};
+#define END_OF_TESTCASES { NULL, NULL, 0, NULL, NULL }
+
+/** A group of tests that are selectable together. */
+struct testgroup_t {
+       const char *prefix; /**< Prefix to prepend to testnames. */
+       struct testcase_t *cases; /** Array, ending with END_OF_TESTCASES */
+};
+#define END_OF_GROUPS { NULL, NULL}
+
+/** Implementation: called from a test to indicate failure, before logging. */
+void _tinytest_set_test_failed(void);
+/** Implementation: called from a test to indicate that we're skipping. */
+void _tinytest_set_test_skipped(void);
+/** Implementation: return 0 for quiet, 1 for normal, 2 for loud. */
+int _tinytest_get_verbosity(void);
+/** Implementation: Set a flag on tests matching a name; returns number
+ * of tests that matched. */
+int _tinytest_set_flag(struct testgroup_t *, const char *, unsigned long);
+
+/** Set all tests in 'groups' matching the name 'named' to be skipped. */
+#define tinytest_skip(groups, named) \
+       _tinytest_set_flag(groups, named, TT_SKIP)
+
+/** Run a single testcase in a single group. */
+int testcase_run_one(const struct testgroup_t *,const struct testcase_t *);
+/** Run a set of testcases from an END_OF_GROUPS-terminated array of groups,
+    as selected from the command line. */
+int tinytest_main(int argc, const char **argv, struct testgroup_t *groups);
+
+#endif
diff --git a/libevent/test/tinytest_demo.c b/libevent/test/tinytest_demo.c
new file mode 100644 (file)
index 0000000..2a999be
--- /dev/null
@@ -0,0 +1,215 @@
+/* tinytest_demo.c -- Copyright 2009-2012 Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ */
+
+
+/* Welcome to the example file for tinytest!  I'll show you how to set up
+ * some simple and not-so-simple testcases. */
+
+/* Make sure you include these headers. */
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+/* ============================================================ */
+
+/* First, let's see if strcmp is working.  (All your test cases should be
+ * functions declared to take a single void * as) an argument. */
+void
+test_strcmp(void *data)
+{
+       (void)data; /* This testcase takes no data. */
+
+       /* Let's make sure the empty string is equal to itself */
+       if (strcmp("","")) {
+               /* This macro tells tinytest to stop the current test
+                * and go straight to the "end" label. */
+               tt_abort_msg("The empty string was not equal to itself");
+       }
+
+       /* Pretty often, calling tt_abort_msg to indicate failure is more
+          heavy-weight than you want.  Instead, just say: */
+       tt_assert(strcmp("testcase", "testcase") == 0);
+
+       /* Occasionally, you don't want to stop the current testcase just
+          because a single assertion has failed.  In that case, use
+          tt_want: */
+       tt_want(strcmp("tinytest", "testcase") > 0);
+
+       /* You can use the tt_*_op family of macros to compare values and to
+          fail unless they have the relationship you want.  They produce
+          more useful output than tt_assert, since they display the actual
+          values of the failing things.
+
+          Fail unless strcmp("abc, "abc") == 0 */
+       tt_int_op(strcmp("abc", "abc"), ==, 0);
+
+       /* Fail unless strcmp("abc, "abcd") is less than 0 */
+       tt_int_op(strcmp("abc", "abcd"), < , 0);
+
+       /* Incidentally, there's a test_str_op that uses strcmp internally. */
+       tt_str_op("abc", <, "abcd");
+
+
+       /* Every test-case function needs to finish with an "end:"
+          label and (optionally) code to clean up local variables. */
+ end:
+       ;
+}
+
+/* ============================================================ */
+
+/* Now let's mess with setup and teardown functions!  These are handy if
+   you have a bunch of tests that all need a similar environment, and you
+   want to reconstruct that environment freshly for each one. */
+
+/* First you declare a type to hold the environment info, and functions to
+   set it up and tear it down. */
+struct data_buffer {
+       /* We're just going to have couple of character buffer.  Using
+          setup/teardown functions is probably overkill for this case.
+
+          You could also do file descriptors, complicated handles, temporary
+          files, etc. */
+       char buffer1[512];
+       char buffer2[512];
+};
+/* The setup function needs to take a const struct testcase_t and return
+   void* */
+void *
+setup_data_buffer(const struct testcase_t *testcase)
+{
+       struct data_buffer *db = malloc(sizeof(struct data_buffer));
+
+       /* If you had a complicated set of setup rules, you might behave
+          differently here depending on testcase->flags or
+          testcase->setup_data or even or testcase->name. */
+
+       /* Returning a NULL here would mean that we couldn't set up for this
+          test, so we don't need to test db for null. */
+       return db;
+}
+/* The clean function deallocates storage carefully and returns true on
+   success. */
+int
+clean_data_buffer(const struct testcase_t *testcase, void *ptr)
+{
+       struct data_buffer *db = ptr;
+
+       if (db) {
+               free(db);
+               return 1;
+       }
+       return 0;
+}
+/* Finally, declare a testcase_setup_t with these functions. */
+struct testcase_setup_t data_buffer_setup = {
+       setup_data_buffer, clean_data_buffer
+};
+
+
+/* Now let's write our test. */
+void
+test_memcpy(void *ptr)
+{
+       /* This time, we use the argument. */
+       struct data_buffer *db = ptr;
+
+       /* We'll also introduce a local variable that might need cleaning up. */
+       char *mem = NULL;
+
+       /* Let's make sure that memcpy does what we'd like. */
+       strcpy(db->buffer1, "String 0");
+       memcpy(db->buffer2, db->buffer1, sizeof(db->buffer1));
+       tt_str_op(db->buffer1, ==, db->buffer2);
+
+       /* Now we've allocated memory that's referenced by a local variable.
+          The end block of the function will clean it up. */
+       mem = strdup("Hello world.");
+       tt_assert(mem);
+
+       /* Another rather trivial test. */
+       tt_str_op(db->buffer1, !=, mem);
+
+ end:
+       /* This time our end block has something to do. */
+       if (mem)
+               free(mem);
+}
+
+/* ============================================================ */
+
+/* Now we need to make sure that our tests get invoked.          First, you take
+   a bunch of related tests and put them into an array of struct testcase_t.
+*/
+
+struct testcase_t demo_tests[] = {
+       /* Here's a really simple test: it has a name you can refer to it
+          with, and a function to invoke it. */
+       { "strcmp", test_strcmp, },
+
+       /* The second test has a flag, "TT_FORK", to make it run in a
+          subprocess, and a pointer to the testcase_setup_t that configures
+          its environment. */
+       { "memcpy", test_memcpy, TT_FORK, &data_buffer_setup },
+
+       /* The array has to end with END_OF_TESTCASES. */
+       END_OF_TESTCASES
+};
+
+/* Next, we make an array of testgroups.  This is mandatory.  Unlike more
+   heavy-duty testing frameworks, groups can't nest. */
+struct testgroup_t groups[] = {
+
+       /* Every group has a 'prefix', and an array of tests.  That's it. */
+       { "demo/", demo_tests },
+
+       END_OF_GROUPS
+};
+
+
+int
+main(int c, const char **v)
+{
+       /* Finally, just call tinytest_main().  It lets you specify verbose
+          or quiet output with --verbose and --quiet.  You can list
+          specific tests:
+
+              tinytest-demo demo/memcpy
+
+          or use a ..-wildcard to select multiple tests with a common
+          prefix:
+
+              tinytest-demo demo/..
+
+          If you list no tests, you get them all by default, so that
+          "tinytest-demo" and "tinytest-demo .." mean the same thing.
+
+       */
+       return tinytest_main(c, v, groups);
+}
diff --git a/libevent/test/tinytest_local.h b/libevent/test/tinytest_local.h
new file mode 100644 (file)
index 0000000..1a7f75e
--- /dev/null
@@ -0,0 +1,12 @@
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/util.h"
+#include "util-internal.h"
+
+#ifdef snprintf
+#undef snprintf
+#endif
+#define snprintf evutil_snprintf
diff --git a/libevent/test/tinytest_macros.h b/libevent/test/tinytest_macros.h
new file mode 100644 (file)
index 0000000..1a07ad1
--- /dev/null
@@ -0,0 +1,184 @@
+/* tinytest_macros.h -- Copyright 2009-2012 Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _TINYTEST_MACROS_H
+#define _TINYTEST_MACROS_H
+
+/* Helpers for defining statement-like macros */
+#define TT_STMT_BEGIN do {
+#define TT_STMT_END } while (0)
+
+/* Redefine this if your test functions want to abort with something besides
+ * "goto end;" */
+#ifndef TT_EXIT_TEST_FUNCTION
+#define TT_EXIT_TEST_FUNCTION TT_STMT_BEGIN goto end; TT_STMT_END
+#endif
+
+/* Redefine this if you want to note success/failure in some different way. */
+#ifndef TT_DECLARE
+#define TT_DECLARE(prefix, args)                               \
+       TT_STMT_BEGIN                                           \
+       printf("\n  %s %s:%d: ",prefix,__FILE__,__LINE__);      \
+       printf args ;                                           \
+       TT_STMT_END
+#endif
+
+/* Announce a failure. Args are parenthesized printf args. */
+#define TT_GRIPE(args) TT_DECLARE("FAIL", args)
+
+/* Announce a non-failure if we're verbose. */
+#define TT_BLATHER(args)                                               \
+       TT_STMT_BEGIN                                                   \
+       if (_tinytest_get_verbosity()>1) TT_DECLARE("  OK", args);      \
+       TT_STMT_END
+
+#define TT_DIE(args)                                           \
+       TT_STMT_BEGIN                                           \
+       _tinytest_set_test_failed();                            \
+       TT_GRIPE(args);                                         \
+       TT_EXIT_TEST_FUNCTION;                                  \
+       TT_STMT_END
+
+#define TT_FAIL(args)                          \
+       TT_STMT_BEGIN                                           \
+       _tinytest_set_test_failed();                            \
+       TT_GRIPE(args);                                         \
+       TT_STMT_END
+
+/* Fail and abort the current test for the reason in msg */
+#define tt_abort_printf(msg) TT_DIE(msg)
+#define tt_abort_perror(op) TT_DIE(("%s: %s [%d]",(op),strerror(errno), errno))
+#define tt_abort_msg(msg) TT_DIE(("%s", msg))
+#define tt_abort() TT_DIE(("%s", "(Failed.)"))
+
+/* Fail but do not abort the current test for the reason in msg. */
+#define tt_fail_printf(msg) TT_FAIL(msg)
+#define tt_fail_perror(op) TT_FAIL(("%s: %s [%d]",(op),strerror(errno), errno))
+#define tt_fail_msg(msg) TT_FAIL(("%s", msg))
+#define tt_fail() TT_FAIL(("%s", "(Failed.)"))
+
+/* End the current test, and indicate we are skipping it. */
+#define tt_skip()                                              \
+       TT_STMT_BEGIN                                           \
+       _tinytest_set_test_skipped();                           \
+       TT_EXIT_TEST_FUNCTION;                                  \
+       TT_STMT_END
+
+#define _tt_want(b, msg, fail)                         \
+       TT_STMT_BEGIN                                   \
+       if (!(b)) {                                     \
+               _tinytest_set_test_failed();            \
+               TT_GRIPE(("%s",msg));                   \
+               fail;                                   \
+       } else {                                        \
+               TT_BLATHER(("%s",msg));                 \
+       }                                               \
+       TT_STMT_END
+
+/* Assert b, but do not stop the test if b fails.  Log msg on failure. */
+#define tt_want_msg(b, msg)                    \
+       _tt_want(b, msg, );
+
+/* Assert b and stop the test if b fails.  Log msg on failure. */
+#define tt_assert_msg(b, msg)                  \
+       _tt_want(b, msg, TT_EXIT_TEST_FUNCTION);
+
+/* Assert b, but do not stop the test if b fails. */
+#define tt_want(b)   tt_want_msg( (b), "want("#b")")
+/* Assert b, and stop the test if b fails. */
+#define tt_assert(b) tt_assert_msg((b), "assert("#b")")
+
+#define tt_assert_test_fmt_type(a,b,str_test,type,test,printf_type,printf_fmt, \
+    setup_block,cleanup_block,die_on_fail)                             \
+       TT_STMT_BEGIN                                                   \
+       type _val1 = (type)(a);                                         \
+       type _val2 = (type)(b);                                         \
+       int _tt_status = (test);                                        \
+       if (!_tt_status || _tinytest_get_verbosity()>1) {               \
+               printf_type _print;                                     \
+               printf_type _print1;                                    \
+               printf_type _print2;                                    \
+               type _value = _val1;                                    \
+               setup_block;                                            \
+               _print1 = _print;                                       \
+               _value = _val2;                                         \
+               setup_block;                                            \
+               _print2 = _print;                                       \
+               TT_DECLARE(_tt_status?"  OK":"FAIL",                    \
+                          ("assert(%s): "printf_fmt" vs "printf_fmt,   \
+                           str_test, _print1, _print2));               \
+               _print = _print1;                                       \
+               cleanup_block;                                          \
+               _print = _print2;                                       \
+               cleanup_block;                                          \
+               if (!_tt_status) {                                      \
+                       _tinytest_set_test_failed();                    \
+                       die_on_fail ;                                   \
+               }                                                       \
+       }                                                               \
+       TT_STMT_END
+
+#define tt_assert_test_type(a,b,str_test,type,test,fmt,die_on_fail)    \
+       tt_assert_test_fmt_type(a,b,str_test,type,test,type,fmt,        \
+           {_print=_value;},{},die_on_fail)
+
+/* Helper: assert that a op b, when cast to type.  Format the values with
+ * printf format fmt on failure. */
+#define tt_assert_op_type(a,op,b,type,fmt)                             \
+       tt_assert_test_type(a,b,#a" "#op" "#b,type,(_val1 op _val2),fmt, \
+           TT_EXIT_TEST_FUNCTION)
+
+#define tt_int_op(a,op,b)                      \
+       tt_assert_test_type(a,b,#a" "#op" "#b,long,(_val1 op _val2), \
+           "%ld",TT_EXIT_TEST_FUNCTION)
+
+#define tt_uint_op(a,op,b)                                             \
+       tt_assert_test_type(a,b,#a" "#op" "#b,unsigned long,            \
+           (_val1 op _val2),"%lu",TT_EXIT_TEST_FUNCTION)
+
+#define tt_ptr_op(a,op,b)                                              \
+       tt_assert_test_type(a,b,#a" "#op" "#b,void*,                    \
+           (_val1 op _val2),"%p",TT_EXIT_TEST_FUNCTION)
+
+#define tt_str_op(a,op,b)                                              \
+       tt_assert_test_type(a,b,#a" "#op" "#b,const char *,             \
+           (strcmp(_val1,_val2) op 0),"<%s>",TT_EXIT_TEST_FUNCTION)
+
+#define tt_want_int_op(a,op,b)                                         \
+       tt_assert_test_type(a,b,#a" "#op" "#b,long,(_val1 op _val2),"%ld",(void)0)
+
+#define tt_want_uint_op(a,op,b)                                                \
+       tt_assert_test_type(a,b,#a" "#op" "#b,unsigned long,            \
+           (_val1 op _val2),"%lu",(void)0)
+
+#define tt_want_ptr_op(a,op,b)                                         \
+       tt_assert_test_type(a,b,#a" "#op" "#b,void*,                    \
+           (_val1 op _val2),"%p",(void)0)
+
+#define tt_want_str_op(a,op,b)                                         \
+       tt_assert_test_type(a,b,#a" "#op" "#b,const char *,             \
+           (strcmp(_val1,_val2) op 0),"<%s>",(void)0)
+
+#endif
diff --git a/libevent/util-internal.h b/libevent/util-internal.h
new file mode 100644 (file)
index 0000000..47fe962
--- /dev/null
@@ -0,0 +1,319 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef _EVENT_UTIL_INTERNAL_H
+#define _EVENT_UTIL_INTERNAL_H
+
+#include "event2/event-config.h"
+#include <errno.h>
+
+/* For EVUTIL_ASSERT */
+#include "log-internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include "event2/util.h"
+
+#include "ipv6-internal.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* If we need magic to say "inline", get it for free internally. */
+#ifdef _EVENT_inline
+#define inline _EVENT_inline
+#endif
+#ifdef _EVENT___func__
+#define __func__ _EVENT___func__
+#endif
+
+/* A good no-op to use in macro definitions. */
+#define _EVUTIL_NIL_STMT ((void)0)
+/* A no-op that tricks the compiler into thinking a condition is used while
+ * definitely not making any code for it.  Used to compile out asserts while
+ * avoiding "unused variable" warnings.  The "!" forces the compiler to
+ * do the sizeof() on an int, in case "condition" is a bitfield value.
+ */
+#define _EVUTIL_NIL_CONDITION(condition) do { \
+       (void)sizeof(!(condition));  \
+} while(0)
+
+/* Internal use only: macros to match patterns of error codes in a
+   cross-platform way.  We need these macros because of two historical
+   reasons: first, nonblocking IO functions are generally written to give an
+   error on the "blocked now, try later" case, so sometimes an error from a
+   read, write, connect, or accept means "no error; just wait for more
+   data," and we need to look at the error code.  Second, Windows defines
+   a different set of error codes for sockets. */
+
+#ifndef WIN32
+
+/* True iff e is an error that means a read/write operation can be retried. */
+#define EVUTIL_ERR_RW_RETRIABLE(e)                             \
+       ((e) == EINTR || (e) == EAGAIN)
+/* True iff e is an error that means an connect can be retried. */
+#define EVUTIL_ERR_CONNECT_RETRIABLE(e)                        \
+       ((e) == EINTR || (e) == EINPROGRESS)
+/* True iff e is an error that means a accept can be retried. */
+#define EVUTIL_ERR_ACCEPT_RETRIABLE(e)                 \
+       ((e) == EINTR || (e) == EAGAIN || (e) == ECONNABORTED)
+
+/* True iff e is an error that means the connection was refused */
+#define EVUTIL_ERR_CONNECT_REFUSED(e)                                  \
+       ((e) == ECONNREFUSED)
+
+#else
+
+#define EVUTIL_ERR_RW_RETRIABLE(e)                                     \
+       ((e) == WSAEWOULDBLOCK ||                                       \
+           (e) == WSAEINTR)
+
+#define EVUTIL_ERR_CONNECT_RETRIABLE(e)                                        \
+       ((e) == WSAEWOULDBLOCK ||                                       \
+           (e) == WSAEINTR ||                                          \
+           (e) == WSAEINPROGRESS ||                                    \
+           (e) == WSAEINVAL)
+
+#define EVUTIL_ERR_ACCEPT_RETRIABLE(e)                 \
+       EVUTIL_ERR_RW_RETRIABLE(e)
+
+#define EVUTIL_ERR_CONNECT_REFUSED(e)                                  \
+       ((e) == WSAECONNREFUSED)
+
+#endif
+
+#ifdef _EVENT_socklen_t
+#define socklen_t _EVENT_socklen_t
+#endif
+
+/* Arguments for shutdown() */
+#ifdef SHUT_RD
+#define EVUTIL_SHUT_RD SHUT_RD
+#else
+#define EVUTIL_SHUT_RD 0
+#endif
+#ifdef SHUT_WR
+#define EVUTIL_SHUT_WR SHUT_WR
+#else
+#define EVUTIL_SHUT_WR 1
+#endif
+#ifdef SHUT_BOTH
+#define EVUTIL_SHUT_BOTH SHUT_BOTH
+#else
+#define EVUTIL_SHUT_BOTH 2
+#endif
+
+/* Locale-independent replacements for some ctypes functions.  Use these
+ * when you care about ASCII's notion of character types, because you are about
+ * to send those types onto the wire.
+ */
+int EVUTIL_ISALPHA(char c);
+int EVUTIL_ISALNUM(char c);
+int EVUTIL_ISSPACE(char c);
+int EVUTIL_ISDIGIT(char c);
+int EVUTIL_ISXDIGIT(char c);
+int EVUTIL_ISPRINT(char c);
+int EVUTIL_ISLOWER(char c);
+int EVUTIL_ISUPPER(char c);
+char EVUTIL_TOUPPER(char c);
+char EVUTIL_TOLOWER(char c);
+
+/** Helper macro.  If we know that a given pointer points to a field in a
+    structure, return a pointer to the structure itself.  Used to implement
+    our half-baked C OO.  Example:
+
+    struct subtype {
+       int x;
+       struct supertype common;
+       int y;
+    };
+    ...
+    void fn(struct supertype *super) {
+       struct subtype *sub = EVUTIL_UPCAST(super, struct subtype, common);
+       ...
+    }
+ */
+#define EVUTIL_UPCAST(ptr, type, field)                                \
+       ((type *)(((char*)(ptr)) - evutil_offsetof(type, field)))
+
+/* As open(pathname, flags, mode), except that the file is always opened with
+ * the close-on-exec flag set. (And the mode argument is mandatory.)
+ */
+int evutil_open_closeonexec(const char *pathname, int flags, unsigned mode);
+
+int evutil_read_file(const char *filename, char **content_out, size_t *len_out,
+    int is_binary);
+
+int evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen);
+
+int evutil_socket_finished_connecting(evutil_socket_t fd);
+
+int evutil_ersatz_socketpair(int, int , int, evutil_socket_t[]);
+
+int evutil_resolve(int family, const char *hostname, struct sockaddr *sa,
+    ev_socklen_t *socklen, int port);
+
+const char *evutil_getenv(const char *name);
+
+long _evutil_weakrand(void);
+
+/* Evaluates to the same boolean value as 'p', and hints to the compiler that
+ * we expect this value to be false. */
+#if defined(__GNUC__) && __GNUC__ >= 3         /* gcc 3.0 or later */
+#define EVUTIL_UNLIKELY(p) __builtin_expect(!!(p),0)
+#else
+#define EVUTIL_UNLIKELY(p) (p)
+#endif
+
+/* Replacement for assert() that calls event_errx on failure. */
+#ifdef NDEBUG
+#define EVUTIL_ASSERT(cond) _EVUTIL_NIL_CONDITION(cond)
+#define EVUTIL_FAILURE_CHECK(cond) 0
+#else
+#define EVUTIL_ASSERT(cond)                                            \
+       do {                                                            \
+               if (EVUTIL_UNLIKELY(!(cond))) {                         \
+                       event_errx(_EVENT_ERR_ABORT,                    \
+                           "%s:%d: Assertion %s failed in %s",         \
+                           __FILE__,__LINE__,#cond,__func__);          \
+                       /* In case a user-supplied handler tries to */  \
+                       /* return control to us, log and abort here. */ \
+                       (void)fprintf(stderr,                           \
+                           "%s:%d: Assertion %s failed in %s",         \
+                           __FILE__,__LINE__,#cond,__func__);          \
+                       abort();                                        \
+               }                                                       \
+       } while (0)
+#define EVUTIL_FAILURE_CHECK(cond) EVUTIL_UNLIKELY(cond)
+#endif
+
+#ifndef _EVENT_HAVE_STRUCT_SOCKADDR_STORAGE
+/* Replacement for sockaddr storage that we can use internally on platforms
+ * that lack it.  It is not space-efficient, but neither is sockaddr_storage.
+ */
+struct sockaddr_storage {
+       union {
+               struct sockaddr ss_sa;
+               struct sockaddr_in ss_sin;
+               struct sockaddr_in6 ss_sin6;
+               char ss_padding[128];
+       } ss_union;
+};
+#define ss_family ss_union.ss_sa.sa_family
+#endif
+
+/* Internal addrinfo error code.  This one is returned from only from
+ * evutil_getaddrinfo_common, when we are sure that we'll have to hit a DNS
+ * server. */
+#define EVUTIL_EAI_NEED_RESOLVE      -90002
+
+struct evdns_base;
+struct evdns_getaddrinfo_request;
+typedef struct evdns_getaddrinfo_request* (*evdns_getaddrinfo_fn)(
+    struct evdns_base *base,
+    const char *nodename, const char *servname,
+    const struct evutil_addrinfo *hints_in,
+    void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
+
+void evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn);
+
+struct evutil_addrinfo *evutil_new_addrinfo(struct sockaddr *sa,
+    ev_socklen_t socklen, const struct evutil_addrinfo *hints);
+struct evutil_addrinfo *evutil_addrinfo_append(struct evutil_addrinfo *first,
+    struct evutil_addrinfo *append);
+void evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints);
+int evutil_getaddrinfo_common(const char *nodename, const char *servname,
+    struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum);
+
+int evutil_getaddrinfo_async(struct evdns_base *dns_base,
+    const char *nodename, const char *servname,
+    const struct evutil_addrinfo *hints_in,
+    void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
+
+/** Return true iff sa is a looback address. (That is, it is 127.0.0.1/8, or
+ * ::1). */
+int evutil_sockaddr_is_loopback(const struct sockaddr *sa);
+
+
+/**
+    Formats a sockaddr sa into a string buffer of size outlen stored in out.
+    Returns a pointer to out.  Always writes something into out, so it's safe
+    to use the output of this function without checking it for NULL.
+ */
+const char *evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen);
+
+long evutil_tv_to_msec(const struct timeval *tv);
+
+int evutil_hex_char_to_int(char c);
+
+#ifdef WIN32
+HANDLE evutil_load_windows_system_library(const TCHAR *library_name);
+#endif
+
+#ifndef EV_SIZE_FMT
+#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
+#define EV_U64_FMT "%I64u"
+#define EV_I64_FMT "%I64d"
+#define EV_I64_ARG(x) ((__int64)(x))
+#define EV_U64_ARG(x) ((unsigned __int64)(x))
+#else
+#define EV_U64_FMT "%llu"
+#define EV_I64_FMT "%lld"
+#define EV_I64_ARG(x) ((long long)(x))
+#define EV_U64_ARG(x) ((unsigned long long)(x))
+#endif
+#endif
+
+#if defined(__STDC__) && defined(__STDC_VERSION__)
+#if (__STDC_VERSION__ >= 199901L)
+#define EV_SIZE_FMT "%zu"
+#define EV_SSIZE_FMT "%zd"
+#define EV_SIZE_ARG(x) (x)
+#define EV_SSIZE_ARG(x) (x)
+#endif
+#endif
+
+#ifndef EV_SIZE_FMT
+#if (_EVENT_SIZEOF_SIZE_T <= _EVENT_SIZEOF_LONG)
+#define EV_SIZE_FMT "%lu"
+#define EV_SSIZE_FMT "%ld"
+#define EV_SIZE_ARG(x) ((unsigned long)(x))
+#define EV_SSIZE_ARG(x) ((long)(x))
+#else
+#define EV_SIZE_FMT EV_U64_FMT
+#define EV_SSIZE_FMT EV_I64_FMT
+#define EV_SIZE_ARG(x) EV_U64_ARG(x)
+#define EV_SSIZE_ARG(x) EV_I64_ARG(x)
+#endif
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libevent/whatsnew-2.0.txt b/libevent/whatsnew-2.0.txt
new file mode 100644 (file)
index 0000000..be0c71b
--- /dev/null
@@ -0,0 +1,609 @@
+What's New In Libevent 2.0 so far:
+
+1. Meta-issues
+
+1.1. About this document
+
+  This document describes the key differences between Libevent 1.4 and
+  Libevent 2.0, from a user's point of view.  It was most recently
+  updated based on features in git master as of August 2010.
+
+  NOTE: I am very sure that I missed some thing on this list.  Caveat
+  haxxor.
+
+1.2. Better documentation
+
+  There is now a book-in-progress that explains how to use Libevent and its
+  growing pile of APIs.  As of this writing, it covers everything except the
+  http and rpc code.  Check out the latest draft at
+  http://www.wangafu.net/~nickm/libevent-book/ .
+
+2. New and Improved Event APIs
+
+  Many APIs are improved, refactored, or deprecated in Libevent 2.0.
+
+  COMPATIBILITY:
+
+  Nearly all existing code that worked with Libevent 1.4 should still
+  work correctly with Libevent 2.0.  However, if you are writing new code,
+  or if you want to port old code, we strongly recommend using the new APIs
+  and avoiding deprecated APIs as much as possible.
+
+  Binaries linked against Libevent 1.4 will need to be recompiled to link
+  against Libevent 2.0.  This is nothing new; we have never been good at
+  preserving binary compatibility between releases.  We'll try harder in the
+  future, though: see 2.1 below.
+
+2.1. New header layout for improved forward-compatibility
+
+  Libevent 2.0 has a new header layout to make it easier for programmers to
+  write good, well-supported libevent code.  The new headers are divided
+  into three types.
+
+  There are *regular headers*, like event2/event.h.  These headers contain
+  the functions that most programmers will want to use.
+
+  There are *backward compatibility headers*, like event2/event_compat.h.
+  These headers contain declarations for deprecated functions from older
+  versions of Libevent.  Documentation in these headers should suggest what's
+  wrong with the old functions, and what functions you want to start using
+  instead of the old ones.  Some of these functions might be removed in a
+  future release.  New programs should generally not include these headers.
+
+  Finally, there are *structure headers*, like event2/event_struct.h.
+  These headers contain definitions of some structures that Libevent has
+  historically exposed.  Exposing them caused problems in the past,
+  since programs that were compiled to work with one version of Libevent
+  would often stop working with another version that changed the size or
+  layout of some object.  We've moving them into separate headers so
+  that programmers can know that their code is not depending on any
+  unstable aspect of the Libvent ABI.  New programs should generally not
+  include these headers unless they really know what they are doing, are
+  willing to rebuild their software whenever they want to link it
+  against a new version of Libevent, and are willing to risk their code
+  breaking if and when data structures change.
+
+  Functionality that once was located in event.h is now more subdivided.
+  The core event logic is now in event2/event.h.  The "evbuffer" functions
+  for low-level buffer manipulation are in event2/buffer.h.  The
+  "bufferevent" functions for higher-level buffered IO are in
+  event2/bufferevent.h.
+
+  COMPATIBILITY:
+
+  All of the old headers (event.h, evdns.h, evhttp.h, evrpc.h, and
+  evutil.h) will continue to work by including the corresponding new
+  headers.  Old code should not be broken by this change.
+
+2.2. New thread-safe, binary-compatible, harder-to-mess-up APIs
+
+  Some aspects of the historical Libevent API have encouraged
+  non-threadsafe code, or forced code built against one version of Libevent
+  to no longer build with another.  The problems with now-deprecated APIs
+  fell into two categories:
+
+     1) Dependence on the "current" event_base.  In an application with
+        multiple event_bases, Libevent previously had a notion of the
+        "current" event_base.  New events were linked to this base, and
+        the caller needed to explicitly reattach them to another base.
+        This was horribly error-prone.
+
+        Functions like "event_set" that worked with the "current" event_base
+        are now deprecated but still available (see 2.1).  There are new
+        functions like "event_assign" that take an explicit event_base
+        argument when setting up a structure.  Using these functions will help
+        prevent errors in your applications, and to be more threadsafe.
+
+     2) Structure dependence.  Applications needed to allocate 'struct
+        event' themselves, since there was no function in Libevent to do it
+        for them.  But since the size and contents of struct event can
+        change between libevent versions, this created binary-compatibility
+        nightmares.  All structures of this kind are now isolated in
+        _struct.h header (see 2.1), and there are new allocate-and-
+        initialize functions you can use instead of the old initialize-only
+        functions.  For example, instead of malloc and event_set, you
+        can use event_new().
+
+        (For people who do really want to allocate a struct event on the
+        stack, or put one inside another structure, you can still use
+        event2/event_compat.h.)
+
+   So in the case where old code would look like this:
+
+      #include <event.h>
+      ...
+      struct event *ev = malloc(sizeof(struct event));
+      /* This call will cause a buffer overrun if you compile with one version
+         of Libevent and link dynamically against another. */
+      event_set(ev, fd, EV_READ, cb, NULL);
+      /* If you forget this call, your code will break in hard-to-diagnose
+         ways in the presence of multiple event bases. */
+      event_set_base(ev, base);
+
+   New code will look more like this:
+
+     #include <event2/event.h>
+     ...
+     struct event *ev;
+     ev = event_new(base, fd, EV_READ, cb, NULL);
+
+2.3. Overrideable allocation functions
+
+  If you want to override the allocation functions used by libevent
+  (for example, to use a specialized allocator, or debug memory
+  issues, or so on), you can replace them by calling
+  event_set_mem_functions.  It takes replacements for malloc(),
+  free(), and realloc().
+
+  If you're going to use this facility, you need to call it _before_
+  Libevent does any memory allocation; otherwise, Libevent may allocate some
+  memory with malloc(), and free it with the free() function you provide.
+
+  You can disable this feature when you are building Libevent by passing
+  the --disable-malloc-replacement argument to configure.
+
+2.4. Configurable event_base creation
+
+  Older versions of Libevent would always got the fastest backend
+  available, unless you reconfigured their behavior with the environment
+  variables EVENT_NOSELECT, EVENT_NOPOLL, and so forth.  This was annoying
+  to programmers who wanted to pick a backend explicitly without messing
+  with the environment.
+
+  Also, despite our best efforts, not every backend supports every
+  operation we might like.  Some features (like edge-triggered events, or
+  working with non-socket file descriptors) only work with some operating
+  systems' fast backends.  Previously, programmers who cared about this
+  needed to know which backends supported what.  This tended to get quite
+  ungainly.
+
+  There is now an API to choose backends, either by name or by feature.
+  Here is an example:
+
+      struct event_config_t *config;
+      struct event_base *base;
+
+      /* Create a new configuration object. */
+      config = event_config_new();
+      /* We don't want to use the "select" method. */
+      event_config_avoid_method(config, "select");
+      /* We want a method that can work with non-socket file descriptors */
+      event_config_require_features(config, EV_FEATURE_FDS);
+
+      base = event_base_new_with_config(config);
+      if (!base) {
+         /* There is no backend method that does what we want. */
+         exit(1);
+      }
+      event_config_free(config);
+
+  Supported features are documented in event2/event.h
+
+2.5. Socket is now an abstract type
+
+  All APIs that formerly accepted int as a socket type now accept
+  "evutil_socket_t".  On Unix, this is just an alias for "int" as
+  before.  On Windows, however, it's an alias for SOCKET, which can
+  be wider than int on 64-bit platforms.
+
+2.6. Timeouts and persistent events work together.
+
+  Previously, it wasn't useful to set a timeout on a persistent event:
+  the timeout would trigger once, and never again.  This is not what
+  applications tend to want.  Instead, applications tend to want every
+  triggering of the event to re-set the timeout.  So now, if you set
+  up an event like this:
+       struct event *ev;
+       struct timeval tv;
+       ev = event_new(base, fd, EV_READ|EV_PERSIST, cb, NULL);
+       tv.tv_sec = 1;
+       tv.tv_usec = 0;
+       event_add(ev, &tv);
+
+  The callback 'cb' will be invoked whenever fd is ready to read, OR whenever
+  a second has passed since the last invocation of cb.
+
+2.7. Multiple events allowed per fd
+
+  Older versions of Libevent allowed at most one EV_READ event and at most
+  one EV_WRITE event per socket, per event base.  This restriction is no
+  longer present.
+
+2.8. evthread_* functions for thread-safe structures.
+
+  Libevent structures can now be built with locking support.  This code
+  makes it safe to add, remove, and activate events on an event base from a
+  different thread.  (Previously, if you wanted to write multithreaded code
+  with Libevent, you could only an event_base or its events in one thread at
+  a time.)
+
+  If you want threading support and you're using pthreads, you can just
+  call evthread_use_pthreads().  (You'll need to link against the
+  libevent_pthreads library in addition to libevent_core.  These functions are
+  not in libevent_core.)
+
+  If you want threading support and you're using Windows, you can just
+  call evthread_use_windows_threads().
+
+  If you are using some locking system besides Windows and pthreads, You
+  can enable this on a per-event-base level by writing functions to
+  implement mutexes, conditions, and thread IDs, and passing them to
+  evthread_set_lock_callbacks and related functions in event2/thread.h.
+
+  Once locking functions are enabled, every new event_base is created with a
+  lock.  You can prevent a single event_base from being built with a lock
+  disabled by using the EVENT_BASE_FLAG_NOLOCK flag in its
+  event_config.  If an event_base is created with a lock, it is safe to call
+  event_del, event_add, and event_active on its events from any thread.  The
+  event callbacks themselves are still all executed from the thread running
+  the event loop.
+
+  To make an evbuffer or a bufferevent object threadsafe, call its
+  *_enable_locking() function.
+
+  The HTTP api is not currently threadsafe.
+
+  To build Libevent with threading support disabled, pass
+  --disable-thread-support to the configure script.
+
+2.9. Edge-triggered events on some backends.
+
+  With some backends, it's now possible to add the EV_ET flag to an event
+  in order to request that the event's semantics be edge-triggered.  Right
+  now, epoll and kqueue support this.
+
+  The corresponding event_config feature is EV_FEATURE_ET; see 2.4 for more
+  information.
+
+2.10. Better support for huge numbers of timeouts
+
+  The heap-based priority queue timer implementation for Libevent 1.4 is good
+  for randomly distributed timeouts, but suboptimal if you have huge numbers
+  of timeouts that all expire in the same amount of time after their
+  creation.  The new event_base_init_common_timeout() logic lets you signal
+  that a given timeout interval will be very common, and should use a linked
+  list implementation instead of a priority queue.
+
+2.11. Improved debugging support
+
+  It's been pretty easy to forget to delete all your events before you
+  re-initialize them, or otherwise put Libevent in an internally inconsistent
+  state.  You can tell libevent to catch these and other common errors with
+  the new event_enable_debug_mode() call.  Just invoke it before you do
+  any calls to other libevent functions, and it'll catch many common
+  event-level errors in your code.
+
+2.12. Functions to access all event fields
+
+  So that you don't have to access the struct event fields directly, Libevent
+  now provides accessor functions to retrieve everything from an event that
+  you set during event_new() or event_assign().
+
+3. Backend-specific and performance improvements.
+
+3.1. Change-minimization on O(1) backends
+
+  With previous versions of Libevent, if you called event_del() and
+  event_add() repeatedly on a single event between trips to the backend's
+  dispatch function, the backend might wind up making unnecessary calls or
+  passing unnecessary data to the kernel.  The new backend logic batches up
+  redundant adds and deletes, and performs no more operations than necessary
+  at the kernel level.
+
+  This logic is on for the kqueue backend, and available (but off by
+  default) for the epoll backend.  To turn it on for the epoll backend,
+  set the EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST flag in the
+  event_base_cofig, or set the EVENT_EPOLL_USE_CHANGELIST environment
+  variable.  Doing this with epoll may result in weird bugs if you give
+  any fds closed by dup() or its variants.
+
+3.2. Improved notification on Linux
+
+  When we need to wake the event loop up from another thread, we use
+  an epollfd to do so, instead of a socketpair.  This is supposed to be
+  faster.
+
+3.3. Windows: better support for everything
+
+  Bufferevents on Windows can use a new mechanism (off-by-default; see below)
+  to send their data via Windows overlapped IO and get their notifications
+  via the IOCP API.  This should be much faster than using event-based
+  notification.
+
+  Other functions throughout the code have been fixed to work more
+  consistently with Windows.  Libevent now builds on Windows using either
+  mingw, or using MSVC (with nmake).  Libevent works fine with UNICODE
+  defined, or not.
+
+  Data structures are a little smarter: our lookups from socket to pending
+  event are now done with O(1) hash tables rather than O(lg n) red-black
+  trees.
+
+  Unfortunately, the main Windows backend is still select()-based: from
+  testing the IOCP backends on the mailing list, it seems that there isn't
+  actually a way to tell for certain whether a socket is writable with IOCP.
+  Libevent 2.1 may add a multithreaded WaitForMultipleEvents-based
+  backend for better performance with many inactive sockets and better
+  integration with Windows events.
+
+4. Improvements to evbuffers
+
+  Libevent has long had an "evbuffer" implementation to wrap access to an
+  input or output memory buffer.  In previous versions, the implementation
+  was very inefficient and lacked some desirable features.  We've made many
+  improvements in Libevent 2.0.
+
+4.1. Chunked-memory internal representation
+
+  Previously, each evbuffer was a huge chunk of memory.  When we ran out of
+  space in an evbuffer, we used realloc() to grow the chunk of memory.  When
+  data was misaligned, we used memmove to move the data back to the front
+  of the buffer.
+
+  Needless to say, this is a terrible interface for networked IO.
+
+  Now, evbuffers are implemented as a linked list of memory chunks, like
+  most Unix kernels use for network IO.  (See Linux's skbuf interfaces,
+  or *BSD's mbufs).  Data is added at the end of the linked list and
+  removed from the front, so that we don't ever need realloc huge chunks
+  or memmove the whole buffer contents.
+
+  To avoid excessive calls to read and write, we use the readv/writev
+  interfaces (or WSASend/WSARecv on Windows) to do IO on multiple chunks at
+  once with a single system call.
+
+  COMPATIBILITY NOTE:
+  The evbuffer struct is no longer exposed in a header.  The code here is
+  too volatile to expose an official evbuffer structure, and there was never
+  any means provided to create an evbuffer except via evbuffer_new which
+  heap-allocated the buffer.
+
+  If you need access to the whole bufer as a linear chunk of memory, the
+  EVBUFFER_DATA() function still works.  Watch out, though: it needs to copy
+  the buffer's contents in a linear chunk before you can use it.
+
+4.2. More flexible readline support
+
+  The old evbuffer_readline() function (which accepted any sequence of
+  CR and LF characters as a newline, and which couldn't handle lines
+  containing NUL characters), is now deprecated.  The preferred
+  function is evbuffer_readln(), which supports a variety of
+  line-ending styles, and which can return the number of characters in
+  the line returned.
+
+  You can also call evbuffer_search_eol() to find the end of a line
+  in an evbuffer without ever extracting the line.
+
+4.3. Support for file-based IO in evbuffers.
+
+  You can now add chunks of a file into a evbuffer, and Libevent will have
+  your OS use mapped-memory functionality, sendfile, or splice to transfer
+  the data without ever copying it to userspace.  On OSs where this is not
+  supported, Libevent just loads the data.
+
+  There are probably some bugs remaining in this code.  On some platforms
+  (like Windows), it just reads the relevant parts of the file into RAM.
+
+4.4. Support for zero-copy ("scatter/gather") writes in evbuffers.
+
+  You can add a piece of memory to an evbuffer without copying it.
+  Instead, Libevent adds a new element to the evbuffer's linked list of
+  chunks with a pointer to the memory you supplied.  You can do this
+  either with a reference-counted chunk (via evbuffer_add_reference), or
+  by asking Libevent for a pointer to its internal vectors (via
+  evbuffer_reserve_space or evbuffer_peek()).
+
+4.5. Multiple callbacks per evbuffer
+
+  Previously, you could only have one callback active on an evbuffer at a
+  time.  In practice, this meant that if one part of Libevent was using an
+  evbuffer callback to notice when an internal evbuffer was reading or
+  writing data, you couldn't have your own callback on that evbuffer.
+
+  Now, you can now use the evbuffer_add_cb() function to add a callback that
+  does not interfere with any other callbacks.
+
+  The evbuffer_setcb() function is now deprecated.
+
+4.6. New callback interface
+
+  Previously, evbuffer callbacks were invoked with the old size of the
+  buffer and the new size of the buffer.  This interface could not capture
+  operations that simultaneously filled _and_ drained a buffer, or handle
+  cases where we needed to postpone callbacks until multiple operations were
+  complete.
+
+  Callbacks that are set with evbuffer_setcb still use the old API.
+  Callbacks added with evbuffer_add_cb() use a new interface that takes a
+  pointer to a struct holding the total number of bytes drained read and the
+  total number of bytes written.  See event2/buffer.h for full details.
+
+4.7. Misc new evbuffer features
+
+   You can use evbuffer_remove() to move a given number of bytes from one
+   buffer to another.
+
+   The evbuffer_search() function lets you search for repeated instances of
+   a pattern inside an evbuffer.
+
+   You can use evbuffer_freeze() to temporarily suspend drains from or adds
+   to a given evbuffer.  This is useful for code that exposes an evbuffer as
+   part of its public API, but wants users to treat it as a pure source or
+   sink.
+
+   There's an evbuffer_copyout() that looks at the data at the start of an
+   evbuffer without doing a drain.
+
+   You can have an evbuffer defer all of its callbacks, so that rather than
+   being invoked immediately when the evbuffer's length changes, they are
+   invoked from within the event_loop.  This is useful when you have a
+   complex set of callbacks that can change the length of other evbuffers,
+   and you want to avoid having them recurse and overflow your stack.
+
+5. Bufferevents improvements
+
+   Libevent has long included a "bufferevents" structure and related
+   functions that were useful for generic buffered IO on a TCP connection.
+   This is what Libevent uses for its HTTP implementation.  In addition to
+   the improvements that they get for free from the underlying evbuffer
+   implementation above, there are many new features in Libevent 2.0's
+   evbuffers.
+
+5.1. New OO implementations
+
+   The "bufferevent" structure is now an abstract base type with multiple
+   implementations.  This should not break existing code, which always
+   allocated bufferevents with bufferevent_new().
+
+   Current implementations of the bufferevent interface are described below.
+
+5.2. bufferevent_socket_new() replaces bufferevent_new()
+
+   Since bufferevents that use a socket are not the only kind,
+   bufferevent_new() is now deprecated.  Use bufferevent_socket_new()
+   instead.
+
+5.3. Filtered bufferevent IO
+
+   You can use bufferevent_filter_new() to create a bufferevent that wraps
+   around another bufferevent and transforms data it is sending and
+   receiving.  See test/regress_zlib.c for a toy example that uses zlib to
+   compress data before sending it over a bufferevent.
+
+5.3. Linked pairs of bufferevents
+
+   You can use bufferevent_pair_new() to produce two linked
+   bufferevents.  This is like using socketpair, but doesn't require
+   system-calls.
+
+5.4. SSL support for bufferevents with OpenSSL
+
+   There is now a bufferevent type that supports SSL/TLS using the
+   OpenSSL library.  The code for this is build in a separate
+   library, libevent_openssl, so that your programs don't need to
+   link against OpenSSL unless they actually want SSL support.
+
+   There are two ways to construct one of these bufferevents, both
+   declared in <event2/bufferevent_ssl.h>.  If you want to wrap an
+   SSL layer around an existing bufferevent, you would call the
+   bufferevent_openssl_filter_new() function.  If you want to do SSL
+   on a socket directly, call bufferevent_openssl_socket_new().
+
+5.5. IOCP support for bufferevents on Windows
+
+   There is now a bufferevents backend that supports IOCP on Windows.
+   Supposedly, this will eventually make Windows IO much faster for
+   programs using bufferevents.  We'll have to see; the code is not
+   currently optimized at all.  To try it out, call the
+   event_base_start_iocp() method on an event_base before contructing
+   bufferevents.
+
+   This is tricky code; there are probably some bugs hiding here.
+
+5.6. Improved connect support for bufferevents.
+
+   You can now create a bufferevent that is not yet connected to any
+   host, and tell it to connect, either by address or by hostname.
+
+   The functions to do this are bufferevent_socket_connect and
+   bufferevent_socket_connect_hostname.
+
+5.7. Rate-limiting for bufferevents
+
+   If you need to limit the number of bytes read/written by a single
+   bufferevent, or by a group of them, you can do this with a new set of
+   bufferevent rate-limiting calls.
+
+6. Other improvements
+
+6.1. DNS improvements
+
+6.1.1. DNS: IPv6 nameservers
+
+   The evdns code now lets you have nameservers whose addresses are IPv6.
+
+6.1.2. DNS: Better security
+
+   Libevent 2.0 tries harder to resist DNS answer-sniping attacks than
+   earlier versions of evdns.  See comments in the code for full details.
+
+   Notably, evdns now supports the "0x20 hack" to make it harder to
+   impersonate a DNS server.  Additionally, Libevent now uses a strong
+   internal RNG to generate DNS transaction IDs, so you don't need to supply
+   your own.
+
+6.1.3. DNS: Getaddrinfo support
+
+   There's now an asynchronous getaddrinfo clone, evdns_getaddrinfo(),
+   to make the results of the evdns functions more usable.  It doesn't
+   support every feature of a typical platform getaddrinfo() yet, but it
+   is quite close.
+
+   There is also a blocking evutil_getaddrinfo() declared in
+   event2/util.h, to provide a getaddrinfo() implementation for
+   platforms that don't have one, and smooth over the differences in
+   various platforms implementations of RFC3493.
+
+   Bufferevents provide bufferevent_connect_hostname(), which combines
+   the name lookup and connect operations.
+
+6.1.4. DNS: No more evdns globals
+
+   Like an event base, evdns operations are now supposed to use an evdns_base
+   argument.  This makes them easier to wrap for other (more OO) languages,
+   and easier to control the lifetime of.  The old evdns functions will
+   still, of course, continue working.
+
+6.2. Listener support
+
+   You can now more easily automate setting up a bound socket to listen for
+   TCP connections.  Just use the evconnlistener_*() functions in the
+   event2/listener.h header.
+
+   The listener code supports IOCP on Windows if available.
+
+6.3. Secure RNG support
+
+   Network code very frequently needs a secure, hard-to-predict random number
+   generator.  Some operating systems provide a good C implementation of one;
+   others do not.  Libevent 2.0 now provides a consistent implementation
+   based on the arc4random code originally from OpenBSD.  Libevent (and you)
+   can use the evutil_secure_rng_*() functions to access a fairly secure
+   random stream of bytes.
+
+6.4. HTTP
+
+   The evhttp uriencoding and uridecoding APIs have updated versions
+   that behave more correctly, and can handle strings with internal NULs.
+
+   The evhttp query parsing and URI parsing logic can now detect errors
+   more usefully.  Moreover, we include an actual URI parsing function
+   (evhttp_uri_parse()) to correctly parse URIs, so as to discourage
+   people from rolling their own ad-hoc parsing functions.
+
+   There are now accessor functions for the useful fields of struct http
+   and friends; it shouldn't be necessary to access them directly any
+   more.
+
+   Libevent now lets you declare support for all specified HTTP methods,
+   including OPTIONS, PATCH, and so on.  The default list is unchanged.
+
+   Numerous evhttp bugs also got fixed.
+
+7. Infrastructure improvements
+
+7.1. Better unit test framework
+
+   We now use a unit test framework that Nick wrote called "tinytest".
+   The main benefit from Libevent's point of view is that tests which
+   might mess with global state can all run each in their own
+   subprocess.  This way, when there's a bug that makes one unit test
+   crash or mess up global state, it doesn't affect any others.
+
+7.2. Better unit tests
+
+   Despite all the code we've added, our unit tests are much better than
+   before.  Right now, iterating over the different backends on various
+   platforms, I'm getting between 78% and 81% test coverage, compared
+   with less than 45% test coverage in Libevent 1.4.
+
diff --git a/libevent/win32select.c b/libevent/win32select.c
new file mode 100644 (file)
index 0000000..46c32c3
--- /dev/null
@@ -0,0 +1,376 @@
+/*
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2003 Michael A. Davis <mike@datanerds.net>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <winsock2.h>
+#include <windows.h>
+#include <sys/types.h>
+#include <sys/queue.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/util.h"
+#include "event2/event-config.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "event2/event.h"
+#include "event-internal.h"
+#include "evmap-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+
+#define XFREE(ptr) do { if (ptr) mm_free(ptr); } while (0)
+
+extern struct event_list timequeue;
+extern struct event_list addqueue;
+
+struct win_fd_set {
+       u_int fd_count;
+       SOCKET fd_array[1];
+};
+
+/* MSDN says this is required to handle SIGFPE */
+volatile double SIGFPE_REQ = 0.0f;
+
+struct idx_info {
+       int read_pos_plus1;
+       int write_pos_plus1;
+};
+
+struct win32op {
+       unsigned num_fds_in_fd_sets;
+       int resize_out_sets;
+       struct win_fd_set *readset_in;
+       struct win_fd_set *writeset_in;
+       struct win_fd_set *readset_out;
+       struct win_fd_set *writeset_out;
+       struct win_fd_set *exset_out;
+       unsigned signals_are_broken : 1;
+};
+
+static void *win32_init(struct event_base *);
+static int win32_add(struct event_base *, evutil_socket_t, short old, short events, void *_idx);
+static int win32_del(struct event_base *, evutil_socket_t, short old, short events, void *_idx);
+static int win32_dispatch(struct event_base *base, struct timeval *);
+static void win32_dealloc(struct event_base *);
+
+struct eventop win32ops = {
+       "win32",
+       win32_init,
+       win32_add,
+       win32_del,
+       win32_dispatch,
+       win32_dealloc,
+       0, /* doesn't need reinit */
+       0, /* No features supported. */
+       sizeof(struct idx_info),
+};
+
+#define FD_SET_ALLOC_SIZE(n) ((sizeof(struct win_fd_set) + ((n)-1)*sizeof(SOCKET)))
+
+static int
+grow_fd_sets(struct win32op *op, unsigned new_num_fds)
+{
+       size_t size;
+
+       EVUTIL_ASSERT(new_num_fds >= op->readset_in->fd_count &&
+              new_num_fds >= op->writeset_in->fd_count);
+       EVUTIL_ASSERT(new_num_fds >= 1);
+
+       size = FD_SET_ALLOC_SIZE(new_num_fds);
+       if (!(op->readset_in = mm_realloc(op->readset_in, size)))
+               return (-1);
+       if (!(op->writeset_in = mm_realloc(op->writeset_in, size)))
+               return (-1);
+       op->resize_out_sets = 1;
+       op->num_fds_in_fd_sets = new_num_fds;
+       return (0);
+}
+
+static int
+do_fd_set(struct win32op *op, struct idx_info *ent, evutil_socket_t s, int read)
+{
+       struct win_fd_set *set = read ? op->readset_in : op->writeset_in;
+       if (read) {
+               if (ent->read_pos_plus1 > 0)
+                       return (0);
+       } else {
+               if (ent->write_pos_plus1 > 0)
+                       return (0);
+       }
+       if (set->fd_count == op->num_fds_in_fd_sets) {
+               if (grow_fd_sets(op, op->num_fds_in_fd_sets*2))
+                       return (-1);
+               /* set pointer will have changed and needs reiniting! */
+               set = read ? op->readset_in : op->writeset_in;
+       }
+       set->fd_array[set->fd_count] = s;
+       if (read)
+               ent->read_pos_plus1 = set->fd_count+1;
+       else
+               ent->write_pos_plus1 = set->fd_count+1;
+       return (set->fd_count++);
+}
+
+static int
+do_fd_clear(struct event_base *base,
+                       struct win32op *op, struct idx_info *ent, int read)
+{
+       int i;
+       struct win_fd_set *set = read ? op->readset_in : op->writeset_in;
+       if (read) {
+               i = ent->read_pos_plus1 - 1;
+               ent->read_pos_plus1 = 0;
+       } else {
+               i = ent->write_pos_plus1 - 1;
+               ent->write_pos_plus1 = 0;
+       }
+       if (i < 0)
+               return (0);
+       if (--set->fd_count != (unsigned)i) {
+               struct idx_info *ent2;
+               SOCKET s2;
+               s2 = set->fd_array[i] = set->fd_array[set->fd_count];
+
+               ent2 = evmap_io_get_fdinfo(&base->io, s2);
+
+               if (!ent2) /* This indicates a bug. */
+                       return (0);
+               if (read)
+                       ent2->read_pos_plus1 = i+1;
+               else
+                       ent2->write_pos_plus1 = i+1;
+       }
+       return (0);
+}
+
+#define NEVENT 32
+void *
+win32_init(struct event_base *_base)
+{
+       struct win32op *winop;
+       size_t size;
+       if (!(winop = mm_calloc(1, sizeof(struct win32op))))
+               return NULL;
+       winop->num_fds_in_fd_sets = NEVENT;
+       size = FD_SET_ALLOC_SIZE(NEVENT);
+       if (!(winop->readset_in = mm_malloc(size)))
+               goto err;
+       if (!(winop->writeset_in = mm_malloc(size)))
+               goto err;
+       if (!(winop->readset_out = mm_malloc(size)))
+               goto err;
+       if (!(winop->writeset_out = mm_malloc(size)))
+               goto err;
+       if (!(winop->exset_out = mm_malloc(size)))
+               goto err;
+       winop->readset_in->fd_count = winop->writeset_in->fd_count = 0;
+       winop->readset_out->fd_count = winop->writeset_out->fd_count
+               = winop->exset_out->fd_count = 0;
+
+       if (evsig_init(_base) < 0)
+               winop->signals_are_broken = 1;
+
+       return (winop);
+ err:
+       XFREE(winop->readset_in);
+       XFREE(winop->writeset_in);
+       XFREE(winop->readset_out);
+       XFREE(winop->writeset_out);
+       XFREE(winop->exset_out);
+       XFREE(winop);
+       return (NULL);
+}
+
+int
+win32_add(struct event_base *base, evutil_socket_t fd,
+                        short old, short events, void *_idx)
+{
+       struct win32op *win32op = base->evbase;
+       struct idx_info *idx = _idx;
+
+       if ((events & EV_SIGNAL) && win32op->signals_are_broken)
+               return (-1);
+
+       if (!(events & (EV_READ|EV_WRITE)))
+               return (0);
+
+       event_debug(("%s: adding event for %d", __func__, (int)fd));
+       if (events & EV_READ) {
+               if (do_fd_set(win32op, idx, fd, 1)<0)
+                       return (-1);
+       }
+       if (events & EV_WRITE) {
+               if (do_fd_set(win32op, idx, fd, 0)<0)
+                       return (-1);
+       }
+       return (0);
+}
+
+int
+win32_del(struct event_base *base, evutil_socket_t fd, short old, short events,
+                 void *_idx)
+{
+       struct win32op *win32op = base->evbase;
+       struct idx_info *idx = _idx;
+
+       event_debug(("%s: Removing event for %d", __func__, fd));
+       if (events & EV_READ)
+               do_fd_clear(base, win32op, idx, 1);
+       if (events & EV_WRITE)
+               do_fd_clear(base, win32op, idx, 0);
+
+       return 0;
+}
+
+static void
+fd_set_copy(struct win_fd_set *out, const struct win_fd_set *in)
+{
+       out->fd_count = in->fd_count;
+       memcpy(out->fd_array, in->fd_array, in->fd_count * (sizeof(SOCKET)));
+}
+
+/*
+  static void dump_fd_set(struct win_fd_set *s)
+  {
+  unsigned int i;
+  printf("[ ");
+  for(i=0;i<s->fd_count;++i)
+  printf("%d ",(int)s->fd_array[i]);
+  printf("]\n");
+  }
+*/
+
+int
+win32_dispatch(struct event_base *base, struct timeval *tv)
+{
+       struct win32op *win32op = base->evbase;
+       int res = 0;
+       unsigned j, i;
+       int fd_count;
+       SOCKET s;
+
+       if (win32op->resize_out_sets) {
+               size_t size = FD_SET_ALLOC_SIZE(win32op->num_fds_in_fd_sets);
+               if (!(win32op->readset_out = mm_realloc(win32op->readset_out, size)))
+                       return (-1);
+               if (!(win32op->exset_out = mm_realloc(win32op->exset_out, size)))
+                       return (-1);
+               if (!(win32op->writeset_out = mm_realloc(win32op->writeset_out, size)))
+                       return (-1);
+               win32op->resize_out_sets = 0;
+       }
+
+       fd_set_copy(win32op->readset_out, win32op->readset_in);
+       fd_set_copy(win32op->exset_out, win32op->writeset_in);
+       fd_set_copy(win32op->writeset_out, win32op->writeset_in);
+
+       fd_count =
+           (win32op->readset_out->fd_count > win32op->writeset_out->fd_count) ?
+           win32op->readset_out->fd_count : win32op->writeset_out->fd_count;
+
+       if (!fd_count) {
+               long msec = evutil_tv_to_msec(tv);
+               /* Sleep's DWORD argument is unsigned long */
+               if (msec < 0)
+                       msec = LONG_MAX;
+               /* Windows doesn't like you to call select() with no sockets */
+               Sleep(msec);
+               return (0);
+       }
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+       res = select(fd_count,
+                    (struct fd_set*)win32op->readset_out,
+                    (struct fd_set*)win32op->writeset_out,
+                    (struct fd_set*)win32op->exset_out, tv);
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       event_debug(("%s: select returned %d", __func__, res));
+
+       if (res <= 0) {
+               return res;
+       }
+
+       if (win32op->readset_out->fd_count) {
+               i = rand() % win32op->readset_out->fd_count;
+               for (j=0; j<win32op->readset_out->fd_count; ++j) {
+                       if (++i >= win32op->readset_out->fd_count)
+                               i = 0;
+                       s = win32op->readset_out->fd_array[i];
+                       evmap_io_active(base, s, EV_READ);
+               }
+       }
+       if (win32op->exset_out->fd_count) {
+               i = rand() % win32op->exset_out->fd_count;
+               for (j=0; j<win32op->exset_out->fd_count; ++j) {
+                       if (++i >= win32op->exset_out->fd_count)
+                               i = 0;
+                       s = win32op->exset_out->fd_array[i];
+                       evmap_io_active(base, s, EV_WRITE);
+               }
+       }
+       if (win32op->writeset_out->fd_count) {
+               SOCKET s;
+               i = rand() % win32op->writeset_out->fd_count;
+               for (j=0; j<win32op->writeset_out->fd_count; ++j) {
+                       if (++i >= win32op->writeset_out->fd_count)
+                               i = 0;
+                       s = win32op->writeset_out->fd_array[i];
+                       evmap_io_active(base, s, EV_WRITE);
+               }
+       }
+       return (0);
+}
+
+void
+win32_dealloc(struct event_base *_base)
+{
+       struct win32op *win32op = _base->evbase;
+
+       evsig_dealloc(_base);
+       if (win32op->readset_in)
+               mm_free(win32op->readset_in);
+       if (win32op->writeset_in)
+               mm_free(win32op->writeset_in);
+       if (win32op->readset_out)
+               mm_free(win32op->readset_out);
+       if (win32op->writeset_out)
+               mm_free(win32op->writeset_out);
+       if (win32op->exset_out)
+               mm_free(win32op->exset_out);
+       /* XXXXX free the tree. */
+
+       memset(win32op, 0, sizeof(win32op));
+       mm_free(win32op);
+}
index 38f728711e1af493bac5da84b21f51ed472a92dd..6c541a8fe0e6fb42c6aecd76629029a3978e594b 100644 (file)
@@ -2,19 +2,17 @@ EXTRA_DIST = \
        afs-check.m4            \
        cnid-backend.m4         \
        config-checks.m4        \
-       cups.m4                 \
        db3-check.m4            \
        grep-check.m4           \
        gssapi-check.m4         \
        iconv.m4                \
        largefile-check.m4      \
        libgcrypt.m4            \
+       netatalk.m4             \
        pam-check.m4            \
        perl-check.m4           \
        ps-check.m4             \
        quota-check.m4          \
-       snprintf-check.m4       \
-       srvloc.m4               \
        ssl-check.m4            \
        summary.m4              \
        tcp-wrappers.m4         \
index 2b74b8cf8246d56a25b95c157aa5d915bed57052..799cfa2649e6fefab6fd3ffe3fdfc0c9a1a19571 100644 (file)
@@ -1,7 +1,7 @@
 dnl $Id: afs-check.m4,v 1.4 2005-08-11 20:15:35 didg Exp $
 dnl Autoconf macro to check whether AFS support should be enabled
 
-AC_DEFUN([NETATALK_AFS_CHECK], [
+AC_DEFUN([AC_NETATALK_AFS_CHECK], [
        AFS_LIBS=
        AFS_CFLAGS=
 
index eb4cf882efe7fe8ceaec72e974149fbaa3e835c3..2b4f4b7e0f3fce515ffba5ea4f49ba73bcba470f 100644 (file)
@@ -1,12 +1,11 @@
-dnl $Id: config-checks.m4,v 1.6 2005-04-28 20:50:05 bfernhomberg Exp $
 dnl Autoconf macro to set the configuration directories.
 
-AC_DEFUN([NETATALK_CONFIG_DIRS], [
-       PKGCONFDIR="${sysconfdir}/netatalk"
+AC_DEFUN([AC_NETATALK_CONFIG_DIRS], [
+       PKGCONFDIR="${sysconfdir}"
 
        AC_ARG_WITH(pkgconfdir,
                [  --with-pkgconfdir=DIR   package specific configuration in DIR
-                          [[SYSCONF/netatalk]]],
+                          [[$sysconfdir]]],
                        [
                        if test "x$withval" != "x"; then
                                PKGCONFDIR="$withval"
@@ -15,13 +14,13 @@ AC_DEFUN([NETATALK_CONFIG_DIRS], [
        )
 
 
-       SERVERTEXT="${PKGCONFDIR}/msg"
+       SERVERTEXT="${localstatedir}/netatalk/msg"
 
        AC_ARG_WITH(message-dir,
-               [  --with-message-dir=PATH path to server message files [[PKGCONF/msg]]],
+               [  --with-message-dir=PATH path to server message files [[$localstatedir/netatalk/msg/]]],
                [
                        if test x"$withval" = x"no";  then 
-                               AC_MSG_WARN([*** message-dir is mandatory and cannot be disabled, using default ***])
+                               AC_MSG_WARN([message-dir is mandatory and cannot be disabled, using default])
                        elif test "x$withval" != "x" && test x"$withval" != x"yes"; then
                                SERVERTEXT="$withval"
                        fi
diff --git a/macros/cups.m4 b/macros/cups.m4
deleted file mode 100644 (file)
index 5507aa4..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-dnl $Id: cups.m4,v 1.3 2010-04-12 14:28:47 franklahm Exp $
-dnl Autoconf macros to check for CUPS
-
-AC_DEFUN([NETATALK_AC_CUPS], [
-
-       dnl Don't use spool unless it's needed
-       spool_required=no
-       netatalk_cv_use_cups=no
-
-       AC_ARG_ENABLE(cups,
-       [  --enable-cups           Turn on CUPS support (default=auto)])
-
-       if test x$enable_cups != xno; then
-               AC_PATH_PROG(CUPS_CONFIG, cups-config)
-
-               if test "x$CUPS_CONFIG" != x; then
-                       AC_DEFINE(HAVE_CUPS, 1, [Define to enable CUPS Support])
-                       CUPS_CFLAGS="`$CUPS_CONFIG --cflags`"
-                       CUPS_LDFLAGS="`$CUPS_CONFIG --ldflags`"
-                       CUPS_LIBS="`$CUPS_CONFIG --libs`"
-                       CUPS_VERSION="`$CUPS_CONFIG --version`"
-                       AC_DEFINE_UNQUOTED(CUPS_API_VERSION, "`$CUPS_CONFIG --api-version`", [CUPS API Version])
-                       AC_SUBST(CUPS_CFLAGS)
-                       AC_SUBST(CUPS_LDFLAGS)
-                       AC_SUBST(CUPS_LIBS)
-       
-                       AC_MSG_CHECKING([CUPS version])
-                       AC_MSG_RESULT([$CUPS_VERSION])
-                       netatalk_cv_use_cups=yes
-       
-                       if test x"$netatalk_cv_HAVE_USABLE_ICONV" = x"no" ; then
-                               AC_WARN([*** Warning: iconv not found on your system, using simple ascii mapping***])
-                       fi
-                       spool_required="yes"
-               elif test x"$enable_cups" = "xyes"; then
-                       AC_MSG_ERROR([*** CUPS not found. You might need to specify the path to cups-config ***])
-               fi
-       fi
-
-       AC_MSG_CHECKING([whether CUPS support can be enabled])
-       AC_MSG_RESULT([$netatalk_cv_use_cups])
-
-
-       AC_ARG_WITH(spooldir,
-               [  --with-spooldir=PATH     path for spooldir used for CUPS support (LOCALSTATEDIR/spool/netatalk)],[
-
-               if test "$withval" = "no"; then
-                      if test x"$spool_required" = x"yes"; then
-                              AC_MSG_ERROR([*** CUPS support requires a spooldir ***])
-                      else
-                              AC_DEFINE(DISABLE_SPOOL, 1, [Define to enable spooldir support])
-                              AC_MSG_RESULT([spool disabled])
-                               fi
-               elif test "$withval" != "yes"; then
-                       SPOOLDIR="$withval"
-                       AC_MSG_RESULT([spooldir set to $withval])
-               else
-                       SPOOLDIR="${localstatedir}/spool/netatalk"
-                       AC_MSG_RESULT([spool set to default])
-               fi
-       ],[
-               SPOOLDIR="${localstatedir}/spool/netatalk"
-       ])
-
-       AM_CONDITIONAL(USE_SPOOLDIR, test x"$spool_required" = x"yes")
-       AC_SUBST(SPOOLDIR)
-])
index 2cc59cbbb6200f40785c98d22d2c1df944dc1050..902220befa3581e0a1d6a9dea9bc4a850e4ea599 100644 (file)
@@ -1,4 +1,3 @@
-dnl $Id: db3-check.m4,v 1.23 2010-04-12 14:28:48 franklahm Exp $
 dnl Autoconf macros to check for the Berkeley DB library
 
 dnl -- check header for minimum version and return version in
@@ -83,7 +82,8 @@ AC_DEFUN([NETATALK_BDB_TRY_LINK],[
 ])
 
 dnl -- This is called from configure
-AC_DEFUN([AC_PATH_BDB],[
+AC_DEFUN([AC_NETATALK_PATH_BDB],[
+if test "x$bdb_required" = "xyes"; then
     trybdbdir=""
     dobdbsearch=yes
     bdb_search_dirs="/usr/local /usr"
@@ -206,6 +206,7 @@ AC_DEFUN([AC_PATH_BDB],[
         ifelse([$1], , :, [$1])
     else
         ifelse([$2], , :, [$2])     
+               AC_MSG_ERROR([Berkeley DB library required but not found!])
     fi
 
     CFLAGS_REMOVE_USR_INCLUDE(BDB_CFLAGS)
@@ -214,6 +215,7 @@ AC_DEFUN([AC_PATH_BDB],[
     AC_SUBST(BDB_LIBS)
     AC_SUBST(BDB_BIN)
     AC_SUBST(BDB_PATH)
+fi
 ])
 
 
index 0818e5eca5047b2f9f7804209a7652c0e1d5cd3d..dee7892dd4d3a09d56fb6af2fa0442781aea245b 100644 (file)
-dnl $Id: gssapi-check.m4,v 1.3 2005-04-28 20:50:05 bfernhomberg Exp $
 dnl Autoconf macro to check for kerberos
 
 AC_DEFUN([NETATALK_GSSAPI_CHECK], 
 [
-       FOUND_GSSAPI=no
-       GSSAPI_LIBS=""
-       GSSAPI_CFLAGS=""
-
-        AC_ARG_WITH(gssapi,
-                [  --with-gssapi[[=PATH]]    path to GSSAPI for Kerberos V UAM [[auto]]],
-                [compilegssapi=$withval],
-                [compilegssapi=auto]
-        )
-
-       if test x"$compilegssapi" != x"no"; then
+    FOUND_GSSAPI=no
+    GSSAPI_LIBS=""
+    GSSAPI_CFLAGS=""
+    GSSAPI_LDFLAGS=""
+    save_CFLAGS="$CFLAGS"
+    save_LDFLAGS="$LDFLAGS"
+    save_LIBS="$LIBS"
+
+    AC_ARG_WITH(gssapi,
+        [  --with-gssapi[[=PATH]]    path to GSSAPI for Kerberos V UAM [[auto]]],
+        [compilegssapi=$withval],
+        [compilegssapi=auto]
+    )
+
+    if test x"$compilegssapi" != x"no" ; then
+        if test "x$compilegssapi" != "xyes" -a "x$compilegssapi" != "xauto" ; then
+            export CFLAGS="-I$withval/include"
+            export LDFLAGS="-L$withval/${atalk_libname}"
+            AC_MSG_NOTICE([checking for GSSAPI support in $compilegssapi])
+        fi
 
-                if test "x$compilegssapi" != "xyes" -a "x$compilegssapi" != "xauto"; then
-                       GSSAPI_CFLAGS="-I$withval/include"
-                       GSSAPI_CPPFLAGS="-I$withval/include"
-                       GSSAPI_LDFLAGS="-L$withval/${atalk_libname}"
-                       FOUND_GSSAPI=yes
-                       AC_MSG_CHECKING([checking for GSSAPI support in])
-                       AC_MSG_RESULT([$compilegssapi])
+        if test x"$compilegssapi" = x"yes" -o x"$compilegssapi" = x"auto" ; then
+            # check for krb5-config from recent MIT and Heimdal kerberos 5
+            AC_PATH_PROG(KRB5_CONFIG, krb5-config)
+            AC_MSG_CHECKING([for working krb5-config that takes --libs gssapi])
+
+            if test -x "$KRB5_CONFIG" ; then 
+                TEMP="`$KRB5_CONFIG --libs gssapi`"
+                if test $? -eq 0 ; then 
+                    GSSAPI_CFLAGS="`$KRB5_CONFIG --cflags | sed s/@INCLUDE_des@//`"
+                    GSSAPI_LIBS="$TEMP"
+                    FOUND_GSSAPI=yes
+                    AC_MSG_RESULT(yes)
+                else
+                    AC_MSG_RESULT(no. Fallback to previous krb5 detection strategy)
                 fi
+            else
+                AC_MSG_RESULT(no. Fallback to previous krb5 detection strategy)
+            fi
+        fi
+    fi
+
+    if test x"$compilegssapi" != x"no" -a x"$FOUND_GSSAPI" = x"no" ; then
+        # check for gssapi headers
+        gss_headers_found=no
+        AC_CHECK_HEADERS(gssapi.h gssapi/gssapi_generic.h gssapi/gssapi.h gssapi/gssapi_krb5.h,
+            [gss_headers_found=yes])
+        if test x"$gss_headers_found" = x"no" ; then
+            AC_MSG_ERROR([GSSAPI installation not found, headers missing])
+        fi
+        # check for libs
+        AC_SEARCH_LIBS(gss_display_status, [gss gssapi gssapi_krb5])
+        if test x"$ac_cv_search_gss_display_status" = x"no" ; then
+            AC_MSG_ERROR([GSSAPI installation not found, library missing])
+        fi
+        GSSAPI_CFLAGS="$CFLAGS"
+        GSSAPI_LIBS="$LIBS"
+        FOUND_GSSAPI=yes
+    fi
+
+    if test x"$FOUND_GSSAPI" = x"yes" ; then
+        # check for functions
+        export CFLAGS="$GSSAPI_CFLAGS"
+        export LIBS="$GSSAPI_LIBS"
+        AC_CHECK_FUNC(gss_acquire_cred, [], [AC_MSG_ERROR([GSSAPI: required function gss_acquire_cred missing])])
+
+        # Heimdal/MIT compatibility fix
+        if test "$ac_cv_header_gssapi_h" = "yes" ; then
+            AC_EGREP_HEADER(
+                GSS_C_NT_HOSTBASED_SERVICE,
+                gssapi.h,
+                AC_DEFINE(HAVE_GSS_C_NT_HOSTBASED_SERVICE, 1, [Wheter GSS_C_NT_HOSTBASED_SERVICE is in gssapi.h])
+            )
+        else
+            AC_EGREP_HEADER(
+                GSS_C_NT_HOSTBASED_SERVICE,
+                gssapi/gssapi.h,
+                AC_DEFINE(HAVE_GSS_C_NT_HOSTBASED_SERVICE, 1, [Wheter GSS_C_NT_HOSTBASED_SERVICE is in gssapi.h])
+            )
+        fi
 
-
-         # Do no harm to the values of CFLAGS and LIBS while testing for
-         # Kerberos support.
-
-               save_CFLAGS=$CFLAGS
-               save_CPPFLAGS=$CPPFLAGS
-               save_LDFLAGS=$LDFLAGS
-               save_LIBS=$LIBS
-
-       if test x$FOUND_GSSAPI = x"no"; then
-         #################################################
-         # check for krb5-config from recent MIT and Heimdal kerberos 5
-         AC_PATH_PROG(KRB5_CONFIG, krb5-config)
-         AC_MSG_CHECKING(for working krb5-config)
-         if test -x "$KRB5_CONFIG"; then
-           TEMP="`$KRB5_CONFIG --libs gssapi`"
-        if test $? -eq 0 ; then
-               save_CFLAGS=$CFLAGS
-           CFLAGS="";export CFLAGS
-               save_LDFLAGS=$LDFLAGS
-           LDFLAGS="";export LDFLAGS
-           GSSAPI_CFLAGS="`$KRB5_CONFIG --cflags | sed s/@INCLUDE_des@//`"
-           GSSAPI_CPPFLAGS="`$KRB5_CONFIG --cflags | sed s/@INCLUDE_des@//`"
-            GSSAPI_LIBS="$TEMP"
-               CFLAGS=$save_CFLAGS;export CFLAGS
-               LDFLAGS=$save_LDFLAGS;export LDFLAGS
-           FOUND_GSSAPI=yes
-           AC_MSG_RESULT(yes)
-         else
-           AC_MSG_RESULT(no. Fallback to previous krb5 detection strategy)
-         fi
-         else
-           AC_MSG_RESULT(no. Fallback to previous krb5 detection strategy)
-       fi
-       fi
-
-       if test x$FOUND_GSSAPI = x"no"; then
-       #################################################
-       # see if this box has the SuSE location for the heimdal krb implementation
-         AC_MSG_CHECKING(for /usr/include/heimdal)
-         if test -d /usr/include/heimdal; then
-           if test -f /usr/lib/heimdal/lib/libkrb5.a; then
-               GSSAPI_CFLAGS="-I/usr/include/heimdal"
-               GSSAPI_CPPFLAGS="-I/usr/include/heimdal"
-               GSSAPI_LDFLAGS="-L/usr/lib/heimdal/lib"
-               AC_MSG_RESULT(yes)
-               FOUND_GSSAPI=yes
-           else
-               GSSAPI_CFLAGS="-I/usr/include/heimdal"
-               GSSAPI_CPPFLAGS="-I/usr/include/heimdal"
-               AC_MSG_RESULT(yes)
-               FOUND_GSSAPI=yes
-           fi
-         else
-           AC_MSG_RESULT(no)
-         fi
-       fi
-
-       if test x$FOUND_GSSAPI = x"no"; then
-       #################################################
-       # see if this box has the RedHat location for kerberos
-         AC_MSG_CHECKING(for /usr/kerberos)
-         if test -d /usr/kerberos -a -f /usr/kerberos/lib/libkrb5.a; then
-               GSSAPI_LDFLAGS="-L/usr/kerberos/lib"
-               GSSAPI_CFLAGS="-I/usr/kerberos/include"
-               GSSAPI_CPPFLAGS="-I/usr/kerberos/include"
-               AC_MSG_RESULT(yes)
-         else
-               AC_MSG_RESULT(no)
-         fi
-       fi
-
-       CFLAGS="$CFLAGS $GSSAPI_CFLAGS"
-       CPPFLAGS="$CPPFLAGS $GSSAPI_CPPFLAGS"
-       LDFLAGS="$LDFLAGS $GSSAPI_LDFLAGS"
-       LIBS="$LIBS $GSSAPI_LIBS"
-
-
-       # check for gssapi headers
-
-       gss_headers_found=no
-       AC_CHECK_HEADERS(gssapi.h gssapi/gssapi_generic.h gssapi/gssapi.h gssapi/gssapi_krb5.h,[gss_headers_found=yes],[],[])
-       if test x"$gss_headers_found" = x"no"; then
-               AC_MSG_ERROR([GSSAPI installation not found, headers missing])
-       fi
-
-       # check for libs
-
-       AC_CHECK_LIB(gssapi, gss_display_status) 
-       AC_CHECK_LIB(gssapi_krb5, gss_display_status) 
-       AC_CHECK_LIB(gss, gss_display_status) 
-
-       # check for functions
-
-       AC_CHECK_FUNC(gss_acquire_cred,[],[AC_MSG_ERROR([GSSAPI: required function gss_acquire_cred missing])])
-
-       # Heimdal/MIT compatibility fix
-       if test "$ac_cv_header_gssapi_h" = "yes"; then
-           AC_EGREP_HEADER(GSS_C_NT_HOSTBASED_SERVICE, gssapi.h, AC_DEFINE(HAVE_GSS_C_NT_HOSTBASED_SERVICE,1,[Wheter GSS_C_NT_HOSTBASED_SERVICE is in gssapi.h]))
-       else
-           AC_EGREP_HEADER(GSS_C_NT_HOSTBASED_SERVICE, gssapi/gssapi.h, AC_DEFINE(HAVE_GSS_C_NT_HOSTBASED_SERVICE,1,[Wheter GSS_C_NT_HOSTBASED_SERVICE is in gssapi.h]))
-       fi
-
-
-       AC_MSG_CHECKING(whether GSSAPI support is used)
-       if test x"$ac_cv_func_gss_acquire_cred" = x"yes"; then
-               AC_DEFINE(HAVE_GSSAPI,1,[Whether to enable GSSAPI support])
-               AC_MSG_RESULT([yes])
-               GSSAPI_LIBS="$LDFLAGS $LIBS"
-       else
-               AC_MSG_RESULT([no])
-               if test x"$compilegssapi" = x"yes"; then
-                       AC_MSG_ERROR([GSSAPI installation not found])
-               fi
-               GSSAPI_LIBS=""
-       fi
-
-        LIBS="$save_LIBS"
-        CFLAGS="$save_CFLAGS"
-        LDFLAGS="$save_LDFLAGS"
-        CPPFLAGS="$save_CPPFLAGS"
-       fi
-
-        if test x"$ac_cv_func_gss_acquire_cred" = x"yes"; then
+        AC_DEFINE(HAVE_GSSAPI, 1, [Whether to enable GSSAPI support])
+        if test x"$ac_cv_func_gss_acquire_cred" = x"yes" ; then
                 ifelse([$1], , :, [$1])
         else
                 ifelse([$2], , :, [$2])
         fi
+    fi
 
+    AC_SUBST(GSSAPI_LIBS)
+    AC_SUBST(GSSAPI_CFLAGS)
+    AC_SUBST(GSSAPI_LDFLAGS)
 
-       AC_SUBST(GSSAPI_LIBS)
-       AC_SUBST(GSSAPI_CFLAGS)
-       AC_SUBST(GSSAPI_LDFLAGS)
-
+    export LIBS="$save_LIBS"
+    export CFLAGS="$save_CFLAGS"
+    export LDFLAGS="$save_LDFLAGS"
 ])
index 77e0e6bbfe9906f8eab1640a00ac2ad7af5dc56c..4805662d7e3933d04aa648c41cc0d322691e7a23 100644 (file)
@@ -1,4 +1,4 @@
-AC_DEFUN([AC_CHECK_ICONV],
+AC_DEFUN([AC_NETATALK_CHECK_ICONV],
 [
 
 dnl    #################################################
index 957275e2fe5c4703e7c50aed5c18c4f8d246f56c..21b323ec0f23a3d53254daf35117976d16355037 100644 (file)
@@ -8,7 +8,7 @@ dnl version of libgcrypt is at least 1.2.5 *and* the API number is 1.  Using
 dnl this features allows to prevent build against newer versions of libgcrypt
 dnl with a changed API.
 dnl
-AC_DEFUN([AM_PATH_LIBGCRYPT],
+AC_DEFUN([AC_NETATALK_PATH_LIBGCRYPT],
 [ AC_ARG_WITH(libgcrypt-dir,
             AC_HELP_STRING([--with-libgcrypt-dir=PATH],
                            [path where LIBGCRYPT is installed (optional). 
@@ -107,6 +107,11 @@ fi
   if test $ok = yes; then
     LIBGCRYPT_CFLAGS=`$LIBGCRYPT_CONFIG --cflags`
     LIBGCRYPT_LIBS=`$LIBGCRYPT_CONFIG --libs`
+    neta_cv_compile_dhx2=yes
+    neta_cv_have_libgcrypt=yes
+       AC_MSG_NOTICE([Enabling DHX2 UAM])
+       AC_DEFINE(HAVE_LIBGCRYPT, 1, [Define if the DHX2 modules should be built with libgcrypt])
+       AC_DEFINE(UAM_DHX2, 1, [Define if the DHX2 UAM modules should be compiled])
     ifelse([$2], , :, [$2])
   else
     LIBGCRYPT_CFLAGS=""
diff --git a/macros/netatalk.m4 b/macros/netatalk.m4
new file mode 100644 (file)
index 0000000..71c7244
--- /dev/null
@@ -0,0 +1,996 @@
+dnl Kitchen sink for configuration macros
+
+dnl Whether to enable developer build
+AC_DEFUN([AC_DEVELOPER], [
+    AC_MSG_CHECKING([whether to enable developer build])
+    AC_ARG_ENABLE(
+        developer,
+        AS_HELP_STRING([--enable-developer], [whether to enable developer build (ABI checking)]),
+        enable_dev=$enableval,
+        enable_dev=no
+    )
+    AC_MSG_RESULT([$enable_dev])
+    AM_CONDITIONAL(DEVELOPER, test x"$enable_dev" = x"yes")
+])
+
+dnl Whether to disable bundled libevent
+AC_DEFUN([AC_NETATALK_LIBEVENT], [
+    AC_MSG_CHECKING([whether to disable bundled libevent (define CPPFLAGS and LDFLAGS otherwise appropiately to pick up installed version)])
+    AC_ARG_ENABLE(
+        bundled-libevent,
+        [AS_HELP_STRING([--disable-bundled-libevent],[whether the bundled version of libevent shall not be used (define CPPFLAGS and LDFLAGS otherwise appropiately to pick up installed version)
+        ])],
+        use_bundled_libevent=$enableval,
+        use_bundled_libevent=yes
+    )
+
+    if test x"$use_bundled_libevent" = x"yes" ; then
+        AC_CONFIG_SUBDIRS([libevent])
+    fi
+    AM_CONDITIONAL(USE_BUILTIN_LIBEVENT, test x"$use_bundled_libevent" = x"yes")
+])
+
+dnl Filesystem Hierarchy Standard (FHS) compatibility
+AC_DEFUN([AC_NETATALK_FHS], [
+AC_MSG_CHECKING([whether to use Filesystem Hierarchy Standard (FHS) compatibility])
+AC_ARG_ENABLE(fhs,
+       [  --enable-fhs            use Filesystem Hierarchy Standard (FHS) compatibility],[
+       if test "$enableval" = "yes"; then
+               bindir="/bin"
+               sbindir="/sbin"
+               sysconfdir="/etc"
+               libdir="/lib"
+               localstatedir="/var"
+               mandir="/usr/share/man"
+               uams_path="${libdir}/netatalk"
+               PKGCONFDIR="${sysconfdir}"
+               SERVERTEXT="${localstatedir}/netatalk/msg"
+               use_pam_so=yes
+               AC_DEFINE(FHS_COMPATIBILITY, 1, [Define if you want compatibily with the FHS])
+               AC_MSG_RESULT([yes])
+       else
+               AC_MSG_RESULT([no])
+       fi
+       ],[
+               AC_MSG_RESULT([no])
+       ]
+)])
+
+dnl 64bit platform check
+AC_DEFUN([AC_NETATALK_64BIT_LIBS], [
+AC_MSG_CHECKING([whether to check for 64bit libraries])
+# Test if the compiler is in 64bit mode
+echo 'int i;' > conftest.$ac_ext
+atalk_cv_cc_64bit_output=no
+if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.$ac_objext` in
+    *"ELF 64"*)
+      atalk_cv_cc_64bit_output=yes
+      ;;
+    esac
+fi
+rm -rf conftest*
+
+case $host_cpu:$atalk_cv_cc_64bit_output in
+powerpc64:yes | s390x:yes | sparc*:yes | x86_64:yes | i386:yes)
+    case $target_os in
+    solaris2*)
+        AC_MSG_RESULT([yes])
+        atalk_libname="lib/64"
+        ;;
+    *bsd* | dragonfly*)
+        AC_MSG_RESULT([no])
+        atalk_libname="lib"
+        ;;
+    *)
+        AC_MSG_RESULT([yes])
+        atalk_libname="lib64"
+        ;;
+    esac
+    ;;
+*:*)
+    AC_MSG_RESULT([no])
+    atalk_libname="lib"
+    ;;
+esac
+])
+
+dnl Check for optional admin group support
+AC_DEFUN([AC_NETATALK_ADMIN_GROUP], [
+    netatalk_cv_admin_group=yes
+    AC_MSG_CHECKING([for administrative group support])
+    AC_ARG_ENABLE(admin-group,
+           [  --disable-admin-group   disable admin group],[
+            if test x"$enableval" = x"no"; then
+                        AC_DEFINE(ADMIN_GRP, 0, [Define if the admin group should be enabled])
+                        netatalk_cv_admin_group=no
+                        AC_MSG_RESULT([no])
+               else
+                        AC_DEFINE(ADMIN_GRP, 1, [Define if the admin group should be enabled])
+                        AC_MSG_RESULT([yes])
+            fi],[
+               AC_DEFINE(ADMIN_GRP, 1, [Define if the admin group should be enabled])
+               AC_MSG_RESULT([yes])
+       ])
+])
+
+dnl Check for optional cracklib support
+AC_DEFUN([AC_NETATALK_CRACKLIB], [
+netatalk_cv_with_cracklib=no
+AC_ARG_WITH(cracklib,
+       [  --with-cracklib[[=DICT]]  enable/set location of cracklib dictionary [[no]]],[
+       if test "x$withval" != "xno" ; then
+               cracklib="$withval"
+               AC_CHECK_LIB(crack, main, [
+                       AC_DEFINE(USE_CRACKLIB, 1, [Define if cracklib should be used])
+                       LIBS="$LIBS -lcrack"
+                       if test "$cracklib" = "yes"; then
+                               cracklib="/usr/$atalk_libname/cracklib_dict"
+                       fi
+                       AC_DEFINE_UNQUOTED(_PATH_CRACKLIB, "$cracklib",
+                               [path to cracklib dictionary])
+                       AC_MSG_RESULT([setting cracklib dictionary to $cracklib])
+                       netatalk_cv_with_cracklib=yes
+                       ],[
+                       AC_MSG_ERROR([cracklib not found!])
+                       ]
+               )
+       fi
+       ]
+)
+AC_MSG_CHECKING([for cracklib support])
+AC_MSG_RESULT([$netatalk_cv_with_cracklib])
+])
+
+dnl Check whether to enable debug code
+AC_DEFUN([AC_NETATALK_DEBUG], [
+AC_MSG_CHECKING([whether to enable verbose debug code])
+AC_ARG_ENABLE(debug,
+       [  --enable-debug          enable verbose debug code],[
+       if test "$enableval" != "no"; then
+               if test "$enableval" = "yes"; then
+                       AC_DEFINE(DEBUG, 1, [Define if verbose debugging information should be included])
+               else
+                       AC_DEFINE_UNQUOTED(DEBUG, $enableval, [Define if verbose debugging information should be included])
+               fi 
+               AC_MSG_RESULT([yes])
+       else
+               AC_MSG_RESULT([no])
+        AC_DEFINE(NDEBUG, 1, [Disable assertions])
+       fi
+       ],[
+               AC_MSG_RESULT([no])
+        AC_DEFINE(NDEBUG, 1, [Disable assertions])
+       ]
+)
+])
+
+dnl Check whethe to disable tickle SIGALARM stuff, which eases debugging
+AC_DEFUN([AC_NETATALK_DEBUGGING], [
+AC_MSG_CHECKING([whether to enable debugging with debuggers])
+AC_ARG_ENABLE(debugging,
+       [  --enable-debugging      disable SIGALRM timers and DSI tickles (eg for debugging with gdb/dbx/...)],[
+       if test "$enableval" != "no"; then
+               if test "$enableval" = "yes"; then
+                       AC_DEFINE(DEBUGGING, 1, [Define if you want to disable SIGALRM timers and DSI tickles])
+               else
+                       AC_DEFINE_UNQUOTED(DEBUGGING, $enableval, [Define if you want to disable SIGALRM timers and DSI tickles])
+               fi 
+               AC_MSG_RESULT([yes])
+       else
+               AC_MSG_RESULT([no])
+       fi
+       ],[
+               AC_MSG_RESULT([no])
+       ]
+)
+
+])
+
+dnl Check for optional shadow password support
+AC_DEFUN([AC_NETATALK_SHADOW], [
+netatalk_cv_use_shadowpw=no
+AC_ARG_WITH(shadow,
+       [  --with-shadow           enable shadow password support [[auto]]],
+       [netatalk_cv_use_shadowpw="$withval"],
+       [netatalk_cv_use_shadowpw=auto]
+)
+
+if test "x$netatalk_cv_use_shadowpw" != "xno"; then
+    AC_CHECK_HEADER([shadow.h])
+    if test x"$ac_cv_header_shadow_h" = x"yes"; then
+       netatalk_cv_use_shadowpw=yes
+       AC_DEFINE(SHADOWPW, 1, [Define if shadow passwords should be used])
+    else 
+      if test "x$shadowpw" = "xyes"; then
+        AC_MSG_ERROR([shadow support not available])
+      else
+               netatalk_cv_use_shadowpw=no
+      fi
+    fi 
+fi
+
+AC_MSG_CHECKING([whether shadow support should be enabled])
+if test "x$netatalk_cv_use_shadowpw" = "xyes"; then
+       AC_MSG_RESULT([yes])
+else
+       AC_MSG_RESULT([no])
+fi
+])
+
+dnl Check for optional valid-shell-check support
+AC_DEFUN([AC_NETATALK_SHELL_CHECK], [
+netatalk_cv_use_shellcheck=yes
+AC_MSG_CHECKING([whether checking for a valid shell should be enabled])
+AC_ARG_ENABLE(shell-check,
+       [  --disable-shell-check   disable checking for a valid shell],[
+       if test "$enableval" = "no"; then 
+               AC_DEFINE(DISABLE_SHELLCHECK, 1, [Define if shell check should be disabled])
+               AC_MSG_RESULT([no])
+               netatalk_cv_use_shellcheck=no
+       else
+               AC_MSG_RESULT([yes])
+       fi
+       ],[
+               AC_MSG_RESULT([yes])
+       ]
+)
+])
+
+dnl Check for optional sysv initscript install
+AC_DEFUN([AC_NETATALK_INIT_STYLE], [
+    AC_ARG_WITH(init-style,
+                [  --with-init-style       use OS specific init config [[redhat-sysv|redhat-systemd|suse-sysv|suse-systemd|gentoo|netbsd|debian|solaris|systemd]]],
+                init_style="$withval", init_style=none
+    )
+    case "$init_style" in 
+    "redhat")
+           AC_MSG_ERROR([--with-init-style=redhat is obsoleted. Use redhat-sysv or redhat-systemd.])
+        ;;
+    "redhat-sysv")
+           AC_MSG_RESULT([enabling redhat-style sysv (upstart) configuration])
+           ;;
+    "redhat-systemd")
+           AC_MSG_RESULT([enabling redhat-style systemd support])
+           ;;
+    "suse")
+           AC_MSG_ERROR([--with-init-style=suse is obsoleted. Use suse-sysv or suse-systemd.])
+        ;;
+    "suse-sysv")
+           AC_MSG_RESULT([enabling suse-style sysv configuration])
+           ;;
+    "suse-systemd")
+           AC_MSG_RESULT([enabling suse-style systemd support (>=openSUSE12.1)])
+           ;;
+    "gentoo")
+           AC_MSG_RESULT([enabling gentoo-style sysv support])
+        ;;
+    "netbsd")
+           AC_MSG_RESULT([enabling netbsd-style sysv support])
+        ;;
+    "debian")
+           AC_MSG_RESULT([enabling debian-style sysv support])
+        ;;
+    "solaris")
+           AC_MSG_RESULT([enabling solaris-style SMF support])
+        ;;
+    "systemd")
+           AC_MSG_RESULT([use general systemd configuration])
+        ;;
+    "none")
+           AC_MSG_RESULT([disabling init-style support])
+        ;;
+    *)
+           AC_MSG_ERROR([illegal init-style])
+        ;;
+    esac
+    AM_CONDITIONAL(USE_NETBSD, test x$init_style = xnetbsd)
+    AM_CONDITIONAL(USE_REDHAT_SYSV, test x$init_style = xredhat-sysv)
+    AM_CONDITIONAL(USE_SUSE_SYSV, test x$init_style = xsuse-sysv)
+    AM_CONDITIONAL(USE_SOLARIS, test x$init_style = xsolaris)
+    AM_CONDITIONAL(USE_GENTOO, test x$init_style = xgentoo)
+    AM_CONDITIONAL(USE_DEBIAN, test x$init_style = xdebian)
+    AM_CONDITIONAL(USE_SYSTEMD, test x$init_style = xsystemd || test x$init_style = xredhat-systemd || test x$init_style = xsuse-systemd)
+    AM_CONDITIONAL(USE_UNDEF, test x$init_style = xnone)
+
+])
+
+dnl OS specific configuration
+AC_DEFUN([AC_NETATALK_OS_SPECIFIC], [
+case "$host_os" in
+       *aix*)                          this_os=aix ;;
+       *freebsd*)                      this_os=freebsd ;;
+       *hpux11*)                       this_os=hpux11 ;;
+       *irix*)                         this_os=irix ;;
+       *linux*)                        this_os=linux ;;
+       *osx*)                          this_os=macosx ;;
+       *darwin*)                       this_os=macosx ;;
+       *netbsd*)                       this_os=netbsd ;;
+       *openbsd*)                      this_os=openbsd ;;
+       *osf*)                          this_os=tru64 ;;
+       *solaris*)                      this_os=solaris ;;
+esac
+
+case "$host_cpu" in
+       i386|i486|i586|i686|k7)         this_cpu=x86 ;;
+       alpha)                                          this_cpu=alpha ;;
+       mips)                                           this_cpu=mips ;;
+       powerpc|ppc)                            this_cpu=ppc ;;
+esac
+
+dnl --------------------- GNU source
+case "$this_os" in
+       linux)  AC_DEFINE(_GNU_SOURCE, 1, [Whether to use GNU libc extensions])
+        ;;
+     kfreebsd-gnu) AC_DEFINE(_GNU_SOURCE, 1, [Whether to use GNU libc extensions])
+        ;;
+esac
+
+dnl --------------------- operating system specific flags (port from sys/*)
+
+dnl ----- FreeBSD specific -----
+if test x"$this_os" = "xfreebsd"; then 
+       AC_MSG_RESULT([ * FreeBSD specific configuration])
+       AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
+       AC_DEFINE(FREEBSD, 1, [Define if OS is FreeBSD])
+    AC_DEFINE(OPEN_NOFOLLOW_ERRNO, EMLINK, errno returned by open with O_NOFOLLOW)
+fi
+
+dnl ----- GNU/kFreeBSD specific -----
+if test x"$this_os" = "xkfreebsd-gnu"; then 
+       AC_MSG_RESULT([ * GNU/kFreeBSD specific configuration])
+       AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
+       AC_DEFINE(FREEBSD, 1, [Define if OS is FreeBSD])
+    AC_DEFINE(OPEN_NOFOLLOW_ERRNO, EMLINK, errno returned by open with O_NOFOLLOW)
+fi
+
+dnl ----- Linux specific -----
+if test x"$this_os" = "xlinux"; then 
+       AC_MSG_RESULT([ * Linux specific configuration])
+       
+       dnl ----- check if we need the quotactl wrapper
+    AC_CHECK_HEADERS(linux/dqblk_xfs.h,,
+               [AC_CHECK_HEADERS(linux/xqm.h linux/xfs_fs.h)
+               AC_CHECK_HEADERS(xfs/libxfs.h xfs/xqm.h xfs/xfs_fs.h)]
+       )
+
+
+       dnl ----- as far as I can tell, dbtob always does the wrong thing
+       dnl ----- on every single version of linux I've ever played with.
+       dnl ----- see etc/afpd/quota.c
+       AC_DEFINE(HAVE_BROKEN_DBTOB, 1, [Define if dbtob is broken])
+
+       need_dash_r=no
+fi
+
+dnl ----- NetBSD specific -----
+if test x"$this_os" = "xnetbsd"; then 
+       AC_MSG_RESULT([ * NetBSD specific configuration])
+       AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
+       AC_DEFINE(NETBSD, 1, [Define if OS is NetBSD])
+    AC_DEFINE(OPEN_NOFOLLOW_ERRNO, EFTYPE, errno returned by open with O_NOFOLLOW)
+
+       CFLAGS="-I\$(top_srcdir)/sys/netbsd $CFLAGS"
+       need_dash_r=yes 
+
+       dnl ----- NetBSD does not have crypt.h, uses unistd.h -----
+       AC_DEFINE(UAM_DHX, 1, [Define if the DHX UAM modules should be compiled])
+fi
+
+dnl ----- OpenBSD specific -----
+if test x"$this_os" = "xopenbsd"; then 
+       AC_MSG_RESULT([ * OpenBSD specific configuration])
+    AC_DEFINE(BSD4_4, 1, [BSD compatiblity macro])
+       dnl ----- OpenBSD does not have crypt.h, uses unistd.h -----
+       AC_DEFINE(UAM_DHX, 1, [Define if the DHX UAM modules should be compiled])
+fi
+
+dnl ----- Solaris specific -----
+if test x"$this_os" = "xsolaris"; then 
+       AC_MSG_RESULT([ * Solaris specific configuration])
+       AC_DEFINE(__svr4__, 1, [Solaris compatibility macro])
+       AC_DEFINE(_ISOC9X_SOURCE, 1, [Compatibility macro])
+       AC_DEFINE(NO_STRUCT_TM_GMTOFF, 1, [Define if the gmtoff member of struct tm is not available])
+       AC_DEFINE(SOLARIS, 1, [Solaris compatibility macro])
+    AC_DEFINE(_XOPEN_SOURCE, 600, [Solaris compilation environment])
+    AC_DEFINE(__EXTENSIONS__,  1, [Solaris compilation environment])
+       CFLAGS="-I\$(top_srcdir)/sys/generic $CFLAGS"
+       need_dash_r=yes
+       init_style=solaris
+
+       solaris_module=no
+       AC_MSG_CHECKING([if we can build Solaris kernel module])
+       if test -x /usr/ccs/bin/ld && test x"$netatalk_cv_ddp_enabled" = x"yes" ; then
+               solaris_module=yes
+       fi
+       AC_MSG_RESULT([$solaris_module])
+
+       COMPILE_64BIT_KMODULE=no
+       KCFLAGS=""
+       KLDFLAGS=""
+       COMPILE_KERNEL_GCC=no
+
+       if test "$solaris_module" = "yes"; then
+          dnl Solaris kernel module stuff
+           AC_MSG_CHECKING([if we have to build a 64bit kernel module])
+
+          # check for isainfo, if not found it has to be a 32 bit kernel (<=2.6)       
+          if test -x /usr/bin/isainfo; then
+               # check for 64 bit platform
+               if isainfo -kv | grep '^64-bit'; then
+                       COMPILE_64BIT_KMODULE=yes
+               fi
+          fi
+
+          AC_MSG_RESULT([$COMPILE_64BIT_KMODULE])
+
+          if test "${GCC}" = yes; then
+               COMPILE_KERNEL_GCC=yes
+               if test "$COMPILE_64BIT_KMODULE" = yes; then
+               
+                        AC_MSG_CHECKING([if we can build a 64bit kernel module])
+                       
+                        case `$CC --version 2>/dev/null` in
+                       [[12]].* | 3.0.*)
+                               COMPILE_64BIT_KMODULE=no
+                               COMPILE_KERNEL_GCC=no   
+                               solaris_module=no;;
+                       *)
+                               # use for 64 bit
+                               KCFLAGS="-m64"
+                               #KLDFLAGS="-melf64_sparc"
+                               KLDFLAGS="-64";;
+                       esac    
+                       
+                       AC_MSG_RESULT([$COMPILE_64BIT_KMODULE])
+                       
+               else
+                       KCFLAGS=""
+                       KLDFLAGS=""
+               fi
+               KCFLAGS="$KCFLAGS -D_KERNEL -Wall -Wstrict-prototypes"
+           else
+               if test "$COMPILE_64BIT_KMODULE" = yes; then
+                # use Sun CC (for a 64-bit kernel, uncomment " -xarch=v9 -xregs=no%appl ")
+                       KCFLAGS="-xarch=v9 -xregs=no%appl"
+                       KLDFLAGS="-64"
+               else
+                       KCFLAGS=""
+                       KLDFLAGS=""
+               fi
+               KCFLAGS="-D_KERNEL $KCFLAGS -mno-app-regs -munaligned-doubles -fpcc-struct-return"
+          fi
+
+           AC_CACHE_CHECK([for timeout_id_t],netatalk_cv_HAVE_TIMEOUT_ID_T,[
+           AC_LINK_IFELSE([AC_LANG_PROGRAM([[\
+#include <sys/stream.h>
+#include <sys/ddi.h>]], [[\
+timeout_id_t dummy;
+]])],[netatalk_cv_HAVE_TIMEOUT_ID_T=yes],[netatalk_cv_HAVE_TIMEOUT_ID_T=no])])
+
+          AC_DEFINE(HAVE_TIMEOUT_ID_T, test x"$netatalk_cv_HAVE_TIMEOUT_ID" = x"yes", [define for timeout_id_t])
+       fi
+
+       AC_SUBST(COMPILE_KERNEL_GCC)
+       AC_SUBST(COMPILE_64BIT_KMODULE)
+       AC_SUBST(KCFLAGS)
+       AC_SUBST(KLDFLAGS)
+fi
+
+dnl Whether to run ldconfig after installing libraries
+AC_PATH_PROG(NETA_LDCONFIG, ldconfig, , [$PATH$PATH_SEPARATOR/sbin$PATH_SEPARATOR/bin$PATH_SEPARATOR/usr/sbin$PATH_SEPARATOR/usr/bin])
+echo NETA_LDCONFIG = $NETA_LDCONFIG
+AM_CONDITIONAL(RUN_LDCONFIG, test x"$this_os" = x"linux" -a x"$NETA_LDCONFIG" != x"")
+])
+
+dnl Check for building PGP UAM module
+AC_DEFUN([AC_NETATALK_PGP_UAM], [
+AC_MSG_CHECKING([whether the PGP UAM should be build])
+AC_ARG_ENABLE(pgp-uam,
+       [  --enable-pgp-uam        enable build of PGP UAM module],[
+       if test "$enableval" = "yes"; then 
+               if test "x$neta_cv_have_openssl" = "xyes"; then 
+                       AC_DEFINE(UAM_PGP, 1, [Define if the PGP UAM module should be compiled])
+                       compile_pgp=yes
+                       AC_MSG_RESULT([yes])
+               else
+                       AC_MSG_RESULT([no])
+               fi
+       fi
+       ],[
+               AC_MSG_RESULT([no])
+       ]
+)
+])
+
+dnl Check for building Kerberos V UAM module
+AC_DEFUN([AC_NETATALK_KRB5_UAM], [
+netatalk_cv_build_krb5_uam=no
+AC_ARG_ENABLE(krbV-uam,
+       [  --enable-krbV-uam       enable build of Kerberos V UAM module],
+       [
+               if test x"$enableval" = x"yes"; then
+                       NETATALK_GSSAPI_CHECK([
+                               netatalk_cv_build_krb5_uam=yes
+                       ],[
+                               AC_MSG_ERROR([need GSSAPI to build Kerberos V UAM])
+                       ])
+               fi
+       ]
+       
+)
+
+AC_MSG_CHECKING([whether Kerberos V UAM should be build])
+if test x"$netatalk_cv_build_krb5_uam" = x"yes"; then
+       AC_MSG_RESULT([yes])
+else
+       AC_MSG_RESULT([no])
+fi
+AM_CONDITIONAL(USE_GSSAPI, test x"$netatalk_cv_build_krb5_uam" = x"yes")
+])
+
+dnl Check if we can directly use Kerberos 5 API, used for reading keytabs
+dnl and automatically construction DirectoryService names from that, instead
+dnl of requiring special configuration in afp.conf
+AC_DEFUN([AC_NETATALK_KERBEROS], [
+AC_MSG_CHECKING([for Kerberos 5 (necessary for GetSrvrInfo:DirectoryNames support)])
+AC_ARG_WITH([kerberos],
+    [AS_HELP_STRING([--with-kerberos], [Kerberos 5 support (default=auto)])],
+    [],
+    [with_kerberos=auto])
+AC_MSG_RESULT($with_kerberos)
+
+if test x"$with_kerberos" != x"no"; then
+   have_krb5_header="no"
+   AC_CHECK_HEADERS([krb5/krb5.h krb5.h], [have_krb5_header="yes"; break])
+   if test x"$have_krb5_header" = x"no" && test x"$with_kerberos" != x"auto"; then
+      AC_MSG_FAILURE([--with-kerberos was given, but no headers found])
+   fi
+
+   AC_PATH_PROG([KRB5_CONFIG], [krb5-config])
+   AC_MSG_CHECKING([for krb5-config])
+   if test -x "$KRB5_CONFIG"; then
+      AC_MSG_RESULT([$KRB5_CONFIG])
+      KRB5_CFLAGS="`$KRB5_CONFIG --cflags krb5`"
+      KRB5_LIBS="`$KRB5_CONFIG --libs krb5`"
+      AC_SUBST(KRB5_CFLAGS)
+      AC_SUBST(KRB5_LIBS)
+      with_kerberos="yes"
+   else
+      AC_MSG_RESULT([not found])
+      if test x"$with_kerberos" != x"auto"; then
+         AC_MSG_FAILURE([--with-kerberos was given, but krb5-config could not be found])
+      fi
+   fi
+fi
+
+if test x"$with_kerberos" = x"yes"; then
+   AC_DEFINE([HAVE_KERBEROS], [1], [Define if Kerberos 5 is available])
+fi
+
+dnl Check for krb5_free_unparsed_name and krb5_free_error_message
+save_CFLAGS="$CFLAGS"
+save_LIBS="$LIBS"
+CFLAGS="$KRB5_CFLAGS"
+LIBS="$KRB5_LIBS"
+AC_CHECK_FUNCS([krb5_free_unparsed_name krb5_free_error_message])
+CFLAGS="$save_CFLAGS"
+LIBS="$save_LIBS"
+])
+
+dnl Check for overwrite the config files or not
+AC_DEFUN([AC_NETATALK_OVERWRITE_CONFIG], [
+AC_MSG_CHECKING([whether configuration files should be overwritten])
+AC_ARG_ENABLE(overwrite,
+       [  --enable-overwrite      overwrite configuration files during installation],
+       [OVERWRITE_CONFIG="${enable_overwrite}"],
+       [OVERWRITE_CONFIG="no"]
+)
+AC_MSG_RESULT([$OVERWRITE_CONFIG])
+AC_SUBST(OVERWRITE_CONFIG)
+])
+
+dnl Check for LDAP support, for client-side ACL visibility
+AC_DEFUN([AC_NETATALK_LDAP], [
+AC_MSG_CHECKING(for LDAP (necessary for client-side ACL visibility))
+AC_ARG_WITH(ldap,
+    [AS_HELP_STRING([--with-ldap],
+        [LDAP support (default=auto)])],
+        netatalk_cv_ldap=$withval,
+        netatalk_cv_ldap=auto
+        )
+AC_MSG_RESULT($netatalk_cv_ldap)
+
+save_CFLAGS="$CFLAGS"
+save_LDFLAGS="$LDFLAGS"
+save_LIBS="$LIBS"
+CFLAGS=""
+LDFLAGS=""
+LIBS=""
+LDAP_CFLAGS=""
+LDAP_LDFLAGS=""
+LDAP_LIBS=""
+
+if test x"$netatalk_cv_ldap" != x"no" ; then
+   if test x"$netatalk_cv_ldap" != x"yes" -a x"$netatalk_cv_ldap" != x"auto"; then
+       CFLAGS="-I$netatalk_cv_ldap/include"
+       LDFLAGS="-L$netatalk_cv_ldap/lib"
+   fi
+       AC_CHECK_HEADER([ldap.h], netatalk_cv_ldap=yes,
+        [ if test x"$netatalk_cv_ldap" = x"yes" ; then
+            AC_MSG_ERROR([Missing LDAP headers])
+        fi
+               netatalk_cv_ldap=no
+        ])
+       AC_CHECK_LIB(ldap, ldap_init, netatalk_cv_ldap=yes,
+        [ if test x"$netatalk_cv_ldap" = x"yes" ; then
+            AC_MSG_ERROR([Missing LDAP library])
+        fi
+               netatalk_cv_ldap=no
+        ])
+fi
+
+if test x"$netatalk_cv_ldap" = x"yes"; then
+    LDAP_CFLAGS="$CFLAGS"
+    LDAP_LDFLAGS="$LDFLAGS"
+    LDAP_LIBS="-lldap"
+       AC_DEFINE(HAVE_LDAP,1,[Whether LDAP is available])
+fi
+
+AC_SUBST(LDAP_CFLAGS)
+AC_SUBST(LDAP_LDFLAGS)
+AC_SUBST(LDAP_LIBS)
+CFLAGS="$save_CFLAGS"
+LDLFLAGS="$save_LDLFLAGS"
+LIBS="$save_LIBS"
+])
+
+dnl Check for ACL support
+AC_DEFUN([AC_NETATALK_ACL], [
+AC_MSG_CHECKING(whether to support ACLs)
+AC_ARG_WITH(acls,
+    [AS_HELP_STRING([--with-acls],
+        [Include ACL support (default=auto)])],
+    [ case "$withval" in
+      yes|no)
+          with_acl_support="$withval"
+                 ;;
+      *)
+          with_acl_support=auto
+          ;;
+      esac ],
+    [with_acl_support=auto])
+AC_MSG_RESULT($with_acl_support)
+
+if test x"$with_acl_support" = x"no"; then
+       AC_MSG_RESULT(Disabling ACL support)
+       AC_DEFINE(HAVE_NO_ACLS,1,[Whether no ACLs support should be built in])
+else
+    with_acl_support=yes
+fi
+
+if test x"$with_acl_support" = x"yes" ; then
+       AC_MSG_NOTICE(checking whether ACL support is available:)
+       case "$host_os" in
+       *sysv5*)
+               AC_MSG_NOTICE(Using UnixWare ACLs)
+               AC_DEFINE(HAVE_UNIXWARE_ACLS,1,[Whether UnixWare ACLs are available])
+               ;;
+       *solaris*)
+               AC_MSG_NOTICE(Using solaris ACLs)
+               AC_DEFINE(HAVE_SOLARIS_ACLS,1,[Whether solaris ACLs are available])
+               ACL_LIBS="$ACL_LIBS -lsec"
+               ;;
+       *hpux*)
+               AC_MSG_NOTICE(Using HPUX ACLs)
+               AC_DEFINE(HAVE_HPUX_ACLS,1,[Whether HPUX ACLs are available])
+               ;;
+       *irix*)
+               AC_MSG_NOTICE(Using IRIX ACLs)
+               AC_DEFINE(HAVE_IRIX_ACLS,1,[Whether IRIX ACLs are available])
+               ;;
+       *aix*)
+               AC_MSG_NOTICE(Using AIX ACLs)
+               AC_DEFINE(HAVE_AIX_ACLS,1,[Whether AIX ACLs are available])
+               ;;
+       *osf*)
+               AC_MSG_NOTICE(Using Tru64 ACLs)
+               AC_DEFINE(HAVE_TRU64_ACLS,1,[Whether Tru64 ACLs are available])
+               ACL_LIBS="$ACL_LIBS -lpacl"
+               ;;
+       *darwin*)
+               AC_MSG_NOTICE(ACLs on Darwin currently not supported)
+               AC_DEFINE(HAVE_NO_ACLS,1,[Whether no ACLs support is available])
+               ;;
+       *)
+               AC_CHECK_LIB(acl,acl_get_file,[ACL_LIBS="$ACL_LIBS -lacl"])
+               case "$host_os" in
+               *linux*)
+                       AC_CHECK_LIB(attr,getxattr,[ACL_LIBS="$ACL_LIBS -lattr"])
+                       ;;
+               esac
+               AC_CACHE_CHECK([for POSIX ACL support],netatalk_cv_HAVE_POSIX_ACLS,[
+                       acl_LIBS=$LIBS
+                       LIBS="$LIBS $ACL_LIBS"
+                       AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+                               #include <sys/types.h>
+                               #include <sys/acl.h>
+                       ]], [[
+                               acl_t acl;
+                               int entry_id;
+                               acl_entry_t *entry_p;
+                               return acl_get_entry(acl, entry_id, entry_p);
+                       ]])],[netatalk_cv_HAVE_POSIX_ACLS=yes],[netatalk_cv_HAVE_POSIX_ACLS=no
+                with_acl_support=no])
+                       LIBS=$acl_LIBS
+               ])
+               if test x"$netatalk_cv_HAVE_POSIX_ACLS" = x"yes"; then
+                       AC_MSG_NOTICE(Using POSIX ACLs)
+                       AC_DEFINE(HAVE_POSIX_ACLS,1,[Whether POSIX ACLs are available])
+                       AC_CACHE_CHECK([for acl_get_perm_np],netatalk_cv_HAVE_ACL_GET_PERM_NP,[
+                               acl_LIBS=$LIBS
+                               LIBS="$LIBS $ACL_LIBS"
+                               AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+                                       #include <sys/types.h>
+                                       #include <sys/acl.h>
+                               ]], [[
+                                       acl_permset_t permset_d;
+                                       acl_perm_t perm;
+                                       return acl_get_perm_np(permset_d, perm);
+                               ]])],[netatalk_cv_HAVE_ACL_GET_PERM_NP=yes],[netatalk_cv_HAVE_ACL_GET_PERM_NP=no])
+                               LIBS=$acl_LIBS
+                       ])
+                       if test x"$netatalk_cv_HAVE_ACL_GET_PERM_NP" = x"yes"; then
+                               AC_DEFINE(HAVE_ACL_GET_PERM_NP,1,[Whether acl_get_perm_np() is available])
+                       fi
+
+
+                       AC_CACHE_CHECK([for acl_from_mode], netatalk_cv_HAVE_ACL_FROM_MODE,[
+                               acl_LIBS=$LIBS
+                               LIBS="$LIBS $ACL_LIBS"
+                AC_CHECK_FUNCS(acl_from_mode,
+                               [netatalk_cv_HAVE_ACL_FROM_MODE=yes],
+                               [netatalk_cv_HAVE_ACL_FROM_MODE=no])
+                               LIBS=$acl_LIBS
+                       ])
+                       if test x"netatalk_cv_HAVE_ACL_FROM_MODE" = x"yes"; then
+                               AC_DEFINE(HAVE_ACL_FROM_MODE,1,[Whether acl_from_mode() is available])
+                       fi
+
+               else
+                       AC_MSG_NOTICE(ACL support is not avaliable)
+                       AC_DEFINE(HAVE_NO_ACLS,1,[Whether no ACLs support is available])
+               fi
+               ;;
+    esac
+fi
+
+if test x"$with_acl_support" = x"yes" ; then
+   AC_CHECK_HEADERS([acl/libacl.h])
+    AC_DEFINE(HAVE_ACLS,1,[Whether ACLs support is available])
+    AC_SUBST(ACL_LIBS)
+fi
+])
+
+dnl Check for Extended Attributes support
+AC_DEFUN([AC_NETATALK_EXTENDED_ATTRIBUTES], [
+neta_cv_eas="ad"
+neta_cv_eas_sys_found=no
+neta_cv_eas_sys_not_found=no
+
+AC_CHECK_HEADERS(sys/attributes.h attr/xattr.h sys/xattr.h sys/extattr.h sys/uio.h sys/ea.h)
+
+case "$this_os" in
+
+  *osf*)
+       AC_SEARCH_LIBS(getproplist, [proplist])
+       AC_CHECK_FUNCS([getproplist fgetproplist setproplist fsetproplist],
+                   [neta_cv_eas_sys_found=yes],
+                   [neta_cv_eas_sys_not_found=yes])
+       AC_CHECK_FUNCS([delproplist fdelproplist add_proplist_entry get_proplist_entry],,
+                   [neta_cv_eas_sys_not_found=yes])
+       AC_CHECK_FUNCS([sizeof_proplist_entry],,
+                   [neta_cv_eas_sys_not_found=yes])
+  ;;
+
+  *solaris*)
+       AC_CHECK_FUNCS([attropen],
+                   [neta_cv_eas_sys_found=yes; AC_DEFINE(HAVE_EAFD, 1, [extattr API has full fledged fds for EAs])],
+                   [neta_cv_eas_sys_not_found=yes])
+  ;;
+
+  'freebsd')
+    AC_CHECK_FUNCS([extattr_delete_fd extattr_delete_file extattr_delete_link],
+                   [neta_cv_eas_sys_found=yes],
+                   [neta_cv_eas_sys_not_found=yes])
+    AC_CHECK_FUNCS([extattr_get_fd extattr_get_file extattr_get_link],,
+                   [neta_cv_eas_sys_not_found=yes])
+    AC_CHECK_FUNCS([extattr_list_fd extattr_list_file extattr_list_link],,
+                   [neta_cv_eas_sys_not_found=yes])
+    AC_CHECK_FUNCS([extattr_set_fd extattr_set_file extattr_set_link],,
+                   [neta_cv_eas_sys_not_found=yes])
+  ;;
+
+  *freebsd4* | *dragonfly* )
+    AC_DEFINE(BROKEN_EXTATTR, 1, [Does extattr API work])
+  ;;
+
+  *)
+       AC_SEARCH_LIBS(getxattr, [attr])
+
+    if test "x$neta_cv_eas_sys_found" != "xyes" ; then
+       AC_CHECK_FUNCS([getxattr lgetxattr fgetxattr listxattr llistxattr],
+                      [neta_cv_eas_sys_found=yes],
+                      [neta_cv_eas_sys_not_found=yes])
+          AC_CHECK_FUNCS([flistxattr removexattr lremovexattr fremovexattr],,
+                      [neta_cv_eas_sys_not_found=yes])
+          AC_CHECK_FUNCS([setxattr lsetxattr fsetxattr],,
+                      [neta_cv_eas_sys_not_found=yes])
+    fi
+
+    if test "x$neta_cv_eas_sys_found" != "xyes" ; then
+          AC_CHECK_FUNCS([getea fgetea lgetea listea flistea llistea],
+                      [neta_cv_eas_sys_found=yes],
+                      [neta_cv_eas_sys_not_found=yes])
+          AC_CHECK_FUNCS([removeea fremoveea lremoveea setea fsetea lsetea],,
+                      [neta_cv_eas_sys_not_found=yes])
+    fi
+
+    if test "x$neta_cv_eas_sys_found" != "xyes" ; then
+          AC_CHECK_FUNCS([attr_get attr_list attr_set attr_remove],,
+                      [neta_cv_eas_sys_not_found=yes])
+       AC_CHECK_FUNCS([attr_getf attr_listf attr_setf attr_removef],,
+                      [neta_cv_eas_sys_not_found=yes])
+    fi
+  ;;
+esac
+
+# Do xattr functions take additional options like on Darwin?
+if test x"$ac_cv_func_getxattr" = x"yes" ; then
+       AC_CACHE_CHECK([whether xattr interface takes additional options], smb_attr_cv_xattr_add_opt, [
+               old_LIBS=$LIBS
+               LIBS="$LIBS $ACL_LIBS"
+               AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+                       #include <sys/types.h>
+                       #if HAVE_ATTR_XATTR_H
+                       #include <attr/xattr.h>
+                       #elif HAVE_SYS_XATTR_H
+                       #include <sys/xattr.h>
+                       #endif
+               ]], [[
+                       getxattr(0, 0, 0, 0, 0, 0);
+               ]])],[smb_attr_cv_xattr_add_opt=yes],[smb_attr_cv_xattr_add_opt=no;LIBS=$old_LIBS])
+       ])
+       if test x"$smb_attr_cv_xattr_add_opt" = x"yes"; then
+               AC_DEFINE(XATTR_ADD_OPT, 1, [xattr functions have additional options])
+       fi
+fi
+
+if test "x$neta_cv_eas_sys_found" = "xyes" ; then
+   if test "x$neta_cv_eas_sys_not_found" != "xyes" ; then
+      neta_cv_eas="$neta_cv_eas | sys"
+   fi
+fi
+AC_DEFINE_UNQUOTED(EA_MODULES,["$neta_cv_eas"],[Available Extended Attributes modules])
+])
+
+dnl Check for libsmbsharemodes from Samba for Samba/Netatalk access/deny/share modes interop
+dnl Defines "neta_cv_have_smbshmd" to "yes" or "no"
+dnl AC_SUBST's "SMB_SHAREMODES_CFLAGS" and "SMB_SHAREMODES_LDFLAGS"
+dnl AM_CONDITIONAL's "USE_SMB_SHAREMODES"
+AC_DEFUN([AC_NETATALK_SMB_SHAREMODES], [
+    neta_cv_have_smbshmd=no
+    AC_ARG_WITH(smbsharemodes-lib,
+                [  --with-smbsharemodes-lib=PATH        PATH to libsmbsharemodes lib from Samba],
+                [SMB_SHAREMODES_LDFLAGS="-L$withval -lsmbsharemodes"]
+    )
+    AC_ARG_WITH(smbsharemodes-include,
+                [  --with-smbsharemodes-include=PATH    PATH to libsmbsharemodes header from Samba],
+                [SMB_SHAREMODES_CFLAGS="-I$withval"]
+    )
+    AC_ARG_WITH(smbsharemodes,
+                [AS_HELP_STRING([--with-smbsharemodes],[Samba interop (default is yes)])],
+                [use_smbsharemodes=$withval],
+                [use_smbsharemodes=yes]
+    )
+
+    if test x"$use_smbsharemodes" = x"yes" ; then
+        AC_MSG_CHECKING([whether to enable Samba/Netatalk access/deny/share-modes interop])
+
+        saved_CFLAGS="$CFLAGS"
+        saved_LDFLAGS="$LDFLAGS"
+        CFLAGS="$SMB_SHAREMODES_CFLAGS $CFLAGS"
+        LDFLAGS="$SMB_SHAREMODES_LDFLAGS $LDFLAGS"
+
+        AC_LINK_IFELSE(
+            [#include <unistd.h>
+             #include <stdio.h>
+             #include <sys/time.h>
+             #include <time.h>
+             #include <stdint.h>
+             /* From messages.h */
+             struct server_id {
+                 pid_t pid;
+             };
+             #include "smb_share_modes.h"
+             int main(void) { (void)smb_share_mode_db_open(""); return 0;}],
+            [neta_cv_have_smbshmd=yes]
+        )
+
+        AC_MSG_RESULT($neta_cv_have_smbshmd)
+        AC_SUBST(SMB_SHAREMODES_CFLAGS, [$SMB_SHAREMODES_CFLAGS])
+        AC_SUBST(SMB_SHAREMODES_LDFLAGS, [$SMB_SHAREMODES_LDFLAGS])
+        CFLAGS="$saved_CFLAGS"
+        LDFLAGS="$saved_LDFLAGS"
+    fi
+
+    AM_CONDITIONAL(USE_SMB_SHAREMODES, test x"$neta_cv_have_smbshmd" = x"yes")
+])
+
+dnl ------ Check for sendfile() --------
+AC_DEFUN([AC_NETATALK_SENDFILE], [
+netatalk_cv_search_sendfile=yes
+AC_ARG_ENABLE(sendfile,
+    [  --disable-sendfile       disable sendfile syscall],
+    [if test x"$enableval" = x"no"; then
+            netatalk_cv_search_sendfile=no
+        fi]
+)
+
+if test x"$netatalk_cv_search_sendfile" = x"yes"; then
+   case "$host_os" in
+   *linux*)
+        AC_DEFINE(SENDFILE_FLAVOR_LINUX,1,[Whether linux sendfile() API is available])
+        AC_CHECK_FUNC([sendfile], [netatalk_cv_HAVE_SENDFILE=yes])
+        ;;
+
+    *solaris*)
+        AC_DEFINE(SENDFILE_FLAVOR_SOLARIS, 1, [Solaris sendfile()])
+        AC_SEARCH_LIBS(sendfile, sendfile)
+        AC_CHECK_FUNC([sendfile], [netatalk_cv_HAVE_SENDFILE=yes])
+        AC_CHECK_FUNCS([sendfilev])
+        ;;
+
+    *freebsd*)
+        AC_DEFINE(SENDFILE_FLAVOR_BSD, 1, [Define if the sendfile() function uses BSD semantics])
+        AC_CHECK_FUNC([sendfile], [netatalk_cv_HAVE_SENDFILE=yes])
+        ;;
+
+    *)
+        ;;
+
+    esac
+
+    if test x"$netatalk_cv_HAVE_SENDFILE" = x"yes"; then
+        AC_DEFINE(WITH_SENDFILE,1,[Whether sendfile() should be used])
+    fi
+fi
+])
+
+dnl --------------------- Check if realpath() takes NULL
+AC_DEFUN([AC_NETATALK_REALPATH], [
+AC_CACHE_CHECK([if the realpath function allows a NULL argument],
+    neta_cv_REALPATH_TAKES_NULL, [
+        AC_RUN_IFELSE([AC_LANG_SOURCE([[
+            #include <stdio.h>
+            #include <limits.h>
+            #include <signal.h>
+
+            void exit_on_core(int ignored) {
+                 exit(1);
+            }
+
+            main() {
+                char *newpath;
+                signal(SIGSEGV, exit_on_core);
+                newpath = realpath("/tmp", NULL);
+                exit((newpath != NULL) ? 0 : 1);
+            }]])],[neta_cv_REALPATH_TAKES_NULL=yes],[neta_cv_REALPATH_TAKES_NULL=no],[neta_cv_REALPATH_TAKES_NULL=cross
+        ])
+    ]
+)
+
+if test x"$neta_cv_REALPATH_TAKES_NULL" = x"yes"; then
+    AC_DEFINE(REALPATH_TAKES_NULL,1,[Whether the realpath function allows NULL])
+fi
+])
index e5663db347fb0f5e3b08884791014305e5c3dbc4..6bc40cbad841562161bf2c1a6a1f3cd776cdb5e4 100644 (file)
@@ -1,7 +1,8 @@
 dnl $Id: pam-check.m4,v 1.6 2010-01-11 13:06:02 franklahm Exp $
 dnl PAM finding macro
 
-AC_DEFUN([AC_PATH_PAM], [
+AC_DEFUN([AC_NETATALK_PATH_PAM], [
+    netatalk_cv_use_pam=no
        AC_ARG_WITH(pam, [  --with-pam[[=PATH]]       specify path to PAM installation [[auto]]],
                [
                        require_pam="yes"
@@ -125,6 +126,10 @@ AC_DEFUN([AC_PATH_PAM], [
        else
                AC_MSG_RESULT([yes])
                ifelse([$1], , :, [$1])
+        use_pam_so=yes
+           compile_pam=yes
+           netatalk_cv_use_pam=yes
+           AC_DEFINE(USE_PAM, 1, [Define to enable PAM support])
        fi
 
     LIB_REMOVE_USR_LIB(PAM_LIBS)
index 44e89bc966840548c411952f21f3286d8ead543c..b7e0c3a213f659dfd041eb04be39cc672c061a17 100644 (file)
@@ -2,7 +2,7 @@ dnl $Id: quota-check.m4,v 1.6 2005-07-20 23:58:21 didg Exp $
 dnl Autoconf macro to check for quota support
 dnl FIXME: This is in now way complete.
 
-AC_DEFUN([AC_CHECK_QUOTA], [
+AC_DEFUN([AC_NETATALK_CHECK_QUOTA], [
        AC_ARG_ENABLE(quota,
        [  --enable-quota           Turn on quota support (default=auto)])
 
diff --git a/macros/snprintf-check.m4 b/macros/snprintf-check.m4
deleted file mode 100644 (file)
index bee8ad7..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-dnl Check for (v)snprintf functions
-
-AC_DEFUN([NETATALK_SNPRINTF_CHECK], [
-       AC_CHECK_FUNCS(snprintf vsnprintf)
-
-       AC_CHECK_HEADERS(stdarg.h varargs.h)
-
-       AC_CHECK_FUNCS(strerror)
-       AC_CACHE_CHECK(for errno,
-       ac_cv_errno,
-       [
-       AC_TRY_LINK(,[extern int errno; return (errno);],
-               ac_cv_errno=yes, ac_cv_errno=no)
-       ])
-       if test "$ac_cv_errno" = yes; then
-               AC_DEFINE(HAVE_ERRNO, 1, [Define if errno declaration exists])
-               AC_CACHE_CHECK(for errno declaration,
-               ac_cv_decl_errno,
-               [
-               AC_TRY_COMPILE([
-               #include <stdio.h>
-               #ifdef HAVE_STDLIB_H
-               #include <stdlib.h>
-               #endif
-               #ifdef HAVE_UNISTD_H
-               #include <unistd.h>
-               #endif
-               #ifdef HAVE_ERRNO_H
-               #include <errno.h>
-               #endif
-               ],[return(sys_nerr);],
-                       ac_cv_decl_errno=yes, ac_cv_decl_errno=no)
-               ])
-               if test "$ac_cv_decl_errno" = yes; then
-                       AC_DEFINE(HAVE_DECL_ERRNO, 1, [Define if errno declaration exists])
-               fi;
-       fi
-
-       AC_CACHE_CHECK(for sys_nerr,
-       ac_cv_sys_nerr,
-       [
-       AC_TRY_LINK(,[extern int sys_nerr; return (sys_nerr);],
-               ac_cv_sys_nerr=yes, ac_cv_sys_nerr=no)
-       ])
-       if test "$ac_cv_sys_nerr" = yes; then
-               AC_DEFINE(HAVE_SYS_NERR, 1, [Define if sys_nerr declaration exists])
-               AC_CACHE_CHECK(for sys_nerr declaration,
-               ac_cv_decl_sys_nerr,
-               [
-               AC_TRY_COMPILE([
-               #include <stdio.h>
-               #ifdef HAVE_STDLIB_H
-               #include <stdlib.h>
-               #endif
-               #ifdef HAVE_UNISTD_H
-               #include <unistd.h>
-               #endif],[return(sys_nerr);],
-               ac_cv_decl_sys_nerr_def=yes, ac_cv_decl_sys_nerr_def=no)
-               ])
-               if test "$ac_cv_decl_sys_nerr" = yes; then
-                       AC_DEFINE(HAVE_DECL_SYS_NERR, 1, [Define if sys_nerr declaration exists])
-               fi
-       fi
-
-
-       AC_CACHE_CHECK(for sys_errlist array,
-       ac_cv_sys_errlist,
-       [AC_TRY_LINK(,[extern char *sys_errlist[];
-               sys_errlist[0];],
-               ac_cv_sys_errlist=yes, ac_cv_sys_errlist=no)
-       ])
-       if test "$ac_cv_sys_errlist" = yes; then
-               AC_DEFINE(HAVE_SYS_ERRLIST, 1, [Define if sys_errlist declaration exists])
-               AC_CACHE_CHECK(for sys_errlist declaration,
-               ac_cv_sys_errlist_def,
-               [AC_TRY_COMPILE([
-               #include <stdio.h>
-               #include <errno.h>
-               #ifdef HAVE_STDLIB_H
-               #include <stdlib.h>
-               #endif
-               #ifdef HAVE_UNISTD_H
-               #include <unistd.h>
-               #endif],[char *s = sys_errlist[0]; return(*s);],
-               ac_cv_decl_sys_errlist=yes, ac_cv_decl_sys_errlist=no)
-               ])
-               if test "$ac_cv_decl_sys_errlist" = yes; then
-                       AC_DEFINE(HAVE_DECL_SYS_ERRLIST, 1, [Define if sys_errlist declaration exists])
-               fi
-       fi
-
-
-
-       AC_CACHE_CHECK(for long long,
-       ac_cv_long_long,
-       [
-       AC_TRY_COMPILE([
-       #include <stdio.h>
-       #include <sys/types.h>
-       ], [printf("%d",sizeof(long long));],
-       ac_cv_long_long=yes, ac_cv_long_long=no)
-       ])
-       if test $ac_cv_long_long = yes; then
-         AC_DEFINE(HAVE_LONG_LONG, 1, [Define if long long is a valid data type])
-       fi
-
-       AC_CACHE_CHECK(for long double,
-       ac_cv_long_double,
-       [
-       AC_TRY_COMPILE([
-       #include <stdio.h>
-       #include <sys/types.h>
-       ], [printf("%d",sizeof(long double));],
-       ac_cv_long_double=yes, ac_cv_long_double=no)
-       ])
-       if test $ac_cv_long_double = yes; then
-         AC_DEFINE(HAVE_LONG_DOUBLE, 1, [Define if long double is a valid data type])
-       fi
-
-       AC_CACHE_CHECK(for quad_t,
-       ac_cv_quad_t,
-       [
-       AC_TRY_COMPILE([
-       #include <stdio.h>
-       #include <sys/types.h>
-       ], [printf("%d",sizeof(quad_t));],
-       ac_cv_quad_t=yes, ac_cv_quad_t=no)
-       ])
-       if test $ac_cv_quad_t = yes; then
-         AC_DEFINE(HAVE_QUAD_T, 1, [Define if quad_t is a valid data type])
-       fi
-])
diff --git a/macros/srvloc.m4 b/macros/srvloc.m4
deleted file mode 100644 (file)
index 4fe3fe2..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-dnl Check for optional server location protocol support (used by MacOS X)
-
-dnl $Id: srvloc.m4,v 1.10 2009-12-13 11:58:30 franklahm Exp $
-
-AC_DEFUN([NETATALK_SRVLOC], [
-
-       SLP_LIBS=""
-       SLP_CFLAGS=""
-       found_slp=no
-       srvlocdir=""
-
-       AC_ARG_ENABLE(srvloc,
-               [  --enable-srvloc[[=DIR]]   enable Server Location Protocol (SLP) support],
-               [srvloc=$enableval],
-               [srvloc=no]
-       )
-
-    dnl make sure atalk_libname is defined beforehand
-    [[ -n "$atalk_libname" ]] || AC_MSG_ERROR([internal error, atalk_libname undefined])
-
-       if test "x$srvloc" != "xno"; then
-
-               savedcppflags="$CPPFLAGS"
-               savedldflags="$LDFLAGS"
-               if test "x$srvloc" = "xyes" ; then
-                       srvlocdir="/usr"
-               else
-                       srvlocdir="$srvloc"
-               fi
-               CPPFLAGS="$CPPFLAGS -I$srvlocdir/include"
-               LDFLAGS="$LDFLAGS -L$srvlocdir/$atalk_libname"
-
-               AC_MSG_CHECKING([for slp.h])
-               AC_TRY_CPP([#include <slp.h>],
-                       [
-                               AC_MSG_RESULT([yes])
-                               found_slp=yes
-                       ],
-                       [
-                               AC_MSG_RESULT([no])
-                       ]
-               )
-               
-               if test "x$found_slp" = "xyes"; then
-                       AC_CHECK_LIB(slp, SLPOpen, [
-                          SLP_LIBS="-L$srvlocdir/$atalk_libname -lslp"
-                          SLP_CFLAGS="-I$srvlocdir/include"
-                       ],[ 
-                          AC_MSG_RESULT([no])
-                          found_slp=no
-                       ])
-               fi
-
-               CPPFLAGS="$savedcppflags"
-               LDFLAGS="$savedldflags"
-       fi
-       
-       netatalk_cv_srvloc=no
-       AC_MSG_CHECKING([whether to enable srvloc (SLP) support])
-       if test "x$found_slp" = "xyes"; then
-               AC_MSG_RESULT([yes])
-               AC_DEFINE(USE_SRVLOC, 1, [Define to enable SLP support])
-               netatalk_cv_srvloc=yes
-       else
-               AC_MSG_RESULT([no])
-               if test "x$srvloc" != "xno" -a "x$srvloc" != "xyes"; then
-                       AC_MSG_ERROR([SLP installation not found])
-               fi
-       fi
-               
-
-
-       LIB_REMOVE_USR_LIB(SLP_LIBS)
-       CFLAGS_REMOVE_USR_INCLUDE(SLP_CFLAGS)
-       AC_SUBST(SLP_LIBS)
-       AC_SUBST(SLP_CFLAGS)
-])
index 9de28019fb5b7473da1091e19ff72bf54135694c..8d9c1b6c66650e5ca8f8f337057b8a229c69cccc 100644 (file)
@@ -1,7 +1,7 @@
 dnl $Id: ssl-check.m4,v 1.14 2008-11-22 12:07:26 didg Exp $
 dnl Autoconf macro to check for SSL or OpenSSL
 
-AC_DEFUN([AC_CRYPT], [
+AC_DEFUN([AC_NETATALK_CRYPT], [
 
        saveLIBS=$LIBS
        LIBS=""
@@ -17,7 +17,7 @@ AC_DEFUN([AC_CRYPT], [
 ])
 
 
-AC_DEFUN([AC_PATH_SSL], [
+AC_DEFUN([AC_NETATALK_PATH_SSL], [
        AC_ARG_WITH(ssl-dir, [  --with-ssl-dir=PATH     specify path to OpenSSL installation (must contain
                           lib and include dirs)],
                [
index dac5fa2cb6b217b9575c18621710b5767fa3590b..a618cf31ccacca089ec2e3a67b9b78038c0af9e9 100644 (file)
@@ -1,18 +1,17 @@
-dnl $Id: summary.m4,v 1.6 2009-10-02 09:32:41 franklahm Exp $
 dnl Autoconf macros, display configure summary
 
 AC_DEFUN([AC_NETATALK_CONFIG_SUMMARY], [
 
        AC_MSG_RESULT([Configure summary:])
-       AC_MSG_RESULT([    Install style:])
-       if test "x$sysv_style" != "x"; then
-               AC_MSG_RESULT([         $sysv_style])
+       AC_MSG_RESULT([    init style:])
+       if test "x$init_style" != "x"; then
+               AC_MSG_RESULT([         $init_style])
        else
                AC_MSG_RESULT([         none])
        fi
        AC_MSG_RESULT([    AFP:])
-       AC_MSG_RESULT([         Large file support (>2GB) for AFP3: $wx_largefile])
        AC_MSG_RESULT([         Extended Attributes: $neta_cv_eas])
+       AC_MSG_RESULT([         ACL support: $with_acl_support])
        AC_MSG_RESULT([    CNID:])
        AC_MSG_RESULT([         backends: $compiled_backends])
        AC_MSG_RESULT([    UAMS:])
@@ -35,21 +34,12 @@ AC_DEFUN([AC_NETATALK_CONFIG_SUMMARY], [
        if test x"$netatalk_cv_build_krb5_uam" = x"yes"; then
                AC_MSG_RESULT([         Kerberos V])
        fi
-       if test x"$compile_kerberos" = x"yes"; then
-               AC_MSG_RESULT([         Kerberos IV])
-       fi
        if test x"$compile_pgp" = x"yes"; then
                AC_MSG_RESULT([         PGP])
        fi
        AC_MSG_RESULT([         clrtxt  ($uams_using_options)])
        AC_MSG_RESULT([         guest])
        AC_MSG_RESULT([    Options:])
-       AC_MSG_RESULT([         DDP (AppleTalk) support: $netatalk_cv_ddp_enabled])
-       if test "x$netatalk_cv_ddp_enabled" = "xyes"; then
-               AC_MSG_RESULT([         CUPS support:            $netatalk_cv_use_cups])
-               AC_MSG_RESULT([         Apple 2 boot support:    $compile_a2boot])
-       fi
-       AC_MSG_RESULT([         SLP support:             $netatalk_cv_srvloc])
        AC_MSG_RESULT([         Zeroconf support:        $netatalk_cv_zeroconf])
        AC_MSG_RESULT([         tcp wrapper support:     $netatalk_cv_tcpwrap])
 dnl    if test x"$netatalk_cv_linux_sendfile" != x; then
@@ -59,10 +49,10 @@ dnl fi
        AC_MSG_RESULT([         admin group support:     $netatalk_cv_admin_group])
        AC_MSG_RESULT([         valid shell check:       $netatalk_cv_use_shellcheck])
        AC_MSG_RESULT([         cracklib support:        $netatalk_cv_with_cracklib])
-       AC_MSG_RESULT([         dropbox kludge:          $netatalk_cv_dropkludge])
-       AC_MSG_RESULT([         force volume uid/gid:    $netatalk_cv_force_uidgid])
+       AC_MSG_RESULT([         Samba sharemode interop: $neta_cv_have_smbshmd])
        AC_MSG_RESULT([         ACL support:             $with_acl_support])
-       AC_MSG_RESULT([         LDAP support:            $with_ldap])
+       AC_MSG_RESULT([         Kerberos support:        $with_kerberos])
+       AC_MSG_RESULT([         LDAP support:            $netatalk_cv_ldap])
        if test x"$use_pam_so" = x"yes" -a x"$netatalk_cv_install_pam" = x"no"; then
                AC_MSG_RESULT([])
                AC_MSG_WARN([ PAM support was configured for your system, but the netatalk PAM configuration file])
@@ -111,11 +101,6 @@ AC_DEFUN([AC_NETATALK_LIBS_SUMMARY], [
                AC_MSG_RESULT([        LIBS   = $GSSAPI_LIBS])
                AC_MSG_RESULT([        CFLAGS = $GSSAPI_CFLAGS])
        fi
-       if test x"$netatalk_cv_srvloc" = x"yes"; then
-               AC_MSG_RESULT([    SRVLOC:])
-               AC_MSG_RESULT([        LIBS   = $SLP_LIBS])
-               AC_MSG_RESULT([        CFLAGS = $SLP_CFLAGS])
-       fi
        if test x"$netatalk_cv_use_cups" = x"yes"; then
                AC_MSG_RESULT([    CUPS:])
                AC_MSG_RESULT([        LIBS   = $CUPS_LIBS])
@@ -126,4 +111,9 @@ AC_DEFUN([AC_NETATALK_LIBS_SUMMARY], [
                AC_MSG_RESULT([        LIBS   = $ZEROCONF_LIBS])
                AC_MSG_RESULT([        CFLAGS = $ZEROCONF_CFLAGS])
        fi
+       if test x"$netatalk_cv_ldap" = x"yes"; then
+               AC_MSG_RESULT([    LDAP:])
+               AC_MSG_RESULT([        LIBS   = $LDAP_LDLFLAGS $LDAP_LIBS])
+               AC_MSG_RESULT([        CFLAGS = $LDAP_CFLAGS])
+       fi
 ])
index d770f049d1ea58ef1a0ed7e1481aae68bc562648..55b0f8c179428c464634cd6f5aa601b6f6521a9f 100644 (file)
@@ -1,6 +1,6 @@
 dnl $Id: tcp-wrappers.m4,v 1.4 2008-08-11 20:44:03 didg Exp $
 
-AC_DEFUN([NETATALK_TCP_WRAPPERS], [
+AC_DEFUN([AC_NETATALK_TCP_WRAPPERS], [
        check=maybe
        AC_ARG_ENABLE(tcp-wrappers,
                [  --disable-tcp-wrappers  disable TCP wrappers support],
diff --git a/macros/webmin.m4 b/macros/webmin.m4
deleted file mode 100644 (file)
index ec722c1..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-dnl $Id: webmin.m4,v 1.1 2009-10-22 08:36:30 franklahm Exp $
-dnl Autoconf macro to install webmin + netatalk webmin module
-
-AC_DEFUN([NETATALK_WEBMIN],[
-    AC_ARG_WITH(webmin,
-        [  --with-webmin=PATH      path where webmin is installed [[$PKGCONFDIR/webmin]]],
-        if test "x$withval" = "xyes"; then
-            webminpath="$PKGCONFDIR"
-        elif test "x$withval" = "xno"; then
-            webminpath=""
-        else
-            webminpath="$withval"
-        fi
-    )
-
-    AC_ARG_WITH(webminuser,
-        [  --with-webminuser=NAME      name for the webmin admin user],
-        if test "x$withval" = "xyes"; then
-            webminuser=""
-        elif test "x$withval" = "xno"; then
-            webminuser=""
-        else
-            webminuser="$withval"
-        fi
-    )
-
-    AC_ARG_WITH(webminversion,
-        [  --with-webminversion=VERSION   Webmin version to fetch from sf.net [[1.490]]],
-        if test "x$withval" = "xyes"; then
-            webminversion="1.490"
-        elif test "x$withval" = "xno"; then
-            webminversions="1.490"
-        else
-            webminversion="$withval"
-        fi
-    )
-
-    AC_ARG_WITH(webminpass,
-        [  --with-webminpass=PASSWORD  password for the webmin admin user],
-        if test "x$withval" = "xyes"; then
-            webminpass=""
-        elif test "x$withval" = "xno"; then
-            webminpass=""
-        else
-            webminpass="$withval"
-        fi
-    )
-
-    AC_ARG_WITH(webminport,
-        [  --with-webminport=PORT  TCP port for webmin],
-        if test "x$withval" = "xyes"; then
-            webminport=""
-        elif test "x$withval" = "xno"; then
-            webminport=""
-        else
-            webminport="$withval"
-        fi
-    )
-
-    AC_MSG_CHECKING([if webmin administration shall be installed])
-    if test "x$webminpath" != "x" &&
-            test "x$webminuser" != "x" &&
-            test "x$webminpass" != "x" &&
-            test "x$webminport" != "x" &&
-            test "x$webminversion" != "x"; then
-        AC_MSG_RESULT([yes])
-        AC_MSG_CHECKING([if neccessary Perl module 'Net::SSLeay' is installed])
-        $ac_cv_path_PERL -e 'use Net::SSLeay' >/dev/null 2>/dev/null
-               if test "$?" != "0" ; then
-            AC_MSG_RESULT([no])
-            webminpath=""
-        else
-            AC_MSG_RESULT([yes])
-            AC_MSG_NOTICE([Installing Webmin in "$webminpath/webmin"])
-        fi
-    else
-        AC_MSG_RESULT([no])
-    fi
-
-    AC_SUBST(WEBMIN_PATH, $webminpath)
-    AC_SUBST(WEBMIN_VERSION, $webminversion)
-    AC_SUBST(WEBMIN_USER, $webminuser)
-    AC_SUBST(WEBMIN_PASS, $webminpass)
-    AC_SUBST(WEBMIN_PORT, $webminport)
-])
\ No newline at end of file
index 2adc84285d6a74a20edb0f553828a9c824e8ef72..6916c9905dca7541fe91f50678994695b3674ed3 100644 (file)
@@ -1,6 +1,6 @@
 dnl Check for optional Zeroconf support
 
-AC_DEFUN([NETATALK_ZEROCONF], [
+AC_DEFUN([AC_NETATALK_ZEROCONF], [
        ZEROCONF_LIBS=""
        ZEROCONF_CFLAGS=""
        found_zeroconf=no
index d98062fb471b84aa39d7365a27fbdeb924b055a7..adca7de8a56d0cc9b27832b0b1f37fa9623b167e 100644 (file)
@@ -1,3 +1,3 @@
 # Makefile.am for man/
 
-SUBDIRS = man1 man3 man4 man5 man8
+SUBDIRS = man1 man5 man8
index 36c6810abb59cca20565cc8ab1d97a75e1ed9ed9..fe81a7d762bf3f8831066049d9523bbeef6dd1ee 100644 (file)
@@ -14,33 +14,14 @@ SUFFIXES= .tmpl .
 
 GENERATED_MANS = uniconv.1 asip-status.pl.1 afpldaptest.1
 TEMPLATE_FILES = uniconv.1.tmpl asip-status.pl.1.tmpl afpldaptest.1.tmpl
+
 NONGENERATED_MANS      =       ad.1 \
                                afppasswd.1 \
                                apple_dump.1 \
                                dbd.1 \
-                               hqx2bin.1 \
-                               macbinary.1 \
                                macusers.1 \
-                               megatron.1 \
-                               netatalk-config.1 \
-                               single2bin.1 \
-                               unbin.1 \
-                               unhex.1 \
-                               unsingle.1
-ATALK_MANS = aecho.1 \
-                               getzones.1 \
-                               nbp.1 \
-                               nbplkup.1 \
-                               nbprgstr.1 \
-                               nbpunrgstr.1 \
-                               pap.1 \
-                               papstatus.1 \
-                               psorder.1
-
-if USE_APPLETALK
-NONGENERATED_MANS += $(ATALK_MANS)
-endif
+                               netatalk-config.1
 
 man_MANS = $(GENERATED_MANS) $(NONGENERATED_MANS)
 CLEANFILES = $(GENERATED_MANS)
-EXTRA_DIST = $(TEMPLATE_FILES) $(NONGENERATED_MANS) $(ATALK_MANS)
+EXTRA_DIST = $(TEMPLATE_FILES) $(NONGENERATED_MANS)
index 7dc8014257d83f8ce21548f8f0bc012cdc4e131a..4d85e8bec1adaf1bae6576a905d8456c3e6f9054 100644 (file)
@@ -3,11 +3,11 @@
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
 .\"      Date: 02 Sep 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "AD" "1" "02 Sep 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "AD" "1" "02 Sep 2011" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
diff --git a/man/man1/aecho.1 b/man/man1/aecho.1
deleted file mode 100644 (file)
index 3dfad5f..0000000
+++ /dev/null
@@ -1,90 +0,0 @@
-'\" t
-.\"     Title: aecho
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 17 Dec 1991
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "AECHO" "1" "17 Dec 1991" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-aecho \- send AppleTalk Echo Protocol packets to network hosts
-.SH "SYNOPSIS"
-.PP
-\fBaecho\fR\fB\fR\fB\fR
-[
-\fB\-c\fR\fI count\fR
-] (
-\fBaddress\fR
-|
-\fBnbpname\fR
-)
-.SH "DESCRIPTION"
-.PP
-\fBaecho\fR
-repeatedly sends an Apple Echo Protocol (AEP) packet to the host specified by the given AppleTalk
-\fBaddress\fR
-or
-\fBnbpname\fR
-and reports whether a reply was received\&. Requests are sent at the rate of one per second\&.
-.PP
-\fBaddress\fR
-is parsed by
-\fBatalk_aton\fR(3)\&.
-\fBnbpname\fR
-is parsed by
-\fBnbp_name\fR(3)\&. The nbp type defaults to `\fBWorkstation\fR\'\&.
-.PP
-When
-\fBaecho\fR
-is terminated, it reports the number of packets sent, the number of responses received, and the percentage of packets lost\&. If any responses were received, the minimum, average, and maximum round trip times are reported\&.
-.SH "EXAMPLE"
-.PP
-Check to see if a particular host is up and responding to AEP packets:
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-example% \fBaecho bloodsport
-\fR\fB11 bytes from 8195\&.13: aep_seq=0\&. time=10\&. ms
-11 bytes from 8195\&.13: aep_seq=1\&. time=10\&. ms
-11 bytes from 8195\&.13: aep_seq=2\&. time=10\&. ms
-11 bytes from 8195\&.13: aep_seq=3\&. time=10\&. ms
-11 bytes from 8195\&.13: aep_seq=4\&. time=10\&. ms
-11 bytes from 8195\&.13: aep_seq=5\&. time=9\&. ms\fR\fB
-\fR\fB\fB^C\fR\fR\fB
-\fR\fB\-\-\-\-8195\&.13 AEP Statistics\-\-\-\-
-6 packets sent, 6 packets received, 0% packet loss
-round\-trip (ms)  min/avg/max = 9/9/10
-\fR
-.fi
-.if n \{\
-.RE
-.\}
-.SH "OPTIONS"
-.PP
-\fB\-c\fR\fI count\fR
-.RS 4
-Stop after
-\fIcount\fR
-packets\&.
-.RE
-.SH "SEE ALSO"
-.PP
-\fBping\fR(1),
-\fBatalk_aton\fR(3),
-\fBnbp_name\fR(3),
-\fBaep\fR(4),
-\fBatalkd\fR(8)\&.
index 2ea753c4e94430165cabeda349b9e42f0a333e68..1d4fbd7edf35e068790f2fc0f03ec943b0b7adff 100644 (file)
@@ -2,12 +2,12 @@
 .\"     Title: afpldaptest
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 30 Mar 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"      Date: 22 Mar 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "AFPLDAPTEST" "1" "30 Mar 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "AFPLDAPTEST" "1" "22 Mar 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
@@ -19,7 +19,7 @@
 .\" * MAIN CONTENT STARTS HERE *
 .\" -----------------------------------------------------------------
 .SH "NAME"
-afpldaptest \- Syntactically check an afp_ldap\&.conf
+afpldaptest \- Syntactically check ldap parameters in afp\&.conf
 .SH "SYNOPSIS"
 .HP \w'\fBafpldaptest\fR\fB\fR\fBafpldaptest\fR\fB\fR\ 'u
 \fBafpldaptest\fR\fB\fR {\-u\ \fIUSER\fR | \-g\ \fIGROUP\fR | \-i\ \fIUUID\fR}
@@ -28,7 +28,7 @@ afpldaptest \- Syntactically check an afp_ldap\&.conf
 .SH "DESCRIPTION"
 .PP
 \fBafpldaptest\fR
-is a simple command to syntactically check :ETCDIR:/afp_ldap\&.conf\&.
+is a simple command to syntactically check ldap parameters in :ETCDIR:/afp\&.conf\&.
 .SH "OPTIONS"
 .PP
 \fB\-u\fR \fIUSER\fR
@@ -55,4 +55,4 @@ Show the help and exit\&.
 .RE
 .SH "SEE ALSO"
 .PP
-\fBafp_ldap.conf\fR(5)
+\fBafp.conf\fR(5)
index 8e9e5dfdd6f7362074d9ac3ee81cdfc7097aca02..860eb693e49b9acaa342d6d6d7c024f5198da751 100644 (file)
@@ -2,12 +2,12 @@
 .\"     Title: afppasswd
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 31 May 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"      Date: 22 Mar 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "AFPPASSWD" "1" "31 May 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "AFPPASSWD" "1" "22 Mar 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
@@ -110,4 +110,4 @@ will use when creating users\&.
 .SH "SEE ALSO"
 .PP
 \fBafpd\fR(8),
-\fBatalkd\fR(8)\&.
+\fBafp.conf\fR(5)\&.
index 4bb8f4de5fe7894cc5862b3363df168ffa2c75a1..56be391e3d1eaf4d96a5dabe51850854d44e39d5 100644 (file)
@@ -2,12 +2,12 @@
 .\"     Title: apple_dump
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 02 Sep 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"      Date: 22 May 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "APPLE_DUMP" "1" "02 Sep 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "APPLE_DUMP" "1" "22 May 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
 .\" * MAIN CONTENT STARTS HERE *
 .\" -----------------------------------------------------------------
 .SH "NAME"
-apple_dump \- Dump AppleSingle/AppleDouble format file
+apple_dump \- Dump AppleSingle/AppleDouble format data
 .SH "SYNOPSIS"
-.HP \w'\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\ 'u
+.HP \w'\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\fBapple_dump\fR\fB\fR\ 'u
 \fBapple_dump\fR\fB\fR [\-a] \fIFILE\fR | \fIDIR\fR 
 .br
+\fBapple_dump\fR\fB\fR \-e \fIFILE\fR | \fIDIR\fR 
+.br
 \fBapple_dump\fR\fB\fR \-f \fIFILE\fR
 .br
 \fBapple_dump\fR\fB\fR \-d \fIFILE\fR
@@ -34,7 +36,7 @@ apple_dump \- Dump AppleSingle/AppleDouble format file
 .SH "DESCRIPTION"
 .PP
 \fBapple_dump\fR
-dump AppleSingle/AppleDouble format file\&.
+dump AppleSingle/AppleDouble format data\&.
 .SH "OPTIONS"
 .PP
 \fB\-a\fR \fIFILE\fR|\fIDIR\fR
@@ -43,16 +45,23 @@ This is default\&. Dump a AppleSingle/AppleDouble file for
 \fIFILE\fR
 or
 \fIDIR\fR
-automatically\&. Extrapolate FinderInfo type from absolute path\&. If FILE is not AppleSingle/AppleDouble format, look for
+automatically\&. If FILE is not AppleSingle/AppleDouble format, look for extended attribute,
 \fI\&.AppleDouble/FILE\fR
 and
 \fI\&._FILE\fR\&. If
-\fIDIR\fR, look for
+\fIDIR\fR, look for extended attribute,
 \fIDIR/\&.AppleDouble/\&.Parent\fR
 and
 \fI\&._DIR\fR\&.
 .RE
 .PP
+\fB\-e\fR \fIFILE\fR|\fIDIR\fR
+.RS 4
+Dump extended attribute of\fIFILE\fR
+or
+\fIDIR\fR\&.
+.RE
+.PP
 \fB\-f\fR \fIFILE\fR
 .RS 4
 Dump
@@ -78,7 +87,10 @@ Show version and exit
 .PP
 There is no way to detect whether FinderInfo is FileInfo or DirInfo\&. By default, apple_dump examins whether file or directory, a parent directory is \&.AppleDouble, filename is \&._*, filename is \&.Parent, and so on\&.
 .PP
-If setting option \-f or \-d, assume FinderInfo and doesn\'t look for another file\&.
+If setting option \-e, \-f or \-d, assume FinderInfo and doesn\'t look for another file\&.
 .SH "SEE ALSO"
 .PP
-\fBad\fR(1)
+\fBad\fR(1),
+\fBgetfattr\fR(1),
+\fBattr\fR(1),
+\fBrunat\fR(1)
index 2bf20b03405bb885b68dfc34a3c0324ec7ca7e4f..8a0f04eea8e0751a5268ed60f4d1619fdfb3a275 100644 (file)
@@ -3,11 +3,11 @@
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
 .\"      Date: 02 Sep 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "ASIP\-STATUS\&.PL" "1" "02 Sep 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "ASIP\-STATUS\&.PL" "1" "02 Sep 2011" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
index 8e6bca59da44b18814b5a44daa249a6e426d0a07..7d95ede2968154b977728a011a5e29056f520e13 100644 (file)
@@ -3,11 +3,11 @@
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
 .\"      Date: 12 Oct 2010
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "DBD" "1" "12 Oct 2010" "Netatalk 2.2" "Netatalk 2.2"
+.TH "DBD" "1" "12 Oct 2010" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
diff --git a/man/man1/getzones.1 b/man/man1/getzones.1
deleted file mode 100644 (file)
index 861ca78..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-'\" t
-.\"     Title: getzones
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 17 Dec 1991
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "GETZONES" "1" "17 Dec 1991" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-getzones \- list AppleTalk zone names
-.SH "SYNOPSIS"
-.HP \w'\fBgetzones\fR\fB\fR\ 'u
-\fBgetzones\fR\fB\fR [\-m | \-l] [\fIaddress\fR]
-.SH "DESCRIPTION"
-.PP
-\fBGetzones\fR
-is used to obtain a list of AppleTalk zone names using the Zone Information Protocol (ZIP)\&. It sends a GetZoneList request to an AppleTalk router\&. By default, it sends the request to the locally running
-\fBatalkd\fR(8)\&.
-.SH "OPTIONS"
-.PP
-\fB\-m\fR
-.RS 4
-List the name of the local zone only; this is accomplished by sending a ZIP GetMyZone request\&.
-.RE
-.PP
-\fB\-l\fR
-.RS 4
-List the local zones; this is accomplished by sending a GetLocalZones request\&.
-.RE
-.PP
-\fIaddress\fR
-.RS 4
-Contact the AppleTalk router at
-\fIaddress\&.\fR
-\fIaddress\fR
-is parsed by
-\fBatalk_aton\fR(3)\&.
-.RE
-.SH "SEE ALSO"
-.PP
-\fBatalk_aton\fR(3),
-\fBatalkd\fR(8)\&.
index 6338c83ffe79e926d087e7cc4b9dd6e795d0a21d..ea823a0b0c5daaa4de12241d156ff5252f22289d 100644 (file)
@@ -3,11 +3,11 @@
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
 .\"      Date: 13 Oct 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "MACUSERS" "1" "13 Oct 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "MACUSERS" "1" "13 Oct 2011" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
index 15667962eaab307898a2b1983f6a95e878a45768..dfd37d044db01f500f06fbf99cd4a200bafbfe03 100644 (file)
@@ -3,11 +3,11 @@
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
 .\"      Date: 02 Sep 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "MEGATRON" "1" "02 Sep 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "MEGATRON" "1" "02 Sep 2011" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
diff --git a/man/man1/nbp.1 b/man/man1/nbp.1
deleted file mode 100644 (file)
index 0958b99..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-'\" t
-.\"     Title: nbp
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 24 June 2004
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "NBP" "1" "24 June 2004" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-nbp, nbplkup, nbprgstr, nbpunrgstr \- access NBP database
-.SH "SYNOPSIS"
-.HP \w'\fBnbplkup\fR\fB\fR\fB\fR\fB\ \fR\ 'u
-\fBnbplkup\fR\fB\fR\fB\fR\fB \fR [\-r\ \fImaxresponses\fR] [\-A\ \fIaddress\fR] [\-m\ \fImaccodepage\fR] \fInbpname\fR
-.HP \w'\fBnbprgstr\fR\fB\fR\fB\ \fR\ 'u
-\fBnbprgstr\fR\fB\fR\fB \fR [\-A\ \fIaddress\fR] [\-p\ \fIport\fR] [\-m\ \fImaccodepage\fR] \fInbpname\fR
-.HP \w'\fBnbpunrgstr\fR\fB\fR\fB\ \fR\ 'u
-\fBnbpunrgstr\fR\fB\fR\fB \fR [\-A\ \fIaddress\fR] [\-m\ \fImaccodepage\fR] \fInbpname\fR
-.SH "DESCRIPTION"
-.PP
-\fBnbprgstr\fR
-registers
-\fInbpname\fR
-with
-\fBatalkd\fR(8), at the given
-\fIport\fR\&.
-\fBnbpunrgstr\fR
-informs
-\fBatalkd\fR
-that
-\fInbpname\fR
-is no longer to be advertised\&.
-.PP
-\fBnbplkup\fR
-displays up to
-\fImaxresponses\fR
-(default 1000) entities registered on the AppleTalk internet\&.
-\fI\fInbpname\fR\fR
-is parsed by
-\fBnbp_name\fR(3)\&. An `\fB=\fR\' for the
-\fIobject\fR
-or
-\fItype\fR
-matches anything, and an `\fB*\fR\' for
-\fIzone\fR
-means the local zone\&. The default values are taken from the
-\fBNBPLKUP\fR
-environment variable, parsed as an
-\fInbpname\fR\&.
-.SH "ENVIRONMENT VARIABLES"
-.PP
-NBPLKUP
-.RS 4
-default nbpname for nbplkup
-.RE
-.PP
-ATALK_MAC_CHARSET
-.RS 4
-the codepage used by the clients on the Appletalk network
-.RE
-.PP
-ATALK_UNIX_CHARSET
-.RS 4
-the codepage used to display extended characters on this shell\&.
-.RE
-.SH "EXAMPLE"
-.PP
-Find all devices of type
-\fBLaserWriter\fR
-in the local zone\&.
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-example% \fBnbplkup :LaserWriter\fR
-               Petoskey:LaserWriter        7942\&.129:218
-             Gloucester:LaserWriter        8200\&.188:186
-                 Rahway:LaserWriter        7942\&.2:138
-             517 Center:LaserWriter        7942\&.2:132
-                  ionia:LaserWriter        7942\&.2:136
-     Evil DEC from Hell:LaserWriter        7942\&.2:130
-              Hamtramck:LaserWriter        7942\&.2:134
-         Iron Mountain :LaserWriter        7942\&.128:250
-example%
-.fi
-.if n \{\
-.RE
-.\}
-.SH "SEE ALSO"
-.PP
-\fBnbp_name\fR(3),
-\fBatalkd\fR(8)\&.
diff --git a/man/man1/nbplkup.1 b/man/man1/nbplkup.1
deleted file mode 100644 (file)
index ac41808..0000000
+++ /dev/null
@@ -1 +0,0 @@
-.so man1/nbp.1
diff --git a/man/man1/nbprgstr.1 b/man/man1/nbprgstr.1
deleted file mode 100644 (file)
index ac41808..0000000
+++ /dev/null
@@ -1 +0,0 @@
-.so man1/nbp.1
diff --git a/man/man1/nbpunrgstr.1 b/man/man1/nbpunrgstr.1
deleted file mode 100644 (file)
index ac41808..0000000
+++ /dev/null
@@ -1 +0,0 @@
-.so man1/nbp.1
index 3d4d9a8b8905b7a53f8485e4ecb35a76b635b1dc..43ebcb7b5399709021732df5764b274ae5a2367f 100644 (file)
@@ -4,10 +4,10 @@
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
 .\"      Date: 09 June 2001
 .\"    Manual: The Netatalk Project
-.\"    Source: Netatalk 2.2
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "NETATALK\-CONFIG" "1" "09 June 2001" "Netatalk 2.2" "The Netatalk Project"
+.TH "NETATALK\-CONFIG" "1" "09 June 2001" "Netatalk 3.0" "The Netatalk Project"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
diff --git a/man/man1/pap.1 b/man/man1/pap.1
deleted file mode 100644 (file)
index bc33328..0000000
+++ /dev/null
@@ -1,150 +0,0 @@
-'\" t
-.\"     Title: pap
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 6 May 2002
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "PAP" "1" "6 May 2002" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-pap \- client interface to remote printers using Printer Access Protocol
-.SH "SYNOPSIS"
-.HP \w'\fBpap\fR\fB\fR\ 'u
-\fBpap\fR\fB\fR [\-A\ \fIaddress\fR] [\-c] [\-d] [\-e] [\-E] [\-p\ \fInbpname\fR] [\-s\ \fIstatusfile\fR] [\-w] [\-W] [\fIFILES\fR]
-.SH "DESCRIPTION"
-.PP
-\fBpap\fR
-is used to connect and send files to an AppleTalk connected printer using the Apple Printer Access Protocol (PAP)\&. When
-\fBpap\fR
-starts execution, it tries to open a session with the printer using PAP, and then downloads the
-\fIfiles\fR
-to the printer\&.
-.PP
-If no
-\fIfiles\fR
-are given on the command line,
-\fBpap\fR
-begins reading from standard input\&.
-.PP
-If no printer is specified on the command line,
-\fBpap\fR
-looks for a file called
-\fB\&.paprc\fR
-in the current working directory and reads it to obtain the
-\fInbpname\fR
-of a printer\&. Blank lines and lines that begin with a `\fB#\fR\' are ignored\&.
-\fItype\fR
-and
-\fIzone\fR
-default to
-\fBLaserWriter\fR
-and the zone of the local host, respectively\&.
-.PP
-Note that
-\fBpap\fR
-is designed to be useful as a communication filter for sending
-\fBlpd\fR(8)
-spooled print jobs to AppleTalk connected printers\&. See
-\fBpsf\fR(8)
-for hints on how to use it this way\&.
-.SH "OPTIONS"
-.PP
-\fB\-A \fR\fIaddress\fR
-.RS 4
-Connect to the printer with Appletalk address
-\fIaddress\fR
-and do not consult the
-\fB\&.paprc\fR
-file to find a printer name\&. See
-\fBatalk_aton\fR(3)
-for the syntax of
-\fIaddress\fR\&.
-.RE
-.PP
-\fB\-c\fR
-.RS 4
-Take cuts\&. The PAP protocol specified a simple queuing procedure, such that the clients tell the printer how long they have been waiting to print\&. This option causes
-\fBpap\fR
-to lie about how long it has been waiting\&.
-.RE
-.PP
-\fB\-d\fR
-.RS 4
-Enable debug output\&.
-.RE
-.PP
-\fB\-e\fR
-.RS 4
-Send any message from the printer to stderr instead of stdout\&.
-\fBpsf\fR(8)
-invokes
-\fBpap\fR
-with this option\&.
-.RE
-.PP
-\fB\-E\fR
-.RS 4
-Don\'t wait for EOF from the printer\&. This option is useful for printers which don\'t implement PAP correctly\&. In a correct implementation, the client side should wait for the printer to return EOF before closing the connection\&. Some clients don\'t wait, and hence some printers have related bugs in their implementation\&.
-.RE
-.PP
-\fB\-p\fR \fInbpname\fR
-.RS 4
-Connect to the printer named
-\fInbpname\fR
-and do not consult the
-\fB\&.paprc\fR
-file to find a printer name\&. See
-\fBnbp_name\fR(3)
-for the syntax of
-\fInbpname\fR\&.
-.RE
-.PP
-\fB\-s\fR \fIstatusfile\fR
-.RS 4
-Update the file called
-\fIstatusfile\fR
-to contain the most recent status message from the printer\&.
-\fBpap\fR
-gets the status from the printer when it is waiting for the printer to process input\&. The
-\fIstatusfile\fR
-will contain a single line terminated with a newline\&. This is useful when
-\fBpap\fR
-is invoked by
-\fBpsf\fR(8)
-within
-\fBlpd\fR\'s spool directory\&.
-.RE
-.PP
-\fB\-w\fR
-.RS 4
-Wait for the printer status to contain the word "waiting" before sending the job\&. This is to defeat printer\-side spool available on HP IV and V printers\&.
-.RE
-.PP
-\fB\-W\fR
-.RS 4
-Wait for the printer status to contain the word "idle" before sending the job\&. This is to defeat printer\-side spool available on HP IV and V printers\&.
-.RE
-.SH "FILES"
-.PP
-\fB\&.paprc\fR
-.RS 4
-file read to obtain printer name if not specified on command line
-.RE
-.SH "SEE ALSO"
-.PP
-\fBnbp_name\fR(3),
-\fBatalk_aton\fR(3),
-\fBlpd\fR(8),
-\fBpsf\fR(8)\&.
diff --git a/man/man1/papstatus.1 b/man/man1/papstatus.1
deleted file mode 100644 (file)
index 631797d..0000000
+++ /dev/null
@@ -1 +0,0 @@
-.so man1/pap.1
diff --git a/man/man1/psorder.1 b/man/man1/psorder.1
deleted file mode 100644 (file)
index 724fe55..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-'\" t
-.\"     Title: psorder
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 17 Dec 1991
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "PSORDER" "1" "17 Dec 1991" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-psorder \- PostScript pageorder filter
-.SH "SYNOPSIS"
-.HP \w'\fBpsorder\fR\fB\fR\ 'u
-\fBpsorder\fR\fB\fR [\-duf] \fIsourcefile\fR
-.SH "DESCRIPTION"
-.PP
-\fBpsorder\fR
-is a filter that re\-orders the pages of a PostScript document\&. The result is written to the standard output\&. By default, documents are processed into ascending order (the lowest numbered page is printed first)\&. Some PostScript documents specify that the order of their pages should never be changed; the default action of
-\fBpsorder\fR
-is to follow this specification\&.
-.PP
-If no source file is given, or if
-\fIsourcefile\fR
-is `\fB\-\fR\',
-\fBpsorder\fR
-reads from the standard input file\&.
-.SH "OPTIONS"
-.PP
-\fB\-d\fR
-.RS 4
-Re\-order the pages of the document in downward or descending order\&. This is typically used to change the order of a document to be printed by a printer that stacks pages face\-up, such as an Apple LaserWriter or LaserWriter Plus\&.
-.RE
-.PP
-\fB\-u\fR
-.RS 4
-Specifies forward order, and is the default\&. It is used to try and ensure the correct ordering when a document will be printed by a printer that stacks the pages face\-down\&.
-.RE
-.PP
-\fB\-f\fR
-.RS 4
-Force
-\fBpsorder\fR
-to re\-order the pages, even if the document claims that its page order is not to be trifled with\&. This option should only be used experimentally, as it may cause documents to print incorrectly\&.
-.RE
-.SH "SEE ALSO"
-.PP
-\fBpsf\fR(8),
-\fBlpr\fR(1)\&.
index 9e314b52749147e0509c41281a0b75724d156bc9..729d35edf5b8de6ce1ebdb671e3158f7febe643a 100644 (file)
@@ -2,12 +2,12 @@
 .\"     Title: uniconv
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 24 Jun 2004
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"      Date: 23 Mar 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "UNICONV" "1" "24 Jun 2004" "Netatalk 2.2" "Netatalk 2.2"
+.TH "UNICONV" "1" "23 Mar 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
@@ -37,20 +37,20 @@ encoding\&.
 .PP
 \-c
 .RS 4
-CNID backend used on this volume, usually cdb or dbd\&. Should match the backend selected with afpd for this volume\&. If not specified, the default CNID backend `:DEFAULT_CNID_SCHEME:\' is used
+CNID backend used on this volume, usually cdb or dbd\&. Should match the backend selected with afpd for this volume\&. If not specified, the default CNID backend ":DEFAULT_CNID_SCHEME:" is used
 .RE
 .PP
 \-d
 .RS 4
-don\'t CAP encode leading dots (:2e), equivalent to
-\fBusedots\fR
+don\'t HEX encode leading dots (:2e), equivalent to
+\fBuse dots = yes\fR
 in
-\fBAppleVolumes.default\fR(5)
+\fBafp.conf\fR(5)
 .RE
 .PP
 \-f
 .RS 4
-encoding to convert from, use ASCII for CAP encoded volumes
+encoding to convert from, use ASCII for HEX encoded volumes
 .RE
 .PP
 \-h
@@ -60,12 +60,12 @@ display help
 .PP
 \-m
 .RS 4
-Macintosh client codepage, required for CAP encoded volumes\&. Defaults to `MAC_ROMAN\'
+Macintosh client codepage, required for HEX encoded volumes\&. Defaults to "MAC_ROMAN"
 .RE
 .PP
 \-n
 .RS 4
-`dry run\', don\'t do any real changes
+"dry run", don\'t do any real changes
 .RE
 .PP
 \-t
@@ -89,7 +89,7 @@ Setting the wrong options might render your data unusable!!! Make sure you know
 .PP
 It is
 \fB*strongly*\fR
-recommended to do a `dry run\' first and to check the output for conversion errors\&.
+recommended to do a "dry run" first and to check the output for conversion errors\&.
 .PP
 \fBafpd\fR(8)
 should
@@ -109,7 +109,7 @@ or
 \fBUSE AT YOUR OWN RISK!!!\fR
 .SH "SELECTABLE CHARSETS"
 .PP
-Netatalk provides internal support for UTF\-8 (pre\- and decomposed) and CAP\&. If you want to use other charsets, they must be provided by
+Netatalk provides internal support for UTF\-8 (pre\- and decomposed) and HEX\&. If you want to use other charsets, they must be provided by
 \fBiconv\fR(1)
 .PP
 \fBuniconv\fR
@@ -164,7 +164,7 @@ example%\fB uniconv \-c cdb \-f ISO\-8859\-1 \-t UTF8 \-m MAC_ROMAN /path/to/sha
 .RE
 .\}
 .PP
-convert 1\&.x volume using iso8859\-1 adapted NLS to CAP encoding:
+convert 1\&.x volume using iso8859\-1 adapted NLS to HEX encoding:
 .sp
 .if n \{\
 .RS 4
@@ -176,7 +176,7 @@ example%\fB uniconv \-f ISO\-8859\-ADAPTED \-t ASCII \-m MAC_ROMAN/path/to/share
 .RE
 .\}
 .PP
-convert UTF\-8 volume to CAP, for MacCyrillic clients:
+convert UTF\-8 volume to HEX, for MacCyrillic clients:
 .sp
 .if n \{\
 .RS 4
@@ -189,4 +189,4 @@ example%\fB uniconv \-f UTF8 \-t ASCII \-m MAC_CYRILLIC /path/to/share\fR
 .\}
 .SH "SEE ALSO"
 .PP
-\fBAppleVolumes.default\fR(5),\fBafpd\fR(8),\fBiconv\fR(1),\fBcnid_metad\fR(8),\fBcnid_dbd\fR(8)
+\fBafp.conf\fR(5),\fBafpd\fR(8),\fBiconv\fR(1),\fBcnid_metad\fR(8),\fBcnid_dbd\fR(8)
diff --git a/man/man3/.gitignore b/man/man3/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/man/man3/Makefile.am b/man/man3/Makefile.am
deleted file mode 100644 (file)
index 198f977..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-# Makefile.am for man/man3
-
-ATALK_MANS = atalk_aton.3 nbp_name.3
-
-if USE_APPLETALK
-man_MANS = $(ATALK_MANS)
-endif
-
-EXTRA_DIST = $(ATALK_MANS)
diff --git a/man/man3/atalk_aton.3 b/man/man3/atalk_aton.3
deleted file mode 100644 (file)
index d4f5d94..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-'\" t
-.\"     Title: atalk_aton
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 12 Jan 1994
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "ATALK_ATON" "3" "12 Jan 1994" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-atalk_aton \- AppleTalk address parsing
-.SH "SYNOPSIS"
-.sp
-.ft B
-.nf
-#include <sys/types\&.h>
-#include <netatalk/at\&.h>
-.fi
-.ft
-.HP \w'atalk_aton('u
-.BI "atalk_aton(char\ *\ " "cp" ", struct\ at_addr\ *\ " "ata" ");"
-.SH "DESCRIPTION"
-.PP
-The
-\fBatalk_aton()\fR
-routine converts an ASCII representation of an AppleTalk address to a format appropriate for system calls\&. Acceptable ASCII representations include both hex and base 10, in triples or doubles\&. For instance, the address `0x1f6b\&.77\' has a network part of `8043\' and a node part of `119\'\&. This same address could be written `8043\&.119\', `31\&.107\&.119\', or `0x1f\&.6b\&.77\'\&. If the address is in hex and the first digit is one of `A\-F\', a leading `0x\' is redundant\&.
-.SH "SEE ALSO"
-.PP
-\fBatalk\fR(4)\&.
diff --git a/man/man3/nbp_name.3 b/man/man3/nbp_name.3
deleted file mode 100644 (file)
index 6791f4a..0000000
+++ /dev/null
@@ -1,88 +0,0 @@
-'\" t
-.\"     Title: nbp_name
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 12 Jan 1994
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "NBP_NAME" "3" "12 Jan 1994" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-nbp_name \- NBP name parsing
-.SH "SYNOPSIS"
-.HP \w'int\ nbp_name('u
-.BI "int nbp_name(char\ *" "name" ", char\ **" "obj" ", char\ **" "type" ", char\ **" "zone" ");"
-.SH "DESCRIPTION"
-.PP
-\fBnbp_name()\fR
-parses user supplied names into their component object, type, and zone\&.
-\fBobj\fR,
-\fBtype\fR, and
-\fIzone\fR
-should be passed by reference, and should point to the caller\'s default values\&.
-\fBnbp_name()\fR
-will change the pointers to the parsed\-out values\&.
-\fBname\fR
-is of the form
-\fIobject\fR\fB:\fR\fItype\fR\fB@\fR\fIzone\fR, where each of
-\fIobject\fR,
-\fB:\fR\fItype\fR\fB,\fR
-and
-\fB@\fR\fIzone\fR
-replace
-\fBobj\fR,
-\fBtype\fR, and
-\fBzone,\fR
-respectively\&.
-\fItype\fR
-must be proceeded by `\fB:\fR\', and
-\fIzone\fR
-must be preceded by `\fB@\fR\'\&.
-.SH "EXAMPLE"
-.PP
-The argument of
-\fBafpd\fR(8)\'s
-\fB\-n\fR
-option is parsed with
-\fBnbp_name()\fR\&. The default value of
-\fBobj\fR
-is the first component of the machine\'s hostname (as returned by
-\fBgethostbyname\fR(3))\&. The default value of
-\fBtype\fR
-is ``AFPServer\'\', and of
-\fIzone\fR
-is ``*\'\', the default zone\&. To cause
-\fBafpd\fR
-to register itself in some zone other than the default, one would invoke it as
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-afpd \-n @some\-other\-zone
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-\fBobj\fR
-and
-\fBtype\fR
-would retain their default values\&.
-.SH "BUGS"
-.PP
-\fBobj\fR,
-\fBtype\fR, and
-\fIzone\fR
-return pointers into static area which may be over\-written on each call\&.
diff --git a/man/man4/.gitignore b/man/man4/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/man/man4/Makefile.am b/man/man4/Makefile.am
deleted file mode 100644 (file)
index d0295d4..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-# Makefile.am for man/man4/
-
-ATALK_MANS = atalk.4
-
-if USE_APPLETALK
-man_MANS = $(ATALK_MANS)
-endif
-
-EXTRA_DIST = $(ATALK_MANS)
diff --git a/man/man4/atalk.4 b/man/man4/atalk.4
deleted file mode 100644 (file)
index 356b93e..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-'\" t
-.\"     Title: atalk
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 17 Dec 1991
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "ATALK" "4" "17 Dec 1991" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-atalk \- AppleTalk protocol family
-.SH "SYNOPSIS"
-.sp
-.ft B
-.nf
-#include <sys/types\&.h>
-#include <netatalk/at\&.h>
-.fi
-.ft
-.SH "DESCRIPTION"
-.PP
-The AppleTalk protocol family is a collection of protocols layered above the Datagram Delivery Protocol (DDP), and using AppleTalk address format\&. The AppleTalk family may provide SOCK_STREAM (ADSP), SOCK_DGRAM (DDP), SOCK_RDM (ATP), and SOCK_SEQPACKET (ASP)\&. Currently, only DDP is implemented in the kernel; ATP and ASP are implemented in user level libraries; and ADSP is planned\&.
-.SH "ADDRESSING"
-.PP
-AppleTalk addresses are three byte quantities, stored in network byte order\&. The include file <\fBnetatalk/at\&.h\fR> defines the AppleTalk address format\&.
-.PP
-Sockets in the AppleTalk protocol family use the following address structure:
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-struct sockaddr_at {
-    short sat_family;
-    u_char sat_port;
-    struct at_addr sat_addr;
-    char sat_zero[ 8 ];
-};
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-The port of a socket may be set with
-\fBbind\fR(2)\&. The node for
-\fBbind\fR
-must always be
-\fBATADDR_ANYNODE\fR: ``this node\&.\'\' The net may be
-\fBATADDR_ANYNET\fR
-or
-\fBATADDR_LATENET\fR\&.
-\fBATADDR_ANYNET\fR
-coresponds to the machine\'s ``primary\'\' address (the first configured)\&.
-\fBATADDR_LATENET\fR
-causes the address in outgoing packets to be determined when a packet is sent, i\&.e\&. determined late\&.
-\fBATADDR_LATENET\fR
-is equivalent to opening one socket for each network interface\&. The port of a socket and either the primary address or
-\fBATADDR_LATENET\fR
-are returned with
-\fBgetsockname\fR(2)\&.
-.SH "SEE ALSO"
-.PP
-\fBbind\fR(2),
-\fBgetsockname\fR(2),
-\fBatalkd\fR(8)\&.
index a8e16a5768e26d71c12dac4d9c3d66b88ee9060b..ba10eeb069f64c047345d71684667225ae54657d 100644 (file)
@@ -1,5 +1,4 @@
 Makefile
 Makefile.in
 *.5
-.gitignore
 *.o
diff --git a/man/man5/AppleVolumes.5 b/man/man5/AppleVolumes.5
deleted file mode 100644 (file)
index e12bc53..0000000
+++ /dev/null
@@ -1 +0,0 @@
-.so man5/AppleVolumes.default.5
diff --git a/man/man5/AppleVolumes.default.5.tmpl b/man/man5/AppleVolumes.default.5.tmpl
deleted file mode 100644 (file)
index 6aabe03..0000000
+++ /dev/null
@@ -1,732 +0,0 @@
-'\" t
-.\"     Title: AppleVolumes.default
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 13 Oct 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "APPLEVOLUMES\&.DEFAU" "5" "13 Oct 2011" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-AppleVolumes.default, AppleVolumes.system, AppleVolumes \- Configuration file used by \fBafpd\fR(8) to determine the shares made available through AFP and specify file name extension mappings\&.
-.SH "SYNOPSIS"
-.HP \w'\fB:ETCDIR:/AppleVolumes\&.default\fR\fB\fR\fB:ETCDIR:/AppleVolumes\&.system\fR\fB\fR\fB~/AppleVolumes\fR\fB\fR\fB~/\&.AppleVolumes\fR\fB\fR\fB~/applevolumes\fR\fB\fR\fB~/\&.applevolumes\fR\fB\fR\ 'u
-\fB:ETCDIR:/AppleVolumes\&.default\fR\fB\fR
-.br
-\fB:ETCDIR:/AppleVolumes\&.system\fR\fB\fR
-.br
-\fB~/AppleVolumes\fR\fB\fR
-.br
-\fB~/\&.AppleVolumes\fR\fB\fR
-.br
-\fB~/applevolumes\fR\fB\fR
-.br
-\fB~/\&.applevolumes\fR\fB\fR
-.SH "DESCRIPTION"
-.PP
-
-:ETCDIR:/AppleVolumes\&.system
-and one of
-:ETCDIR:/AppleVolumes\&.default,
-~/AppleVolumes,
-~/\&.AppleVolumes,
-~/applevolumes, or
-~/\&.applevolumes
-are the configuration files used by
-\fBafpd\fR
-to determine what portions of the file system will be shared via Apple Filing Protocol, as well as their behaviour\&.
-.PP
-Any line not prefixed with # is interpreted\&. Newline escaping is supported\&. The configuration lines are composed like:
-.PP
-path
-\fI[ volume name ] [ options ]\fR
-.PP
-\&.extension
-\fI[ type [ creator ] ]\fR
-.PP
-The path name must be a fully qualified path name, or a path name using either the ~ shell shorthand or any of the substitution variables, which are listed below\&.
-.PP
-The volume name is the name that appears in the Chooser ot the "connect to server" dialog on Macintoshes to represent the appropriate share\&. If volumename is unspecified, the last component of pathname is used\&. No two volumes may have the same name\&. If there are spaces in the name, it should be in quotes (i\&.e\&. "File Share")\&. The volume name cannot contain the
-\':\'
-character\&. The volume name is mangled if it is very long\&. Mac codepage volume name is limited to 27 characters\&. UTF8\-MAC volume name is limited to \-volnamelen parameter in afpd\&.conf
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-.PP
-Each volume has to be configured on a
-\fBsingle\fR
-line\&. Though newline escaping is supported\&.
-.sp .5v
-.RE
-.PP
-The leading\-dot lines specify file name extension mappings\&. The extension \'\&.\' sets the default creator and type for otherwise untyped Unix files\&.
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-.PP
-File name extension mapping is useful for Mac OS 9 and earlier\&. But it should not use for Mac OS X\&.
-.sp .5v
-.RE
-.PP
-It is possible to specify default options for all volumes with a
-\fI:DEFAULT: \fRline preceeding these volume definitions:
-.PP
-\fBExample.\ \&:DEFAULT: configuration line\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-:DEFAULT: options:upriv,usedots dbpath:/var/dbd/AppleDB/$v dperm:0775 fperm:0664
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-The possible options and their meanings are:
-.PP
-adouble:\fI[v1|v2|osx]\fR
-.RS 4
-Specify the format of the metadata files, which are used for saving Mac resource fork as well\&. Earlier versions used AppleDouble V1, the new default format is V2\&. Starting with Netatalk 2\&.0, the scheme MacOS X 10\&.3\&.x uses, is also supported\&.
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-\fBadouble:osx\fR
-\fBcannot\fR
-be treated normally any longer\&. Its only aim was to temporarely share eg\&. FAT32 formatted FireWire harddrives written on a Macintosh with afpd\&. Apple\'s metadata scheme lacks several essential features, so using it on the server\'s side will break both CNIDs and MacOS 9 compatibility\&. AppleDouble file of Mac OS X 10\&.6 is incompatible to V1 and V2\&.
-.sp .5v
-.RE
-.RE
-.PP
-volsizelimit:\fIsize in MiB\fR
-.RS 4
-Useful for TimeMachine: limits the reported volume size, thus preventing TM from using the whole real disk space for backup\&. Example: "volsizelimit:1000" would limit the reported disk space to 1 GB\&.
-\fBIMPORTANT: \fR
-This is an approximated calculation taking into accout the contents of TM sparsebundle images\&. Therefor you MUST NOT use this volume to store other content when using this option, because it would NOT be accounted\&. The calculation works by reading the band size from the Info\&.plist XML file of the sparsebundle, reading the bands/ directory counting the number of band files, and then multiplying one with the other\&.
-.RE
-.PP
-allow:\fI[users/groups]\fR
-.RS 4
-The allow option allows the users and groups that access a share to be specified\&. Users and groups are specified, delimited by commas\&. Groups are designated by a @ prefix\&. Example: allow:user1,user2,@group
-.RE
-.PP
-deny:\fI[users/groups]\fR
-.RS 4
-The deny option specifies users and groups who are not allowed access to the share\&. It follows the same format as the allow option\&.
-.RE
-.PP
-allowed_hosts:\fI[IP host address/IP netmask bits[, \&.\&.\&. ]]\fR
-.RS 4
-Only listed hosts and networks are allowed, all others are rejected\&. The network address may be specified either in dotted\-decimal format for IPv4 or in hexadecimal format for IPv6\&.
-.sp
-Example: allowed_hosts:10\&.1\&.0\&.0/16,10\&.2\&.1\&.100,2001:0db8:1234::/48
-.RE
-.PP
-denied_hosts:\fI[IP host address/IP netmask bits[, \&.\&.\&.]]\fR
-.RS 4
-Listed hosts and nets are rejected, all others are allowed\&.
-.sp
-Example: denied_hosts: 192\&.168\&.100/24,10\&.1\&.1\&.1,2001:db8::1428:57ab
-.RE
-.PP
-cnidscheme:\fI[backend]\fR
-.RS 4
-set the CNID backend to be used for the volume, default is [:DEFAULT_CNID_SCHEME:] available schemes: [:COMPILED_BACKENDS:]
-.RE
-.PP
-dbpath:\fI[path]\fR
-.RS 4
-Sets the database information to be stored in path\&. You have to specifiy a writable location, even if the volume is read only\&.
-.RE
-.PP
-cnidserver:\fI[fqdn|IP[:port]]\fR
-.RS 4
-Query this servername or IP address (default:\fIlocalhost\fR) and port (default:
-\fI4700\fR) for CNIDs\&. Only used with CNID backend "\fIdbd\fR"\&. This option here overrides any setting from
-afpd\&.conf:\fBcnidserver\fR\&.
-.RE
-.PP
-ea:\fI[none|auto|sys|ad]\fR
-.RS 4
-Specify how Extended Attributes
-are stored\&.
-\fBauto\fR
-is the default\&.
-.PP
-auto
-.RS 4
-Try
-\fBsys\fR
-(by setting an EA on the shared directory itself), fallback to
-\fBad\fR\&. Requires writeable volume for perfoming test\&.
-\fBoptions:ro\fR
-overwrites
-\fBauto\fR
-with
-\fBnone\fR\&. Use explicit
-\fBea:sys|ad\fR
-for read\-only volumes where appropiate\&.
-.RE
-.PP
-sys
-.RS 4
-Use filesystem Extended Attributes\&.
-.RE
-.PP
-ad
-.RS 4
-Use files in
-\fI\&.AppleDouble\fR
-directories\&.
-.RE
-.PP
-none
-.RS 4
-No Extended Attributes support\&.
-.RE
-.RE
-.PP
-maccharset:\fI[charset]\fR
-.RS 4
-specifies the mac client codepage for this Volume, e\&.g\&. "MAC_ROMAN", "MAC_CYRILLIC"\&. If not specified the setting from
-afpd\&.conf
-is inherited\&. This setting is only required if you need volumes, where the mac codepage differs from the one globally set in
-afpd\&.conf\&.
-.RE
-.PP
-options:\fI[option]\fR
-.RS 4
-This allows multiple options to be specified in a comma delimited format\&. The available options are:
-.PP
-searchdb
-.RS 4
-Use fast CNID database namesearch instead of slow recursive filesystem search\&. Relies on a consistent CNID database, ie Samba or local filesystem access lead to inaccurate or wrong results\&. Works only for "dbd" CNID db volumes\&.
-.RE
-.PP
-tm
-.RS 4
-Enable Time Machine suport for this volume\&.
-.RE
-.PP
-invisibledots
-.RS 4
-Use with
-\fBusedots\fR: make dot files invisible\&.
-.RE
-.PP
-nonetids
-.RS 4
-Try to force ACL unawareness on the client\&.
-.RE
-.PP
-limitsize
-.RS 4
-Limit disk size reporting to 2GB\&. This can be used for older Macintoshes using newer Appleshare clients\&.
-.RE
-.PP
-preexec_close
-.RS 4
-a non\-zero return code from preexec close the volume being immediately, preventing clients to mount/see the volume in question\&.
-.RE
-.PP
-ro
-.RS 4
-Specifies the share as being read only for all users\&. The \&.AppleDB directory has to be writeable, you can use the
-\fB\-dbpath\fR
-option to relocate it\&. Overwrites
-\fBea:auto\fR
-with
-\fBea:none\fR
-.RE
-.PP
-root_preexec_close
-.RS 4
-a non\-zero return code from root_preexec closes the volume immediately, preventing clients to mount/see the volume in question\&.
-.RE
-.PP
-upriv
-.RS 4
-use AFP3 unix privileges\&. This should be set for OS X clients\&. Starting with Netatalk 2\&.1 it\'s part of the default config :DEFAULT: line\&. See also:
-\fBperm|fperm|dperm\fR\&.
-.RE
-.PP
-usedots
-.RS 4
-Don\'t do :hex translation for dot files\&. note: when this option gets set, certain file names become illegal\&. These are \&.Parent and anything that starts with \&.Apple\&. See also
-\fBinvisibledots\fR\&.
-.RE
-.RE
-.PP
-password:\fI[password]\fR
-.RS 4
-This option allows you to set a volume password, which can be a maximum of 8 characters long (using ASCII strongly recommended at the time of this writing)\&.
-.RE
-.PP
-perm|fperm|dperm:\fI[mode]\fR
-.RS 4
-Add(or) with the client requested permissions:
-\fBperm\fR
-affects files and directories,
-\fBfperm\fR
-is for files only,
-\fBdperm\fR
-is for directories only\&. Use with
-\fBoptions:upriv\fR\&.
-.PP
-\fBExample.\ \&Volume for a collaborative workgroup\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-/path/to/volume "Workgroup" options:upriv dperm:0770 fperm:0660
-.fi
-.if n \{\
-.RE
-.\}
-.RE
-.PP
-umask:\fI[mode]\fR
-.RS 4
-set perm mask\&. Use with
-\fBoptions:upriv\fR\&.
-.RE
-.PP
-preexec:\fI[command]\fR
-.RS 4
-command to be run when the volume is mounted, ignored for user defined volumes
-.RE
-.PP
-postexec:\fI[command]\fR
-.RS 4
-command to be run when the volume is closed, ignored for user defined volumes
-.RE
-.PP
-root_preexec:\fI[command]\fR
-.RS 4
-command to be run as root when the volume is mounted, ignored for user defined volumes
-.RE
-.PP
-root_postexec:\fI[command]\fR
-.RS 4
-command to be run as root when the volume is closed, ignored for user defined volumes
-.RE
-.PP
-rolist:[\fBusers/groups\fR]
-.RS 4
-Allows certain users and groups to have read\-only access to a share\&. This follows the allow option format\&.
-.RE
-.PP
-rwlist:\fI[users/groups]\fR
-.RS 4
-Allows certain users and groups to have read/write access to a share\&. This follows the allow option format\&.
-.RE
-.PP
-veto:\fI[vetoed names]\fR
-.RS 4
-hide files and directories,where the path matches one of the \'/\' delimited vetoed names\&. The veto string must always be terminated with a \'/\', eg\&. "veto1/", "veto1/veto2/"\&.
-.RE
-.PP
-volcharset:\fI[charset]\fR
-.RS 4
-specifies the volume codepage, e\&.g\&. "UTF8", "UTF8\-MAC", "ISO\-8859\-15"\&. Defaults to "UTF8"\&.
-.RE
-.SH "VARIABLE SUBSTITUTIONS"
-.PP
-You can use variables in both volume path and volume name\&.
-.sp
-.RS 4
-.ie n \{\
-\h'-04' 1.\h'+01'\c
-.\}
-.el \{\
-.sp -1
-.IP "  1." 4.2
-.\}
-if you specify an unknown variable, it will not get converted\&.
-.RE
-.sp
-.RS 4
-.ie n \{\
-\h'-04' 2.\h'+01'\c
-.\}
-.el \{\
-.sp -1
-.IP "  2." 4.2
-.\}
-if you specify a known variable, but that variable doesn\'t have a value, it will get ignored\&.
-.RE
-.PP
-The variables which can be used for substitutions are:
-.PP
-$b
-.RS 4
-basename
-.RE
-.PP
-$c
-.RS 4
-client\'s ip or appletalk address
-.RE
-.PP
-$d
-.RS 4
-volume pathname on server
-.RE
-.PP
-$f
-.RS 4
-full name (contents of the gecos field in the passwd file)
-.RE
-.PP
-$g
-.RS 4
-group name
-.RE
-.PP
-$h
-.RS 4
-hostname
-.RE
-.PP
-$i
-.RS 4
-client\'s ip, without port
-.RE
-.PP
-$s
-.RS 4
-server name (this can be the hostname)
-.RE
-.PP
-$u
-.RS 4
-user name (if guest, it is the user that guest is running as)
-.RE
-.PP
-$v
-.RS 4
-volume name (either ADEID_NAME or basename of path)
-.RE
-.PP
-$z
-.RS 4
-appletalk zone (may not exist)
-.RE
-.PP
-$$
-.RS 4
-prints dollar sign ($)
-.RE
-.PP
-\fBExample.\ \&Using variable substitution when defining volumes\fR
-.PP
-.if n \{\
-.RS 4
-.\}
-.nf
-/home/groups/$g "Groupdir for $g"
-~ "$f is the best one"
-.fi
-.if n \{\
-.RE
-.\}
-.sp
-We define "groupdirs" for each primary group and use a personalized server name for homedir shares\&.
-.SH "CNID BACKENDS"
-.PP
-The AFP protocol mostly refers to files and directories by ID and not by name\&. Netatalk needs a way to store these ID\'s in a persistent way, to achieve this several different CNID backends are available\&. The CNID Databases are by default located in the
-\&.AppleDB
-folder in the volume root\&.
-.PP
-cdb
-.RS 4
-"Concurrent database", backend is based on Sleepycat\'s Berkely DB\&. With this backend several
-\fBafpd\fR
-deamons access the CNID database directly\&. Berkeley DB locking is used to synchronize access, if more than one
-\fBafpd\fR
-process is active for a volume\&. The drawback is, that the crash of a single
-\fBafpd\fR
-process might corrupt the database\&.
-.RE
-.PP
-dbd
-.RS 4
-Access to the CNID database is restricted to the
-\fBcnid_metad\fR
-daemon process\&.
-\fBafpd\fR
-processes communicate with the daemon for database reads and updates\&. If built with Berkeley DB transactions the probability for database corruption is practically zero, but performance can be slower than with
-\fBcdb\fR
-.RE
-.PP
-last
-.RS 4
-This backend is an exception, in terms of ID persistency\&. ID\'s are only valid for the current session\&. This is basically what
-\fBafpd\fR
-did in the 1\&.5 (and 1\&.6) versions\&. This backend is still available, as it is useful for e\&.g\&. sharing cdroms\&.
-.sp
-\fBWarning\fR: It is
-\fINOT\fR
-recommended to use this backend for volumes anymore, as
-\fBafpd\fR
-now relies heavily on a persistent ID database\&. Aliases will likely not work and filename mangling is not supported\&.
-.RE
-.PP
-Even though
-\fB\&./configure \-\-help\fR
-might show that there are other CNID backends available, be warned those are likely broken or mainly used for testing\&. Don\'t use them unless you know what you\'re doing, they may be removed without further notice from future versions\&.
-.SH "CHARSET OPTIONS"
-.PP
-With OS X Apple introduced the AFP3 protocol\&. One of the most important changes was that AFP3 uses unicode names encoded as UTF\-8 decomposed\&. Previous AFP/OS versions used codepages, like MacRoman, MacCentralEurope, etc\&.
-.PP
-\fBafpd\fR
-needs a way to preserve extended macintosh characters, or characters illegal in unix filenames, when saving files on a unix filesystem\&. Earlier versions used the the so called CAP encoding\&. An extended character (>0x7F) would be converted to a :xx sequence, e\&.g\&. the Apple Logo (MacRoman: 0XF0) was saved as
-:f0\&. Some special characters will be converted as to :xx notation as well\&. \'/\' will be encoded to
-:2f, if
-\fBusedots\fR
-is not specified, a leading dot \'\&.\' will be encoded as
-:2e\&.
-.PP
-This version now uses UTF\-8 as the default encoding for names\&. Special characters, like \'/\' and a leading \'\&.\' will still be CAP style encoded \&.
-.PP
-The
-\fB\-volcharset\fR
-option will allow you to select another volume encoding\&. E\&.g\&. for western users another useful setting could be \-volcharset ISO\-8859\-15\&.
-\fBapfd\fR
-will accept any
-\fBiconv\fR(1)
-provided charset\&. If a character cannot be converted from the mac codepage to the selected volcharset, afpd will save it as a CAP encoded character\&. For AFP3 clients,
-\fBafpd\fR
-will convert the UTF\-8
-character to
-\fB\-maccharset\fR
-first\&. If this conversion fails, you\'ll receive a \-50 error on the mac\&.
-.PP
-\fINote\fR: Whenever you can, please stick with the default UTF\-8 volume format\&.
-.SH "COMPATIBILITY WITH EARLIER VERSIONS"
-.PP
-To use a volume created with an earlier
-\fBafpd\fR
-version, you\'ll have to specify the following options:
-.PP
-\fBExample.\ \&use a 1.x style volume\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-/path/to/volume "Volname" adouble:v1 volcharset:ASCII
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-In case you used an NLS you could try using a compatible iconv charset for
-\fB\-volcharset\fR\&.
-.PP
-\fBExample.\ \&use a 1.x style volume, created with maccode.iso8859-1\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-/path/to/volume "Volname" adouble:v1 volcharset:ISO\-8859\-1
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-You should consider converting old style volumes to the new UTF\-8/AD2 format\&. The safest way to do this, is to create a new volume with the default options and copy the files between this volumes with a mac\&.
-.PP
-\fINote\fR: Using above example options will allow you to downgrade to 1\&.x netatalk again\&.
-.PP
-\fINote\fR: Some 1\&.x NLS files used non standard mappings, e\&.g\&.
-maccode\&.iso8859\-1\&.adapted\&. Three 1\&.x CAP double\-byte maccharsets are incompatible to netatalk 2\&.x; "MAC_CHINESE_TRAD", "MAC_JAPANESE" and "MAC_KOREAN"\&. These are not supported anymore\&. You\'ll have to copy the contents of those volumes files to a Mac and then back to the netatalk server, preferably to an UTF\-8 volume\&.
-.SH "ADVANCED OPTIONS"
-.PP
-The following options should only be used after serious consideration\&. Be sure you fully understood the, sometimes complex, consequences, before using them\&.
-.PP
-casefold:\fB[option]\fR
-.RS 4
-The casefold option handles, if the case of filenames should be changed\&. The available options are:
-.sp
-\fBtolower\fR
-\- Lowercases names in both directions\&.
-.sp
-\fBtoupper\fR
-\- Uppercases names in both directions\&.
-.sp
-\fBxlatelower\fR
-\- Client sees lowercase, server sees uppercase\&.
-.sp
-\fBxlateupper\fR
-\- Client sees uppercase, server sees lowercase\&.
-.RE
-.PP
-options:[\fBoption\fR]
-.RS 4
-This allows multiple options to be specified in a comma delimited format\&. The available options are:
-.PP
-caseinsensitive
-.RS 4
-The underlying filesystem is case insensitive (only tested with JFS in OS2 mode)\&.
-.RE
-.PP
-crlf
-.RS 4
-Enables crlf translation for TEXT files, automatically converting macintosh line breaks into Unix ones\&. Use of this option might be dangerous since some older programs store binary data files as type "TEXT" when saving and switch the filetype in a second step\&.
-\fBAfpd\fR
-will potentially destroy such files when "erroneously" changing bytes in order to do line break translation\&.
-.RE
-.PP
-dropbox
-.RS 4
-Allows a volume to be declared as being a "dropbox\&." Note that netatalk must be compiled with dropkludge support for this to function\&.
-\fIWarning\fR: This option is deprecated and might not work as expected\&.
-.RE
-.PP
-dropkludge
-.RS 4
-same as "dropbox"\&.
-.RE
-.PP
-mswindows
-.RS 4
-Forces filename restrictions imposed by MS WinXX\&.
-\fIWarning\fR: This is
-\fINOT\fR
-recommened for volumes mainly used by Macs\&. Please make sure you fully understand this option before using it\&.
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBWarning\fR
-.ps -1
-.br
-This option breaks direct saving to netatalk volumes from some applications, i\&.e\&. OfficeX\&.
-.sp .5v
-.RE
-.RE
-.PP
-noadouble
-.RS 4
-Forces
-\fBafpd\fR
-to not create \&.AppleDouble directories unless macintosh metadata needs to be written\&. This option is only useful if you want to share files mostly used NOT by macs, causing
-\fBafpd\fR
-to not automatically create \&.AppleDouble subdirs containing AD header files in every directory it enters (which will it do by default)\&.
-.sp
-In case, you save or change files from mac clients, AD metadata files have to be written even in case you set this option\&. So you can\'t avoid the creation of \&.AppleDouble directories and its contents when you give macs write access to a share and they make use of it\&.
-.sp
-Try to avoid
-\fBnoadouble\fR
-whenever possible\&.
-.RE
-.PP
-nocnidcache
-.RS 4
-If set
-\fBafpd\fR
-doesn\'t store the ID information in AppleDouble V2 header files\&. As these IDs are used for caching and as a database backup, this option normally shouldn\'t be set\&.
-.RE
-.PP
-nodev
-.RS 4
-always use 0 for device number, helps when the device number is not constant across a reboot, cluster, \&.\&.\&.
-.RE
-.PP
-nofileid
-.RS 4
-don\'t advertise createfileid, resolveid, deleteid calls\&.
-.RE
-.PP
-nohex
-.RS 4
-Disables :hex translations for anything except dot files\&. This option makes the
-\'/\' character illegal\&.
-.RE
-.PP
-nostat
-.RS 4
-don\'t stat volume path when enumerating volumes list, useful for automounting or volumes created by a preexec script\&.
-.RE
-.PP
-prodos
-.RS 4
-Provides compatibility with Apple II clients\&. (legacy)
-.RE
-.RE
-.SH "FILE NAME EXTENSION MAPPINGS"
-.PP
-\fBExample.\ \&Extension is jpg. Type is "JPEG". Creator is "ogle".\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\&.jpg "JPEG" "ogle"
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-\fBExample.\ \&Extension is lzh. Type is "LHA ". Creator is not defined.\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\&.lzh "LHA "
-.fi
-.if n \{\
-.RE
-.\}
-.SH "SEE ALSO"
-.PP
-\fBafpd.conf\fR(5),
-\fBafpd\fR(8),
-\fBcnid_metad\fR(8)
diff --git a/man/man5/AppleVolumes.system.5 b/man/man5/AppleVolumes.system.5
deleted file mode 100644 (file)
index e12bc53..0000000
+++ /dev/null
@@ -1 +0,0 @@
-.so man5/AppleVolumes.default.5
index a382039eeae6ebfa7475aba6bb89d57ab5039139..fd2edf6ca7aa9b84d68dbd9844fdbb39687827fe 100644 (file)
@@ -9,35 +9,17 @@ SUFFIXES = .tmpl .
            -e "s@:BINDIR:@${bindir}@g" \
            -e "s@:ETCDIR:@${pkgconfdir}@g" \
            -e "s@:LIBDIR:@${libdir}@g" \
+           -e "s@:STATEDIR:@${localstatedir}@g" \
            -e "s@:DEFAULT_CNID_SCHEME:@${DEFAULT_CNID_SCHEME}@g" \
            -e "s@:COMPILED_BACKENDS:@${compiled_backends}@g" \
            <$< >$@
 
-GENERATED_MANS = AppleVolumes.default.5 \
-       afpd.conf.5 \
-       netatalk.conf.5 \
-       afp_ldap.conf.5 \
-       afp_signature.conf.5 \
-       afp_voluuid.conf.5
-
-TEMPLATE_FILES = AppleVolumes.default.5.tmpl \
-       afpd.conf.5.tmpl \
-       netatalk.conf.5.tmpl \
-       afp_ldap.conf.5.tmpl \
-       afp_signature.conf.5.tmpl \
-       afp_voluuid.conf.5.tmpl
-
-ATALK_MANS = atalkd.conf.5.tmpl papd.conf.5.tmpl
-
-if USE_APPLETALK
-GENERATED_MANS += atalkd.conf.5 papd.conf.5
-TEMPLATE_FILES += $(ATALK_MANS)
-endif
-
-NONGENERATED_MANS = AppleVolumes.5 AppleVolumes.system.5
+GENERATED_MANS = afp.conf.5 afp_signature.conf.5 afp_voluuid.conf.5
+TEMPLATE_FILES = afp.conf.5.tmpl afp_signature.conf.5.tmpl afp_voluuid.conf.5.tmpl
+NONGENERATED_MANS =
 
 man_MANS = $(GENERATED_MANS) $(NONGENERATED_MANS)
 
 CLEANFILES = $(GENERATED_MANS)
 
-EXTRA_DIST = $(TEMPLATE_FILES) $(NONGENERATED_MANS) $(ATALK_MANS)
+EXTRA_DIST = $(TEMPLATE_FILES) $(NONGENERATED_MANS)
diff --git a/man/man5/afp.conf.5.tmpl b/man/man5/afp.conf.5.tmpl
new file mode 100644 (file)
index 0000000..5b53084
--- /dev/null
@@ -0,0 +1,1105 @@
+'\" t
+.\"     Title: afp.conf
+.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
+.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
+.\"      Date: 22 May 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
+.\"  Language: English
+.\"
+.TH "AFP\&.CONF" "5" "22 May 2012" "Netatalk 3.0" "Netatalk 3.0"
+.\" -----------------------------------------------------------------
+.\" * set default formatting
+.\" -----------------------------------------------------------------
+.\" disable hyphenation
+.nh
+.\" disable justification (adjust text to left margin only)
+.ad l
+.\" -----------------------------------------------------------------
+.\" * MAIN CONTENT STARTS HERE *
+.\" -----------------------------------------------------------------
+.SH "NAME"
+afp.conf \- Netatalk configuration file
+.SH "SYNOPSIS"
+.PP
+The
+afp\&.conf
+file is the configuration file for the
+\fBNetatalk\fR
+AFP file server\&.
+.PP
+All AFP specific configuration and AFP volume definitions are done via this file\&.
+.SH "FILE FORMAT"
+.PP
+The file consists of sections and parameters\&. A section begins with the name of the section in square brackets and continues until the next section begins\&. Sections contain parameters of the form:
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+\fIname\fR = \fIvalue \fR
+      
+.fi
+.if n \{\
+.RE
+.\}
+.PP
+The file is line\-based \- that is, each newline\-terminated line represents either a comment, a section name or a parameter\&.
+.PP
+Section and parameter names are case sensitive\&.
+.PP
+Only the first equals sign in a parameter is significant\&. Whitespace before or after the first equals sign is discarded\&. Leading, trailing and internal whitespace in section and parameter names is irrelevant\&. Leading and trailing whitespace in a parameter value is discarded\&. Internal whitespace within a parameter value is retained verbatim\&.
+.PP
+Any line beginning with a semicolon (\(lq;\(rq) or a hash (\(lq#\(rq) character is ignored, as are lines containing only whitespace\&.
+.PP
+Any line ending in a
+\(lq\e\(rq
+is continued on the next line in the customary UNIX fashion\&.
+.PP
+The values following the equals sign in parameters are all either a string (no quotes needed) or a boolean, which may be given as yes/no, 1/0 or true/false\&. Case is not significant in boolean values, but is preserved in string values\&. Some items such as create masks are numeric\&.
+.PP
+The parameter
+\fBinclude = \fR\fB\fIpath\fR\fR
+allows you to include one config file inside another\&. The file is included literally, as though typed in place\&. Nested includes are not supported\&.
+.SH "SECTION DESCRIPTIONS"
+.PP
+Each section in the configuration file (except for the [Global] section) describes a shared resource (known as a
+\(lqvolume\(rq)\&. The section name is the name of the volume and the parameters within the section define the volume attributes and options\&.
+.PP
+There are two special sections, [Global] and [Homes], which are described under
+\fIspecial sections\fR\&. The following notes apply to ordinary section descriptions\&.
+.PP
+A volume consists of a directory to which access is being given plus a description of the access rights which are granted to the user of the service\&. For volumes the
+\fBpath\fR
+option must specify the directory to share\&.
+.PP
+Any volume section without
+\fBpath\fR
+option is considered a
+\fIvol preset\fR
+which can be selected in other volume sections via the
+\fBvol preset\fR
+option and constitutes defaults for the volume\&. For any option speficied both in a preset
+\fIand\fR
+in a volume section the volume section setting completly substitutes the preset option\&.
+.PP
+The access rights granted by the server are masked by the access rights granted to the specified or guest UNIX user by the host system\&. The server does not grant more access than the host system grants\&.
+.PP
+The following sample section defines an AFP volume\&. The user has full access to the path
+/foo/bar\&. The share is accessed via the share name
+baz:
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+[baz]
+path = /foo/bar
+      
+.fi
+.if n \{\
+.RE
+.\}
+.SH "SPECIAL SECTIONS"
+.SS "The [Global] section"
+.PP
+Parameters in this section apply to the server as a whole\&. Parameters denoted by a (G) below are must be set in this section\&.
+.SS "The [Homes] section"
+.PP
+This section enable sharing of the UNIX server user home directories\&. Specifying an optional
+\fBpath\fR
+parameter means that not the whole user home will be shared but the subdirectory
+\fBpath\fR\&. It is neccessary to define the
+\fBbasedir regex\fR
+option\&. It should be a regex which matches the parent directory of the user homes\&. Parameters denoted by a (H) belong to volume sections\&. The optional parameter
+\fBhome name\fR
+can be used to change the AFP volume name which
+\fI$u\'s home\fR
+by default\&. See below under VARIABLE SUBSTITUTIONS\&.
+.PP
+The following example illustrates this\&. Given all user home directories are stored under
+/home:
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+[Homes]
+path = afp\-data
+basedir regex = /home
+      
+.fi
+.if n \{\
+.RE
+.\}
+.sp
+For a user
+\fIjohn\fR
+this results in an AFP home volume with a path of
+/home/john/afp\-data\&.
+.SH "PARAMETERS"
+.PP
+Parameters define the specific attributes of sections\&.
+.PP
+Some parameters are specific to the [Global] section (e\&.g\&.,
+\fIlog type\fR)\&. All others are permissible only in volume sections\&. The letter
+\fIG\fR
+in parentheses indicates that a parameter is specific to the [Global] section\&. The letter
+\fIV\fR
+indicates that a parameter can be specified in a volume specific section\&.
+.SH "VARIABLE SUBSTITUTIONS"
+.PP
+You can use variables in volume names\&. The use of variables in paths is not supported for now\&.
+.sp
+.RS 4
+.ie n \{\
+\h'-04' 1.\h'+01'\c
+.\}
+.el \{\
+.sp -1
+.IP "  1." 4.2
+.\}
+if you specify an unknown variable, it will not get converted\&.
+.RE
+.sp
+.RS 4
+.ie n \{\
+\h'-04' 2.\h'+01'\c
+.\}
+.el \{\
+.sp -1
+.IP "  2." 4.2
+.\}
+if you specify a known variable, but that variable doesn\'t have a value, it will get ignored\&.
+.RE
+.PP
+The variables which can be used for substitutions are:
+.PP
+$b
+.RS 4
+basename
+.RE
+.PP
+$c
+.RS 4
+client\'s ip address
+.RE
+.PP
+$d
+.RS 4
+volume pathname on server
+.RE
+.PP
+$f
+.RS 4
+full name (contents of the gecos field in the passwd file)
+.RE
+.PP
+$g
+.RS 4
+group name
+.RE
+.PP
+$h
+.RS 4
+hostname
+.RE
+.PP
+$i
+.RS 4
+client\'s ip, without port
+.RE
+.PP
+$s
+.RS 4
+server name (this can be the hostname)
+.RE
+.PP
+$u
+.RS 4
+user name (if guest, it is the user that guest is running as)
+.RE
+.PP
+$v
+.RS 4
+volume name
+.RE
+.PP
+$$
+.RS 4
+prints dollar sign ($)
+.RE
+.SH "EXPLANATION OF GLOBAL PARAMETERS"
+.SS "Authentication Options"
+.PP
+admin auth user = \fIuser\fR \fB(G)\fR
+.RS 4
+Specifying eg "\fBadmin auth user = root\fR" whenever a normal user login fails, afpd will try to authenticate as the specified
+\fBadmin auth user\fR\&. If this succeeds, a normal session is created for the original connecting user\&. Said differently: if you know the password of
+\fBadmin auth user\fR, you can authenticate as any other user\&.
+.RE
+.PP
+k5 keytab = \fIpath\fR \fB(G)\fR, k5 service = \fIservice\fR \fB(G)\fR, k5 realm = \fIrealm\fR \fB(G)\fR
+.RS 4
+These are required if the server supports the Kerberos 5 authentication UAM\&.
+.RE
+.PP
+ldap auth method = \fInone|simple|sasl\fR \fB(G)\fR
+.RS 4
+Authentication method:
+\fBnone | simple | sasl\fR
+.PP
+none
+.RS 4
+anonymous LDAP bind
+.RE
+.PP
+simple
+.RS 4
+simple LDAP bind
+.RE
+.PP
+sasl
+.RS 4
+SASL\&. Not yet supported !
+.RE
+.RE
+.PP
+ldap auth dn = \fIdn\fR \fB(G)\fR
+.RS 4
+Distinguished Name of the user for simple bind\&.
+.sp
+.RE
+.PP
+ldap auth pw = \fIpassword\fR \fB(G)\fR
+.RS 4
+Distinguished Name of the user for simple bind\&.
+.sp
+.RE
+.PP
+ldap server = \fIhost\fR \fB(G)\fR
+.RS 4
+Name or IP address of your LDAP Server\&. This is only needed for explicit ACL support in order to be able to query LDAP for UUIDs\&.
+.sp
+You can use
+\fBafpldaptest\fR(1)
+to syntactically check your config\&.
+.RE
+.PP
+ldap userbase = \fIbase dn\fR \fB(G)\fR
+.RS 4
+DN of the user container in LDAP\&.
+.sp
+.RE
+.PP
+ldap userscope = \fIscope\fR \fB(G)\fR
+.RS 4
+Search scope for user search:
+\fBbase | one | sub\fR
+.sp
+.RE
+.PP
+ldap groupbase = \fIbase dn\fR \fB(G)\fR
+.RS 4
+DN of the group container in LDAP\&.
+.sp
+.RE
+.PP
+ldap groupscope = \fIscope\fR \fB(G)\fR
+.RS 4
+Search scope for user search:
+\fBbase | one | sub\fR
+.sp
+.RE
+.PP
+ldap uuid attr = \fIdn\fR \fB(G)\fR
+.RS 4
+Name of the LDAP attribute with the UUIDs\&.
+.sp
+Note: this is used both for users and groups\&.
+.sp
+.RE
+.PP
+ldap name attr = \fIdn\fR \fB(G)\fR
+.RS 4
+Name of the LDAP attribute with the users short name\&.
+.sp
+.RE
+.PP
+ldap uuid string = \fISTRING\fR \fB(G)\fR
+.RS 4
+Format of the uuid string in the directory\&. A series of x and \-, where every x denotes a value 0\-9a\-f and every \- is a seperator\&.
+.sp
+Default: xxxxxxxx\-xxxx\-xxxx\-xxxx\-xxxxxxxxxxxx
+.RE
+.PP
+ldap group attr = \fIdn\fR \fB(G)\fR
+.RS 4
+Name of the LDAP attribute with the groups short name\&.
+.sp
+.RE
+.PP
+nt domain = \fIDOMAIN\fR \fB(G)\fR, nt separator = \fISEPERATOR\fR \fB(G)\fR
+.RS 4
+Use for eg\&. winbind authentication, prepends both strings before the username from login and then tries to authenticate with the result through the availabel and active UAM authentication modules\&.
+.RE
+.PP
+save password = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(G)\fR
+.RS 4
+Enables or disables the ability of clients to save passwords locally\&.
+.RE
+.PP
+set password = \fIBOOLEAN\fR (default: \fIno\fR) \fB(G)\fR
+.RS 4
+Enables or disables the ability of clients to change their passwords via chooser or the "connect to server" dialog\&.
+.RE
+.PP
+uam list = \fIuam list\fR \fB(G)\fR
+.RS 4
+Space or comma separated list of UAMs\&. (The default is "uams_dhx\&.so uams_dhx2\&.so")\&.
+.sp
+The most commonly used UAMs are:
+.PP
+uams_guest\&.so
+.RS 4
+allows guest logins
+.RE
+.PP
+uams_clrtxt\&.so
+.RS 4
+(uams_pam\&.so or uams_passwd\&.so) Allow logins with passwords transmitted in the clear\&. (legacy)
+.RE
+.PP
+uams_randum\&.so
+.RS 4
+allows Random Number and Two\-Way Random Number Exchange for authentication (requires a separate file containing the passwords, either :ETCDIR:/afppasswd file or the one specified via "\fBpasswd file\fR"\&. See
+\fBafppasswd\fR(1)
+for details\&. (legacy)
+.RE
+.PP
+uams_dhx\&.so
+.RS 4
+(uams_dhx_pam\&.so or uams_dhx_passwd\&.so) Allow Diffie\-Hellman eXchange (DHX) for authentication\&.
+.RE
+.PP
+uams_dhx2\&.so
+.RS 4
+(uams_dhx2_pam\&.so or uams_dhx2_passwd\&.so) Allow Diffie\-Hellman eXchange 2 (DHX2) for authentication\&.
+.RE
+.PP
+uam_gss\&.so
+.RS 4
+Allow Kerberos V for authentication (optional)
+.RE
+.RE
+.PP
+uam path = \fIpath\fR \fB(G)\fR
+.RS 4
+Sets the default path for UAMs for this server (default is :LIBDIR:/netatalk)\&.
+.RE
+.SS "Charset Options"
+.PP
+With OS X Apple introduced the AFP3 protocol\&. One of the big changes was, that AFP3 uses Unicode names encoded as Decomposed UTF\-8 (UTF8\-MAC)\&. Previous AFP/OS versions used charsets like MacRoman, MacCentralEurope, etc\&.
+.PP
+To be able to serve AFP3 and older clients at the same time,
+\fBafpd\fR
+needs to be able to convert between UTF\-8 and Mac charsets\&. Even OS X clients partly still rely on the mac charset\&. As there\'s no way,
+\fBafpd\fR
+can detect the codepage a pre AFP3 client uses, you have to specify it using the
+\fBmac charset\fR
+option\&. The default is MacRoman, which should be fine for most western users\&.
+.PP
+As
+\fBafpd\fR
+needs to interact with UNIX operating system as well, it need\'s to be able to convert from UTF8\-MAC / Mac charset to the UNIX charset\&. By default
+\fBafpd\fR
+uses
+\fIUTF8\fR\&. You can set the UNIX charset using the
+\fBunix charset\fR
+option\&. If you\'re using extended characters in the configuration files for
+\fBafpd\fR, make sure your terminal matches the
+\fBunix charset\fR\&.
+.PP
+mac charset = \fICHARSET\fR \fB(G)/(V)\fR
+.RS 4
+Specifies the Mac clients charset, e\&.g\&.
+\fIMAC_ROMAN\fR\&. This is used to convert strings and filenames to the clients codepage for OS9 and Classic, i\&.e\&. for authentication and AFP messages (SIGUSR2 messaging)\&. This will also be the default for the volumes
+\fBmac charset\fR\&. Defaults to
+\fIMAC_ROMAN\fR\&.
+.RE
+.PP
+unix charset = \fICHARSET\fR \fB(G)\fR
+.RS 4
+Specifies the servers unix charset, e\&.g\&.
+\fIISO\-8859\-15\fR
+or
+\fIEUC\-JP\fR\&. This is used to convert strings to/from the systems locale, e\&.g\&. for authenthication, server messages and volume names\&. If
+\fILOCALE\fR
+is set, the systems locale is used\&. Defaults to
+\fIUTF8\fR\&.
+.RE
+.PP
+vol charset = \fICHARSET\fR \fB(G)/(V)\fR
+.RS 4
+Specifies the encoding of the volumes filesystem\&. By default, it is the same as
+\fBunix charset\fR\&.
+.RE
+.SS "Password Options"
+.PP
+passwd file = \fIpath\fR \fB(G)\fR
+.RS 4
+Sets the path to the Randnum UAM passwd file for this server (default is :ETCDIR:/afppasswd)\&.
+.RE
+.PP
+passwd minlen = \fInumber\fR \fB(G)\fR
+.RS 4
+Sets the minimum password length, if supported by the UAM
+.RE
+.SS "Network Options"
+.PP
+advertise ssh = \fIBOOLEAN\fR (default: \fIno\fR) \fB(G)\fR
+.RS 4
+Allows old Mac OS X clients (10\&.3\&.3\-10\&.4) to automagically establish a tunneled AFP connection through SSH\&. If this option is set, the server\'s answers to client\'s FPGetSrvrInfo requests contain an additional entry\&. It depends on both client\'s settings and a correctly configured and running
+\fBsshd\fR(8)
+on the server to let things work\&.
+.if n \{\
+.sp
+.\}
+.RS 4
+.it 1 an-trap
+.nr an-no-space-flag 1
+.nr an-break-flag 1
+.br
+.ps +1
+\fBNote\fR
+.ps -1
+.br
+Setting this option is not recommended since globally encrypting AFP connections via SSH will increase the server\'s load significantly\&. On the other hand, Apple\'s client side implementation of this feature in MacOS X versions prior to 10\&.3\&.4 contained a security flaw\&.
+.sp .5v
+.RE
+.RE
+.PP
+afp listen = \fIip address[:port] [ip adress[:port] \&.\&.\&.]\fR \fB(G)\fR
+.RS 4
+Specifies the IP address that the server should advertise
+\fBand\fR
+listens to\&. The default is advertise the first IP address of the system, but to listen for any incoming request\&. The network address may be specified either in dotted\-decimal format for IPv4 or in hexadecimal format for IPv6\&.
+.RE
+.PP
+afp port = \fIport number\fR \fB(G)\fR
+.RS 4
+Allows a different TCP port to be used for AFP\&. The default is 548\&. Also sets the default port applied when none specified in an
+\fBafp listen\fR
+option\&.
+.RE
+.PP
+cnid listen = \fIip address[:port] [ip adress[:port] \&.\&.\&.]\fR \fB(G)\fR
+.RS 4
+Specifies the IP address that the CNID server should listen on\&. The default is
+\fBlocalhost:4700\fR\&.
+.RE
+.PP
+disconnect time = \fInumber\fR \fB(G)\fR
+.RS 4
+Keep disconnected AFP sessions for
+\fInumber\fR
+hours before dropping them\&. Default is 24 hours\&.
+.RE
+.PP
+dsireadbuf = \fInumber\fR \fB(G)\fR
+.RS 4
+Scale factor that determines the size of the DSI/TCP readahead buffer, default is 12\&. This is multiplies with the DSI server quantum (default ~300k) to give the size of the buffer\&. Increasing this value might increase throughput in fast local networks for volume to volume copies\&.
+\fINote\fR: This buffer is allocated per afpd child process, so specifying large values will eat up large amount of memory (buffer size * number of clients)\&.
+.RE
+.PP
+fqdn = \fIname:port\fR \fB(G)\fR
+.RS 4
+Specifies a fully\-qualified domain name, with an optional port\&. This is discarded if the server cannot resolve it\&. This option is not honored by AppleShare clients <= 3\&.8\&.3\&. This option is disabled by default\&. Use with caution as this will involve a second name resolution step on the client side\&. Also note that afpd will advertise this name:port combination but not automatically listen to it\&.
+.RE
+.PP
+hostname = \fIname\fR \fB(G)\fR
+.RS 4
+Use this instead of the result from calling hostname for dertermening which IP address to advertise, therfore the hostname is resolved to an IP which is the advertised\&. This is NOT used for listening and it is also overwritten by
+\fBafp listen\fR\&.
+.RE
+.PP
+max connections = \fInumber\fR \fB(G)\fR
+.RS 4
+Sets the maximum number of clients that can simultaneously connect to the server (default is 200)\&.
+.RE
+.PP
+server quantum = \fInumber\fR \fB(G)\fR
+.RS 4
+This specifies the DSI server quantum\&. The default value is 303840\&. The maximum value is 0xFFFFFFFFF, the minimum is 32000\&. If you specify a value that is out of range, the default value will be set\&. Do not change this value unless you\'re absolutely sure, what you\'re doing
+.RE
+.PP
+sleep time = \fInumber\fR \fB(G)\fR
+.RS 4
+Keep sleeping AFP sessions for
+\fInumber\fR
+hours before disconnecting clients in sleep mode\&. Default is 10 hours\&.
+.RE
+.PP
+tcprcvbuf = \fInumber\fR \fB(G)\fR
+.RS 4
+Try to set TCP receive buffer using setsockpt()\&. Often OSes impose restrictions on the applications ability to set this value\&.
+.RE
+.PP
+tcpsndbuf = \fInumber\fR \fB(G)\fR
+.RS 4
+Try to set TCP send buffer using setsockpt()\&. Often OSes impose restrictions on the applications ability to set this value\&.
+.RE
+.PP
+use sendfile = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(G)\fR
+.RS 4
+Whether to use sendfile
+syscall for sending file data to clients\&.
+.RE
+.PP
+zeroconf = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(G)\fR
+.RS 4
+Whether to use automatic Zeroconf
+service registration if Avahi or mDNSResponder were compiled in\&.
+.RE
+.SS "Miscellaneous Options"
+.PP
+admin group = \fIgroup\fR \fB(G)\fR
+.RS 4
+Allows users of a certain group to be seen as the superuser when they log in\&. This option is disabled by default\&.
+.RE
+.PP
+afp read locks = \fIBOOLEAN\fR (default: \fIno\fR) \fB(G)\fR
+.RS 4
+Whether to apply locks to the byte region read in FPRead calls\&. The AFP spec mandates this, but it\'s not really in line with UNIX semantics and is a performance hug\&.
+.RE
+.PP
+basedir regex = \fIregex\fR \fB(H)\fR
+.RS 4
+Regular expression which matches the parent directory of the user homes\&. In the simple case this is just a path ie
+\fBbasedir regex = /home\fR
+.RE
+.PP
+close vol = \fIBOOLEAN\fR (default: \fIno\fR) \fB(G)\fR
+.RS 4
+Whether to close volumes possibly opened by clients when they\'re removed from the configuration and the configuration is reloaded\&.
+.RE
+.PP
+cnid server = \fIipaddress[:port]\fR \fB(G)/(V)\fR
+.RS 4
+Specifies the IP address and port of a cnid_metad server, required for CNID dbd backend\&. Defaults to localhost:4700\&. The network address may be specified either in dotted\-decimal format for IPv4 or in hexadecimal format for IPv6\&.\-
+.RE
+.PP
+dircachesize = \fInumber\fR \fB(G)\fR
+.RS 4
+Maximum possible entries in the directory cache\&. The cache stores directories and files\&. It is used to cache the full path to directories and CNIDs which considerably speeds up directory enumeration\&.
+.sp
+Default size is 8192, maximum size is 131072\&. Given value is rounded up to nearest power of 2\&. Each entry takes about 100 bytes, which is not much, but remember that every afpd child process for every connected user has its cache\&.
+.RE
+.PP
+fce listener = \fIhost[:port]\fR \fB(G)\fR
+.RS 4
+Enables sending FCE events to the specified
+\fIhost\fR, default
+\fIport\fR
+is 12250 if not specified\&. Specifying mutliple listeners is done by having this option once for each of them\&.
+.RE
+.PP
+fce events = \fIfmod,fdel,ddel,fcre,dcre,tmsz\fR \fB(G)\fR
+.RS 4
+Speficies which FCE events are active, default is
+\fIfmod,fdel,ddel,fcre,dcre\fR\&.
+.RE
+.PP
+fce coalesce = \fIall|delete|create\fR \fB(G)\fR
+.RS 4
+Coalesce FCE events\&.
+.RE
+.PP
+fce holdfmod = \fIseconds\fR \fB(G)\fR
+.RS 4
+This determines the time delay in seconds which is always waited if another file modification for the same file is done by a client before sending an FCE file modification event (fmod)\&. For example saving a file in Photoshop would generate multiple events by itself because the application is opening, modifying and closing a file mutliple times for every "save"\&. Defautl: 60 seconds\&.
+.RE
+.PP
+guest account = \fIname\fR \fB(G)\fR
+.RS 4
+Specifies the user that guests should use (default is "nobody")\&. The name should be quoted\&.
+.RE
+.PP
+home name = \fIname\fR \fB(H)\fR
+.RS 4
+AFP user home volume name\&. The default is
+\fIusers\'s home\fR\&.
+.RE
+.PP
+icon = \fIBOOLEAN\fR (default: \fIno\fR) \fB(G)\fR
+.RS 4
+Use the platform\-specific icon\&. Mac OS X doesn\'t display it\&.
+.RE
+.PP
+keep sessions = \fIBOOLEAN\fR (default: \fIno\fR) \fB(G)\fR
+.RS 4
+Enable "Continuous AFP Service"\&. This means restarting AFP and CNID service daemons master processes, but keeping the AFP session processes\&. This can be used to install (most) updates to Netatalk without interruping active AFP sessions\&. Existing AFP sessions will still run the version from before updating, but new AFP sessions will run the updated code\&. After enabling this option when sending SIGQUIT to the
+\fInetatalk\fR
+service controller process, the AFP and CNID daemons will exit and then the service controller will restart them\&. AFP session processes are notified of the master afpd shutdown, they will then sleep 15\-20 seconds and then try to reconnect their IPC channel to the master afpd process\&. The IPC channel between the AFP master service daemon and the AFP session child is used for keeping session state of AFP sessions in the AFP master process\&. The session state is needed when AFP clients experience eg network outages and try to reconnect to the AFP server\&.
+.RE
+.PP
+login message = \fImessage\fR \fB(G)/(V)\fR
+.RS 4
+Sets a message to be displayed when clients logon to the server\&. The message should be in
+\fBunix charset\fR
+and should be quoted\&. Extended characters are allowed\&.
+.RE
+.PP
+map acls = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(G)\fR
+.RS 4
+Whether to map filesystem ACLs to effective permissions\&.
+.RE
+.PP
+mimic model = \fImodel\fR \fB(G)\fR
+.RS 4
+Specifies the icon model that appears on clients\&. Defaults to off\&. Examples: RackMac (same as Xserve), PowerBook, PowerMac, Macmini, iMac, MacBook, MacBookPro, MacBookAir, MacPro, AppleTV1,1, AirPort\&.
+.RE
+.PP
+signature = <text> \fB(G)\fR
+.RS 4
+Specify a server signature\&. The maximum length is 16 characters\&. This option is useful for clustered environments, to provide fault isolation etc\&. By default, afpd generate signature and saving it to
+:STATEDIR:/netatalk/afp_signature\&.conf
+automatically (based on random number)\&. See also asip\-status\&.pl(1)\&.
+.RE
+.PP
+solaris share reservations = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(G)\fR
+.RS 4
+Use share reservations on Solaris\&. Solaris CIFS server uses this too, so this makes a lock coherent multi protocol server\&.
+.RE
+.PP
+vol dbpath = \fIpath\fR \fB(G)\fR
+.RS 4
+Sets the database information to be stored in path\&. You have to specifiy a writable location, even if the volume is read only\&. The default is
+:STATEDIR:/netatalk/CNID/\&.
+.RE
+.PP
+volnamelen = \fInumber\fR \fB(G)\fR
+.RS 4
+Max length of UTF8\-MAC volume name for Mac OS X\&. Note that Hangul is especially sensitive to this\&.
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+73:  limit of Mac OS X 10\&.1
+80:  limit of Mac OS X 10\&.4/10\&.5 (default)
+255: limit of recent Mac OS X
+.fi
+.if n \{\
+.RE
+.\}
+.sp
+Mac OS 9 and earlier are not influenced by this, because Maccharset volume name is always limitted to 27 bytes\&.
+.RE
+.PP
+vol preset = \fIname\fR \fB(G)/(V)\fR
+.RS 4
+Use section
+\fBname\fR
+as option preset for all volumes (when set in the [Global] section) or for one volume (when set in that volume\'s section)\&.
+.RE
+.SS "Logging Options"
+.PP
+log file = \fIlogfile\fR \fB(G)\fR
+.RS 4
+If not specified Netatalk logs to syslogs daemon facilify\&. Otherwise it logs to
+\fBlogfile\fR\&.
+.RE
+.PP
+log level = \fItype:level [type:level \&.\&.\&.]\fR \fB(G)\fR, log level = \fItype:level,[type:level, \&.\&.\&.]\fR \fB(G)\fR
+.RS 4
+Specify that any message of a loglevel up to the given
+\fBlog level\fR
+should be logged\&.
+.sp
+By default afpd logs to syslog with a default logging setup equivalent to
+\fBdefault:note\fR
+.sp
+logtypes: default, afpdaemon, logger, uamsdaemon
+.sp
+loglevels: severe, error, warn, note, info, debug, debug6, debug7, debug8, debug9, maxdebug
+.if n \{\
+.sp
+.\}
+.RS 4
+.it 1 an-trap
+.nr an-no-space-flag 1
+.nr an-break-flag 1
+.br
+.ps +1
+\fBNote\fR
+.ps -1
+.br
+Both logtype and loglevels are case insensitive\&.
+.sp .5v
+.RE
+.RE
+.SS "Debug Parameters"
+.PP
+These options are useful for debugging only\&.
+.PP
+tickleval = \fInumber\fR \fB(G)\fR
+.RS 4
+Sets the tickle timeout interval (in seconds)\&. Defaults to 30\&.
+.RE
+.PP
+timeout = \fInumber\fR \fB(G)\fR
+.RS 4
+Specify the number of tickles to send before timing out a connection\&. The default is 4, therefore a connection will timeout after 2 minutes\&.
+.RE
+.PP
+client polling = \fIBOOLEAN\fR (default: \fIno\fR) \fB(G)\fR
+.RS 4
+With this option enabled, afpd won\'t advertise that it is capable of server notifications, so that connected clients poll the server every 10 seconds to detect changes in opened server windows\&.
+\fINote\fR: Depending on the number of simultaneously connected clients and the network\'s speed, this can lead to a significant higher load on your network!
+.sp
+Do not use this option any longer as present Netatalk correctly supports server notifications, allowing connected clients to update folder listings in case another client changed the contents\&.
+.RE
+.SH "EXPLANATION OF VOLUME PARAMETERS"
+.SS "Parameters"
+.PP
+The section name defines the volume name which is the name that appears in the Chooser or the "connect to server" dialog on Macintoshes to represent the appropriate share\&. No two volumes may have the same name\&. The volume name cannot contain the
+\':\'
+character\&. The volume name is mangled if it is very long\&. Mac charset volume name is limited to 27 characters\&. UTF8\-MAC volume name is limited to volnamelen parameter\&.
+.PP
+path = \fIPATH\fR \fB(V)\fR
+.RS 4
+The path name must be a fully qualified path name, or a path name using either the ~ shell shorthand or any of the substitution variables, which are listed below\&.
+.sp
+The volume name is the name that appears in the Chooser ot the "connect to server" dialog on Macintoshes to represent the appropriate share\&. If volumename is unspecified, the last component of pathname is used\&. No two volumes may have the same name\&. If there are spaces in the name, it should be in quotes (i\&.e\&. "File Share")\&. The volume name cannot contain the
+\':\'
+character\&. The volume name is mangled if it is very long\&. Mac charset volume name is limited to 27 characters\&. UTF8\-MAC volume name is limited to volnamelen parameter\&.
+.RE
+.PP
+appledouble = \fIea|v2\fR \fB(V)\fR
+.RS 4
+Specify the format of the metadata files, which are used for saving Mac resource fork as well\&. Earlier versions used AppleDouble v2, the new default format is
+\fBea\fR\&.
+.RE
+.PP
+vol size limit = \fIsize in MiB\fR \fB(V)\fR
+.RS 4
+Useful for Time Machine: limits the reported volume size, thus preventing Time Machine from using the whole real disk space for backup\&. Example: "vol size limit = 1000" would limit the reported disk space to 1 GB\&.
+\fBIMPORTANT: \fR
+This is an approimated calculation taking into accout the contents of Time Machine sparsebundle images\&. Therefor you MUST NOT use this volume to store other content when using this option, because it would NOT be accounted\&. The calculation works by reading the band size from the Info\&.plist XML file of the sparsebundle, reading the bands/ directory counting the number of band files, and then multiplying one with the other\&.
+.RE
+.PP
+valid users = \fIusers/groups\fR \fB(V)\fR
+.RS 4
+The allow option allows the users and groups that access a share to be specified\&. Users and groups are specified, delimited by spaces or commas\&. Groups are designated by a @ prefix\&. Example: "valid users = user1 user2 @group"
+.RE
+.PP
+invalid users = \fIusers/groups\fR \fB(V)\fR
+.RS 4
+The deny option specifies users and groups who are not allowed access to the share\&. It follows the same format as the "valid users" option\&.
+.RE
+.PP
+hosts allow = \fIIP host address/IP netmask bits [ \&.\&.\&. ]\fR \fB(V)\fR
+.RS 4
+Only listed hosts and networks are allowed, all others are rejected\&. The network address may be specified either in dotted\-decimal format for IPv4 or in hexadecimal format for IPv6\&.
+.sp
+Example: hosts allow = 10\&.1\&.0\&.0/16 10\&.2\&.1\&.100 2001:0db8:1234::/48
+.RE
+.PP
+hosts deny = \fIIP host address/IP netmask bits [ \&.\&.\&. ]\fR \fB(V)\fR
+.RS 4
+Listed hosts and nets are rejected, all others are allowed\&.
+.sp
+Example: hosts deny = 192\&.168\&.100/24 10\&.1\&.1\&.1 2001:db8::1428:57ab
+.RE
+.PP
+cnid scheme = \fIbackend\fR \fB(V)\fR
+.RS 4
+set the CNID backend to be used for the volume, default is [:DEFAULT_CNID_SCHEME:] available schemes: [:COMPILED_BACKENDS:]
+.RE
+.PP
+ea = \fInone|auto|sys|ad\fR
+.RS 4
+Specify how Extended Attributes
+are stored\&.
+\fBauto\fR
+is the default\&.
+.PP
+auto
+.RS 4
+Try
+\fBsys\fR
+(by setting an EA on the shared directory itself), fallback to
+\fBad\fR\&. Requires writeable volume for perfoming test\&. "\fBread only = yes\fR" overwrites
+\fBauto\fR
+with
+\fBnone\fR\&. Use explicit "\fBea = sys|ad\fR" for read\-only volumes where appropiate\&.
+.RE
+.PP
+sys
+.RS 4
+Use filesystem Extended Attributes\&.
+.RE
+.PP
+ad
+.RS 4
+Use files in
+\fI\&.AppleDouble\fR
+directories\&.
+.RE
+.PP
+none
+.RS 4
+No Extended Attributes support\&.
+.RE
+.RE
+.PP
+mac charset = \fICHARSET\fR \fB(V)\fR
+.RS 4
+specifies the Mac client charset for this Volume, e\&.g\&.
+\fIMAC_ROMAN\fR,
+\fIMAC_CYRILLIC\fR\&. If not specified the global setting is applied\&. This setting is only required if you need volumes, where the Mac charset differs from the one globally set in the [Global] section\&.
+.RE
+.PP
+casefold = \fBoption\fR
+.RS 4
+The casefold option handles, if the case of filenames should be changed\&. The available options are:
+.sp
+\fBtolower\fR
+\- Lowercases names in both directions\&.
+.sp
+\fBtoupper\fR
+\- Uppercases names in both directions\&.
+.sp
+\fBxlatelower\fR
+\- Client sees lowercase, server sees uppercase\&.
+.sp
+\fBxlateupper\fR
+\- Client sees uppercase, server sees lowercase\&.
+.RE
+.PP
+password = \fIpassword\fR \fB(V)\fR
+.RS 4
+This option allows you to set a volume password, which can be a maximum of 8 characters long (using ASCII strongly recommended at the time of this writing)\&.
+.RE
+.PP
+file perm = \fImode\fR \fB(V)\fR, directory perm = \fImode\fR \fB(V)\fR
+.RS 4
+Add(or) with the client requested permissions:
+\fBfile perm\fR
+is for files only,
+\fBdirectory perm\fR
+is for directories only\&. Don\'t use with "\fBunix priv = no\fR"\&.
+.PP
+\fBExample.\ \&Volume for a collaborative workgroup\fR
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+file perm = 0660
+directory perm = 0770
+.fi
+.if n \{\
+.RE
+.\}
+
+.RE
+.PP
+umask = \fImode\fR \fB(V)\fR
+.RS 4
+set perm mask\&. Don\'t use with "\fBunix priv = no\fR"\&.
+.RE
+.PP
+preexec = \fIcommand\fR \fB(V)\fR
+.RS 4
+command to be run when the volume is mounted, ignored for user defined volumes
+.RE
+.PP
+postexec = \fIcommand\fR \fB(V)\fR
+.RS 4
+command to be run when the volume is closed, ignored for user defined volumes
+.RE
+.PP
+root preexec = \fIcommand\fR \fB(V)\fR
+.RS 4
+command to be run as root when the volume is mounted, ignored for user defined volumes
+.RE
+.PP
+root postexec = \fIcommand\fR \fB(V)\fR
+.RS 4
+command to be run as root when the volume is closed, ignored for user defined volumes
+.RE
+.PP
+rolist = \fBusers/groups\fR \fB(V)\fR
+.RS 4
+Allows certain users and groups to have read\-only access to a share\&. This follows the allow option format\&.
+.RE
+.PP
+rwlist = \fIusers/groups\fR \fB(V)\fR
+.RS 4
+Allows certain users and groups to have read/write access to a share\&. This follows the allow option format\&.
+.RE
+.PP
+veto files = \fIvetoed names\fR \fB(V)\fR
+.RS 4
+hide files and directories,where the path matches one of the \'/\' delimited vetoed names\&. The veto string must always be terminated with a \'/\', eg\&. "veto1/", "veto1/veto2/"\&.
+.RE
+.SS "Volume options"
+.PP
+Boolean volume options\&.
+.PP
+acls = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(V)\fR
+.RS 4
+Whether to flag volumes as supporting ACLs\&. If ACL support is compiled in, this is yes by default\&.
+.RE
+.PP
+cnid dev = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(V)\fR
+.RS 4
+Whether to use the device number in the CNID backends\&. Helps when the device number is not constant across a reboot, eg cluster, \&.\&.\&.
+.RE
+.PP
+convert appledouble = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(V)\fR
+.RS 4
+Whether automatic conversion from
+\fBappledouble = v2\fR
+to
+\fBappledouble = ea\fR
+is performed when accessing filesystems from clients\&. This is generally useful, but costs some performance\&. It\'s recommdable to run
+\fBdbd\fR
+on volumes and do the conversion with that\&. Then this option can be set to no\&.
+.RE
+.PP
+invisible dots = \fIBOOLEAN\fR (default: \fIno\fR) \fB(V)\fR
+.RS 4
+make dot files invisible\&.
+.RE
+.PP
+network ids = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(V)\fR
+.RS 4
+Whether the server support network ids\&. Setting this to
+\fIno\fR
+will result in the client not using ACL AFP functions\&.
+.RE
+.PP
+preexec close = \fIBOOLEAN\fR (default: \fIno\fR) \fB(V)\fR
+.RS 4
+A non\-zero return code from preexec close the volume being immediately, preventing clients to mount/see the volume in question\&.
+.RE
+.PP
+read only = \fIBOOLEAN\fR (default: \fIno\fR) \fB(V)\fR
+.RS 4
+Specifies the share as being read only for all users\&. Overwrites
+\fBea = auto\fR
+with
+\fBea = none\fR
+.RE
+.PP
+root preexec close= \fIBOOLEAN\fR (default: \fIno\fR) \fB(V)\fR
+.RS 4
+A non\-zero return code from root_preexec closes the volume immediately, preventing clients to mount/see the volume in question\&.
+.RE
+.PP
+search db = \fIBOOLEAN\fR (default: \fIno\fR) \fB(V)\fR
+.RS 4
+Use fast CNID database namesearch instead of slow recursive filesystem search\&. Relies on a consistent CNID database, ie Samba or local filesystem access lead to inaccurate or wrong results\&. Works only for "dbd" CNID db volumes\&.
+.RE
+.PP
+stat vol = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(V)\fR
+.RS 4
+Whether to stat volume path when enumerating volumes list, useful for automounting or volumes created by a preexec script\&.
+.RE
+.PP
+time machine = \fIBOOLEAN\fR (default: \fIno\fR) \fB(V)\fR
+.RS 4
+Whether to enable Time Machine suport for this volume\&.
+.RE
+.PP
+unix priv = \fIBOOLEAN\fR (default: \fIyes\fR) \fB(V)\fR
+.RS 4
+Whether to use AFP3 UNIX privileges\&. This should be set for OS X clients\&. See also:
+\fBfile perm\fR,
+\fBdirectory perm\fR
+and
+\fBumask\fR\&.
+.RE
+.SH "CNID BACKENDS"
+.PP
+The AFP protocol mostly refers to files and directories by ID and not by name\&. Netatalk needs a way to store these ID\'s in a persistent way, to achieve this several different CNID backends are available\&. The CNID Databases are by default located in the
+\&.AppleDB
+folder in the volume root\&.
+.PP
+cdb
+.RS 4
+"Concurrent database", backend is based on Oracle Berkely DB\&. With this backend several
+\fBafpd\fR
+deamons access the CNID database directly\&. Berkeley DB locking is used to synchronize access, if more than one
+\fBafpd\fR
+process is active for a volume\&. The drawback is, that the crash of a single
+\fBafpd\fR
+process might corrupt the database\&.
+.RE
+.PP
+dbd
+.RS 4
+Access to the CNID database is restricted to the
+\fBcnid_metad\fR
+daemon process\&.
+\fBafpd\fR
+processes communicate with the daemon for database reads and updates\&. If built with Berkeley DB transactions the probability for database corruption is practically zero, but performance can be slower than with
+\fBcdb\fR
+.RE
+.PP
+last
+.RS 4
+This backend is an exception, in terms of ID persistency\&. ID\'s are only valid for the current session\&. This is basically what
+\fBafpd\fR
+did in the 1\&.5 (and 1\&.6) versions\&. This backend is still available, as it is useful for e\&.g\&. sharing cdroms\&.
+.sp
+\fBWarning\fR: It is
+\fINOT\fR
+recommended to use this backend for volumes anymore, as
+\fBafpd\fR
+now relies heavily on a persistent ID database\&. Aliases will likely not work and filename mangling is not supported\&.
+.RE
+.PP
+Even though
+\fB\&./configure \-\-help\fR
+might show that there are other CNID backends available, be warned those are likely broken or mainly used for testing\&. Don\'t use them unless you know what you\'re doing, they may be removed without further notice from future versions\&.
+.SH "CHARSET OPTIONS"
+.PP
+With OS X Apple introduced the AFP3 protocol\&. One of the most important changes was that AFP3 uses unicode names encoded as UTF\-8 decomposed\&. Previous AFP/OS versions used codepages, like MacRoman, MacCentralEurope, etc\&.
+.PP
+\fBafpd\fR
+needs a way to preserve extended macintosh characters, or characters illegal in unix filenames, when saving files on a unix filesystem\&. Earlier versions used the the so called CAP encoding\&. An extended character (>0x7F) would be converted to a :xx sequence, e\&.g\&. the Apple Logo (MacRoman: 0xF0) was saved as
+:f0\&. Some special characters will be converted as to :xx notation as well\&. \'/\' will be encoded to
+:2f, if
+\fBusedots\fR
+is not specified, a leading dot \'\&.\' will be encoded as
+:2e\&.
+.PP
+This version now uses UTF\-8 as the default encoding for names\&. \'/\' will be converted to \':\'\&.
+.PP
+The
+\fBvol charset\fR
+option will allow you to select another volume encoding\&. E\&.g\&. for western users another useful setting could be vol charset ISO\-8859\-15\&.
+\fBafpd\fR
+will accept any
+\fBiconv\fR(1)
+provided charset\&. If a character cannot be converted from the
+\fBmac charset\fR
+to the selected
+\fBvol charset\fR, afpd will save it as a CAP encoded character\&. For AFP3 clients,
+\fBafpd\fR
+will convert the UTF\-8
+character to
+\fBmac charset\fR
+first\&. If this conversion fails, you\'ll receive a \-50 error on the mac\&.
+.PP
+\fINote\fR: Whenever you can, please stick with the default UTF\-8 volume format\&.
+.SH "SEE ALSO"
+.PP
+\fBafpd\fR(8),
+\fBafppasswd\fR(5),
+\fBafp_signature.conf\fR(5),
+\fBcnid_metad\fR(8)
diff --git a/man/man5/afp_ldap.conf.5.tmpl b/man/man5/afp_ldap.conf.5.tmpl
deleted file mode 100644 (file)
index 8ad1302..0000000
+++ /dev/null
@@ -1,164 +0,0 @@
-'\" t
-.\"     Title: afp_ldap.conf
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 30 Mar 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "AFP_LDAP\&.CONF" "5" "30 Mar 2011" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-afp_ldap.conf \- Configuration file used by afpd(8) to configure a LDAP connection to an LDAP server\&. That is needed for ACL support in order to be able to query LDAP for UUIDs\&.
-.SH "DESCRIPTION"
-.PP
-:ETCDIR:/afp_ldap\&.conf
-is the configuration file used by
-\fBafpd\fR
-to set up an LDAP connection to an LDAP server\&.
-.PP
-Any line not prefixed with # is interpreted\&.
-.PP
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-.PP
-You can use
-\fBafpldaptest\fR(1)
-to syntactically check your config
-.sp .5v
-.RE
-The required parameters and their meanings are:
-.SH "PARAMETER"
-.PP
-ldap_server
-.RS 4
-Name or IP address of your LDAP Server
-.sp
-.RE
-.PP
-ldap_auth_method
-.RS 4
-Authentication method:
-\fBnone | simple | sasl\fR
-.PP
-none
-.RS 4
-anonymous LDAP bind
-.RE
-.PP
-simple
-.RS 4
-simple LDAP bind
-.RE
-.PP
-sasl
-.RS 4
-SASL\&. Not yet supported !
-.RE
-.RE
-.PP
-ldap_auth_dn
-.RS 4
-Distinguished Name of the user for simple bind\&.
-.sp
-.RE
-.PP
-ldap_auth_pw
-.RS 4
-Distinguished Name of the user for simple bind\&.
-.sp
-.RE
-.PP
-ldap_userbase
-.RS 4
-DN of the user container in LDAP\&.
-.sp
-.RE
-.PP
-ldap_userscope
-.RS 4
-Search scope for user search:
-\fBbase | one | sub\fR
-.sp
-.RE
-.PP
-ldap_groupbase
-.RS 4
-DN of the group container in LDAP\&.
-.sp
-.RE
-.PP
-ldap_groupscope
-.RS 4
-Search scope for user search:
-\fBbase | one |\ \&sub\fR
-.sp
-.RE
-.PP
-ldap_uuuid_attr
-.RS 4
-Name of the LDAP attribute with the UUIDs\&.
-.sp
-Note: this is used both for users and groups\&.
-.sp
-.RE
-.PP
-ldap_name_attr
-.RS 4
-Name of the LDAP attribute with the users short name\&.
-.sp
-.RE
-.PP
-ldap_group_attr
-.RS 4
-Name of the LDAP attribute with the groups short name\&.
-.sp
-.RE
-.SH "EXAMPLES"
-.PP
-\fBExample.\ \&afp_ldap.conf setup with simple bind\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-ldap_server      = localhost
-ldap_auth_method = simple
-ldap_auth_dn     = cn=admin,dc=domain,dc=org
-ldap_auth_pw     = notthisone
-ldap_userbase    = ou=users,dc=domain,dc=org
-ldap_userscope   = one
-ldap_groupbase   = ou=groups,dc=domain,dc=org
-ldap_groupscope  = one
-ldap_uuid_attr   = some_attribute
-ldap_name_attr   = cn
-ldap_group_attr  = cn
-.fi
-.if n \{\
-.RE
-.\}
-.SH "SEE ALSO"
-.PP
-\fBafpd\fR(8),
-\fBAppleVolumes.default\fR(5),
-\fBafpldaptest\fR(1)
index 592b8fbb0171c2e3b54057a85ff37e5d3168a44f..54e2267f557704e45023ac46971aa70c25d20611 100644 (file)
@@ -2,12 +2,12 @@
 .\"     Title: afp_signature.conf
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 08 Mar 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"      Date: 23 Mar 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "AFP_SIGNATURE\&.CONF" "5" "08 Mar 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "AFP_SIGNATURE\&.CONF" "5" "23 Mar 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
@@ -22,7 +22,7 @@
 afp_signature.conf \- Configuration file used by afpd(8) to specify server signature
 .SH "DESCRIPTION"
 .PP
-:ETCDIR:/afp_signature\&.conf
+:STATEDIR:/netatalk/afp_signature\&.conf
 is the configuration file used by
 \fBafpd\fR
 to specify server signature automagically\&. The configuration lines are composed like:
@@ -52,22 +52,20 @@ Netatalk 2\&.0 and earlier generated server signature by using gethostid()\&. Th
 .PP
 Current netatalk generates the signature from random numbers and saves it into afp_signature\&.conf\&. When starting next time, it is read from this file\&.
 .PP
-This file should not be thoughtlessly edited and be copied onto another server\&. If it wants to set the signature intentionally, use the option "\-signature user:xxxx" in afpd\&.conf\&. In this case, afp_signature\&.conf is not used\&.
+This file should not be thoughtlessly edited and be copied onto another server\&. If it wants to set the signature intentionally, use the option "signature =" in afp\&.conf\&. In this case, afp_signature\&.conf is not used\&.
 .sp .5v
 .RE
 .PP
 .SH "EXAMPLES"
 .PP
-\fBExample.\ \&afp_signature.conf three servers on one netatalk\fR
+\fBExample.\ \&afp_signature.conf\fR
 .sp
 .if n \{\
 .RS 4
 .\}
 .nf
 # This is a comment\&.
-"Guest Server" 251D25569CB29AFDF296C6B5B3A385B7
-"User Server" 26B5D785046C019F55718F76B1C13BFB
-special 74A0BB94EC8C13988B2E75042347E528
+"My Server" 74A0BB94EC8C13988B2E75042347E528
 .fi
 .if n \{\
 .RE
@@ -75,5 +73,5 @@ special 74A0BB94EC8C13988B2E75042347E528
 .SH "SEE ALSO"
 .PP
 \fBafpd\fR(8),
-\fBafpd.conf\fR(5),
+\fBafp.conf\fR(5),
 \fBasip-status.pl\fR(1)
index c36a1124a38401388d941742ea03c2fc590c1b4f..8d3626d04c17b3712a534a3ae48270e87ad2793b 100644 (file)
@@ -2,12 +2,12 @@
 .\"     Title: afp_voluuid.conf
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 8 March 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"      Date: 23 Mar 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "AFP_VOLUUID\&.CONF" "5" "8 March 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "AFP_VOLUUID\&.CONF" "5" "23 Mar 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
@@ -22,7 +22,7 @@
 afp_voluuid.conf \- Configuration file used by afpd(8) to specify UUID for Time Machine volume
 .SH "DESCRIPTION"
 .PP
-:ETCDIR:/afp_voluuid\&.conf
+:STATEDIR:/netatalk/afp_voluuid\&.conf
 is the configuration file used by
 \fBafpd\fR
 to specify UUID of Time Machine volume automagically\&. The configuration lines are composed like:
@@ -48,7 +48,7 @@ The leading spaces and tabs are ignored\&. Blank lines are ignored\&. The lines
 .PP
 This UUID is advertised by Zeroconf in order to provide robust disambiguation of Time Machine volume\&.
 .PP
-The afpd generates the UUID from random numbers and saves it into afp_voluuid\&.conf, only when setting "tm" option in AppleVolumes file\&.
+The afpd generates the UUID from random numbers and saves it into afp_voluuid\&.conf, only when setting "time machine = yes" option in afp\&.conf\&.
 .PP
 This file should not be thoughtlessly edited and be copied onto another server\&.
 .sp .5v
@@ -73,5 +73,6 @@ mary 6331E2D1\-446C\-B68C\-3066\-D685AADBE911
 .SH "SEE ALSO"
 .PP
 \fBafpd\fR(8),
-\fBAppleVolumes.default\fR(5),
-\fBavahi-daemon\fR(8)
+\fBafp.conf\fR(5),
+\fBavahi-daemon\fR(8),
+\fBmDNSResponder\fR(8)
diff --git a/man/man5/afpd.conf.5.tmpl b/man/man5/afpd.conf.5.tmpl
deleted file mode 100644 (file)
index c6d0288..0000000
+++ /dev/null
@@ -1,676 +0,0 @@
-'\" t
-.\"     Title: afpd.conf
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 15 Aug 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "AFPD\&.CONF" "5" "15 Aug 2011" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-afpd.conf \- Configuration file used by afpd(8) to determine the setup of its file sharing services
-.SH "DESCRIPTION"
-.PP
-:ETCDIR:/afpd\&.conf
-is the configuration file used by
-\fBafpd\fR
-to determine the behavior and configuration of the different virtual file servers that it provides\&.
-.PP
-Any line not prefixed with # is interpreted\&. The configuration lines are composed like: server name [ options ] If a
-\fB\-\fR
-is used instead of a server name, the default server is specified\&. Server names must be quoted if they contain spaces\&. They must not contain ":" or "@"\&. The path name must be a fully qualified path name, or a path name using either the ~ shell shorthand or any of the substitution variables, which are listed below\&.
-.PP
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-.PP
-Each server has to be configured on a
-\fBsingle\fR
-line\&. Though, using "\e" character, newline escaping is supported\&.
-.sp .5v
-.RE
-The possible options and their meanings are:
-.SH "APPLEVOLUMES FILES"
-.PP
-\-defaultvol \fI[path]\fR
-.RS 4
-Specifies path to AppleVolumes\&.default file (default is
-:ETCDIR:/AppleVolumes\&.default)\&.
-.RE
-.PP
-\-systemvol \fI[path]\fR
-.RS 4
-Specifies path to AppleVolumes\&.system file (default is
-:ETCDIR:/AppleVolumes\&.system)\&.
-.RE
-.PP
-\-[no]uservol
-.RS 4
-Enables or disables reading of the users\' individual volumes file entirely\&.
-.RE
-.PP
-\-[no]uservolfirst
-.RS 4
-Enables or disables reading of the users\' individual volumes file before processing the global
-AppleVolumes\&.default
-file\&.
-.RE
-.SH "AUTHENTICATION METHODS"
-.PP
-\-uamlist \fI[uams list]\fR
-.RS 4
-Comma separated list of UAMs\&. (The default is uams_dhx\&.so,uams_dhx2\&.so)\&.
-.sp
-The most commonly used UAMs are:
-.PP
-uams_guest\&.so
-.RS 4
-allows guest logins
-.RE
-.PP
-uams_clrtxt\&.so
-.RS 4
-(uams_pam\&.so or uams_passwd\&.so) Allow logins with passwords transmitted in the clear\&. (legacy)
-.RE
-.PP
-uams_randum\&.so
-.RS 4
-allows Random Number and Two\-Way Random Number Exchange for authentication (requires a separate file containing the passwords, either :ETCDIR:/afppasswd file or the one specified via
-\fB\-passwdfile\fR\&. See
-\fBafppasswd\fR(1)
-for details\&. (legacy)
-.RE
-.PP
-uams_dhx\&.so
-.RS 4
-(uams_dhx_pam\&.so or uams_dhx_passwd\&.so) Allow Diffie\-Hellman eXchange (DHX) for authentication\&.
-.RE
-.PP
-uams_dhx2\&.so
-.RS 4
-(uams_dhx2_pam\&.so or uams_dhx2_passwd\&.so) Allow Diffie\-Hellman eXchange 2 (DHX2) for authentication\&.
-.RE
-.PP
-uam_gss\&.so
-.RS 4
-Allow Kerberos V for authentication (optional)
-.RE
-.RE
-.PP
-\-uampath \fI[path]\fR
-.RS 4
-Sets the default path for UAMs for this server (default is :ETCDIR:/uams)\&.
-.RE
-.PP
-\-k5keytab \fI[path]\fR, \-k5service \fI[service]\fR, \-k5realm \fI[realm]\fR
-.RS 4
-These are required if the server supports the Kerberos 5 authentication UAM\&.
-.RE
-.PP
-\-ntdomain, \-ntseparator
-.RS 4
-Use for eg\&. winbind authentication, prepends both strings before the username from login and then tries to authenticate with the result through the availabel and active UAM authentication modules\&.
-.RE
-.PP
-\-adminauthuser
-.RS 4
-Specifying eg
-\fB\-adminauthuser root\fR
-whenever a normal user login fails, afpd will try to authenticate as the specified
-\fBadminauthuser\fR\&. If this succeeds, a normal session is created for the original connecting user\&. Said differently: if you know the password of
-\fBadminauthuser\fR, you can authenticate as any other user\&.
-.RE
-.SH "CODEPAGE OPTIONS"
-.PP
-With OS X Apple introduced the AFP3 protocol\&. One of the big changes was, that AFP3 uses Unicode names encoded as Decomposed UTF\-8 (UTF8\-MAC)\&. Previous AFP/OS versions used codepages like MacRoman, MacCentralEurope, etc\&.
-.PP
-To be able to serve AFP3 and older clients at the same time,
-\fBafpd\fR
-needs to be able to convert between UTF\-8 and Mac codepages\&. Even OS X clients partly still rely on codepages\&. As there\'s no way,
-\fBafpd\fR
-can detect the codepage a pre AFP3 client uses, you have to specify it using the
-\fB\-maccodepage\fR
-option\&. The default is MacRoman, which should be fine for most western users\&.
-.PP
-As
-\fBafpd\fR
-needs to interact with unix operating system as well, it need\'s to be able to convert from UTF8\-MAC/MacCodepage to the unix codepage\&. By default
-\fBafpd\fR
-uses the systems LOCALE, or ASCII if your system doesn\'t support locales\&. You can set the unix codepage using the
-\fB\-unixcodepage\fR
-option\&. If you\'re using extended characters in the configuration files for
-\fBafpd\fR, make sure your terminal matches the
-\fB\-unixcodepage\fR\&.
-.PP
-\-unixcodepage [\fICODEPAGE\fR]
-.RS 4
-Specifies the servers unix codepage, e\&.g\&. "ISO\-8859\-15" or "UTF8"\&. This is used to convert strings to/from the systems locale, e\&.g\&. for authenthication, server messages and volume names\&. Defaults to LOCALE if your system supports it, otherwise ASCII will be used\&.
-.RE
-.PP
-\-maccodepage [\fICODEPAGE\fR]
-.RS 4
-Specifies the mac clients codepage, e\&.g\&. "MAC_ROMAN"\&. This is used to convert strings and filenames to the clients codepage for OS9 and Classic, i\&.e\&. for authentication and AFP messages (SIGUSR2 messaging)\&. This will also be the default for the volumes maccharset\&. Defaults to MAC_ROMAN\&.
-.RE
-.SH "PASSWORD OPTIONS"
-.PP
-\-loginmaxfail [\fInumber\fR]
-.RS 4
-Sets the maximum number of failed logins, if supported by the UAM (currently none)
-.RE
-.PP
-\-passwdfile [\fIpath\fR]
-.RS 4
-Sets the path to the Randnum UAM passwd file for this server (default is :ETCDIR:/afppasswd)\&.
-.RE
-.PP
-\-passwdminlen [\fInumber\fR]
-.RS 4
-Sets the minimum password length, if supported by the UAM
-.RE
-.PP
-\-[no]savepassword
-.RS 4
-Enables or disables the ability of clients to save passwords locally
-.RE
-.PP
-\-[no]setpassword
-.RS 4
-Enables or disables the ability of clients to change their passwords via chooser or the "connect to server" dialog
-.RE
-.SH "TRANSPORT PROTOCOLS"
-.PP
-\-[no]ddp
-.RS 4
-Enables or disables AFP\-over\-Appletalk\&. If
-\fB\-proxy\fR
-is specified, you must instead use
-\fB\-uamlist ""\fR
-to prevent DDP connections from working\&. (default is \-noddp)
-.RE
-.PP
-\-[no]tcp
-.RS 4
-Enables or disables AFP\-over\-TCP (default is \-tcp)
-.RE
-.PP
-\-transall
-.RS 4
-Make both available
-.RE
-.SH "TRANSPORT OPTIONS"
-.PP
-\-advertise_ssh
-.RS 4
-Allows Mac OS X clients (10\&.3\&.3\-10\&.4) to automagically establish a tunneled AFP connection through SSH\&. If this option is set, the server\'s answers to client\'s FPGetSrvrInfo requests contain an additional entry\&. It depends on both client\'s settings and a correctly configured and running
-\fBsshd\fR(8)
-on the server to let things work\&.
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-Setting this option is not recommended since globally encrypting AFP connections via SSH will increase the server\'s load significantly\&. On the other hand, Apple\'s client side implementation of this feature in MacOS X versions prior to 10\&.3\&.4 contained a security flaw\&.
-.sp .5v
-.RE
-.RE
-.PP
-\-ddpaddr \fI[ddp address]\fR
-.RS 4
-Specifies the DDP address of the server\&. The default is to auto\-assign an address (0\&.0)\&. This is only useful if you are running AppleTalk on more than one interface\&.
-.RE
-.PP
-\-fqdn \fI[name:port]\fR
-.RS 4
-Specifies a fully\-qualified domain name, with an optional port\&. This is discarded if the server cannot resolve it\&. This option is not honored by AppleShare clients <= 3\&.8\&.3\&. This option is disabled by default\&. Use with caution as this will involve a second name resolution step on the client side\&. Also note that afpd will advertise this name:port combination but not automatically listen to it\&.
-.RE
-.PP
-\-hostname\fI [name]\fR
-.RS 4
-Use this instead of the result from calling hostname for dertermening which IP address to advertise, therfore the hostname is resolved to an IP which is the advertised\&. This is NOT used for listening and it is also overwritten by
-\fB\-ipaddr\fR\&.
-.RE
-.PP
-\-ipaddr \fI[ip address]\fR
-.RS 4
-Specifies the IP address that the server should advertise
-\fBand\fR
-listens to\&. The default is advertise the first IP address of the system, but to listen for any incoming request\&. The network address may be specified either in dotted\-decimal format for IPv4 or in hexadecimal format for IPv6\&. This option also allows to use one machine to advertise the AFP\-over\-TCP/IP settings of another machine via NBP
-when used together with the
-\fB\-proxy\fR
-option\&.
-.PP
-\fBExample.\ \&afpd.conf onfiguration line\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-              fluxxus \-hostname afp\&.example\&.org \-ipaddr 192\&.168\&.0\&.1 \-fqdn www\&.example\&.com
-            
-.fi
-.if n \{\
-.RE
-.\}
-.sp
-
-\fBResult\fR
-.sp
-(UTF8) Server name: fluxxus, Listening and advertised network address: 192\&.168\&.0\&.1, Advertised network address: www\&.example\&.com, hostname is not used\&.
-.RE
-.PP
-\-port \fI[port number]\fR
-.RS 4
-Allows a different TCP port to be used for AFP\-over\-TCP\&. The default is 548\&.
-.RE
-.PP
-\-proxy
-.RS 4
-Runs an AppleTalk proxy server for the specified AFP\-over\-TCP server\&. If the address and port aren\'t given, then the first IP address of the system and port 548 will be used\&. If you don\'t want the proxy server to act as a DDP
-server as well, set
-\fB\-uamlist ""\fR\&.
-.RE
-.PP
-\-server_quantum \fI[number]\fR
-.RS 4
-This specifies the DSI server quantum\&. The default value is 303840\&. The maximum value is 0xFFFFFFFFF, the minimum is 32000\&. If you specify a value that is out of range, the default value will be set\&. Do not change this value unless you\'re absolutely sure, what you\'re doing
-.RE
-.PP
-\-dsireadbuf \fI[number]\fR
-.RS 4
-Scale factor that determines the size of the DSI/TCP readahead buffer, default is 12\&. This is multiplies with the DSI server quantum (default ~300k) to give the size of the buffer\&. Increasing this value might increase throughput in fast local networks for volume to volume copies\&.
-\fINote\fR: This buffer is allocated per afpd child process, so specifying large values will eat up large amount of memory (buffer size * number of clients)\&.
-.RE
-.PP
-\-tcprcvbuf \fI[number]\fR
-.RS 4
-Try to set TCP receive buffer using setsockpt()\&. Often OSes impose restrictions on the applications ability to set this value\&.
-.RE
-.PP
-\-tcpsndbuf \fI[number]\fR
-.RS 4
-Try to set TCP send buffer using setsockpt()\&. Often OSes impose restrictions on the applications ability to set this value\&.
-.RE
-.PP
-\-nozeroconf
-.RS 4
-Disable automatic Zeroconf
-service registration if support was compiled in\&.
-.RE
-.PP
-\-slp
-.RS 4
-Register this server using the Service Location Protocol (if SLP
-support was compiled in)\&.
-.RE
-.SH "MISCELLANEOUS OPTIONS"
-.PP
-\-admingroup \fI[group]\fR
-.RS 4
-Allows users of a certain group to be seen as the superuser when they log in\&. This option is disabled by default\&.
-.RE
-.PP
-\-authprintdir \fI[path]\fR
-.RS 4
-Specifies the path to be used (per server) to store the files required to do CAP\-style print authentication which papd will examine to determine if a print job should be allowed\&. These files are created at login and if they are to be properly removed, this directory probably needs to be umode 1777\&.
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-\fB\-authprintdir\fR
-will only work for clients connecting via DDP\&. Almost all modern Clients will use TCP\&.
-.sp .5v
-.RE
-.RE
-.PP
-\-client_polling
-.RS 4
-With this switch enabled, afpd won\'t advertise that it is capable of server notifications, so that connected clients poll the server every 10 seconds to detect changes in opened server windows\&.
-\fINote\fR: Depending on the number of simultaneously connected clients and the network\'s speed, this can lead to a significant higher load on your network!
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-Do not use this option any longer as Netatalk 2\&.x correctly supports server notifications, allowing connected clients to update folder listings in case another client changed the contents\&.
-.sp .5v
-.RE
-.RE
-.PP
-\-closevol
-.RS 4
-Immediately unmount volumes removed from AppleVolumes files on SIGHUP sent to the afp master process\&.
-.RE
-.PP
-\-cnidserver \fI[ipaddress:port]\fR
-.RS 4
-Specifies the IP address and port of a cnid_metad server, required for CNID dbd backend\&. Defaults to localhost:4700\&. The network address may be specified either in dotted\-decimal format for IPv4 or in hexadecimal format for IPv6\&.\-
-.RE
-.PP
-\-dircachesize\fI entries\fR
-.RS 4
-Maximum possible entries in the directory cache\&. The cache stores directories and files\&. It is used to cache the full path to directories and CNIDs which considerably speeds up directory enumeration\&.
-.sp
-Default size is 8192, maximum size is 131072\&. Given value is rounded up to nearest power of 2\&. Each entry takes about 100 bytes, which is not much, but remember that every afpd child process for every connected user has its cache\&.
-.RE
-.PP
-\-fcelistener \fIhost[:port]\fR
-.RS 4
-Enables sending FCE events to the specified
-\fIhost\fR, default
-\fIport\fR
-is 12250 if not specified\&. Specifying mutliple listeners is done by having this option once for each of them\&.
-.RE
-.PP
-\-fceevents \fIfmod,fdel,ddel,fcre,dcre,tmsz\fR
-.RS 4
-Speficies which FCE events are active, default is
-\fIfmod,fdel,ddel,fcre,dcre\fR\&.
-.RE
-.PP
-\-fcecoalesce \fIall|delete|create\fR
-.RS 4
-Coalesce FCE events\&.
-.RE
-.PP
-\-fceholdfmod \fIseconds\fR
-.RS 4
-This determines the time delay in seconds which is always waited if another file modification for the same file is done by a client before sending an FCE file modification event (fmod)\&. For example saving a file in Photoshop would generate multiple events by itself because the application is opening, modifying and closing a file mutliple times for every "save"\&. Defautl: 60 seconds\&.
-.RE
-.PP
-\-guestname \fI[name]\fR
-.RS 4
-Specifies the user that guests should use (default is "nobody")\&. The name should be quoted\&.
-.RE
-.PP
-\-[no]icon
-.RS 4
-[Don\'t] Use the platform\-specific icon\&. Recent Mac OS don\'t display it any longer\&.
-.RE
-.PP
-\-keepsessions
-.RS 4
-Enable "Continuous AFP Service"\&. This means the ability to stop the master afpd process with a SIGQUIT signal, possibly install an afpd update and start the afpd process\&. Existing AFP sessions afpd processes will remain unaffected\&. Technically they will be notified of the master afpd shutdown, sleep 15\-20 seconds and then try to reconnect their IPC channel to the master afpd process\&. If this reconnect fails, the sessions are in an undefined state\&. Therefor it\'s absolutely critical to restart the master process in time!
-.RE
-.PP
-\-loginmesg \fI[message]\fR
-.RS 4
-Sets a message to be displayed when clients logon to the server\&. The message should be in
-\fBunixcodepage\fR
-and should be quoted\&. Extended characters are allowed\&.
-.RE
-.PP
-\-mimicmodel \fImodel\fR
-.RS 4
-Specifies the icon model that appears on clients\&. Defaults to off\&. Examples: RackMac (same as Xserve), PowerBook, PowerMac, Macmini, iMac, MacBook, MacBookPro, MacBookAir, MacPro, AppleTV1,1, AirPort\&.
-.RE
-.PP
-\-noacl2maccess
-.RS 4
-Don\'t map filesystem ACLs to effective permissions\&.
-.RE
-.PP
-\-nodebug
-.RS 4
-Disables debugging\&.
-.RE
-.PP
-\-sleep \fI[number]\fR
-.RS 4
-AFP 3\&.x waits
-\fInumber\fR
-hours before disconnecting clients in sleep mode\&. Default is 10 hours\&.
-.RE
-.PP
-\-signature { user:<text> | auto }
-.RS 4
-Specify a server signature\&. This option is useful while running multiple independent instances of afpd on one machine (eg\&. in clustered environments, to provide fault isolation etc\&.)\&. Default is "auto"\&. "auto" signature type allows afpd generating signature and saving it to
-:ETCDIR:/afp_signature\&.conf
-automatically (based on random number)\&. "host" signature type switches back to "auto" because it is obsoleted\&. "user" signature type allows administrator to set up a signature string manually\&. The maximum length is 16 characters\&.
-.PP
-\fBExample.\ \&Three server definitions using 2 different server signatures\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-first \-signature user:USERS 
-second \-signature user:USERS 
-third \-signature user:ADMINS
-.fi
-.if n \{\
-.RE
-.\}
-
-
-First two servers will appear as one logical AFP service to the clients \- if user logs in to first one and then connects to second one, session will be automatically redirected to the first one\&. But if client connects to first and then to third, will be asked for password twice and will see resources of both servers\&. Traditional method of signature generation causes two independent afpd instances to have the same signature and thus cause clients to be redirected automatically to server (s)he logged in first\&.
-.RE
-.PP
-\-volnamelen \fI[number] \fR
-.RS 4
-Max length of UTF8\-MAC volume name for Mac OS X\&. Note that Hangul is especially sensitive to this\&.
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-73:  limit of Mac OS X 10\&.1
-80:  limit for Mac OS X 10\&.4/10\&.5 (default)
-255: limit of spec
-.fi
-.if n \{\
-.RE
-.\}
-.sp
-Mac OS 9 and earlier are not influenced by this, because Maccharset volume name is always limitted to 27 bytes\&.
-.RE
-.SH "LOGGING OPTIONS"
-.PP
-\-setuplog "\fI<logtype> <loglevel> [<filename>]\fR"
-.RS 4
-Specify that any message of a loglevel up to the given
-\fBloglevel\fR
-should be logged to the given file\&. If the filename is ommited the loglevel applies to messages passed to syslog\&.
-.sp
-By default (no explicit
-\fB\-setuplog\fR
-and no buildtime configure flag
-\fB\-\-with\-logfile\fR) afpd logs to syslog with a default logging setup equivalent to
-\fB"\-setuplog default log_info\fR"\&.
-.sp
-If build with
-\fB\-\-with\-logfile\fR
-(default logfile
-\fI/var/log/netatalk\&.log\fR) or
-\fB\-\-with\-logfile=somefile\fR
-afpd defaults to a setup that is equivalent to "\fB\-setuplog default log_info [\fR\fB\fInetatalk\&.log|somefile]\fR\fR"\&.
-.sp
-logtypes: Default, AFPDaemon, Logger, UAMSDaemon
-.sp
-loglevels: LOG_SEVERE, LOG_ERROR, LOG_WARN, LOG_NOTE, LOG_INFO, LOG_DEBUG, LOG_DEBUG6, LOG_DEBUG7, LOG_DEBUG8, LOG_DEBUG9, LOG_MAXDEBUG
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-The config is case\-ignoring
-.sp .5v
-.RE
-.PP
-\fBExample.\ \&Useful default config\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\- \-setuplog "default log_info /var/log/afpd\&.log"
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-\fBExample.\ \&Debugging config\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\- \-setuplog "default log_maxdebug /var/log/afpd\&.log"
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-\fBExample.\ \&afpd logging to different files\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\- \-setuplog "default log_info /var/log/afpd\&.log" \e
-\-setuplog "UAMSDaemon log_maxdebug /var/log/uams\&.log"
-.fi
-.if n \{\
-.RE
-.\}
-.RE
-.PP
-\-unsetuplog "\fI<logtype> [<filename>]\fR"
-.RS 4
-Note that for
-\fBunsetuplog\fR
-specifying any string as filename is sufficient for the config parser to distinguish between requests to disable syslog logging or file\-logging\&.
-.PP
-\fBExample.\ \&Disable afpd logging set at build-time from configure\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\- \-unsetuplog "default \-"
-.fi
-.if n \{\
-.RE
-.\}
-.RE
-.SH "DEBUG OPTIONS"
-.PP
-These options are useful for debugging only\&.
-.PP
-\-tickleval \fI[number]\fR
-.RS 4
-Sets the tickle timeout interval (in seconds)\&. Defaults to 30\&.
-.RE
-.PP
-\-timeout \fI[number]\fR
-.RS 4
-Specify the number of tickles to send before timing out a connection\&. The default is 4, therefore a connection will timeout after 2 minutes\&.
-.RE
-.SH "EXAMPLES"
-.PP
-\fBExample.\ \&afpd.conf default configuration\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\- \-tcp \-noddp \-uamlist uams_dhx\&.so,uams_dhx2\&.so \-nosavepassword
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-\fBExample.\ \&afpd.conf MacCyrillic setup / UTF8 unix locale\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\- \-maccodepage mac_cyrillic \-unixcodepage utf8
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-\fBExample.\ \&afpd.conf setup for Kerberos V auth with newline escaping\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\- \-uamlist uams_dhx\&.so,uams_dhx2\&.so,uams_guest\&.so,uams_gss\&.so \e 
-\-k5service afpserver \-k5keytab /path/to/afpserver\&.keytab \e 
-\-k5realm YOUR\&.REALM \-fqdn your\&.fqdn\&.namel:548
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-\fBExample.\ \&afpd.conf letting afpd appear as three servers on the net\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-"Guest Server" \-uamlist uams_guest\&.so \-loginmesg "Welcome guest!"
-"User Server" \-uamlist uams_dhx2\&.so \-port 12000
-"special" \-ddp \-notcp \-defaultvol <path> \-systemvol <path>
-.fi
-.if n \{\
-.RE
-.\}
-.SH "SEE ALSO"
-.PP
-\fBafpd\fR(8),
-\fBafppasswd\fR(1),
-\fBAppleVolumes.default\fR(5),
-\fBafp_signature.conf\fR(5),
-\fBcnid_metad\fR(8)
diff --git a/man/man5/atalkd.conf.5.tmpl b/man/man5/atalkd.conf.5.tmpl
deleted file mode 100644 (file)
index ed51c8c..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-'\" t
-.\"     Title: atalkd.conf
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 22 September 2000
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "ATALKD\&.CONF" "5" "22 September 2000" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-atalkd.conf \- Configuration file used by atalkd(8) to determine the interfaces used by the master Netatalk daemon
-.SH "DESCRIPTION"
-.PP
-\fB:ETCDIR:/atalkd\&.conf\fR
-is the configuration file used by atalkd to configure the Appletalk interfaces and their behavior
-.PP
-Any line not prefixed with
-\fB#\fR
-is interpreted\&. The configuration lines are composed like:
-.PP
-\fIInterface\fR
-\fB[\fR
-\fIoptions\fR
-\fB]\fR
-.PP
-The simplest case is to have either no atalkd\&.conf, or to have one that has no active lines\&. In this case, atalkd should auto\-discover the local interfaces on the machine\&. Please note that you cannot split lines\&.
-.PP
-The interface is the network interface that this to work over, such as
-\fBeth0\fR
-for Linux, or
-\fBle0\fR
-for Sun\&.
-.PP
-The possible options and their meanings are:
-.PP
-\fB\-addr \fR\fB\fInet\&.node\fR\fR
-.RS 4
-Allows specification of the net and node numbers for this interface, specified in Appletalk numbering format (example:
-\fB\-addr 66\&.6\fR)\&.
-.RE
-.PP
-\fB\-dontroute\fR
-.RS 4
-Disables Appletalk routing\&. It is the opposite of
-\fB\-router\fR\&.
-.RE
-.PP
-\fB\-net first[\-last]\fR
-.RS 4
-Allows the available net to be set, optionally as a range\&.
-.RE
-.PP
-\fB\-noallmulti\fR (linux only)
-.RS 4
-On linux the interfaces, atalkd uses, are set to ALLMULTI by default caused by countless NICs having problems without being forced into this mode (some even don\'t work with allmulti set)\&. In case, you\'ve a NIC known to support multicasts properly, you might want to set this option causing less packets to be processed
-.RE
-.PP
-\fB\-phase ( 1 | 2 )\fR
-.RS 4
-Specifies the Appletalk phase that this interface is to use (either Phase 1 or Phase 2)\&.
-.RE
-.PP
-\fB\-router\fR
-.RS 4
-Like
-\fB\-seed\fR, but allows single interface routing\&. It is the opposite of
-\fB\-dontroute\fR\&.
-.RE
-.PP
-\fB\-seed\fR
-.RS 4
-The seed option only works if you have multiple interfaces\&. It also causes all missing arguments to be automagically configured from the network\&.
-.RE
-.PP
-\fB\-zone \fR\fB\fIzonename\fR\fR
-.RS 4
-Specifies a specific zone that this interface should appear on (example:
-\fB\-zone "Parking Lot"\fR)\&. Please note that zones with spaces and other special characters should be enclosed in parentheses\&.
-.RE
-.SH "SEE ALSO"
-.PP
-\fBatalkd\fR(8)
diff --git a/man/man5/netatalk.conf.5.tmpl b/man/man5/netatalk.conf.5.tmpl
deleted file mode 100644 (file)
index 6c9b4b7..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-'\" t
-.\"     Title: netatalk.conf
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 30 Mar 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "NETATALK\&.CONF" "5" "30 Mar 2011" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-netatalk.conf \- Configuration file used by Netatalk to determine its general configuration
-.SH "SYNOPSIS"
-.HP \w'\fB:ETCDIR:/netatalk\&.conf\fR\fB\fR\fB:DESTDIR:/etc/default/netatalk\fR\fB\fR\ 'u
-\fB:ETCDIR:/netatalk\&.conf\fR\fB\fR
-.br
-\fB:DESTDIR:/etc/default/netatalk\fR\fB\fR
-.SH "DESCRIPTION"
-.PP
-\fB:ETCDIR:/netatalk\&.conf\fR
-is the configuration file used by afpd to determine what portions of the file system will be shared via AFP, as well as their behaviors\&.
-.PP
-If netatalk has been configured with \-\-enable\-debian, it is not
-\fB:ETCDIR:/netatalk\&.conf\fR
-but
-\fB:DESTDIR:/etc/default/netatalk\fR\&.
-.PP
-Any line not prefixed with
-\fB#\fR
-is interpreted\&. The configuration lines are composed like:
-.PP
-\fIoption\fR
-\fB=\fR
-\fIvalue\fR
-.PP
-The possible options and their meanings are:
-.PP
-\fBAFPD_GUEST\fR
-.RS 4
-Sets the id of the guest user to a local user on the system\&.
-.RE
-.PP
-\fBAFPD_MAX_CLIENTS\fR
-.RS 4
-Sets the maximum number of clients that can simultaneously connect to the server\&.
-.RE
-.PP
-\fBAFPD_RUN\fR
-.RS 4
-Enables the afpd daemon if set to "yes"\&. This should be enabled if you are planning on using netatalk as a file server\&.
-.RE
-.PP
-\fBAFPD_UAM_LIST\fR
-.RS 4
-Sets the default UAMs for afpd (and papd, if printer authentication is compiled in) to use\&.
-.sp
-\fIExample:\fR
-\fBAFPD_UAMLIST\fR=\fB"\-U uams_guest\&.so,uams_randnum\&.so"\fR
-.RE
-.PP
-\fBCNID_METAD_RUN\fR
-.RS 4
-Enables the cnid_metad daemon if set to "yes"\&. This should be enabled if you are going to use the dbd CNID backend\&.
-.RE
-.PP
-\fBCNID_CONFIG\fR
-.RS 4
-Configuration options for cnid_metad\&. See:
-\fBcnid_metad\fR(8)
-.RE
-.PP
-\fBATALK_BGROUND\fR
-.RS 4
-"yes" will set netatalk to initialize in the background, and "no" will cause normal initialization\&.
-.RE
-.PP
-\fBATALK_NAME\fR
-.RS 4
-Sets the machines\' Appletalk name\&.
-.RE
-.PP
-\fBATALK_ZONE\fR
-.RS 4
-Sets the machines\' Appletalk zone\&.
-.RE
-.PP
-\fBATALKD_RUN\fR
-.RS 4
-Enables the atalkd daemon if set to "yes"\&. This should be enabled if you are planning on providing Appletalk services\&.
-.RE
-.PP
-\fBPAPD_RUN\fR
-.RS 4
-Enables the papd daemon if set to "yes"\&. This should be enabled if you are planning on using netatalk as a print server\&.
-.RE
-.PP
-\fBATALK_MAC_CHARSET\fR
-.RS 4
-Set the Mac client codepage, used by atalkd and papd to convert extended characters from the Unix to the Mac codepage\&.
-.RE
-.PP
-\fBATALK_UNIX_CHARSET\fR
-.RS 4
-Set the Unix codepage, used by atalkd and papd to convert extended characters from the Unix to the Mac codepage\&. Has to match the codepage of the configuration files\&.
-.RE
-.SH "SEE ALSO"
-.PP
-\fBafpd\fR(8),
-\fBafpd.conf\fR(5),
-\fBcnid_metad\fR(8),
-\fBatalkd\fR(8),
-\fBatalkd.conf\fR(5)
diff --git a/man/man5/papd.conf.5.tmpl b/man/man5/papd.conf.5.tmpl
deleted file mode 100644 (file)
index caf5f60..0000000
+++ /dev/null
@@ -1,209 +0,0 @@
-'\" t
-.\"     Title: papd.conf
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 06 Sep 2004
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "PAPD\&.CONF" "5" "06 Sep 2004" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-papd.conf \- Configuration file used by papd(8) to determine the configuration of printers used by the Netatalk printing daemon
-.SH "DESCRIPTION"
-.PP
-\fB:ETCDIR:/papd\&.conf\fR
-is the configuration file used by papd to configure the printing services offered by netatalk\&. Please note that papd must be enabled in
-\fB:ETCDIR:/netatalk\&.conf\fR
-for this to take any effect\&.
-\fBpapd\fR
-shares the same defaults as lpd on many systems, but not Solaris\&.
-.PP
-Any line not prefixed with
-\fB#\fR
-is interpreted\&. The configuration lines are composed like:
-.PP
-\fIprintername:[options]\fR
-.PP
-On systems running a System V printing system the simplest case is to have either no papd\&.conf, or to have one that has no active lines\&. In this case, atalkd should auto\-discover the local printers on the machine\&. Please note that you can split lines by using
-\fB\e\efR\&.\fR
-.PP
-printername may be just a name (\fBPrinter 1\fR), or it may be a full name in nbp_name format (\fBPrinter 1:LaserWriter@My Zone\fR)\&.
-.PP
-Systems using a BSD printing system should make use of a pipe to the printing command in question within the
-\fBpr\fR
-option (eg\&.
-\fBpr=|/usr/bin/lpr\fR)\&.
-.PP
-When CUPS support is compiled in, then
-\fBcupsautoadd \fR
-as the first entry in papd\&.conf will automagically share all CUPS printers by papd utilizing the PPDs assigned in CUPS (customizable \-\- see below)\&. This can be overwritten for individal printers by subsequently adding individual entries using the CUPS queue name as
-\fBpr \fR
-entry\&. Note: CUPS support is mutually exclusive with System V support described above\&.
-.PP
-The possible options are colon delimited (\fB:\fR), and lines must be terminated with colons\&. The possible options and flags are:
-.PP
-\fBam=(uams list)\fR
-.RS 4
-The
-\fBam\fR
-option allows specific UAMs to be specified for a particular printer\&. It has no effect if the
-\fBau\fR
-flag is not present or if papd authentication was not built into netatalk\&. Note: possible values are
-\fBuams_guest\&.so\fR
-and
-\fB uams_clrtxt\&.so\fR
-only\&. The first method requires a valid username, but no password\&. The second requires both a valid username and the correct password\&.
-.RE
-.PP
-\fBau\fR
-.RS 4
-If present, this flag enables authentication for the printer\&. Please note that papd authentication must be built into netatalk for this to take effect\&.
-.RE
-.PP
-\fBco=(CUPS options)\fR
-.RS 4
-The
-\fBco\fR
-option allows options to be passed through to CUPS (eg\&.
-\fBco="protocol=TBCP" \fR
-or
-\fBco="raw"\fR)\&.
-.RE
-.PP
-\fBcupsautoadd[:type][@zone]\fR
-.RS 4
-If used as the first entry in papd\&.conf this will share all CUPS printers via papd\&. type/zone settings as well as other parameters assigned to this special printer share will apply to all CUPS printers\&. Unless the
-\fBpd\fR
-option is set, the CUPS PPDs will be used\&. To overwrite these global settings for individual printers simply add them subsequently to papd\&.conf and assign different settings\&.
-.RE
-.PP
-\fBfo\fR
-.RS 4
-If present, this flag enables a hack to translate line endings originating from pre Mac OS X LaserWriter drivers to let
-\fBfoomatic\-rip\fR
-recognize foomatic PPD options set in the printer dialog\&. Attention: Use with caution since this might corrupt binary print jobs!
-.RE
-.PP
-\fBop=(operator)\fR
-.RS 4
-This specifies the operator name, for lpd spooling\&.
-.RE
-.PP
-\fBpa=(appletalk address)\fR
-.RS 4
-Allows specification of Appletalk addresses\&. Usually not needed\&.
-.RE
-.PP
-\fBpd=(path to ppd file)\fR
-.RS 4
-Specifies a particular PPD (printer description file) to associate with the selected printer\&.
-.RE
-.PP
-\fBpr=(lpd/CUPS printer name or pipe command)\fR
-.RS 4
-Sets the
-\fBlpd\fR
-or
-\fBCUPS\fR
-printer that this is spooled to\&.
-.RE
-.SH "EXAMPLES"
-.PP
-Unless CUPS support has been compiled in (which is default from Netatalk 2\&.0 on) one simply defines the lpd queue in question by setting the
-\fBpr\fR
-parameter to the queue name, in the following example "ps"\&. If no
-\fBpr\fR
-parameter is set, the default printer will be used\&.
-.PP
-\fBExample.\ \&papd.conf System V printing system examples\fR
-.PP
-The first spooler is known by the AppleTalk name Mac Printer Spooler, and uses a PPD file located in
-/usr/share/lib/ppd\&. In addition, the user mcs will be the owner of all jobs that are spooled\&. The second spooler is known as HP Printer and all options are the default\&.
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-Mac Printer Spooler:\e
-   :pr=ps:\e
-   :pd=/usr/share/lib/ppd/HPLJ_4M\&.PPD:\e
-   :op=mcs:
-
-HP Printer:\e
-   :
-.fi
-.if n \{\
-.RE
-.\}
-
-.PP
-An alternative to the technique outlined above is to direct papd\'s output via a pipe into another program\&. Using this mechanism almost all printing systems can be driven\&.
-.PP
-\fBExample.\ \&papd.conf examples using pipes\fR
-.PP
-The first spooler is known as HP 8100\&. It pipes the print job to
-\fB/usr/bin/lpr\fR
-for printing\&. PSSP authenticated printing is enabled, as is CAP\-style authenticated printing\&. Both methods support guest and cleartext authentication as specified by the \'\fBam\fR\' option\&. The PPD used is
-/etc/atalk/ppds/hp8100\&.ppd\&.
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-HP 8100:\e
-   :pr=|/usr/bin/lpr \-Plp:\e
-   :sp:\e
-   :ca=/tmp/print:\e
-   :am=uams_guest\&.so,uams_pam\&.so:\e
-   :pd=/etc/atalk/ppds/hp8100\&.ppd:
-      
-.fi
-.if n \{\
-.RE
-.\}
-.sp
-
-.PP
-Starting with Netatalk 2\&.0 direct CUPS integration is available\&. In this case, defining only a queue name as
-\fBpr\fR
-parameter won\'t invoke the SysV lpd daemon but uses CUPS instead\&. Unless a specific PPD has been assigned using the
-\fBpd\fR
-switch, the PPD configured in CUPS will be used by
-\fBpapd\fR, too\&.
-.PP
-There exists one special share named "cupsautoadd"\&. If this is present as the first entry then all available CUPS queues will be served automagically using the parameters assigned to this global share\&. But subsequent printer definitions can be used to override these global settings for individual spoolers\&.
-.PP
-\fBExample.\ \&papd.conf CUPS examples\fR
-.PP
-The first entry sets up automatic sharing of all CUPS printers\&. All those shares appear in the zone "1st floor" and since no additional settings have been made, they use the CUPS printer name as NBP name and use the PPD configured in CUPS\&. The second entry defines different settings for one single CUPS printer\&. It\'s NBP name is differing from the printer\'s name and the registration happens in another zone\&.
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-cupsautoadd@1st floor:op=root:
-
-Boss\' LaserWriter@2nd floor:\e
-   :pr=laserwriter\-chief:
-.fi
-.if n \{\
-.RE
-.\}
-
-.SH "SEE ALSO"
-.PP
-\fBpapd\fR(8),
-\fBatalkd.conf\fR(5),
-\fBlpd\fR(8),
-\fBlpoptions\fR(8)
index 358906e83826718a2af0347130397acd128d1237..711b8c366feeaa990bf572e2d9538b5f97a361d0 100644 (file)
@@ -5,8 +5,8 @@ afp_acls.8
 atalkd.8
 cnid_dbd.8
 cnid_metad.8
+netatalk.8
 papd.8
 papstatus.8
 psf.8
-.gitignore
 *.o
index 26273d4378663bcbdaabe2e167fffd4a085cd202..eb112ab3d7445ee15c824cea5b2df46e1d74d485 100644 (file)
@@ -10,21 +10,15 @@ SUFFIXES = .tmpl .
            -e s@:ETCDIR:@${pkgconfdir}@ \
            -e s@:LIBDIR:@${libdir}@ \
            -e s@:LIBEXECDIR:@${libexecdir}@ \
+           -e "s@:STATEDIR:@${localstatedir}@g" \
            -e s@:NETATALK_VERSION:@${NETATALK_VERSION}@ \
            <$< >$@
 
-NONGENERATED_MANS = timelord.8
-GENERATED_MANS    = afpd.8 cnid_dbd.8 cnid_metad.8
-TEMPLATE_FILES    = afpd.8.tmpl cnid_dbd.8.tmpl cnid_metad.8.tmpl
-ATALK_MANS        = atalkd.8.tmpl papd.8.tmpl papstatus.8.tmpl psf.8.tmpl
+GENERATED_MANS    = afpd.8 cnid_dbd.8 cnid_metad.8 netatalk.8
+TEMPLATE_FILES    = afpd.8.tmpl cnid_dbd.8.tmpl cnid_metad.8.tmpl netatalk.8.tmpl
 
-if USE_APPLETALK
-GENERATED_MANS += atalkd.8 papd.8 papstatus.8 psf.8
-TEMPLATE_FILES += $(ATALK_MANS)
-endif
-
-man_MANS = $(GENERATED_MANS) $(NONGENERATED_MANS)
+man_MANS = $(GENERATED_MANS)
 
 CLEANFILES = $(GENERATED_MANS)
 
-EXTRA_DIST = $(TEMPLATE_FILES) $(NONGENERATED_MANS) $(ATALK_MANS)
+EXTRA_DIST = $(TEMPLATE_FILES)
index 6ce60fd41ef68274000299dbcef1746e5557e6dc..3a913925f3bff9e797bd4df2f96f88a2daea127c 100644 (file)
@@ -2,12 +2,12 @@
 .\"     Title: afpd
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 08 Mar 2011
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"      Date: 23 Mar 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "AFPD" "8" "08 Mar 2011" "Netatalk 2.2" "Netatalk 2.2"
+.TH "AFPD" "8" "23 Mar 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
 afpd \- Apple Filing Protocol daemon
 .SH "SYNOPSIS"
 .HP \w'\fBafpd\fR\fB\fR\fBafpd\fR\fB\fR\ 'u
-\fBafpd\fR\fB\fR [\-duptDTI] [\-f\ \fIdefaultvolumes\fR] [\-s\ \fIsystemvolumes\fR] [\-n\ \fInbpname\fR] [\-c\ \fImaxconnections\fR] [\-g\ \fIguest\fR] [\-P\ \fIpidfile\fR] [\-S\ \fIport\fR] [\-L\ \fImessage\fR] [\-F\ \fIconfigfile\fR] [\-U\ \fIuams\fR] [\-m\ \fIumask\fR]
+\fBafpd\fR\fB\fR [\-d] [\-F\ \fIconfigfile\fR]
 .br
 \fBafpd\fR\fB\fR \-v | \-V | \-h 
 .SH "DESCRIPTION"
 .PP
 \fBafpd\fR
-provides an Apple Filing Protocol (AFP) interface to the Unix file system\&. It is normally started at boot time from /etc/rc\&.
+provides an Apple Filing Protocol (AFP) interface to the Unix file system\&. It is normally started at boot time by
+\fBnetatalk\fR(8)\&.
 .PP
-:ETCDIR:/afpd\&.conf
+:ETCDIR:/afp\&.conf
 is the configuration file used by
 \fBafpd\fR
-to determine the behavior and configuration of the different virtual file servers that it provides\&.
-.PP
-The list of volumes offered to the user is generated from
-:ETCDIR:/AppleVolumes\&.system
-and one of
-:ETCDIR:/AppleVolumes\&.default,
-~/AppleVolumes,
-~/\&.AppleVolumes,
-~/applevolumes, or
-~/\&.applevolumes\&. The
-AppleVolumes
-files is used to specify volumes to mount and file name extension mappings\&.
-.PP
+to determine the behavior and configuration of a file server\&.
 .SH "OPTIONS"
 .PP
 \-d
 .RS 4
-Specifies that the daemon should not fork\&. If netatalk has been configured with
-\fI\-\-enable\-debug1\fR, a trace of all AFP commands will be written to stdout\&.
-.RE
-.PP
-\-p
-.RS 4
-Prevents clients from saving their passwords\&. (Equivalent to \-\fBnosavepasswd\fR
-in
-afpd\&.conf\&.)
-.RE
-.PP
-\-t
-.RS 4
-Allows clients to change their passwords\&. (Equivalent to
-\fB\-setpasswd\fR
-in
-afpd\&.conf\&.)
-.RE
-.PP
-\-D
-.RS 4
-Use DDP (AppleTalk) as transport protocol\&. (Equivalent to
-\fB\-ddp\fR
-in
-afpd\&.cond\&.)
-.RE
-.PP
-\-T
-.RS 4
-Use TCP/IP as transport protocol\&. (Equivalent to
-\fB\-tcp\fR
-in
-afpd\&.conf\&.)
+Specifies that the daemon should not fork\&.
 .RE
 .PP
 \-v
@@ -100,104 +57,10 @@ Print verbose information and exit\&.
 Print help and exit\&.
 .RE
 .PP
-\-I
-.RS 4
-Use a platform specific icon\&. (Equivalent to
-\fB\-icon\fR
-in
-afpd\&.conf\&.) (Recent Mac OS don\'t display it\&.)
-.RE
-.PP
-\-f \fIdefaultvolumes\fR
-.RS 4
-Specifies that
-\fIdefaultvolumes\fR
-should be read for a list of default volumes to offer, instead of
-:ETCDIR:/AppleVolumes\&.default\&.
-.RE
-.PP
-\-s \fIsystemvolumes\fR
-.RS 4
-Specifies that
-\fIsystemvolumes\fR
-should be read for a list of volume that all users will be offered, instead of
-:ETCDIR:/AppleVolumes\&.system\&.
-.RE
-.PP
-\-u
-.RS 4
-Read the user\'s
-AppleVolumes
-file first\&. This option causes volume names in the user\'s
-AppleVolumes
-file to override volume names in the system\'s
-AppleVolumes
-file\&. The default is to read the system
-AppleVolumes
-file first\&. Note that this option doesn\'t effect the precendence of filename extension mappings: the user\'s
-AppleVolumes
-file always has precedence\&.
-.RE
-.PP
-\-n \fInbpname\fR
-.RS 4
-Specifies that
-\fInbpname\fR
-should be used for NBP registration, instead of the first component of the hostname in the local zone\&.
-.RE
-.PP
-\-c \fImaxconnections\fR
-.RS 4
-Specifies the maximum number of connections to allow for this
-\fBafpd\fR\&. The default is 20\&.
-.RE
-.PP
-\-g \fIguest\fR
-.RS 4
-Specifies the name of the guest account\&. The default is \'\fInobody\fR\'\&.
-.RE
-.PP
-\-P \fIpidfile\fR
-.RS 4
-Specifies the file in which
-\fBafpd\fR
-stores its process id\&.
-.RE
-.PP
-\-S \fIport\fR
-.RS 4
-Specifies the port to register with when doing AFPoverTCP\&. Defaults to 548\&. (Equivalent to
-\fB\-port \fRin
-afpd\&.conf\&.)
-.RE
-.PP
-\-L \fImessage\fR
-.RS 4
-Specifies the login message that will be sent to clients\&. (Equivalent to
-\fB\-loginmsg\fR
-in
-afpd\&.conf\&.)
-.RE
-.PP
 \-F \fIconfigfile\fR
 .RS 4
 Specifies the configuration file to use\&. (Defaults to
-:ETCDIR:/netatalk/afpd\&.conf\&.)
-.RE
-.PP
-\-U \fIuams\fR
-.RS 4
-Comma\-separated list of UAMs to use for the authentication process\&. (Equivalent to
-\fB\-uamlist\fR
-in
-afpd\&.conf\&.)
-.RE
-.PP
-\-m \fIumask\fR
-.RS 4
-Use this
-\fIumask\fR
-for the creation of folders in Netatalk\&.
+:ETCDIR:/afp\&.conf\&.)
 .RE
 .SH "SIGNALS"
 .PP
@@ -264,53 +127,30 @@ process will look in the message directory configured at build time for a file n
 .RE
 .SH "FILES"
 .PP
-:ETCDIR:/afpd\&.conf
+:ETCDIR:/afp\&.conf
 .RS 4
 configuration file used by afpd
 .RE
 .PP
-:ETCDIR:/AppleVolumes\&.default
-.RS 4
-list of default volumes to mount
-.RE
-.PP
-:ETCDIR:/AppleVolumes\&.system
-.RS 4
-list of volumes to offer all users
-.RE
-.PP
-~/AppleVolumes, ~/\&.AppleVolumes, ~/applevolumes, ~/\&.applevolumes
-.RS 4
-user\'s list of volumes to mount
-.RE
-.PP
-:ETCDIR:/afp_signature\&.conf
+:STATEDIR:/netatalk/afp_signature\&.conf
 .RS 4
 list of server signature
 .RE
 .PP
-:ETCDIR:/afp_voluuid\&.conf
+:STATEDIR:/netatalk/afp_voluuid\&.conf
 .RS 4
 list of UUID for Time Machine volume
 .RE
 .PP
-:ETCDIR:/afp_ldap\&.conf
-.RS 4
-configuration file for LDAP and ACL support
-.RE
-.PP
 :ETCDIR:/msg/message\&.pid
 .RS 4
 contains messages to be sent to users\&.
 .RE
-.SH "BUGS"
-.PP
 .SH "SEE ALSO"
 .PP
+\fBnetatalk\fR(8),
 \fBhosts_access\fR(5),
-\fBafpd.conf\fR(5),
-\fBAppleVolumes.default\fR(5),
+\fBafp.conf\fR(5),
 \fBafp_signature.conf\fR(5),
 \fBafp_voluuid.conf\fR(5),
-\fBafp_ldap.conf\fR(5),
 \fBdbd\fR(1)\&.
diff --git a/man/man8/atalkd.8.tmpl b/man/man8/atalkd.8.tmpl
deleted file mode 100644 (file)
index 819e388..0000000
+++ /dev/null
@@ -1,109 +0,0 @@
-'\" t
-.\"     Title: atalkd
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 06 Sep 2004
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "ATALKD" "8" "06 Sep 2004" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-atalkd \- AppleTalk RTMP, NBP, ZIP, and AEP manager
-.SH "SYNOPSIS"
-.HP \w'\fBatalkd\fR\fB\fR\fB\fR\fB\fR\fB\fR\fB\fR\fB\fR\ 'u
-\fBatalkd\fR\fB\fR\fB\fR\fB\fR\fB\fR\fB\fR\fB\fR [\-f\ \fIconfigfile\fR] [\-1] [\-2]
-.SH "DESCRIPTION"
-.PP
-\fBatalkd\fR
-is responsible for all user level AppleTalk network management\&. This includes routing, name registration and lookup, zone lookup, and the AppleTalk Echo Protocol (similar to
-\fBping\fR(8))\&.
-\fBatalkd\fR
-is typically started at boot time, out of
-/etc/rc\&. It first reads from its configuration file,
-:ETCDIR:/atalkd\&.conf\&. If there is no configuration file,
-\fBatalkd\fR
-will attempt to configure all available interfaces and will create a configuration file\&. The file consists of a series of interfaces, one per line\&. Lines with `#\' in the first column are ignored, as are blank lines\&. The syntax is
-.PP
-\fIinterface\fR
-[
-\fB\-seed\fR
-] [
-\fB\-phase\fR
-\fInumber\fR
-] [
-\fB\-net\fR
-\fInet\-range\fR
-] [
-\fB\-addr\fR
-\fIaddress\fR
-] [
-\fB\-zone\fR
-\fIzonename\fR
-] \&.\&.\&.
-.PP
-Note that all fields except the interface are optional\&. The loopback interface is configured automatically\&. If
-\fB\-seed\fR
-is specified, all other fields must be present\&. Also,
-\fBatalkd\fR
-will exit during bootstrap\%ping, if a router disagrees with its seed information\&. If
-\fB\-seed\fR
-is not given, all other information may be overriden during auto\-configuration\&. If no
-\fB\-phase\fR
-option is given, the default phase as given on the command line is used (the default is 2)\&. If
-\fB\-addr\fR
-is given and
-\fB\-net\fR
-is not, a net\-range of one is assumed\&.
-.PP
-The first \-zone directive for each interface is the ``default\'\' zone\&. Under Phase 1, there is only one zone\&. Under Phase 2, all routers on the network are configured with the default zone and must agree\&.
-\fBatalkd\fR
-maps ``*\'\' to the default zone of the first interface\&. Note: The default zone for a machine is determined by the configuration of the local routers; to appear in a non\-default zone, each service, e\&.g\&.
-\fBafpd\fR, must individually specify the desired zone\&. See also
-\fBnbp_name\fR(3)\&.
-.SH "ROUTING"
-.PP
-If you are connecting a netatalk router to an existing AppleTalk internet, you should first contact your local network administrators to obtain appropriate network addresses\&.
-.PP
-\fBatalkd\fR
-can provide routing between interfaces by configuring multiple interfaces\&. Each interface must be assigned a unique net\-range
-between 1 and 65279 (0 and 65535 are illegal, and addresses between 65280 and 65534 are reserved for startup)\&. It is best to choose the smallest useful net\-range, i\&.e\&. if you have three machines on an Ethernet, don\'t chose a net\-range of 1000\-2000\&. Each net\-range may have an arbitrary list of zones associated with it\&.
-.SH "EXAMPLES"
-.PP
-Below is an example configuration file for a sun4/40\&. The machine has two interfaces, ``le0\'\' and ``le1\'\'\&. The ``le0\'\' interface is configured automatically from other routers on the network\&. The machine is the only router for the ``le1\'\' interface\&.
-.PP
-.if n \{\
-.RS 4
-.\}
-.nf
-   le0
-   le1 \-seed \-net 9461\-9471 \-zone netatalk \-zone Argus
-.fi
-.if n \{\
-.RE
-.\}
-.sp
-\fBatalkd\fR
-automatically acts as a router if there is more than one interface\&.
-.SH "FILES"
-.PP
-:ETCDIR:/atalkd\&.conf
-configuration file
-.SH "BUGS"
-.PP
-On some systems,
-\fBatalkd\fR
-can not be restarted\&.
-.SH "SEE ALSO"
-.PP
-\fBatalkd.conf\fR(5)
index 0219cdca5048164e8449d621e8eb1c37a2891c4a..347921efa17139e8f3b1b3c4e5637372443f93ea 100644 (file)
@@ -3,11 +3,11 @@
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
 .\"      Date: 01 Jan 2012
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "CNID_DBD" "8" "01 Jan 2012" "Netatalk 2.2" "Netatalk 2.2"
+.TH "CNID_DBD" "8" "01 Jan 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
@@ -22,7 +22,7 @@
 cnid_dbd \- implement access to CNID databases through a dedicated daemon process
 .SH "SYNOPSIS"
 .HP \w'\fBcnid_dbd\fR\fB\fR\fB\fR\fB\fR\fBcnid_dbd\fR\fB\fR\ 'u
-\fBcnid_dbd\fR\fB\fR\fB\fR\fB\fR \fIvolpath\fR \fIctrlfd\fR \fIclntfd\fR \fIlogconfig_string\fR
+\fBcnid_dbd\fR\fB\fR\fB\fR\fB\fR
 .br
 \fBcnid_dbd\fR\fB\fR \-v | \-V 
 .SH "DESCRIPTION"
@@ -80,13 +80,6 @@ via the filedescriptor
 \fIctrlfd\fR\&.
 .PP
 \fBcnid_dbd\fR
-uses
-\fBlogconfig_string\fR
-which is passed from
-\fBcnid_metad\fR
-to configure its logging output\&.
-.PP
-\fBcnid_dbd\fR
 can be configured to run forever or to exit after a period of inactivity\&. If
 \fBcnid_dbd\fR
 receives a TERM or an INT signal it will exit cleanly after flushing dirty database buffers to disk and closing
index 7d4b2cee64860ee7d86a1ffb619ab559e0d97922..f96778f1b12bb761ed815e118ba41ce9aa03592a 100644 (file)
@@ -2,12 +2,12 @@
 .\"     Title: cnid_metad
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 01 Jan 2012
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
+.\"      Date: 23 Mar 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
 .\"  Language: English
 .\"
-.TH "CNID_METAD" "8" "01 Jan 2012" "Netatalk 2.2" "Netatalk 2.2"
+.TH "CNID_METAD" "8" "23 Mar 2012" "Netatalk 3.0" "Netatalk 3.0"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
@@ -22,7 +22,7 @@
 cnid_metad \- start cnid_dbd daemons on request
 .SH "SYNOPSIS"
 .HP \w'\fBcnid_metad\fR\fB\fR\fBcnid_metad\fR\fB\fR\ 'u
-\fBcnid_metad\fR\fB\fR [\-l\ \fIloglevel\fR\ [\-f\ \fIfilename\fR]] [\-d] [\-h\ \fIhostname\fR] [\-p\ \fIport\fR] [\-u\ \fIuser\fR] [\-g\ \fIgroup\fR] [\-s\ \fIcnid_dbdpathname\fR]
+\fBcnid_metad\fR\fB\fR [\-d] [\-F\ \fIconfiguration\ file\fR]
 .br
 \fBcnid_metad\fR\fB\fR \-v | \-V 
 .SH "DESCRIPTION"
@@ -36,116 +36,22 @@ daemon\&. It keeps track of the status of a
 \fBcnid_dbd\fR
 instance once started and will restart it if necessary\&.
 \fBcnid_metad\fR
-is normally started at boot time from
-/etc/rc
-or equivalent and runs until shutdown\&.
-\fBafpd\fR
-needs to be configured with the
-\fB\-cnidserver\fR
-option in
-\fBafpd\&.conf\fR
-in order to access
-\fBcnid_metad\&.\fR
-It is possible to run more than one instance of
-\fBcnid_metad\fR
-on the same machine if different values for the interface and/or port are specified with the
-\fB\-h\fR
-and
-\fB\-p\fR
-options\&.
+is normally started at boot time by
+\fBnetatalk\fR(8) and runs until shutdown\&.
 .SH "OPTIONS"
 .PP
-\fB\-l\fR\fI <loglevel> [\-f <filename>]\fR
-.RS 4
-Specify that any message of a loglevel up to the given
-\fBloglevel\fR
-should be logged to the given file\&. If the filename is ommited the loglevel applies to messages passed to syslog\&. Default is logs to syslog with a default logging setup of
-\fB"log_note\fR"\&.
-.sp
-\fBNote:\fR
-\fBcnid_metad\fR
-passes this to
-\fBcnid_dbd\fR
-which will in turn use this for its logging setup\&.
-.sp
-loglevels: LOG_SEVERE, LOG_ERROR, LOG_WARN, LOG_NOTE, LOG_INFO, LOG_DEBUG, LOG_DEBUG6, LOG_DEBUG7, LOG_DEBUG8, LOG_DEBUG9, LOG_MAXDEBUG
-.PP
-\fBExample.\ \&Useful default config\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\-l log_info \-f /var/log/afpd\&.log
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-\fBExample.\ \&Debugging config\fR
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-\-l log_maxdebug \-f /var/log/afpd\&.log
-.fi
-.if n \{\
-.RE
-.\}
-.RE
-.PP
 \fB\-d\fR
 .RS 4
 \fBcnid_metad will remain in the foreground and\fR
 will also leave the standard input, standard output and standard error file descriptors open\&. Useful for debugging\&.
 .RE
 .PP
-\fB\-h\fR\fI hostname\fR
-.RS 4
-Use
-\fIhostname\fR
-as the network interface for requests as opposed to the default
-\fBlocalhost\fR\&. The network address may be specified either in dotted\-decimal format for IPv4 or in hexadecimal format for IPv6\&.
-.RE
-.PP
-\fB\-p\fR\fI port\fR
-.RS 4
-Use
-\fIport\fR
-as the port number for reqests\&. Default is 4700\&.
-.RE
-.PP
-\fB\-u\fR\fI user\fR
-.RS 4
-Switch to the userid of
-\fIuser\fR
-before serving requests\&. This userid will be inherited by all
-\fBcnid_dbd\fR
-daemon processes started\&.
-.RE
-.PP
-\fB\-g\fR\fI group\fR
-.RS 4
-Switch to the groupid of
-\fIgroup\fR
-before serving requests\&. This groupid will be inherited by all
-\fBcnid_dbd\fR
-daemon processes started\&. Both
-\fIuser\fR
-and
-\fIgroup\fR
-must be specified as strings\&.
-.RE
-.PP
-\fB\-s\fR\fI cnid_dbd pathname\fR
+\fB\-F\fR \fIconfiguration file\fR
 .RS 4
 Use
-\fIcnid_dbd pathname\fR
-as the pathname of the executeable of the
-\fBcnid_dbd\fR
-daemon\&. The default is
-\fI:SBINDIR:/cnid_dbd\&.\fR
+\fIconfiguration file\fR
+as the configuration file\&. The default is
+\fI:ETCDIR:/afp\&.conf\fR\&.
 .RE
 .PP
 \fB\-v, \-V\fR
@@ -154,10 +60,6 @@ Show version and exit\&.
 .RE
 .SH "CAVEATS"
 .PP
-The number of
-\fBcnid_dbd\fR
-subprocecesses is currently limited to 512\&.
-.PP
 \fBcnid_metad\fR
 does not block or catch any signals apart from SIGPIPE\&. It will therefore exit on most signals received\&. This will also cause all instances of
 \fBcnid_dbd\'s\fR
@@ -172,6 +74,8 @@ is restarted
 processes will transparently reconnect\&.
 .SH "SEE ALSO"
 .PP
+\fBnetatalk\fR(8),
 \fBcnid_dbd\fR(8),
 \fBafpd\fR(8),
-\fBdbd\fR(1)
+\fBdbd\fR(1),
+\fBafp.conf\fR(5)
diff --git a/man/man8/netatalk.8.tmpl b/man/man8/netatalk.8.tmpl
new file mode 100644 (file)
index 0000000..61cfffe
--- /dev/null
@@ -0,0 +1,64 @@
+'\" t
+.\"     Title: netatalk
+.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
+.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
+.\"      Date: 22 Mar 2012
+.\"    Manual: Netatalk 3.0
+.\"    Source: Netatalk 3.0
+.\"  Language: English
+.\"
+.TH "NETATALK" "8" "22 Mar 2012" "Netatalk 3.0" "Netatalk 3.0"
+.\" -----------------------------------------------------------------
+.\" * set default formatting
+.\" -----------------------------------------------------------------
+.\" disable hyphenation
+.nh
+.\" disable justification (adjust text to left margin only)
+.ad l
+.\" -----------------------------------------------------------------
+.\" * MAIN CONTENT STARTS HERE *
+.\" -----------------------------------------------------------------
+.SH "NAME"
+netatalk \- Netatalk AFP server service controller daemon
+.SH "SYNOPSIS"
+.HP \w'\fBnetatalk\fR\fB\fR\fBnetatalk\fR\fB\fR\ 'u
+\fBnetatalk\fR\fB\fR
+.br
+\fBnetatalk\fR\fB\fR
+.SH "DESCRIPTION"
+.PP
+\fBnetatalk\fR
+is the service controller daemon responsible for starting and restarting the AFP daemon
+\fBafpd\fR
+and the CNID daemon
+\fBcnid_metad\fR\&. It is normally started at boot time from /etc/rc\&.
+.SH "SIGNALS"
+.PP
+SIGTERM
+.RS 4
+Stop Netatalk service, AFP and CNID daemons
+.RE
+.PP
+SIGQUIT
+.RS 4
+Restart AFP and CNID master daemons, but keep all session AFP processes running\&. Can be used to implement
+AFP service without downtime\&.
+.RE
+.PP
+SIGHUP
+.RS 4
+Sending a
+\fBSIGHUP\fR
+will cause the AFP daemon reload its configuration file\&.
+.RE
+.SH "FILES"
+.PP
+:ETCDIR:/afp\&.conf
+.RS 4
+configuration file used by afpd and cnid_metad
+.RE
+.SH "SEE ALSO"
+.PP
+\fBafpd\fR(8),
+\fBcnid_metad\fR(8),
+\fBafp.conf\fR(5)\&.
diff --git a/man/man8/papd.8.tmpl b/man/man8/papd.8.tmpl
deleted file mode 100644 (file)
index c48cf80..0000000
+++ /dev/null
@@ -1,276 +0,0 @@
-'\" t
-.\"     Title: papd
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 06 September 2004
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "PAPD" "8" "06 September 2004" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-papd \- AppleTalk print server daemon
-.SH "SYNOPSIS"
-.HP \w'\fBpapd\fR\fB\fR\fB\fR\ 'u
-\fBpapd\fR\fB\fR\fB\fR [\-d] [\-f\ configfile] [\-p\ printcap]
-.SH "DESCRIPTION"
-.PP
-\fBpapd\fR
-is the AppleTalk printer daemon\&. This daemon accepts print jobs from AppleTalk clients (typically Macintosh computers) using the Printer Access Protocol (PAP)\&. When used with System V printing systems,
-\fBpapd\fR
-spools jobs directly into an
-\fBlpd\fR(8)
-spool directory and wakes up
-\fBlpd\fR
-after accepting a job from the network to have it re\-examine the appropriate spool directory\&. The actual printing and spooling is handled entirely by
-\fBlpd\fR\&.
-.PP
-\fBpapd\fR
-can also pipe the print job to an external program for processing, and this is the preferred method on systems not using CUPS to avoid compatibility problems with all the flavours of
-\fBlpd\fR
-in use\&.
-.PP
-As of version 2\&.0, CUPS is also supported\&. Simply using
-\fBcupsautoadd\fR
-as first papd\&.conf entry will share all CUPS printers automagically using the PPD files configured in CUPS\&. It ist still possible to overwrite these defaults by individually define printer shares\&. See
-\fBpapd.conf\fR(5)
-for details\&.
-.PP
-\fBpapd\fR
-is typically started at boot time, out of system init scripts\&. It first reads from its configuration file,
-:ETCDIR:/papd\&.conf\&. The file is in the same format as
-/etc/printcap\&. See
-\fBprintcap\fR(5)
-for details\&. The name of the entry is registered with NBP\&.
-.PP
-The following options are supported:
-.TS
-tab(:);
-cB cB cB nB.
-T{
-Name
-T}:T{
-Type
-T}:T{
-Default
-T}:T{
-Description
-T}
-.T&
-c l l l
-c l l l
-c l l l
-c l l l
-c l l l
-c l l l
-c l l l
-c l l l
-c l l l
-c l l l.
-T{
-pd
-T}:T{
-str
-T}:T{
-\'\&.ppd\'
-T}:T{
-Pathname to PPD file
-T}
-T{
-pr
-T}:T{
-str
-T}:T{
-\'lp\'
-T}:T{
-LPD or CUPS printer name (or pipe to a print
-              command)
-T}
-T{
-op
-T}:T{
-str
-T}:T{
-\'operator\'
-T}:T{
-Operator name for LPD spooling
-T}
-T{
-au
-T}:T{
-bool
-T}:T{
-false
-T}:T{
-Whether to do authenticated printing or not
-T}
-T{
-ca
-T}:T{
-str
-T}:T{
-NULL
-T}:T{
-Pathname used for CAP\-style authentification
-T}
-T{
-sp
-T}:T{
-bool
-T}:T{
-false
-T}:T{
-PSSP\-style authetication
-T}
-T{
-am
-T}:T{
-str
-T}:T{
-NULL
-T}:T{
-UAMS to use for authentication
-T}
-T{
-pa
-T}:T{
-str
-T}:T{
-NULL
-T}:T{
-Printer\'s AppleTalk address
-T}
-T{
-co
-T}:T{
-str
-T}:T{
-NULL
-T}:T{
-CUPS options as supplied to the \fBlp\fR(1) command with "\-o"
-T}
-T{
-fo
-T}:T{
-bool
-T}:T{
-false
-T}:T{
-adjust lineending for foomatic\-rip
-T}
-.TE
-.sp 1
-If no configuration file is given, the hostname of the machine is used as the NBP name and all options take their default value\&.
-.SH "OPTIONS"
-.PP
-\-d
-.RS 4
-Do not fork or disassociate from the terminal\&. Write some debugging information to stderr\&.
-.RE
-.PP
-\-f \fIconfigfile\fR
-.RS 4
-Consult
-\fIconfigfile\fR
-instead of
-:ETCDIR:/papd\&.conf
-for the configuration information\&.
-.RE
-.PP
-\-p \fIprintcap\fR
-.RS 4
-Consult
-\fIprintcap\fR
-instead of
-/etc/printcap
-for LPD configuration information\&.
-.RE
-.SH "NOTES"
-.PP
-PSSP
-(Print Server Security Protocol) is an authentication protocol
-carried out through postscript printer queries to the print server\&. Using PSSP requires LaserWriter 8\&.6\&.1 or greater on the client mac\&. The user will be prompted to enter their username and password before they print\&. It may be necessary to re\-setup the printer on each client the first time PSSP is enabled, so that the client can figure out that authentication is required to print\&. You can enable PSSP on a per\-printer basis\&. PSSP is the recommended method of authenticating printers as it is more robust than CAP\-style authentication, described below\&.
-.PP
-CAP\-style authentication
-gets its name from the method the CAP (Columbia APpletalk) package used to authenticate its mac clients\' printing\&. This method requires that a user login to a file share before they print\&.
-\fBafpd\fR
-records the username in a temporary file named after the client\'s Appletalk address, and it deletes the temporary file when the user disconnects\&. Therefore CAP style authentification will
-\fInot\fR
-work for clients connected to
-\fBafpd\fR
-via TCP/IP\&.
-\fBpapd\fR
-gets the username from the file with the same Appletalk address as the machine connecting to it\&. CAP\-style authentication will work with any mac client\&. If both CAP and PSSP are enabled for a particular printer, CAP will be tried first, then
-\fBpapd\fR
-will fall back to PSSP\&.
-.PP
-The list of UAMs to use for authentication (specified with the \'am\' option) applies to all printers\&. It is not possible to define different authentication methods on each printer\&. You can specify the list of UAMS multiple times, but only the last setting will be used\&. Currently only uams_guest\&.so and uams_clrtxt\&.so are supported as printer authentication methods\&. The guest method requires a valid username, but not a password\&. The Cleartext UAM requires both a valid username and the correct password\&.
-.if n \{\
-.sp
-.\}
-.RS 4
-.it 1 an-trap
-.nr an-no-space-flag 1
-.nr an-break-flag 1
-.br
-.ps +1
-\fBNote\fR
-.ps -1
-.br
-.PP
-As of this writing, Mac OS X makes no use of PSSP authentication any longer\&. CAP\-style authentication normally won\'t be an option, too caused by the use of AFP over TCP these days\&.
-.sp .5v
-.RE
-.PP
-.SH "FILES"
-.PP
-:ETCDIR:/papd\&.conf
-.RS 4
-Default configuration file\&.
-.RE
-.PP
-/etc/printcap
-.RS 4
-Printer capabilities database\&.
-.RE
-.PP
-\&.ppd
-.RS 4
-PostScript Printer Description file\&. papd answers configuration and font queries from printing clients by consulting the configured PPD file\&. Such files are available for download from Adobe, Inc\&. (\m[blue]\fBhttp://www\&.adobe\&.com/support/downloads/main\&.htm\fR\m[]\&\s-2\u[1]\d\s+2), or from the printer\'s manufacturer\&. If no PPD file is configured, papd will return the default answer, possibly causing the client to send excessively large jobs\&.
-.RE
-.SH "CAVEATS"
-.PP
-\fBpapd\fR
-accepts characters with the high bit set (a full 8\-bits) from the clients, but some PostScript printers (including Apple Computer\'s LaserWriter family) only accept 7\-bit characters on their serial interface by default\&. The same applies for some printers when they\'re accessed via TCP/IP methods (remote LPR or socket)\&. You will need to configure your printer to accept a full 8 bits or take special precautions and convert the printjob\'s encoding (eg\&. by using
-\fBco="protocol=BCP"\fR
-when using CUPS 1\&.1\&.19 or above)\&.
-.PP
-When printing clients run MacOS 10\&.2 or above, take care that PPDs do not make use of
-\fB*cupsFilter:\fR
-comments unless the appropriate filters are installed at the client\'s side, too (remember: Starting with 10\&.2 Apple chose to integrate CUPS into MacOS X)\&. For in\-depth information on how CUPS uses PPDs see chapter 3\&.4 in
-\m[blue]\fBhttp://tinyurl\&.com/zbxn\fR\m[]\&\s-2\u[2]\d\s+2)\&.
-.SH "SEE ALSO"
-.PP
-\fBlpr\fR(1),\fBlprm\fR(1),\fBprintcap\fR(5),\fBlpc\fR(8),\fBlpd\fR(8),
-\fBlp\fR(1)\&.
-.SH "NOTES"
-.IP " 1." 4
-http://www.adobe.com/support/downloads/main.htm
-.RS 4
-\%http://www.adobe.com/support/downloads/main.html#Printer
-.RE
-.IP " 2." 4
-http://tinyurl.com/zbxn
-.RS 4
-\%http://tinyurl.com/zbxn
-.RE
diff --git a/man/man8/papstatus.8.tmpl b/man/man8/papstatus.8.tmpl
deleted file mode 100644 (file)
index d0bc11d..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-'\" t
-.\"     Title: papstatus
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 17 Dec 1991
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "PAPSTATUS" "8" "17 Dec 1991" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-papstatus \- get the status of an AppleTalk\-connected printer
-.SH "SYNOPSIS"
-.HP \w'\fB:SBINDIR:/papstatus\fR\fB\fR\ 'u
-\fB:SBINDIR:/papstatus\fR\fB\fR [\-d] [\-p\ \fIprinter\fR] [\fIretrytime\fR]
-.SH "DESCRIPTION"
-.PP
-\fBpapstatus\fR
-is used to obtain the current status message from an AppleTalk connected printer\&. It uses the Printer Access Protocol (PAP) to obtain the status information\&.
-.PP
-If no printer is specified on the command line,
-\fBpapstatus\fR
-looks for a file called
-\fB\&.paprc\fR
-in the current directory and reads it to obtain the name of a printer\&. The
-\fB\&.paprc\fR
-file should contain a single line of the form
-\fIobject\fR\fB:\fR\fItype\fR\fB@\fR\fIzone\fR
-where each of
-\fIobject\fR,
-\fB:\fR\fItype\fR\fB,\fR
-and
-\fB@\fR\fIzone\fR
-are optional\&.
-\fItype\fR
-and
-\fIzone\fR
-must be proceeded by `\fB:\fR\' and `\fB@\fR\' respectively\&. Blank lines and lines the begin with a `\fB#\fR\' are ignored\&.
-\fItype\fR
-and
-\fIzone\fR
-default to
-\fBLaserWriter\fR
-and the zone of the local host, respectively\&.
-.SH "OPTIONS"
-.PP
-\fB\-d\fR
-.RS 4
-Turns on a debugging mode that prints some extra information to standard error\&.
-.RE
-.PP
-\fB\-p\fR \fIprinter\fR
-.RS 4
-Get status from
-\fIprinter\fR
-(do not consult any
-\fB\&.paprc\fR
-files to find a printer name)\&. The syntax for
-\fIprinter\fR
-is the same as discussed above for the
-\fB\&.paprc\fR
-file\&.
-.RE
-.PP
-\fIretrytime\fR
-.RS 4
-Normally,
-\fBpapstatus\fR
-only gets the status from the printer once\&. If
-\fIretrytime\fR
-is specified, the status is obtained repeatedly, with a sleep of
-\fIretrytime\fR
-seconds between inquiring the printer\&.
-.RE
-.SH "FILES"
-.PP
-\fB\&.paprc\fR
-.RS 4
-file that contains printer name
-.RE
-.SH "SEE ALSO"
-.PP
-\fBnbp\fR(1),
-\fBpap\fR(1)
diff --git a/man/man8/psf.8.tmpl b/man/man8/psf.8.tmpl
deleted file mode 100644 (file)
index ed9f59e..0000000
+++ /dev/null
@@ -1,115 +0,0 @@
-'\" t
-.\"     Title: psf
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 17 Dec 1991
-.\"    Manual: Netatalk 2.2
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "PSF" "8" "17 Dec 1991" "Netatalk 2.2" "Netatalk 2.2"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-psf \- PostScript filter
-.SH "SYNOPSIS"
-.HP \w'\fBpsf\fR\fB\fR\ 'u
-\fBpsf\fR\fB\fR [\-n\ \fIname\fR] [\-h\ \fIhost\fR] [\-w\ \fIwidth\fR] [\-l\ \fIlength\fR] [\-i\ \fIindent\fR] [\-c]
-.SH "DESCRIPTION"
-.PP
-\fBpsf\fR
-is an
-\fBlpd\fR
-filter for PostScript printing\&.
-\fBpsf\fR
-interprets the name it was called with to determine what filters to invoke\&. First, if the string ``pap\'\' appears anywhere in the name,
-\fBpsf\fR
-invokes
-\fBpap\fR
-to talk to a printer via AppleTalk\&. Next, if the string ``rev\'\' appears,
-\fBpsf\fR
-invokes
-\fBpsorder\fR
-to reverse the pages of the job\&. Finally, if
-\fBpsf\fR
-was called with a filter\'s name as the leading string, it invokes that filter\&. If there is no filter to run,
-\fBpsf\fR
-examines the magic number of the input, and if the input is not PostScript, converts it to PostScript\&.
-.SH "KLUDGE"
-.PP
-In the default configuration,
-\fBpsf\fR
-supports two kludges\&. The first causes
-\fBpsf\fR
-to check its name for the letter `m\'\&. If this letter is found and accounting is turned on,
-\fBpsf\fR
-calls
-\fBpap\fR
-twice, once to get an initial page count and to print the job, and another time to get a final page count\&. This is a work\-around for bugs in a variety of PAP implementions that cause printers to never properly close the PAP output file\&. A notable example is any printer by Hewlett\-Packard\&.
-.PP
-The second kludge causes
-\fBpsf\fR
-to examine its name for the letter `w\'\&. If this letter is found and accounting is turned on,
-\fBpsf\fR
-calls
-\fBpap\fR
-with the
-\fB\-w\fR
-flag\&. This flag causes
-\fBpap\fR
-to wait until the printer\'s status contains the string `idle\'\&. Once this string is found, the job is printed as normal\&. This kludge is a work\-around for printers, notably Hewlett\-Packard\'s LaserJet IV, which will report a page count while a previous jobs is still printing\&.
-.SH "EXAMPLE"
-.PP
-The sample
-\fBprintcap\fR
-entry below invokes
-\fBpsf\fR
-to print text files, PostScript files,
-\fBtroff\fR\'s C/A/T output, and
-\fBTeX\fR\'s DVI output, to an AppleTalk connected LaserWriter Plus\&. Since the LaserWriter Plus stacks pages in descending order, we reverse the pages and print the burst page last\&.
-.sp
-.if n \{\
-.RS 4
-.\}
-.nf
-laser|lp|LaserWriter Plus on AppleTalk:\e
-    :sd=/usr/spool/lpd/laser:\e
-    :lp=/usr/spool/lpd/laser/null:\e
-    :lf=/var/adm/lpd\-errs:pw#80:hl:\e
-    :of=:LIBEXECDIR:/ofpap:\e
-    :if=:LIBEXECDIR:/ifpaprev:\e
-    :tf=:LIBEXECDIR:/tfpaprev:\e
-    :df=:LIBEXECDIR:/dfpaprev:
-.fi
-.if n \{\
-.RE
-.\}
-.PP
-Note that if the host in question spools to more than one AppleTalk printer,
-/dev/null
-should not be used for the
-\fBlp\fR
-capability\&. Instead, a null device should be created with
-\fBmknod\fR
-for each printer, as has been done above\&.
-.PP
-Finally, there is a file in the spool directory,
-/var/spool/lpd/laser, called
-\fB\&.paprc\fR, which
-\fBpap\fR
-reads for the AppleTalk name of the printer\&.
-.SH "SEE ALSO"
-.PP
-\fBpsorder\fR(1),
-\fBprintcap\fR(5),
-\fBlpd\fR(1),
-\fBmknod\fR(1),
-\fBpap\fR(1)\&.
diff --git a/man/man8/timelord.8 b/man/man8/timelord.8
deleted file mode 100644 (file)
index 1496486..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-'\" t
-.\"     Title: timelord
-.\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
-.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: 27 Jun 2001
-.\"    Manual: The Netatalk Project
-.\"    Source: Netatalk 2.2
-.\"  Language: English
-.\"
-.TH "TIMELORD" "8" "27 Jun 2001" "Netatalk 2.2" "The Netatalk Project"
-.\" -----------------------------------------------------------------
-.\" * set default formatting
-.\" -----------------------------------------------------------------
-.\" disable hyphenation
-.nh
-.\" disable justification (adjust text to left margin only)
-.ad l
-.\" -----------------------------------------------------------------
-.\" * MAIN CONTENT STARTS HERE *
-.\" -----------------------------------------------------------------
-.SH "NAME"
-timelord \- Macintosh time server daemon
-.SH "SYNOPSIS"
-.SH "SYNTAX"
-.PP
-timelord [\-d] [\-n
-\fIfilename\fR]
-.SH "DESCRIPTION"
-.PP
-\fBtimelord\fR
-is a simple time server for Macintosh computers that use the
-\fBtardis\fR
-client\&.
-.SH "OPTIONS"
-.PP
-\fB\-d\fR
-.RS 4
-Debug mode, i\&.e\&. don\'t disassociate from controlling TTY\&.
-.RE
-.PP
-\fB\-n\fR \fInbpname\fR
-.RS 4
-Register this server as
-\fInbpname\fR\&. This defaults to the hostname\&.
-.RE
diff --git a/services.atalk b/services.atalk
deleted file mode 100644 (file)
index 2d8555e..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-rtmp           1/ddp           # Routing Table Maintenance Protocol
-nbp            2/ddp           # Name Binding Protocol
-echo           4/ddp           # AppleTalk Echo Protocol
-zip            6/ddp           # Zone Information Protocol
-
-afpovertcp     548/tcp         # AFP over TCP
-afpovertcp     548/udp
diff --git a/sys/.gitignore b/sys/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/sys/Makefile.am b/sys/Makefile.am
deleted file mode 100644 (file)
index 4472c8f..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-# Makefile.am for sys/
-
-SUBDIRS = netatalk generic solaris netbsd sunos ultrix
diff --git a/sys/generic/.gitignore b/sys/generic/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/sys/generic/Makefile.am b/sys/generic/Makefile.am
deleted file mode 100644 (file)
index 081839c..0000000
+++ /dev/null
@@ -1 +0,0 @@
-SUBDIRS = sys
diff --git a/sys/generic/sys/.gitignore b/sys/generic/sys/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/sys/generic/sys/Makefile.am b/sys/generic/sys/Makefile.am
deleted file mode 100644 (file)
index 187947d..0000000
+++ /dev/null
@@ -1 +0,0 @@
-EXTRA_DIST = cdefs.h
diff --git a/sys/generic/sys/cdefs.h b/sys/generic/sys/cdefs.h
deleted file mode 100644 (file)
index c24481c..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * $Id: cdefs.h,v 1.4 2001-08-15 15:29:14 srittau Exp $
- */
-
-#ifndef _SYS_CDEFS_H
-#define _SYS_CDEFS_H 1
-
-#if defined(__STDC__) || defined(__DECC)
-/* Note that there must be exactly one space between __P(args) and args,
- * otherwise DEC C chokes.
- */
-#define __P(args) args
-#else /* __STDC__ */
-#define __P(args)    ()
-#endif /* __STDC__ */
-
-#endif /* sys/cdefs.h */
diff --git a/sys/netatalk/.gitignore b/sys/netatalk/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/sys/netatalk/Makefile.am b/sys/netatalk/Makefile.am
deleted file mode 100644 (file)
index 14eeab7..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-# Makefile.am for sys/netatalk/
-
-pkginclude_HEADERS = aarp.h at.h at_var.h ddp.h ddp_var.h endian.h phase2.h
-
-SOURCES = aarp.c at_control.c at_proto.c ddp_input.c ddp_output.c ddp_usrreq.c
-
-EXTRA_DIST = $(SOURCES)
diff --git a/sys/netatalk/aarp.c b/sys/netatalk/aarp.c
deleted file mode 100644 (file)
index ee18845..0000000
+++ /dev/null
@@ -1,802 +0,0 @@
-/*
- * $Id: aarp.c,v 1.3 2002-01-03 17:49:39 sibaz Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <syslog.h>
-#include <sys/param.h>
-#include <sys/mbuf.h>
-#include <sys/time.h>
-#ifndef _IBMR2
-#include <sys/kernel.h>
-#endif /* _IBMR2 */
-#include <net/if.h>
-#include <net/route.h>
-#include <net/af.h>
-#include <netinet/in.h>
-#undef s_net
-#include <netinet/if_ether.h>
-#ifdef _IBMR2
-#include <netinet/in_netarp.h>
-#include <net/spl.h>
-#include <sys/errno.h>
-#include <sys/err_rec.h>
-#endif /* _IBMR2 */
-
-#include "at.h"
-#include "at_var.h"
-#include "aarp.h"
-#include "ddp_var.h"
-#include "endian.h"
-#include "phase2.h"
-
-#ifdef GATEWAY
-#define AARPTAB_BSIZ   16
-#define AARPTAB_NB     37
-#else /* GATEWAY */
-#define AARPTAB_BSIZ   9
-#define AARPTAB_NB     19
-#endif /* GATEWAY */
-#define AARPTAB_SIZE   (AARPTAB_BSIZ * AARPTAB_NB)
-struct aarptab         aarptab[AARPTAB_SIZE];
-int                    aarptab_size = AARPTAB_SIZE;
-
-#define AARPTAB_HASH(a) \
-    ((((a).s_net << 8 ) + (a).s_node ) % AARPTAB_NB )
-
-#define AARPTAB_LOOK(aat,addr) { \
-    int                n; \
-    aat = &aarptab[ AARPTAB_HASH(addr) * AARPTAB_BSIZ ]; \
-    for ( n = 0; n < AARPTAB_BSIZ; n++, aat++ ) \
-       if ( aat->aat_ataddr.s_net == (addr).s_net && \
-            aat->aat_ataddr.s_node == (addr).s_node ) \
-           break; \
-       if ( n >= AARPTAB_BSIZ ) \
-           aat = 0; \
-}
-
-#define AARPT_AGE      (60 * 1)
-#define AARPT_KILLC    20
-#define AARPT_KILLI    3
-
-#ifdef sun
-extern struct ether_addr       etherbroadcastaddr;
-#else /* sun */
-extern u_char                  etherbroadcastaddr[6];
-#endif /* sun */
-
-u_char atmulticastaddr[ 6 ] = {
-    0x09, 0x00, 0x07, 0xff, 0xff, 0xff,
-};
-
-u_char at_org_code[ 3 ] = {
-    0x08, 0x00, 0x07,
-};
-u_char aarp_org_code[ 3 ] = {
-    0x00, 0x00, 0x00,
-};
-
-aarptimer()
-{
-    struct aarptab     *aat;
-    int                        i, s;
-
-    timeout( aarptimer, (caddr_t)0, AARPT_AGE * hz );
-    aat = aarptab;
-    for ( i = 0; i < AARPTAB_SIZE; i++, aat++ ) {
-       if ( aat->aat_flags == 0 || ( aat->aat_flags & ATF_PERM ))
-           continue;
-       if ( ++aat->aat_timer < (( aat->aat_flags & ATF_COM ) ?
-               AARPT_KILLC : AARPT_KILLI ))
-           continue;
-       s = splimp();
-       aarptfree( aat );
-       splx( s );
-    }
-}
-
-struct ifaddr *
-at_ifawithnet( sat, ifa )
-    struct sockaddr_at *sat;
-    struct ifaddr      *ifa;
-{
-    struct at_ifaddr   *aa;
-
-    for (; ifa; ifa = ifa->ifa_next ) {
-#ifdef BSD4_4
-       if ( ifa->ifa_addr->sa_family != AF_APPLETALK ) {
-           continue;
-       }
-       if ( satosat( ifa->ifa_addr )->sat_addr.s_net ==
-               sat->sat_addr.s_net ) {
-           break;
-       }
-#else /* BSD4_4 */
-       if ( ifa->ifa_addr.sa_family != AF_APPLETALK ) {
-           continue;
-       }
-       aa = (struct at_ifaddr *)ifa;
-       if ( ntohs( sat->sat_addr.s_net ) >= ntohs( aa->aa_firstnet ) &&
-               ntohs( sat->sat_addr.s_net ) <= ntohs( aa->aa_lastnet )) {
-           break;
-       }
-#endif /* BSD4_4 */
-    }
-    return( ifa );
-}
-
-aarpwhohas( ac, sat )
-    struct arpcom      *ac;
-    struct sockaddr_at *sat;
-{
-    struct mbuf                *m;
-    struct ether_header        *eh;
-    struct ether_aarp  *ea;
-    struct at_ifaddr   *aa;
-    struct llc         *llc;
-    struct sockaddr    sa;
-
-#ifdef BSD4_4
-    if (( m = m_gethdr( M_DONTWAIT, MT_DATA )) == NULL ) {
-       return;
-    }
-    m->m_len = sizeof( *ea );
-    m->m_pkthdr.len = sizeof( *ea );
-    MH_ALIGN( m, sizeof( *ea ));
-#else /* BSD4_4 */
-    if (( m = m_get( M_DONTWAIT, MT_DATA )) == NULL ) {
-       return;
-    }
-    m->m_len = sizeof( *ea );
-    m->m_off = MMAXOFF - sizeof( *ea );
-#endif /* BSD4_4 */
-
-    ea = mtod( m, struct ether_aarp *);
-    bzero((caddr_t)ea, sizeof( *ea ));
-
-    ea->aarp_hrd = htons( AARPHRD_ETHER );
-    ea->aarp_pro = htons( ETHERTYPE_AT );
-    ea->aarp_hln = sizeof( ea->aarp_sha );
-    ea->aarp_pln = sizeof( ea->aarp_spu );
-    ea->aarp_op = htons( AARPOP_REQUEST );
-#ifdef sun
-    bcopy((caddr_t)&ac->ac_enaddr, (caddr_t)ea->aarp_sha,
-           sizeof( ea->aarp_sha ));
-#else /* sun */
-    bcopy((caddr_t)ac->ac_enaddr, (caddr_t)ea->aarp_sha,
-           sizeof( ea->aarp_sha ));
-#endif /* sun */
-
-    /*
-     * We need to check whether the output ethernet type should
-     * be phase 1 or 2. We have the interface that we'll be sending
-     * the aarp out. We need to find an AppleTalk network on that
-     * interface with the same address as we're looking for. If the
-     * net is phase 2, generate an 802.2 and SNAP header.
-     */
-    if (( aa = (struct at_ifaddr *)at_ifawithnet( sat, ac->ac_if.if_addrlist ))
-           == NULL ) {
-       m_freem( m );
-       return;
-    }
-
-    eh = (struct ether_header *)sa.sa_data;
-
-    if ( aa->aa_flags & AFA_PHASE2 ) {
-#ifdef sun
-       bcopy((caddr_t)atmulticastaddr, (caddr_t)&eh->ether_dhost,
-               sizeof( eh->ether_dhost ));
-#else /* sun */
-       bcopy((caddr_t)atmulticastaddr, (caddr_t)eh->ether_dhost,
-               sizeof( eh->ether_dhost ));
-#endif /* sun */
-#if defined( sun ) && defined( i386 )
-       eh->ether_type = htons( sizeof( struct llc ) +
-               sizeof( struct ether_aarp ));
-#else /* sun && i386 */
-       eh->ether_type = sizeof( struct llc ) + sizeof( struct ether_aarp );
-#endif /* sun && i386 */
-#ifdef BSD4_4
-       M_PREPEND( m, sizeof( struct llc ), M_WAIT );
-#else /* BSD4_4 */
-       m->m_len += sizeof( struct llc );
-       m->m_off -= sizeof( struct llc );
-#endif /* BSD4_4 */
-       llc = mtod( m, struct llc *);
-       llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
-       llc->llc_control = LLC_UI;
-       bcopy( aarp_org_code, llc->llc_org_code, sizeof( aarp_org_code ));
-       llc->llc_ether_type = htons( ETHERTYPE_AARP );
-
-       
-       bcopy( &AA_SAT( aa )->sat_addr.s_net, ea->aarp_spnet,
-               sizeof( ea->aarp_spnet ));
-       ea->aarp_spnode = AA_SAT( aa )->sat_addr.s_node;
-       bcopy( &sat->sat_addr.s_net, ea->aarp_tpnet,
-               sizeof( ea->aarp_tpnet ));
-       ea->aarp_tpnode = sat->sat_addr.s_node;
-    } else {
-#ifdef sun
-       bcopy((caddr_t)&etherbroadcastaddr, (caddr_t)&eh->ether_dhost,
-               sizeof( eh->ether_dhost ));
-#else /* sun */
-       bcopy((caddr_t)etherbroadcastaddr, (caddr_t)eh->ether_dhost,
-               sizeof( eh->ether_dhost ));
-#endif /* sun */
-#if defined( sun ) && defined( i386 )
-       eh->ether_type = htons( ETHERTYPE_AARP );
-#else /* sun && i386 */
-       eh->ether_type = ETHERTYPE_AARP;
-#endif /* sun && i386 */
-
-       ea->aarp_spa = AA_SAT( aa )->sat_addr.s_node;
-       ea->aarp_tpa = sat->sat_addr.s_node;
-    }
-
-#ifdef BSD4_4
-    sa.sa_len = sizeof( struct sockaddr );
-#endif /* BSD4_4 */
-    sa.sa_family = AF_UNSPEC;
-    (*ac->ac_if.if_output)(&ac->ac_if, m, &sa );
-}
-
-aarpresolve( ac, m, destsat, desten )
-    struct arpcom      *ac;
-    struct mbuf                *m;
-    struct sockaddr_at *destsat;
-#ifdef sun
-    struct ether_addr  *desten;
-#else /* sun */
-    u_char             *desten;
-#endif /* sun */
-{
-    struct at_ifaddr   *aa;
-    struct ifaddr      ifa;
-    struct aarptab     *aat;
-    int                        s;
-
-    if ( at_broadcast( destsat )) {
-       if (( aa = (struct at_ifaddr *)at_ifawithnet( destsat,
-               ((struct ifnet *)ac)->if_addrlist )) == NULL ) {
-           m_freem( m );
-           return( 0 );
-       }
-       if ( aa->aa_flags & AFA_PHASE2 ) {
-           bcopy( (caddr_t)atmulticastaddr, (caddr_t)desten,
-                   sizeof( atmulticastaddr ));
-       } else {
-#ifdef sun
-           bcopy( (caddr_t)&etherbroadcastaddr, (caddr_t)desten,
-                   sizeof( etherbroadcastaddr ));
-#else /* sun */
-           bcopy( (caddr_t)etherbroadcastaddr, (caddr_t)desten,
-                   sizeof( etherbroadcastaddr ));
-#endif /* sun */
-       }
-       return( 1 );
-    }
-
-    s = splimp();
-    AARPTAB_LOOK( aat, destsat->sat_addr );
-    if ( aat == 0 ) {                  /* No entry */
-       aat = aarptnew( &destsat->sat_addr );
-       if ( aat == 0 ) {
-           panic( "aarpresolve: no free entry" );
-       }
-       aat->aat_hold = m;
-       aarpwhohas( ac, destsat );
-       splx( s );
-       return( 0 );
-    }
-    /* found an entry */
-    aat->aat_timer = 0;
-    if ( aat->aat_flags & ATF_COM ) {  /* entry is COMplete */
-       bcopy( (caddr_t)aat->aat_enaddr, (caddr_t)desten,
-               sizeof( aat->aat_enaddr ));
-       splx( s );
-       return( 1 );
-    }
-    /* entry has not completed */
-    if ( aat->aat_hold ) {
-       m_freem( aat->aat_hold );
-    }
-    aat->aat_hold = m;
-    aarpwhohas( ac, destsat );
-    splx( s );
-    return( 0 );
-}
-
-aarpinput( ac, m )
-    struct arpcom      *ac;
-    struct mbuf                *m;
-{
-    struct arphdr      *ar;
-
-    if ( ac->ac_if.if_flags & IFF_NOARP )
-       goto out;
-
-#ifndef BSD4_4
-    IF_ADJ( m );
-#endif /* BSD4_4 */
-
-    if ( m->m_len < sizeof( struct arphdr )) {
-       goto out;
-    }
-
-    ar = mtod( m, struct arphdr *);
-    if ( ntohs( ar->ar_hrd ) != AARPHRD_ETHER ) {
-       goto out;
-    }
-    
-    if ( m->m_len < sizeof( struct arphdr ) + 2 * ar->ar_hln +
-           2 * ar->ar_pln ) {
-       goto out;
-    }
-    
-    switch( ntohs( ar->ar_pro )) {
-    case ETHERTYPE_AT :
-       at_aarpinput( ac, m );
-       return;
-
-    default:
-       break;
-    }
-
-out:
-    m_freem( m );
-}
-
-
-at_aarpinput( ac, m )
-    struct arpcom      *ac;
-    struct mbuf                *m;
-{
-    struct mbuf                *m0;
-    struct ether_aarp  *ea;
-    struct at_ifaddr   *aa;
-    struct aarptab     *aat;
-    struct ether_header        *eh;
-    struct llc         *llc;
-    struct sockaddr_at sat;
-    struct sockaddr    sa;
-    struct at_addr     spa, tpa, ma;
-    int                        op, s;
-    u_short            net;
-
-    ea = mtod( m, struct ether_aarp *);
-
-    /* Check to see if from my hardware address */
-#ifdef sun
-    if ( !bcmp(( caddr_t )ea->aarp_sha, ( caddr_t )&ac->ac_enaddr,
-           sizeof( ac->ac_enaddr ))) {
-       m_freem( m );
-       return;
-    }
-#else /* sun */
-    if ( !bcmp(( caddr_t )ea->aarp_sha, ( caddr_t )ac->ac_enaddr,
-           sizeof( ac->ac_enaddr ))) {
-       m_freem( m );
-       return;
-    }
-#endif /* sun */
-
-    /*
-     * Check if from broadcast address.  This could be a more robust
-     * check, since we could look for multicasts.
-     */
-#ifdef sun
-    if ( !bcmp(( caddr_t )ea->aarp_sha, ( caddr_t )&etherbroadcastaddr,
-           sizeof( etherbroadcastaddr ))) {
-       log( LOG_ERR, "aarp: source is broadcast!\n" );
-       m_freem( m );
-       return;
-    }
-#else /* sun */
-    if ( !bcmp(( caddr_t )ea->aarp_sha, ( caddr_t )etherbroadcastaddr,
-           sizeof( etherbroadcastaddr ))) {
-#ifndef _IBMR2
-#ifdef ultrix
-       mprintf( LOG_ERR,
-#else /* ultrix */
-       log( LOG_ERR,
-#endif /* ultrix */
-               "aarp: source is broadcast!\n" );
-#endif /* ! _IBMR2 */
-       m_freem( m );
-       return;
-    }
-#endif /* sun */
-
-    op = ntohs( ea->aarp_op );
-    bcopy( ea->aarp_tpnet, &net, sizeof( net ));
-
-    if ( net != 0 ) {
-       sat.sat_family = AF_APPLETALK;
-       sat.sat_addr.s_net = net;
-       if (( aa = (struct at_ifaddr *)at_ifawithnet( &sat,
-               ac->ac_if.if_addrlist )) == NULL ) {
-           m_freem( m );
-           return;
-       }
-       bcopy( ea->aarp_spnet, &spa.s_net, sizeof( spa.s_net ));
-       bcopy( ea->aarp_tpnet, &tpa.s_net, sizeof( tpa.s_net ));
-    } else {
-       /*
-        * Since we don't know the net, we just look for the first
-        * phase 1 address on the interface.
-        */
-       for ( aa = (struct at_ifaddr *)ac->ac_if.if_addrlist; aa;
-               aa = (struct at_ifaddr *)aa->aa_ifa.ifa_next ) {
-           if ( AA_SAT( aa )->sat_family == AF_APPLETALK &&
-                   ( aa->aa_flags & AFA_PHASE2 ) == 0 ) {
-               break;
-           }
-       }
-       if ( aa == NULL ) {
-           m_freem( m );
-           return;
-       }
-       tpa.s_net = spa.s_net = AA_SAT( aa )->sat_addr.s_net;
-    }
-
-    spa.s_node = ea->aarp_spnode;
-    tpa.s_node = ea->aarp_tpnode;
-    ma.s_net = AA_SAT( aa )->sat_addr.s_net;
-    ma.s_node = AA_SAT( aa )->sat_addr.s_node;
-
-    /*
-     * This looks like it's from us.
-     */
-    if ( spa.s_net == ma.s_net && spa.s_node == ma.s_node ) {
-       if ( aa->aa_flags & AFA_PROBING ) {
-           /*
-            * We're probing, someone either responded to our probe, or
-            * probed for the same address we'd like to use. Change the
-            * address we're probing for.
-            */
-           untimeout( aarpprobe, ac );
-           wakeup( aa );
-           m_freem( m );
-           return;
-       } else if ( op != AARPOP_PROBE ) {
-           /*
-            * This is not a probe, and we're not probing. This means
-            * that someone's saying they have the same source address
-            * as the one we're using. Get upset...
-            */
-#ifndef _IBMR2
-#ifdef ultrix
-           mprintf( LOG_ERR,
-#else /* ultrix */
-           log( LOG_ERR,
-#endif /* ultrix */
-                   "aarp: duplicate AT address!! %x:%x:%x:%x:%x:%x\n",
-                   ea->aarp_sha[ 0 ], ea->aarp_sha[ 1 ], ea->aarp_sha[ 2 ],
-                   ea->aarp_sha[ 3 ], ea->aarp_sha[ 4 ], ea->aarp_sha[ 5 ]);
-#endif /* ! _IBMR2 */
-           m_freem( m );
-           return;
-       }
-    }
-
-    AARPTAB_LOOK( aat, spa );
-    if ( aat ) {
-       if ( op == AARPOP_PROBE ) {
-           /*
-            * Someone's probing for spa, dealocate the one we've got,
-            * so that if the prober keeps the address, we'll be able
-            * to arp for him.
-            */
-           aarptfree( aat );
-           m_freem( m );
-           return;
-       }
-
-       bcopy(( caddr_t )ea->aarp_sha, ( caddr_t )aat->aat_enaddr,
-               sizeof( ea->aarp_sha ));
-       aat->aat_flags |= ATF_COM;
-       if ( aat->aat_hold ) {
-#ifdef _IBMR2
-           /*
-            * Like in ddp_output(), we can't rely on the if_output
-            * routine to resolve AF_APPLETALK addresses, on the rs6k.
-            * So, we fill the destination ethernet address here.
-            *
-            * This should really be replaced with something like
-            * rsif_output(). XXX Will have to be for phase 2.
-            */
-            /* XXX maybe fill in the rest of the frame header */
-           sat.sat_family = AF_UNSPEC;
-           bcopy( aat->aat_enaddr, (*(struct sockaddr *)&sat).sa_data,
-                   sizeof( aat->aat_enaddr ));
-#else /* _IBMR2 */
-           sat.sat_family = AF_APPLETALK;
-           sat.sat_addr = spa;
-#endif /* _IBMR2 */
-           (*ac->ac_if.if_output)( &ac->ac_if, aat->aat_hold,
-                   (struct sockaddr *)&sat );
-           aat->aat_hold = 0;
-       }
-    }
-
-    if ( aat == 0 && tpa.s_net == ma.s_net && tpa.s_node == ma.s_node
-           && op != AARPOP_PROBE ) {
-       if ( aat = aarptnew( &spa )) {
-           bcopy(( caddr_t )ea->aarp_sha, ( caddr_t )aat->aat_enaddr,
-                   sizeof( ea->aarp_sha ));
-           aat->aat_flags |= ATF_COM;
-       }
-    }
-
-    /*
-     * Don't respond to responses, and never respond if we're
-     * still probing.
-     */
-    if ( tpa.s_net != ma.s_net || tpa.s_node != ma.s_node ||
-           op == AARPOP_RESPONSE || ( aa->aa_flags & AFA_PROBING )) {
-       m_freem( m );
-       return;
-    }
-
-    bcopy(( caddr_t )ea->aarp_sha, ( caddr_t )ea->aarp_tha,
-           sizeof( ea->aarp_sha ));
-#ifdef sun
-    bcopy(( caddr_t )&ac->ac_enaddr, ( caddr_t )ea->aarp_sha,
-           sizeof( ea->aarp_sha ));
-#else /* sun */
-    bcopy(( caddr_t )ac->ac_enaddr, ( caddr_t )ea->aarp_sha,
-           sizeof( ea->aarp_sha ));
-#endif /* sun */
-
-    eh = (struct ether_header *)sa.sa_data;
-#ifdef sun
-    bcopy(( caddr_t )ea->aarp_tha, ( caddr_t )&eh->ether_dhost,
-           sizeof( eh->ether_dhost ));
-#else /* sun */
-    bcopy(( caddr_t )ea->aarp_tha, ( caddr_t )eh->ether_dhost,
-           sizeof( eh->ether_dhost ));
-#endif /* sun */
-
-    if ( aa->aa_flags & AFA_PHASE2 ) {
-#if defined( sun ) && defined( i386 )
-       eh->ether_type = htons( sizeof( struct llc ) +
-               sizeof( struct ether_aarp ));
-#else /* sun && i386 */
-       eh->ether_type = sizeof( struct llc ) + sizeof( struct ether_aarp );
-#endif /* sun && i386 */
-#ifdef BSD4_4
-       M_PREPEND( m, sizeof( struct llc ), M_DONTWAIT );
-       if ( m == NULL ) {
-           m_freem( m );
-           return;
-       }
-#else /* BSD4_4 */
-       MGET( m0, M_DONTWAIT, MT_HEADER );
-       if ( m0 == NULL ) {
-           m_freem( m );
-           return;
-       }
-       m0->m_next = m;
-       m = m0;
-       m->m_off = MMAXOFF - sizeof( struct llc );
-       m->m_len = sizeof ( struct llc );
-#endif /* BSD4_4 */
-       llc = mtod( m, struct llc *);
-       llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
-       llc->llc_control = LLC_UI;
-       bcopy( aarp_org_code, llc->llc_org_code, sizeof( aarp_org_code ));
-       llc->llc_ether_type = htons( ETHERTYPE_AARP );
-
-       bcopy( ea->aarp_spnet, ea->aarp_tpnet, sizeof( ea->aarp_tpnet ));
-       bcopy( &ma.s_net, ea->aarp_spnet, sizeof( ea->aarp_spnet ));
-    } else {
-#if defined( sun ) && defined( i386 )
-       eh->ether_type = htons( ETHERTYPE_AARP );
-#else /* sun && i386 */
-       eh->ether_type = ETHERTYPE_AARP;
-#endif /* sun && i386 */
-    }
-
-    ea->aarp_tpnode = ea->aarp_spnode;
-    ea->aarp_spnode = ma.s_node;
-    ea->aarp_op = htons( AARPOP_RESPONSE );
-
-#ifdef BSD4_4
-    sa.sa_len = sizeof( struct sockaddr );
-#endif /* BSD4_4 */
-    sa.sa_family = AF_UNSPEC;
-    (*ac->ac_if.if_output)( &ac->ac_if, m, &sa );
-    return;
-}
-
-aarptfree( aat )
-    struct aarptab     *aat;
-{
-
-    if ( aat->aat_hold )
-       m_freem( aat->aat_hold );
-    aat->aat_hold = 0;
-    aat->aat_timer = aat->aat_flags = 0;
-    aat->aat_ataddr.s_net = 0;
-    aat->aat_ataddr.s_node = 0;
-}
-
-    struct aarptab *
-aarptnew( addr )
-    struct at_addr     *addr;
-{
-    int                        n;
-    int                        oldest = -1;
-    struct aarptab     *aat, *aato = NULL;
-    static int         first = 1;
-
-    if ( first ) {
-       first = 0;
-       timeout( aarptimer, (caddr_t)0, hz );
-    }
-    aat = &aarptab[ AARPTAB_HASH( *addr ) * AARPTAB_BSIZ ];
-    for ( n = 0; n < AARPTAB_BSIZ; n++, aat++ ) {
-       if ( aat->aat_flags == 0 )
-           goto out;
-       if ( aat->aat_flags & ATF_PERM )
-           continue;
-       if ((int) aat->aat_timer > oldest ) {
-           oldest = aat->aat_timer;
-           aato = aat;
-       }
-    }
-    if ( aato == NULL )
-       return( NULL );
-    aat = aato;
-    aarptfree( aat );
-out:
-    aat->aat_ataddr = *addr;
-    aat->aat_flags = ATF_INUSE;
-    return( aat );
-}
-
-aarpprobe( ac )
-    struct arpcom      *ac;
-{
-    struct mbuf                *m;
-    struct ether_header        *eh;
-    struct ether_aarp  *ea;
-    struct at_ifaddr   *aa;
-    struct llc         *llc;
-    struct sockaddr    sa;
-
-    /*
-     * We need to check whether the output ethernet type should
-     * be phase 1 or 2. We have the interface that we'll be sending
-     * the aarp out. We need to find an AppleTalk network on that
-     * interface with the same address as we're looking for. If the
-     * net is phase 2, generate an 802.2 and SNAP header.
-     */
-    for ( aa = (struct at_ifaddr *)ac->ac_if.if_addrlist; aa;
-           aa = (struct at_ifaddr *)aa->aa_ifa.ifa_next ) {
-       if ( AA_SAT( aa )->sat_family == AF_APPLETALK &&
-               ( aa->aa_flags & AFA_PROBING )) {
-           break;
-       }
-    }
-    if ( aa == NULL ) {                /* serious error XXX */
-       printf( "aarpprobe why did this happen?!\n" );
-       return;
-    }
-
-    if ( aa->aa_probcnt <= 0 ) {
-       aa->aa_flags &= ~AFA_PROBING;
-       wakeup( aa );
-       return;
-    } else {
-       timeout( aarpprobe, (caddr_t)ac, hz / 5 );
-    }
-
-#ifdef BSD4_4
-    if (( m = m_gethdr( M_DONTWAIT, MT_DATA )) == NULL ) {
-       return;
-    }
-    m->m_len = sizeof( *ea );
-    m->m_pkthdr.len = sizeof( *ea );
-    MH_ALIGN( m, sizeof( *ea ));
-#else /* BSD4_4 */
-    if (( m = m_get( M_DONTWAIT, MT_DATA )) == NULL ) {
-       return;
-    }
-    m->m_len = sizeof( *ea );
-    m->m_off = MMAXOFF - sizeof( *ea );
-#endif /* BSD4_4 */
-
-    ea = mtod( m, struct ether_aarp *);
-    bzero((caddr_t)ea, sizeof( *ea ));
-
-    ea->aarp_hrd = htons( AARPHRD_ETHER );
-    ea->aarp_pro = htons( ETHERTYPE_AT );
-    ea->aarp_hln = sizeof( ea->aarp_sha );
-    ea->aarp_pln = sizeof( ea->aarp_spu );
-    ea->aarp_op = htons( AARPOP_PROBE );
-#ifdef sun
-    bcopy((caddr_t)&ac->ac_enaddr, (caddr_t)ea->aarp_sha,
-           sizeof( ea->aarp_sha ));
-#else /* sun */
-    bcopy((caddr_t)ac->ac_enaddr, (caddr_t)ea->aarp_sha,
-           sizeof( ea->aarp_sha ));
-#endif /* sun */
-
-    eh = (struct ether_header *)sa.sa_data;
-
-    if ( aa->aa_flags & AFA_PHASE2 ) {
-#ifdef sun
-       bcopy((caddr_t)atmulticastaddr, (caddr_t)&eh->ether_dhost,
-               sizeof( eh->ether_dhost ));
-#else /* sun */
-       bcopy((caddr_t)atmulticastaddr, (caddr_t)eh->ether_dhost,
-               sizeof( eh->ether_dhost ));
-#endif /* sun */
-#if defined( sun ) && defined( i386 )
-       eh->ether_type = htons( sizeof( struct llc ) +
-               sizeof( struct ether_aarp ));
-#else /* sun && i386 */
-       eh->ether_type = sizeof( struct llc ) + sizeof( struct ether_aarp );
-#endif /* sun && i386 */
-#ifdef BSD4_4
-       M_PREPEND( m, sizeof( struct llc ), M_WAIT );
-#else /* BSD4_4 */
-       m->m_len += sizeof( struct llc );
-       m->m_off -= sizeof( struct llc );
-#endif /* BSD4_4 */
-       llc = mtod( m, struct llc *);
-       llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
-       llc->llc_control = LLC_UI;
-       bcopy( aarp_org_code, llc->llc_org_code, sizeof( aarp_org_code ));
-       llc->llc_ether_type = htons( ETHERTYPE_AARP );
-
-       bcopy( &AA_SAT( aa )->sat_addr.s_net, ea->aarp_spnet,
-               sizeof( ea->aarp_spnet ));
-       bcopy( &AA_SAT( aa )->sat_addr.s_net, ea->aarp_tpnet,
-               sizeof( ea->aarp_tpnet ));
-       ea->aarp_spnode = ea->aarp_tpnode = AA_SAT( aa )->sat_addr.s_node;
-    } else {
-#ifdef sun
-       bcopy((caddr_t)&etherbroadcastaddr, (caddr_t)&eh->ether_dhost,
-               sizeof( eh->ether_dhost ));
-#else /* sun */
-       bcopy((caddr_t)etherbroadcastaddr, (caddr_t)eh->ether_dhost,
-               sizeof( eh->ether_dhost ));
-#endif /* sun */
-#if defined( sun ) && defined( i386 )
-       eh->ether_type = htons( ETHERTYPE_AARP );
-#else /* sun && i386 */
-       eh->ether_type = ETHERTYPE_AARP;
-#endif /* sun && i386 */
-       ea->aarp_spa = ea->aarp_tpa = AA_SAT( aa )->sat_addr.s_node;
-    }
-
-#ifdef BSD4_4
-    sa.sa_len = sizeof( struct sockaddr );
-#endif /* BSD4_4 */
-    sa.sa_family = AF_UNSPEC;
-    (*ac->ac_if.if_output)(&ac->ac_if, m, &sa );
-    aa->aa_probcnt--;
-}
-
-aarp_clean()
-{
-    struct aarptab     *aat;
-    int                        i;
-
-    untimeout( aarptimer, 0 );
-    for ( i = 0, aat = aarptab; i < AARPTAB_SIZE; i++, aat++ ) {
-       if ( aat->aat_hold ) {
-           m_freem( aat->aat_hold );
-       }
-    }
-}
diff --git a/sys/netatalk/aarp.h b/sys/netatalk/aarp.h
deleted file mode 100644 (file)
index a391aae..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * $Id: aarp.h,v 1.2 2001-06-29 14:14:47 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * This structure is used for both phase 1 and 2. Under phase 1
- * the net is not filled in. It is in phase 2. In both cases, the
- * hardware address length is (for some unknown reason) 4. If
- * anyone at Apple could program their way out of paper bag, it
- * would be 1 and 3 respectively for phase 1 and 2.
- */
-
-#ifndef _AARP_H
-#define _AARP_H 1
-
-union aapa {
-    u_char             ap_pa[4];
-    struct ap_node {
-       u_char          an_zero;
-       u_char          an_net[2];
-       u_char          an_node;
-    } ap_node;
-};
-
-struct ether_aarp {
-    struct arphdr      eaa_hdr;
-    u_char             aarp_sha[6];
-    union aapa         aarp_spu;
-    u_char             aarp_tha[6];
-    union aapa         aarp_tpu;
-};
-#define aarp_hrd       eaa_hdr.ar_hrd
-#define aarp_pro       eaa_hdr.ar_pro
-#define aarp_hln       eaa_hdr.ar_hln
-#define aarp_pln       eaa_hdr.ar_pln
-#define aarp_op                eaa_hdr.ar_op
-#define aarp_spa       aarp_spu.ap_node.an_node
-#define aarp_tpa       aarp_tpu.ap_node.an_node
-#define aarp_spnet     aarp_spu.ap_node.an_net
-#define aarp_tpnet     aarp_tpu.ap_node.an_net
-#define aarp_spnode    aarp_spu.ap_node.an_node
-#define aarp_tpnode    aarp_tpu.ap_node.an_node
-
-struct aarptab {
-    struct at_addr     aat_ataddr;
-    u_char             aat_enaddr[ 6 ];
-    u_char             aat_timer;
-    u_char             aat_flags;
-    struct mbuf                *aat_hold;
-};
-
-#define AARPHRD_ETHER  0x0001
-
-#define AARPOP_REQUEST 0x01
-#define AARPOP_RESPONSE        0x02
-#define AARPOP_PROBE   0x03
-
-#ifdef KERNEL
-struct aarptab         *aarptnew();
-int                    aarpprobe();
-#endif /* KERNEL */
-
-#endif /* _AARP_H */
diff --git a/sys/netatalk/at.h b/sys/netatalk/at.h
deleted file mode 100644 (file)
index f544c40..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- *
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifndef __AT_HEADER__
-#define __AT_HEADER__
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifndef NO_DDP
-
-#if defined(linux) /* pull in the linux header */
-#include <sys/socket.h>
-#include <asm/types.h>
-#include <linux/atalk.h>
-
-#ifdef HAVE_ATALK_ADDR
-#define at_addr atalk_addr
-#define netrange atalk_netrange
-#endif /* HAVE_ATALK_ADDR */
-
-#else /* linux */
-
-#include <sys/types.h>
-#include <netinet/in.h> /* so that we can deal with sun's s_net #define */
-
-#ifdef MACOSX_SERVER
-#include <netat/appletalk.h>
-#endif /* MACOSX_SERVER */
-
-/*
- * Supported protocols
- */
-#ifdef ATPROTO_DDP
-#undef ATPROTO_DDP
-#endif /* ATPROTO_DDP */
-#define ATPROTO_DDP    0
-#define ATPROTO_AARP   254
-
-/*
- * Ethernet types, for DIX.
- * These should really be in some global header file, but we can't
- * count on them being there, and it's annoying to patch system files.
- */
-#ifndef ETHERTYPE_AT
-#define ETHERTYPE_AT   0x809B          /* AppleTalk protocol */
-#endif
-#ifndef ETHERTYPE_AARP
-#define ETHERTYPE_AARP 0x80F3          /* AppleTalk ARP */
-#endif
-
-#define DDP_MAXSZ      587
-
-/*
- * If ATPORT_FIRST <= Port < ATPORT_RESERVED,
- * Port was created by a privileged process.
- * If ATPORT_RESERVED <= Port < ATPORT_LAST,
- * Port was not necessarily created by a
- * privileged process.
- */
-#define ATPORT_FIRST   1
-#define ATPORT_RESERVED        128
-#define ATPORT_LAST    254 /* 254 is reserved on ether/tokentalk networks */
-
-/*
- * AppleTalk address.
- */
-#ifndef MACOSX_SERVER
-struct at_addr {
-#ifdef s_net
-#undef s_net
-#endif /* s_net */
-    u_short    s_net;
-    u_char     s_node;
-};
-#endif /* MACOSX_SERVER */
-
-#define ATADDR_ANYNET  (u_short)0x0000
-#define ATADDR_ANYNODE (u_char)0x00
-#define ATADDR_ANYPORT (u_char)0x00
-#define ATADDR_BCAST   (u_char)0xff            /* There is no BCAST for NET */
-
-/*
- * Socket address, AppleTalk style.  We keep magic information in the 
- * zero bytes.  There are three types, NONE, CONFIG which has the phase
- * and a net range, and IFACE which has the network address of an
- * interface.  IFACE may be filled in by the client, and is filled in
- * by the kernel.
- */
-#ifndef MACOSX_SERVER
-struct sockaddr_at {
-#ifdef BSD4_4
-    u_char             sat_len;
-    u_char             sat_family;
-#else /* BSD4_4 */
-    short              sat_family;
-#endif /* BSD4_4 */
-    u_char             sat_port;
-    struct at_addr     sat_addr;
-#ifdef notdef
-    struct {
-       u_char          sh_type;
-# define SATHINT_NONE  0
-# define SATHINT_CONFIG        1
-# define SATHINT_IFACE 2
-       union {
-           char                su_zero[ 7 ];   /* XXX check size */
-           struct {
-               u_char          sr_phase;
-               u_short         sr_firstnet, sr_lastnet;
-           } su_range;
-           u_short             su_interface;
-       } sh_un;
-    } sat_hints;
-#else /* notdef */
-    char               sat_zero[ 8 ];
-#endif /* notdef */
-};
-#endif /* MACOSX_SERVER */
-
-struct netrange {
-    u_char             nr_phase;
-    u_short            nr_firstnet;
-    u_short            nr_lastnet;
-};
-
-#ifdef KERNEL
-extern struct domain   atalkdomain;
-extern struct protosw  atalksw[];
-#endif /* KERNEL */
-
-#endif /* linux */
-#endif /* NO_DDP */
-#endif /* __AT_HEADER__ */
-
diff --git a/sys/netatalk/at_control.c b/sys/netatalk/at_control.c
deleted file mode 100644 (file)
index 3cc3a1e..0000000
+++ /dev/null
@@ -1,586 +0,0 @@
-/*
- * $Id: at_control.c,v 1.2 2001-06-29 14:14:47 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/param.h>
-#include <sys/systm.h>
-#ifdef ibm032
-#include <sys/dir.h>
-#endif /* ibm032 */
-#include <sys/user.h>
-#include <sys/types.h>
-#include <sys/errno.h>
-#include <sys/ioctl.h>
-#include <sys/mbuf.h>
-#ifndef _IBMR2
-#include <sys/kernel.h>
-#endif /* ! _IBMR2 */
-#include <sys/socket.h>
-#include <sys/socketvar.h>
-#include <net/if.h>
-#include <net/af.h>
-#include <net/route.h>
-#include <netinet/in.h>
-#undef s_net
-#include <netinet/if_ether.h>
-#ifdef _IBMR2
-#include <net/spl.h>
-#endif /* _IBMR2 */
-
-#include "at.h"
-#include "at_var.h"
-#include "aarp.h"
-#include "phase2.h"
-
-#ifdef BSD4_4
-# define sateqaddr(a,b)        ((a)->sat_len == (b)->sat_len && \
-                   (a)->sat_family == (b)->sat_family && \
-                   (a)->sat_addr.s_net == (b)->sat_addr.s_net && \
-                   (a)->sat_addr.s_node == (b)->sat_addr.s_node )
-#else /* BSD4_4 */
-atalk_hash( sat, hp )
-    struct sockaddr_at *sat;
-    struct afhash      *hp;
-{
-    hp->afh_nethash = sat->sat_addr.s_net;
-    hp->afh_hosthash = ( sat->sat_addr.s_net << 8 ) +
-           sat->sat_addr.s_node;
-}
-
-/*
- * Note the magic to get ifa_ifwithnet() to work without adding an
- * ifaddr entry for each net in our local range.
- */
-atalk_netmatch( sat1, sat2 )
-    struct sockaddr_at *sat1, *sat2;
-{
-    struct at_ifaddr   *aa;
-
-    for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-       if ( AA_SAT( aa ) == sat1 ) {
-           break;
-       }
-    }
-    if ( aa ) {
-       return( ntohs( aa->aa_firstnet ) <= ntohs( sat2->sat_addr.s_net ) &&
-               ntohs( aa->aa_lastnet ) >= ntohs( sat2->sat_addr.s_net ));
-    }
-    return( sat1->sat_addr.s_net == sat2->sat_addr.s_net );
-}
-#endif /* BSD4_4 */
-
-at_control( cmd, data, ifp )
-    int                        cmd;
-    caddr_t            data;
-    struct ifnet       *ifp;
-{
-    struct ifreq       *ifr = (struct ifreq *)data;
-    struct sockaddr_at *sat;
-    struct netrange    *nr;
-#ifdef BSD4_4
-    struct at_aliasreq *ifra = (struct at_aliasreq *)data;
-    struct at_ifaddr   *aa0;
-#endif /* BSD4_4 */
-    struct at_ifaddr   *aa = 0;
-    struct mbuf                *m;
-    struct ifaddr      *ifa;
-
-    if ( ifp ) {
-       for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-           if ( aa->aa_ifp == ifp ) break;
-       }
-    }
-
-    switch ( cmd ) {
-#ifdef BSD4_4
-    case SIOCAIFADDR:
-    case SIOCDIFADDR:
-       if ( ifra->ifra_addr.sat_family == AF_APPLETALK ) {
-           for ( ; aa; aa = aa->aa_next ) {
-               if ( aa->aa_ifp == ifp &&
-                       sateqaddr( &aa->aa_addr, &ifra->ifra_addr )) {
-                   break;
-               }
-           }
-       }
-       if ( cmd == SIOCDIFADDR && aa == 0 ) {
-           return( EADDRNOTAVAIL );
-       }
-       /*FALLTHROUGH*/
-#endif /* BSD4_4 */
-
-    case SIOCSIFADDR:
-#ifdef BSD4_4
-       /*
-        * What a great idea this is: Let's reverse the meaning of
-        * the return...
-        */
-       if ( suser( u.u_cred, &u.u_acflag )) {
-           return( EPERM );
-       }
-#else /* BSD4_4 */
-       if ( !suser()) {
-           return( EPERM );
-       }
-#endif /* BSD4_4 */
-
-       sat = satosat( &ifr->ifr_addr );
-       nr = (struct netrange *)sat->sat_zero;
-       if ( nr->nr_phase == 1 ) {
-           for ( ; aa; aa = aa->aa_next ) {
-               if ( aa->aa_ifp == ifp &&
-                       ( aa->aa_flags & AFA_PHASE2 ) == 0 ) {
-                   break;
-               }
-           }
-       } else {                /* default to phase 2 */
-           for ( ; aa; aa = aa->aa_next ) {
-               if ( aa->aa_ifp == ifp && ( aa->aa_flags & AFA_PHASE2 )) {
-                   break;
-               }
-           }
-       }
-
-       if ( ifp == 0 )
-           panic( "at_control" );
-
-       if ( aa == (struct at_ifaddr *) 0 ) {
-           m = m_getclr( M_WAIT, MT_IFADDR );
-           if ( m == (struct mbuf *)NULL ) {
-               return( ENOBUFS );
-           }
-
-           if (( aa = at_ifaddr ) != NULL ) {
-               /*
-                * Don't let the loopback be first, since the first
-                * address is the machine's default address for
-                * binding.
-                */
-               if ( at_ifaddr->aa_ifp->if_flags & IFF_LOOPBACK ) {
-                   aa = mtod( m, struct at_ifaddr *);
-                   aa->aa_next = at_ifaddr;
-                   at_ifaddr = aa;
-               } else {
-                   for ( ; aa->aa_next; aa = aa->aa_next )
-                       ;
-                   aa->aa_next = mtod( m, struct at_ifaddr *);
-               }
-           } else {
-               at_ifaddr = mtod( m, struct at_ifaddr *);
-           }
-
-           aa = mtod( m, struct at_ifaddr *);
-
-           if (( ifa = ifp->if_addrlist ) != NULL ) {
-               for ( ; ifa->ifa_next; ifa = ifa->ifa_next )
-                   ;
-               ifa->ifa_next = (struct ifaddr *)aa;
-           } else {
-               ifp->if_addrlist = (struct ifaddr *)aa;
-           }
-
-#ifdef BSD4_4
-           aa->aa_ifa.ifa_addr = (struct sockaddr *)&aa->aa_addr;
-           aa->aa_ifa.ifa_dstaddr = (struct sockaddr *)&aa->aa_addr;
-           aa->aa_ifa.ifa_netmask = (struct sockaddr *)&aa->aa_netmask;
-#endif /* BSD4_4 */
-
-           /*
-            * Set/clear the phase 2 bit.
-            */
-           if ( nr->nr_phase == 1 ) {
-               aa->aa_flags &= ~AFA_PHASE2;
-           } else {
-               aa->aa_flags |= AFA_PHASE2;
-           }
-           aa->aa_ifp = ifp;
-       } else {
-           at_scrub( ifp, aa );
-       }
-       break;
-
-    case SIOCGIFADDR :
-       sat = satosat( &ifr->ifr_addr );
-       nr = (struct netrange *)sat->sat_zero;
-       if ( nr->nr_phase == 1 ) {
-           for ( ; aa; aa = aa->aa_next ) {
-               if ( aa->aa_ifp == ifp &&
-                       ( aa->aa_flags & AFA_PHASE2 ) == 0 ) {
-                   break;
-               }
-           }
-       } else {                /* default to phase 2 */
-           for ( ; aa; aa = aa->aa_next ) {
-               if ( aa->aa_ifp == ifp && ( aa->aa_flags & AFA_PHASE2 )) {
-                   break;
-               }
-           }
-       }
-
-       if ( aa == (struct at_ifaddr *) 0 )
-           return( EADDRNOTAVAIL );
-       break;
-    }
-
-    switch ( cmd ) {
-    case SIOCGIFADDR:
-#ifdef BSD4_4
-       *(struct sockaddr_at *)&ifr->ifr_addr = aa->aa_addr;
-#else /* BSD4_4 */
-       ifr->ifr_addr = aa->aa_addr;
-#endif /* BSD4_4 */
-       break;
-
-    case SIOCSIFADDR:
-       return( at_ifinit( ifp, aa, (struct sockaddr_at *)&ifr->ifr_addr ));
-
-#ifdef BSD4_4
-    case SIOCAIFADDR:
-       if ( sateqaddr( &ifra->ifra_addr, &aa->aa_addr )) {
-           return( 0 );
-       }
-       return( at_ifinit( ifp, aa, (struct sockaddr_at *)&ifr->ifr_addr ));
-
-    case SIOCDIFADDR:
-       at_scrub( ifp, aa );
-       if (( ifa = ifp->if_addrlist ) == (struct ifaddr *)aa ) {
-           ifp->if_addrlist = ifa->ifa_next;
-       } else {
-           while ( ifa->ifa_next && ( ifa->ifa_next != (struct ifaddr *)aa )) {
-               ifa = ifa->ifa_next;
-           }
-           if ( ifa->ifa_next ) {
-               ifa->ifa_next = ((struct ifaddr *)aa)->ifa_next;
-           } else {
-               panic( "at_control" );
-           }
-       }
-
-       aa0 = aa;
-       if ( aa0 == ( aa = at_ifaddr )) {
-           at_ifaddr = aa->aa_next;
-       } else {
-           while ( aa->aa_next && ( aa->aa_next != aa0 )) {
-               aa = aa->aa_next;
-           }
-           if ( aa->aa_next ) {
-               aa->aa_next = aa0->aa_next;
-           } else {
-               panic( "at_control" );
-           }
-       }
-       m_free( dtom( aa0 ));
-       break;
-#endif /* BSD4_4 */
-
-    default:
-       if ( ifp == 0 || ifp->if_ioctl == 0 )
-           return( EOPNOTSUPP );
-       return( (*ifp->if_ioctl)( ifp, cmd, data ));
-    }
-    return( 0 );
-}
-
-at_scrub( ifp, aa )
-    struct ifnet       *ifp;
-    struct at_ifaddr   *aa;
-{
-#ifndef BSD4_4
-    struct sockaddr_at netsat;
-    int                        error;
-    u_short            net;
-#endif /* ! BSD4_4 */
-
-    if ( aa->aa_flags & AFA_ROUTE ) {
-#ifdef BSD4_4
-       if (( error = rtinit( &(aa->aa_ifa), RTM_DELETE,
-               ( ifp->if_flags & IFF_LOOPBACK ) ? RTF_HOST : 0 )) != 0 ) {
-           return( error );
-       }
-       aa->aa_ifa.ifa_flags &= ~IFA_ROUTE;
-#else /* BSD4_4 */
-       if ( ifp->if_flags & IFF_LOOPBACK ) {
-           rtinit( &aa->aa_addr, &aa->aa_addr, SIOCDELRT, RTF_HOST );
-       } else {
-           bzero( &netsat, sizeof( struct sockaddr_at ));
-           netsat.sat_family = AF_APPLETALK;
-           netsat.sat_addr.s_node = ATADDR_ANYNODE;
-
-           /*
-            * If the range is the full 0-fffe range, just use
-            * the default route.
-            */
-           if ( aa->aa_firstnet == htons( 0x0000 ) &&
-                   aa->aa_lastnet == htons( 0xfffe )) {
-               netsat.sat_addr.s_net = 0;
-               rtinit((struct sockaddr *)&netsat, &aa->aa_addr,
-                       (int)SIOCDELRT, 0 );
-           } else {
-               for ( net = ntohs( aa->aa_firstnet );
-                       net <= ntohs( aa->aa_lastnet ); net++ ) {
-                   netsat.sat_addr.s_net = htons( net );
-                   rtinit((struct sockaddr *)&netsat, &aa->aa_addr,
-                           (int)SIOCDELRT, 0 );
-               }
-           }
-       }
-#endif /* BSD4_4 */
-       aa->aa_flags &= ~AFA_ROUTE;
-    }
-    return( 0 );
-}
-
-extern struct timeval  time;
-
-at_ifinit( ifp, aa, sat )
-    struct ifnet       *ifp;
-    struct at_ifaddr   *aa;
-    struct sockaddr_at *sat;
-{
-    struct netrange    nr, onr;
-#ifdef BSD4_4
-    struct sockaddr_at oldaddr;
-#else /* BSD4_4 */
-    struct sockaddr    oldaddr;
-#endif /* BSD4_4 */
-    struct sockaddr_at netaddr;
-    int                        s = splimp(), error = 0, i, j, netinc, nodeinc, nnets;
-    u_short            net;
-
-    oldaddr = aa->aa_addr;
-    bzero( AA_SAT( aa ), sizeof( struct sockaddr_at ));
-    bcopy( sat->sat_zero, &nr, sizeof( struct netrange ));
-    nnets = ntohs( nr.nr_lastnet ) - ntohs( nr.nr_firstnet ) + 1;
-
-    onr.nr_firstnet = aa->aa_firstnet;
-    onr.nr_lastnet = aa->aa_lastnet;
-    aa->aa_firstnet = nr.nr_firstnet;
-    aa->aa_lastnet = nr.nr_lastnet;
-
-    /*
-     * We could eliminate the need for a second phase 1 probe (post
-     * autoconf) if we check whether we're resetting the node. Note
-     * that phase 1 probes use only nodes, not net.node pairs.  Under
-     * phase 2, both the net and node must be the same.
-     */
-    if ( ifp->if_flags & IFF_LOOPBACK ) {
-#ifdef BSD4_4
-       AA_SAT( aa )->sat_len = sat->sat_len;
-#endif /* BSD4_4 */
-       AA_SAT( aa )->sat_family = AF_APPLETALK;
-       AA_SAT( aa )->sat_addr.s_net = sat->sat_addr.s_net;
-       AA_SAT( aa )->sat_addr.s_node = sat->sat_addr.s_node;
-    } else {
-       aa->aa_flags |= AFA_PROBING;
-       AA_SAT( aa )->sat_family = AF_APPLETALK;
-       if ( aa->aa_flags & AFA_PHASE2 ) {
-           if ( sat->sat_addr.s_net == ATADDR_ANYNET ) {
-               if ( nnets != 1 ) {
-                   net = ntohs( nr.nr_firstnet ) + time.tv_sec % ( nnets - 1 );
-               } else {
-                   net = ntohs( nr.nr_firstnet );
-               }
-           } else {
-               if ( ntohs( sat->sat_addr.s_net ) < ntohs( nr.nr_firstnet ) ||
-                       ntohs( sat->sat_addr.s_net ) > ntohs( nr.nr_lastnet )) {
-                   aa->aa_addr = oldaddr;
-                   aa->aa_firstnet = onr.nr_firstnet;
-                   aa->aa_lastnet = onr.nr_lastnet;
-                   return( EINVAL );
-               }
-               net = ntohs( sat->sat_addr.s_net );
-           }
-       } else {
-           net = ntohs( sat->sat_addr.s_net );
-       }
-
-       if ( sat->sat_addr.s_node == ATADDR_ANYNODE ) {
-           AA_SAT( aa )->sat_addr.s_node = time.tv_sec;
-       } else {
-           AA_SAT( aa )->sat_addr.s_node = sat->sat_addr.s_node;
-       }
-
-       for ( i = nnets, netinc = 1; i > 0; net = ntohs( nr.nr_firstnet ) +
-               (( net - ntohs( nr.nr_firstnet ) + netinc ) % nnets ), i-- ) {
-           AA_SAT( aa )->sat_addr.s_net = htons( net );
-
-           for ( j = 0, nodeinc = time.tv_sec | 1; j < 256;
-                   j++, AA_SAT( aa )->sat_addr.s_node += nodeinc ) {
-               if ( AA_SAT( aa )->sat_addr.s_node > 253 ||
-                       AA_SAT( aa )->sat_addr.s_node < 1 ) {
-                   continue;
-               }
-               aa->aa_probcnt = 10;
-               timeout( aarpprobe, (caddr_t)ifp, hz / 5 );
-               splx( s );
-               if ( sleep( aa, PSLEP|PCATCH )) {
-                   printf( "at_ifinit why did this happen?!\n" );
-                   aa->aa_addr = oldaddr;
-                   aa->aa_firstnet = onr.nr_firstnet;
-                   aa->aa_lastnet = onr.nr_lastnet;
-                   return( EINTR );
-               }
-               s = splimp();
-               if (( aa->aa_flags & AFA_PROBING ) == 0 ) {
-                   break;
-               }
-           }
-           if (( aa->aa_flags & AFA_PROBING ) == 0 ) {
-               break;
-           }
-           /* reset node for next network */
-           AA_SAT( aa )->sat_addr.s_node = time.tv_sec;
-       }
-
-       if ( aa->aa_flags & AFA_PROBING ) {
-           aa->aa_addr = oldaddr;
-           aa->aa_firstnet = onr.nr_firstnet;
-           aa->aa_lastnet = onr.nr_lastnet;
-           splx( s );
-           return( EADDRINUSE );
-       }
-    }
-
-    if ( ifp->if_ioctl &&
-           ( error = (*ifp->if_ioctl)( ifp, SIOCSIFADDR, aa ))) {
-       splx( s );
-       aa->aa_addr = oldaddr;
-       aa->aa_firstnet = onr.nr_firstnet;
-       aa->aa_lastnet = onr.nr_lastnet;
-       return( error );
-    }
-
-#ifdef BSD4_4
-    aa->aa_netmask.sat_len = 6;
-    aa->aa_netmask.sat_family = AF_APPLETALK;
-    aa->aa_netmask.sat_addr.s_net = 0xffff;
-    aa->aa_netmask.sat_addr.s_node = 0;
-#endif /* BSD4_4 */
-
-    if ( ifp->if_flags & IFF_LOOPBACK ) {
-#ifndef BSD4_4
-       rtinit( &aa->aa_addr, &aa->aa_addr, (int)SIOCADDRT,
-               RTF_HOST|RTF_UP );
-#else /* ! BSD4_4 */
-       error = rtinit( &(aa->aa_ifa), (int)RTM_ADD, RTF_HOST|RTF_UP );
-#endif /* ! BSD4_4 */
-    } else {
-#ifndef BSD4_4
-       /*
-        * rtrequest looks for point-to-point links first. The
-        * broadaddr is in the same spot as the destaddr. So, if
-        * ATADDR_ANYNET is 0, and we don't fill in the broadaddr, we
-        * get 0.0 routed out the ether interface.  So, initialize the
-        * broadaddr, even tho we don't use it.
-        *
-        * We *could* use the broadaddr field to reduce some of the
-        * sockaddr_at overloading that we've done.  E.g. Just send
-        * to INTERFACE-NET.255, and have the kernel reroute that
-        * to broadaddr, which would be 0.255 for phase 2 interfaces,
-        * and IFACE-NET.255 for phase 1 interfaces.
-        */
-       ((struct sockaddr_at *)&aa->aa_broadaddr)->sat_addr.s_net =
-               sat->sat_addr.s_net;
-       ((struct sockaddr_at *)&aa->aa_broadaddr)->sat_addr.s_node =
-               ATADDR_BCAST;
-
-       bzero( &netaddr, sizeof( struct sockaddr_at ));
-       netaddr.sat_family = AF_APPLETALK;
-       netaddr.sat_addr.s_node = ATADDR_ANYNODE;
-       if (( aa->aa_flags & AFA_PHASE2 ) == 0 ) {
-           netaddr.sat_addr.s_net = AA_SAT( aa )->sat_addr.s_net;
-           rtinit((struct sockaddr *)&netaddr, &aa->aa_addr,
-                   (int)SIOCADDRT, RTF_UP );
-       } else {
-           /*
-            * If the range is the full 0-fffe range, just use
-            * the default route.
-            */
-           if ( aa->aa_firstnet == htons( 0x0000 ) &&
-                   aa->aa_lastnet == htons( 0xfffe )) {
-               netaddr.sat_addr.s_net = 0;
-               rtinit((struct sockaddr *)&netaddr, &aa->aa_addr,
-                       (int)SIOCADDRT, RTF_UP );
-           } else {
-               for ( net = ntohs( aa->aa_firstnet );
-                       net <= ntohs( aa->aa_lastnet ); net++ ) {
-                   netaddr.sat_addr.s_net = htons( net );
-                   rtinit((struct sockaddr *)&netaddr, &aa->aa_addr,
-                           (int)SIOCADDRT, RTF_UP );
-               }
-           }
-       }
-#else /* ! BSD4_4 */
-       error = rtinit( &(aa->aa_ifa), (int)RTM_ADD, RTF_UP );
-#endif /* ! BSD4_4 */
-    }
-    if ( error ) {
-       aa->aa_addr = oldaddr;
-       aa->aa_firstnet = onr.nr_firstnet;
-       aa->aa_lastnet = onr.nr_lastnet;
-       splx( s );
-       return( error );
-    }
-
-#ifdef BSD4_4
-    aa->aa_ifa.ifa_flags |= IFA_ROUTE;
-#endif /* BSD4_4 */
-    aa->aa_flags |= AFA_ROUTE;
-    splx( s );
-    return( 0 );
-}
-
-at_broadcast( sat )
-    struct sockaddr_at *sat;
-{
-    struct at_ifaddr   *aa;
-
-    if ( sat->sat_addr.s_node != ATADDR_BCAST ) {
-       return( 0 );
-    }
-    if ( sat->sat_addr.s_net == 0 ) {
-       return( 1 );
-    } else {
-       for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-           if (( aa->aa_ifp->if_flags & IFF_BROADCAST ) &&
-                ( ntohs( sat->sat_addr.s_net ) >= ntohs( aa->aa_firstnet ) &&
-                ntohs( sat->sat_addr.s_net ) <= ntohs( aa->aa_lastnet ))) {
-               return( 1 );
-           }
-       }
-    }
-    return( 0 );
-}
-
-aa_clean()
-{
-    struct at_ifaddr   *aa;
-    struct ifaddr      *ifa;
-    struct ifnet       *ifp;
-
-    while ( aa = at_ifaddr ) {
-       ifp = aa->aa_ifp;
-       at_scrub( ifp, aa );
-       at_ifaddr = aa->aa_next;
-       if (( ifa = ifp->if_addrlist ) == (struct ifaddr *)aa ) {
-           ifp->if_addrlist = ifa->ifa_next;
-       } else {
-           while ( ifa->ifa_next &&
-                   ( ifa->ifa_next != (struct ifaddr *)aa )) {
-               ifa = ifa->ifa_next;
-           }
-           if ( ifa->ifa_next ) {
-               ifa->ifa_next = ((struct ifaddr *)aa)->ifa_next;
-           } else {
-               panic( "at_entry" );
-           }
-       }
-    }
-}
diff --git a/sys/netatalk/at_proto.c b/sys/netatalk/at_proto.c
deleted file mode 100644 (file)
index 21aa36a..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * $Id: at_proto.c,v 1.2 2001-06-29 14:14:47 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- *
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/protosw.h>
-#include <sys/domain.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include "at.h"
-
-extern int             ddp_usrreq();
-extern int             ddp_output();
-extern int             ddp_init();
-
-#ifdef ultrix
-extern int             ddp_ifoutput();
-extern int             ddp_ifinput();
-extern int             ddp_ifioctl();
-#endif /* ultrix */
-
-struct protosw         atalksw[] = {
-    {
-       /* Identifiers */
-       SOCK_DGRAM,     &atalkdomain,   ATPROTO_DDP,    PR_ATOMIC|PR_ADDR,
-       /*
-        * protocol-protocol interface.
-        * fields are pr_input, pr_output, pr_ctlinput, and pr_ctloutput.
-        * pr_input can be called from the udp protocol stack for iptalk
-        * packets bound for a local socket.
-        * pr_output can be used by higher level appletalk protocols, should
-        * they be included in the kernel.
-        */
-       0,              ddp_output,     0,              0,
-       /* socket-protocol interface. */
-       ddp_usrreq,
-       /* utility routines. */
-       ddp_init,       0,              0,              0,
-#ifdef ultrix
-       /* interface hooks */
-       ddp_ifoutput,   ddp_ifinput,    ddp_ifioctl,    0,
-#endif /* ultrix */
-    },
-};
-
-struct domain          atalkdomain = {
-    AF_APPLETALK,      "appletalk",    0,      0,      0,      atalksw,
-    &atalksw[ sizeof( atalksw ) / sizeof( atalksw[ 0 ] ) ]
-};
diff --git a/sys/netatalk/at_var.h b/sys/netatalk/at_var.h
deleted file mode 100644 (file)
index 87fe44a..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * $Id: at_var.h,v 1.2 2001-06-29 14:14:47 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- *
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifndef _ATVAR_H
-#define _ATVAR_H 1
-
-/*
- * For phase2, we need to keep not only our address on an interface,
- * but also the legal networks on the interface.
- */
-struct at_ifaddr {
-    struct ifaddr      aa_ifa;
-# define aa_ifp                        aa_ifa.ifa_ifp
-#ifdef BSD4_4
-    struct sockaddr_at aa_addr;
-    struct sockaddr_at aa_broadaddr;
-    struct sockaddr_at aa_netmask;
-#else /* BSD4_4 */
-# define aa_addr               aa_ifa.ifa_addr
-# define aa_broadaddr          aa_ifa.ifa_broadaddr
-# define aa_dstaddr            aa_ifa.ifa_dstaddr
-#endif /* BSD4_4 */
-    int                        aa_flags;
-    u_short            aa_firstnet, aa_lastnet;
-    int                        aa_probcnt;
-    struct at_ifaddr   *aa_next;
-};
-
-#ifdef BSD4_4
-struct at_aliasreq {
-       char    ifra_name[IFNAMSIZ];            /* if name, e.g. "en0" */
-       struct  sockaddr_at ifra_addr;
-       struct  sockaddr_at ifra_broadaddr;
-#define ifra_dstaddr ifra_broadaddr
-       struct  sockaddr_at ifra_mask;
-};
-#endif /* BSD4_4 */
-
-#define AA_SAT(aa) \
-    ((struct sockaddr_at *)&((struct at_ifaddr *)(aa))->aa_addr)
-#define satosat(sa)    ((struct sockaddr_at *)(sa))
-
-#define AFA_ROUTE      0x0001
-#define AFA_PROBING    0x0002
-#define AFA_PHASE2     0x0004
-
-#ifdef KERNEL
-struct at_ifaddr       *at_ifaddr;
-struct ifqueue         atintrq1, atintrq2;
-int                    atdebug;
-#endif /* KERNEL */
-
-#endif /* _ATVAR_H */
diff --git a/sys/netatalk/ddp.h b/sys/netatalk/ddp.h
deleted file mode 100644 (file)
index 4388386..0000000
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * $Id: ddp.h,v 1.2 2001-06-29 14:14:47 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- */
-
-/*
- * <-1byte(8bits) ->
- * +---------------+
- * | 0 | hopc  |len|
- * +---------------+
- * | len (cont)    |
- * +---------------+
- * |               |
- * +- DDP csum    -+
- * |               |
- * +---------------+
- * |               |
- * +- Dest NET    -+
- * |               |
- * +---------------+
- * |               |
- * +- Src NET     -+
- * |               |
- * +---------------+
- * | Dest NODE     |
- * +---------------+
- * | Src NODE      |
- * +---------------+
- * | Dest PORT     |
- * +---------------+
- * | Src PORT      |
- * +---------------+
- *
- * On Apples, there is also a ddp_type field, after src_port. However,
- * under this unix implementation, user level processes need to be able
- * to set the ddp_type. In later revisions, the ddp_type may only be
- * available in a raw_appletalk interface.
- */
-
-#ifndef _NETATALK_DDP_H
-#define _NETATALK_DDP_H 1
-
-#include <netatalk/endian.h>
-
-struct elaphdr {
-    u_char     el_dnode;
-    u_char     el_snode;
-    u_char     el_type;
-};
-
-#define        SZ_ELAPHDR      3
-
-#define ELAP_DDPSHORT  0x01
-#define ELAP_DDPEXTEND 0x02
-
-/*
- * Extended DDP header. Includes sickness for dealing with arbitrary
- * bitfields on a little-endian arch.
- */
-struct ddpehdr {
-    union {
-       struct {
-#if BYTE_ORDER == BIG_ENDIAN
-    unsigned           dub_pad:2;
-    unsigned           dub_hops:4;
-    unsigned           dub_len:10;
-    unsigned           dub_sum:16;
-#else /* BYTE_ORDER == BIG_ENDIAN */
-#if BYTE_ORDER == LITTLE_ENDIAN
-    unsigned           dub_sum:16;
-    unsigned           dub_len:10;
-    unsigned           dub_hops:4;
-    unsigned           dub_pad:2;
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-    OOPS!
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-#endif /* BYTE_ORDER == BIG_ENDIAN */
-       } du_bits;
-       unsigned        du_bytes;
-    } deh_u;
-#define deh_pad                deh_u.du_bits.dub_pad
-#define deh_hops       deh_u.du_bits.dub_hops
-#define deh_len                deh_u.du_bits.dub_len
-#define deh_sum                deh_u.du_bits.dub_sum
-#define deh_bytes      deh_u.du_bytes
-    u_short            deh_dnet;
-    u_short            deh_snet;
-    u_char             deh_dnode;
-    u_char             deh_snode;
-    u_char             deh_dport;
-    u_char             deh_sport;
-};
-
-#define SZ_DDPEHDR      12
-
-#define DDP_MAXHOPS    15
-
-struct ddpshdr {
-    union {
-       struct {
-#if BYTE_ORDER == BIG_ENDIAN
-    unsigned           dub_pad:6;
-    unsigned           dub_len:10;
-    unsigned           dub_dport:8;
-    unsigned           dub_sport:8;
-#endif /* BYTE_ORDER == BIG_ENDIAN */
-#if BYTE_ORDER == LITTLE_ENDIAN
-    unsigned           dub_sport:8;
-    unsigned           dub_dport:8;
-    unsigned           dub_len:10;
-    unsigned           dub_pad:6;
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-       } du_bits;
-       unsigned        du_bytes;
-    } dsh_u;
-#define dsh_pad                dsh_u.du_bits.dub_pad
-#define dsh_len                dsh_u.du_bits.dub_len
-#define dsh_dport      dsh_u.du_bits.dub_dport
-#define dsh_sport      dsh_u.du_bits.dub_sport
-#define dsh_bytes      dsh_u.du_bytes
-};
-#define SZ_DDPSHDR      4
-
-#endif /* netatalk/ddp.h */
diff --git a/sys/netatalk/ddp_input.c b/sys/netatalk/ddp_input.c
deleted file mode 100644 (file)
index 74501f9..0000000
+++ /dev/null
@@ -1,407 +0,0 @@
-/*
- * $Id: ddp_input.c,v 1.4 2002-01-04 04:45:48 sibaz Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/mbuf.h>
-#include <sys/socket.h>
-#include <sys/socketvar.h>
-#include <atalk/logger.h>
-#include <net/if.h>
-#include <net/route.h>
-#ifdef _IBMR2
-#include <net/spl.h>
-#endif /* _IBMR2 */
-
-#include "at.h"
-#include "at_var.h"
-#include "endian.h"
-#include "ddp.h"
-#include "ddp_var.h"
-
-int            ddp_forward = 1;
-int            ddp_firewall = 0;
-extern int     ddp_cksum;
-extern u_short at_cksum();
-
-/*
- * Could probably merge these two code segments a little better...
- */
-atintr()
-{
-    struct elaphdr     *elhp, elh;
-    struct ifnet       *ifp;
-    struct mbuf                *m;
-    struct at_ifaddr   *aa;
-    int                        s;
-
-    for (;;) {
-#ifndef _IBMR2
-       s = splimp();
-#endif /* ! _IBMR2 */
-
-#ifdef BSD4_4
-       IF_DEQUEUE( &atintrq2, m );
-#else /* BSD4_4 */
-       IF_DEQUEUEIF( &atintrq2, m, ifp );
-#endif /* BSD4_4 */
-
-#ifndef _IBMR2
-       splx( s );
-#endif /* ! _IBMR2 */
-
-       if ( m == 0 ) {                 /* no more queued packets */
-           break;
-       }
-
-#ifdef BSD4_4
-       ifp = m->m_pkthdr.rcvif;
-#endif /* BSD4_4 */
-       for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-           if ( aa->aa_ifp == ifp && ( aa->aa_flags & AFA_PHASE2 )) {
-               break;
-           }
-       }
-       if ( aa == NULL ) {             /* ifp not an appletalk interface */
-           m_freem( m );
-           continue;
-       }
-
-       ddp_input( m, ifp, (struct elaphdr *)NULL, 2 );
-    }
-
-    for (;;) {
-#ifndef _IBMR2
-       s = splimp();
-#endif /* ! _IBMR2 */
-
-#ifdef BSD4_4
-       IF_DEQUEUE( &atintrq1, m );
-#else /* BSD4_4 */
-       IF_DEQUEUEIF( &atintrq1, m, ifp );
-#endif /* BSD4_4 */
-
-#ifndef _IBMR2
-       splx( s );
-#endif /* ! _IBMR2 */
-
-       if ( m == 0 ) {                 /* no more queued packets */
-           break;
-       }
-
-#ifdef BSD4_4
-       ifp = m->m_pkthdr.rcvif;
-#endif /* BSD4_4 */
-       for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-           if ( aa->aa_ifp == ifp && ( aa->aa_flags & AFA_PHASE2 ) == 0 ) {
-               break;
-           }
-       }
-       if ( aa == NULL ) {             /* ifp not an appletalk interface */
-           m_freem( m );
-           continue;
-       }
-
-       if ( m->m_len < SZ_ELAPHDR &&
-               (( m = m_pullup( m, SZ_ELAPHDR )) == 0 )) {
-           ddpstat.ddps_tooshort++;
-           continue;
-       }
-
-       elhp = mtod( m, struct elaphdr *);
-       m_adj( m, SZ_ELAPHDR );
-
-       if ( elhp->el_type == ELAP_DDPEXTEND ) {
-           ddp_input( m, ifp, (struct elaphdr *)NULL, 1 );
-       } else {
-           bcopy((caddr_t)elhp, (caddr_t)&elh, SZ_ELAPHDR );
-           ddp_input( m, ifp, &elh, 1 );
-       }
-    }
-    return;
-}
-
-struct route   forwro;
-
-ddp_input( m, ifp, elh, phase )
-    struct mbuf                *m;
-    struct ifnet       *ifp;
-    struct elaphdr     *elh;
-    int                        phase;
-{
-    struct sockaddr_at from, to;
-    struct ddpshdr     *dsh, ddps;
-    struct at_ifaddr   *aa;
-    struct ddpehdr     *deh, ddpe;
-#ifndef BSD4_4
-    struct mbuf                *mp;
-#endif /* BSD4_4 */
-    struct ddpcb       *ddp;
-    int                        dlen, mlen;
-    u_short            cksum;
-
-    bzero( (caddr_t)&from, sizeof( struct sockaddr_at ));
-    if ( elh ) {
-       ddpstat.ddps_short++;
-
-       if ( m->m_len < sizeof( struct ddpshdr ) &&
-               (( m = m_pullup( m, sizeof( struct ddpshdr ))) == 0 )) {
-           ddpstat.ddps_tooshort++;
-           return;
-       }
-
-       dsh = mtod( m, struct ddpshdr *);
-       bcopy( (caddr_t)dsh, (caddr_t)&ddps, sizeof( struct ddpshdr ));
-       ddps.dsh_bytes = ntohl( ddps.dsh_bytes );
-       dlen = ddps.dsh_len;
-
-       to.sat_addr.s_net = 0;
-       to.sat_addr.s_node = elh->el_dnode;
-       to.sat_port = ddps.dsh_dport;
-       from.sat_addr.s_net = 0;
-       from.sat_addr.s_node = elh->el_snode;
-       from.sat_port = ddps.dsh_sport;
-
-       for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-           if ( aa->aa_ifp == ifp && ( aa->aa_flags & AFA_PHASE2 ) == 0 &&
-                   ( AA_SAT( aa )->sat_addr.s_node == to.sat_addr.s_node ||
-                   to.sat_addr.s_node == ATADDR_BCAST )) {
-               break;
-           }
-       }
-       if ( aa == NULL ) {
-           m_freem( m );
-           return;
-       }
-    } else {
-       ddpstat.ddps_long++;
-
-       if ( m->m_len < sizeof( struct ddpehdr ) &&
-               (( m = m_pullup( m, sizeof( struct ddpehdr ))) == 0 )) {
-           ddpstat.ddps_tooshort++;
-           return;
-       }
-
-       deh = mtod( m, struct ddpehdr *);
-       bcopy( (caddr_t)deh, (caddr_t)&ddpe, sizeof( struct ddpehdr ));
-       ddpe.deh_bytes = ntohl( ddpe.deh_bytes );
-       dlen = ddpe.deh_len;
-
-       if (( cksum = ddpe.deh_sum ) == 0 ) {
-           ddpstat.ddps_nosum++;
-       }
-
-       from.sat_addr.s_net = ddpe.deh_snet;
-       from.sat_addr.s_node = ddpe.deh_snode;
-       from.sat_port = ddpe.deh_sport;
-       to.sat_addr.s_net = ddpe.deh_dnet;
-       to.sat_addr.s_node = ddpe.deh_dnode;
-       to.sat_port = ddpe.deh_dport;
-
-       if ( to.sat_addr.s_net == 0 ) {
-           for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-               if ( phase == 1 && ( aa->aa_flags & AFA_PHASE2 )) {
-                   continue;
-               }
-               if ( phase == 2 && ( aa->aa_flags & AFA_PHASE2 ) == 0 ) {
-                   continue;
-               }
-               if ( aa->aa_ifp == ifp &&
-                       ( AA_SAT( aa )->sat_addr.s_node == to.sat_addr.s_node ||
-                       to.sat_addr.s_node == ATADDR_BCAST ||
-                       ( ifp->if_flags & IFF_LOOPBACK ))) {
-                   break;
-               }
-           }
-       } else {
-           for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-               if ( to.sat_addr.s_net == aa->aa_firstnet &&
-                       to.sat_addr.s_node == 0 ) {
-                   break;
-               }
-               if (( ntohs( to.sat_addr.s_net ) < ntohs( aa->aa_firstnet ) ||
-                       ntohs( to.sat_addr.s_net ) > ntohs( aa->aa_lastnet )) &&
-                       ( ntohs( to.sat_addr.s_net ) < 0xff00 ||
-                       ntohs( to.sat_addr.s_net ) > 0xfffe)) {
-                   continue;
-               }
-               if ( to.sat_addr.s_node != AA_SAT( aa )->sat_addr.s_node &&
-                       to.sat_addr.s_node != ATADDR_BCAST ) {
-                   continue;
-               }
-               break;
-           }
-       }
-    }
-
-    /*
-     * Adjust the length, removing any padding that may have been added
-     * at a link layer.  We do this before we attempt to forward a packet,
-     * possibly on a different media.
-     */
-#ifdef BSD4_4
-    mlen = m->m_pkthdr.len;
-#else /* BSD4_4 */
-    for ( mlen = 0, mp = m; mp; mp = mp->m_next ) {
-       mlen += mp->m_len;
-    }
-#endif /* BSD4_4 */
-    if ( mlen < dlen ) {
-       ddpstat.ddps_toosmall++;
-       m_freem( m );
-       return;
-    }
-    if ( mlen > dlen ) {
-       m_adj( m, dlen - mlen );
-    }
-
-    /*
-     * XXX Should we deliver broadcasts locally, also, or rely on the
-     * link layer to give us a copy?  For the moment, the latter.
-     */
-    if ( aa == NULL || ( to.sat_addr.s_node == ATADDR_BCAST &&
-           aa->aa_ifp != ifp && ( ifp->if_flags & IFF_LOOPBACK ) == 0 )) {
-       if ( ddp_forward == 0 ) {
-           m_freem( m );
-           return;
-       }
-       if ( forwro.ro_rt && ( satosat( &forwro.ro_dst )->sat_addr.s_net !=
-               to.sat_addr.s_net ||
-               satosat( &forwro.ro_dst )->sat_addr.s_node !=
-               to.sat_addr.s_node )) {
-#ifdef ultrix
-           rtfree( forwro.ro_rt );
-#else /* ultrix */
-           RTFREE( forwro.ro_rt );
-#endif /* ultrix */
-           forwro.ro_rt = (struct rtentry *)0;
-       }
-       if ( forwro.ro_rt == (struct rtentry *)0 ||
-            forwro.ro_rt->rt_ifp == (struct ifnet *)0 ) {
-#ifdef BSD4_4
-           forwro.ro_dst.sa_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-           forwro.ro_dst.sa_family = AF_APPLETALK;
-           satosat( &forwro.ro_dst )->sat_addr.s_net = to.sat_addr.s_net;
-           satosat( &forwro.ro_dst )->sat_addr.s_node = to.sat_addr.s_node;
-           rtalloc( &forwro );
-       }
-
-       if ( to.sat_addr.s_net != satosat( &forwro.ro_dst )->sat_addr.s_net &&
-               ddpe.deh_hops == DDP_MAXHOPS ) {
-           m_freem( m );
-           return;
-       }
-
-       if ( ddp_firewall &&
-               ( forwro.ro_rt == NULL || ( forwro.ro_rt->rt_ifp != ifp &&
-               forwro.ro_rt->rt_ifp != at_ifaddr->aa_ifp ))) {
-           m_freem( m );
-           return;
-       }
-
-       ddpe.deh_hops++;
-       ddpe.deh_bytes = htonl( ddpe.deh_bytes );
-       bcopy( (caddr_t)&ddpe, (caddr_t)deh, sizeof( u_short ));
-       if ( ddp_route( m, &forwro )) {
-           ddpstat.ddps_cantforward++;
-       } else {
-           ddpstat.ddps_forward++;
-       }
-       return;
-    }
-
-#ifdef BSD4_4
-    from.sat_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-    from.sat_family = AF_APPLETALK;
-
-    if ( elh ) {
-       m_adj( m, sizeof( struct ddpshdr ));
-    } else {
-       if ( ddp_cksum && cksum && cksum != at_cksum( m, sizeof( int ))) {
-           ddpstat.ddps_badsum++;
-           m_freem( m );
-           return;
-       }
-       m_adj( m, sizeof( struct ddpehdr ));
-    }
-
-    if (( ddp = ddp_search( &from, &to, aa )) == NULL ) {
-       m_freem( m );
-       return;
-    }
-
-    if ( sbappendaddr( &ddp->ddp_socket->so_rcv, (struct sockaddr *)&from,
-           m, (struct mbuf *)0 ) == 0 ) {
-       ddpstat.ddps_nosockspace++;
-       m_freem( m );
-       return;
-    }
-    sorwakeup( ddp->ddp_socket );
-}
-
-m_printm( m )
-    struct mbuf        *m;
-{
-    for (; m; m = m->m_next ) {
-       bprint( mtod( m, char * ), m->m_len );
-    }
-}
-
-#define BPXLEN 48
-#define BPALEN 16
-#include <ctype.h>
-char   hexdig[] = "0123456789ABCDEF";
-
-bprint( data, len )
-    char       *data;
-    int                len;
-{
-    char       xout[ BPXLEN ], aout[ BPALEN ];
-    int                i = 0;
-
-    bzero( xout, BPXLEN );
-    bzero( aout, BPALEN );
-
-    for ( ;; ) {
-       if ( len < 1 ) {
-           if ( i != 0 ) {
-               printf( "%s\t%s\n", xout, aout );
-           }
-           printf( "%s\n", "(end)" );
-           break;
-       }
-
-       xout[ (i*3) ] = hexdig[ ( *data & 0xf0 ) >> 4 ];
-       xout[ (i*3) + 1 ] = hexdig[ *data & 0x0f ];
-
-       if ( (u_char)*data < 0x7f && (u_char)*data > 0x20 ) {
-           aout[ i ] = *data;
-       } else {
-           aout[ i ] = '.';
-       }
-
-       xout[ (i*3) + 2 ] = ' ';
-
-       i++;
-       len--;
-       data++;
-
-       if ( i > BPALEN - 2 ) {
-           printf( "%s\t%s\n", xout, aout );
-           bzero( xout, BPXLEN );
-           bzero( aout, BPALEN );
-           i = 0;
-           continue;
-       }
-    }
-}
diff --git a/sys/netatalk/ddp_output.c b/sys/netatalk/ddp_output.c
deleted file mode 100644 (file)
index 75fe9cb..0000000
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * $Id: ddp_output.c,v 1.4 2002-01-04 04:45:49 sibaz Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/mbuf.h>
-#include <sys/socket.h>
-#include <sys/errno.h>
-#include <atalk/logger.h>
-
-#include <net/if.h>
-#include <net/route.h>
-
-#include <netinet/in.h>
-#undef s_net
-#include <netinet/if_ether.h>
-
-#include "at.h"
-#include "at_var.h"
-#include "endian.h"
-#include "ddp.h"
-#include "ddp_var.h"
-
-u_short        at_cksum();
-int    ddp_cksum = 1;
-
-ddp_output( ddp, m )
-    struct ddpcb       *ddp;
-    struct mbuf                *m;
-{
-#ifndef BSD4_4
-    struct mbuf                *m0;
-    int                        len;
-#endif /* ! BSD4_4 */
-    struct ifnet       *ifp;
-    struct at_ifaddr   *aa = NULL;
-    struct ddpehdr     *deh;
-    u_short            net;
-
-#ifdef BSD4_4
-    M_PREPEND( m, sizeof( struct ddpehdr ), M_WAIT );
-#else /* BSD4_4 */
-    for ( len = 0, m0 = m; m; m = m->m_next ) {
-       len += m->m_len;
-    }
-    MGET( m, M_WAIT, MT_HEADER );
-    if ( m == 0 ) {
-       m_freem( m0 );
-       return( ENOBUFS );
-    }
-    m->m_next = m0;
-#endif /* BSD4_4 */
-
-#ifndef BSD4_4
-# define align(a)      (((a)+3)&0xfc)
-    m->m_off = MMINOFF + align( SZ_ELAPHDR );
-    m->m_len = sizeof( struct ddpehdr );
-#endif /* ! BSD4_4 */
-
-    deh = mtod( m, struct ddpehdr *);
-    deh->deh_pad = 0;
-    deh->deh_hops = 0;
-
-#ifdef BSD4_4
-    deh->deh_len = m->m_pkthdr.len;
-#else /* BSD4_4 */
-    deh->deh_len = len + sizeof( struct ddpehdr );
-#endif /* BSD4_4 */
-
-    deh->deh_dnet = ddp->ddp_fsat.sat_addr.s_net;
-    deh->deh_dnode = ddp->ddp_fsat.sat_addr.s_node;
-    deh->deh_dport = ddp->ddp_fsat.sat_port;
-    deh->deh_snet = ddp->ddp_lsat.sat_addr.s_net;
-    deh->deh_snode = ddp->ddp_lsat.sat_addr.s_node;
-    deh->deh_sport = ddp->ddp_lsat.sat_port;
-
-    /*
-     * The checksum calculation is done after all of the other bytes have
-     * been filled in.
-     */
-    if ( ddp_cksum ) {
-       deh->deh_sum = at_cksum( m, sizeof( int ));
-    } else {
-       deh->deh_sum = 0;
-    }
-    deh->deh_bytes = htonl( deh->deh_bytes );
-
-    return( ddp_route( m, &ddp->ddp_route ));
-}
-
-    u_short
-at_cksum( m, skip )
-    struct mbuf        *m;
-    int                skip;
-{
-    u_char     *data, *end;
-    u_int32_t  cksum = 0;
-
-    for (; m; m = m->m_next ) {
-       for ( data = mtod( m, u_char * ), end = data + m->m_len; data < end;
-               data++ ) {
-           if ( skip ) {
-               skip--;
-               continue;
-           }
-           cksum = ( cksum + *data ) << 1;
-           if ( cksum & 0x00010000 ) {
-               cksum++;
-           }
-           cksum &= 0x0000ffff;
-       }
-    }
-
-    if ( cksum == 0 ) {
-       cksum = 0x0000ffff;
-    }
-    return( (u_short)cksum );
-}
-
-ddp_route( m, ro )
-    struct mbuf                *m;
-    struct route       *ro;
-{
-    struct sockaddr_at gate;
-    struct elaphdr     *elh;
-    struct mbuf                *m0;
-    struct at_ifaddr   *aa = NULL;
-    struct ifnet       *ifp;
-    int                        mlen;
-    u_short            net;
-
-    if ( ro->ro_rt && ( ifp = ro->ro_rt->rt_ifp )) {
-#ifdef BSD4_4
-       net = satosat( ro->ro_rt->rt_gateway )->sat_addr.s_net;
-#else /* BSD4_4 */
-       net = satosat( &ro->ro_rt->rt_gateway )->sat_addr.s_net;
-#endif /* BSD4_4 */
-       for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-           if ( aa->aa_ifp == ifp &&
-                   ntohs( net ) >= ntohs( aa->aa_firstnet ) &&
-                   ntohs( net ) <= ntohs( aa->aa_lastnet )) {
-               break;
-           }
-       }
-    }
-    if ( aa == NULL ) {
-       m_freem( m );
-       return( EINVAL );
-    }
-
-    /*
-     * There are several places in the kernel where data is added to
-     * an mbuf without ensuring that the mbuf pointer is aligned.
-     * This is bad for transition routing, since phase 1 and phase 2
-     * packets end up poorly aligned due to the three byte elap header.
-     */
-    if ( aa->aa_flags & AFA_PHASE2 ) {
-       for ( mlen = 0, m0 = m; m0; m0 = m0->m_next ) {
-           mlen += m0->m_len;
-       }
-       if (( m = m_pullup( m, MIN( MLEN, mlen ))) == 0 ) {
-           return( ENOBUFS );
-       }
-    } else {
-# ifdef notdef
-#ifdef BSD4_4
-       M_PREPEND( m, SZ_ELAPHDR, M_DONTWAIT );
-       if ( m == NULL ) {
-           return( ENOBUFS );
-       }
-#else /* BSD4_4 */
-       m->m_off -= SZ_ELAPHDR;
-       m->m_len += SZ_ELAPHDR;
-#endif /* BSD4_4 */
-# endif /* notdef */
-
-       MGET( m0, M_WAIT, MT_HEADER );
-       if ( m0 == 0 ) {
-           m_freem( m );
-           return( ENOBUFS );
-       }
-       m0->m_next = m;
-       m0->m_off = MMINOFF + align( sizeof( struct ether_header ));
-       m0->m_len = SZ_ELAPHDR;
-       m = m0;
-
-       elh = mtod( m, struct elaphdr *);
-       elh->el_snode = satosat( &aa->aa_addr )->sat_addr.s_node;
-       elh->el_type = ELAP_DDPEXTEND;
-       if ( ntohs( satosat( &ro->ro_dst )->sat_addr.s_net ) >=
-               ntohs( aa->aa_firstnet ) &&
-               ntohs( satosat( &ro->ro_dst )->sat_addr.s_net ) <=
-               ntohs( aa->aa_lastnet )) {
-           elh->el_dnode = satosat( &ro->ro_dst )->sat_addr.s_node;
-       } else {
-#ifdef BSD4_4
-           elh->el_dnode = satosat( ro->ro_rt->rt_gateway )->sat_addr.s_node;
-#else /* BSD4_4 */
-           elh->el_dnode = satosat( &ro->ro_rt->rt_gateway )->sat_addr.s_node;
-#endif /* BSD4_4 */
-       }
-    }
-
-    if ( ntohs( satosat( &ro->ro_dst )->sat_addr.s_net ) >=
-           ntohs( aa->aa_firstnet ) &&
-           ntohs( satosat( &ro->ro_dst )->sat_addr.s_net ) <=
-           ntohs( aa->aa_lastnet )) {
-       gate = *satosat( &ro->ro_dst );
-    } else {
-#ifdef BSD4_4
-       gate = *satosat( ro->ro_rt->rt_gateway );
-#else /* BSD4_4 */
-       gate = *satosat( &ro->ro_rt->rt_gateway );
-#endif /* BSD4_4 */
-    }
-    ro->ro_rt->rt_use++;
-
-#ifdef ultrix
-    /*
-     * SAIEW: We can't make changes to net/if_loop.c, so we don't route
-     * further than this: if it's going to go through the lookback,
-     * short-circuit to ddp_input(). Who needs queuing?
-     *
-     * Note: Passing NULL for the elaphdr is cool, since we'll only ever
-     * try to send long form ddp throught the loopback.
-     */
-    if ( ifp->if_flags & IFF_LOOPBACK ) {
-#ifdef notdef
-       m->m_off += SZ_ELAPHDR;
-       m->m_len -= SZ_ELAPHDR;
-#endif /* notdef */
-       ddp_input( m, ifp, (struct elaphdr *)NULL, 2 );
-       return( 0 );
-    }
-#endif /* ultrix */
-
-#ifdef _IBMR2
-    /*
-     * We can't make changes to the interface routines on RS6ks, and
-     * they don't provide hooks for if_output, so we just resolve
-     * our address here, and pass the packet as a raw ethernet packet.
-     * This doesn't work particularly well, if we aren't *on* ethernet,
-     * but it's ok for the moment.
-     */
-    if ( ! ( ifp->if_flags & IFF_LOOPBACK )) {
-       struct ether_header     eh;
-
-       if ( !aarpresolve(( struct arpcom *)ifp, m,
-               &gate, eh.ether_dhost )) {
-           return( 0 );
-       }
-       eh.ether_type = htons( ETHERTYPE_AT );
-       gate.sat_family = AF_UNSPEC;
-       bcopy( &eh, (*(struct sockaddr *)&gate).sa_data,
-               sizeof( (*(struct sockaddr *)&gate).sa_data ));
-    }
-#endif /* _IBMR2 */
-    return((*ifp->if_output)( ifp, m, &gate ));
-}
diff --git a/sys/netatalk/ddp_usrreq.c b/sys/netatalk/ddp_usrreq.c
deleted file mode 100644 (file)
index 50c0202..0000000
+++ /dev/null
@@ -1,536 +0,0 @@
-/*
- * $Id: ddp_usrreq.c,v 1.2 2001-06-29 14:14:47 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/errno.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/systm.h>
-#ifdef ibm032
-#include <sys/dir.h>
-#endif /* ibm032 */
-#include <sys/user.h>
-#include <sys/mbuf.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/socketvar.h>
-#include <sys/protosw.h>
-#include <net/if.h>
-#include <net/route.h>
-#ifdef _IBMR2
-#include <net/spl.h>
-#endif /* _IBMR2 */
-
-#include "at.h"
-#include "at_var.h"
-#include "ddp_var.h"
-#include "endian.h"
-
-struct ddpcb   *ddpcb = NULL;
-u_int32_t              ddp_sendspace = DDP_MAXSZ; /* Max ddp size + 1 (ddp_type) */
-u_int32_t              ddp_recvspace = 10 * ( 587 + sizeof( struct sockaddr_at ));
-
-/*ARGSUSED*/
-ddp_usrreq( so, req, m, addr, rights )
-    struct socket      *so;
-    int                        req;
-    struct mbuf                *m, *addr, *rights;
-{
-    struct ddpcb       *ddp;
-    int                        error = 0;
-
-    ddp = sotoddpcb( so );
-
-    if ( req == PRU_CONTROL ) {
-       return( at_control( (int) m, (caddr_t) addr,
-               (struct ifnet *) rights ));
-    }
-
-    if ( rights && rights->m_len ) {
-       error = EINVAL;
-       goto release;
-    }
-
-    if ( ddp == NULL && req != PRU_ATTACH ) {
-       error = EINVAL;
-       goto release;
-    }
-
-    switch ( req ) {
-    case PRU_ATTACH :
-       if ( ddp != NULL ) {
-           error = EINVAL;
-           break;
-       }
-       if (( error = at_pcballoc( so )) != 0 ) {
-           break;
-       }
-       error = soreserve( so, ddp_sendspace, ddp_recvspace );
-       break;
-
-    case PRU_DETACH :
-       at_pcbdetach( so, ddp );
-       break;
-
-    case PRU_BIND :
-       error = at_pcbsetaddr( ddp, addr );
-       break;
-    
-    case PRU_SOCKADDR :
-       at_sockaddr( ddp, addr );
-       break;
-
-    case PRU_CONNECT:
-       if ( ddp->ddp_fsat.sat_port != ATADDR_ANYPORT ) {
-           error = EISCONN;
-           break;
-       }
-
-       error = at_pcbconnect( ddp, addr );
-       if ( error == 0 )
-           soisconnected( so );
-       break;
-
-    case PRU_DISCONNECT:
-       if ( ddp->ddp_fsat.sat_addr.s_node == ATADDR_ANYNODE ) {
-           error = ENOTCONN;
-           break;
-       }
-       at_pcbdisconnect( ddp );
-       soisdisconnected( so );
-       break;
-
-    case PRU_SHUTDOWN:
-       socantsendmore( so );
-       break;
-
-    case PRU_SEND: {
-       int     s;
-
-       if ( addr ) {
-           if ( ddp->ddp_fsat.sat_port != ATADDR_ANYPORT ) {
-               error = EISCONN;
-               break;
-           }
-
-           s = splnet();
-           error = at_pcbconnect( ddp, addr );
-           if ( error ) {
-               splx( s );
-               break;
-           }
-       } else {
-           if ( ddp->ddp_fsat.sat_port == ATADDR_ANYPORT ) {
-               error = ENOTCONN;
-               break;
-           }
-       }
-
-       error = ddp_output( ddp, m );
-       m = NULL;
-       if ( addr ) {
-           at_pcbdisconnect( ddp );
-           splx( s );
-       }
-       }
-       break;
-
-    case PRU_ABORT:
-       soisdisconnected( so );
-       at_pcbdetach( so, ddp );
-       break;
-
-    case PRU_LISTEN:
-    case PRU_CONNECT2:
-    case PRU_ACCEPT:
-    case PRU_SENDOOB:
-    case PRU_FASTTIMO:
-    case PRU_SLOWTIMO:
-    case PRU_PROTORCV:
-    case PRU_PROTOSEND:
-       error = EOPNOTSUPP;
-       break;
-
-    case PRU_RCVD:
-    case PRU_RCVOOB:
-       /*
-        * Don't mfree. Good architecture...
-        */
-       return( EOPNOTSUPP );
-
-    case PRU_SENSE:
-       /*
-        * 1. Don't return block size.
-        * 2. Don't mfree.
-        */
-       return( 0 );
-
-    default:
-       error = EOPNOTSUPP;
-    }
-
-release:
-    if ( m != NULL ) {
-       m_freem( m );
-    }
-    return( error );
-}
-
-at_sockaddr( ddp, addr )
-    struct ddpcb       *ddp;
-    struct mbuf                *addr;
-{
-    struct sockaddr_at *sat;
-
-    addr->m_len = sizeof( struct sockaddr_at );
-    sat = mtod( addr, struct sockaddr_at *);
-    *sat = ddp->ddp_lsat;
-}
-
-at_pcbsetaddr( ddp, addr )
-    struct ddpcb       *ddp;
-    struct mbuf                *addr;
-{
-    struct sockaddr_at lsat, *sat;
-    struct at_ifaddr   *aa;
-    struct ddpcb       *ddpp;
-
-    if ( ddp->ddp_lsat.sat_port != ATADDR_ANYPORT ) { /* shouldn't be bound */
-       return( EINVAL );
-    }
-
-    if ( addr != 0 ) {                 /* validate passed address */
-       sat = mtod( addr, struct sockaddr_at *);
-       if ( addr->m_len != sizeof( *sat )) {
-           return( EINVAL );
-       }
-       if ( sat->sat_family != AF_APPLETALK ) {
-           return( EAFNOSUPPORT );
-       }
-
-       if ( sat->sat_addr.s_node != ATADDR_ANYNODE ||
-               sat->sat_addr.s_net != ATADDR_ANYNET ) {
-           for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-               if (( sat->sat_addr.s_net == AA_SAT( aa )->sat_addr.s_net ) &&
-                ( sat->sat_addr.s_node == AA_SAT( aa )->sat_addr.s_node )) {
-                   break;
-               }
-           }
-           if ( !aa ) {
-               return( EADDRNOTAVAIL );
-           }
-       }
-
-       if ( sat->sat_port != ATADDR_ANYPORT ) {
-           if ( sat->sat_port < ATPORT_FIRST ||
-                   sat->sat_port >= ATPORT_LAST ) {
-               return( EINVAL );
-           }
-#ifdef BSD4_4
-           if ( sat->sat_port < ATPORT_RESERVED &&
-                   suser( u.u_cred, &u.u_acflag )) {
-               return( EACCES );
-           }
-#else /* BSD4_4 */
-           if ( sat->sat_port < ATPORT_RESERVED && ( !suser())) {
-               return( EACCES );
-           }
-#endif /* BSD4_4 */
-       }
-    } else {
-       bzero( (caddr_t)&lsat, sizeof( struct sockaddr_at ));
-       lsat.sat_family = AF_APPLETALK;
-       sat = &lsat;
-    }
-
-    if ( sat->sat_addr.s_node == ATADDR_ANYNODE &&
-           sat->sat_addr.s_net == ATADDR_ANYNET ) {
-       if ( at_ifaddr == NULL ) {
-           return( EADDRNOTAVAIL );
-       }
-       sat->sat_addr = AA_SAT( at_ifaddr )->sat_addr;
-    }
-    ddp->ddp_lsat = *sat;
-
-    /*
-     * Choose port.
-     */
-    if ( sat->sat_port == ATADDR_ANYPORT ) {
-       for ( sat->sat_port = ATPORT_RESERVED;
-               sat->sat_port < ATPORT_LAST; sat->sat_port++ ) {
-           if ( ddp_ports[ sat->sat_port - 1 ] == 0 ) {
-               break;
-           }
-       }
-       if ( sat->sat_port == ATPORT_LAST ) {
-           return( EADDRNOTAVAIL );
-       }
-       ddp->ddp_lsat.sat_port = sat->sat_port;
-       ddp_ports[ sat->sat_port - 1 ] = ddp;
-    } else {
-       for ( ddpp = ddp_ports[ sat->sat_port - 1 ]; ddpp;
-               ddpp = ddpp->ddp_pnext ) {
-           if ( ddpp->ddp_lsat.sat_addr.s_net == sat->sat_addr.s_net &&
-                   ddpp->ddp_lsat.sat_addr.s_node == sat->sat_addr.s_node ) {
-               break;
-           }
-       }
-       if ( ddpp != NULL ) {
-           return( EADDRINUSE );
-       }
-       ddp->ddp_pnext = ddp_ports[ sat->sat_port - 1 ];
-       ddp_ports[ sat->sat_port - 1 ] = ddp;
-       if ( ddp->ddp_pnext ) {
-           ddp->ddp_pnext->ddp_pprev = ddp;
-       }
-    }
-
-    return( 0 );
-}
-
-at_pcbconnect( ddp, addr )
-    struct ddpcb       *ddp;
-    struct mbuf                *addr;
-{
-    struct sockaddr_at *sat = mtod( addr, struct sockaddr_at *);
-    struct route       *ro;
-    struct at_ifaddr   *aa = 0;
-    struct ifnet       *ifp;
-    u_short            hintnet = 0, net;
-
-    if ( addr->m_len != sizeof( *sat ))
-       return( EINVAL );
-    if ( sat->sat_family != AF_APPLETALK ) {
-       return( EAFNOSUPPORT );
-    }
-
-    /*
-     * Under phase 2, network 0 means "the network".  We take "the
-     * network" to mean the network the control block is bound to.
-     * If the control block is not bound, there is an error.
-     */
-    if ( sat->sat_addr.s_net == 0 && sat->sat_addr.s_node != ATADDR_ANYNODE ) {
-       if ( ddp->ddp_lsat.sat_port == ATADDR_ANYPORT ) {
-           return( EADDRNOTAVAIL );
-       }
-       hintnet = ddp->ddp_lsat.sat_addr.s_net;
-    }
-
-    ro = &ddp->ddp_route;
-    /*
-     * If we've got an old route for this pcb, check that it is valid.
-     * If we've changed our address, we may have an old "good looking"
-     * route here.  Attempt to detect it.
-     */
-    if ( ro->ro_rt ) {
-       if ( hintnet ) {
-           net = hintnet;
-       } else {
-           net = sat->sat_addr.s_net;
-       }
-       aa = 0;
-       if ( ifp = ro->ro_rt->rt_ifp ) {
-           for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-               if ( aa->aa_ifp == ifp &&
-                       ntohs( net ) >= ntohs( aa->aa_firstnet ) &&
-                       ntohs( net ) <= ntohs( aa->aa_lastnet )) {
-                   break;
-               }
-           }
-       }
-       if ( aa == NULL || ( satosat( &ro->ro_dst )->sat_addr.s_net !=
-               ( hintnet ? hintnet : sat->sat_addr.s_net ) ||
-               satosat( &ro->ro_dst )->sat_addr.s_node !=
-               sat->sat_addr.s_node )) {
-#ifdef ultrix
-           rtfree( ro->ro_rt );
-#else /* ultrix */
-           RTFREE( ro->ro_rt );
-#endif /* ultrix */
-           ro->ro_rt = (struct rtentry *)0;
-       }
-    }
-
-    /*
-     * If we've got no route for this interface, try to find one.
-     */
-    if ( ro->ro_rt == (struct rtentry *)0 ||
-        ro->ro_rt->rt_ifp == (struct ifnet *)0 ) {
-#ifdef BSD4_4
-       ro->ro_dst.sa_len = sizeof( struct sockaddr_at );
-#endif /* BSD4_4 */
-       ro->ro_dst.sa_family = AF_APPLETALK;
-       if ( hintnet != 0 ) {
-           satosat( &ro->ro_dst )->sat_addr.s_net = hintnet;
-       } else {
-           satosat( &ro->ro_dst )->sat_addr.s_net = sat->sat_addr.s_net;
-       }
-       satosat( &ro->ro_dst )->sat_addr.s_node = sat->sat_addr.s_node;
-       rtalloc( ro );
-    }
-
-    /*
-     * Make sure any route that we have has a valid interface.
-     */
-    aa = 0;
-    if ( ro->ro_rt && ( ifp = ro->ro_rt->rt_ifp )) {
-       for ( aa = at_ifaddr; aa; aa = aa->aa_next ) {
-           if ( aa->aa_ifp == ifp ) {
-               break;
-           }
-       }
-    }
-    if ( aa == 0 ) {
-       return( ENETUNREACH );
-    }
-
-    ddp->ddp_fsat = *sat;
-    if ( ddp->ddp_lsat.sat_port == ATADDR_ANYPORT ) {
-       return( at_pcbsetaddr( ddp, (struct mbuf *)0 ));
-    }
-    return( 0 );
-}
-
-at_pcbdisconnect( ddp )
-    struct ddpcb       *ddp;
-{
-    ddp->ddp_fsat.sat_addr.s_net = ATADDR_ANYNET;
-    ddp->ddp_fsat.sat_addr.s_node = ATADDR_ANYNODE;
-    ddp->ddp_fsat.sat_port = ATADDR_ANYPORT;
-}
-
-at_pcballoc( so )
-    struct socket      *so;
-{
-    struct ddpcb       *ddp;
-    struct mbuf                *m;
-
-    m = m_getclr( M_WAIT, MT_PCB );
-    ddp = mtod( m, struct ddpcb * );
-    ddp->ddp_lsat.sat_port = ATADDR_ANYPORT;
-
-    ddp->ddp_next = ddpcb;
-    ddp->ddp_prev = NULL;
-    ddp->ddp_pprev = NULL;
-    ddp->ddp_pnext = NULL;
-    if ( ddpcb ) {
-       ddpcb->ddp_prev = ddp;
-    }
-    ddpcb = ddp;
-
-    ddp->ddp_socket = so;
-    so->so_pcb = (caddr_t)ddp;
-    return( 0 );
-}
-
-at_pcbdetach( so, ddp )
-    struct socket      *so;
-    struct ddpcb       *ddp;
-{
-    soisdisconnected( so );
-    so->so_pcb = 0;
-    sofree( so );
-
-    /* remove ddp from ddp_ports list */
-    if ( ddp->ddp_lsat.sat_port != ATADDR_ANYPORT &&
-           ddp_ports[ ddp->ddp_lsat.sat_port - 1 ] != NULL ) {
-       if ( ddp->ddp_pprev != NULL ) {
-           ddp->ddp_pprev->ddp_pnext = ddp->ddp_pnext;
-       } else {
-           ddp_ports[ ddp->ddp_lsat.sat_port - 1 ] = ddp->ddp_pnext;
-       }
-       if ( ddp->ddp_pnext != NULL ) {
-           ddp->ddp_pnext->ddp_pprev = ddp->ddp_pprev;
-       }
-    }
-
-    if ( ddp->ddp_route.ro_rt ) {
-       rtfree( ddp->ddp_route.ro_rt );
-    }
-
-    if ( ddp->ddp_prev ) {
-       ddp->ddp_prev->ddp_next = ddp->ddp_next;
-    } else {
-       ddpcb = ddp->ddp_next;
-    }
-    if ( ddp->ddp_next ) {
-       ddp->ddp_next->ddp_prev = ddp->ddp_prev;
-    }
-
-    (void) m_free( dtom( ddp ));
-}
-
-/*
- * For the moment, this just find the pcb with the correct local address.
- * In the future, this will actually do some real searching, so we can use
- * the sender's address to do de-multiplexing on a single port to many
- * sockets (pcbs).
- */
-    struct ddpcb *
-ddp_search( from, to, aa )
-    struct sockaddr_at *from, *to;
-    struct at_ifaddr   *aa;
-{
-    struct ddpcb       *ddp;
-
-    /*
-     * Check for bad ports.
-     */
-    if ( to->sat_port < ATPORT_FIRST || to->sat_port >= ATPORT_LAST ) {
-       return( NULL );
-    }
-
-    /*
-     * Make sure the local address matches the sent address.  What about
-     * the interface?
-     */
-    for ( ddp = ddp_ports[ to->sat_port - 1 ]; ddp; ddp = ddp->ddp_pnext ) {
-       /* XXX should we handle 0.YY? */
-
-       /* XXXX.YY to socket on destination interface */
-       if ( to->sat_addr.s_net == ddp->ddp_lsat.sat_addr.s_net &&
-               to->sat_addr.s_node == ddp->ddp_lsat.sat_addr.s_node ) {
-           break;
-       }
-
-       /* 0.255 to socket on receiving interface */
-       if ( to->sat_addr.s_node == ATADDR_BCAST && ( to->sat_addr.s_net == 0 ||
-               to->sat_addr.s_net == ddp->ddp_lsat.sat_addr.s_net ) &&
-               ddp->ddp_lsat.sat_addr.s_net == AA_SAT( aa )->sat_addr.s_net ) {
-           break;
-       }
-
-       /* XXXX.0 to socket on destination interface */
-       if ( to->sat_addr.s_net == aa->aa_firstnet &&
-               to->sat_addr.s_node == 0 &&
-               ntohs( ddp->ddp_lsat.sat_addr.s_net ) >=
-               ntohs( aa->aa_firstnet ) &&
-               ntohs( ddp->ddp_lsat.sat_addr.s_net ) <=
-               ntohs( aa->aa_lastnet )) {
-           break;
-       }
-    }
-    return( ddp );
-}
-
-ddp_init()
-{
-    atintrq1.ifq_maxlen = IFQ_MAXLEN;
-    atintrq2.ifq_maxlen = IFQ_MAXLEN;
-}
-
-ddp_clean()
-{
-    struct ddpcb       *ddp;
-
-    for ( ddp = ddpcb; ddp; ddp = ddp->ddp_next ) {
-       at_pcbdetach( ddp->ddp_socket, ddp );
-    }
-}
diff --git a/sys/netatalk/ddp_var.h b/sys/netatalk/ddp_var.h
deleted file mode 100644 (file)
index 42654a2..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * $Id: ddp_var.h,v 1.2 2001-06-29 14:14:47 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1994 Regents of The University of Michigan.
- * All Rights Reserved.  See COPYRIGHT.
- */
-
-#ifndef _NETATALK_DDP_VAR_H
-#define _NETATALK_DDP_VAR_H 1
-
-#include <netatalk/endian.h>
-
-struct ddpcb {
-    struct sockaddr_at ddp_fsat, ddp_lsat;
-    struct route       ddp_route;
-    struct socket      *ddp_socket;
-    struct ddpcb       *ddp_prev, *ddp_next;
-    struct ddpcb       *ddp_pprev, *ddp_pnext;
-};
-
-#define sotoddpcb(so)  ((struct ddpcb *)(so)->so_pcb)
-
-struct ddpstat {
-    u_int32_t  ddps_short;             /* short header packets received */
-    u_int32_t  ddps_long;              /* long header packets received */
-    u_int32_t  ddps_nosum;             /* no checksum */
-    u_int32_t  ddps_badsum;            /* bad checksum */
-    u_int32_t  ddps_tooshort;          /* packet too short */
-    u_int32_t  ddps_toosmall;          /* not enough data */
-    u_int32_t  ddps_forward;           /* packets forwarded */
-    u_int32_t  ddps_encap;             /* packets encapsulated */
-    u_int32_t  ddps_cantforward;       /* packets rcvd for unreachable dest */
-    u_int32_t  ddps_nosockspace;       /* no space in sockbuf for packet */
-};
-
-#ifdef KERNEL
-struct ddpcb           *ddp_ports[ ATPORT_LAST ];
-struct ddpcb           *ddpcb;
-struct ddpstat         ddpstat;
-struct ddpcb           *ddp_search();
-#endif /* KERNEL */
-
-#endif /* netatalk/ddp_var.h */
diff --git a/sys/netatalk/endian.h b/sys/netatalk/endian.h
deleted file mode 100644 (file)
index a216e60..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * $Id: endian.h,v 1.9 2009-01-06 20:05:00 morgana Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved. See COPYRIGHT.
- *
- * This file handles both byte ordering and integer sizes.
- */
-
-#ifndef _ATALK_ENDIAN_H_
-#define _ATALK_ENDIAN_H_
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <netinet/in.h>
-
-#ifdef _IBMR2
-#include <sys/machine.h>
-#endif /*_IBMR2*/
-
-#ifdef _ISOC9X_SOURCE
-#include <inttypes.h>
-#ifndef __BIT_TYPES_DEFINED__
-#define __BIT_TYPES_DEFINED__
-typedef uint8_t        u_int8_t;
-typedef uint16_t       u_int16_t;
-typedef uint32_t       u_int32_t;
-typedef uint64_t       u_int64_t;
-#endif /* ! __BIT_TYPES_DEFINED__ */
-#else
-
-/* handle sunos and solaris */
-#ifdef sun
-#ifdef BSD4_3
-#include <sys/bitypes.h>
-#else /* BSD4_3 */
-/* solaris and sunos don't consistently define u_int*_t. */
-typedef unsigned char      u_int8_t;
-typedef unsigned short     u_int16_t;
-typedef unsigned int       u_int32_t;
-typedef int                int32_t;
-#endif /* BSD4_3 */
-
-typedef unsigned long long u_int64_t;
-
-#ifndef _SSIZE_T
-#define _SSIZE_T
-typedef int ssize_t;
-#endif /* ssize_t */
-
-#else /* sun */
-
-/* luckily ultrix is dead. as a result, we know what the sizes of
- * various types are forever. this makes some assumptions about integer
- * sizes. */
-#if defined (ultrix) || defined(HAVE_32BIT_LONGS) || defined(HAVE_64BIT_LONGS)
-#ifndef __BIT_TYPES_DEFINED__
-#define __BIT_TYPES_DEFINED__
-typedef unsigned char  u_int8_t;
-typedef unsigned short u_int16_t;
-typedef unsigned int   u_int32_t;
-typedef int            int32_t;
-#endif
-#endif /* ultrix || HAVE_32BIT_LONGS || HAVE_64BIT_LONGS */
-
-#ifdef ultrix
-typedef int            ssize_t;
-#endif /* ultrix */
-
-#ifdef HAVE_64BIT_LONGS
-typedef unsigned long u_int64_t;
-#else /* HAVE_64BIT_LONGS */
-/* check for long long support. currently, i assume that if 64-bit
- * ints exist that their made available via long long */
-#ifdef linux
-#include <endian.h> /* i think this is here for libc4 */
-#else /* linux */
-#if defined(HAVE_32BIT_LONGS) && !(defined(BSD4_4) || \
-                                 defined(NO_LARGE_VOL_SUPPORT))
-typedef unsigned long long  u_int64_t;
-#endif /* HAVE_32BIT_LONGS || !BSD4_4 || NO_LARGE_VOL_SUPPORT */
-#endif /* linux */
-#endif /* HAVE_64BIT_LONGS */
-#endif /* sun */
-#endif /* ISOC9X */
-
-# ifndef BYTE_ORDER
-#define LITTLE_ENDIAN  1234
-#define BIG_ENDIAN     4321
-#define PDP_ENDIAN     3412
-
-
-#if defined(WORDS_BIGENDIAN) || defined(_BIG_ENDIAN)
-#define BYTE_ORDER     BIG_ENDIAN
-#else
-#define BYTE_ORDER     LITTLE_ENDIAN
-#endif /* WORDS_BIGENDIAN */
-
-# ifndef ntohl
-# if defined( sun ) || defined( ultrix ) || defined( _IBMR2 )
-#if BYTE_ORDER == BIG_ENDIAN
-#define ntohl(x)       (x)
-#define ntohs(x)       (x)
-#define htonl(x)       (x)
-#define htons(x)       (x)
-
-#else /* BYTE_ORDER == BIG_ENDIAN */
-#if defined( mips ) && defined( KERNEL )
-#define        ntohl(x)        nuxi_l(x)
-#define        ntohs(x)        nuxi_s(x)
-#define        htonl(x)        nuxi_l(x)
-#define        htons(x)        nuxi_s(x)
-
-#else /* mips && KERNEL */
-
-#if !( defined( sun ) && ( defined( i386 ) || defined(__x86_64) ) )
-unsigned short ntohs(), htons();
-unsigned int  ntohl(), htonl();
-#endif /* ! ( sun && i386 ) */
-
-#endif /* mips && KERNEL */
-#endif /* BYTE_ORDER == BIGENDIAN*/
-# endif /* sun ultrix _IBMR2 */
-# endif /* ntohl */
-#endif /* BYTE_ORDER */
-
-#endif /* _ATALK_ENDIAN_H_ */
-
diff --git a/sys/netatalk/phase2.h b/sys/netatalk/phase2.h
deleted file mode 100644 (file)
index ec9735b..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * $Id: phase2.h,v 1.2 2001-06-29 14:14:47 rufustfirefly Exp $
- *
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- */
-
-# if defined( ultrix ) || defined( BSD4_4 )
-#include <net/if_llc.h>
-# else /* ultrix || BSD4_4 */
-
-#if defined( sun ) && !defined( __svr4__ )
-#include <net/if_ieee802.h>
-#endif /* sun && !__svr4__ */
-
-/*
- * Copyright (c) 1988 Regents of the University of California.
- * All rights reserved.
- *
- *      @(#)if_llc.h   7.2 (Berkeley) 6/28/90
- */
-
-/*
- * IEEE 802.2 Link Level Control headers, for use in conjunction with
- * 802.{3,4,5} media access control methods.
- *
- * Headers here do not use bit fields due to shortcommings in many
- * compilers.
- */
-
-struct llc {
-       u_char  llc_dsap;
-       u_char  llc_ssap;
-       union {
-           struct {
-               u_char control;
-               u_char format_id;
-               u_char class;
-               u_char window_x2;
-           } type_u;
-           struct {
-               u_char num_snd_x2;
-               u_char num_rcv_x2;
-           } type_i;
-           struct {
-               u_char control;
-               u_char num_rcv_x2;
-           } type_s;
-           struct {
-               u_char control;
-               u_char org_code[3];
-               u_short ether_type;
-           } type_snap;
-       } llc_un;
-};
-#define llc_control llc_un.type_u.control
-#define llc_fid llc_un.type_u.format_id
-#define llc_class llc_un.type_u.class
-#define llc_window llc_un.type_u.window_x2
-#define llc_org_code llc_un.type_snap.org_code
-#define llc_ether_type llc_un.type_snap.ether_type
-
-#define LLC_UI         0x3
-#define LLC_UI_P       0x13
-#define LLC_XID                0xaf
-#define LLC_XID_P      0xbf
-#define LLC_TEST       0xe3
-#define LLC_TEST_P     0xf3
-
-#define LLC_ISO_LSAP   0xfe
-#define LLC_SNAP_LSAP  0xaa
-
-# endif /* ultrix && BSD4_4 */
-
-#if defined( sun ) || defined( ibm032 )
-#define SIOCPHASE1     _IOW(i, 100, struct ifreq)      /* AppleTalk phase 1 */
-#define SIOCPHASE2     _IOW(i, 101, struct ifreq)      /* AppleTalk phase 2 */
-#endif /* sun || ibm032 */
-
-#if defined( ultrix ) || defined( BSD4_4 ) || defined( _IBMR2 )
-#define SIOCPHASE1     _IOW('i', 100, struct ifreq)    /* AppleTalk phase 1 */
-#define SIOCPHASE2     _IOW('i', 101, struct ifreq)    /* AppleTalk phase 2 */
-#endif /* ultrix || BSD4_4 || _IBMR2 */
diff --git a/sys/netbsd/.gitignore b/sys/netbsd/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/sys/netbsd/Makefile.am b/sys/netbsd/Makefile.am
deleted file mode 100644 (file)
index 454fafe..0000000
+++ /dev/null
@@ -1 +0,0 @@
-SUBDIRS = netatalk
diff --git a/sys/netbsd/netatalk/.gitignore b/sys/netbsd/netatalk/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/sys/netbsd/netatalk/Makefile.am b/sys/netbsd/netatalk/Makefile.am
deleted file mode 100644 (file)
index f4ec9dc..0000000
+++ /dev/null
@@ -1 +0,0 @@
-EXTRA_DIST = endian.h
diff --git a/sys/netbsd/netatalk/endian.h b/sys/netbsd/netatalk/endian.h
deleted file mode 100644 (file)
index a1957e2..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-
-/*
- * netatalk/endian.h
- *
- * This file is a dummy replacement for endian.h. NetBSD includes
- * machine/endian.h in sys/types.h, and it was decided that a
- * second include file was not needed. This file is included to
- * make all the source code compile correctly.
- */
diff --git a/sys/solaris/.gitignore b/sys/solaris/.gitignore
deleted file mode 100644 (file)
index 2f9b1d7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-ddp
-.gitignore
-*.o
diff --git a/sys/solaris/Makefile.in b/sys/solaris/Makefile.in
deleted file mode 100644 (file)
index 9f6c89a..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-# Solaris specific defines, passed to subdirectories.
-# To use Sun CC, uncomment the CC and KFLAGS variables.
-#
-# $Id: Makefile.in,v 1.6 2009-11-25 14:58:26 franklahm Exp $
-# This Makefile.in is not automake generated
-# copy and paste from automake Makefile.in
-srcdir = @srcdir@
-top_srcdir = @top_srcdir@
-VPATH = @srcdir@
-# end copy and paste
-
-CC     = @CC@
-# LD hardcoded to sun ld, GNU ld has been reported to cause some trouble with 64 bit
-LD     = /usr/ccs/bin/ld
-
-INSTALL = @INSTALL@
-GREP=@GREP@
-
-
-# -D_ISOC9X_SOURCE is handled by OSVERSION. basically, it's not needed
-# with 2.5.1.
-DEFS=  -D__svr4__ -DSOLARIS -I../../sys/generic \
-       -I.. @DEFS@
-
-# Variables
-KCFLAGS=@KCFLAGS@
-KLDFLAGS=@KLDFLAGS@
-COMPILE_KERNEL_GCC=@COMPILE_KERNEL_GCC@
-SPARC64=@COMPILE_64BIT_KMODULE@
-SOLARIS_MODULE_FALSE=@SOLARIS_MODULE_FALSE@
-SOLARIS_MODULE_TRUE=@SOLARIS_MODULE_TRUE@
-USE_SOLARIS_TRUE=@USE_SOLARIS_TRUE@
-USE_SOLARIS_FALSE=@USE_SOLARIS_FALSE@
-
-OPTOPTS=
-
-# Local build stuff.
-
-SRC= linkage.c tpi.c dlpi.c ioc.c if.c aarp.c ddp.c sock.c rt.c
-OBJ= linkage.o tpi.o dlpi.o ioc.o if.o aarp.o ddp.o sock.o rt.o
-HEADERS= if.h ioc.h rt.h sock.h
-EXTRA_DIST= ddp.conf Makefile.in $(SRC) $(HEADERS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-
-INCPATH=       -I../../include -I../netatalk -I../..
-CFLAGS=        ${DEFS} ${OPTOPTS} ${INCPATH} ${KCFLAGS}
-
-# Not building on Solaris
-@USE_SOLARIS_FALSE@all:
-
-# No Solaris kernel module build
-@USE_SOLARIS_TRUE@@SOLARIS_MODULE_FALSE@all:
-@USE_SOLARIS_TRUE@@SOLARIS_MODULE_FALSE@       @echo
-@USE_SOLARIS_TRUE@@SOLARIS_MODULE_FALSE@       @echo "Solaris kernel module cannot be build"
-@SOLARIS_MODULE_FALSE@install:
-@SOLARIS_MODULE_FALSE@
-@SOLARIS_MODULE_FALSE@uninstall:
-
-# Build Solaris kernel module
-@SOLARIS_MODULE_TRUE@all :     kernel
-
-@SOLARIS_MODULE_TRUE@kernel: ddp 
-
-@SOLARIS_MODULE_TRUE@FRC: 
-
-@SOLARIS_MODULE_TRUE@ddp :     ${OBJ}
-@SOLARIS_MODULE_TRUE@  ${LD} ${KLDFLAGS} -r -o ddp ${OBJ}
-
-@SOLARIS_MODULE_TRUE@linkage.o : linkage.c
-@SOLARIS_MODULE_TRUE@  ${CC} ${CFLAGS} -DVERSION=\"`cat ../../VERSION`\" -c linkage.c
-
-@SOLARIS_MODULE_TRUE@kuninstall : FRC
-@SOLARIS_MODULE_TRUE@  @if [ x"${SPARC64}" = x"yes" ] ; then \
-@SOLARIS_MODULE_TRUE@          ${RM} /usr/kernel/drv/sparcv9/ddp; \
-@SOLARIS_MODULE_TRUE@          ${RM} /usr/kernel/strmod/sparcv9/ddp; \
-@SOLARIS_MODULE_TRUE@  else \
-@SOLARIS_MODULE_TRUE@          ${RM} /usr/kernel/drv/ddp; \
-@SOLARIS_MODULE_TRUE@          ${RM} /usr/kernel/strmod/ddp; \
-@SOLARIS_MODULE_TRUE@  fi
-@SOLARIS_MODULE_TRUE@  ${RM} /usr/kernel/drv/ddp.conf
-@SOLARIS_MODULE_TRUE@  -rem_drv ddp
-@SOLARIS_MODULE_TRUE@  sync;sync;sync
-
-@SOLARIS_MODULE_TRUE@kinstall : kernel kuninstall
-@SOLARIS_MODULE_TRUE@  @if [ x"${SPARC64}" = x"yes" ]; then \
-@SOLARIS_MODULE_TRUE@          ${INSTALL} -o root -g sys -c ddp /usr/kernel/drv/sparcv9/ddp; \
-@SOLARIS_MODULE_TRUE@          ln /usr/kernel/drv/sparcv9/ddp /usr/kernel/strmod/sparcv9/ddp; \
-@SOLARIS_MODULE_TRUE@  else \
-@SOLARIS_MODULE_TRUE@          ${INSTALL} -o root -g sys -c ddp /usr/kernel/drv/ddp; \
-@SOLARIS_MODULE_TRUE@          ln /usr/kernel/drv/ddp /usr/kernel/strmod/ddp; \
-@SOLARIS_MODULE_TRUE@  fi
-@SOLARIS_MODULE_TRUE@  ${INSTALL} -o root -g sys -c ddp.conf /usr/kernel/drv/ddp.conf
-@SOLARIS_MODULE_TRUE@  add_drv -m '* 0666 root sys' ddp
-@SOLARIS_MODULE_TRUE@  sync;sync;sync
-@SOLARIS_MODULE_TRUE@  @if ${GREP} 'ddp' /etc/netconfig; then \
-@SOLARIS_MODULE_TRUE@            echo "netconfig already contains a ddp module, skipping"; \
-@SOLARIS_MODULE_TRUE@        else \
-@SOLARIS_MODULE_TRUE@            echo "adding ddp module to netconfig"; \
-@SOLARIS_MODULE_TRUE@            echo "ddp        tpi_clts      -    appletalk ddp   /dev/ddp        -" >> /etc/netconfig; \
-@SOLARIS_MODULE_TRUE@  fi
-@SOLARIS_MODULE_TRUE@  @echo "Installed Solaris kernel module"
-
-
-@SOLARIS_MODULE_TRUE@install:
-@SOLARIS_MODULE_TRUE@  @echo
-@SOLARIS_MODULE_TRUE@  @echo "To install the Solaris kernel module type 'make kinstall' as root user"
-
-@SOLARIS_MODULE_TRUE@uninstall:
-@SOLARIS_MODULE_TRUE@  @echo
-@SOLARIS_MODULE_TRUE@  @echo "To uninstall the Solaris kernel module type 'make kuninstall' as root user"
-
-# copy and paste from automake Makefile.in
-distdir : $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
-       list='$(DISTFILES)'; for file in $$list; do \
-         case $$file in \
-           $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
-           $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
-         esac; \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
-         if test "$$dir" != "$$file" && test "$$dir" != "."; then \
-           dir="/$$dir"; \
-           $(mkdir_p) "$(distdir)$$dir"; \
-         else \
-           dir=''; \
-         fi; \
-         if test -d $$d/$$file; then \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
-           fi; \
-           cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
-         else \
-           test -f $(distdir)/$$file \
-           || cp -p $$d/$$file $(distdir)/$$file \
-           || exit 1; \
-         fi; \
-       done
-# end copy and paste
-
-clean : sysclean
-
-klean sysclean :
-       rm -f a.out core* *.o *.bak *[Ee]rrs tags
-       rm -f ddp
-
-distclean: clean
-        -rm -f Makefile
-
-maintainer-clean: distclean
-
-depend :
-
-check:
-
-tags:
-
-dvi:
-
-installcheck:
-
-install-exec:
-
-# DO NOT DELETE THIS LINE
-
diff --git a/sys/solaris/aarp.c b/sys/solaris/aarp.c
deleted file mode 100644 (file)
index ea3cf67..0000000
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * $Id: aarp.c,v 1.4 2005-04-28 20:50:07 bfernhomberg Exp $
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/byteorder.h>
-#include <sys/errno.h>
-#include <sys/stream.h>
-#include <sys/ethernet.h>
-#include <sys/kmem.h>
-#include <sys/cmn_err.h>
-#include <sys/ddi.h>
-#include <netinet/arp.h>
-#include <net/if.h>
-
-#ifdef STDC_HEADERS
-#include <strings.h>
-#else
-#include <string.h>
-#endif
-
-#include <netatalk/at.h>
-#include <netatalk/aarp.h>
-#include <netatalk/phase2.h>
-
-#include "if.h"
-
-struct aarplist {
-    struct aarplist    *aal_next, *aal_prev;
-    struct at_addr     aal_addr;
-    u_char             aal_hwaddr[ ETHERADDRL ];
-    u_char             aal_age;
-    u_char             aal_flags;
-    mblk_t             *aal_m;
-};
-
-    struct aarplist *
-aarp_find( struct atif_data *aid, ushort net, unchar node )
-{
-    struct aarplist    *aal;
-
-    for ( aal = aid->aid_aarplist; aal != NULL; aal = aal->aal_next ) {
-       if ( aal->aal_addr.s_net == net && aal->aal_addr.s_node == node ) {
-           break;
-       }
-    }
-    return( aal );
-}
-
-    struct aarplist *
-aarp_alloc( struct atif_data *aid, ushort net, unchar node )
-{
-    struct aarplist    *aal;
-
-    for ( aal = aid->aid_aarplist; aal != NULL; aal = aal->aal_next ) {
-       if ( aal->aal_addr.s_net == net && aal->aal_addr.s_node == node ) {
-           return( aal );
-       }
-    }
-
-    if ( aid->aid_aarpflist == NULL ) {
-        if (( aal = (struct aarplist *)kmem_alloc( sizeof( struct aarplist ),
-                KM_NOSLEEP )) == NULL ) {
-            return( NULL );
-        }
-    } else {
-       aal = aid->aid_aarpflist;
-       aid->aid_aarpflist = aal->aal_next;
-       if ( aid->aid_aarpflist != NULL ) {
-           aid->aid_aarpflist->aal_prev = NULL;
-       }
-    }
-
-    aal->aal_addr.s_net = net;
-    aal->aal_addr.s_node = node;
-    bzero( aal->aal_hwaddr, sizeof( aal->aal_hwaddr ));
-    aal->aal_age = 0;
-    aal->aal_flags = 0;
-    aal->aal_m = NULL;
-
-    aal->aal_next = aid->aid_aarplist;
-    aal->aal_prev = NULL;
-    if ( aid->aid_aarplist != NULL ) {
-       aid->aid_aarplist->aal_prev = aal;
-    }
-    aid->aid_aarplist = aal;
-
-    return( aal );
-}
-
-/*
- * Move entry to free list.
- */
-    void
-aarp_free( struct atif_data *aid, struct aarplist *aal )
-{
-    if ( aal->aal_next != NULL ) {
-       aal->aal_next->aal_prev = aal->aal_prev;
-    }
-    if ( aal->aal_prev != NULL ) {
-       aal->aal_prev->aal_next = aal->aal_next;
-    }
-    if ( aid->aid_aarplist == aal ) {
-       aid->aid_aarplist = aal->aal_next;
-    }
-
-    if ( aal->aal_m != NULL ) {
-       freemsg( aal->aal_m );
-       aal->aal_m = NULL;
-    }
-
-    aal->aal_prev = NULL;
-    aal->aal_next = aid->aid_aarpflist;
-    if ( aid->aid_aarpflist != NULL ) {
-       aid->aid_aarpflist->aal_prev = aal;
-    }
-    aid->aid_aarpflist = aal;
-    return;
-}
-
-    void
-aarp_timeout( void *ptr )
-{
-    struct atif_data   *aid = (struct atif_data *) ptr;
-    struct aarplist    *aal, *p;
-
-    aid->aid_aarptimeo = qtimeout( aid->aid_q, aarp_timeout,
-           (caddr_t)aid, 60 * hz );
-    for ( aal = aid->aid_aarplist; aal != NULL; aal = p ) {
-       p = aal->aal_next;
-       if ( ++aal->aal_age < (( aal->aal_flags ) ? 5 : 3 )) {
-           continue;
-       }
-       aarp_free( aid, aal );
-    }
-    return;
-}
-
-    void
-aarp_init( struct atif_data *aid )
-{
-    aid->aid_aarptimeo = qtimeout( aid->aid_q, aarp_timeout,
-           (caddr_t)aid, 60 * hz );
-    return;
-}
-
-    void
-aarp_clean( struct atif_data *aid )
-{
-    struct aarplist *aal, *p;
-
-    if ( aid->aid_aarptimeo != 0 ) {
-       quntimeout( aid->aid_q, aid->aid_aarptimeo );
-       aid->aid_aarptimeo = 0;
-    }
-
-    for ( aal = aid->aid_aarplist; aal != NULL; aal = p ) {
-       p = aal->aal_next;
-       if ( aal->aal_m != NULL ) {
-           freemsg( aal->aal_m );
-           aal->aal_m = NULL;
-       }
-       kmem_free( aal, sizeof( struct aarplist ));
-    }
-    aid->aid_aarplist = NULL;
-
-    for ( aal = aid->aid_aarpflist; aal != NULL; aal = p ) {
-       p = aal->aal_next;
-       if ( aal->aal_m != NULL ) {
-           freemsg( aal->aal_m );
-           aal->aal_m = NULL;
-       }
-       kmem_free( aal, sizeof( struct aarplist ));
-    }
-    aid->aid_aarpflist = NULL;
-
-    return;
-}
-
-    int
-aarp_rput( queue_t *q, mblk_t *m )
-{
-    struct atif_data   *aid = (struct atif_data *)q->q_ptr;
-    struct ether_aarp  *ea;
-    struct aarplist    *aal;
-    ushort             tpnet, spnet, op;
-
-    if ( m->b_wptr - m->b_rptr < sizeof( struct ether_aarp )) {
-       cmn_err( CE_NOTE, "aarp_rput short packet\n" );
-       goto done;
-    }
-
-    ea = (struct ether_aarp *)m->b_rptr;
-
-    if ( ea->aarp_hrd != htons( AARPHRD_ETHER ) ||
-           ea->aarp_pro != htons( ETHERTYPE_AT ) ||
-           ea->aarp_hln != sizeof( ea->aarp_sha ) ||
-           ea->aarp_pln != sizeof( ea->aarp_spu )) {
-       cmn_err( CE_NOTE, "aarp_rput bad constants\n" );
-       goto done;
-    }
-
-    if ( bcmp( ea->aarp_sha, aid->aid_hwaddr, sizeof( ea->aarp_sha )) == 0 ) {
-       goto done;
-    }
-
-    op = ntohs( ea->aarp_op );
-    bcopy( ea->aarp_tpnet, &tpnet, sizeof( tpnet ));
-    bcopy( ea->aarp_spnet, &spnet, sizeof( spnet ));
-
-    if ( aid->aid_flags & AIDF_PROBING ) {
-       if ( tpnet == aid->aid_sat.sat_addr.s_net &&
-               ea->aarp_tpnode == aid->aid_sat.sat_addr.s_node ) {
-           aid->aid_flags &= ~AIDF_PROBING;
-           aid->aid_flags |= AIDF_PROBEFAILED;
-           cmn_err( CE_NOTE, "aarp_rput probe collision %s\n", aid->aid_name );
-       }
-    } else {
-       if ( tpnet == aid->aid_sat.sat_addr.s_net &&
-               ea->aarp_tpnode == aid->aid_sat.sat_addr.s_node ) {
-           switch ( op ) {
-           case AARPOP_REQUEST :
-               aal = aarp_alloc( aid, spnet, ea->aarp_spnode );
-               bcopy( ea->aarp_sha, aal->aal_hwaddr, sizeof( ea->aarp_sha ));
-               aal->aal_age = 0;
-               aal->aal_flags = 1;             /* complete */
-           case AARPOP_PROBE :
-               aarp_send( aid, AARPOP_RESPONSE, ea->aarp_sha,
-                       spnet, ea->aarp_spnode );
-               break;
-
-           case AARPOP_RESPONSE :
-               if (( aal =
-                       aarp_find( aid, spnet, ea->aarp_spnode )) == NULL ) {
-                   break;
-               }
-               bcopy( ea->aarp_sha, aal->aal_hwaddr, sizeof( ea->aarp_sha ));
-               aal->aal_age = 0;
-               aal->aal_flags = 1;             /* complete */
-               if ( aal->aal_m != NULL ) {
-                   dl_unitdata_req( WR( q ), aal->aal_m, ETHERTYPE_AT,
-                           aal->aal_hwaddr );
-                   aal->aal_m = NULL;
-               }
-               break;
-
-           default :
-               cmn_err( CE_NOTE, "aarp_rput bad op %X\n", op );
-               break;
-           }
-       } else {
-           switch ( op ) {
-           case AARPOP_REQUEST :
-               break;
-           case AARPOP_PROBE :
-               if (( aal =
-                       aarp_find( aid, spnet, ea->aarp_spnode )) != NULL ) {
-                   aarp_free( aid, aal );
-               }
-               break;
-
-           case AARPOP_RESPONSE :
-               cmn_err( CE_NOTE, "aarp_rput someone using our address\n" );
-               break;
-
-           default :
-               cmn_err( CE_NOTE, "aarp_rput bad op %X\n", op );
-               break;
-           }
-       }
-    }
-
-done :
-    freemsg( m );
-    return( 0 );
-}
-
-    void
-aarp_send( struct atif_data *aid, int op, caddr_t hwaddr,
-       ushort net, unchar node )
-{
-    mblk_t             *m;
-    struct ether_aarp  *ea;
-
-    if (( m = allocb( sizeof( struct ether_aarp ), BPRI_HI )) == NULL ) {
-       return;
-    }
-    m->b_wptr = m->b_rptr + sizeof( struct ether_aarp );
-    ea = (struct ether_aarp *)m->b_rptr;
-    bzero( (caddr_t)ea, sizeof( struct ether_aarp ));
-
-    ea->aarp_hrd = htons( AARPHRD_ETHER );
-    ea->aarp_pro = htons( ETHERTYPE_AT );
-    ea->aarp_hln = sizeof( ea->aarp_sha );
-    ea->aarp_pln = sizeof( ea->aarp_spu );
-    ea->aarp_op = htons( op );
-    bcopy( aid->aid_hwaddr, ea->aarp_sha, sizeof( ea->aarp_sha ));
-
-    if ( hwaddr == NULL ) {
-       bzero( ea->aarp_tha, sizeof( ea->aarp_tha ));
-    } else {
-       bcopy( hwaddr, ea->aarp_tha, sizeof( ea->aarp_tha ));
-    }
-
-    ea->aarp_tpnode = node;
-    bcopy( &aid->aid_sat.sat_addr.s_net, ea->aarp_spnet,
-           sizeof( ea->aarp_spnet ));
-    bcopy( &net, ea->aarp_tpnet, sizeof( ea->aarp_tpnet ));
-    ea->aarp_spnode = aid->aid_sat.sat_addr.s_node;
-    ea->aarp_tpnode = node;
-
-    if ( hwaddr == NULL ) {
-       dl_unitdata_req( WR( aid->aid_q ), m, ETHERTYPE_AARP,
-               at_multicastaddr );
-    } else {
-       dl_unitdata_req( WR( aid->aid_q ), m, ETHERTYPE_AARP, hwaddr );
-    }
-    return;
-}
-
-    int
-aarp_resolve( struct atif_data *aid, mblk_t *m, struct sockaddr_at *sat )
-{
-    struct aarplist    *aal;
-
-    if ( sat->sat_addr.s_node == ATADDR_BCAST ) {
-       dl_unitdata_req( WR( aid->aid_q ), m, ETHERTYPE_AT, at_multicastaddr );
-       return( 0 );
-    }
-
-    if (( aal = aarp_alloc( aid, sat->sat_addr.s_net, sat->sat_addr.s_node )) ==
-           NULL ) {
-       freemsg( m );
-       return( ENOMEM );
-    }
-    aal->aal_age = 0;
-
-    if ( aal->aal_flags ) {    /* complete */
-       dl_unitdata_req( WR( aid->aid_q ), m, ETHERTYPE_AT, aal->aal_hwaddr );
-    } else {
-       /* send aarp request */
-       if ( aal->aal_m != NULL ) {
-           freemsg( aal->aal_m );
-       }
-       /* either freed above, in timeout, or sent in aarp_rput() */
-       aal->aal_m = m; 
-       aarp_send( aid, AARPOP_REQUEST, NULL,
-               sat->sat_addr.s_net, sat->sat_addr.s_node );
-    }
-    return( 0 );
-}
diff --git a/sys/solaris/ddp.c b/sys/solaris/ddp.c
deleted file mode 100644 (file)
index 526c5f8..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * $Id: ddp.c,v 1.3 2002-01-17 06:13:02 srittau Exp $
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/stream.h>
-#include <sys/cmn_err.h>
-#include <sys/socket.h>
-#include <sys/errno.h>
-#include <sys/tihdr.h>
-#include <sys/ddi.h>
-#include <sys/ethernet.h>
-#include <net/if.h>
-
-#ifdef STDC_HEADERS
-#include <strings.h>
-#else
-#include <string.h>
-#endif
-
-#include <netatalk/endian.h>
-#include <netatalk/ddp.h>
-#include <netatalk/at.h>
-
-#include "if.h"
-#include "sock.h"
-
-    int
-ddp_rput( struct atif_data *aid, mblk_t *m )
-{
-    struct atif_data   *daid;
-    struct ddpehdr     *deh;
-    struct sockaddr_at sat;
-    struct sock_data   *sd;
-
-    if ( m->b_wptr - m->b_rptr < sizeof( struct ddpehdr )) {
-       cmn_err( CE_NOTE, "ddp_rput short packet\n" );
-       freemsg( m );
-       return( EINVAL );
-    }
-
-    deh = (struct ddpehdr *)m->b_rptr;
-
-    sat.sat_addr.s_net = deh->deh_dnet;
-    sat.sat_addr.s_node = deh->deh_dnode;
-    sat.sat_port = deh->deh_dport;
-
-    if (( daid = if_dest( aid, &sat )) != NULL ) {
-       if (( sd = sock_dest( daid, &sat )) != NULL ) {
-           if ( sd->sd_state != TS_IDLE ) {
-               freemsg( m );
-               return( EHOSTDOWN );
-           }
-           bzero( (caddr_t)&sat, sizeof( struct sockaddr_at ));
-           sat.sat_family = AF_APPLETALK;
-           sat.sat_addr.s_net = deh->deh_snet;
-           sat.sat_addr.s_node = deh->deh_snode;
-           sat.sat_port = deh->deh_sport;
-           adjmsg( m, sizeof( struct ddpehdr ));
-           t_unitdata_ind( WR( sd->sd_q ), m, &sat );
-       } else {
-           /* toss it */
-           freemsg( m );
-           return( EHOSTDOWN );
-       }
-    } else {
-       /* route it */
-       freemsg( m );
-       return( ENETUNREACH );
-    }
-    return( 0 );
-}
diff --git a/sys/solaris/ddp.conf b/sys/solaris/ddp.conf
deleted file mode 100644 (file)
index e0257ad..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-#
-# Netatalk driver's configuration file
-#
-
-name="ddp" parent="pseudo" instance=0;
diff --git a/sys/solaris/dlpi.c b/sys/solaris/dlpi.c
deleted file mode 100644 (file)
index 2be6de3..0000000
+++ /dev/null
@@ -1,478 +0,0 @@
-/* $Id: dlpi.c,v 1.2 2002-01-17 06:13:02 srittau Exp $
- */
-
-#include <config.h>
-
-#include <sys/types.h>
-#include <sys/kmem.h>
-#include <sys/stream.h>
-#include <sys/conf.h>
-#include <sys/modctl.h>
-#include <sys/cmn_err.h>
-#include <sys/ddi.h>
-#include <sys/socket.h>
-#include <sys/sockio.h>
-#include <sys/dlpi.h>
-#include <sys/ethernet.h>
-#include <sys/byteorder.h>
-#include <sys/sunddi.h>
-#include <net/if.h>
-#include <errno.h>
-
-#include <netatalk/phase2.h>
-#include <netatalk/at.h>
-
-#include "ioc.h"
-#include "if.h"
-
-u_char at_multicastaddr[ ETHERADDRL ] = {
-    0x09, 0x00, 0x07, 0xff, 0xff, 0xff,
-};
-u_char at_org_code[ 3 ] = {
-    0x08, 0x00, 0x07,
-};
-u_char aarp_org_code[ 3 ] = {
-    0x00, 0x00, 0x00,
-};
-
-    static int
-dlpi_open( queue_t *q, dev_t *dev, int oflag, int sflag, cred_t *cred )
-{
-    struct atif_data   *aid;
-    int                        err = 0;
-
-    if (( err = drv_priv( cred )) != 0 ) {
-       return( err );
-    }
-    if (( aid = if_alloc( q )) == NULL ) {
-       return( ENOMEM );
-    }
-    q->q_ptr = (void *)aid;
-
-    qprocson( q );
-    return( err );
-}
-
-    static int
-dlpi_close( queue_t *q, int oflag, cred_t *cred )
-{
-    struct atif_data   *aid = (struct atif_data *)q->q_ptr;
-
-    qprocsoff( q );
-    if_free( aid );
-    return( 0 );
-}
-
-    static int
-dl_bind_req( queue_t *q, ulong sap )
-{
-    union DL_primitives        *dl;
-    mblk_t             *m;
-
-    if (( m = allocb( DL_BIND_REQ_SIZE, BPRI_HI )) == NULL ) {
-       return( ENOMEM );
-    }
-    m->b_wptr = m->b_rptr + DL_BIND_REQ_SIZE;
-    m->b_datap->db_type = M_PROTO;
-
-    dl = (union DL_primitives *)m->b_rptr;
-    dl->dl_primitive = DL_BIND_REQ;
-    dl->bind_req.dl_sap = sap;
-    dl->bind_req.dl_max_conind = 0;
-    dl->bind_req.dl_service_mode = DL_CLDLS;
-    dl->bind_req.dl_conn_mgmt = 0;
-    dl->bind_req.dl_xidtest_flg = 0;   /* XXX */
-    putnext( q, m );
-    return( 0 );
-}
-
-    static int
-dl_attach_req( queue_t *q, ulong ppa )
-{
-    union DL_primitives        *dl;
-    mblk_t             *m;
-
-    if (( m = allocb( DL_ATTACH_REQ_SIZE, BPRI_HI )) == NULL ) {
-       return( ENOMEM );
-    }
-    m->b_wptr = m->b_rptr + DL_ATTACH_REQ_SIZE;
-    m->b_datap->db_type = M_PROTO;
-
-    dl = (union DL_primitives *)m->b_rptr;
-    dl->dl_primitive = DL_ATTACH_REQ;
-    dl->attach_req.dl_ppa = ppa;
-    putnext( q, m );
-    return( 0 );
-}
-
-    int
-dl_enabmulti_req( queue_t *q, caddr_t addr )
-{
-    union DL_primitives        *dl;
-    mblk_t             *m;
-
-    if (( m = allocb( DL_ENABMULTI_REQ_SIZE + ETHERADDRL, BPRI_HI )) == NULL ) {
-       return( ENOMEM );
-    }
-    m->b_wptr = m->b_rptr + DL_ENABMULTI_REQ_SIZE;
-    m->b_datap->db_type = M_PROTO;
-
-    dl = (union DL_primitives *)m->b_rptr;
-    dl->dl_primitive = DL_ENABMULTI_REQ;
-    dl->enabmulti_req.dl_addr_length = ETHERADDRL;
-    dl->enabmulti_req.dl_addr_offset = m->b_wptr - m->b_rptr;
-    bcopy( addr, m->b_wptr, ETHERADDRL );
-    m->b_wptr += ETHERADDRL;
-    putnext( q, m );
-    return( 0 );
-}
-
-    int
-dl_unitdata_req( queue_t *q, mblk_t *m0, ushort type, caddr_t addr )
-{
-    union DL_primitives        *dl;
-    struct llc         *llc;
-    mblk_t             *m1, *m;
-    ushort              len;
-
-    /* len = msgdsize( m0 ) + sizeof( struct llc ); */
-
-    if (( m1 = allocb( sizeof( struct llc ), BPRI_HI )) == NULL ) {
-       cmn_err( CE_NOTE, "dl_unitdate_req NOMEM 1\n" );
-       return( ENOMEM );
-    }
-    m1->b_wptr = m1->b_rptr + sizeof( struct llc );
-    m1->b_datap->db_type = M_DATA;
-    llc = (struct llc *)m1->b_rptr;
-
-    llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
-    llc->llc_control = LLC_UI;
-    if ( type == ETHERTYPE_AARP ) {
-       bcopy( aarp_org_code, llc->llc_org_code, sizeof( aarp_org_code ));
-    } else if ( type == ETHERTYPE_AT ) {
-       bcopy( at_org_code, llc->llc_org_code, sizeof( aarp_org_code ));
-    } else {
-       cmn_err( CE_NOTE, "dl_unitdate_req type %X\n", type );
-       return( EINVAL );
-    }
-    llc->llc_ether_type = htons( type );
-    linkb( m1, m0 );
-
-    if (( m = allocb( DL_UNITDATA_REQ_SIZE + ETHERADDRL + sizeof( ushort ),
-                     BPRI_HI )) == NULL ) {
-       cmn_err( CE_NOTE, "dl_unitdate_req NOMEM 2\n" );
-       return( ENOMEM );
-    }
-    m->b_wptr = m->b_rptr + DL_UNITDATA_REQ_SIZE;
-    m->b_datap->db_type = M_PROTO;
-    linkb( m, m1 );
-
-    dl = (union DL_primitives *)m->b_rptr;
-    dl->dl_primitive = DL_UNITDATA_REQ;
-    dl->unitdata_req.dl_dest_addr_length = ETHERADDRL + sizeof ( ushort );
-    dl->unitdata_req.dl_dest_addr_offset = m->b_wptr - m->b_rptr;
-
-    bcopy(addr, m->b_wptr, ETHERADDRL );
-    m->b_wptr += ETHERADDRL;
-    len = 0;
-    bcopy( &len, m->b_wptr, sizeof( ushort ));
-    m->b_wptr += sizeof( ushort );
-    putnext( q, m );
-    return( 0 );
-}
-
-    static int
-dlpi_rput( queue_t *q, mblk_t *m )
-{
-    struct atif_data   *aid = (struct atif_data *)q->q_ptr;
-    union DL_primitives        *dl;
-    mblk_t             *m0;
-    struct llc         *llc;
-
-    switch ( m->b_datap->db_type ) {
-    case M_IOCNAK :
-       putnext( q, m );
-       return( 0 );
-
-    case M_PCPROTO :
-    case M_PROTO :
-       if ( m->b_wptr - m->b_rptr < sizeof( dl->dl_primitive )) {
-           break;
-       }
-       dl = (union DL_primitives *)m->b_rptr;
-       switch ( dl->dl_primitive ) {
-       case DL_UNITDATA_IND :
-           if ( m->b_wptr - m->b_rptr < sizeof( DL_UNITDATA_IND_SIZE )) {
-               break;
-           }
-           if (( m0 = unlinkb( m )) == NULL ) {
-               break;
-           }
-           if ( m0->b_wptr - m0->b_rptr < sizeof( struct llc )) {
-               freemsg( m0 );
-               break;
-           }
-           llc = (struct llc *)m0->b_rptr;
-           if ( llc->llc_dsap != LLC_SNAP_LSAP ||
-                   llc->llc_ssap != LLC_SNAP_LSAP ||
-                   llc->llc_control != LLC_UI ) {
-               freemsg( m0 );
-               break;
-           }
-
-           if ( bcmp( llc->llc_org_code, at_org_code,
-                   sizeof( at_org_code )) == 0 &&
-                   ntohs( llc->llc_ether_type ) == ETHERTYPE_AT ) {
-               adjmsg( m0, sizeof( struct llc ));
-               ddp_rput( aid, m0 );
-           } else if ( bcmp( llc->llc_org_code, aarp_org_code,
-                   sizeof( aarp_org_code )) == 0 &&
-                   ntohs( llc->llc_ether_type ) == ETHERTYPE_AARP ) {
-               adjmsg( m0, sizeof( struct llc ));
-               aarp_rput( q, m0 );
-           } else {
-               freemsg( m0 );
-           }
-           break;
-
-       case DL_OK_ACK :
-           if ( m->b_wptr - m->b_rptr < sizeof( DL_OK_ACK_SIZE )) {
-               break;
-           }
-           switch ( dl->ok_ack.dl_correct_primitive ) {
-           case DL_ATTACH_REQ :
-               if ( aid->aid_state != DL_ATTACH_PENDING ) {
-                   cmn_err( CE_NOTE, "dlpi_rput DL_OK_ACK attach state %d\n",
-                           aid->aid_state );
-                   break;
-               }
-               if ( aid->aid_c.c_type != IF_UNITSEL ) {
-                   cmn_err( CE_NOTE, "dlpi_rput DL_OK_ACK attach context %x\n",
-                           aid->aid_c.c_type );
-                   break;
-               }
-
-               if ( WR(q)->q_next == NULL || WR(q)->q_next->q_qinfo == NULL ||
-                       WR(q)->q_next->q_qinfo->qi_minfo == NULL ||
-                       WR(q)->q_next->q_qinfo->qi_minfo->mi_idname == NULL ) {
-                   cmn_err( CE_NOTE, "dlpi_rput can't get interface name\n" );
-                   break;
-               }
-
-               if_name( aid, WR(q)->q_next->q_qinfo->qi_minfo->mi_idname,
-                       aid->aid_c.c_u.u_unit.uu_ppa );
-
-               aid->aid_state = DL_BIND_PENDING;
-
-#ifdef i386
-               /*
-                * As of Solaris 7 (nice name), the i386 arch needs to be
-                * bound as 0 to receive 802 frames.  However, in the same
-                * OS, Sparcs must be bound as ETHERMTU (or at least not 0)
-                * to receive the same frames.  A bug?  In the Solaris 7
-                * (nice name) kernel?
-                */
-               dl_bind_req( WR( q ), 0 );
-#else /* i386 */
-               dl_bind_req( WR( q ), ETHERMTU );
-#endif /* i386 */
-               break;
-
-           case DL_ENABMULTI_REQ :
-               if ( aid->aid_c.c_type != SIOCADDMULTI ) {
-                   cmn_err( CE_NOTE,
-                           "dlpi_rput DL_OK_ACK enabmulti context %x\n",
-                           aid->aid_c.c_type );
-                   break;
-               }
-
-               ioc_ok_ack( aid->aid_c.c_u.u_multi.um_q,
-                       aid->aid_c.c_u.u_multi.um_m, 0 );
-               aid->aid_c.c_type = 0;
-               aid->aid_c.c_u.u_multi.um_q = NULL;
-               aid->aid_c.c_u.u_multi.um_m = 0;
-               break;
-
-           default :
-               cmn_err( CE_CONT, "!dlpi_rput DL_OK_ACK unhandled %d\n",
-                       dl->ok_ack.dl_correct_primitive );
-               break;
-           }
-           break;
-
-       case DL_BIND_ACK :
-           if ( m->b_wptr - m->b_rptr < sizeof( DL_BIND_ACK_SIZE )) {
-               break;
-           }
-           if ( aid->aid_state != DL_BIND_PENDING ) {
-               break;
-           }
-           if ( aid->aid_c.c_type != IF_UNITSEL ) {
-               break;
-           }
-           bcopy( m->b_rptr + dl->bind_ack.dl_addr_offset, aid->aid_hwaddr, 
-                   dl->bind_ack.dl_addr_length );
-           aid->aid_state = DL_IDLE;
-           ioc_ok_ack( WR(q), aid->aid_c.c_u.u_unit.uu_m, 0 );
-           aid->aid_c.c_type = 0;
-           aid->aid_c.c_u.u_unit.uu_m = NULL;
-           aid->aid_c.c_u.u_unit.uu_ppa = 0;
-           break;
-
-       case DL_ERROR_ACK :
-           if ( m->b_wptr - m->b_rptr < sizeof( DL_ERROR_ACK_SIZE )) {
-               break;
-           }
-
-           switch ( aid->aid_c.c_type ) {
-           case IF_UNITSEL :
-               if ( dl->error_ack.dl_errno == DL_SYSERR ) {
-                   ioc_error_ack( WR(q), aid->aid_c.c_u.u_unit.uu_m,
-                           dl->error_ack.dl_unix_errno );
-               } else {
-                   cmn_err( CE_CONT, "dlpi_rput DL_ERROR_ACK 0x%x\n",
-                           dl->error_ack.dl_errno );
-                   ioc_error_ack( WR(q), aid->aid_c.c_u.u_unit.uu_m, EINVAL );
-               }
-               aid->aid_c.c_type = 0;
-               aid->aid_c.c_u.u_unit.uu_m = NULL;
-               aid->aid_c.c_u.u_unit.uu_ppa = 0;
-               break;
-
-           default :
-               cmn_err( CE_NOTE, "dlpi_rput DL_ERROR_ACK unhandled %d %d %d\n",
-                       dl->error_ack.dl_error_primitive,
-                       dl->error_ack.dl_errno, dl->error_ack.dl_unix_errno );
-               break;
-           }
-           break;
-
-       default :
-           cmn_err( CE_NOTE, "dlpi_rput M_PCPROTO 0x%x\n", dl->dl_primitive );
-           break;
-       }
-       break;
-
-    default :
-       cmn_err( CE_NOTE, "dlpi_rput 0x%X\n", m->b_datap->db_type );
-       break;
-    }
-
-    freemsg( m );
-    return( 0 );
-}
-
-    static int
-dlpi_wput( queue_t *q, mblk_t *m )
-{
-    struct atif_data           *aid = (struct atif_data *)RD(q)->q_ptr;
-    struct iocblk              *ioc;
-    int                                rc;
-
-    switch ( m->b_datap->db_type ) {
-    case M_IOCTL :
-       if ( m->b_wptr - m->b_rptr < sizeof( struct iocblk )) {
-           freemsg( m );
-           break;
-       }
-       ioc = (struct iocblk *)m->b_rptr;
-       switch ( ioc->ioc_cmd ) {
-       case IF_UNITSEL :
-           if ( ioc->ioc_count != TRANSPARENT ) {
-               cmn_err( CE_NOTE, "dlpi_wput IF_UNITSEL non-TRANSPARENT\n" );
-               ioc_error_ack( q, m, EINVAL );
-               break;
-           }
-           if ( m->b_cont == NULL ) {
-               cmn_err( CE_NOTE, "dlpi_wput IF_UNITSEL no arg\n" );
-               ioc_error_ack( q, m, EINVAL );
-               break;
-           }
-           if ( aid->aid_state != DL_UNATTACHED ) {
-               cmn_err( CE_NOTE, "dlpi_wput IF_UNITSEL already attached\n" );
-               ioc_error_ack( q, m, EINVAL );
-               break;
-           }
-           if ( aid->aid_c.c_type != 0 ) {
-               cmn_err( CE_NOTE, "dlpi_wput IF_UNITSEL context %x\n",
-                       aid->aid_c.c_type );
-               ioc_error_ack( q, m, EINVAL );
-               break;
-           }
-
-           aid->aid_state = DL_ATTACH_PENDING;
-           aid->aid_c.c_type = IF_UNITSEL;
-           aid->aid_c.c_u.u_unit.uu_m = m;
-           aid->aid_c.c_u.u_unit.uu_ppa = *(ulong *)m->b_cont->b_rptr;
-           if (( rc = dl_attach_req( q, aid->aid_c.c_u.u_unit.uu_ppa )) < 0 ) {
-               ioc_error_ack( q, m, rc );
-               break;
-           }
-           break;
-
-       default :
-           cmn_err( CE_NOTE, "dlpi_wput M_IOCTL 0x%X\n", ioc->ioc_cmd );
-           putnext( q, m );
-           break;
-       }
-       break;
-
-    default :
-       cmn_err( CE_NOTE, "dlpi_wput 0x%X\n", m->b_datap->db_type );
-       freemsg( m );
-       break;
-    }
-
-    return( 0 );
-}
-
-static struct module_info      dlpi_info = {
-    0,
-    "ddp",
-    0,
-    1500,
-    3000,
-    64
-};
-
-static struct qinit            dlpi_rinit = {
-    dlpi_rput,         /* qi_putp */
-    NULL,              /* qi_srvp */
-    dlpi_open,         /* qi_qopen */
-    dlpi_close,                /* qi_qclose */
-    NULL,
-    &dlpi_info,                /* qi_minfo */
-    NULL,
-};
-
-static struct qinit            dlpi_winit = {
-    dlpi_wput,         /* qi_putp */
-    NULL,              /* qi_srvp */
-    NULL,              /* qi_qopen */
-    NULL,              /* qi_qclose */
-    NULL,
-    &dlpi_info,                /* qi_minfo */
-    NULL,
-};
-
-static struct streamtab                dlpi_stream = {
-    &dlpi_rinit,
-    &dlpi_winit,
-    NULL,
-    NULL
-};
-
-static struct fmodsw           dlpi_fmodsw = {
-    "ddp",
-    &dlpi_stream,
-    D_NEW | D_MP | D_MTPERMOD
-};
-
-/*
- * DDP Streams module.  This module is pushed on DLPI drivers by atalkd.
- */
-struct modlstrmod              dlpi_lstrmod = {
-    &mod_strmodops,
-    "DDP Streams module",
-    &dlpi_fmodsw,
-};
diff --git a/sys/solaris/if.c b/sys/solaris/if.c
deleted file mode 100644 (file)
index 7e0918f..0000000
+++ /dev/null
@@ -1,382 +0,0 @@
-/* $Id: if.c,v 1.3 2005-04-28 20:50:07 bfernhomberg Exp $
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/sockio.h>
-#include <sys/stream.h>
-#include <sys/kmem.h>
-#include <sys/dlpi.h>
-#include <sys/cmn_err.h>
-#include <sys/errno.h>
-#include <sys/byteorder.h>
-#include <sys/ethernet.h>
-#include <sys/ddi.h>
-#include <net/if.h>
-#include <netinet/arp.h>
-
-#ifdef STDC_HEADERS
-#include <strings.h>
-#else
-#include <string.h>
-#endif
-
-#include <netatalk/at.h>
-#include <netatalk/aarp.h>
-
-#include "if.h"
-#include "rt.h"
-#include "ioc.h"
-
-static struct atif_data        *interfaces = NULL;
-
-    struct atif_data *
-if_primary()
-{
-    return( interfaces );
-}
-
-    struct atif_data *
-if_alloc( queue_t *q )
-{
-    struct atif_data   *aid;
-
-    if (( aid = kmem_zalloc( sizeof( struct atif_data ), KM_SLEEP )) == NULL ) {
-       return( NULL );
-    }
-    aid->aid_q = q;
-    aid->aid_state = DL_UNATTACHED;
-
-    return( aid );
-}
-
-/*
- * Name an interface, insert it in our list of interfaces.  If this is the
- * first interface, create the loopback interface.  If it's not the first
- * interfaces, keep the first interface the same, i.e. the first configured
- * interface should be the primary interface.
- */
-    int
-if_name( struct atif_data *aid, char *name, ulong ppa )
-{
-    sprintf( aid->aid_name, "%s%ld", name, ppa );
-
-    if ( interfaces == NULL ) {                /* create fake loopback */
-       if (( interfaces = if_alloc( NULL )) == NULL ) {
-           return( ENOMEM );
-       }
-       strcpy( interfaces->aid_name, "lo0" );
-       interfaces->aid_state = DL_IDLE;
-       bzero( interfaces->aid_hwaddr, sizeof( interfaces->aid_hwaddr ));
-       interfaces->aid_flags = AIDF_LOOPBACK;
-       interfaces->aid_c.c_type = 0;
-
-       aid->aid_next = interfaces;
-       aid->aid_next->aid_prev = aid;
-       interfaces = aid;
-    } else {
-       aid->aid_next = interfaces->aid_next;
-       aid->aid_prev = interfaces;
-       aid->aid_next->aid_prev = aid;
-       interfaces->aid_next = aid;
-    }
-
-    aarp_init( aid );
-    return( 0 );
-}
-
-    void
-if_free( struct atif_data *aid )
-{
-    if ( aid->aid_c.c_type != 0 ) {
-       cmn_err( CE_NOTE, "if_free context %x\n", aid->aid_c.c_type );
-       return;
-    }
-
-    aarp_clean( aid );
-
-    if ( aid->aid_next != NULL ) {
-       aid->aid_next->aid_prev = aid->aid_prev;
-    }
-    if ( aid->aid_prev != NULL ) {
-       aid->aid_prev->aid_next = aid->aid_next;
-    }
-    if ( aid == interfaces ) {
-       interfaces = aid->aid_next;
-    }
-    kmem_free( aid, sizeof( struct atif_data ));
-
-    if ( interfaces != NULL && interfaces->aid_next == NULL ) {
-       kmem_free( interfaces, sizeof( struct atif_data ));
-       interfaces = NULL;
-    }
-    return;
-}
-
-    int
-if_getaddr( char *name, struct sockaddr_at *sat )
-{
-    struct atif_data   *aid;
-
-    for ( aid = interfaces; aid != NULL; aid = aid->aid_next ) {
-       if ( strcmp( name, aid->aid_name ) == 0 ) {
-           break;
-       }
-    }
-    if ( aid == NULL ) {
-       return( EADDRNOTAVAIL );
-    }
-
-    bcopy( &aid->aid_sat, sat, sizeof( struct sockaddr_at ));
-    return( 0 );
-}
-
-    int
-if_addmulti( queue_t *q, mblk_t *m, char *name, struct sockaddr *sa )
-{
-    struct atif_data   *aid;
-
-    for ( aid = interfaces; aid != NULL; aid = aid->aid_next ) {
-       if ( strcmp( name, aid->aid_name ) == 0 ) {
-           break;
-       }
-    }
-    if ( aid == NULL ) {
-       return( EADDRNOTAVAIL );
-    }
-
-    if ( aid->aid_c.c_type != 0 ) {
-       cmn_err( CE_NOTE, "if_addmulti context %x\n", aid->aid_c.c_type );
-       return( EINVAL );
-    }
-
-    aid->aid_c.c_type = SIOCADDMULTI;
-    aid->aid_c.c_u.u_multi.um_q = q;
-    aid->aid_c.c_u.u_multi.um_m = m;
-    dl_enabmulti_req( WR( aid->aid_q ), sa->sa_data );
-
-    return( 0 );
-}
-
-    void
-if_pickaddr( void *ptr )
-{
-    struct atif_data *aid = (struct atif_data*) ptr;
-
-    if ( aid->aid_c.c_type != SIOCSIFADDR ) {
-       cmn_err( CE_NOTE, "if_pickaddr context %x\n", aid->aid_c.c_type );
-       return;
-    }
-
-    if ( aid->aid_flags & AIDF_PROBEFAILED ) {
-       aid->aid_flags &= ~AIDF_PROBEFAILED;
-       /* choose new address */
-       for (;;) {
-           if ( aid->aid_c.c_u.u_addr.ua_nodecnt == 0 ) {
-               /* if we've exausted all addresses, fail */
-               if ( aid->aid_c.c_u.u_addr.ua_netcnt == 0 ) {
-                   ioc_error_ack( aid->aid_c.c_u.u_addr.ua_q,
-                           aid->aid_c.c_u.u_addr.ua_m, EADDRINUSE );
-                   aid->aid_c.c_type = 0;
-                   aid->aid_c.c_u.u_addr.ua_q = NULL;
-                   aid->aid_c.c_u.u_addr.ua_m = NULL;
-                   aid->aid_c.c_u.u_addr.ua_probecnt = 0;
-                   aid->aid_c.c_u.u_addr.ua_netcnt = 0;
-                   aid->aid_c.c_u.u_addr.ua_nodecnt = 0;
-               } else {
-                   aid->aid_c.c_u.u_addr.ua_nodecnt = 256;
-                   aid->aid_c.c_u.u_addr.ua_netcnt--;
-                   if ( ntohs(aid->aid_sat.sat_addr.s_net) >
-                           ntohs(aid->aid_nr.nr_lastnet) ) {
-                       aid->aid_sat.sat_addr.s_net = aid->aid_nr.nr_firstnet;
-                   } else
-                     aid->aid_sat.sat_addr.s_net = 
-                       htons(ntohs(aid->aid_sat.sat_addr.s_net) + 1);
-               }
-           } else {
-               aid->aid_sat.sat_addr.s_node++;
-               aid->aid_c.c_u.u_addr.ua_nodecnt--;
-               if ( aid->aid_sat.sat_addr.s_node == 0 || 
-                       aid->aid_sat.sat_addr.s_node == 255 || 
-                       aid->aid_sat.sat_addr.s_node == 254 ) {
-                   continue;
-               }
-               break;
-           }
-       }
-    }
-    if ( aid->aid_c.c_u.u_addr.ua_probecnt-- <= 0 ) {
-       aid->aid_flags &= ~AIDF_PROBING;
-       /* worked, send ioctl reponse */
-       ioc_ok_ack( aid->aid_c.c_u.u_addr.ua_q, aid->aid_c.c_u.u_addr.ua_m, 0 );
-       aid->aid_c.c_type = 0;
-       aid->aid_c.c_u.u_addr.ua_q = NULL;
-       aid->aid_c.c_u.u_addr.ua_m = NULL;
-       aid->aid_c.c_u.u_addr.ua_probecnt = 0;
-       aid->aid_c.c_u.u_addr.ua_netcnt = 0;
-       aid->aid_c.c_u.u_addr.ua_nodecnt = 0;
-       return;
-    }
-
-    aarp_send( aid, AARPOP_PROBE, NULL,
-           aid->aid_sat.sat_addr.s_net, aid->aid_sat.sat_addr.s_node );
-    qtimeout( aid->aid_q, if_pickaddr, (caddr_t)aid, hz / 5 );
-}
-
-    int
-if_setaddr( queue_t *q, mblk_t *m, char *name, struct sockaddr_at *sat )
-{
-    struct atif_data   *aid;
-    struct netrange    nr;
-    ulong              time;
-
-    for ( aid = interfaces; aid != NULL; aid = aid->aid_next ) {
-       if ( strcmp( name, aid->aid_name ) == 0 ) {
-           break;
-       }
-    }
-    if ( aid == NULL ) {
-       return( EADDRNOTAVAIL );
-    }
-
-    if ( aid->aid_c.c_type != 0 ) {
-       cmn_err( CE_NOTE, "if_setaddr context %x\n", aid->aid_c.c_type );
-       return( EINVAL );
-    }
-
-    bcopy( sat->sat_zero, &nr, sizeof( struct netrange ));
-
-    if ( aid->aid_flags & AIDF_LOOPBACK ) {
-       aid->aid_sat = *sat;
-       aid->aid_nr = nr;
-
-       /* routes? */
-
-       ioc_ok_ack( q, m, 0 );
-       return( 0 );
-    }
-
-    drv_getparm( TIME, &time );
-    if ( sat->sat_addr.s_net == ATADDR_ANYNET ) {
-       if ( nr.nr_lastnet == nr.nr_firstnet ) {
-           sat->sat_addr.s_net = nr.nr_firstnet;
-       } else {
-           sat->sat_addr.s_net = htons(ntohs(nr.nr_firstnet) + time %
-                   (ntohs(nr.nr_lastnet) - ntohs(nr.nr_firstnet)));
-       }
-    } else {
-       if ( ntohs( sat->sat_addr.s_net ) < ntohs( nr.nr_firstnet ) ||
-               ntohs( sat->sat_addr.s_net ) > ntohs( nr.nr_lastnet )) {
-           return( EINVAL );
-       }
-    }
-
-    if ( sat->sat_addr.s_node == ATADDR_ANYNODE ) {
-       sat->sat_addr.s_node = time;
-    }
-
-    aid->aid_flags |= AIDF_PROBING;
-    aid->aid_sat = *sat;
-    aid->aid_nr = nr;
-
-    aid->aid_c.c_type = SIOCSIFADDR;
-    aid->aid_c.c_u.u_addr.ua_q = q;
-    aid->aid_c.c_u.u_addr.ua_m = m;
-    aid->aid_c.c_u.u_addr.ua_probecnt = 10;
-    aid->aid_c.c_u.u_addr.ua_netcnt = ntohs(nr.nr_lastnet) - 
-      ntohs(nr.nr_firstnet);
-    aid->aid_c.c_u.u_addr.ua_nodecnt = 256;
-    qtimeout( aid->aid_q, if_pickaddr, (caddr_t)aid, 0 );
-    return( 0 );
-}
-
-/*
- * These three routines are all a big mess...
- */
-    struct atif_data *
-if_dest( struct atif_data *aid, struct sockaddr_at *sat )
-{
-    struct atif_data   *dest;
-
-    for ( dest = interfaces; dest != NULL; dest = dest->aid_next ) {
-       if ((( sat->sat_addr.s_net == 0 && aid == dest ) ||
-               ( ntohs(sat->sat_addr.s_net) >= 
-                 ntohs(dest->aid_nr.nr_firstnet) &&
-               ntohs(sat->sat_addr.s_net) <= 
-                 ntohs(dest->aid_nr.nr_lastnet) )) &&
-               ( sat->sat_addr.s_node == dest->aid_sat.sat_addr.s_node ||
-               sat->sat_addr.s_node == ATADDR_BCAST )) {
-           break;
-       }
-    }
-    if ( dest == NULL ) {
-       return( NULL );
-    }
-    return( dest );
-}
-
-    struct atif_data *
-if_withaddr( struct sockaddr_at *sat )
-{
-    struct atif_data   *dest;
-
-    for ( dest = interfaces; dest != NULL; dest = dest->aid_next ) {
-       if ( sat->sat_addr.s_net == dest->aid_sat.sat_addr.s_net &&
-               sat->sat_addr.s_node == dest->aid_sat.sat_addr.s_node ) {
-           break;
-       }
-    }
-    return( dest );
-}
-
-    struct atif_data *
-if_withnet( struct sockaddr_at *sat )
-{
-    struct atif_data   *dest;
-
-    for ( dest = interfaces; dest != NULL; dest = dest->aid_next ) {
-       if ( ntohs(sat->sat_addr.s_net) >= ntohs(dest->aid_nr.nr_firstnet) &&
-               ntohs(sat->sat_addr.s_net) <= ntohs(dest->aid_nr.nr_lastnet)) {
-           break;
-       }
-    }
-    return( dest );
-}
-
-    int
-if_route( struct atif_data *aid, mblk_t *m, struct sockaddr_at *sat )
-{
-    struct sockaddr_at gate;
-
-    if ( sat->sat_addr.s_net == 0 ) {
-       if ( sat->sat_addr.s_node == 0 ) {
-           aid = if_withaddr( sat );
-       }
-       if ( aid == NULL ) {
-           freemsg( m );
-           return( ENETUNREACH );
-       }
-       gate = *sat;
-    } else {
-       if ( rt_gate( sat, &gate ) < 0 ) {      /* no route */
-           gate = *sat;
-       }
-       if (( aid = if_withaddr( &gate )) == NULL ) {
-           if (( aid = if_withnet( &gate )) == NULL ) {
-               freemsg( m );
-               return( ENETUNREACH );
-           }
-       }
-    }
-
-    if ( aid->aid_flags & AIDF_LOOPBACK ) {
-       return( ddp_rput( aid, m ));
-    } else {
-       /* the aarp layer is expected to send broadcast packets appropriately */
-       return( aarp_resolve( aid, m, &gate ));
-    }
-}
diff --git a/sys/solaris/if.h b/sys/solaris/if.h
deleted file mode 100644 (file)
index 0348d10..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-struct atif_data {
-    struct atif_data   *aid_next, *aid_prev;
-    char               aid_name[ IFNAMSIZ ];
-    unchar             aid_hwaddr[ ETHERADDRL ];
-    queue_t            *aid_q;                         /* RD() side */
-    int                        aid_state;
-    int                        aid_flags;
-    struct sockaddr_at aid_sat;
-    struct netrange    aid_nr;
-    struct aarplist    *aid_aarplist, *aid_aarpflist;
-    /* solaris 7 wants timeout_id_t, but solaris 2.6 doesn't have that.
-     * so, we compromise with an unsigned long as we know that's big
-     * enough to hold a pointer. */
-#ifdef HAVE_TIMEOUT_ID_T
-    timeout_id_t       aid_aarptimeo;
-#else
-    unsigned long      aid_aarptimeo;
-#endif
-    /*
-     * A little bit of cleverness, to overcome the inability of
-     * streams to sleep.  The type of context must be checked before
-     * the data is accessed.  The atif_data can't be freed if the
-     * type is non-zero.
-     */
-    struct {
-       int             c_type;                 /* ioctl command */
-       union {
-           struct {                            /* unit select */
-               mblk_t          *uu_m;
-               ulong           uu_ppa;
-           }           u_unit;
-           struct {                            /* set addr */
-               mblk_t          *ua_m;
-               queue_t         *ua_q;
-               int             ua_probecnt;
-               int             ua_netcnt;
-               int             ua_nodecnt;
-           }           u_addr;
-           struct {                            /* add multi */
-               mblk_t          *um_m;
-               queue_t         *um_q;
-           }           u_multi;
-       }               c_u;
-    }                  aid_c;
-};
-
-#define AIDF_LOOPBACK  (1<<0)
-#define AIDF_PROBING   (1<<1)
-#define AIDF_PROBEFAILED       (1<<2)
-
-extern u_char  at_multicastaddr[ ETHERADDRL ];
-extern u_char  at_org_code[ 3 ];
-extern u_char  aarp_org_code[ 3 ];
-
-int                    if_setaddr( queue_t *, mblk_t *, char *,
-                               struct sockaddr_at * );
-int                    if_getaddr(  char *, struct sockaddr_at * );
-int                    if_addmulti( queue_t *, mblk_t *, char *,
-                               struct sockaddr * );
-
-struct atif_data       *if_alloc( queue_t * );
-void                   if_free( struct atif_data * );
-int                    if_name( struct atif_data *, char *, ulong );
-int                    if_attach( struct atif_data *, char * );
-struct atif_data       *if_primary( void );
-struct atif_data       *if_dest( struct atif_data *, struct sockaddr_at * );
-struct atif_data       *if_withaddr( struct sockaddr_at * );
-struct atif_data       *if_withnet( struct sockaddr_at * );
-int                    if_route( struct atif_data *, mblk_t *,
-                               struct sockaddr_at * );
-
-int                    dl_unitdata_req( queue_t *, mblk_t *, ushort, caddr_t );
-int                    dl_enabmulti_req( queue_t *, caddr_t );
-void                   aarp_send( struct atif_data *, int, caddr_t,
-                               ushort, unchar );
-int                    aarp_rput( queue_t *, mblk_t * );
-int                    aarp_resolve( struct atif_data *, mblk_t *,
-                               struct sockaddr_at *);
-void                   aarp_init( struct atif_data * );
-void                   aarp_clean( struct atif_data * );
-int                    ddp_rput( struct atif_data *, mblk_t * );
diff --git a/sys/solaris/ioc.c b/sys/solaris/ioc.c
deleted file mode 100644 (file)
index 4a53f9a..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-/* $Id: ioc.c,v 1.3 2005-04-28 20:50:07 bfernhomberg Exp $
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/stream.h>
-#include <sys/cmn_err.h>
-
-#ifdef STDC_HEADERS
-#include <strings.h>
-#else
-#include <string.h>
-#endif
-
-#include "ioc.h"
-
-    void
-ioc_ok_ack( queue_t *q, mblk_t *m, int rval )
-{
-    struct iocblk      *ioc;
-    mblk_t             *m0;
-
-    if (( m0 = unlinkb( m )) != NULL ) {
-       freemsg( m0 );
-    }
-
-    if ( m->b_wptr - m->b_rptr < sizeof( struct iocblk )) {
-       cmn_err( CE_CONT, "ioc_ok_ack too small\n" );
-       freemsg( m );
-       return;
-    }
-    m->b_datap->db_type = M_IOCACK;
-    m->b_wptr = m->b_rptr + sizeof( struct iocblk );
-    ioc = (struct iocblk *)m->b_rptr;
-    ioc->ioc_error = 0;
-    ioc->ioc_count = 0;
-    ioc->ioc_rval = rval;
-    qreply( q, m );
-    return;
-}
-
-    void
-ioc_error_ack( queue_t *q, mblk_t *m, int errno )
-{
-    struct iocblk      *ioc;
-    mblk_t             *m0;
-
-    if (( m0 = unlinkb( m )) != NULL ) {
-       freemsg( m0 );
-    }
-
-    if ( m->b_wptr - m->b_rptr < sizeof( struct iocblk )) {
-       cmn_err( CE_CONT, "ioc_error_ack too small\n" );
-       freemsg( m );
-       return;
-    }
-    m->b_datap->db_type = M_IOCNAK;
-    m->b_wptr = m->b_rptr + sizeof( struct iocblk );
-    ioc = (struct iocblk *)m->b_rptr;
-    ioc->ioc_error = errno;
-    ioc->ioc_count = 0;
-    ioc->ioc_rval = -1;
-    qreply( q, m );
-    return;
-}
-
-    void
-ioc_copyin( queue_t *q, mblk_t *m, mblk_t *private, caddr_t addr, uint size )
-{
-    struct copyreq     *cq;
-    mblk_t             *m0;
-
-    if (( m0 = unlinkb( m )) != NULL ) {
-       freemsg( m0 );
-    }
-
-#ifdef notdef
-    /* supposedly this will fit anyway */
-    if ( m->b_wptr - m->b_rptr < sizeof( struct copyreq )) {
-       cmn_err( CE_CONT, "ioc_copyin too small\n" );
-       freemsg( m );
-       return;
-    }
-#endif /* notdef */
-    m->b_datap->db_type = M_COPYIN;
-    m->b_wptr = m->b_rptr + sizeof( struct copyreq );
-    cq = (struct copyreq *)m->b_rptr;
-    cq->cq_addr = addr;
-    cq->cq_size = size;
-    cq->cq_flag = 0;
-    cq->cq_private = private;
-    qreply( q, m );
-    return;
-}
-
-    void
-ioc_copyout( queue_t *q, mblk_t *m, mblk_t *private, caddr_t data,
-       caddr_t addr, uint size )
-{
-    struct copyreq     *cq;
-    mblk_t             *m0;
-
-    if (( m0 = unlinkb( m )) != NULL ) {
-       freemsg( m0 );
-    }
-
-#ifdef notdef
-    /* supposedly this will fit anyway */
-    if ( m->b_wptr - m->b_rptr < sizeof( struct copyreq )) {
-       cmn_err( CE_CONT, "ioc_copyout too small\n" );
-       freemsg( m );
-       return;
-    }
-#endif /* notdef */
-    if (( m0 = allocb( size, BPRI_MED )) == NULL ) {
-       cmn_err( CE_CONT, "ioc_copyout nomem\n" );
-       freemsg( m );
-       return;
-    }
-    m0->b_wptr = m0->b_rptr + size;
-    bcopy( data, m0->b_rptr, size );
-    linkb( m, m0 );
-
-    m->b_datap->db_type = M_COPYOUT;
-    m->b_wptr = m->b_rptr + sizeof( struct copyreq );
-    cq = (struct copyreq *)m->b_rptr;
-    cq->cq_addr = addr;
-    cq->cq_size = size;
-    cq->cq_flag = 0;
-    cq->cq_private = private;
-
-    qreply( q, m );
-    return;
-}
diff --git a/sys/solaris/ioc.h b/sys/solaris/ioc.h
deleted file mode 100644 (file)
index 4b1424a..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-void ioc_ok_ack( queue_t *, mblk_t *, int );
-void ioc_error_ack( queue_t *, mblk_t *, int );
-void ioc_copyin( queue_t *, mblk_t *, mblk_t *, caddr_t, uint );
-void ioc_copyout( queue_t *, mblk_t *, mblk_t *, caddr_t, caddr_t, uint );
diff --git a/sys/solaris/linkage.c b/sys/solaris/linkage.c
deleted file mode 100644 (file)
index 7917607..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Linkage information.  Mostly this is Solaris specific, but not all.
- * Code to do real work is in other files, this file just has the crap
- * to get the real code loaded and called.
- */
-
-#include <sys/types.h>
-#include <sys/modctl.h>
-#include <sys/cmn_err.h>
-
-char   *netatalk_version = VERSION;
-
-extern struct modldrv tpi_ldrv;
-extern struct modldrv dlpi_lstrmod;
-
-static struct modlinkage       ddp_linkage = {
-    MODREV_1,
-    {
-       (void *)&tpi_ldrv,
-       (void *)&dlpi_lstrmod,
-       NULL,
-    }
-};
-
-/*
- * While these are code, they're mostly related to linkage, so
- * we leave them here.
- */
-    int
-_init( void )
-{
-    cmn_err( CE_CONT, "?netatalk %s\n", netatalk_version );
-    return( mod_install( &ddp_linkage ));
-}
-
-    int
- _info( struct modinfo *modinfop )
-{
-    return( mod_info( &ddp_linkage, modinfop ));
-}
-
-    int
-_fini( void )
-{
-    return( mod_remove( &ddp_linkage ));
-}
diff --git a/sys/solaris/rt.c b/sys/solaris/rt.c
deleted file mode 100644 (file)
index 95bd1e2..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/cmn_err.h>
-#include <sys/kmem.h>
-#include <net/route.h>
-#include <netatalk/at.h>
-#include <errno.h>
-
-#include "rt.h"
-
-struct rtab {
-    struct rtab                *r_next, *r_prev;
-    struct sockaddr_at r_dst;
-    struct sockaddr_at r_gate;
-};
-
-static struct rtab     *rt_net = NULL;
-static struct rtab     *rt_host = NULL;
-
-    int
-rt_add( struct sockaddr_at *dst, struct sockaddr_at *gate, int flags )
-{
-    struct rtab                *r;
-    struct rtab                *rtab;
-
-    if ( flags & RTF_HOST ) {
-       rtab = rt_host;
-    } else {
-       rtab = rt_net;
-    }
-    for ( r = rtab; r != NULL; r = r->r_next ) {
-       if (( r->r_dst.sat_addr.s_net == dst->sat_addr.s_net ) &&
-               (( flags & RTF_HOST ) ?
-               r->r_dst.sat_addr.s_node == dst->sat_addr.s_node : 1 )) {
-           return( EEXIST );
-       }
-    }
-
-    if (( r = kmem_alloc( sizeof( struct rtab ), KM_NOSLEEP )) == NULL ) {
-       return( ENOMEM );
-    }
-    r->r_dst = *dst;
-    r->r_gate = *gate;
-
-    r->r_prev = NULL;
-    r->r_next = rtab;
-    if ( rtab != NULL ) {
-       rtab->r_prev = r;
-    }
-    if ( flags & RTF_HOST ) {
-       rt_host = r;
-    } else {
-       rt_net = r;
-    }
-    return( 0 );
-}
-
-    int
-rt_del( struct sockaddr_at *dst, struct sockaddr_at *gate, int flags )
-{
-    struct rtab                *r;
-    struct rtab                *rtab;
-
-    if ( flags & RTF_HOST ) {
-       rtab = rt_host;
-    } else {
-       rtab = rt_net;
-    }
-    for ( r = rtab; r != NULL; r = r->r_next ) {
-       if (( r->r_dst.sat_addr.s_net == dst->sat_addr.s_net ) &&
-               (( flags & RTF_HOST ) ?
-               r->r_dst.sat_addr.s_node == dst->sat_addr.s_node : 1 )) {
-           break;
-       }
-    }
-    if ( r == NULL ) {
-       return( ESRCH );
-    }
-
-    if ( r == rtab ) {
-       if ( flags & RTF_HOST ) {
-           rt_host = r->r_next;
-       } else {
-           rt_net = r->r_next;
-       }
-    }
-    if ( r->r_next != NULL ) {
-       r->r_next->r_prev = r->r_prev;
-    }
-    if ( r->r_prev != NULL ) {
-       r->r_prev->r_next = r->r_next;
-    }
-    kmem_free( r, sizeof( struct rtab ));
-    return( 0 );
-}
-
-    int
-rt_gate( struct sockaddr_at *dst, struct sockaddr_at *gate )
-{
-    struct rtab                *r;
-
-    for ( r = rt_host; r != NULL; r = r->r_next ) {
-       if ( r->r_dst.sat_addr.s_net == dst->sat_addr.s_net &&
-               r->r_dst.sat_addr.s_node == dst->sat_addr.s_node ) {
-           break;
-       }
-    }
-    if ( r != NULL ) {
-       *gate = r->r_gate;
-       return( 0 );
-    }
-
-    for ( r = rt_net; r != NULL; r = r->r_next ) {
-       if ( r->r_dst.sat_addr.s_net == dst->sat_addr.s_net ) {
-           break;
-       }
-    }
-    if ( r == NULL ) {
-       return( -1 );
-    }
-
-    *gate = r->r_gate;
-    return( 0 );
-}
diff --git a/sys/solaris/rt.h b/sys/solaris/rt.h
deleted file mode 100644 (file)
index ef7e17f..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-int    rt_add( struct sockaddr_at *, struct sockaddr_at *, int );
-int    rt_del( struct sockaddr_at *, struct sockaddr_at *, int );
-int    rt_gate( struct sockaddr_at *, struct sockaddr_at * );
diff --git a/sys/solaris/sock.c b/sys/solaris/sock.c
deleted file mode 100644 (file)
index 0a3fb79..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-/* $Id: sock.c,v 1.2 2002-01-17 07:11:13 srittau Exp $
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#include <sys/types.h>
-#include <sys/stream.h>
-#include <sys/socket.h>
-#include <sys/errno.h>
-#include <sys/kmem.h>
-#include <sys/cmn_err.h>
-#include <sys/tihdr.h>
-#include <sys/ethernet.h>
-#include <net/if.h>
-
-#ifdef STDC_HEADERS
-#include <strings.h>
-#else
-#include <string.h>
-#endif
-
-#include <netatalk/at.h>
-
-#include "if.h"
-#include "sock.h"
-
-static struct sock_data        *sockets = NULL;
-
-    struct sock_data *
-sock_alloc( queue_t *q )
-{
-    struct sock_data   *sd;
-
-    if (( sd = kmem_alloc( sizeof( struct sock_data ), KM_SLEEP )) == NULL ) {
-       return( NULL );
-    }
-    sd->sd_state = TS_UNBND;
-    sd->sd_q = q;
-    sd->sd_next = sd->sd_prev = NULL;
-    bzero( (caddr_t)&sd->sd_sat, sizeof( struct sockaddr_at ));
-
-    sd->sd_next = sockets;
-    if ( sockets != NULL ) {
-       sockets->sd_prev = sd;
-    }
-    sockets = sd;
-
-    return( sd );
-}
-
-    void
-sock_free( struct sock_data *sd )
-{
-    if ( sd == sockets ) {
-       sockets = sd->sd_next;
-    }
-    if ( sd->sd_next != NULL ) {
-       sd->sd_next->sd_prev = sd->sd_prev;
-    }
-    if ( sd->sd_prev != NULL ) {
-       sd->sd_prev->sd_next = sd->sd_next;
-    }
-    kmem_free( sd, sizeof( struct sock_data ));
-    return;
-}
-
-    struct sock_data *
-sock_dest( struct atif_data *aid, struct sockaddr_at *sat )
-{
-    struct sock_data   *sd;
-
-    for ( sd = sockets; sd != NULL; sd = sd->sd_next ) {
-       if ( sat->sat_port == sd->sd_sat.sat_port &&
-               /* huh? */
-               aid->aid_sat.sat_addr.s_net == sd->sd_sat.sat_addr.s_net &&
-               ( sat->sat_addr.s_node == sd->sd_sat.sat_addr.s_node ||
-               sat->sat_addr.s_node == ATADDR_BCAST )) {
-           break;
-       }
-    }
-    return( sd );
-}
-
-/*
- * This is a change in semantics.  The port must be ATADDR_ANYPORT for
- * ATADDR_ANYNET/NODE to not mean the loopback.
- */
-    int
-sock_bind( struct sock_data *sd, struct sockaddr_at *sat )
-{
-    struct atif_data   *paid;
-    struct sock_data   *psd;
-    struct sockaddr_at psat;
-    u_short            port;
-
-    psat = *sat;
-    if ( psat.sat_family != AF_APPLETALK ) {
-       cmn_err( CE_CONT, "sock_bind non-AppleTalk\n" );
-       return( EPROTOTYPE );
-    }
-
-    if ( psat.sat_port == ATADDR_ANYPORT ) {
-       if ( psat.sat_addr.s_net == ATADDR_ANYNET &&
-               psat.sat_addr.s_node == ATADDR_ANYNODE ) {
-           /* chose primary interface */
-           if (( paid = if_primary()) == NULL ) {
-               return( EADDRNOTAVAIL );
-           }
-           psat.sat_addr.s_net = paid->aid_sat.sat_addr.s_net;
-           psat.sat_addr.s_node = paid->aid_sat.sat_addr.s_node;
-       }
-
-       /* pick unused port */
-       for ( port = ATPORT_RESERVED; port < ATPORT_LAST; port++ ) {
-           for ( psd = sockets; psd != NULL; psd = psd->sd_next ) {
-               if ( port == psd->sd_sat.sat_port &&
-                       psat.sat_addr.s_net == psd->sd_sat.sat_addr.s_net &&
-                       psat.sat_addr.s_node == psd->sd_sat.sat_addr.s_node ) {
-                   break;
-               }
-           }
-           if ( psd == NULL ) {
-               break;
-           }
-       }
-       if ( psd != NULL ) {
-           return( EADDRINUSE );
-       }
-       psat.sat_port = port;
-    }
-
-    sd->sd_sat = psat;
-    sd->sd_state = TS_IDLE;
-    return( 0 );
-}
diff --git a/sys/solaris/sock.h b/sys/solaris/sock.h
deleted file mode 100644 (file)
index 2397bd7..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-struct sock_data {
-    struct sock_data   *sd_next, *sd_prev;
-    int                        sd_state;
-    queue_t            *sd_q;
-    struct sockaddr_at sd_sat;
-};
-
-struct sock_data       *sock_alloc( queue_t * );
-void                   sock_free( struct sock_data * );
-struct sock_data       *sock_dest( struct atif_data *, struct sockaddr_at * );
-int                    sock_bind( struct sock_data *, struct sockaddr_at * );
-void           t_unitdata_ind( queue_t *, mblk_t *, struct sockaddr_at * );
diff --git a/sys/solaris/tpi.c b/sys/solaris/tpi.c
deleted file mode 100644 (file)
index 0bf89ed..0000000
+++ /dev/null
@@ -1,728 +0,0 @@
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-#include <sys/types.h>
-#include <sys/kmem.h>
-#include <sys/conf.h>
-#include <sys/stream.h>
-#include <sys/devops.h>
-#include <sys/modctl.h>
-#include <sys/ddi.h>
-#include <sys/stat.h>
-#include <sys/sockio.h>
-#include <sys/socket.h>
-#include <sys/tihdr.h>
-#include <sys/tiuser.h>
-#include <sys/timod.h>
-#include <sys/sunddi.h>
-#include <sys/ethernet.h>
-#include <net/if.h>
-#include <net/route.h>
-#include <errno.h>
-
-#include <netatalk/endian.h>
-#include <netatalk/at.h>
-#include <netatalk/ddp.h>
-
-#include "ioc.h"
-#include "if.h"
-#include "sock.h"
-#include "rt.h"
-
-    static int
-tpi_getinfo( dev_info_t *dip, ddi_info_cmd_t cmd, void *arg, void **resultp )
-{
-    *resultp = NULL;
-    return( DDI_FAILURE );
-}
-
-/* Solaris 10 removed DDI_IDENTIFIED and replaced "identify" with "nulldev" */
-#ifdef DDI_IDENTIFIED
-    static int
-tpi_identify( dev_info_t *dip )
-{
-    char *tmp;
-
-    /* don't use strcmp under Solaris 9, problem loading kernel module */
-    tmp = ddi_get_name( dip );
-    if ((tmp[0]== 'd') && (tmp[1]=='d') && (tmp[2]=='p') && tmp[3]==0) {
-       return( DDI_IDENTIFIED );
-    } else {
-       return( DDI_NOT_IDENTIFIED );
-    }
-}
-#endif /* DDI_IDENTIFIED */
-
-    static int
-tpi_attach( dev_info_t *dip, ddi_attach_cmd_t cmd )
-{
-    int                rc;
-
-    if ( cmd != DDI_ATTACH ) {
-       return( DDI_FAILURE );
-    }
-
-    if (( rc = ddi_create_minor_node( dip, "ddp", S_IFCHR, 0, DDI_PSEUDO,
-           CLONE_DEV )) != DDI_SUCCESS ) {
-       /* undo anything */
-    }
-    return( rc );
-}
-
-    static int
-tpi_detach( dev_info_t *dip, ddi_detach_cmd_t cmd )
-{
-    if ( cmd != DDI_DETACH ) {
-       return( DDI_FAILURE );
-    }
-
-    ddi_remove_minor_node( dip, "ddp" );
-
-    return( DDI_SUCCESS );
-}
-
-    static int
-tpi_open( queue_t *q, dev_t *dev, int oflag, int sflag, cred_t *cred )
-{
-    static minor_t     minor = 1;
-
-    if ( sflag != CLONEOPEN ) {
-       return( EINVAL );
-    }
-    if (( q->q_ptr = (void *)sock_alloc( q )) == NULL ) {
-       return( ENOMEM );
-    }
-
-    *dev = makedevice( getmajor( *dev ), minor++ );
-    qprocson( q );
-    return( 0 );
-}
-
-    static int
-tpi_close( queue_t *q, int oflag, cred_t *cred )
-{
-    struct sock_data   *sd = (struct sock_data *)q->q_ptr;
-
-    qprocsoff( q );
-    sock_free( sd );
-    return( 0 );
-}
-
-    static int
-tpi_rput( queue_t *q,  mblk_t *m )
-{
-    cmn_err( CE_NOTE, "tpi_rput dp_type = 0x%X\n", m->b_datap->db_type );
-    freemsg( m );
-    return( 0 );
-}
-
-    void
-t_bind_ack( queue_t *q, struct sockaddr_at *sat )
-{
-    mblk_t             *m;
-    struct T_bind_ack  *t;
-
-    if (( m = allocb( sizeof( struct T_bind_ack ) +
-           sizeof( struct sockaddr_at ), BPRI_HI )) == NULL ) {
-       return;
-    }
-    m->b_wptr = m->b_rptr + sizeof( struct T_bind_ack );
-    m->b_datap->db_type = M_PCPROTO;
-
-    t = (struct T_bind_ack *)m->b_rptr;
-    t->PRIM_type = T_BIND_ACK;
-    t->ADDR_length = sizeof( struct sockaddr_at );
-    t->ADDR_offset = m->b_wptr - m->b_rptr;
-    t->CONIND_number = 0;
-
-    bcopy( (caddr_t)sat, m->b_wptr, sizeof( struct sockaddr_at ));
-    m->b_wptr += sizeof( struct sockaddr_at );
-
-    qreply( q, m );
-    return;
-}
-
-    void
-t_ok_ack( queue_t *q, long prim )
-{
-    mblk_t             *m;
-    struct T_ok_ack    *t;
-
-
-    if (( m = allocb( sizeof( struct T_ok_ack ), BPRI_HI )) == NULL ) {
-       return;
-    }
-    m->b_wptr = m->b_rptr + sizeof( struct T_ok_ack );
-    m->b_datap->db_type = M_PCPROTO;
-
-    t = (struct T_ok_ack *)m->b_rptr;
-    t->PRIM_type = T_OK_ACK;
-    t->CORRECT_prim = prim;
-    qreply( q, m );
-    return;
-}
-
-    void
-t_error_ack( queue_t *q, long prim, long terror, long uerror )
-{
-    mblk_t             *m;
-    struct T_error_ack *t;
-
-
-    if (( m = allocb( sizeof( struct T_error_ack ), BPRI_HI )) == NULL ) {
-       return;
-    }
-    m->b_wptr = m->b_rptr + sizeof( struct T_error_ack );
-    m->b_datap->db_type = M_PCPROTO;
-
-    t = (struct T_error_ack *)m->b_rptr;
-    t->PRIM_type = T_ERROR_ACK;
-    t->ERROR_prim = prim;
-    t->TLI_error = terror;
-    t->UNIX_error = uerror;
-    qreply( q, m );
-    return;
-}
-
-    void
-t_info_ack( queue_t *q, long state )
-{
-    mblk_t             *m;
-    struct T_info_ack  *t;
-
-
-    if (( m = allocb( sizeof( struct T_info_ack ), BPRI_HI )) == NULL ) {
-       return;
-    }
-    m->b_wptr = m->b_rptr + sizeof( struct T_info_ack );
-    m->b_datap->db_type = M_PCPROTO;
-
-    t = (struct T_info_ack *)m->b_rptr;
-    t->PRIM_type = T_INFO_ACK;
-    t->TSDU_size = 586;
-    t->ETSDU_size = -2;
-    t->CDATA_size = -2;
-    t->DDATA_size = -2;
-    t->ADDR_size = sizeof( struct sockaddr_at );
-    t->OPT_size = 64;
-    t->TIDU_size = 1024;
-    t->SERV_type = T_CLTS;
-    t->CURRENT_state = state;
-    t->PROVIDER_flag = 0;
-    qreply( q, m );
-    return;
-}
-
-    void
-t_unitdata_ind( queue_t *q, mblk_t *m0, struct sockaddr_at *sat )
-{
-    mblk_t                     *m;
-    struct T_unitdata_ind      *t;
-
-    if (( m = allocb( sizeof( struct T_unitdata_ind ) +
-           sizeof( struct sockaddr_at ), BPRI_HI )) == NULL ) {
-       return;
-    }
-    m->b_wptr = m->b_rptr + sizeof( struct T_unitdata_ind );
-    m->b_datap->db_type = M_PROTO;
-
-    t = (struct T_unitdata_ind *)m->b_rptr;
-    t->PRIM_type = T_UNITDATA_IND;
-    t->SRC_length = sizeof( struct sockaddr_at );
-    t->SRC_offset = m->b_wptr - m->b_rptr;
-    bcopy( (caddr_t)sat, m->b_wptr, sizeof( struct sockaddr_at ));
-    m->b_wptr += sizeof( struct sockaddr_at );
-    t->OPT_length = 0;
-    t->OPT_offset = 0;
-    linkb( m, m0 );
-
-    qreply( q, m );
-    return;
-}
-
-struct ioc_state {
-    int                is_state;
-    int                is_count;
-    caddr_t    is_addr;
-};
-
-    static int
-tpi_wput( queue_t *q,  mblk_t *m )
-{
-    struct sock_data   *sd = (struct sock_data *)RD(q)->q_ptr;
-    union T_primitives *tl;
-    struct iocblk      *ioc;
-    struct copyresp    *cp;
-    struct ioc_state   *is;
-    struct ddpehdr     *deh;
-    mblk_t             *m0;
-    struct sockaddr_at sat;
-    struct netbuf      nb;
-    struct rtentry     rt;
-    struct ifreq       ifr;
-    int                        err;
-
-    switch ( m->b_datap->db_type ) {
-    case M_PCPROTO :
-    case M_PROTO :
-       if ( m->b_wptr - m->b_rptr < sizeof( tl->type )) {
-           freemsg( m );
-           break;
-       }
-       tl = (union T_primitives *)m->b_rptr;
-       switch ( tl->type ) {
-       case T_INFO_REQ :
-           t_info_ack( q, sd->sd_state );
-           freemsg( m );
-           break;
-
-       case T_UNBIND_REQ :
-           if ( m->b_wptr - m->b_rptr < sizeof( struct T_unbind_req )) {
-               freemsg( m );
-               break;
-           }
-           if ( sd->sd_state != TS_IDLE ) {
-               t_error_ack( q, T_BIND_REQ, TOUTSTATE, 0 );
-               freemsg( m );
-               break;
-           }
-           bzero( (caddr_t)&sd->sd_sat, sizeof( struct sockaddr_at ));
-           sd->sd_state = TS_UNBND;
-           t_ok_ack( q, T_UNBIND_REQ );
-           break;
-
-       case T_BIND_REQ :
-           if ( m->b_wptr - m->b_rptr < sizeof( struct T_bind_req )) {
-               freemsg( m );
-               break;
-           }
-           if ( sd->sd_state != TS_UNBND ) {
-               t_error_ack( q, T_BIND_REQ, TOUTSTATE, 0 );
-               freemsg( m );
-               break;
-           }
-
-           if ( tl->bind_req.ADDR_length == 0 ) {
-               bzero( (caddr_t)&sat, sizeof( struct sockaddr_at ));
-               sat.sat_family = AF_APPLETALK;
-           } else {
-               if ( tl->bind_req.ADDR_length != sizeof( struct sockaddr ) ||
-                       m->b_wptr - m->b_rptr <
-                       tl->bind_req.ADDR_offset + tl->bind_req.ADDR_length ) {
-                   cmn_err( CE_CONT, "tpi_wput T_BIND_REQ wierd\n" );
-                   freemsg( m );
-                   break;
-               }
-               sat = *(struct sockaddr_at *)(m->b_rptr +
-                       tl->bind_req.ADDR_offset );
-           }
-
-           if (( err = sock_bind( sd, &sat )) != 0 ) {
-               t_error_ack( q, T_BIND_REQ, TSYSERR, err );
-           } else {
-               /* seems like we must return the requested address */
-               t_bind_ack( q, &sat );
-           }
-           freemsg( m );
-           break;
-
-       case T_UNITDATA_REQ :
-           if ( m->b_wptr - m->b_rptr < sizeof( struct T_unitdata_req )) {
-               freemsg( m );
-               break;
-           }
-           if ( sd->sd_state != TS_IDLE ) {
-               cmn_err( CE_NOTE, "tpi_wput unitdata on unbound socket\n" );
-               t_error_ack( q, T_UNITDATA_REQ, TOUTSTATE, 0 );
-               freemsg( m );
-               break;
-           }
-           if ( tl->unitdata_req.DEST_length != sizeof( struct sockaddr )) {
-               cmn_err( CE_NOTE, "tpi_wput T_UNITDATA_REQ %d\n",
-                       tl->unitdata_req.DEST_length );
-               freemsg( m );
-               break;
-           }
-
-#ifdef notdef
-           /*
-            * Sometimes, the socket layer gives us crap...  Sound like a bug?
-            */
-           if ( m->b_rptr + tl->unitdata_req.DEST_offset +
-                   tl->unitdata_req.DEST_length > m->b_wptr ) {
-cmn_err( CE_CONT, "tpi_wput T_UNITDATA_REQ mblk size %X %X\n", m->b_rptr + tl->unitdata_req.DEST_offset + tl->unitdata_req.DEST_length, m->b_wptr );
-               freemsg( m );
-               break;
-           }
-#endif /* notdef */
-
-           sat = *(struct sockaddr_at *)(m->b_rptr +
-                   tl->unitdata_req.DEST_offset );
-           if ( sat.sat_family != AF_APPLETALK ) {
-               cmn_err( CE_CONT, "tpi_wput non-AppleTalk\n" );
-               freemsg( m );
-               break;
-           }
-
-           if ( m->b_wptr - m->b_rptr < sizeof( struct ddpehdr )) {
-               cmn_err( CE_CONT, "tpi_wput m too short\n" );
-               freemsg( m );
-               break;
-           }
-           m->b_wptr = m->b_rptr + sizeof( struct ddpehdr );
-           m->b_datap->db_type = M_DATA;
-           deh = (struct ddpehdr *)m->b_rptr;
-           deh->deh_pad = 0;
-           deh->deh_hops = 0;
-           deh->deh_len = msgdsize( m );
-
-           deh->deh_dnet = sat.sat_addr.s_net;
-           deh->deh_dnode = sat.sat_addr.s_node;
-           deh->deh_dport = sat.sat_port;
-
-           deh->deh_snet = sd->sd_sat.sat_addr.s_net;
-           deh->deh_snode = sd->sd_sat.sat_addr.s_node;
-           deh->deh_sport = sd->sd_sat.sat_port;
-
-           deh->deh_sum = 0;                   /* XXX */
-           deh->deh_bytes = htonl( deh->deh_bytes );
-           return( if_route( if_withaddr( &sd->sd_sat ), m, &sat ));
-
-       default :
-           /* cmn_err( CE_NOTE, "tpi_wput M_PCPROTO 0x%X\n", tl->type ); */
-           t_error_ack( q, tl->type, TNOTSUPPORT, 0 );
-           freemsg( m );
-           break;
-       }
-       break;
-
-    case M_IOCTL :
-       if ( m->b_wptr - m->b_rptr < sizeof( struct iocblk )) {
-           freemsg( m );
-           break;
-       }
-       ioc = (struct iocblk *)m->b_rptr;
-       if ( ioc->ioc_count != TRANSPARENT ) {
-           cmn_err( CE_CONT, "tpi_wput non-TRANSPARENT %X\n", ioc->ioc_cmd );
-           ioc_error_ack( q, m, EINVAL );
-           break;
-       }
-       if ( m->b_cont == NULL ) {
-           cmn_err( CE_CONT, "tpi_wput M_IOCTL no arg\n" );
-           ioc_error_ack( q, m, EINVAL );
-           break;
-       }
-
-       /* de-allocated after M_IOCDATA processing */
-       if (( m0 = allocb( sizeof( struct ioc_state ), BPRI_HI )) == NULL ) {
-           cmn_err( CE_CONT, "tpi_wput m0 no mem\n" );
-           ioc_error_ack( q, m, EINVAL );
-           break;
-       }
-       m0->b_wptr = m->b_rptr + sizeof( struct ioc_state );
-       is = (struct ioc_state *)m0->b_rptr;
-
-       switch ( ioc->ioc_cmd ) {
-       case SIOCADDRT :
-       case SIOCDELRT :
-           if (( err = drv_priv( ioc->ioc_cr )) != 0 ) {
-               ioc_error_ack( q, m, err );
-               break;
-           }
-           is->is_state = M_COPYIN;
-           is->is_addr = *(caddr_t *)m->b_cont->b_rptr;
-           ioc_copyin( q, m, m0, is->is_addr, sizeof( struct rtentry ));
-           break;
-
-       case SIOCADDMULTI :
-       case SIOCSIFADDR :
-           if (( err = drv_priv( ioc->ioc_cr )) != 0 ) {
-               ioc_error_ack( q, m, err );
-               break;
-           }
-
-       case SIOCGIFADDR :
-           is->is_state = M_COPYIN;
-           is->is_addr = *(caddr_t *)m->b_cont->b_rptr;
-           ioc_copyin( q, m, m0, is->is_addr, sizeof( struct ifreq ));
-           break;
-
-       case TI_GETMYNAME :
-           is->is_state = M_COPYIN;
-           is->is_addr = *(caddr_t *)m->b_cont->b_rptr;
-           ioc_copyin( q, m, m0, is->is_addr, sizeof( struct netbuf ));
-           break;
-
-       default :
-           ioc_error_ack( q, m, EINVAL );
-           break;
-       }
-       break;
-
-    case M_IOCDATA :
-       if ( m->b_wptr - m->b_rptr < sizeof( struct copyresp )) {
-           freemsg( m );
-           break;
-       }
-       cp = (struct copyresp *)m->b_rptr;
-       if ( cp->cp_rval != 0 ) {
-           cmn_err( CE_CONT, "tpi_wput IOCDATA failed %s\n", cp->cp_rval );
-           freemsg( m );
-           break;
-       }
-
-       if (( m0 = cp->cp_private ) == NULL ) {
-           cmn_err( CE_CONT, "tpi_wput IOCDATA no state\n" );
-           ioc_error_ack( q, m, EINVAL );
-           break;
-       }
-       if ( m0->b_wptr - m0->b_rptr < sizeof( struct ioc_state )) {
-           cmn_err( CE_CONT, "tpi_wput IOCDATA private too short\n" );
-           ioc_error_ack( q, m, EINVAL );
-           break;
-       }
-       is = (struct ioc_state *)m0->b_rptr;
-
-       switch ( cp->cp_cmd ) {
-       case TI_GETMYNAME :
-           switch ( is->is_state ) {
-           case M_COPYIN :
-               if ( m->b_cont == NULL ) {
-                   cmn_err( CE_CONT, "tpi_wput TI_GETMYNAME COPYIN no arg\n" );
-                   ioc_error_ack( q, m, EINVAL );
-                   break;
-               }
-               nb = *(struct netbuf *)m->b_cont->b_rptr;
-               nb.len = sizeof( struct sockaddr_at );
-               /* copy out netbuf */
-               is->is_state = M_COPYOUT;
-               is->is_count = 1;
-               ioc_copyout( q, m, m0, (caddr_t)&nb, is->is_addr,
-                       sizeof( struct netbuf ));
-               is->is_addr = nb.buf;
-               return( 0 );
-
-           case M_COPYOUT :
-               switch ( is->is_count ) {
-               case 1 :
-                   /* copy out address to nb.buf */
-                   is->is_state = M_COPYOUT;
-                   is->is_count = 2;
-                   ioc_copyout( q, m, m0, (caddr_t)&sd->sd_sat, is->is_addr,
-                           sizeof( struct sockaddr_at ));
-                   return( 0 );
-
-               case 2 :
-                   ioc_ok_ack( q, m, 0 );
-                   break;
-
-               default :
-                   cmn_err( CE_NOTE, "tpi_wput TI_GETMYNAME count %d\n",
-                           is->is_count );
-                   ioc_error_ack( q, m, EINVAL );
-                   break;
-               }
-               break;
-
-           default :
-               cmn_err( CE_NOTE, "tpi_wput TI_GETMYNAME state %d\n",
-                       is->is_state );
-               ioc_error_ack( q, m, EINVAL );
-               break;
-           }
-           break;
-
-       case SIOCADDRT :        /* manipulate routing table */
-       case SIOCDELRT :
-           if (( err = drv_priv( cp->cp_cr )) != 0 ) {
-               ioc_error_ack( q, m, err );
-               break;
-           }
-           if ( is->is_state != M_COPYIN ) {
-               cmn_err( CE_CONT, "tpi_wput SIOC(ADD|DEL)RT bad state\n" );
-               freemsg( m );
-               break;
-           }
-
-           rt = *(struct rtentry *)m->b_cont->b_rptr;
-
-           if ( cp->cp_cmd == SIOCADDRT ) {
-               err = rt_add( (struct sockaddr_at *)&rt.rt_dst,
-                       (struct sockaddr_at *)&rt.rt_gateway, rt.rt_flags );
-           } else if ( cp->cp_cmd == SIOCDELRT ) {
-               err = rt_del( (struct sockaddr_at *)&rt.rt_dst,
-                       (struct sockaddr_at *)&rt.rt_gateway, rt.rt_flags );
-           } else {
-               cmn_err( CE_CONT, "tpi_wput SIOC(ADD|DEL)RT bad cmd\n" );
-               freemsg( m );
-               break;
-           }
-           if ( err != 0 ) {
-               ioc_error_ack( q, m, err );
-           } else {
-               ioc_ok_ack( q, m, 0 );
-           }
-           break;
-
-       /*
-        * These both require lower messages to be sent.
-        */
-       case SIOCADDMULTI :
-       case SIOCSIFADDR :
-           if (( err = drv_priv( cp->cp_cr )) != 0 ) {
-               ioc_error_ack( q, m, err );
-               break;
-           }
-           if ( is->is_state != M_COPYIN ) {
-               cmn_err( CE_CONT, "tpi_wput SIOCSIFADDR bad state\n" );
-               freemsg( m );
-               break;
-           }
-
-           ifr = *(struct ifreq *)m->b_cont->b_rptr;
-
-           /* initiate command, pass q and m (current context to be saved */
-           if ( cp->cp_cmd == SIOCSIFADDR ) {
-               err = if_setaddr( q, m, ifr.ifr_name,
-                       (struct sockaddr_at *)&ifr.ifr_addr );
-           } else {
-               err = if_addmulti( q, m, ifr.ifr_name, &ifr.ifr_addr );
-           }
-           if ( err != 0 ) {
-               ioc_error_ack( q, m, err );
-               break;
-           }
-           break;
-
-       case SIOCGIFADDR :      /* get interface address */
-           switch ( is->is_state ) {
-           case M_COPYOUT :
-               /* ack the original ioctl */
-               ioc_ok_ack( q, m, 0 );
-               break;
-
-           case M_COPYIN :
-               if ( m->b_cont == NULL ) {
-                   cmn_err( CE_CONT, "tpi_wput SIOCGIFADDR COPYIN no arg\n" );
-                   ioc_error_ack( q, m, EINVAL );
-                   break;
-               }
-
-               /* size??? */
-               ifr = *(struct ifreq *)m->b_cont->b_rptr;
-               if (( err = if_getaddr( ifr.ifr_name,
-                       (struct sockaddr_at *)&ifr.ifr_addr )) != 0 ) {
-                   ioc_error_ack( q, m, err );
-               }
-               is->is_state = M_COPYOUT;
-               ioc_copyout( q, m, m0, (caddr_t)&ifr, is->is_addr,
-                       sizeof( struct ifreq ));
-               return( 0 );    /* avoid freemsg( m0 ) below */
-
-           default :
-               cmn_err( CE_CONT, "tpi_wput SIOCGIFADDR bad state\n" );
-               freemsg( m );
-               break;
-           }
-           break;
-
-       default :
-           cmn_err( CE_NOTE, "tpi_wput M_IOCDATA 0x%X\n", cp->cp_cmd );
-           ioc_error_ack( q, m, EINVAL );
-           break;
-       }
-       freemsg( m0 );
-       break;
-
-    default :
-       cmn_err( CE_NOTE, "!tpi_wput dp_type = 0x%X\n", m->b_datap->db_type );
-       freemsg( m );
-       break;
-    }
-
-    return( 0 );
-}
-
-static struct module_info      tpi_info = {
-    0,                 /* XXX */
-    "ddp",
-    0,
-    1500,
-    3000,
-    64
-};
-
-static struct qinit            tpi_rinit = {
-    tpi_rput,                  /* qi_putp */
-    NULL,                      /* qi_srvp */
-    tpi_open,                  /* qi_qopen */
-    tpi_close,                 /* qi_qclose */
-    NULL,
-    &tpi_info,                 /* qi_minfo */
-    NULL,
-};
-
-static struct qinit            tpi_winit = {
-    tpi_wput,                  /* qi_putp */
-    NULL,
-    NULL,
-    NULL,
-    NULL,
-    &tpi_info,
-    NULL,
-};
-
-static struct streamtab                tpi_stream = {
-    &tpi_rinit,
-    &tpi_winit,
-    NULL,
-    NULL
-};
-
-static struct cb_ops           tpi_cbops = {
-    nulldev,           /* cb_open */
-    nulldev,           /* cb_close */
-    nodev,
-    nodev,
-    nodev,
-    nodev,
-    nodev,
-    nodev,
-    nodev,
-    nodev,
-    nodev,
-    nochpoll,
-    ddi_prop_op,
-    &tpi_stream,
-    D_NEW | D_MP | D_MTPERMOD, /* cb_flag */
-    CB_REV,            /* cb_rev */
-    nodev,             /* cb_aread */
-    nodev,             /* cb_awrite */
-};
-
-static struct dev_ops          tpi_devops = {
-    DEVO_REV,
-    0,
-    tpi_getinfo,
-#ifdef DDI_IDENTIFIED
-    tpi_identify,
-#else
-    nulldev,
-#endif
-    nulldev,
-    tpi_attach,
-    tpi_detach,
-    nodev,
-    &tpi_cbops,
-    (struct bus_ops *)NULL,
-    NULL,
-};
-
-/*
- * DDP Streams device.  This device is opened by socket().
- */
-struct modldrv                 tpi_ldrv = {
-    &mod_driverops,
-    "DDP Streams device",
-    &tpi_devops,
-};
diff --git a/sys/sunos/.gitignore b/sys/sunos/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/sys/sunos/Makefile.am b/sys/sunos/Makefile.am
deleted file mode 100644 (file)
index ad9b76c..0000000
+++ /dev/null
@@ -1 +0,0 @@
-EXTRA_DIST = Makefile.kernel at_sun.c
diff --git a/sys/sunos/Makefile.kernel b/sys/sunos/Makefile.kernel
deleted file mode 100644 (file)
index e489af1..0000000
+++ /dev/null
@@ -1,148 +0,0 @@
-# Sun specific defines, passed to subdirectories.
-DEFS= -DBSD4_3 -DUSE_OLD_RQUOTA -DUSE_UFS_QUOTA_H -DUSE_MNTENT_H \
-       -DDLSYM_PREPEND_UNDERSCORE
-OPTOPTS=       -O
-CC=    gcc
-INSTALL=       install
-# use -lbind instead of -lresolv if you're using BIND >= 8.x
-AFPLIBS=-lresolv
-ADDLIBS=
-
-#CSHAREDFLAGS=   -pic
-CSHAREDFLAGS=   -fPIC
-
-#LDFLAGS_EXPORT=
-LDSHARED=      ld
-LDSHAREDFLAGS=  -assert pure-text
-LIBSHARED=      -ldl
-
-
-# source for kernel module
-SRC=   at_sun.c aarp.c at_control.c at_proto.c ddp_input.c ddp_output.c \
-       ddp_usrreq.c
-OBJ=   at_sun.o aarp.o at_control.o at_proto.o ddp_input.o ddp_output.o \
-       ddp_usrreq.o
-
-INCPATH = -I../../include -I../netatalk
-CFLAGS=        ${DEFS} ${OPTOPTS} ${INCPATH}
-
-ALL=   ../../libatalk ../../include ../../bin ../../etc ../../man
-
-all:   kernel ${ALL}
-
-kernel : netatalk.o
-
-netatalk.o:    ${OBJ}
-       ${LD} -r -o netatalk.o ${OBJ}
-
-at_sun.o:      at_sun.c
-       ${CC} ${CFLAGS} -DKERNEL -D`arch -k` -c at_sun.c
-
-aarp.o:        ../netatalk/aarp.c
-       ${CC} ${CFLAGS} -DKERNEL -D`arch -k` -c ../netatalk/aarp.c
-
-at_control.o:  ../netatalk/at_control.c
-       ${CC} ${CFLAGS} -DKERNEL -D`arch -k` -c ../netatalk/at_control.c
-
-at_proto.o:    ../netatalk/at_proto.c
-       ${CC} ${CFLAGS} -DKERNEL -D`arch -k` -c ../netatalk/at_proto.c
-
-ddp_input.o:   ../netatalk/ddp_input.c
-       ${CC} ${CFLAGS} -DKERNEL -D`arch -k` -c ../netatalk/ddp_input.c
-
-ddp_output.o:  ../netatalk/ddp_output.c
-       ${CC} ${CFLAGS} -DKERNEL -D`arch -k` -c ../netatalk/ddp_output.c
-
-ddp_usrreq.o:  ../netatalk/ddp_usrreq.c
-       ${CC} ${CFLAGS} -DKERNEL -D`arch -k` -c ../netatalk/ddp_usrreq.c
-
-../../bin ../../etc:   ../../libatalk
-
-${ALL}:        FRC
-       cd $@; ${MAKE} ${MFLAGS} CC="${CC}" \
-           ADDLIBS="${ADDLIBS}" DEFS="${DEFS}" OPTOPTS="${OPTOPTS}" \
-           SBINDIR="${SBINDIR}" BINDIR="${BINDIR}" RESDIR="${RESDIR}" \
-           ETCDIR="${ETCDIR}" LIBDIR="${LIBDIR}" INCDIR="${INCDIR}" \
-           AFPLIBS="${AFPLIBS}" LDSHARED="${LDSHARED}" \
-           LDFLAGS_EXPORT="${LDFLAGS_EXPORT}" \
-           LDSHAREDFLAGS="${LDSHAREDFLAGS}" CSHAREDFLAGS="${CSHAREDFLAGS}" \
-           LIBSHARED="${LIBSHARED}" \
-           all
-
-FRC:
-
-kinstall :     kernel
-       -mkdir ${DESTDIR}
-       -mkdir ${ETCDIR}
-       ${INSTALL} -c netatalk.o ${ETCDIR}
-
-install :      kinstall
-       -mkdir ${DESTDIR}
-       -mkdir ${SBINDIR}
-       -mkdir ${BINDIR}
-       -mkdir ${ETCDIR}
-       -mkdir ${LIBDIR}
-       for i in ${ALL}; \
-           do (cd $$i; ${MAKE} ${MFLAGS} CC="${CC}" \
-               ADDLIBS="${ADDLIBS}" DEFS="${DEFS}" OPTOPTS="${OPTOPTS}" \
-               SBINDIR="${SBINDIR}" BINDIR="${BINDIR}" RESDIR="${RESDIR}" \
-               ETCDIR="${ETCDIR}" LIBDIR="${LIBDIR}" INCDIR="${INCDIR}" \
-               DESTDIR="${DESTDIR}" MANDIR="${MANDIR}" AFPLIBS="${AFPLIBS}" \
-               AFSDIR="${AFSDIR}" KRBDIR="${KRBDIR}" \
-               LDSHARED="${LDSHARED}" LDFLAGS_EXPORT="${LDFLAGS_EXPORT}" \
-               LDSHAREDFLAGS="${LDSHAREDFLAGS}" \
-               CSHAREDFLAGS="${CSHAREDFLAGS}" LIBSHARED="${LIBSHARED}" \
-               INSTALL="${INSTALL}" $@); \
-       done
-       rm -f ${ETCDIR}/rc.atalk
-       sed -e s@:DESTDIR:@${DESTDIR}@ -e s@:SBINDIR:@${SBINDIR}@ \
-               -e s@:BINDIR:@${BINDIR}@ -e s@:RESDIR:@${RESDIR}@ \
-               -e s@:ETCDIR:@${ETCDIR}@ -e s@:LIBDIR:@${LIBDIR}@ \
-               -e s@:INCDIR:@${INCDIR}@ -e 's@^##@@' \
-           < ../../distrib/initscripts/rc.atalk.bsd > ${ETCDIR}/rc.atalk
-       if [ -f ${ETCDIR}/afpd.conf ]; then \
-               echo "Retaining old afpd.conf file.";  \
-       else \
-               sed -e s@:DESTDIR:@${DESTDIR}@ -e s@:SBINDIR:@${SBINDIR}@ \
-                       -e s@:BINDIR:@${BINDIR}@ -e s@:RESDIR:@${RESDIR}@ \
-                       -e s@:ETCDIR:@${ETCDIR}@ -e s@:LIBDIR:@${LIBDIR}@ \
-                       -e s@:INCDIR:@${INCDIR}@ \
-                       < ../../config/afpd.conf > ${ETCDIR}/afpd.conf; \
-       fi
-       @echo
-       @echo "Install is done.  Don't forget to add lines from"
-       @echo "services.atalk to /etc/services and to call rc.atalk"
-       @echo "in /etc/rc.  See README and README.SUN for more"
-       @echo "information."
-
-clean : sysclean
-       for i in ${ALL}; \
-           do (cd $$i; ${MAKE} ${MFLAGS} clean); \
-       done
-
-sysclean :
-       rm -f a.out core* *.o *.bak *[Ee]rrs tags
-       rm -f netatalk.o
-
-depend :
-       for i in ${ALL}; \
-           do (cd $$i; ${MAKE} ${MFLAGS} DEFS=${DEFS} depend); \
-       done
-       for i in ${SRC} ; do \
-           ${CC} -M ${DEFS} ${INCPATH} $$i | \
-           awk ' { if ($$1 != prev) { print rec; rec = $$0; prev = $$1; } \
-               else { if (length(rec $$2) > 78) { print rec; rec = $$0; } \
-               else rec = rec " " $$2 } } \
-               END { print rec } ' >> makedep; done
-       sed -n '1,/^# DO NOT DELETE THIS LINE/p' Makefile > Makefile.tmp
-       cat makedep >> Makefile.tmp
-       rm makedep
-       echo '# DEPENDENCIES MUST END AT END OF FILE' >> Makefile.tmp
-       echo '# IF YOU PUT STUFF HERE IT WILL GO AWAY' >> Makefile.tmp
-       echo '# see make depend above' >> Makefile.tmp
-       rm -f Makefile.bak
-       cp Makefile Makefile.bak
-       mv Makefile.tmp Makefile
-
-# DO NOT DELETE THIS LINE
-
diff --git a/sys/sunos/at_sun.c b/sys/sunos/at_sun.c
deleted file mode 100644 (file)
index 1cfc020..0000000
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- * $Id: at_sun.c,v 1.2 2001-08-06 13:39:30 rufustfirefly Exp $
- */
-
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/mbuf.h>
-#include <sys/protosw.h>
-#include <sys/domain.h>
-#include <sys/errno.h>
-
-#include <net/if_arp.h>
-#include <net/if.h>
-#include <net/route.h>
-#include <net/af.h>
-#include <net/netisr.h>
-
-#include <sun/vddrv.h>
-
-#include <netinet/in.h>
-#undef s_net
-#include <netinet/if_ether.h>
-
-#include <netatalk/at.h>
-#include <netatalk/at_var.h>
-#include <netatalk/ddp_var.h>
-#include <netatalk/phase2.h>
-
-struct vdlat {
-    int                vda_magic;
-    char       *vda_name;
-}      atvdl = {
-    VDMAGIC_USER, "netatalk"
-};
-
-struct ifqueue *atef_input();
-int            atef_output();
-extern int     atintr();
-
-extern u_char  aarp_org_code[ 3 ];
-extern u_char  at_org_code[ 3 ];
-
-/*
- * Entries in this table are inserted into the ether_families linked
- * list at the beginnning. As such, they will be searched by the input
- * and output routines opposite to the order here.
- *
- * In order to do both phase 1 and phase 2 during output, we have a
- * special entry (the AF_APPLETALK entry) whose ethertype field is
- * changed by the output function, to reflect the actual link layer
- * to be used. This ether_family entry is never seen during Ethernet
- * input, since the earlier entry captures all packets (it is seen
- * during loopback input, in that the input function is called directly
- * on loopback output).
- */
-struct ether_family    ether_atalk[] = {
-    {
-       AF_APPLETALK,   0,      /* Changed by atef_output() */
-       atef_input,     atef_output,    atintr,
-    },
-    {
-       0,              ETHERTYPE_AARP,
-       atef_input,     0,              0,
-    },
-    {
-       0,              ETHERTYPE_AT,
-       atef_input,     0,              atintr,
-    },
-    {
-       0,              EF_8023_TYPE,
-       atef_input,     0,              atintr,
-    },
-};
-int    ether_atalkN = sizeof( ether_atalk ) / sizeof( ether_atalk[ 0 ] );
-
-extern struct ether_family     *ether_families;
-
-extern int                     atalk_hash(), atalk_netmatch();
-extern int                     null_hash(), null_netmatch();
-
-xxxinit( cmd, vdd, vdi, vds )
-    unsigned int       cmd;
-    struct vddrv       *vdd;
-    addr_t             vdi;
-    struct vdstat      *vds;
-{
-    struct ether_family        *ef;
-    struct domain      *dom;
-    struct protosw     *pr;
-    int                        i;
-
-    switch( cmd ) {
-       case VDLOAD :
-           vdd->vdd_vdtab = (struct vdlinkage *)&atvdl;
-
-           /*
-            * Register with the network-interface layer (ethernet).
-            */
-           for ( i = 0; i < ether_atalkN; i++ ) {
-               ether_register( &ether_atalk[ i ] );
-           }
-
-           /*
-            * Register with the socket layer.
-            */
-           atalkdomain.dom_next = domains;
-           domains = &atalkdomain;
-           if ( atalkdomain.dom_init ) {
-               (*atalkdomain.dom_init)();
-           }
-           for ( pr = atalkdomain.dom_protosw;
-                   pr < atalkdomain.dom_protoswNPROTOSW; pr++ ) {
-               if ( pr->pr_init ) {
-                   (*pr->pr_init)();
-               }
-           }
-
-           /*
-            * Cobble ourselves into the routing table.
-            */
-           afswitch[ AF_APPLETALK ].af_hash = atalk_hash;
-           afswitch[ AF_APPLETALK ].af_netmatch = atalk_netmatch;
-           return( 0 );
-
-       case VDUNLOAD :
-           /*
-            * Make sure that there are no open appletalk sockets.
-            */
-           if ( ddpcb != NULL ) {
-               return( EMFILE );
-           }
-
-           /*
-            * There is no ether_unregister(), so we'll have to do it
-            * our selves...
-            */
-           for ( i = 0; i < ether_atalkN; i++ ) {
-               if ( ether_families == &ether_atalk[ i ] ) {
-                   ether_families = ether_families->ef_next;
-                   continue;
-               } else {
-                   for ( ef = ether_families; ef->ef_next; ef = ef->ef_next ) {
-                       if ( ef->ef_next == &ether_atalk[ i ] ) {
-                           ef->ef_next = ef->ef_next->ef_next;
-                           break;
-                       }
-                   }
-               }
-           }
-
-           /*
-            * Remove aarp timers and held packets.
-            */
-           aarp_clean();
-
-           /*
-            * Remove AppleTalk interface addresses.
-            */
-           aa_clean();
-
-           /*
-            * Remove our routines from the routing table.
-            */
-           afswitch[ AF_APPLETALK ].af_hash = null_hash;
-           afswitch[ AF_APPLETALK ].af_netmatch = null_netmatch;
-
-           /*
-            * Remove atalkdomain from the domains list.
-            * Unlikely, but someone may have registered after us.
-            */
-           if ( domains == &atalkdomain ) {
-               domains = domains->dom_next;
-           } else {
-               for ( dom = domains; dom->dom_next; dom = dom->dom_next ) {
-                   if ( dom->dom_next == &atalkdomain ) {
-                       dom->dom_next = dom->dom_next->dom_next;
-                       break;
-                   }
-               }
-           }
-           return( 0 );
-
-       case VDSTAT :
-           return( 0 );
-       default :
-           return( EIO );
-    }
-}
-
-/*
- * Input routine for netatalk on suns.  There are five possible
- * packets.  First, packets received on the loopback interface
- * are immediately sent to the phase 1 interrupt queue (this will
- * have to change if we ever do a phase 2 only version).  Second,
- * IEEE802 packet are sent to either the aarpinput() routine or
- * the phase 2 interrupt queue.  Finally, DIX packets are sent
- * to either aarpinput() or the phase 1 interrupt queue.
- */
-    struct ifqueue *
-atef_input( ifp, m, header )
-    struct ifnet       *ifp;
-    struct mbuf                *m;
-    struct ether_header        *header;
-{
-    struct llc         llc;
-    struct mbuf                *n = 0;
-
-    /*
-     * Check first for LOOPBACK flag, since loopback code passes NULL for
-     * the header.
-     */
-    if ( ifp->if_flags & IFF_LOOPBACK ) {
-       return( &atintrq2 );
-    }
-
-    /*
-     * Before SunOS 4.1, the ether_type was passed as is from the
-     * packet.  After SunOS 4.1, the ether_type is swapped in
-     * do_protocol(), before the ether_family routines are called.
-     */
-#if defined( sun ) && defined( i386 )
-    header->ether_type = ntohs( header->ether_type );
-#endif /* sun i386 */
-
-    if ( header->ether_type <= ETHERMTU ) {    /* IEEE802 */
-       /*
-        * We need to remove the interface pointer from the beginning of this
-        * packet.  We can't always use IF_ADJ(), since it can (and will,
-        * very often) MFREE() the first mbuf in our chain.  If IF_ADJ()
-        * would free the first mbuf, we just advance our pointer to the
-        * next mbuf.  Since our calling routine passes m by value, we're
-        * not actually losing m.  Later, we don't need to put the interface
-        * pointer back on, since the caller still has it in its copy of m.
-        */
-       if ( m->m_len == sizeof( struct ifnet * )) {
-           n = m;
-           m = m->m_next;
-       } else {
-           IF_ADJ( m );
-       }
-
-       /*
-        * We can't call m_pullup(), since we need to preserve
-        * the value of m.
-        */
-       if ( m->m_len < sizeof( struct llc )) {
-printf( "atef_input size llc\n" );
-           ( n ) ? m_freem( n ) : m_freem( m );
-           return( 0 );
-       }
-       bcopy( mtod( m, caddr_t ), &llc, sizeof( struct llc ));
-       if ( llc.llc_dsap != LLC_SNAP_LSAP || llc.llc_ssap != LLC_SNAP_LSAP ||
-               llc.llc_control != LLC_UI ) {
-           ( n ) ? m_freem( n ) : m_freem( m );
-           return( 0 );
-       }
-
-       /*
-        * See IF_ADJ() above.  Here we prepend ifp to the mbuf chain.  If we
-        * didn't remove it earlier, we don't replace it here.
-        */
-       if ( n ) {
-           m_adj( m, sizeof( struct llc ));
-       } else {
-           m_adj( m, sizeof( struct llc ) - sizeof( struct ifnet *));
-           if ( m->m_len < sizeof( struct ifnet * )) {
-printf( "atef_input too small!\n" );
-               m_freem( m );
-               return( 0 );
-           }
-           *mtod( m, struct ifnet ** ) = ifp;
-       }
-
-       if ( ntohs( llc.llc_ether_type ) == ETHERTYPE_AT &&
-               bcmp( llc.llc_org_code, at_org_code,
-               sizeof( at_org_code )) == 0 ) {
-           return( &atintrq2 );
-       }
-
-       /* do we really want to pass m, here?  what happened to n? XXX */
-       if ( ntohs( llc.llc_ether_type ) == ETHERTYPE_AARP &&
-               bcmp( llc.llc_org_code, aarp_org_code,
-               sizeof( aarp_org_code )) == 0 ) {
-           aarpinput( ifp, n ? n : m );
-           return( 0 );
-       }
-
-    } else {                                   /* DIX */
-       switch ( header->ether_type ) {
-       case ETHERTYPE_AT :
-           return( &atintrq1 );
-
-       case ETHERTYPE_AARP :
-           aarpinput( ifp, m );
-           return( 0 );
-       }
-    }
-
-    ( n ) ? m_freem( n ) : m_freem( m );
-    return( 0 );
-}
-
-/*
- * If the destination is on a 802.3 wire, do phase 2 encapsulation,
- * adding the 802.2 and SNAP headers.  Always fill in the edst with the
- * ethernet address of the destination.
- */
-atef_output( dst, m, ifp, edst )
-    struct sockaddr_at *dst;
-    struct mbuf                *m;
-    struct ifnet       *ifp;
-    struct ether_addr  *edst;
-{
-    struct at_ifaddr   *aa;
-    struct mbuf                *m0;
-    struct llc         llc;
-    int                        s;
-
-    s = splimp();
-    if ( !aarpresolve( ifp, m, dst, edst )) {
-       (void) splx( s );
-       return( 1 );
-    }
-    (void) splx( s );
-
-    /*
-     * ifaddr is the first thing in at_ifaddr
-     */
-    if (( aa = (struct at_ifaddr *)at_ifawithnet( dst, ifp->if_addrlist ))
-           == 0 ) {
-       m_freem( m );
-       return( 1 );
-    }
-
-    /*
-     * In the phase 2 case, we need to prepend an mbuf for the llc header.
-     * Since we must preserve the value of m, which is passed to us by
-     * value, we m_copy() the first mbuf, and use it for our llc header.
-     *
-     * We could worry about leaving space for the ether header, but
-     * since we'll have to go through all sorts of hoops, including a
-     * possibly large copy, there's really no sense.
-     */
-    if ( aa->aa_flags & AFA_PHASE2 ) {
-       if ( M_HASCL( m ) || m->m_off - MMINOFF < sizeof( struct llc )) {
-           if (( m0 = m_copy( m, 0, m->m_len )) == 0 ) {
-               m_freem( m );
-               return( 1 );
-           }
-           if ( M_HASCL( m )) {        /* m is a cluster */
-               int s = splimp();
-
-               mclput( m );
-               splx( s );
-           }
-
-           m0->m_next = m->m_next;
-           m->m_next = m0;
-           m->m_off = MMAXOFF - sizeof( struct llc );
-           m->m_len = sizeof( struct llc );
-       } else {
-           m->m_off -= sizeof( struct llc );
-           m->m_len += sizeof( struct llc );
-       }
-
-       llc.llc_dsap = llc.llc_ssap = LLC_SNAP_LSAP;
-       llc.llc_control = LLC_UI;
-       bcopy( at_org_code, llc.llc_org_code, sizeof( at_org_code ));
-       llc.llc_ether_type = htons( ETHERTYPE_AT );
-       bcopy( &llc, mtod( m, caddr_t ), sizeof( struct llc ));
-       ether_atalk[ 0 ].ef_ethertype = EF_8023_TYPE;
-       return( 0 );
-    } else {
-       ether_atalk[ 0 ].ef_ethertype = ETHERTYPE_AT;
-       return( 0 );
-    }
-}
diff --git a/sys/ultrix/.gitignore b/sys/ultrix/.gitignore
deleted file mode 100644 (file)
index 895a5e7..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-Makefile
-Makefile.in
-.gitignore
-*.o
diff --git a/sys/ultrix/Makefile.am b/sys/ultrix/Makefile.am
deleted file mode 100644 (file)
index 9906f2c..0000000
+++ /dev/null
@@ -1 +0,0 @@
-EXTRA_DIST = Makefile.kernel at_ultrix.c kpatch-4.1 kpatch-4.2
diff --git a/sys/ultrix/Makefile.kernel b/sys/ultrix/Makefile.kernel
deleted file mode 100644 (file)
index e3aa638..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-# Ultrix specific defines, passed to subdirectories.
-# i believe that the current setup will break with this.
-#DEFS=
-DEFS=-I../../sys/generic -DUSE_OLD_RQUOTA
-OPTOPTS=
-#CC=   cc 
-CC = gcc 
-CSHAREDFLAGS=   -fPIC
-LDSHARED=      gcc
-LDSHAREDFLAGS=  -shared
-LDFLAGS_EXPORT=-rdynamic
-
-INSTALL=       install
-
-LIBSHARED=      -ldl
-AFPLIBS= 
-ADDLIBS=
-
-INCPATH = -I../../include -I../netatalk
-CFLAGS=        ${DEFS} ${OPTOPTS} ${INCPATH}
-
-ALL=   ../../libatalk ../../include ../../bin ../../etc ../../man
-
-oops:
-       @echo "Read README again.  Don't type 'make' here."
-       @exit 1
-
-all:    ${ALL}
-
-../../bin ../../etc:   ../../libatalk
-
-${ALL}:        FRC
-       cd $@; ${MAKE} ${MFLAGS} CC="${CC}" \
-           ADDLIBS="${ADDLIBS}" DEFS="${DEFS}" OPTOPTS="${OPTOPTS}" \
-           SBINDIR="${SBINDIR}" BINDIR="${BINDIR}" RESDIR="${RESDIR}" \
-           ETCDIR="${ETCDIR}" LIBDIR="${LIBDIR}" INCDIR="${INCDIR}" \
-           DESTDIR="${DESTDIR}" AFSDIR="${AFSDIR}" KRBDIR="${KRBDIR}" \
-           AFPLIBS="${AFPLIBS}" LDSHARED="${LDSHARED}" \
-           LDFLAGS_EXPORT="${LDFLAGS_EXPORT}" \
-           LDSHAREDFLAGS="${LDSHAREDFLAGS}" CSHAREDFLAGS="${CSHAREDFLAGS}" \
-           LIBSHARED="${LIBSHARED}" \
-           all
-
-FRC: kpatch-4.3 kpatch-4.4
-
-kpatch-4.3:
-       -ln -s kpatch-4.2 kpatch-4.3
-kpatch-4.4:
-       -ln -s kpatch-4.2 kpatch-4.4
-
-install :
-       -mkdir ${DESTDIR}
-       for i in ${ALL}; \
-           do (cd $$i; ${MAKE} ${MFLAGS} CC="${CC}" \
-               ADDLIBS="${ADDLIBS}" DEFS="${DEFS}" OPTOPTS="${OPTOPTS}" \
-               SBINDIR="${SBINDIR}" BINDIR="${BINDIR}" RESDIR="${RESDIR}" \
-               ETCDIR="${ETCDIR}" LIBDIR="${LIBDIR}" INCDIR="${INCDIR}" \
-               DESTDIR="${DESTDIR}" MANDIR="${MANDIR}" \
-               AFSDIR="${AFSDIR}" KRBDIR="${KRBDIR}" AFPLIBS="${AFPLIBS}" \
-               LDSHARED="${LDSHARED}" LDFLAGS_EXPORT="${LDFLAGS_EXPORT}" \
-               LDSHAREDFLAGS="${LDSHAREDFLAGS}" \
-               CSHAREDFLAGS="${CSHAREDFLAGS}" LIBSHARED="${LIBSHARED}" \
-               INSTALL="${INSTALL}" $@); \
-       done
-       rm -f ${ETCDIR}/rc.atalk
-       sed -e s@:DESTDIR:@${DESTDIR}@ -e s@:SBINDIR:@${SBINDIR}@ \
-               -e s@:BINDIR:@${BINDIR}@ -e s@:RESDIR:@${RESDIR}@ \
-               -e s@:ETCDIR:@${ETCDIR}@ -e s@:LIBDIR:@${LIBDIR}@ \
-               -e s@:INCDIR:@${INCDIR}@ \
-           < ../../distrib/initscripts/rc.atalk.bsd > ${ETCDIR}/rc.atalk
-       @echo
-       @echo "Install is done.  Don't forget to add lines from"
-       @echo "services.atalk to /etc/services and to call rc.atalk
-       @echo "in /etc/rc.  Next, install the kernel patches."
-       @echo "See README.ULTRIX for more information."
-
-kpatch :
-       @echo "WARNING!!!  This patches your kernel!!!"
-       @echo -n "(hit control-c with in 10 seconds, to stop)"
-       @sleep 10
-       @echo
-       @echo
-       @if grep -s -w atalk /sys/conf/files; then \
-           echo "You already have a version of netatalk installed."; \
-           echo "You will have to remove this old version.  See"; \
-           echo "README.ULTRIX for specific instructions."; \
-           exit 1; \
-       else \
-           case `/bin/uname -r` in \
-               4.1) echo -n "Applying 4.1 patches..."; \
-                   patch -s -d /sys -p0 < kpatch-4.1;  \
-                   echo " done."; \
-                   ;; \
-               4.2|4.3|4.4) echo -n "Applying 4.2/4.3/4.4 patches..."; \
-                   patch -s -d /sys -p0 < kpatch-4.2;  \
-                   echo " done."; \
-                   ;; \
-               *) echo "Unknown release of Ultrix"; exit 1; \
-                   ;; \
-           esac; \
-       fi
-       @echo
-       @echo "Next, install the netatalk kernel files.  See README.ULTRIX"
-       @echo "for specific instructions."
-
-kinstall :
-       @echo "Copying netatalk to kernel building area..."
-       -mkdir /sys/net/netatalk
-       cp ../netatalk/*.[ch] *.[ch] /sys/net/netatalk
-       @echo "Done."
-       @echo
-       @echo "Next, make a new kernel.  See README.ULTRIX"
-       @echo "for specific instructions."
-
-clean :
-       for i in ${ALL}; \
-           do (cd $$i; ${MAKE} ${MFLAGS} clean); \
-       done
-
-sysclean :
-
-depend :
-       for i in ${ALL}; \
-           do (cd $$i; ${MAKE} ${MFLAGS} DEFS="${DEFS}" depend); \
-       done
-       for i in ${SRC} ; do \
-           ${CC} -M ${DEFS} ${INCPATH} $$i | \
-           awk ' { if ($$1 != prev) { print rec; rec = $$0; prev = $$1; } \
-               else { if (length(rec $$2) > 78) { print rec; rec = $$0; } \
-               else rec = rec " " $$2 } } \
-               END { print rec } ' >> makedep; done
-       sed -n '1,/^# DO NOT DELETE THIS LINE/p' Makefile > Makefile.tmp
-       cat makedep >> Makefile.tmp
-       rm makedep
-       echo '# DEPENDENCIES MUST END AT END OF FILE' >> Makefile.tmp
-       echo '# IF YOU PUT STUFF HERE IT WILL GO AWAY' >> Makefile.tmp
-       echo '# see make depend above' >> Makefile.tmp
-       rm -f Makefile.bak
-       cp Makefile Makefile.bak
-       mv Makefile.tmp Makefile
-
-# DO NOT DELETE THIS LINE
-
diff --git a/sys/ultrix/at_ultrix.c b/sys/ultrix/at_ultrix.c
deleted file mode 100644 (file)
index e53fb39..0000000
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (c) 1990,1991 Regents of The University of Michigan.
- * All Rights Reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby granted,
- * provided that the above copyright notice appears in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation, and that the name of The University
- * of Michigan not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. This software is supplied as is without expressed or
- * implied warranties of any kind.
- *
- *     Research Systems Unix Group
- *     The University of Michigan
- *     c/o Mike Clark
- *     535 W. William Street
- *     Ann Arbor, Michigan
- *     +1-313-763-0525
- *     netatalk@itd.umich.edu
- */
-
-#include <sys/types.h>
-#include <sys/mbuf.h>
-#include <sys/socket.h>
-#include <sys/protosw.h>
-#include <sys/ioctl.h>
-#include <sys/errno.h>
-#include <net/if.h>
-#include <net/if_llc.h>
-#include <net/if_to_proto.h>
-#include <net/netisr.h>
-#include <netinet/in.h>
-#undef s_net
-#include <netinet/if_ether.h>
-
-#include "at.h"
-#include "at_var.h"
-
-extern u_char  at_org_code[ 3 ];
-extern u_char  aarp_org_code[ 3 ];
-
-/*
- * This is the magic input routine, for all AppleTalk related packets.
- * It will pick up *all* packets received, on all interfaces, apparently.
- * If it turns out that receiving all packets in this fashion causes
- * DLI to not receive packets what it should, we may need to call DLI
- * directly from within the AppleTalk input routines.  Ick.
- */
-struct mbuf *
-ddp_ifinput( m, ifp, inq, eh )
-    struct mbuf                *m;
-    struct ifnet       *ifp;
-    struct ifqueue     **inq;
-    struct ether_header        *eh;
-{
-    struct llc         llc;
-    struct if_family   *ifam;
-
-    switch ( eh->ether_type ) {
-    case ETHERTYPE_AT :
-       *inq = &atintrq1;
-       smp_lock( &(*inq)->lk_ifqueue, LK_RETRY );
-       schednetisr( NETISR_AT );
-       return( m );
-
-    case ETHERTYPE_AARP :
-       aarpinput( ifp, m );
-       return( 0 );
-
-    default :
-       if ( eh->ether_type <= ETHERMTU ) {             /* ieee802 */
-           if ( m->m_len < sizeof( struct llc )) {
-               break;
-           }
-
-           bcopy( mtod( m, caddr_t ), &llc, sizeof( struct llc ));
-           if ( llc.llc_dsap != LLC_SNAP_LSAP ||
-                   llc.llc_ssap != LLC_SNAP_LSAP ||
-                   llc.llc_control != LLC_UI ) {
-               break;
-           }
-
-           if ( bcmp( llc.llc_org_code, at_org_code,
-                   sizeof( at_org_code )) == 0 &&
-                   ntohs( llc.llc_ether_type ) == ETHERTYPE_AT ) {
-               m_adj( m, sizeof( struct llc ));
-               *inq = &atintrq2;
-               smp_lock( &(*inq)->lk_ifqueue, LK_RETRY );
-               schednetisr( NETISR_AT );
-               return( m );
-           }
-
-           if ( bcmp( llc.llc_org_code, aarp_org_code,
-                   sizeof( aarp_org_code )) == 0 &&
-                   ntohs( llc.llc_ether_type ) == ETHERTYPE_AARP ) {
-               m_adj( m, sizeof( struct llc ));
-               aarpinput( ifp, m );
-               return( 0 );
-           }
-       }
-    }
-
-    /*
-     * Check is anyone else wants this packet.
-     */
-    for ( ifam = if_family; ifam->domain != -1; ifam++ ) {
-       if (( eh->ether_type == ifam->if_type || ifam->if_type == -1 ) &&
-               ifam->prswitch &&
-               ifam->prswitch->pr_ifinput != (int (*)())ddp_ifinput ) {
-           break;
-       }
-    }
-    if ( ifam->domain != -1 && ifam->prswitch->pr_ifinput ) {
-       return( (struct mbuf *)(*ifam->prswitch->pr_ifinput)( m, ifp,
-               inq, eh ));
-    }
-
-    m_freem( m );
-    return( 0 );
-}
-
-/*
- * Fill in type and odst. odst is the media output address, i.e.
- * the MAC layer address. Type is the MAC type. Should be 0 to
- * indicate IEEE addressing.
- *
- * Stupidly enough, there's no way to say "can't send this now."
- * So, we just let the first packet go into the air. Not much
- * else to be done, except maybe bitch at DEC. Note: we're not
- * passing the mbuf to aarpresolve() -- that way it doesn't get
- * mfree-ed twice.
- */
-ddp_ifoutput( ifp, m, dst, type, odst )
-    struct ifnet       *ifp;
-    struct mbuf                *m;
-    struct sockaddr_at *dst;
-    short              *type;
-    char               *odst;
-{
-    struct at_ifaddr   *aa;
-    struct llc         *llc;
-    struct mbuf                *m0;
-
-    if ( !aarpresolve( ifp, 0, dst, odst )) {
-       *type = 0xffff;
-       return( 0 );
-    }
-
-    if (( aa = (struct at_ifaddr *)at_ifawithnet( dst, ifp->if_addrlist ))
-           == 0 ) {
-       *type = 0xffff;
-       return( 0 );
-    }
-
-    if ( aa->aa_flags & AFA_PHASE2 ) {
-       /*
-        * This code needs to be modeled after the similar code in
-        * at_sun.c -- you can't just MGET() and bcopy(), since we might be
-        * dealing with mbufs which are really pages.
-        */
-       MGET( m0, M_WAIT, MT_HEADER );
-       if ( m0 == 0 ) {
-           *type = 0xffff;
-           return( 0 );
-       }
-       m0->m_next = m->m_next;
-       m0->m_off = m->m_off;
-       m0->m_len = m->m_len;
-       bcopy( mtod( m, caddr_t ), mtod( m0, caddr_t ), m->m_len );
-       m->m_next = m0;
-       m->m_off = MMINOFF;
-       m->m_len = sizeof( struct llc );
-
-       llc = mtod( m, struct llc *);
-       llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
-       llc->llc_control = LLC_UI;
-       bcopy( at_org_code, llc->llc_org_code, sizeof( at_org_code ));
-       llc->llc_ether_type = htons( ETHERTYPE_AT );
-
-       /*
-        * Set the type to be the length of the packet, instead of 0.
-        * Ultrix used to put the length in the packet when we set type
-        * to 0, however, now we do it ourselves.
-        */
-       for ( *type = 0; m; m = m->m_next ) {
-           *type += m->m_len;
-       }
-    } else {
-       *type = ETHERTYPE_AT;
-    }
-
-    return( 1 );
-}
-
-ddp_ifioctl( ifp, cmd, data )
-    struct ifnet       *ifp;
-    int                        cmd;
-    caddr_t            data;
-{
-    switch( cmd ) {
-    case SIOCSIFADDR :
-       aarpwhohas((struct arpcom *)ifp,
-               &AA_SAT((struct ifaddr *)data)->sat_addr );
-       break;
-    default :
-       return( EINVAL );
-    }
-    return( 0 );
-}
diff --git a/sys/ultrix/kpatch-4.1 b/sys/ultrix/kpatch-4.1
deleted file mode 100644 (file)
index 8a30e43..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-*** ../sys.old/conf/files      Fri Jul  6 10:19:49 1990
---- ./conf/files       Thu Mar 12 17:33:58 1992
-***************
-*** 75,80 ****
---- 75,87 ----
-  net/netinet/tcp_timer.c      optional inet Binary
-  net/netinet/tcp_usrreq.c     optional inet Binary
-  net/netinet/udp_usrreq.c     optional inet Binary
-+ net/netatalk/aarp.c  optional atalk
-+ net/netatalk/at_control.c    optional atalk
-+ net/netatalk/at_proto.c      optional atalk
-+ net/netatalk/at_ultrix.c     optional atalk
-+ net/netatalk/ddp_input.c     optional atalk
-+ net/netatalk/ddp_output.c    optional atalk
-+ net/netatalk/ddp_usrreq.c    optional atalk
-  net/netbsc/bsc_pcb.c optional bsc Binary
-  net/netbsc/bsc_proto.c       optional bsc 
-  net/netbsc/bsc_states.c      optional bsc Binary
-*** ../sys.old/data/af_data.c  Fri Jul  6 09:40:50 1990
---- ./data/af_data.c   Thu Mar 12 17:34:03 1992
-***************
-*** 69,74 ****
---- 69,82 ----
-  #define AFNS AFNULL
-  #endif NS
-  
-+ #ifdef ATALK
-+ extern int atalk_hash(), atalk_netmatch();
-+ #define AFATALK \
-+      { atalk_hash,   atalk_netmatch }
-+ #else
-+ #define AFATALK      AFNULL
-+ #endif
-+ 
-  #ifdef BINARY
-  
-  extern       struct afswitch afswitch[];
-***************
-*** 78,83 ****
-  struct afswitch afswitch[AF_MAX] = {
-       AFNULL, AFNULL, AFINET, AFINET, AFPUP,
-       AFNULL, AFNS,   AFNULL, AFNULL, AFNULL,
-!      AFNULL
-  };
-  #endif
---- 86,92 ----
-  struct afswitch afswitch[AF_MAX] = {
-       AFNULL, AFNULL, AFINET, AFINET, AFPUP,
-       AFNULL, AFNS,   AFNULL, AFNULL, AFNULL,
-!      AFNULL, AFNULL, AFNULL, AFNULL, AFNULL,
-!      AFNULL, AFATALK, AFNULL, AFNULL, AFNULL,
-  };
-  #endif
-*** ../sys.old/data/if_to_proto_data.c Fri Jul  6 09:40:26 1990
---- ./data/if_to_proto_data.c  Thu Jun  3 11:53:44 1993
-***************
-*** 135,140 ****
---- 135,156 ----
-          { ETHERTYPE_RC,         AF_DLI,         0,              0 }
-  #endif
-  
-+ /*
-+  * Hook for netatalk.  We receive all packets.  If we're not interested
-+  * in the packet, we do a normal search on if_family for someone else
-+  * who might want the packet.
-+  * (Not yet. XXX)
-+  */
-+ #ifdef ATALK
-+ #include "atalk.h"
-+ #undef s_net
-+ #include "../net/netatalk/at.h"
-+ #define ETHER_ATALK \
-+      { -1,                   AF_APPLETALK,   ATPROTO_DDP,    0 }
-+ #else ATALK
-+ #define ETHER_ATALK  IFNULL
-+ #endif ATALK
-+ 
-  #ifdef       BINARY
-  
-  extern struct if_family if_family[];
-***************
-*** 145,151 ****
-  
-  struct if_family if_family[] = {
-!      ETHER_DECNET,   ETHER_LAT,      ETHER_APPLE, ETHER_APPLEARP,
-       ETHER_NS,       ETHER_DLI,      IFEND
-  };
-  
-  #endif
---- 162,168 ----
-  
-  struct if_family if_family[] = {
-!      ETHER_ATALK,    ETHER_DECNET,   ETHER_LAT,      ETHER_APPLE, ETHER_APPLEARP,
-       ETHER_NS,       ETHER_DLI,      IFEND
-  };
-  
-  #endif
-*** ../sys.old/data/uipc_domain_data.c Fri Jul  6 09:40:44 1990
---- ./data/uipc_domain_data.c  Thu Mar 12 17:38:18 1992
-***************
-*** 107,112 ****
---- 107,116 ----
-       ADDDOMAIN(ccitt);
-  #endif CCITT
-  #endif
-+ #ifdef ATALK
-+ #include "atalk.h"
-+      ADDDOMAIN(atalk);
-+ #endif ATALK
-  
-       for (dp = domains; dp; dp = dp->dom_next)
-               for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
-*** ../sys.old/net/net/conf_net.c      Fri Jul  6 10:03:25 1990
---- ./net/net/conf_net.c       Thu Mar 12 17:39:11 1992
-***************
-*** 236,241 ****
---- 236,245 ----
-  extern int ddpintr();
-  #endif
-  
-+ #ifdef ATALK
-+ extern int atintr();
-+ #endif
-+ 
-  #include "../net/net/netisr.h" 
-  /*
-   * table of interrupt vectors - scanned in locore when sofware 
-***************
-*** 280,285 ****
---- 284,292 ----
-  #ifdef OSI
-          {NETISR_OSI,osiintr},
-  #endif OSI
-+ #ifdef ATALK
-+      {NETISR_AT,atintr},
-+ #endif ATALK
-       {-1     ,0}
-  };
-  
-*** ../sys.old/net/net/netisr.h        Fri Jul  6 10:03:28 1990
---- ./net/net/netisr.h Thu Mar 12 17:39:45 1992
-***************
-*** 66,71 ****
---- 66,72 ----
-  #define NETISR_DLI   13              /* same as AF_DLI */
-  #define NETISR_LAT   14              /* same as AF_LAT */
-  #define NETISR_BSC   15              /* same as AF_BSC */
-+ #define NETISR_AT    16              /* same as AF_APPLETALK */
-  #define NETISR_OSI      19              /* same as AF_OSI */
-  
-  #define      schednetisr(anisr)      { set_bit_atomic(anisr,&netisr); setsoftnet(); }
diff --git a/sys/ultrix/kpatch-4.2 b/sys/ultrix/kpatch-4.2
deleted file mode 100644 (file)
index 0c8fa8e..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-*** ../sys.old/conf/files      Wed Jun 19 14:23:30 1991
---- ./conf/files       Fri Mar  6 18:06:45 1992
-***************
-*** 75,80 ****
---- 75,87 ----
-  net/netinet/tcp_timer.c      optional inet Binary
-  net/netinet/tcp_usrreq.c     optional inet Binary
-  net/netinet/udp_usrreq.c     optional inet Binary
-+ net/netatalk/aarp.c  optional atalk
-+ net/netatalk/at_control.c    optional atalk
-+ net/netatalk/at_proto.c      optional atalk
-+ net/netatalk/at_ultrix.c     optional atalk
-+ net/netatalk/ddp_input.c     optional atalk
-+ net/netatalk/ddp_output.c    optional atalk
-+ net/netatalk/ddp_usrreq.c    optional atalk
-  net/netbsc/bsc_pcb.c optional bsc Binary
-  net/netbsc/bsc_proto.c       optional bsc 
-  net/netbsc/bsc_states.c      optional bsc Binary
-*** ../sys.old/data/af_data.c  Mon Apr 29 15:45:53 1991
---- ./data/af_data.c   Sun Mar  8 22:25:15 1992
-***************
-*** 69,74 ****
---- 69,82 ----
-  #define AFNS AFNULL
-  #endif NS
-  
-+ #ifdef ATALK
-+ extern int atalk_hash(), atalk_netmatch();
-+ #define AFATALK \
-+      { atalk_hash,   atalk_netmatch }
-+ #else
-+ #define AFATALK      AFNULL
-+ #endif
-+ 
-  #ifdef BINARY
-  
-  extern       struct afswitch afswitch[];
-***************
-*** 78,83 ****
-  struct afswitch afswitch[AF_MAX] = {
-       AFNULL, AFNULL, AFINET, AFINET, AFPUP,
-       AFNULL, AFNS,   AFNULL, AFNULL, AFNULL,
-!      AFNULL
-  };
-  #endif
---- 86,92 ----
-  struct afswitch afswitch[AF_MAX] = {
-       AFNULL, AFNULL, AFINET, AFINET, AFPUP,
-       AFNULL, AFNS,   AFNULL, AFNULL, AFNULL,
-!      AFNULL, AFNULL, AFNULL, AFNULL, AFNULL,
-!      AFNULL, AFATALK, AFNULL, AFNULL, AFNULL,
-  };
-  #endif
-*** ../sys.old/data/if_to_proto_data.c Mon Apr 29 15:46:34 1991
---- ./data/if_to_proto_data.c  Thu Jun  3 11:53:44 1993
-***************
-*** 125,130 ****
---- 125,143 ----
-          { ETHERTYPE_RC,         AF_DLI,         0,              0 }
-  #endif
-  
-+ /*
-+  * Hook for netatalk.  We receive all packets.  If we're not interested
-+  * in the packet, we do a normal search on if_family for someone else
-+  * who might want the packet.
-+  */
-+ #ifdef ATALK
-+ #include "atalk.h"
-+ #undef s_net
-+ #include "../net/netatalk/at.h"
-+ #define ETHER_ATALK \
-+      { -1,                   AF_APPLETALK,   ATPROTO_DDP,    0 }
-+ #endif ATALK
-+ 
-  #ifdef       BINARY
-  
-  extern struct if_family if_family[];
-***************
-*** 134,139 ****
---- 148,156 ----
-  /* INET specific stuff is kept in drivers for now */
-  
-  struct if_family if_family[] = {
-+ #ifdef ETHER_ATALK
-+      ETHER_ATALK,
-+ #endif
-  #ifdef ETHER_DECNET
-       ETHER_DECNET,
-  #endif
-*** ../sys.old/data/uipc_domain_data.c Mon Apr 29 15:47:08 1991
---- ./data/uipc_domain_data.c  Mon Mar  2 15:24:28 1992
-***************
-*** 123,128 ****
---- 123,132 ----
-       ADDDOMAIN(x25);
-  #endif XXXVNATV
-  #endif X25_DONE
-+ #ifdef ATALK
-+ #include "atalk.h"
-+      ADDDOMAIN(atalk);
-+ #endif ATALK
-  
-  #endif
-  
-*** ../sys.old/net/net/conf_net.c      Mon Apr 29 16:16:23 1991
---- ./net/net/conf_net.c       Sun Mar  8 22:28:32 1992
-***************
-*** 233,238 ****
---- 233,242 ----
-  extern int ddpintr();
-  #endif
-  
-+ #ifdef ATALK
-+ extern int atintr();
-+ #endif
-+ 
-  #include "../net/net/netisr.h" 
-  /*
-   * table of interrupt vectors - scanned in locore when sofware 
-***************
-*** 272,277 ****
---- 276,284 ----
-  #if NLAT == 1
-       {NETISR_LAT,latintr},
-  #endif /* NLAT */
-+ #ifdef ATALK
-+      {NETISR_AT,atintr},
-+ #endif ATALK
-  #ifdef APPLETALK
-       {NETISR_DDP,ddpintr},
-  #endif APPLETALK
-*** ../sys.old/net/net/netisr.h        Mon Apr 29 16:16:21 1991
---- ./net/net/netisr.h Sun Mar  8 22:29:04 1992
-***************
-*** 72,77 ****
---- 72,78 ----
-  #define NETISR_DLI   13              /* same as AF_DLI */
-  #define NETISR_LAT   14              /* same as AF_LAT */
-  #define NETISR_BSC   15              /* same as AF_BSC */
-+ #define NETISR_AT    16              /* same as AF_APPLETALK */
-  #define NETISR_DLO      19              /* same as AF_OSI */
-  
-  #define      schednetisr(anisr)      { set_bit_atomic(anisr,&netisr); setsoftnet(); }
index ca379e0eec0fcd6c79f29c8d7164ed3f97ccc6ef..033c9e1d3784c3b4c0651100d0243c2aa02bf84f 100644 (file)
@@ -10,58 +10,58 @@ EXTRA_DIST = test.sh
 CLEANFILES = test.default test.conf
 
 test_SOURCES =  test.c subtests.c afpfunc_helpers.c \
-                               $(top_builddir)/etc/afpd/afp_avahi.c \
-                               $(top_builddir)/etc/afpd/afp_config.c \
-                               $(top_builddir)/etc/afpd/afp_dsi.c \
-                               $(top_builddir)/etc/afpd/afp_options.c \
-                               $(top_builddir)/etc/afpd/afp_util.c \
-                               $(top_builddir)/etc/afpd/afprun.c \
-                               $(top_builddir)/etc/afpd/appl.c \
-                               $(top_builddir)/etc/afpd/auth.c \
-                               $(top_builddir)/etc/afpd/afp_zeroconf.c \
-                               $(top_builddir)/etc/afpd/catsearch.c \
-                               $(top_builddir)/etc/afpd/desktop.c \
-                               $(top_builddir)/etc/afpd/dircache.c \
-                               $(top_builddir)/etc/afpd/directory.c \
-                               $(top_builddir)/etc/afpd/enumerate.c \
-                               $(top_builddir)/etc/afpd/extattrs.c \
-                               $(top_builddir)/etc/afpd/fce_api.c \
-                               $(top_builddir)/etc/afpd/fce_util.c \
-                               $(top_builddir)/etc/afpd/file.c \
-                               $(top_builddir)/etc/afpd/filedir.c \
-                               $(top_builddir)/etc/afpd/fork.c \
-                               $(top_builddir)/etc/afpd/gettok.c \
-                               $(top_builddir)/etc/afpd/hash.c \
-                               $(top_builddir)/etc/afpd/mangle.c \
-                               $(top_builddir)/etc/afpd/messages.c \
-                               $(top_builddir)/etc/afpd/nfsquota.c \
-                               $(top_builddir)/etc/afpd/ofork.c \
-                               $(top_builddir)/etc/afpd/quota.c \
-                               $(top_builddir)/etc/afpd/status.c \
-                               $(top_builddir)/etc/afpd/switch.c \
-                               $(top_builddir)/etc/afpd/uam.c \
-                               $(top_builddir)/etc/afpd/unix.c \
-                               $(top_builddir)/etc/afpd/volume.c
+                               $(top_srcdir)/etc/afpd/afp_avahi.c \
+                               $(top_srcdir)/etc/afpd/afp_config.c \
+                               $(top_srcdir)/etc/afpd/afp_dsi.c \
+                               $(top_srcdir)/etc/afpd/afp_mdns.c \
+                               $(top_srcdir)/etc/afpd/afp_options.c \
+                               $(top_srcdir)/etc/afpd/afp_util.c \
+                               $(top_srcdir)/etc/afpd/afprun.c \
+                               $(top_srcdir)/etc/afpd/appl.c \
+                               $(top_srcdir)/etc/afpd/auth.c \
+                               $(top_srcdir)/etc/afpd/afp_zeroconf.c \
+                               $(top_srcdir)/etc/afpd/catsearch.c \
+                               $(top_srcdir)/etc/afpd/desktop.c \
+                               $(top_srcdir)/etc/afpd/dircache.c \
+                               $(top_srcdir)/etc/afpd/directory.c \
+                               $(top_srcdir)/etc/afpd/enumerate.c \
+                               $(top_srcdir)/etc/afpd/extattrs.c \
+                               $(top_srcdir)/etc/afpd/fce_api.c \
+                               $(top_srcdir)/etc/afpd/fce_util.c \
+                               $(top_srcdir)/etc/afpd/file.c \
+                               $(top_srcdir)/etc/afpd/filedir.c \
+                               $(top_srcdir)/etc/afpd/fork.c \
+                               $(top_srcdir)/etc/afpd/gettok.c \
+                               $(top_srcdir)/etc/afpd/hash.c \
+                               $(top_srcdir)/etc/afpd/mangle.c \
+                               $(top_srcdir)/etc/afpd/messages.c \
+                               $(top_srcdir)/etc/afpd/nfsquota.c \
+                               $(top_srcdir)/etc/afpd/ofork.c \
+                               $(top_srcdir)/etc/afpd/quota.c \
+                               $(top_srcdir)/etc/afpd/status.c \
+                               $(top_srcdir)/etc/afpd/switch.c \
+                               $(top_srcdir)/etc/afpd/uam.c \
+                               $(top_srcdir)/etc/afpd/unix.c \
+                               $(top_srcdir)/etc/afpd/volume.c
 
 if HAVE_ACLS
-test_SOURCES += $(top_builddir)/etc/afpd/acls.c
+test_SOURCES += $(top_srcdir)/etc/afpd/acls.c
 endif
 
-test_CFLAGS = -I$(top_srcdir)/include -I$(top_srcdir)/etc/afpd \
-        @SLP_CFLAGS@ @ZEROCONF_CFLAGS@ \
-        -DAPPLCNAME \
-        -DSERVERTEXT=\"$(SERVERTEXT)/\" \
-        -D_PATH_AFPDDEFVOL=\"$(pkgconfdir)/AppleVolumes.default\" \
-        -D_PATH_AFPDSYSVOL=\"$(pkgconfdir)/AppleVolumes.system\" \
-        -D_PATH_AFPDPWFILE=\"$(pkgconfdir)/afppasswd\" \
-        -D_PATH_AFPDCONF=\"$(pkgconfdir)/afpd.conf\" \
-        -D_PATH_AFPDUAMPATH=\"$(UAMS_PATH)/\" \
-        -D_PATH_ACL_LDAPCONF=\"$(pkgconfdir)/afp_ldap.conf\" \
-        -D_PATH_AFPDSIGCONF=\"$(pkgconfdir)/afp_signature.conf\" \
-        -D_PATH_AFPDUUIDCONF=\"$(pkgconfdir)/afp_voluuid.conf\"
+test_CFLAGS = \
+       -I$(top_srcdir)/etc/afpd \
+       -I$(top_srcdir)/include \
+       -I$(top_srcdir)/sys \
+       @ZEROCONF_CFLAGS@ @GSSAPI_CFLAGS@ @KRB5_CFLAGS@\
+       -DAPPLCNAME \
+       -DSERVERTEXT=\"$(SERVERTEXT)/\" \
+       -D_PATH_AFPDPWFILE=\"$(pkgconfdir)/afppasswd\" \
+       -D_PATH_AFPDUAMPATH=\"$(UAMS_PATH)/\" \
+       -D_PATH_CONFDIR=\"$(pkgconfdir)/\" \
+       -D_PATH_STATEDIR='"$(localstatedir)/netatalk/"'
 
-test_LDADD = $(top_builddir)/libatalk/cnid/libcnid.la \
+test_LDADD = \
        $(top_builddir)/libatalk/libatalk.la \
-       @QUOTA_LIBS@ @SLP_LIBS@ @WRAP_LIBS@ @LIBADD_DL@ @ACL_LIBS@ @ZEROCONF_LIBS@ @PTHREAD_LIBS@
+       @LIBGCRYPT_LIBS@ @QUOTA_LIBS@ @WRAP_LIBS@ @LIBADD_DL@ @ACL_LIBS@ @ZEROCONF_LIBS@ @PTHREAD_LIBS@ @GSSAPI_LIBS@ @KRB5_LIBS@
 
 test_LDFLAGS = -export-dynamic
index fe443c15747bd50e3fee07086baedee53d8eb67e..4387bdfca7e852f7cb45e4f943cd352501c69df5 100644 (file)
@@ -176,6 +176,7 @@ int enumerate(AFPObj *obj, uint16_t vid, cnid_t did)
     char buf[bufsize];
     char *p = buf;
     int len = 0;
+    int ret;
 
     ADD(p, len , 2);
 
@@ -189,7 +190,11 @@ int enumerate(AFPObj *obj, uint16_t vid, cnid_t did)
 
     len += push_path(&p, "");
 
-    return afp_enumerate_ext2(obj, buf, len, rbuf, &rbuflen);
+    ret = afp_enumerate_ext2(obj, buf, len, rbuf, &rbuflen);
+
+    if (ret != AFPERR_NOOBJ && ret != AFP_OK)
+        return -1;
+    return 0;
 }
 
 uint16_t openvol(AFPObj *obj, const char *name)
index 74008019c7c77283f27e7ea719494b72eb3e960b..54fc23745a70a8bf519428a8e2f4f174137acf13 100644 (file)
@@ -29,6 +29,7 @@
 #include <atalk/queue.h>
 #include <atalk/bstrlib.h>
 #include <atalk/globals.h>
+#include <atalk/netatalk_conf.h>
 
 #include "file.h"
 #include "filedir.h"
 
 /* Stuff from main.c which of cource can't be added as source to testbin */
 unsigned char nologin = 0;
-struct afp_options default_options;
-static AFPConfig *configs;
-
+static AFPObj obj;
+#define ARGNUM 3
+static char *args[] = {"test", "-F", "test.conf"};
 /* Static variables */
 
 int main(int argc, char **argv)
 {
-    #define ARGNUM 7
-    char *args[ARGNUM] = {"test", "-F", "test.conf", "-f", "test.default", "-s" ,"test.system"};
     int reti;
     uint16_t vid;
     struct vol *vol;
@@ -60,22 +59,24 @@ int main(int argc, char **argv)
     struct path *path;
 
     /* initialize */
-    afp_version = 32;
     printf("Initializing\n============\n");
-    TEST(setuplog("default log_note /dev/tty"));
-    TEST(afp_options_init(&default_options));
-    TEST_int(afp_options_parse( ARGNUM, args, &default_options), 1);
-    TEST_expr(configs = configinit(&default_options), configs != NULL);
-    TEST(cnid_init());
-    TEST(load_volumes(&configs->obj));
-    TEST_int(dircache_init(8192), 0);
+    TEST(setuplog("default:note","/dev/tty"));
+
+    TEST( afp_options_parse_cmdline(&obj, 3, &args[0]) );
+
+    TEST_int( afp_config_parse(&obj, NULL), 0);
+    TEST_int( configinit(&obj), 0);
+    TEST( cnid_init() );
+    TEST( load_volumes(&obj, NULL) );
+    TEST_int( dircache_init(8192), 0);
+    obj.afp_version = 32;
+
     printf("\n");
 
     /* now run tests */
     printf("Running tests\n=============\n");
 
-    TEST_expr(vid = openvol(&configs->obj, "test"), vid != 0);
+    TEST_expr(vid = openvol(&obj, "test"), vid != 0);
     TEST_expr(vol = getvolbyvid(vid), vol != NULL);
 
     /* test directory.c stuff */
@@ -84,27 +85,27 @@ int main(int argc, char **argv)
     TEST_expr(path = cname(vol, retdir, cnamewrap("Network Trash Folder")), path != NULL);
 
     TEST_expr(retdir = dirlookup(vol, DIRDID_ROOT), retdir != NULL);
-    TEST_int(getfiledirparms(&configs->obj, vid, DIRDID_ROOT_PARENT, "test"), 0);
-    TEST_int(getfiledirparms(&configs->obj, vid, DIRDID_ROOT, ""), 0);
+    TEST_int(getfiledirparms(&obj, vid, DIRDID_ROOT_PARENT, "test"), 0);
+    TEST_int(getfiledirparms(&obj, vid, DIRDID_ROOT, ""), 0);
 
-    TEST_expr(reti = createdir(&configs->obj, vid, DIRDID_ROOT, "dir1"),
+    TEST_expr(reti = createdir(&obj, vid, DIRDID_ROOT, "dir1"),
               reti == 0 || reti == AFPERR_EXIST);
 
-    TEST_int(getfiledirparms(&configs->obj, vid, DIRDID_ROOT, "dir1"), 0);
+    TEST_int(getfiledirparms(&obj, vid, DIRDID_ROOT, "dir1"), 0);
 /*
   FIXME: this doesn't work although it should. "//" get translated to \000 \000 at means ".."
   ie this should getfiledirparms for DIRDID_ROOT_PARENT -- at least afair!
     TEST_int(getfiledirparms(&configs->obj, vid, DIRDID_ROOT, "//"), 0);
 */
-    TEST_int(createfile(&configs->obj, vid, DIRDID_ROOT, "dir1/file1"), 0);
-    TEST_int(delete(&configs->obj, vid, DIRDID_ROOT, "dir1/file1"), 0);
-    TEST_int(delete(&configs->obj, vid, DIRDID_ROOT, "dir1"), 0);
+    TEST_int(createfile(&obj, vid, DIRDID_ROOT, "dir1/file1"), 0);
+    TEST_int(delete(&obj, vid, DIRDID_ROOT, "dir1/file1"), 0);
+    TEST_int(delete(&obj, vid, DIRDID_ROOT, "dir1"), 0);
 
-    TEST_int(createfile(&configs->obj, vid, DIRDID_ROOT, "file1"), 0);
-    TEST_int(getfiledirparms(&configs->obj, vid, DIRDID_ROOT, "file1"), 0);
-    TEST_int(delete(&configs->obj, vid, DIRDID_ROOT, "file1"), 0);
+    TEST_int(createfile(&obj, vid, DIRDID_ROOT, "file1"), 0);
+    TEST_int(getfiledirparms(&obj, vid, DIRDID_ROOT, "file1"), 0);
+    TEST_int(delete(&obj, vid, DIRDID_ROOT, "file1"), 0);
 
 
     /* test enumerate.c stuff */
-    TEST_int(enumerate(&configs->obj, vid, DIRDID_ROOT), 0);
+    TEST_int(enumerate(&obj, vid, DIRDID_ROOT), 0);
 }
index 80066b6e118937b250413abece50a9fc18b0c33e..0396f689241801b84265f46ff68b04e887be0374 100755 (executable)
@@ -10,15 +10,12 @@ fi
 if [ ! -f test.conf ] ; then
     echo -n "Creating configuration template ... "
     cat > test.conf <<EOF
-test -noddp -port 10548
-EOF
-    echo [ok]
-fi
+[Global]
+afp port = 10548
 
-if [ ! -f test.default ] ; then
-    echo -n "Creating volume config template ... "
-    cat > test.default <<EOF
-/tmp/AFPtestvolume "test" ea:none
+[test]
+path = /tmp/AFPtestvolume
+cnid scheme = last
 EOF
     echo [ok]
 fi