# Makefile.am for top level of netatalk package
-SUBDIRS = libatalk bin config etc man contrib distrib include sys doc macros
+SUBDIRS = libatalk bin config etc man contrib distrib include sys doc macros test
EXTRA_DIST = CONTRIBUTORS COPYRIGHT COPYING NEWS\
TODO VERSION services.atalk
-dnl $Id: configure.in,v 1.244 2010-04-13 08:05:06 franklahm Exp $
+dnl $Id: configure.in,v 1.241 2010/04/03 07:11:33 franklahm Exp $
dnl configure.in for netatalk
AC_INIT(etc/afpd/main.c)
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])
]
)
libatalk/adouble/Makefile
libatalk/asp/Makefile
libatalk/atp/Makefile
+ libatalk/bstring/Makefile
libatalk/cnid/Makefile
libatalk/cnid/cdb/Makefile
libatalk/cnid/last/Makefile
sys/solaris/Makefile
sys/sunos/Makefile
sys/ultrix/Makefile
+ test/Makefile
+ test/afpd/Makefile
],
[chmod a+x distrib/config/netatalk-config contrib/shell_utils/apple_*]
)
file.c enumerate.c desktop.c filedir.c fork.c appl.c gettok.c \
mangle.c status.c afp_options.c afp_asp.c afp_dsi.c messages.c \
afp_config.c nfsquota.c quota.c uam.c afs.c uid.c afp_util.c \
- catsearch.c afprun.c hash.c extattrs.c
+ catsearch.c afprun.c hash.c extattrs.c dircache.c
if USE_NFSv4_ACLS
afpd_SOURCES += acls.c
noinst_HEADERS = auth.h afp_config.h desktop.h directory.h file.h \
filedir.h fork.h globals.h icon.h mangle.h misc.h status.h switch.h \
- uam_auth.h uid.h unix.h volume.h hash.h acls.h acl_mappings.h extattrs.h
+ uam_auth.h uid.h unix.h volume.h hash.h acls.h acl_mappings.h extattrs.h \
+ dircache.h
hash_SOURCES = hash.c
hash_CFLAGS = -DKAZLIB_TEST_MAIN -I$(top_srcdir)/include
/*
- * $Id: afp_dsi.c,v 1.53 2010-03-30 12:55:26 franklahm Exp $
+ * $Id: afp_dsi.c,v 1.53 2010/03/30 12:55:26 franklahm Exp $
*
* Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
* Copyright (c) 1990,1993 Regents of The University of Michigan.
#include "switch.h"
#include "auth.h"
#include "fork.h"
+#include "dircache.h"
#ifdef FORCE_UIDGID
#warning UIDGID
}
#endif /* DEBUGGING */
+ if (dircache_init(obj->options.dircachesize) != 0)
+ afp_dsi_die(EXITERR_SYS);
+
/* get stuck here until the end */
while ((cmd = dsi_receive(dsi))) {
child.tickle = 0;
if (reload_request) {
reload_request = 0;
load_volumes(child.obj);
+ dircache_dump();
}
if (debug_request) {
/*
- * $Id: afp_options.c,v 1.54 2010-04-02 16:17:22 hat001 Exp $
+ * $Id: afp_options.c,v 1.54 2010/04/02 16:17:22 hat001 Exp $
*
* Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu)
* Copyright (c) 1990,1993 Regents of The University of Michigan.
#include "globals.h"
#include "status.h"
#include "auth.h"
+#include "dircache.h"
#include <atalk/compat.h>
/* don't advertize slp by default */
options->flags |= OPTION_NOSLP;
#endif
+ options->dircachesize = DEFAULT_MAX_DIRCACHE_SIZE;
}
/* parse an afpd.conf line. i'm doing it this way because it's
if ((c = getoption(buf, "-ntseparator")) && (opt = strdup(c)))
options->ntseparator = opt;
+
+ if ((c = getoption(buf, "-dircachesize")))
+ options->dircachesize = atoi(c);
if ((c = getoption(buf, "-signature")) && (opt = strdup(c))) {
set_signature(opt, options);
/*
- * $Id: appl.c,v 1.18 2009-10-15 10:43:13 didg Exp $
+ * $Id: appl.c,v 1.18.4.1 2010-02-01 10:56:08 franklahm Exp $
*
* Copyright (c) 1990,1993 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
#include <atalk/adouble.h>
#include <atalk/afp.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
#include "volume.h"
#include "globals.h"
* See afp_getappl() for the backward compatiblity code.
*/
static char *
-makemacpath(char *mpath, int mpathlen, struct dir *dir, char *path)
+makemacpath(const struct vol *vol, char *mpath, int mpathlen, struct dir *dir, char *path)
{
char *p;
p -= strlen( path );
memcpy( p, path, strlen( path ));
- while ( dir->d_parent != NULL ) {
- p -= strlen( dir->d_m_name ) + 1;
+ while ( dir->d_did != DIRDID_ROOT ) {
+ p -= blength(dir->d_m_name) + 1;
if (p < mpath) {
/* FIXME: pathname too long */
return NULL;
}
- strcpy( p, dir->d_m_name );
- dir = dir->d_parent;
+ memcpy(p, cfrombstring(dir->d_m_name), blength(dir->d_m_name) + 1);
+ if ((dir = dirlookup(vol, dir->d_pdid)) == NULL)
+ return NULL;
}
return( p );
+
+
+#if 0
+ char buffer[12 + MAXPATHLEN + 1];
+ int buflen = 12 + MAXPATHLEN + 1;
+ char *ret = mpath;
+ char *path = name;
+ char *uname = NULL;
+ struct bstrList *pathlist = NULL;
+ cnid_t cnid = dir->d_pdid;
+
+ /* Create list for path elements, request 16 list elements for now*/
+ if ((pathlist = bstListCreateMin(16)) == NULL) {
+ LOG(log_error, logtype_afpd, "makemacpath: OOM: %s", strerror(errno));
+ return NULL;
+ }
+
+ while ( cnid != DIRDID_ROOT ) {
+
+ /* construct path, copy already found uname to path element list*/
+ if ((bstrListPush(pathlist, bfromcstr(path))) != BSTR_OK) {
+ afp_errno = AFPERR_MISC;
+ ret = NULL;
+ goto exit;
+ }
+
+ /* next part */
+ if ((uname = cnid_resolve(vol->v_cdb, &cnid, buffer, buflen)) == NULL ) {
+ afp_errno = AFPERR_NOOBJ;
+ ret = NULL;
+ goto exit;
+ }
+
+ if ((path = utompath(vol, uname, cnid, utf8_encoding())) == NULL) {
+ afp_errno = AFPERR_MISC;
+ ret = NULL;
+ goto exit;
+ }
+ }
+
+
+
+exit:
+ if (pathlist)
+ bstrListDestroy(pathlist);
+
+ return(ret);
+#endif
}
return( AFPERR_PARAM );
}
mpath = obj->newtmp;
- mp = makemacpath( mpath, AFPOBJ_TMPSIZ, curdir, path->m_name );
+ mp = makemacpath( vol, mpath, AFPOBJ_TMPSIZ, curdir, path->m_name );
if (!mp) {
return AFPERR_PARAM;
}
return( AFPERR_PARAM );
}
mpath = obj->newtmp;
- mp = makemacpath( mpath, AFPOBJ_TMPSIZ, curdir, path->m_name );
+ mp = makemacpath( vol, mpath, AFPOBJ_TMPSIZ, curdir, path->m_name );
if (!mp) {
return AFPERR_PARAM ;
}
memcpy( q, p, len );
q = cbuf;
- if (( path = cname( vol, vol->v_dir, &q )) == NULL ) {
+ if (( path = cname( vol, vol->v_root, &q )) == NULL ) {
*rbuflen = 0;
return( AFPERR_NOITEM );
}
#ifdef CNID_DB
#include <atalk/cnid.h>
#endif /* CNID_DB */
+
#include <atalk/util.h>
+#include <atalk/bstradd.h>
#include "desktop.h"
#include "directory.h"
+#include "dircache.h"
#include "file.h"
#include "volume.h"
#include "globals.h"
/* Put new element. Allocate and copy lname and path. */
ds = dstack + dsidx++;
ds->dir = dir;
+ dir->d_flags |= DIRF_CACHELOCK;
ds->pidx = pidx;
ds->checked = 0;
if (pidx >= 0) {
while (dsidx > 0) {
if (dstack[dsidx-1].checked) {
dsidx--;
+ dstack[dsidx].dir->d_flags &= ~DIRF_CACHELOCK;
free(dstack[dsidx].path);
} else
return dsidx - 1;
save_cidx = -1;
while (dsidx > 0) {
dsidx--;
+ dstack[dsidx].dir->d_flags &= ~DIRF_CACHELOCK;
free(dstack[dsidx].path);
}
}
char *rrbuf = rbuf;
time_t start_time;
int num_rounds = NUM_ROUNDS;
- int cached;
int cwd = -1;
int error;
start_time = time(NULL);
while ((cidx = reducestack()) != -1) {
- cached = 1;
-
error = lchdir(dstack[cidx].path);
- if (!error && dirpos == NULL) {
+ if (!error && dirpos == NULL)
dirpos = opendir(".");
- cached = (dstack[cidx].dir->d_child != NULL);
- }
+
+ if (dirpos == NULL)
+ dirpos = opendir(dstack[cidx].path);
+
if (error || dirpos == NULL) {
switch (errno) {
case EACCES:
ie if in the same loop the parent dir wasn't in the cache
ALL dirsearch_byname will fail.
*/
- if (cached)
- path.d_dir = dirsearch_byname(vol, dstack[cidx].dir, path.u_name);
- else
- path.d_dir = NULL;
- if (!path.d_dir) {
+ int unlen = strlen(path.u_name);
+ path.d_dir = dircache_search_by_name(vol, dstack[cidx].dir, path.u_name, unlen);
+ if (path.d_dir == NULL) {
/* path.m_name is set by adddir */
- if (NULL == (path.d_dir = adddir( vol, dstack[cidx].dir, &path) ) ) {
+ if (NULL == (path.d_dir = dir_add( vol, dstack[cidx].dir, &path, unlen) ) ) {
result = AFPERR_MISC;
goto catsearch_end;
}
}
- path.m_name = path.d_dir->d_m_name;
+ path.m_name = cfrombstring(path.d_dir->d_m_name);
if (addstack(path.u_name, path.d_dir, cidx) == -1) {
result = AFPERR_MISC;
/* Call search */
*rbuflen = 24;
- ret = catsearch(vol, vol->v_dir, rmatches, &catpos[0], rbuf+24, &nrecs, &rsize, ext);
+ ret = catsearch(vol, vol->v_root, rmatches, &catpos[0], rbuf+24, &nrecs, &rsize, ext);
memcpy(rbuf, catpos, sizeof(catpos));
rbuf += sizeof(catpos);
/*
- * $Id: desktop.c,v 1.50 2010-01-22 04:40:38 didg Exp $
+ * $Id: desktop.c,v 1.50.2.1 2010-02-01 10:56:08 franklahm Exp $
*
* See COPYRIGHT.
*
u_int16_t flags;
if ( *mpath == '\0' ) {
- return( "." );
+ strcpy(upath, ".");
+ return upath;
}
/* set conversion flags */
if (ad_getentryoff(adp, ADEID_COMMENT)) {
if ( (ad_get_MD_flags( adp ) & O_CREAT) ) {
if ( *path->m_name == '\0' ) {
- name = curdir->d_m_name;
+ name = (char *)curdir->d_m_name->data;
} else {
name = path->m_name;
}
--- /dev/null
+/*
+ $Id: dircache.c,v 1.1.2.7 2010-02-11 13:06:54 franklahm Exp $
+ Copyright (c) 2010 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 <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <assert.h>
+
+#include <atalk/util.h>
+#include <atalk/cnid.h>
+#include <atalk/logger.h>
+#include <atalk/volume.h>
+#include <atalk/directory.h>
+#include <atalk/queue.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
+
+#include "dircache.h"
+#include "directory.h"
+#include "hash.h"
+#include "globals.h"
+
+/*
+ * Dircache and indexes
+ * ====================
+ * The maximum dircache size is:
+ * max(DEFAULT_MAX_DIRCACHE_SIZE, min(size, MAX_POSSIBLE_DIRCACHE_SIZE)).
+ * It is a hashtable which we use to store "struct dir"s in. If the cache get full, oldest
+ * entries are evicted in chunks of DIRCACHE_FREE.
+ * We have/need two indexes:
+ * - a DID/name index on the main dircache, another hashtable
+ * - a queue index on the dircache, for evicting the oldest entries
+ * The cache supports locking of struct dir elements through the DIRF_CACHELOCK flag. A dir
+ * locked this way wont ever be removed from the cache, so be careful.
+ *
+ * Sending SIGHUP to a afpd child causes it to dump the dircache to a file
+ * "/tmp/dircache.PID".
+ */
+
+/********************************************************
+ * Local funcs and variables
+ ********************************************************/
+
+/*****************************
+ * THE dircache */
+
+static hash_t *dircache; /* The actual cache */
+static unsigned int dircache_maxsize; /* cache maximum size */
+
+/* FNV 1a */
+static hash_val_t hash_vid_did(const void *key)
+{
+ const struct dir *k = (const struct dir *)key;
+ hash_val_t hash = 2166136261;
+
+ hash ^= k->d_vid >> 8;
+ hash *= 16777619;
+ hash ^= k->d_vid;
+ hash *= 16777619;
+
+ hash ^= k->d_did >> 24;
+ hash *= 16777619;
+ hash ^= (k->d_did >> 16) & 0xff;
+ hash *= 16777619;
+ hash ^= (k->d_did >> 8) & 0xff;
+ hash *= 16777619;
+ hash ^= (k->d_did >> 0) & 0xff;
+ hash *= 16777619;
+
+ return hash;
+}
+
+static int hash_comp_vid_did(const void *key1, const void *key2)
+{
+ const struct dir *k1 = key1;
+ const struct dir *k2 = key2;
+
+ return !(k1->d_did == k2->d_did && k1->d_vid == k2->d_vid);
+}
+
+/**************************************************
+ * DID/name index on dircache (another hashtable) */
+
+static hash_t *index_didname;
+
+#undef get16bits
+#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
+ || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
+#define get16bits(d) (*((const uint16_t *) (d)))
+#endif
+
+#if !defined (get16bits)
+#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \
+ +(uint32_t)(((const uint8_t *)(d))[0]) )
+#endif
+
+static hash_val_t hash_didname(const void *p)
+{
+ const struct dir *key = (const struct dir *)p;
+ const unsigned char *data = key->d_u_name->data;
+ int len = key->d_u_name->slen;
+ hash_val_t hash = key->d_pdid + key->d_vid;
+ hash_val_t tmp;
+
+ int rem = len & 3;
+ len >>= 2;
+
+ /* Main loop */
+ for (;len > 0; len--) {
+ hash += get16bits (data);
+ tmp = (get16bits (data+2) << 11) ^ hash;
+ hash = (hash << 16) ^ tmp;
+ data += 2*sizeof (uint16_t);
+ hash += hash >> 11;
+ }
+
+ /* Handle end cases */
+ switch (rem) {
+ case 3: hash += get16bits (data);
+ hash ^= hash << 16;
+ hash ^= data[sizeof (uint16_t)] << 18;
+ hash += hash >> 11;
+ break;
+ case 2: hash += get16bits (data);
+ hash ^= hash << 11;
+ hash += hash >> 17;
+ break;
+ case 1: hash += *data;
+ hash ^= hash << 10;
+ hash += hash >> 1;
+ }
+
+ /* Force "avalanching" of final 127 bits */
+ hash ^= hash << 3;
+ hash += hash >> 5;
+ hash ^= hash << 4;
+ hash += hash >> 17;
+ hash ^= hash << 25;
+ hash += hash >> 6;
+
+ return hash;
+}
+
+static int hash_comp_didname(const void *k1, const void *k2)
+{
+ const struct dir *key1 = (const struct dir *)k1;
+ const struct dir *key2 = (const struct dir *)k2;
+
+ return ! (key1->d_vid == key2->d_vid
+ && key1->d_pdid == key2->d_pdid
+ && (bstrcmp(key1->d_u_name, key2->d_u_name) == 0) );
+}
+
+/***************************
+ * queue index on dircache */
+
+static q_t *index_queue; /* the index itself */
+static unsigned int queue_count;
+static const int dircache_free_quantum = 256; /* number of entries to free */
+
+/*!
+ * @brief Remove a fixed number of (oldest) entries from the cache and indexes
+ *
+ * The default is to remove the 256 oldest entries from the cache.
+ * 1. Get the oldest entry
+ * 2. If it's in use ie open forks reference it or it's curdir requeue it,
+ * or it's locked (from catsearch) dont remove it
+ * 3. Remove the dir from the main cache and the didname index
+ * 4. Free the struct dir structure and all its members
+ */
+static void dircache_evict(void)
+{
+ int i = dircache_free_quantum;
+ struct dir *dir;
+
+ LOG(log_debug, logtype_afpd, "dircache: {starting cache eviction}");
+
+ while (i--) {
+ if ((dir = (struct dir *)dequeue(index_queue)) == NULL) { /* 1 */
+ dircache_dump();
+ exit(EXITERR_SYS);
+ }
+ queue_count--;
+
+ if (curdir == dir
+ || dir->d_ofork
+ || (dir->d_flags & DIRF_CACHELOCK)) { /* 2 */
+ if ((dir->qidx_node = enqueue(index_queue, dir)) == NULL) {
+ dircache_dump();
+ exit(EXITERR_SYS);
+ }
+ queue_count++;
+ continue;
+ }
+
+ dircache_remove(NULL, dir, DIRCACHE | DIDNAME_INDEX); /* 3 */
+ dir_free(dir); /* 4 */
+ }
+
+ AFP_ASSERT(queue_count == dircache->hash_nodecount);
+
+ LOG(log_debug, logtype_afpd, "dircache: {finished cache eviction}");
+}
+
+
+/********************************************************
+ * Interface
+ ********************************************************/
+
+/*!
+ * @brief Search the dircache via a DID
+ *
+ * @param vol (r) pointer to struct vol
+ * @param did (r) CNID of the directory
+ *
+ * @returns Pointer to struct dir if found, else NULL
+ */
+struct dir *dircache_search_by_did(const struct vol *vol, cnid_t did)
+{
+ struct dir *cdir = NULL;
+ struct dir key;
+ hnode_t *hn;
+
+ AFP_ASSERT(vol);
+ AFP_ASSERT(ntohl(did) >= CNID_START);
+
+ key.d_vid = vol->v_vid;
+ key.d_did = did;
+ if ((hn = hash_lookup(dircache, &key)))
+ cdir = hnode_get(hn);
+
+ if (cdir)
+ LOG(log_debug, logtype_afpd, "dircache(did:%u): {cached: path:'%s'}", ntohl(did), cfrombstring(cdir->d_fullpath));
+ else
+ LOG(log_debug, logtype_afpd, "dircache(did:%u): {not in cache}", ntohl(did));
+
+ return cdir;
+}
+
+/*!
+ * @brief Search the cache via did/name hashtable
+ *
+ * @param vol (r) volume
+ * @param dir (r) directory
+ * @param name (r) name (server side encoding)
+ * @parma len (r) strlen of name
+ *
+ * @returns pointer to struct dir if found in cache, else NULL
+ */
+struct dir *dircache_search_by_name(const struct vol *vol, const struct dir *dir, char *name, int len)
+{
+ struct dir *cdir = NULL;
+ struct dir key;
+ hnode_t *hn;
+ static_bstring uname = {-1, len, (unsigned char *)name};
+
+ AFP_ASSERT(vol);
+ AFP_ASSERT(dir);
+ AFP_ASSERT(name);
+ AFP_ASSERT(len == strlen(name));
+ AFP_ASSERT(len < 256);
+
+ if (dir->d_did != DIRDID_ROOT_PARENT) {
+ key.d_vid = vol->v_vid;
+ key.d_pdid = dir->d_did;
+ key.d_u_name = &uname;
+
+ if ((hn = hash_lookup(index_didname, &key)))
+ cdir = hnode_get(hn);
+ }
+
+ if (cdir)
+ LOG(log_debug, logtype_afpd, "dircache(pdid:%u, did:%u, '%s'): {found in cache}",
+ ntohl(dir->d_did), ntohl(cdir->d_did), cfrombstring(cdir->d_fullpath));
+ else
+ LOG(log_debug, logtype_afpd, "dircache(pdid:%u,'%s/%s'): {not in cache}",
+ ntohl(dir->d_did), cfrombstring(dir->d_fullpath), name);
+
+ return cdir;
+}
+
+/*!
+ * @brief create struct dir from struct path
+ *
+ * Add a struct dir to the cache and its indexes.
+ *
+ * @param dir (r) pointer to parrent directory
+ *
+ * @returns 0 on success, -1 on error which should result in an abort
+ */
+int dircache_add(struct dir *dir)
+{
+ AFP_ASSERT(dir);
+ AFP_ASSERT(ntohl(dir->d_pdid) >= 2);
+ AFP_ASSERT(ntohl(dir->d_did) >= CNID_START);
+ AFP_ASSERT(dir->d_fullpath);
+ AFP_ASSERT(dir->d_u_name);
+ AFP_ASSERT(dir->d_vid);
+ AFP_ASSERT(dircache->hash_nodecount <= dircache_maxsize);
+
+ /* Check if cache is full */
+ if (dircache->hash_nodecount == dircache_maxsize)
+ dircache_evict();
+
+ /* Add it to the main dircache */
+ if (hash_alloc_insert(dircache, dir, dir) == 0) {
+ dircache_dump();
+ exit(EXITERR_SYS);
+ }
+
+ /* Add it to the did/name index */
+ if (hash_alloc_insert(index_didname, dir, dir) == 0) {
+ dircache_dump();
+ exit(EXITERR_SYS);
+ }
+
+ /* Add it to the fifo queue index */
+ if ((dir->qidx_node = enqueue(index_queue, dir)) == NULL) {
+ dircache_dump();
+ exit(EXITERR_SYS);
+ } else {
+ queue_count++;
+ }
+
+ LOG(log_debug, logtype_afpd, "dircache(did:%u,'%s'): {added}", ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
+
+ AFP_ASSERT(queue_count == index_didname->hash_nodecount
+ && queue_count == dircache->hash_nodecount);
+
+ return 0;
+}
+
+/*!
+ * @brief Remove an entry from the dircache
+ *
+ * Callers outside of dircache.c should call this with
+ * flags = QUEUE_INDEX | DIDNAME_INDEX | DIRCACHE.
+ */
+void dircache_remove(const struct vol *vol _U_, struct dir *dir, int flags)
+{
+ hnode_t *hn;
+
+ AFP_ASSERT(dir);
+ AFP_ASSERT((flags & ~(QUEUE_INDEX | DIDNAME_INDEX | DIRCACHE)) == 0);
+
+ if (dir->d_flags & DIRF_CACHELOCK)
+ return;
+
+ if (flags & QUEUE_INDEX) {
+ /* remove it from the queue index */
+ dequeue(dir->qidx_node->prev); /* this effectively deletes the dequeued node */
+ queue_count--;
+ }
+
+ if (flags & DIDNAME_INDEX) {
+ if ((hn = hash_lookup(index_didname, dir)) == NULL) {
+ LOG(log_error, logtype_default, "dircache_remove(%u,%s): not in didname index",
+ ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
+ dircache_dump();
+ exit(EXITERR_SYS);
+ }
+ hash_delete(index_didname, hn);
+ }
+
+ if (flags & DIRCACHE) {
+ if ((hn = hash_lookup(dircache, dir)) == NULL) {
+ LOG(log_error, logtype_default, "dircache_remove(%u,%s): not in dircache",
+ ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
+ dircache_dump();
+ exit(EXITERR_SYS);
+ }
+ hash_delete(dircache, hn);
+ }
+
+ LOG(log_debug, logtype_afpd, "dircache(did:%u,'%s'): {removed}", ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
+
+ AFP_ASSERT(queue_count == index_didname->hash_nodecount
+ && queue_count == dircache->hash_nodecount);
+}
+
+/*!
+ * @brief Initialize the dircache and indexes
+ *
+ * This is called in child afpd initialisation. The maximum cache size will be
+ * max(DEFAULT_MAX_DIRCACHE_SIZE, min(size, MAX_POSSIBLE_DIRCACHE_SIZE)).
+ * It initializes a hashtable which we use to store a directory cache in.
+ * It also initializes two indexes:
+ * - a DID/name index on the main dircache
+ * - a queue index on the dircache
+ *
+ * @param size (r) requested maximum size from afpd.conf
+ *
+ * @return 0 on success, -1 on error
+ */
+int dircache_init(int reqsize)
+{
+ dircache_maxsize = DEFAULT_MAX_DIRCACHE_SIZE;
+
+ /* Initialize the main dircache */
+ if (reqsize > DEFAULT_MAX_DIRCACHE_SIZE && reqsize < MAX_POSSIBLE_DIRCACHE_SIZE) {
+ while ((dircache_maxsize < MAX_POSSIBLE_DIRCACHE_SIZE) && (dircache_maxsize < reqsize))
+ dircache_maxsize *= 2;
+ }
+ if ((dircache = hash_create(dircache_maxsize, hash_comp_vid_did, hash_vid_did)) == NULL)
+ return -1;
+
+ LOG(log_debug, logtype_afpd, "dircache_init: done. max dircache size: %u", dircache_maxsize);
+
+ /* Initialize did/name index hashtable */
+ if ((index_didname = hash_create(dircache_maxsize, hash_comp_didname, hash_didname)) == NULL)
+ return -1;
+
+ /* Initialize index queue */
+ if ((index_queue = queue_init()) == NULL)
+ return -1;
+ else
+ queue_count = 0;
+
+ /* As long as directory.c hasn't got its own initializer call, we do it for it */
+ rootParent.d_did = DIRDID_ROOT_PARENT;
+ rootParent.d_fullpath = bfromcstr("ROOT_PARENT");
+ rootParent.d_m_name = bfromcstr("ROOT_PARENT");
+ rootParent.d_u_name = rootParent.d_m_name;
+
+ return 0;
+}
+
+/*!
+ * @brief Dump dircache to /tmp/dircache.PID
+ */
+void dircache_dump(void)
+{
+ char tmpnam[64];
+ FILE *dump;
+ qnode_t *n = index_queue->next;
+ const struct dir *dir;
+
+ LOG(log_warning, logtype_afpd, "Dumping directory cache...");
+
+ sprintf(tmpnam, "/tmp/dircache.%u", getpid());
+ if ((dump = fopen(tmpnam, "w+")) == NULL) {
+ LOG(log_error, logtype_afpd, "dircache_dump: %s", strerror(errno));
+ return;
+ }
+ setbuf(dump, NULL);
+
+ fprintf(dump, "Number of cache entries: %u\n", queue_count);
+ fprintf(dump, "Configured maximum cache size: %u\n", dircache_maxsize);
+ fprintf(dump, "==================================================\n\n");
+
+ for (int i = 1; i <= queue_count; i++) {
+ if (n == index_queue)
+ break;
+ dir = (struct dir *)n->data;
+ fprintf(dump, "%05u: vid:%u, pdid:%6u, did:%6u, path:%s, locked:%3s, oforks:%s\n",
+ i, ntohs(dir->d_vid), ntohl(dir->d_pdid), ntohl(dir->d_did), cfrombstring(dir->d_fullpath),
+ (dir->d_flags & DIRF_CACHELOCK) ? "yes" : "no",
+ dir->d_ofork ? "yes" : "no");
+ n = n->next;
+ }
+
+ fprintf(dump, "\n");
+ return;
+}
--- /dev/null
+/*
+ $Id: dircache.h,v 1.1.2.5 2010-02-11 14:13:06 franklahm Exp $
+ Copyright (c) 2010 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 DIRCACHE_H
+#define DIRCACHE_H
+
+#include <atalk/volume.h>
+#include <atalk/directory.h>
+
+/* Maximum size of the dircache hashtable */
+#define DEFAULT_MAX_DIRCACHE_SIZE 8192
+#define MAX_POSSIBLE_DIRCACHE_SIZE 131072
+
+/* flags for dircache_remove */
+#define DIRCACHE (1 << 0)
+#define DIDNAME_INDEX (1 << 1)
+#define QUEUE_INDEX (1 << 2)
+
+extern int dircache_init(int reqsize);
+extern int dircache_add(struct dir *);
+extern void dircache_remove(const struct vol *, struct dir *, int flag);
+extern struct dir *dircache_search_by_did(const struct vol *vol, cnid_t did);
+extern struct dir *dircache_search_by_name(const struct vol *, const struct dir *dir, char *name, int len);
+extern void dircache_dump(void);
+
+#endif /* DIRCACHE_H */
/*
- * $Id: directory.c,v 1.140 2010-03-12 15:16:49 franklahm Exp $
+ * $Id: directory.c,v 1.140 2010/03/12 15:16:49 franklahm Exp $
*
* Copyright (c) 1990,1993 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
- *
- * 19 jan 2000 implemented red-black trees for directory lookups
- * (asun@cobalt.com).
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_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 <stdio.h>
#include <stdlib.h>
-
#include <grp.h>
#include <pwd.h>
#include <sys/param.h>
+#include <sys/stat.h>
#include <errno.h>
#include <utime.h>
+#include <assert.h>
#include <atalk/adouble.h>
#include <atalk/vfs.h>
#include <atalk/logger.h>
#include <atalk/uuid.h>
#include <atalk/unix.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
#include "directory.h"
+#include "dircache.h"
#include "desktop.h"
#include "volume.h"
#include "fork.h"
extern void addir_inherit_acl(const struct vol *vol);
#endif
-/*
- * Directory caches
- * ================
- *
- * There are currently two cache structures where afpd caches directory information
- * a) a DID/dirname cache in a hashtable
- * b) a (red-black) tree with CNIDs as key
- *
- * a) is for searching by DID/dirname
- * b) is for searching by CNID
- *
- * Through additional parent, child, previous and next pointers, b) is also used to
- * represent the on-disk layout of the filesystem. parent and child point to parent
- * and child directory respectively, linking 2 or more subdirectories in one
- * directory with previous and next pointers.
- *
- * Usage examples, highlighting the main functions:
- *
- * a) is eg used in enumerate():
- * if IS_DIR
- * dir = dirsearch_byname() // search in cache
- * if (dir == NULL) // not found
- * dir = adddir() // add to cache
- * getdirparams()
- *
- * b) is eg used in afp_getfildirparams()
- * dirlookup() // wrapper for cache and db search
- * => dir = dirsearch() // search in cache
- * if (dir) // found
- * return
- * else // not found,
- * cnid_resolve() // resolve with CNID database
- * cname() // add to cache
+/*
+ * FIXMEs, loose ends after the dircache rewrite:
+ * o merge dircache_search_by_name and dir_add ??
+ * o case-insensitivity is gone from cname
*/
-struct dir *curdir;
+
+/*******************************************************************************************
+ * Globals
+ ******************************************************************************************/
+
int afp_errno;
+struct dir rootParent = {
+ NULL, NULL, NULL, NULL, /* path, d_m_name, d_u_name, d_m_name_ucs2 */
+ NULL, NULL, 0, 0, /* qidx_node, d_ofork, ctime, d_flags */
+ 0, 0, 0, 0 /* pdid, did, offcnt, d_vid */
+};
+struct dir *curdir = &rootParent;
+struct path Cur_Path = {
+ 0,
+ "", /* mac name */
+ ".", /* unix name */
+ 0, /* id */
+ NULL,/* struct dir * */
+ 0, /* stat is not set */
+ 0, /* errno */
+ {0} /* struct stat */
+};
-#define SENTINEL (&sentinel)
-static struct dir sentinel = { SENTINEL, SENTINEL, NULL, /* left, right, back */
- DIRTREE_COLOR_BLACK, /* color */
- NULL, NULL, /* parent, child */
- NULL, NULL, /* previous, next */
- NULL, 0, 0, /* oforks, did, flags */
- 0, 0, /* ctime, offcnt */
- NULL, NULL, NULL}; /* mname, uname, ucs2-name */
-static struct dir rootpar = { SENTINEL, SENTINEL, NULL,
- 0,
- NULL, NULL,
- NULL, NULL,
- NULL, 0, 0,
- 0, 0,
- NULL, NULL, NULL};
-
-/* (from IM: Toolbox Essentials)
- * dirFinderInfo (DInfo) fields:
- * field bytes
- * frRect 8 folder's window rectangle
- * frFlags 2 flags
- * frLocation 4 folder's location in window
- * frView 2 folder's view (default == closedView (256))
- *
- * extended dirFinderInfo (DXInfo) fields:
- * frScroll 4 scroll position
- * frOpenChain: 4 directory ID chain of open folders
- * frScript: 1 script flag and code
- * frXFlags: 1 reserved
- * frComment: 2 comment ID
- * frPutAway: 4 home directory ID
- */
-static struct dir *
-vol_tree_root(const struct vol *vol, u_int32_t did)
-{
- struct dir *dir;
+/*******************************************************************************************
+ * Locals
+ ******************************************************************************************/
- if (vol->v_curdir && vol->v_curdir->d_did == did) {
- dir = vol->v_curdir;
- }
- else {
- dir = vol->v_root;
+
+/* -------------------------
+ appledouble mkdir afp error code.
+*/
+static int netatalk_mkdir(const char *name)
+{
+ if (ad_mkdir(name, DIRBITS | 0777) < 0) {
+ switch ( errno ) {
+ case ENOENT :
+ return( AFPERR_NOOBJ );
+ case EROFS :
+ return( AFPERR_VLOCK );
+ case EPERM:
+ case EACCES :
+ return( AFPERR_ACCESS );
+ case EEXIST :
+ return( AFPERR_EXIST );
+ case ENOSPC :
+ case EDQUOT :
+ return( AFPERR_DFULL );
+ default :
+ return( AFPERR_PARAM );
+ }
}
- return dir;
+ return AFP_OK;
}
-/*
- * redid did assignment for directories. now we use red-black trees.
- * how exciting.
- */
-struct dir *
-dirsearch(const struct vol *vol, u_int32_t did)
+/* ------------------- */
+static int deletedir(int dirfd, char *dir)
{
- struct dir *dir;
+ char path[MAXPATHLEN + 1];
+ DIR *dp;
+ struct dirent *de;
+ struct stat st;
+ size_t len;
+ int err = AFP_OK;
+ size_t remain;
+ if ((len = strlen(dir)) +2 > sizeof(path))
+ return AFPERR_PARAM;
- /* check for 0 did */
- if (!did) {
- afp_errno = AFPERR_PARAM;
- return NULL;
- }
- if ( did == DIRDID_ROOT_PARENT ) {
- if (!rootpar.d_did)
- rootpar.d_did = DIRDID_ROOT_PARENT;
- rootpar.d_child = vol->v_dir;
- return( &rootpar );
- }
+ /* already gone */
+ if ((dp = opendirat(dirfd, dir)) == NULL)
+ return AFP_OK;
- dir = vol_tree_root(vol, did);
+ strcpy(path, dir);
+ strcat(path, "/");
+ len++;
+ remain = sizeof(path) -len -1;
+ while ((de = readdir(dp)) && err == AFP_OK) {
+ /* skip this and previous directory */
+ if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
+ continue;
- afp_errno = AFPERR_NOOBJ;
- while ( dir != SENTINEL ) {
- if (dir->d_did == did)
- return dir->d_m_name ? dir : NULL;
- dir = (dir->d_did > did) ? dir->d_left : dir->d_right;
+ if (strlen(de->d_name) > remain) {
+ err = AFPERR_PARAM;
+ break;
+ }
+ strcpy(path + len, de->d_name);
+ if (lstatat(dirfd, path, &st)) {
+ continue;
+ }
+ if (S_ISDIR(st.st_mode)) {
+ err = deletedir(dirfd, path);
+ } else {
+ err = netatalk_unlinkat(dirfd, path);
+ }
}
- return NULL;
-}
+ closedir(dp);
-/* ------------------- */
-int get_afp_errno(const int param)
-{
- if (afp_errno != AFPERR_DID1)
- return afp_errno;
- return param;
+ /* okay. the directory is empty. delete it. note: we already got rid
+ of .AppleDouble. */
+ if (err == AFP_OK) {
+ err = netatalk_rmdir(dirfd, dir);
+ }
+ return err;
}
-/* ------------------- */
-struct dir *
-dirsearch_byname( const struct vol *vol, struct dir *cdir, char *name)
+/* do a recursive copy. */
+static int copydir(const struct vol *vol, int dirfd, char *src, char *dst)
{
- struct dir *dir = NULL;
+ char spath[MAXPATHLEN + 1], dpath[MAXPATHLEN + 1];
+ DIR *dp;
+ struct dirent *de;
+ struct stat st;
+ struct utimbuf ut;
+ size_t slen, dlen;
+ size_t srem, drem;
+ int err;
- if ((cdir->d_did != DIRDID_ROOT_PARENT) && (cdir->d_child)) {
- struct dir key;
- hnode_t *hn;
+ /* doesn't exist or the path is too long. */
+ if (((slen = strlen(src)) > sizeof(spath) - 2) ||
+ ((dlen = strlen(dst)) > sizeof(dpath) - 2) ||
+ ((dp = opendirat(dirfd, src)) == NULL))
+ return AFPERR_PARAM;
- key.d_parent = cdir;
- key.d_u_name = name;
- hn = hash_lookup(vol->v_hash, &key);
- if (hn) {
- dir = hnode_get(hn);
- }
+ /* try to create the destination directory */
+ if (AFP_OK != (err = netatalk_mkdir(dst)) ) {
+ closedir(dp);
+ return err;
}
- return dir;
-}
-/* -----------------------------------------
- * if did is not in the cache resolve it with cnid
- *
- * FIXME
- * OSX call it with bogus id, ie file ID not folder ID,
- * and we are really bad in this case.
- */
-struct dir *
-dirlookup( struct vol *vol, u_int32_t did)
-{
- struct dir *ret;
- char *upath;
- cnid_t id, cnid;
- static char path[MAXPATHLEN + 1];
- size_t len, pathlen;
- char *ptr;
- static char buffer[12 + MAXPATHLEN + 1];
- int buflen = 12 + MAXPATHLEN + 1;
- char *mpath;
- int utf8;
- size_t maxpath;
+ /* set things up to copy */
+ strcpy(spath, src);
+ strcat(spath, "/");
+ slen++;
+ srem = sizeof(spath) - slen -1;
- ret = dirsearch(vol, did);
- if (ret != NULL || afp_errno == AFPERR_PARAM)
- return ret;
+ strcpy(dpath, dst);
+ strcat(dpath, "/");
+ dlen++;
+ drem = sizeof(dpath) - dlen -1;
- utf8 = utf8_encoding();
- maxpath = (utf8)?MAXPATHLEN -7:255;
- id = did;
- if (NULL == (upath = cnid_resolve(vol->v_cdb, &id, buffer, buflen)) ) {
- afp_errno = AFPERR_NOOBJ;
- return NULL;
- }
- ptr = path + MAXPATHLEN;
- if (NULL == ( mpath = utompath(vol, upath, did, utf8) ) ) {
- afp_errno = AFPERR_NOOBJ;
- return NULL;
- }
- len = strlen(mpath);
- pathlen = len; /* no 0 in the last part */
- len++;
- strcpy(ptr - len, mpath);
- ptr -= len;
- while (1) {
- ret = dirsearch(vol,id);
- if (ret != NULL) {
- break;
- }
- cnid = id;
- if ( NULL == (upath = cnid_resolve(vol->v_cdb, &id, buffer, buflen))
- ||
- NULL == (mpath = utompath(vol, upath, cnid, utf8))
- ) {
- afp_errno = AFPERR_NOOBJ;
- return NULL;
- }
+ err = AFP_OK;
+ while ((de = readdir(dp))) {
+ /* skip this and previous directory */
+ if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
+ continue;
- len = strlen(mpath) + 1;
- pathlen += len;
- if (pathlen > maxpath) {
- afp_errno = AFPERR_PARAM;
- return NULL;
+ if (strlen(de->d_name) > srem) {
+ err = AFPERR_PARAM;
+ break;
}
- strcpy(ptr - len, mpath);
- ptr -= len;
- }
+ strcpy(spath + slen, de->d_name);
- /* fill the cache, another place where we know about the path type */
- if (utf8) {
- u_int16_t temp16;
- u_int32_t temp;
+ if (lstatat(dirfd, spath, &st) == 0) {
+ if (strlen(de->d_name) > drem) {
+ err = AFPERR_PARAM;
+ break;
+ }
+ strcpy(dpath + dlen, de->d_name);
- ptr -= 2;
- temp16 = htons(pathlen);
- memcpy(ptr, &temp16, sizeof(temp16));
+ if (S_ISDIR(st.st_mode)) {
+ if (AFP_OK != (err = copydir(vol, dirfd, spath, dpath)))
+ goto copydir_done;
+ } else if (AFP_OK != (err = copyfile(vol, vol, dirfd, spath, dpath, NULL, NULL))) {
+ goto copydir_done;
- temp = htonl(kTextEncodingUTF8);
- ptr -= 4;
- memcpy(ptr, &temp, sizeof(temp));
- ptr--;
- *ptr = 3;
+ } else {
+ /* keep the same time stamp. */
+ ut.actime = ut.modtime = st.st_mtime;
+ utime(dpath, &ut);
+ }
+ }
}
- else {
- ptr--;
- *ptr = (unsigned char)pathlen;
- ptr--;
- *ptr = 2;
+
+ /* keep the same time stamp. */
+ if (lstatat(dirfd, src, &st) == 0) {
+ ut.actime = ut.modtime = st.st_mtime;
+ utime(dst, &ut);
}
- /* cname is not efficient */
- if (cname( vol, ret, &ptr ) == NULL )
- return NULL;
- return dirsearch(vol, did);
+copydir_done:
+ closedir(dp);
+ return err;
}
-/* child addition/removal */
-static void dirchildadd(const struct vol *vol, struct dir *a, struct dir *b)
+/* ---------------------
+ * is our cached offspring count valid?
+ */
+static int diroffcnt(struct dir *dir, struct stat *st)
{
- if (!a->d_child)
- a->d_child = b;
- else {
- b->d_next = a->d_child;
- b->d_prev = b->d_next->d_prev;
- b->d_next->d_prev = b;
- b->d_prev->d_next = b;
- }
- if (!hash_alloc_insert(vol->v_hash, b, b)) {
- LOG(log_error, logtype_afpd, "dirchildadd: can't hash %s", b->d_u_name);
- }
+ return st->st_ctime == dir->ctime;
}
-static void dirchildremove(struct dir *a,struct dir *b)
+/* --------------------- */
+static int invisible_dots(const struct vol *vol, const char *name)
{
- if (a->d_child == b)
- a->d_child = (b == b->d_next) ? NULL : b->d_next;
- b->d_next->d_prev = b->d_prev;
- b->d_prev->d_next = b->d_next;
- b->d_next = b->d_prev = b;
+ return vol_inv_dots(vol) && *name == '.' && strcmp(name, ".") && strcmp(name, "..");
}
-/* --------------------------- */
-/* rotate the tree to the left */
-static void dir_leftrotate(struct vol *vol, struct dir *dir)
+/* ------------------ */
+static int set_dir_errors(struct path *path, const char *where, int err)
{
- struct dir *right = dir->d_right;
-
- /* whee. move the right's left tree into dir's right tree */
- dir->d_right = right->d_left;
- if (right->d_left != SENTINEL)
- right->d_left->d_back = dir;
-
- if (right != SENTINEL) {
- right->d_back = dir->d_back;
- right->d_left = dir;
+ switch ( err ) {
+ case EPERM :
+ case EACCES :
+ return AFPERR_ACCESS;
+ case EROFS :
+ return AFPERR_VLOCK;
}
+ LOG(log_error, logtype_afpd, "setdirparam(%s): %s: %s", fullpathname(path->u_name), where, strerror(err) );
+ return AFPERR_PARAM;
+}
- if (!dir->d_back) /* no parent. move the right tree to the top. */
- vol->v_root = right;
- else if (dir == dir->d_back->d_left) /* we were on the left */
- dir->d_back->d_left = right;
- else
- dir->d_back->d_right = right; /* we were on the right */
+/*!
+ * @brief Convert name in client encoding to server encoding
+ *
+ * Convert ret->m_name to ret->u_name from client encoding to server encoding.
+ * This only gets called from cname().
+ *
+ * @returns 0 on success, -1 on error
+ *
+ * @note If the passed ret->m_name is mangled, we'll demangle it
+ */
+static int cname_mtouname(const struct vol *vol, const struct dir *dir, struct path *ret, int toUTF8)
+{
+ static char temp[ MAXPATHLEN + 1];
+ char *t;
+ cnid_t fileid;
+
+ if (afp_version >= 30) {
+ if (toUTF8) {
+ if (dir->d_did == DIRDID_ROOT_PARENT) {
+ /*
+ * With uft8 volume name is utf8-mac, but requested path may be a mangled longname. See #2611981.
+ * So we compare it with the longname from the current volume and if they match
+ * we overwrite the requested path with the utf8 volume name so that the following
+ * strcmp can match.
+ */
+ ucs2_to_charset(vol->v_maccharset, vol->v_macname, temp, AFPVOL_MACNAMELEN + 1);
+ if (strcasecmp(ret->m_name, temp) == 0)
+ ucs2_to_charset(CH_UTF8_MAC, vol->v_u8mname, ret->m_name, AFPVOL_U8MNAMELEN);
+ } else {
+ /* toUTF8 */
+ if (mtoUTF8(vol, ret->m_name, strlen(ret->m_name), temp, MAXPATHLEN) == (size_t)-1) {
+ afp_errno = AFPERR_PARAM;
+ return -1;
+ }
+ strcpy(ret->m_name, temp);
+ }
+ }
- /* re-insert dir on the left tree */
- if (dir != SENTINEL)
- dir->d_back = right;
-}
+ /* check for OS X mangled filename :( */
+ t = demangle_osx(vol, ret->m_name, dir->d_did, &fileid);
+ LOG(log_maxdebug, logtype_afpd, "cname_mtouname('%s',did:%u) {demangled:'%s', fileid:%u}",
+ ret->m_name, ntohl(dir->d_did), t, ntohl(fileid));
+
+ if (t != ret->m_name) {
+ ret->u_name = t;
+ /* 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())) ) {
+ /* at last got our view of mac name */
+ strcpy(ret->m_name, t);
+ }
+ }
+ } /* afp_version >= 30 */
+ /* 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) {
+ afp_errno = AFPERR_PARAM;
+ return -1;
+ }
+ }
+ return 0;
+}
-/* rotate the tree to the right */
-static void dir_rightrotate(struct vol *vol, struct dir *dir)
+/*!
+ * @brief Build struct path from struct dir
+ *
+ * The final movecwd in cname failed, possibly with EPERM or ENOENT. We:
+ * 1. move cwd into parent dir (we're often already there, but not always)
+ * 2. set struct path to the dirname
+ * 3. in case of
+ * AFPERR_ACCESS: the dir is there, we just cant chdir into it
+ * AFPERR_NOOBJ: the dir was there when we stated it in cname, so we have a race
+ * 4. indicate there's no dir for this path
+ * 5. remove the dir
+ */
+static struct path *path_from_dir(struct vol *vol, struct dir *dir, struct path *ret)
{
- struct dir *left = dir->d_left;
+ if (dir->d_did == DIRDID_ROOT_PARENT || dir->d_did == DIRDID_ROOT)
+ return NULL;
- /* whee. move the left's right tree into dir's left tree */
- dir->d_left = left->d_right;
- if (left->d_right != SENTINEL)
- left->d_right->d_back = dir;
+ switch (afp_errno) {
- if (left != SENTINEL) {
- left->d_back = dir->d_back;
- left->d_right = dir;
- }
+ case AFPERR_ACCESS:
+ if (movecwd( vol, dirlookup(vol, dir->d_pdid)) < 0 ) /* 1 */
+ return NULL;
- if (!dir->d_back) /* no parent. move the left tree to the top. */
- vol->v_root = left;
- else if (dir == dir->d_back->d_right) /* we were on the right */
- dir->d_back->d_right = left;
- else
- dir->d_back->d_left = left; /* we were on the left */
+ memcpy(ret->m_name, cfrombstring(dir->d_m_name), blength(dir->d_m_name) + 1); /* 3 */
+ if (dir->d_m_name == dir->d_u_name) {
+ ret->u_name = ret->m_name;
+ } else {
+ ret->u_name = ret->m_name + blength(dir->d_m_name) + 1;
+ memcpy(ret->u_name, cfrombstring(dir->d_u_name), blength(dir->d_u_name) + 1);
+ }
- /* re-insert dir on the right tree */
- if (dir != SENTINEL)
- dir->d_back = left;
-}
+ ret->d_dir = dir;
-#if 0
-/* recolor after a removal */
-static struct dir *dir_rmrecolor(struct vol *vol, struct dir *dir)
-{
- struct dir *leaf;
-
- while ((dir != vol->v_root) && (dir->d_color == DIRTREE_COLOR_BLACK)) {
- /* are we on the left tree? */
- if (dir == dir->d_back->d_left) {
- leaf = dir->d_back->d_right; /* get right side */
- if (leaf->d_color == DIRTREE_COLOR_RED) {
- /* we're red. we need to change to black. */
- leaf->d_color = DIRTREE_COLOR_BLACK;
- dir->d_back->d_color = DIRTREE_COLOR_RED;
- dir_leftrotate(vol, dir->d_back);
- leaf = dir->d_back->d_right;
- }
+ LOG(log_debug, logtype_afpd, "cname('%s') {path-from-dir: AFPERR_ACCESS. curdir:'%s', path:'%s'}",
+ cfrombstring(dir->d_fullpath),
+ cfrombstring(curdir->d_fullpath),
+ ret->u_name);
- /* right leaf has black end nodes */
- if ((leaf->d_left->d_color == DIRTREE_COLOR_BLACK) &&
- (leaf->d_right->d_color = DIRTREE_COLOR_BLACK)) {
- leaf->d_color = DIRTREE_COLOR_RED; /* recolor leaf as red */
- dir = dir->d_back; /* ascend */
- } else {
- if (leaf->d_right->d_color == DIRTREE_COLOR_BLACK) {
- leaf->d_left->d_color = DIRTREE_COLOR_BLACK;
- leaf->d_color = DIRTREE_COLOR_RED;
- dir_rightrotate(vol, leaf);
- leaf = dir->d_back->d_right;
- }
- leaf->d_color = dir->d_back->d_color;
- dir->d_back->d_color = DIRTREE_COLOR_BLACK;
- leaf->d_right->d_color = DIRTREE_COLOR_BLACK;
- dir_leftrotate(vol, dir->d_back);
- dir = vol->v_root;
- }
- } else { /* right tree */
- leaf = dir->d_back->d_left; /* left tree */
- if (leaf->d_color == DIRTREE_COLOR_RED) {
- leaf->d_color = DIRTREE_COLOR_BLACK;
- dir->d_back->d_color = DIRTREE_COLOR_RED;
- dir_rightrotate(vol, dir->d_back);
- leaf = dir->d_back->d_left;
- }
+ return ret;
- /* left leaf has black end nodes */
- if ((leaf->d_right->d_color == DIRTREE_COLOR_BLACK) &&
- (leaf->d_left->d_color = DIRTREE_COLOR_BLACK)) {
- leaf->d_color = DIRTREE_COLOR_RED; /* recolor leaf as red */
- dir = dir->d_back; /* ascend */
- } else {
- if (leaf->d_left->d_color == DIRTREE_COLOR_BLACK) {
- leaf->d_right->d_color = DIRTREE_COLOR_BLACK;
- leaf->d_color = DIRTREE_COLOR_RED;
- dir_leftrotate(vol, leaf);
- leaf = dir->d_back->d_left;
- }
- leaf->d_color = dir->d_back->d_color;
- dir->d_back->d_color = DIRTREE_COLOR_BLACK;
- leaf->d_left->d_color = DIRTREE_COLOR_BLACK;
- dir_rightrotate(vol, dir->d_back);
- dir = vol->v_root;
- }
+ case AFPERR_NOOBJ:
+ if (movecwd(vol, dirlookup(vol, dir->d_pdid)) < 0 ) /* 1 */
+ return NULL;
+
+ memcpy(ret->m_name, cfrombstring(dir->d_m_name), blength(dir->d_m_name) + 1);
+ if (dir->d_m_name == dir->d_u_name) {
+ ret->u_name = ret->m_name;
+ } else {
+ ret->u_name = ret->m_name + blength(dir->d_m_name) + 1;
+ memcpy(ret->u_name, cfrombstring(dir->d_u_name), blength(dir->d_u_name) + 1);
}
+
+ ret->d_dir = NULL; /* 4 */
+ dir_remove(vol, dir); /* 5 */
+ return ret;
+
+ default:
+ return NULL;
}
- dir->d_color = DIRTREE_COLOR_BLACK;
- return dir;
+ /* DEADC0DE: never get here */
+ return NULL;
}
-#endif /* 0 */
-/* --------------------- */
-static void dir_hash_del(const struct vol *vol, struct dir *dir)
-{
- hnode_t *hn;
- hn = hash_lookup(vol->v_hash, dir);
- if (!hn) {
- LOG(log_error, logtype_afpd, "dir_hash_del: %s not hashed", dir->d_u_name);
- }
- else {
- hash_delete(vol->v_hash, hn);
- }
+/*********************************************************************************************
+ * Interface
+ ********************************************************************************************/
+
+int get_afp_errno(const int param)
+{
+ if (afp_errno != AFPERR_DID1)
+ return afp_errno;
+ return param;
}
-/* remove the node from the tree. this is just like insertion, but
- * different. actually, it has to worry about a bunch of things that
- * insertion doesn't care about. */
+/*!
+ * @brief Resolve a DID
+ *
+ * Resolve a DID, allocate a struct dir for it
+ * 1. Check for special CNIDs 0 (invalid), 1 and 2.
+ * 2. Check if the DID is in the cache.
+ * 3. If it's not in the cache resolve it via the database.
+ * 4. Build complete server-side path to the dir.
+ * 5. Check if it exists and is a directory.
+ * 6. Create the struct dir and populate it.
+ * 7. Add it to the cache.
+ *
+ * @param vol (r) pointer to struct vol
+ * @param did (r) DID to resolve
+ *
+ * @returns pointer to struct dir
+ *
+ * @note FIXME: OSX calls it with bogus id, ie file ID not folder ID,
+ * and we are really bad in this case.
+ */
+struct dir *dirlookup(const struct vol *vol, cnid_t did)
+{
+ static char buffer[12 + MAXPATHLEN + 1];
+ struct stat st;
+ struct dir *ret = NULL, *pdir;
+ bstring fullpath = NULL;
+ char *upath = NULL, *mpath;
+ cnid_t cnid, pdid;
+ size_t maxpath;
+ int buflen = 12 + MAXPATHLEN + 1;
+ int utf8;
+ int err = 0;
+
+ LOG(log_debug, logtype_afpd, "dirlookup(did: %u) {start}", ntohl(did));
-static void dir_remove( struct vol *vol, struct dir *dir)
-{
-#ifdef REMOVE_NODES
- struct ofork *of, *last;
- struct dir *node, *leaf;
-#endif /* REMOVE_NODES */
-
- if (!dir || (dir == SENTINEL))
- return;
-
- /* i'm not sure if it really helps to delete stuff. */
- dir_hash_del(vol, dir);
- vol->v_curdir = NULL;
-#ifndef REMOVE_NODES
- dirfreename(dir);
- dir->d_m_name = NULL;
- dir->d_u_name = NULL;
- dir->d_m_name_ucs2 = NULL;
-#else /* ! REMOVE_NODES */
-
- /* go searching for a node with at most one child */
- if ((dir->d_left == SENTINEL) || (dir->d_right == SENTINEL)) {
- node = dir;
- } else {
- node = dir->d_right;
- while (node->d_left != SENTINEL)
- node = node->d_left;
+ /* check for did 0, 1 and 2 */
+ if (did == 0 || vol == NULL) { /* 1 */
+ afp_errno = AFPERR_PARAM;
+ return NULL;
+ } else if (did == DIRDID_ROOT_PARENT) {
+ rootParent.d_vid = vol->v_vid;
+ return (&rootParent);
+ } else if (did == DIRDID_ROOT) {
+ return vol->v_root;
+ }
+
+ /* Search the cache */
+ if ((ret = dircache_search_by_did(vol, did)) != NULL) { /* 2 */
+ if (lstat(cfrombstring(ret->d_fullpath), &st) != 0) {
+ LOG(log_debug, logtype_afpd, "dirlookup(did: %u) {lstat: %s}", ntohl(did), strerror(errno));
+ switch (errno) {
+ case ENOENT:
+ case ENOTDIR:
+ /* It's not there anymore, so remove it */
+ LOG(log_debug, logtype_afpd, "dirlookup(did: %u) {calling dir_remove()}", ntohl(did));
+ dir_remove(vol, ret);
+ afp_errno = AFPERR_NOOBJ;
+ return NULL;
+ default:
+ return ret;
+ }
+ /* DEADC0DE */
+ return NULL;
+ }
+ return ret;
}
- /* get that child */
- leaf = (node->d_left != SENTINEL) ? node->d_left : node->d_right;
+ utf8 = utf8_encoding();
+ maxpath = (utf8) ? MAXPATHLEN - 7 : 255;
- /* detach node */
- leaf->d_back = node->d_back;
- if (!node->d_back) {
- vol->v_root = leaf;
- } else if (node == node->d_back->d_left) { /* left tree */
- node->d_back->d_left = leaf;
- } else {
- node->d_back->d_right = leaf;
+ /* Get it from the database */
+ cnid = did;
+ if ( (upath = cnid_resolve(vol->v_cdb, &cnid, buffer, buflen)) == NULL
+ || (upath = strdup(upath)) == NULL) { /* 3 */
+ afp_errno = AFPERR_NOOBJ;
+ err = 1;
+ goto exit;
}
+ pdid = cnid;
- /* we want to free node, but we also want to free the data in dir.
- * currently, that's d_name and the directory traversal bits.
- * we just copy the necessary bits and then fix up all the
- * various pointers to the directory. needless to say, there are
- * a bunch of places that store the directory struct. */
- if (node != dir) {
- struct dir save, *tmp;
-
- memcpy(&save, dir, sizeof(save));
- memcpy(dir, node, sizeof(struct dir));
+ /*
+ * Recurse up the tree, terminates in dirlookup when either
+ * - DIRDID_ROOT is hit
+ * - a cached entry is found
+ */
+ if ((pdir = dirlookup(vol, pdid)) == NULL) {
+ err = 1;
+ goto exit;
+ }
- /* restore the red-black bits */
- dir->d_left = save.d_left;
- dir->d_right = save.d_right;
- dir->d_back = save.d_back;
- dir->d_color = save.d_color;
+ /* build the fullpath */
+ if ((fullpath = bstrcpy(pdir->d_fullpath)) == NULL
+ || bconchar(fullpath, '/') != BSTR_OK
+ || bcatcstr(fullpath, upath) != BSTR_OK) {
+ err = 1;
+ goto exit;
+ }
- if (node == vol->v_dir) {/* we may need to fix up this pointer */
- vol->v_dir = dir;
- rootpar.d_child = vol->v_dir;
- } else {
- /* if we aren't the root directory, we have parents and
- * siblings to worry about */
- if (dir->d_parent->d_child == node)
- dir->d_parent->d_child = dir;
- dir->d_next->d_prev = dir;
- dir->d_prev->d_next = dir;
- }
+ /* stat it and check if it's a dir */
+ LOG(log_debug, logtype_afpd, "dirlookup: {stating %s}", cfrombstring(fullpath));
- /* fix up children. */
- tmp = dir->d_child;
- while (tmp) {
- tmp->d_parent = dir;
- tmp = (tmp == dir->d_child->d_prev) ? NULL : tmp->d_next;
+ if (stat(cfrombstring(fullpath), &st) != 0) { /* 5a */
+ switch (errno) {
+ case ENOENT:
+ afp_errno = AFPERR_NOOBJ;
+ err = 1;
+ goto exit;
+ case EPERM:
+ afp_errno = AFPERR_ACCESS;
+ err = 1;
+ goto exit;
+ default:
+ afp_errno = AFPERR_MISC;
+ err = 1;
+ goto exit;
}
-
- if (node == curdir) /* another pointer to fixup */
- curdir = dir;
-
- /* we also need to fix up oforks. bleah */
- if ((of = dir->d_ofork)) {
- last = of->of_d_prev;
- while (of) {
- of->of_dir = dir;
- of = (last == of) ? NULL : of->of_d_next;
- }
+ } else {
+ if ( ! S_ISDIR(st.st_mode)) { /* 5b */
+ afp_errno = AFPERR_BADTYPE;
+ err = 1;
+ goto exit;
}
-
- /* set the node's d_name */
- node->d_m_name = save.d_m_name;
- node->d_u_name = save.d_u_name;
- node->d_m_name_ucs2 = save.d_m_name_ucs2;
}
- if (node->d_color == DIRTREE_COLOR_BLACK)
- dir_rmrecolor(vol, leaf);
+ /* Get macname from unix name */
+ if ( (mpath = utompath(vol, upath, did, utf8)) == NULL ) {
+ afp_errno = AFPERR_NOOBJ;
+ err = 1;
+ goto exit;
+ }
- if (node->d_m_name_ucs2)
- free(node->d_u_name_ucs2);
- if (node->d_u_name != node->d_m_name) {
- free(node->d_u_name);
+ /* Create struct dir */
+ if ((ret = dir_new(mpath, upath, vol, pdid, did, fullpath)) == NULL) { /* 6 */
+ LOG(log_error, logtype_afpd, "dirlookup(did: %u) {%s, %s}: %s", ntohl(did), mpath, upath, strerror(errno));
+ err = 1;
+ goto exit;
}
- free(node->d_m_name);
- free(node);
-#endif /* ! REMOVE_NODES */
-}
-/* ---------------------------------------
- * remove the node and its childs from the tree
- *
- * FIXME what about opened forks with refs to it?
- * it's an afp specs violation because you can't delete
- * an opened forks. Now afpd doesn't care about forks opened by other
- * process. It's fixable within afpd if fnctl_lock, doable with smb and
- * next to impossible for nfs and local filesystem access.
- */
-static void dir_invalidate( struct vol *vol, struct dir *dir)
-{
- if (curdir == dir) {
- /* v_root can't be deleted */
- if (movecwd(vol, vol->v_root) < 0) {
- LOG(log_error, logtype_afpd, "cname can't chdir to : %s", vol->v_root);
- }
+ /* Add it to the cache only if it's a dir */
+ if (dircache_add(ret) != 0) { /* 7 */
+ err = 1;
+ goto exit;
}
- /* FIXME */
- dirchildremove(dir->d_parent, dir);
- dir_remove( vol, dir );
-}
-/* ------------------------------------ */
-static struct dir *dir_insert(const struct vol *vol, struct dir *dir)
-{
- struct dir *pdir;
-
- pdir = vol_tree_root(vol, dir->d_did);
- while (pdir->d_did != dir->d_did ) {
- if ( pdir->d_did > dir->d_did ) {
- if ( pdir->d_left == SENTINEL ) {
- pdir->d_left = dir;
- dir->d_back = pdir;
- return NULL;
- }
- pdir = pdir->d_left;
- } else {
- if ( pdir->d_right == SENTINEL ) {
- pdir->d_right = dir;
- dir->d_back = pdir;
- return NULL;
- }
- pdir = pdir->d_right;
+ LOG(log_debug, logtype_afpd, "dirlookup(did: %u) {end: did:%u, path:'%s'}",
+ ntohl(did), ntohl(pdid), cfrombstring(ret->d_fullpath));
+
+exit:
+ if (err) {
+ LOG(log_debug, logtype_afpd, "dirlookup(did: %u) {exit_error: %s}",
+ ntohl(did), AfpErr2name(afp_errno));
+ free(upath);
+ if (fullpath)
+ bdestroy(fullpath);
+ if (ret) {
+ dir_free(ret);
+ ret = NULL;
}
}
- return pdir;
+ return ret;
}
#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)
+int caseenumerate(const struct vol *vol, struct path *path, struct dir *dir)
{
DIR *dp;
struct dirent *de;
}
-/*
- * attempt to extend the current dir. tree to include path
- * as a side-effect, movecwd to that point and return the new dir
+/*!
+ * @brief Construct struct dir
+ *
+ * Construct struct dir from parameters.
+ *
+ * @param m_name (r) directory name in UTF8-dec
+ * @param u_name (r) directory name in server side encoding
+ * @param vol (r) pointer to struct vol
+ * @param pdid (r) Parent CNID
+ * @param did (r) CNID
+ * @param fullpath (r) Full unix path to dir
+ *
+ * @returns pointer to new struct dir or NULL on error
+ *
+ * @note Most of the time mac name and unix name are the same.
*/
-static struct dir *
-extenddir(struct vol *vol, struct dir *dir, struct path *path)
+struct dir *dir_new(const char *m_name,
+ const char *u_name,
+ const struct vol *vol,
+ cnid_t pdid,
+ cnid_t did,
+ bstring path)
{
- path->d_dir = NULL;
+ struct dir *dir;
- if ( path->u_name == NULL) {
- afp_errno = AFPERR_PARAM;
+ dir = (struct dir *) calloc(1, sizeof( struct dir ));
+ if (!dir)
return NULL;
- }
- if (check_name(vol, path->u_name)) {
- /* the name is illegal */
- LOG(log_info, logtype_afpd, "extenddir: illegal path: '%s'", path->u_name);
- path->u_name = NULL;
- afp_errno = AFPERR_PARAM;
+ if ((dir->d_m_name = bfromcstr(m_name)) == NULL) {
+ free(dir);
return NULL;
}
- if (of_stat( path ) != 0 ) {
- if (!(vol->v_flags & AFPVOL_CASEINSEN))
- return NULL;
- else if(caseenumerate(vol, path, dir) != 0)
- return(NULL);
- }
-
- if (!S_ISDIR(path->st.st_mode)) {
- return( NULL );
- }
-
- /* mac name is always with the right encoding (from cname()) */
- if (( dir = adddir( vol, dir, path)) == NULL ) {
- return( NULL );
- }
-
- path->d_dir = dir;
- if ( movecwd( vol, dir ) < 0 ) {
- return( NULL );
- }
-
- return( dir );
-}
-
-/* -------------------------
- appledouble mkdir afp error code.
-*/
-static int netatalk_mkdir(const char *name)
-{
- if (ad_mkdir(name, DIRBITS | 0777) < 0) {
- switch ( errno ) {
- case ENOENT :
- return( AFPERR_NOOBJ );
- case EROFS :
- return( AFPERR_VLOCK );
- case EPERM:
- case EACCES :
- return( AFPERR_ACCESS );
- case EEXIST :
- return( AFPERR_EXIST );
- case ENOSPC :
- case EDQUOT :
- return( AFPERR_DFULL );
- default :
- return( AFPERR_PARAM );
- }
- }
- return AFP_OK;
-}
-
-/* ------------------- */
-static int deletedir(int dirfd, char *dir)
-{
- char path[MAXPATHLEN + 1];
- DIR *dp;
- struct dirent *de;
- struct stat st;
- size_t len;
- int err = AFP_OK;
- size_t remain;
-
- if ((len = strlen(dir)) +2 > sizeof(path))
- return AFPERR_PARAM;
-
- /* already gone */
- if ((dp = opendirat(dirfd, dir)) == NULL)
- return AFP_OK;
-
- strcpy(path, dir);
- strcat(path, "/");
- len++;
- remain = sizeof(path) -len -1;
- while ((de = readdir(dp)) && err == AFP_OK) {
- /* skip this and previous directory */
- if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
- continue;
-
- if (strlen(de->d_name) > remain) {
- err = AFPERR_PARAM;
- break;
- }
- strcpy(path + len, de->d_name);
- if (lstatat(dirfd, path, &st)) {
- continue;
- }
- if (S_ISDIR(st.st_mode)) {
- err = deletedir(dirfd, path);
- } else {
- err = netatalk_unlinkat(dirfd, path);
- }
- }
- closedir(dp);
-
- /* okay. the directory is empty. delete it. note: we already got rid
- of .AppleDouble. */
- if (err == AFP_OK) {
- err = netatalk_rmdir(dirfd, dir);
- }
- return err;
-}
-
-/* do a recursive copy. */
-static int copydir(const struct vol *vol, int dirfd, char *src, char *dst)
-{
- char spath[MAXPATHLEN + 1], dpath[MAXPATHLEN + 1];
- DIR *dp;
- struct dirent *de;
- struct stat st;
- struct utimbuf ut;
- size_t slen, dlen;
- size_t srem, drem;
- int err;
-
- /* doesn't exist or the path is too long. */
- if (((slen = strlen(src)) > sizeof(spath) - 2) ||
- ((dlen = strlen(dst)) > sizeof(dpath) - 2) ||
- ((dp = opendirat(dirfd, src)) == NULL))
- return AFPERR_PARAM;
-
- /* try to create the destination directory */
- if (AFP_OK != (err = netatalk_mkdir(dst)) ) {
- closedir(dp);
- return err;
+ if (convert_string_allocate( (utf8_encoding()) ? CH_UTF8_MAC : vol->v_maccharset,
+ CH_UCS2,
+ m_name,
+ -1, (char **)&dir->d_m_name_ucs2) == (size_t)-1 ) {
+ LOG(log_error, logtype_afpd, "dir_new(did: %u) {%s, %s}: couldn't set UCS2 name", ntohl(did), m_name, u_name);
+ dir->d_m_name_ucs2 = NULL;
}
- /* set things up to copy */
- strcpy(spath, src);
- strcat(spath, "/");
- slen++;
- srem = sizeof(spath) - slen -1;
-
- strcpy(dpath, dst);
- strcat(dpath, "/");
- dlen++;
- drem = sizeof(dpath) - dlen -1;
-
- err = AFP_OK;
- while ((de = readdir(dp))) {
- /* skip this and previous directory */
- if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
- continue;
-
- if (strlen(de->d_name) > srem) {
- err = AFPERR_PARAM;
- break;
- }
- strcpy(spath + slen, de->d_name);
-
- if (lstatat(dirfd, spath, &st) == 0) {
- if (strlen(de->d_name) > drem) {
- err = AFPERR_PARAM;
- break;
- }
- strcpy(dpath + dlen, de->d_name);
-
- if (S_ISDIR(st.st_mode)) {
- if (AFP_OK != (err = copydir(vol, dirfd, spath, dpath)))
- goto copydir_done;
- } else if (AFP_OK != (err = copyfile(vol, vol, dirfd, spath, dpath, NULL, NULL))) {
- goto copydir_done;
-
- } else {
- /* keep the same time stamp. */
- ut.actime = ut.modtime = st.st_mtime;
- utime(dpath, &ut);
- }
- }
+ if (m_name == u_name || !strcmp(m_name, u_name)) {
+ dir->d_u_name = dir->d_m_name;
}
-
- /* keep the same time stamp. */
- if (lstatat(dirfd, src, &st) == 0) {
- ut.actime = ut.modtime = st.st_mtime;
- utime(dst, &ut);
+ else if ((dir->d_u_name = bfromcstr(u_name)) == NULL) {
+ bdestroy(dir->d_m_name);
+ free(dir);
+ return NULL;
}
-copydir_done:
- closedir(dp);
- return err;
+ dir->d_did = did;
+ dir->d_pdid = pdid;
+ dir->d_vid = vol->v_vid;
+ dir->d_fullpath = path;
+ return dir;
}
-
-/* --- public functions follow --- */
-
-/* NOTE: we start off with at least one node (the root directory). */
-static struct dir *dirinsert(struct vol *vol, struct dir *dir)
+/*!
+ * @brief Free a struct dir and all its members
+ *
+ * @param (rw) pointer to struct dir
+ */
+void dir_free(struct dir *dir)
{
- struct dir *node;
-
- if ((node = dir_insert(vol, dir)))
- return node;
-
- /* recolor the tree. the current node is red. */
- dir->d_color = DIRTREE_COLOR_RED;
-
- /* parent of this node has to be black. if the parent node
- * is red, then we have a grandparent. */
- while ((dir != vol->v_root) &&
- (dir->d_back->d_color == DIRTREE_COLOR_RED)) {
- /* are we on the left tree? */
- if (dir->d_back == dir->d_back->d_back->d_left) {
- node = dir->d_back->d_back->d_right; /* get the right node */
- if (node->d_color == DIRTREE_COLOR_RED) {
- /* we're red. we need to change to black. */
- dir->d_back->d_color = DIRTREE_COLOR_BLACK;
- node->d_color = DIRTREE_COLOR_BLACK;
- dir->d_back->d_back->d_color = DIRTREE_COLOR_RED;
- dir = dir->d_back->d_back; /* finished. go up. */
- } else {
- if (dir == dir->d_back->d_right) {
- dir = dir->d_back;
- dir_leftrotate(vol, dir);
- }
- dir->d_back->d_color = DIRTREE_COLOR_BLACK;
- dir->d_back->d_back->d_color = DIRTREE_COLOR_RED;
- dir_rightrotate(vol, dir->d_back->d_back);
- }
- } else {
- node = dir->d_back->d_back->d_left;
- if (node->d_color == DIRTREE_COLOR_RED) {
- /* we're red. we need to change to black. */
- dir->d_back->d_color = DIRTREE_COLOR_BLACK;
- node->d_color = DIRTREE_COLOR_BLACK;
- dir->d_back->d_back->d_color = DIRTREE_COLOR_RED;
- dir = dir->d_back->d_back; /* finished. ascend */
- } else {
- if (dir == dir->d_back->d_left) {
- dir = dir->d_back;
- dir_rightrotate(vol, dir);
- }
- dir->d_back->d_color = DIRTREE_COLOR_BLACK;
- dir->d_back->d_back->d_color = DIRTREE_COLOR_RED;
- dir_leftrotate(vol, dir->d_back->d_back);
- }
- }
+ if (dir->d_u_name != dir->d_m_name) {
+ bdestroy(dir->d_u_name);
}
-
- vol->v_root->d_color = DIRTREE_COLOR_BLACK;
- return NULL;
+ if (dir->d_m_name_ucs2)
+ free(dir->d_m_name_ucs2);
+ bdestroy(dir->d_m_name);
+ bdestroy(dir->d_fullpath);
+ free(dir);
}
-/* ---------------------------- */
-struct dir *
-adddir(struct vol *vol, struct dir *dir, struct path *path)
+/*!
+ * @brief Create struct dir from struct path
+ *
+ * Create a new struct dir from struct path. Then add it to the cache.
+ * The caller must have assured that the dir is not already in the cache,
+ * cf theAFP_ASSERTion.
+ * 1. Open adouble file, get CNID from it.
+ * 2. Search the database, hinting with the CNID from (1).
+ * 3. Build fullpath and create struct dir.
+ * 4. Add it to the cache.
+ *
+ * @param vol (r) pointer to struct vol
+ * @param dir (r) pointer to parrent directory
+ * @param path (rw) pointer to struct path with valid path->u_name
+ * @param len (r) strlen of path->u_name
+ *
+ * @returns Pointer to new struct dir or NULL on error.
+ *
+ * @note Function also assigns path->m_name from path->u_name.
+ */
+struct dir *dir_add(const struct vol *vol, const struct dir *dir, struct path *path, int len)
{
- struct dir *cdir, *edir;
- int upathlen;
- char *name;
- char *upath;
- struct stat *st;
- int deleted;
+ int err = 0;
+ struct dir *cdir = NULL;
+ cnid_t id;
struct adouble ad;
struct adouble *adp = NULL;
- cnid_t id;
-
- upath = path->u_name;
- st = &path->st;
- upathlen = strlen(upath);
+ bstring fullpath;
+
+ AFP_ASSERT(vol);
+ AFP_ASSERT(dir);
+ AFP_ASSERT(path);
+ AFP_ASSERT(len > 0);
+
+ if ((cdir = dircache_search_by_name(vol, dir, path->u_name, strlen(path->u_name))) != NULL) {
+ /* there's a stray entry in the dircache */
+ LOG(log_debug, logtype_afpd, "dir_add(did:%u,'%s/%s'): {stray cache entry: did:%u,'%s', removing}",
+ ntohl(dir->d_did), cfrombstring(dir->d_fullpath), path->u_name,
+ ntohl(cdir->d_did), cfrombstring(dir->d_fullpath));
+ if (dir_remove(vol, cdir) != 0) {
+ dircache_dump();
+ exit(EXITERR_SYS);
+ }
+ }
/* get_id needs adp for reading CNID from adouble file */
ad_init(&ad, vol->v_adouble, vol->v_ad_options);
- if ((ad_open_metadata(upath, ADFLAGS_DIR, 0, &ad)) == 0)
+ if ((ad_open_metadata(path->u_name, ADFLAGS_DIR, 0, &ad)) == 0) /* 1 */
adp = &ad;
- id = get_id(vol, adp, st, dir->d_did, upath, upathlen);
+ /* Get CNID */
+ if ((id = get_id(vol, adp, &path->st, dir->d_did, path->u_name, len)) == 0) { /* 2 */
+ err = 1;
+ goto exit;
+ }
if (adp)
ad_close_metadata(adp);
- if (id == 0) {
- return NULL;
- }
- if (!path->m_name && !(path->m_name = utompath(vol, upath, id , utf8_encoding()))) {
- return NULL;
- }
- name = path->m_name;
- if ((cdir = dirnew(name, upath)) == NULL) {
- LOG(log_error, logtype_afpd, "adddir: malloc: %s", strerror(errno) );
- return NULL;
- }
- if ((size_t)-1 == convert_string_allocate((utf8_encoding())?CH_UTF8_MAC:vol->v_maccharset, CH_UCS2, path->m_name, -1, (char **)&cdir->d_m_name_ucs2)) {
- LOG(log_error, logtype_afpd, "Couldn't set UCS2 name for %s", name);
- cdir->d_m_name_ucs2 = NULL;
- }
-
- cdir->d_did = id;
-
- if ((edir = dirinsert( vol, cdir ))) {
- /* it's not possible with LASTDID
- for CNID:
- - someone else have moved the directory.
- - it's a symlink inside the share.
- - it's an ID reused, the old directory was deleted but not
- the cnid record and the server've reused the inode for
- the new dir.
- for HASH (we should get ride of HASH)
- - someone else have moved the directory.
- - it's an ID reused as above
- - it's a hash duplicate and we are in big trouble
- */
- deleted = (edir->d_m_name == NULL);
- if (!deleted)
- dir_hash_del(vol, edir);
- dirfreename(edir);
- edir->d_m_name = cdir->d_m_name;
- edir->d_u_name = cdir->d_u_name;
- edir->d_m_name_ucs2 = cdir->d_m_name_ucs2;
- free(cdir);
- cdir = edir;
- LOG(log_error, logtype_afpd, "adddir: insert %s", edir->d_m_name);
- if (!cdir->d_parent || (cdir->d_parent == dir && !deleted)) {
- hash_alloc_insert(vol->v_hash, cdir, cdir);
- return cdir;
+ /* Get macname from unixname */
+ if (path->m_name == NULL) {
+ if ((path->m_name = utompath(vol, path->u_name, id, utf8_encoding())) == NULL) {
+ err = 2;
+ goto exit;
}
- /* the old was not in the same folder */
- if (!deleted)
- dirchildremove(cdir->d_parent, cdir);
}
- /* parent/child directories */
- cdir->d_parent = dir;
- dirchildadd(vol, dir, cdir);
- return( cdir );
-}
-
-/* --- public functions follow --- */
-/* free everything down. we don't bother to recolor as this is only
- * called to free the entire tree */
-void dirfreename(struct dir *dir)
-{
- if (dir->d_u_name != dir->d_m_name) {
- free(dir->d_u_name);
+ /* Build fullpath */
+ if ( ((fullpath = bstrcpy(dir->d_fullpath)) == NULL) /* 3 */
+ || (bconchar(fullpath, '/') != BSTR_OK)
+ || (bcatcstr(fullpath, path->u_name)) != BSTR_OK) {
+ LOG(log_error, logtype_afpd, "dir_add: fullpath: %s", strerror(errno) );
+ err = 3;
+ goto exit;
}
- if (dir->d_m_name_ucs2)
- free(dir->d_m_name_ucs2);
- free(dir->d_m_name);
-}
-
-void dirfree(struct dir *dir)
-{
- if (!dir || (dir == SENTINEL))
- return;
- if ( dir->d_left != SENTINEL ) {
- dirfree( dir->d_left );
+ /* Allocate and initialize struct dir */
+ if ((cdir = dir_new( path->m_name, path->u_name, vol, dir->d_did, id, fullpath)) == NULL) { /* 3 */
+ err = 4;
+ goto exit;
}
- if ( dir->d_right != SENTINEL ) {
- dirfree( dir->d_right );
+
+ if ((dircache_add(cdir)) != 0) { /* 4 */
+ LOG(log_error, logtype_afpd, "dir_add: fatal dircache error: %s", cfrombstring(fullpath));
+ exit(EXITERR_SYS);
}
- if (dir != SENTINEL) {
- dirfreename(dir);
- free( dir );
+exit:
+ if (err != 0) {
+ LOG(log_debug, logtype_afpd, "dir_add('%s/%s'): error: %u",
+ cfrombstring(dir->d_u_name), path->u_name, err);
+
+ if (adp)
+ ad_close_metadata(adp);
+ if (!cdir && fullpath)
+ bdestroy(fullpath);
+ if (cdir)
+ dir_free(cdir);
+ cdir = NULL;
+ } else {
+ /* no error */
+ LOG(log_debug, logtype_afpd, "dir_add(did:%u,'%s/%s'): {cached: %u,'%s'}",
+ ntohl(dir->d_did), cfrombstring(dir->d_fullpath), path->u_name,
+ ntohl(cdir->d_did), cfrombstring(cdir->d_fullpath));
}
+
+ return(cdir);
}
-/* --------------------------------------------
- * most of the time mac name and unix name are the same
+/*!
+ * @brief Remove a dir from a cache and free it and any ressources with it
+ *
+ * 1. Check if the dir is locked or has opened forks
+ * 2. If it's a request to remove curdir, just chdir to volume root
+ * 3. Remove it from the cache
+ * 4. Remove the dir plus any allocated resources it references
+ *
+ * @param (r) pointer to struct vol
+ * @param (rw) pointer to struct dir
*/
-struct dir *dirnew(const char *m_name, const char *u_name)
+int dir_remove(const struct vol *vol, struct dir *dir)
{
- struct dir *dir;
+ AFP_ASSERT(vol);
+ AFP_ASSERT(dir);
- dir = (struct dir *) calloc(1, sizeof( struct dir ));
- if (!dir)
- return NULL;
+ if (dir->d_did == DIRDID_ROOT_PARENT || dir->d_did == DIRDID_ROOT)
+ return 0;
- if ((dir->d_m_name = strdup(m_name)) == NULL) {
- free(dir);
- return NULL;
+ if (dir->d_flags & DIRF_CACHELOCK || dir->d_ofork) { /* 1 */
+ LOG(log_warning, logtype_afpd, "dir_remove(did:%u,'%s'): dir is locked or has opened forks",
+ ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
+ return 0;
}
- if (m_name == u_name || !strcmp(m_name, u_name)) {
- dir->d_u_name = dir->d_m_name;
- }
- else if ((dir->d_u_name = strdup(u_name)) == NULL) {
- free(dir->d_m_name);
- free(dir);
- return NULL;
+ if (curdir == dir) { /* 2 */
+ if (movecwd(vol, vol->v_root) < 0) {
+ LOG(log_error, logtype_afpd, "dir_remove: can't chdir to : %s", vol->v_root);
+ }
}
- dir->d_m_name_ucs2 = NULL;
- dir->d_left = dir->d_right = SENTINEL;
- dir->d_next = dir->d_prev = dir;
- return dir;
-}
-
-#if 0
-/* ------------------ */
-static hash_val_t hash_fun_dir(const void *key)
-{
- const struct dir *k = key;
-
- static unsigned long randbox[] = {
- 0x49848f1bU, 0xe6255dbaU, 0x36da5bdcU, 0x47bf94e9U,
- 0x8cbcce22U, 0x559fc06aU, 0xd268f536U, 0xe10af79aU,
- 0xc1af4d69U, 0x1d2917b5U, 0xec4c304dU, 0x9ee5016cU,
- 0x69232f74U, 0xfead7bb3U, 0xe9089ab6U, 0xf012f6aeU,
- };
-
- const unsigned char *str = (unsigned char *)(k->d_u_name);
- hash_val_t acc = k->d_parent->d_did;
-
- while (*str) {
- acc ^= randbox[(*str + acc) & 0xf];
- acc = (acc << 1) | (acc >> 31);
- acc &= 0xffffffffU;
- acc ^= randbox[((*str++ >> 4) + acc) & 0xf];
- acc = (acc << 2) | (acc >> 30);
- acc &= 0xffffffffU;
- }
- return acc;
-}
-#endif
+ LOG(log_debug, logtype_afpd, "dir_remove(did:%u,'%s'): {removing}",
+ ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
-#undef get16bits
-#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
- || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
-#define get16bits(d) (*((const uint16_t *) (d)))
-#endif
+ dircache_remove(vol, dir, DIRCACHE | DIDNAME_INDEX | QUEUE_INDEX); /* 3 */
+ dir_free(dir); /* 4 */
-#if !defined (get16bits)
-#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \
- +(uint32_t)(((const uint8_t *)(d))[0]) )
-#endif
+ return 0;
+}
-static hash_val_t hash_fun2_dir(const void *key)
+/*!
+ * @brief Modify a struct dir, adjust cache
+ *
+ * Any value that is 0 or NULL is not changed. If new_uname is NULL it is set to new_mname.
+ * If given new_uname == new_mname, new_uname will point to new_mname.
+ *
+ * @param vol (r) pointer to struct vol
+ * @param dir (rw) pointer to struct dir
+ * @param pdid (r) new parent DID
+ * @param did (r) new DID
+ * @param new_mname (r) new mac-name
+ * @param new_uname (r) new unix-name
+ */
+int dir_modify(const struct vol *vol,
+ struct dir *dir,
+ cnid_t pdid,
+ cnid_t did,
+ const char *new_mname,
+ const char *new_uname,
+ bstring pdir_fullpath)
{
- const struct dir *k = key;
- const char *data = k->d_u_name;
- int len = strlen(k->d_u_name);
- hash_val_t hash = k->d_parent->d_did, tmp;
-
- int rem = len & 3;
- len >>= 2;
-
- /* Main loop */
- for (;len > 0; len--) {
- hash += get16bits (data);
- tmp = (get16bits (data+2) << 11) ^ hash;
- hash = (hash << 16) ^ tmp;
- data += 2*sizeof (uint16_t);
- hash += hash >> 11;
- }
-
- /* Handle end cases */
- switch (rem) {
- case 3: hash += get16bits (data);
- hash ^= hash << 16;
- hash ^= data[sizeof (uint16_t)] << 18;
- hash += hash >> 11;
- break;
- case 2: hash += get16bits (data);
- hash ^= hash << 11;
- hash += hash >> 17;
- break;
- case 1: hash += *data;
- hash ^= hash << 10;
- hash += hash >> 1;
- }
-
- /* Force "avalanching" of final 127 bits */
- hash ^= hash << 3;
- hash += hash >> 5;
- hash ^= hash << 4;
- hash += hash >> 17;
- hash ^= hash << 25;
- hash += hash >> 6;
+ int ret = 0;
- return hash;
-}
+ /* Remove it from the cache */
+ dircache_remove(vol, dir, DIRCACHE | DIDNAME_INDEX | QUEUE_INDEX);
-/* ---------------- */
-static int hash_comp_dir(const void *key1, const void *key2)
-{
- const struct dir *k1 = key1;
- const struct dir *k2 = key2;
+ if (pdid)
+ dir->d_pdid = pdid;
+ if (did)
+ dir->d_did = did;
- return !(k1->d_parent->d_did == k2->d_parent->d_did && !strcmp(k1->d_u_name, k2->d_u_name));
-}
+ if (new_mname) {
+ /* free uname if it's not the same as mname */
+ if (dir->d_m_name != dir->d_u_name)
+ bdestroy(dir->d_u_name);
-/* ---------------- */
-hash_t *
-dirhash(void)
-{
- return hash_create(HASHCOUNT_T_MAX, hash_comp_dir, hash_fun2_dir);
-}
+ if (new_uname == NULL)
+ new_uname = new_mname;
-/* ------------------ */
-static struct path *invalidate (struct vol *vol, struct dir *dir, struct path *ret)
-{
- /* it's tricky:
- movecwd failed some of dir path are not there anymore.
- FIXME Is it true with other errors?
- so we remove dir from the cache
- */
- if (dir->d_did == DIRDID_ROOT_PARENT)
- return NULL;
- if (afp_errno == AFPERR_ACCESS) {
- if ( movecwd( vol, dir->d_parent ) < 0 ) {
- return NULL;
- }
- /* FIXME should we set these?, don't need to call stat() after:
- ret->st_valid = 1;
- ret->st_errno = EACCES;
- */
- ret->m_name = dir->d_m_name;
- ret->u_name = dir->d_u_name;
- ret->d_dir = dir;
- return ret;
- } else if (afp_errno == AFPERR_NOOBJ) {
- if ( movecwd( vol, dir->d_parent ) < 0 ) {
- return NULL;
- }
- strcpy(ret->m_name, dir->d_m_name);
- if (dir->d_m_name == dir->d_u_name) {
- ret->u_name = ret->m_name;
+ /* assign new name */
+ if ((bassigncstr(dir->d_m_name, new_mname)) != BSTR_OK) {
+ LOG(log_error, logtype_afpd, "dir_modify: bassigncstr: %s", strerror(errno) );
+ return -1;
}
- else {
- size_t tp = strlen(ret->m_name)+1;
- ret->u_name = ret->m_name +tp;
- strcpy(ret->u_name, dir->d_u_name);
+ if (new_mname == new_uname || (strcmp(new_mname, new_uname) == 0)) {
+ dir->d_u_name = dir->d_m_name;
+ } else {
+ if ((dir->d_u_name = bfromcstr(new_uname)) == NULL) {
+ LOG(log_error, logtype_afpd, "renamedir: bassigncstr: %s", strerror(errno) );
+ return -1;
+ }
}
- /* FIXME should we set :
- ret->st_valid = 1;
- ret->st_errno = ENOENT;
- */
- dir_invalidate(vol, dir);
- return ret;
}
- dir_invalidate(vol, dir);
- return NULL;
-}
-/* -------------------------------------------------- */
-/* cname
- return
- if it's a filename:
- in extenddir:
- compute unix name
- stat the file or errno
- return
- filename
- curdir: filename parent directory
-
- if it's a dirname:
- not in the cache
- in extenddir
- compute unix name
- stat the dir or errno
- return
- if chdir error
- dirname
- curdir: dir parent directory
- sinon
- dirname: ""
- curdir: dir
- in the cache
- return
- if chdir error
- dirname
- curdir: dir parent directory
- else
- dirname: ""
- curdir: dir
+ if (pdir_fullpath) {
+ if (bassign(dir->d_fullpath, pdir_fullpath) != BSTR_OK)
+ return -1;
+ if (bcatcstr(dir->d_fullpath, "/") != BSTR_OK)
+ return -1;
+ if (bcatcstr(dir->d_fullpath, new_uname) != BSTR_OK)
+ return -1;
+ }
+
+ if (dir->d_m_name_ucs2)
+ free(dir->d_m_name_ucs2);
+ if ((size_t)-1 == convert_string_allocate((utf8_encoding())?CH_UTF8_MAC:vol->v_maccharset, CH_UCS2, dir->d_m_name, -1, (char**)&dir->d_m_name_ucs2))
+ dir->d_m_name_ucs2 = NULL;
+
+ /* Re-add it to the cache */
+ if ((dircache_add(dir)) != 0) {
+ dircache_dump();
+ exit(EXITERR_SYS);
+ }
-*/
-struct path *
-cname(struct vol *vol, struct dir *dir, char **cpath)
+ return ret;
+}
+
+/*!
+ * @brief Resolve a catalog node name path
+ *
+ * 1. Evaluate path type
+ * 2. Move to start dir, if we cant, it might eg because of EACCES, build
+ * path from dirname, so eg getdirparams has sth it can chew on. curdir
+ * is dir parent then. All this is done in path_from_dir().
+ * 3. Parse next cnode name in path, cases:
+ * 4. single "\0" -> do nothing
+ * 5. two or more consecutive "\0" -> chdir("..") one or more times
+ * 6. cnode name -> copy it to path.m_name
+ * 7. Get unix name from mac name
+ * 8. Special handling of request with did 1
+ * 9. stat the cnode name
+ * 10. If it's not there, it's probably an afp_createfile|dir,
+ * return with curdir = dir parent, struct path = dirname
+ * 11. If it's there and it's a file, it must should be the last element of the requested
+ * path. Return with curdir = cnode name parent dir, struct path = filename
+ * 12. Treat symlinks like files, dont follow them
+ * 13. If it's a dir:
+ * 14. Search the dircache for it
+ * 15. If it's not in the cache, create a struct dir for it and add it to the cache
+ * 16. chdir into the dir and
+ * 17. set m_name to the mac equivalent of "."
+ * 18. goto 3
+ */
+struct path *cname(struct vol *vol, struct dir *dir, char **cpath)
{
- struct dir *cdir, *scdir=NULL;
static char path[ MAXPATHLEN + 1];
static struct path ret;
+ struct dir *cdir;
char *data, *p;
- int extend = 0;
int len;
u_int32_t hint;
u_int16_t len16;
int size = 0;
- char sep;
int toUTF8 = 0;
+ LOG(log_maxdebug, logtype_afpd, "came('%s'): {start}", cfrombstring(dir->d_fullpath));
+
data = *cpath;
afp_errno = AFPERR_NOOBJ;
memset(&ret, 0, sizeof(ret));
- switch (ret.m_type = *data) { /* path type */
+
+ switch (ret.m_type = *data) { /* 1 */
case 2:
data++;
len = (unsigned char) *data++;
size = 2;
- sep = 0;
if (afp_version >= 30) {
ret.m_type = 3;
toUTF8 = 1;
len = ntohs(len16);
data += 2;
size = 7;
- sep = 0; /* '/';*/
break;
}
/* else it's an error */
return( NULL );
}
*cpath += len + size;
- *path = '\0';
+
+ path[0] = 0;
ret.m_name = path;
- for ( ;; ) {
- if ( len == 0 ) {
- if (movecwd( vol, dir ) < 0 ) {
- return invalidate(vol, dir, &ret );
- }
- if (*path == '\0') {
- ret.u_name = ".";
- ret.d_dir = dir;
- }
- return &ret;
- }
- if (*data == sep ) {
+ if (movecwd(vol, dir) < 0 ) {
+ LOG(log_debug, logtype_afpd, "cname(did:%u): failed to chdir to '%s'",
+ ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
+ if (len == 0)
+ return path_from_dir(vol, dir, &ret);
+ else
+ return NULL;
+ }
+
+ while (len) { /* 3 */
+ if (*data == 0) { /* 4 or 5 */
data++;
len--;
- }
- while (*data == sep && len > 0 ) {
- if ( dir->d_parent == NULL ) {
- return NULL;
+ while (len > 0 && *data == 0) { /* 5 */
+ /* chdir to parrent dir */
+ if ((dir = dirlookup(vol, dir->d_pdid)) == NULL)
+ return NULL;
+ if (movecwd( vol, dir ) < 0 ) {
+ dir_remove(vol, dir);
+ return NULL;
+ }
+ data++;
+ len--;
}
- dir = dir->d_parent;
- data++;
- len--;
+ continue;
}
- /* would this be faster with strlen + strncpy? */
- p = path;
- while ( *data != sep && len > 0 ) {
+ /* 6*/
+ for ( p = path; *data != 0 && len > 0; len-- ) {
*p++ = *data++;
if (p > &path[ MAXPATHLEN]) {
afp_errno = AFPERR_PARAM;
- return( NULL );
+ return NULL;
}
- len--;
}
+ *p = 0; /* Terminate string */
+ ret.u_name = NULL;
- /* short cut bits by chopping off a trailing \0. this also
- makes the traversal happy w/ filenames at the end of the
- cname. */
- if (len == 1)
- len--;
-
- *p = '\0';
-
- if ( p == path ) { /* end of the name parameter */
- continue;
+ if (cname_mtouname(vol, dir, &ret, toUTF8) != 0) { /* 7 */
+ LOG(log_error, logtype_afpd, "cname('%s'): error from cname_mtouname", path);
+ return NULL;
}
- ret.u_name = NULL;
- if (afp_version >= 30) {
- char *t;
- cnid_t fileid;
- if (toUTF8) {
- static char temp[ MAXPATHLEN + 1];
+ LOG(log_maxdebug, logtype_afpd, "came('%s'): {node: '%s}", cfrombstring(dir->d_fullpath), ret.u_name);
- if (dir->d_did == DIRDID_ROOT_PARENT) {
- /*
- With uft8 volume name is utf8-mac, but requested path may be a mangled longname. See #2611981.
- So we compare it with the longname from the current volume and if they match
- we overwrite the requested path with the utf8 volume name so that the following
- strcmp can match.
- */
- ucs2_to_charset(vol->v_maccharset, vol->v_macname, temp, AFPVOL_MACNAMELEN + 1);
- if (strcasecmp( path, temp) == 0)
- ucs2_to_charset(CH_UTF8_MAC, vol->v_u8mname, path, AFPVOL_U8MNAMELEN);
- } else {
- /* toUTF8 */
- if (mtoUTF8(vol, path, strlen(path), temp, MAXPATHLEN) == (size_t)-1) {
- afp_errno = AFPERR_PARAM;
- return( NULL );
- }
- strcpy(path, temp);
- }
- }
- /* check for OS X mangled filename :( */
+ /* Prevent access to our special folders like .AppleDouble */
+ if (check_name(vol, ret.u_name)) {
+ /* the name is illegal */
+ LOG(log_info, logtype_afpd, "cname: illegal path: '%s'", ret.u_name);
+ afp_errno = AFPERR_PARAM;
+ return NULL;
+ }
- t = demangle_osx(vol, path, dir->d_did, &fileid);
- if (t != path) {
- ret.u_name = t;
- /* duplicate work but we can't reuse all convert_char we did in demangle_osx
- * flags weren't the same
+ if (dir->d_did == DIRDID_ROOT_PARENT) { /* 8 */
+ /*
+ * Special case: CNID 1
+ * root parent (did 1) has one child: the volume. Requests for did=1 with
+ * some <name> must check against the volume name.
+ */
+ if ((strcmp(cfrombstring(vol->v_root->d_m_name), ret.m_name)) == 0)
+ cdir = vol->v_root;
+ else
+ return NULL;
+ } else {
+ /*
+ * CNID != 1, eg. most of the times we take this way.
+ * Now check if current path-part is a file or dir:
+ * o if it's dir we have to step into it
+ * o if it's a file we expect it to be the last part of the requested path
+ * and thus call continue which should terminate the while loop because
+ * len = 0. Ok?
+ */
+ if (of_stat(&ret) != 0) { /* 9 */
+ /*
+ * ret.u_name doesn't exist, might be afp_createfile|dir
+ * that means it should have been the last part
*/
- if ( (t = utompath(vol, ret.u_name, fileid, utf8_encoding())) ) {
- /* at last got our view of mac name */
- strcpy(path,t);
+ if (len > 0) {
+ /* it wasn't the last part, so we have a bogus path request */
+ afp_errno = AFPERR_NOOBJ;
+ return NULL;
}
+ /*
+ * this will terminate clean in while (1) because len == 0,
+ * probably afp_createfile|dir
+ */
+ LOG(log_maxdebug, logtype_afpd, "came('%s'): {leave-cnode ENOENT (possile create request): '%s'}", cfrombstring(dir->d_fullpath), ret.u_name);
+ continue; /* 10 */
}
- }
- if (ret.u_name == NULL) {
- if (!(ret.u_name = mtoupath(vol, ret.m_name, dir->d_did, utf8_encoding()))) {
- afp_errno = AFPERR_PARAM;
- return NULL;
- }
- }
- if ( !extend ) {
- ucs2_t *tmpname;
- cdir = dir->d_child;
- scdir = NULL;
- if ( cdir && (vol->v_flags & AFPVOL_CASEINSEN) &&
- (size_t)-1 != convert_string_allocate(((ret.m_type == 3)?CH_UTF8_MAC:vol->v_maccharset),
- CH_UCS2, path, -1, (char **)&tmpname) )
- {
- while (cdir) {
- if (!cdir->d_m_name_ucs2) {
- LOG(log_error, logtype_afpd, "cname: no UCS2 name for %s (did %u)!!!", cdir->d_m_name, ntohl(cdir->d_did) );
- /* this shouldn't happen !!!! */
- goto noucsfallback;
- }
- if ( strcmp_w( cdir->d_m_name_ucs2, tmpname ) == 0 ) {
- break;
- }
- if ( strcasecmp_w( cdir->d_m_name_ucs2, tmpname ) == 0 ) {
- scdir = cdir;
- }
- cdir = (cdir == dir->d_child->d_prev) ? NULL :cdir->d_next;
- }
- free(tmpname);
- }
- else {
- noucsfallback:
- if (dir->d_did == DIRDID_ROOT_PARENT) {
- /*
- root parent (did 1) has one child: the volume. Requests for did=1 with some <name>
- must check against the volume name.
- */
- if (!strcmp(vol->v_dir->d_m_name, ret.m_name))
- cdir = vol->v_dir;
- else
- cdir = NULL;
+ switch (ret.st.st_mode & S_IFMT) {
+ case S_IFREG: /* 11 */
+ LOG(log_debug, logtype_afpd, "came('%s'): {file: '%s'}", cfrombstring(dir->d_fullpath), ret.u_name);
+ if (len > 0) {
+ /* it wasn't the last part, so we have a bogus path request */
+ afp_errno = AFPERR_PARAM;
+ return NULL;
}
- else {
- cdir = dirsearch_byname(vol, dir, ret.u_name);
+ continue; /* continues while loop */
+ case S_IFLNK: /* 12 */
+ LOG(log_debug, logtype_afpd, "came('%s'): {link: '%s'}", cfrombstring(dir->d_fullpath), ret.u_name);
+ if (len > 0) {
+ LOG(log_warning, logtype_afpd, "came('%s'): {symlinked dir: '%s'}", cfrombstring(dir->d_fullpath), ret.u_name);
+ afp_errno = AFPERR_PARAM;
+ return NULL;
}
+ continue; /* continues while loop */
+ case S_IFDIR: /* 13 */
+ break;
+ default:
+ LOG(log_info, logtype_afpd, "cname: special file: '%s'", ret.u_name);
+ afp_errno = AFPERR_NODIR;
+ return NULL;
}
- if (cdir == NULL && scdir != NULL) {
- cdir = scdir;
- /* LOG(log_debug, logtype_afpd, "cname: using casediff for %s, (%s = %s)", fullpathname(cdir->d_u_name), cdir->d_m_name, path ); */
- }
-
- if ( cdir == NULL ) {
- ++extend;
- /* if dir == curdir it always succeed,
- even if curdir is deleted.
- it's not a pb because it will fail in extenddir
- */
- if ( movecwd( vol, dir ) < 0 ) {
- /* dir is not valid anymore
- we delete dir from the cache and abort.
- */
- if ( dir->d_did == DIRDID_ROOT_PARENT) {
- afp_errno = AFPERR_NOOBJ;
- return NULL;
- }
- if (afp_errno == AFPERR_ACCESS)
- return NULL;
- dir_invalidate(vol, dir);
+ /* Search the cache */
+ int unamelen = strlen(ret.u_name);
+ cdir = dircache_search_by_name(vol, dir, ret.u_name, unamelen); /* 14 */
+ if (cdir == NULL) {
+ /* Not in cache, create one */
+ if ((cdir = dir_add(vol, dir, &ret, unamelen)) == NULL) { /* 15 */
+ LOG(log_error, logtype_afpd, "cname(did:%u, name:'%s', cwd:'%s'): failed to add dir",
+ ntohl(dir->d_did), ret.u_name, getcwdpath());
return NULL;
}
- cdir = extenddir( vol, dir, &ret );
}
+ } /* if/else cnid==1 */
+
+ /* Now chdir to the evaluated dir */
+ if (movecwd( vol, cdir ) < 0 ) { /* 16 */
+ LOG(log_debug, logtype_afpd, "cname(cwd:'%s'): failed to chdir to new subdir '%s': %s",
+ cfrombstring(curdir->d_fullpath), cfrombstring(cdir->d_fullpath), strerror(errno));
+ if (len == 0)
+ return path_from_dir(vol, cdir, &ret);
+ else
+ return NULL;
+ }
+ dir = cdir;
+ ret.m_name[0] = 0; /* 17, so we later know last token was a dir */
+ } /* while (len) */
- } else {
- cdir = extenddir( vol, dir, &ret );
- } /* if (!extend) */
+ if (curdir->d_did == DIRDID_ROOT_PARENT) {
+ afp_errno = AFPERR_DID1;
+ return NULL;
+ }
- if ( cdir == NULL ) {
+ if (ret.m_name[0] == 0) {
+ /* Last part was a dir */
+ ret.u_name = mtoupath(vol, ret.m_name, 0, 1); /* Force "." into a useable static buffer */
+ ret.d_dir = dir;
+ }
- if ( len > 0 || !ret.u_name ) {
- return NULL;
- }
+ LOG(log_debug, logtype_afpd, "came('%s') {end: curdir:'%s', path:'%s'}",
+ cfrombstring(dir->d_fullpath),
+ cfrombstring(curdir->d_fullpath),
+ ret.u_name);
- } else {
- dir = cdir;
- *path = '\0';
- }
- } /* for (;;) */
+ return &ret;
}
/*
- * Move curdir to dir, with a possible chdir()
+ * @brief chdir() to dir
+ *
+ * @param vol (r) pointer to struct vol
+ * @param dir (r) pointer to struct dir
+ *
+ * @returns 0 on success, -1 on error with afp_errno set appropiately
*/
-int movecwd(struct vol *vol, struct dir *dir)
+int movecwd(const struct vol *vol, struct dir *dir)
{
- char path[MAXPATHLEN + 1];
- struct dir *d;
- char *p, *u;
- int n;
- int ret;
+ int ret;
- if ( dir == curdir ) {
+ AFP_ASSERT(vol);
+ AFP_ASSERT(dir);
+
+ LOG(log_maxdebug, logtype_afpd, "movecwd(curdir:'%s', cwd:'%s')",
+ cfrombstring(curdir->d_fullpath), getcwdpath());
+
+ if ( dir == curdir)
return( 0 );
- }
- if ( dir->d_did == DIRDID_ROOT_PARENT) {
- afp_errno = AFPERR_DID1; /* AFPERR_PARAM;*/
- return( -1 );
+ if (dir->d_did == DIRDID_ROOT_PARENT) {
+ curdir = &rootParent;
+ return 0;
}
- p = path + sizeof(path) - 1;
- *p = '\0';
- for ( d = dir; d->d_parent != NULL && d != curdir; d = d->d_parent ) {
- u = d->d_u_name;
- if (!u) {
- /* parent directory is deleted */
- afp_errno = AFPERR_NOOBJ;
- return -1;
- }
- n = strlen( u );
- if (p -n -1 < path) {
- afp_errno = AFPERR_PARAM;
- return -1;
- }
- *--p = '/';
- p -= n;
- memcpy( p, u, n );
- }
- if ( d != curdir ) {
- n = strlen( vol->v_path );
- if (p -n -1 < path) {
- afp_errno = AFPERR_PARAM;
- return -1;
- }
- *--p = '/';
- p -= n;
- memcpy( p, vol->v_path, n );
- }
- if ( (ret = lchdir(p )) != 0 ) {
- LOG(log_debug, logtype_afpd, "movecwd('%s'): ret:%d, %u/%s", p, ret, errno, strerror(errno));
+ LOG(log_debug, logtype_afpd, "movecwd(did:%u, '%s')", ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
+ if ((ret = lchdir(cfrombstring(dir->d_fullpath))) != 0 ) {
+ LOG(log_debug, logtype_afpd, "movecwd('%s'): ret: %u, %s",
+ cfrombstring(dir->d_fullpath), ret, strerror(errno));
if (ret == 1) {
/* p is a symlink or getcwd failed */
afp_errno = AFPERR_BADTYPE;
- vol->v_curdir = curdir = vol->v_dir;
+
if (chdir(vol->v_path ) < 0) {
- LOG(log_debug, logtype_afpd, "can't chdir back'%s': %s", vol->v_path, strerror(errno));
+ LOG(log_error, logtype_afpd, "can't chdir back'%s': %s", vol->v_path, strerror(errno));
/* XXX what do we do here? */
}
+ curdir = vol->v_root;
return -1;
}
+
switch (errno) {
case EACCES:
case EPERM:
break;
default:
afp_errno = AFPERR_NOOBJ;
-
}
return( -1 );
}
- vol->v_curdir = curdir = dir;
+
+ curdir = dir;
return( 0 );
}
dir->d_flags &= ~DIRF_CNID;
}
-/* ---------------------
- * is our cached offspring count valid?
- */
-
-static int diroffcnt(struct dir *dir, struct stat *st)
-{
- return st->st_ctime == dir->ctime;
-}
/* ---------------------
* is our cached also for reenumerate id?
*/
-
int dirreenumerate(struct dir *dir, struct stat *st)
{
return st->st_ctime == dir->ctime && (dir->d_flags & DIRF_CNID);
}
-/* --------------------- */
-static int invisible_dots(const struct vol *vol, const char *name)
-{
- return vol_inv_dots(vol) && *name == '.' && strcmp(name, ".") && strcmp(name, "..");
-}
-
/* ------------------------------
(".", curdir)
(name, dir) with curdir:name == dir, from afp_enumerate
s_path->st.st_dev,
s_path->st.st_ino,
dir->d_did,
- dir->d_parent->d_did,
+ dir->d_pdid,
vol->v_stamp);
ad_flush( &ad);
}
}
}
- if ( dir->d_did == DIRDID_ROOT) {
- pdid = DIRDID_ROOT_PARENT;
- } else if (dir->d_did == DIRDID_ROOT_PARENT) {
- pdid = 0;
- } else {
- pdid = dir->d_parent->d_did;
- }
+ pdid = dir->d_pdid;
data = buf;
while ( bitmap != 0 ) {
case DIRPBIT_ATTR :
if ( isad ) {
ad_getattr(&ad, &ashort);
- } else if (invisible_dots(vol, dir->d_u_name)) {
+ } else if (invisible_dots(vol, cfrombstring(dir->d_u_name))) {
ashort = htons(ATTRBIT_INVISIBLE);
} else
ashort = 0;
case DIRPBIT_PDID :
memcpy( data, &pdid, sizeof( pdid ));
data += sizeof( pdid );
+ LOG(log_debug, logtype_afpd, "metadata('%s'): Parent DID: %u",
+ s_path->u_name, ntohl(pdid));
break;
case DIRPBIT_CDATE :
memcpy(data + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
/* dot files are by default visible */
- if (invisible_dots(vol, dir->d_u_name)) {
+ if (invisible_dots(vol, cfrombstring(dir->d_u_name))) {
ashort = htons(FINDERINFO_INVISIBLE);
memcpy(data + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
}
case DIRPBIT_DID :
memcpy( data, &dir->d_did, sizeof( aint ));
data += sizeof( aint );
+ LOG(log_debug, logtype_afpd, "metadata('%s'): DID: %u",
+ s_path->u_name, ntohl(dir->d_did));
break;
case DIRPBIT_OFFCNT :
if ( l_nameoff ) {
ashort = htons( data - buf );
memcpy( l_nameoff, &ashort, sizeof( ashort ));
- data = set_name(vol, data, pdid, dir->d_m_name, dir->d_did, 0);
+ data = set_name(vol, data, pdid, cfrombstring(dir->d_m_name), dir->d_did, 0);
}
if ( utf_nameoff ) {
ashort = htons( data - buf );
memcpy( utf_nameoff, &ashort, sizeof( ashort ));
- data = set_name(vol, data, pdid, dir->d_m_name, dir->d_did, utf8);
+ data = set_name(vol, data, pdid, cfrombstring(dir->d_m_name), dir->d_did, utf8);
}
if ( isad ) {
ad_close_metadata( &ad );
*
* assume path == '\0' eg. it's a directory in canonical form
*/
-
-struct path Cur_Path = {
- 0,
- "", /* mac name */
- ".", /* unix name */
- 0, /* id */
- NULL,/* struct dir */
- 0, /* stat is not set */
-};
-
-/* ------------------ */
-static int set_dir_errors(struct path *path, const char *where, int err)
-{
- switch ( err ) {
- case EPERM :
- case EACCES :
- return AFPERR_ACCESS;
- case EROFS :
- return AFPERR_VLOCK;
- }
- LOG(log_error, logtype_afpd, "setdirparam(%s): %s: %s", fullpathname(path->u_name), where, strerror(err) );
- return AFPERR_PARAM;
-}
-
-/* ------------------ */
-int setdirparams(struct vol *vol,
- struct path *path, u_int16_t d_bitmap, char *buf )
+int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *buf )
{
struct maccess ma;
struct adouble ad;
* to set our name, etc.
*/
if ( (ad_get_HF_flags( &ad ) & O_CREAT)) {
- ad_setname(&ad, curdir->d_m_name);
+ ad_setname(&ad, cfrombstring(curdir->d_m_name));
}
}
if (path->st_valid && !path->st_errno) {
struct stat *st = &path->st;
- if (dir && dir->d_parent) {
- ad_setid(&ad, st->st_dev, st->st_ino, dir->d_did, dir->d_parent->d_did, vol->v_stamp);
+ 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);
if (change_parent_mdate && dir->d_did != DIRDID_ROOT
&& gettimeofday(&tv, NULL) == 0) {
- if (!movecwd(vol, dir->d_parent)) {
+ if (movecwd(vol, dirlookup(vol, dir->d_pdid)) == 0) {
newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
/* be careful with bitmap because now dir is null */
bitmap = 1<<DIRPBIT_MDATE;
if ( fsync(dfd) < 0 )
LOG(log_error, logtype_afpd, "afp_syncdir(%s): %s",
- vol->ad_path(dir->d_u_name, ADFLAGS_DIR), strerror(errno) );
+ vol->ad_path(cfrombstring(dir->d_u_name), ADFLAGS_DIR), strerror(errno) );
close(dfd);
}
if (of_stat(s_path) < 0) {
return AFPERR_MISC;
}
+
curdir->offcnt++;
- if ((dir = adddir( vol, curdir, s_path)) == NULL) {
+
+ if ((dir = dir_add(vol, curdir, s_path, strlen(s_path->u_name))) == NULL) {
return AFPERR_MISC;
}
char *newname)
{
struct adouble ad;
- struct dir *parent;
- char *buf;
- int len, err;
+ int err;
/* existence check moved to afp_moveandrename */
if ( unix_rename(dirfd, src, -1, dst ) < 0 ) {
vol->vfs->vfs_renamedir(vol, dirfd, src, dst);
- len = strlen( newname );
- /* rename() succeeded so we need to update our tree even if we can't open
- * metadata
- */
-
ad_init(&ad, vol->v_adouble, vol->v_ad_options);
if (!ad_open_metadata( dst, ADFLAGS_DIR, 0, &ad)) {
ad_close_metadata( &ad);
}
- dir_hash_del(vol, dir);
- if (dir->d_m_name == dir->d_u_name)
- dir->d_u_name = NULL;
-
- if ((buf = (char *) realloc( dir->d_m_name, len + 1 )) == NULL ) {
- LOG(log_error, logtype_afpd, "renamedir: realloc mac name: %s", strerror(errno) );
- /* FIXME : fatal ? */
+ if (dir_modify(vol, dir, curdir->d_did, 0, newname, dst, curdir->d_fullpath) != 0) {
+ LOG(log_error, logtype_afpd, "renamedir: fatal error from dir_modify: %s -> %s", src, dst);
return AFPERR_MISC;
}
- dir->d_m_name = buf;
- strcpy( dir->d_m_name, newname );
-
- if (newname == dst) {
- free(dir->d_u_name);
- dir->d_u_name = dir->d_m_name;
- }
- else {
- if ((buf = (char *) realloc( dir->d_u_name, strlen(dst) + 1 )) == NULL ) {
- LOG(log_error, logtype_afpd, "renamedir: realloc unix name: %s", strerror(errno) );
- return AFPERR_MISC;
- }
- dir->d_u_name = buf;
- strcpy( dir->d_u_name, dst );
- }
-
- if (dir->d_m_name_ucs2)
- free(dir->d_m_name_ucs2);
-
- dir->d_m_name_ucs2 = NULL;
- if ((size_t)-1 == convert_string_allocate((utf8_encoding())?CH_UTF8_MAC:vol->v_maccharset, CH_UCS2, dir->d_m_name, -1, (char**)&dir->d_m_name_ucs2))
- dir->d_m_name_ucs2 = NULL;
-
- if (( parent = dir->d_parent ) == NULL ) {
- return( AFP_OK );
- }
- if ( parent == newparent ) {
- hash_alloc_insert(vol->v_hash, dir, dir);
- return( AFP_OK );
- }
- /* detach from old parent and add to new one. */
- dirchildremove(parent, dir);
- dir->d_parent = newparent;
- dirchildadd(vol, newparent, dir);
return( AFP_OK );
}
u_int16_t ashort;
int err;
- if ( curdir->d_parent == NULL ) {
+ if ( dirlookup(vol, curdir->d_pdid) == NULL ) {
return( AFPERR_ACCESS );
}
}
}
- if ( movecwd( vol, curdir->d_parent ) < 0 ) {
+ if ( movecwd(vol, dirlookup(vol, curdir->d_pdid)) < 0 ) {
err = afp_errno;
goto delete_done;
}
- err = netatalk_rmdir_all_errors(-1, fdir->d_u_name);
+ err = netatalk_rmdir_all_errors(-1, cfrombstring(fdir->d_u_name));
if ( err == AFP_OK || err == AFPERR_NOOBJ) {
- dirchildremove(curdir, fdir);
cnid_delete(vol->v_cdb, fdir->d_did);
dir_remove( vol, fdir );
}
/*
- * $Id: directory.h,v 1.34 2010-03-12 15:16:49 franklahm Exp $
+ * $Id: directory.h,v 1.34 2010/03/12 15:16:49 franklahm Exp $
*
* Copyright (c) 1990,1991 Regents of The University of Michigan.
* All Rights Reserved.
#include "globals.h"
#include "volume.h"
-#define DIRTREE_COLOR_RED 0
-#define DIRTREE_COLOR_BLACK 1
-
#define DIRF_FSMASK (3<<0)
#define DIRF_NOFS (0<<0)
#define DIRF_AFS (1<<0)
#define DIRF_UFS (2<<0)
-#define DIRF_OFFCNT (1<<4) /* offsprings count is valid */
-#define DIRF_CNID (1<<5) /* renumerate id */
+#define DIRF_OFFCNT (1<<4) /* offsprings count is valid */
+#define DIRF_CNID (1<<5) /* renumerate id */
+#define DIRF_CACHELOCK (1<<6) /* lock in cache, don't remove in dircache_eviction, for catsearch */
#define AFPDIR_READ (1<<0)
#define FILDIRBIT_ISDIR (1 << 7) /* is a directory */
#define FILDIRBIT_ISFILE (0) /* is a file */
-/* reserved directory id's */
-#define DIRDID_ROOT_PARENT htonl(1) /* parent directory of root */
-#define DIRDID_ROOT htonl(2) /* root directory */
-
/* file/directory ids. what a mess. we scramble things in a vain attempt
* to get something meaningful */
#ifndef AFS
#define CNID(a,b) (((a)->st_ino & 0x7fffffff) | CNID_FILE(b))
#endif /* AFS */
-
struct maccess {
u_char ma_user;
u_char ma_world;
#define AR_UWRITE (1<<2)
#define AR_UOWN (1<<7)
-extern struct dir *dirnew (const char *, const char *);
-extern void dirfreename (struct dir *);
-extern void dirfree (struct dir *);
-extern struct dir *dirsearch (const struct vol *, u_int32_t);
-extern struct dir *dirlookup (struct vol *, u_int32_t);
-extern struct dir *dirsearch_byname (const struct vol *, struct dir *,char *);
-
-extern struct dir *adddir (struct vol *, struct dir *,
- struct path *);
-
-extern int movecwd (struct vol *, struct dir *);
-extern int deletecurdir (struct vol *);
-extern struct path *cname (struct vol *, struct dir *,
- char **);
-extern mode_t mtoumode (struct maccess *);
-extern void utommode (struct stat *, struct maccess *);
-extern int getdirparams (const struct vol *, u_int16_t, struct path *,
- struct dir *, char *, size_t *);
-extern int setdirparams (struct vol *, struct path *, u_int16_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 int dirreenumerate (struct dir *dir, struct stat *st);
-
typedef int (*dir_loop)(struct dirent *, char *, void *);
-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 netatalk_unlink (const char *name);
+extern struct dir *dir_new(const char *mname, const char *uname, const struct vol *,
+ cnid_t pdid, cnid_t did, bstring fullpath); /* volume.c needs it once */
+extern void dir_free (struct dir *);
+extern struct dir *dir_add(const struct vol *, const struct dir *, struct path *, int);
+extern int dir_modify(const struct vol *vol, struct dir *dir, cnid_t pdid, cnid_t did,
+ const char *new_mname, const char *new_uname, bstring pdir_fullpath);
+extern int dir_remove(const struct vol *vol, struct dir *dir);
+extern struct dir *dirlookup (const struct vol *, cnid_t);
+extern int movecwd (const struct vol *, struct dir *);
+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 *,
+ struct dir *, char *, size_t *);
-extern int caseenumerate (const struct vol *, struct path *, struct dir *);
+extern int setdirparams(struct vol *, struct path *, u_int16_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 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 netatalk_unlink (const char *name);
+extern int caseenumerate (const struct vol *, struct path *, struct dir *);
-extern hash_t *dirhash (void);
/* from enumerate.c */
-extern char *check_dirent (const struct vol *, char *);
+extern char *check_dirent (const struct vol *, char *);
/* FP functions */
int afp_createdir (AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen);
/*
- * $Id: enumerate.c,v 1.49 2010-02-10 14:05:37 franklahm Exp $
+ * $Id: enumerate.c,v 1.49 2010/02/10 14:05:37 franklahm Exp $
*
* Copyright (c) 1990,1993 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
#include <atalk/adouble.h>
#include <atalk/vfs.h>
#include <atalk/cnid.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
+
#include "desktop.h"
#include "directory.h"
+#include "dircache.h"
#include "volume.h"
#include "globals.h"
#include "file.h"
return path_error(o_path, AFPERR_NODIR );
}
- LOG(log_debug, logtype_afpd, "enumerate(vid:%u, did:%u, name:'%s', f/d:%04x/%04x, rc:%u, i:%u, max:%u)",
- ntohs(vid), ntohl(did), o_path->u_name, fbitmap, dbitmap, reqcnt, sindex, maxsz);
+ LOG(log_debug, logtype_afpd, "enumerate(vid:%u, did:%u, cwddid:%u, cwd:'%s', name:'%s', f/d:%04x/%04x, rc:%u, i:%u, max:%u)",
+ ntohs(vid), ntohl(did), ntohl(curdir->d_did),
+ cfrombstring(curdir->d_fullpath), 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 */
if ( dbitmap == 0 ) {
continue;
}
- dir = dirsearch_byname(vol, curdir, s_path.u_name);
- if (!dir && NULL == (dir = adddir( vol, curdir, &s_path) ) ) {
+ int len = strlen(s_path.u_name);
+ if ((dir = dircache_search_by_name(vol, curdir, s_path.u_name, len)) == NULL) {
+ if ((dir = dir_add(vol, curdir, &s_path, len)) == NULL) {
+ LOG(log_error, logtype_afpd, "enumerate(vid:%u, did:%u, name:'%s'): error adding dir: '%s'",
+ ntohs(vid), ntohl(did), o_path->u_name, s_path.u_name);
return AFPERR_MISC;
}
- if (AFP_OK != ( ret = getdirparams(vol, dbitmap, &s_path, dir,
- data + header , &esz ))) {
- return( ret );
}
+ if ((ret = getdirparams(vol, dbitmap, &s_path, dir, data + header , &esz)) != AFP_OK)
+ return( ret );
} else {
if ( fbitmap == 0 ) {
/*
- * $Id: file.c,v 1.141 2010-03-12 15:16:49 franklahm Exp $
+ * $Id: file.c,v 1.141 2010/03/12 15:16:49 franklahm Exp $
*
* Copyright (c) 1990,1993 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
(1 << FILPBIT_UNIXPR)))
/* -------------------------- */
-u_int32_t get_id(struct vol *vol, struct adouble *adp, const struct stat *st,
+u_int32_t get_id(const struct vol *vol, struct adouble *adp, const struct stat *st,
const cnid_t did, char *upath, const int len)
{
u_int32_t adcnid;
struct stat *st;
struct maccess ma;
-#ifdef DEBUG
- LOG(log_debug9, logtype_afpd, "begin getmetadata:");
-#endif /* DEBUG */
upath = path->u_name;
st = &path->st;
#endif
memcpy(data, &ashort, sizeof( ashort ));
data += sizeof( ashort );
+ LOG(log_debug, logtype_afpd, "metadata('%s'): AFP Attributes: %04x",
+ path->u_name, ntohs(ashort));
break;
case FILPBIT_PDID :
memcpy(data, &dir->d_did, sizeof( u_int32_t ));
data += sizeof( u_int32_t );
+ LOG(log_debug, logtype_afpd, "metadata('%s'): Parent DID: %u",
+ path->u_name, ntohl(dir->d_did));
break;
case FILPBIT_CDATE :
case FILPBIT_FNUM :
memcpy(data, &id, sizeof( id ));
data += sizeof( id );
+ LOG(log_debug, logtype_afpd, "metadata('%s'): CNID: %u",
+ path->u_name, ntohl(id));
break;
case FILPBIT_DFLEN :
int opened = 0;
int rc;
-#ifdef DEBUG
- LOG(log_debug9, logtype_default, "begin getfilparams:");
-#endif /* DEBUG */
-
opened = PARAM_NEED_ADP(bitmap);
adp = NULL;
if ( adp ) {
ad_close_metadata( adp);
}
-#ifdef DEBUG
- LOG(log_debug9, logtype_afpd, "end getfilparams:");
-#endif /* DEBUG */
return( rc );
}
}
if (NULL == ( dir = dirlookup( vol, id )) ) {
+ if (afp_errno == AFPERR_NOOBJ) {
+ err = AFPERR_NOOBJ;
+ goto delete;
+ }
return( AFPERR_PARAM );
}
else if (S_ISDIR(st.st_mode)) /* directories are bad */
return AFPERR_BADTYPE;
+delete:
if (cnid_delete(vol->v_cdb, fileid)) {
switch (errno) {
case EROFS:
/*
- * $Id: file.h,v 1.26 2010-03-12 15:16:49 franklahm Exp $
+ * $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.
extern size_t mtoUTF8 (const struct vol *, const char *, size_t , char *, size_t );
extern int copy_path_name (const struct vol *, char *, char *i);
-extern u_int32_t get_id (struct vol *, struct adouble *, const struct stat *,
+extern u_int32_t get_id (const struct vol *, struct adouble *, const struct stat *,
const cnid_t , char *, const int );
/* FP functions */
/*
- * $Id: filedir.c,v 1.73 2010-03-12 15:16:49 franklahm Exp $
+ * $Id: filedir.c,v 1.73 2010/03/12 15:16:49 franklahm Exp $
*
* Copyright (c) 1990,1993 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
#include <atalk/cnid.h>
#include <atalk/logger.h>
#include <atalk/unix.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
#include "directory.h"
#include "desktop.h"
#ifdef DROPKLUDGE
int matchfile2dirperms(
/* Since it's kinda' big; I decided against an
-inline function */
- char *upath,
+ inline function */
+ char *upath,
struct vol *vol,
- int did)
+ 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 */
+ fixing dropboxes. It has known security problem. See the netatalk FAQ for
+ more information */
{
- struct stat st, sb;
- struct dir *dir;
- char *adpath;
+ 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
+#endif
if (stat(upath, &st ) < 0) {
LOG(log_error, logtype_afpd, "Could not stat %s: %s", upath, strerror(errno));
adpath, strerror(errno));
ret = AFPERR_ACCESS;
}
- seteuid(uid);
+ seteuid(uid);
}
} /* end else if stat success */
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;
+ struct stat *st;
+ struct vol *vol;
+ struct dir *dir;
u_int32_t did;
- int ret;
- size_t buflen;
- u_int16_t fbitmap, dbitmap, vid;
+ int ret;
+ size_t buflen;
+ u_int16_t fbitmap, dbitmap, vid;
struct path *s_path;
*rbuflen = 0;
if (NULL == ( vol = getvolbyvid( vid )) ) {
/* was AFPERR_PARAM but it helps OS 10.3 when a volume has been removed
* from the list.
- */
+ */
return( AFPERR_ACCESS );
}
ibuf += sizeof( dbitmap );
if (NULL == ( s_path = cname( vol, dir, &ibuf )) ) {
- return get_afp_errno(AFPERR_NOOBJ);
+ return get_afp_errno(AFPERR_NOOBJ);
}
- LOG(log_debug, logtype_afpd, "getfildirparams(vid:%u, did:%u, name:'%s', f/d:%04x/%04x) {cwd: %s}",
- ntohs(vid), ntohl(dir->d_did), s_path->u_name, fbitmap, dbitmap, getcwdpath());
+ LOG(log_debug, logtype_afpd, "getfildirparams(vid:%u, did:%u, f/d:%04x/%04x) {cwdid:%u, cwd: %s, name:'%s'}",
+ ntohs(vid), ntohl(dir->d_did), fbitmap, dbitmap,
+ ntohl(curdir->d_did), cfrombstring(curdir->d_fullpath), s_path->u_name);
st = &s_path->st;
if (!s_path->st_valid) {
of_statdir(vol, s_path);
}
if ( s_path->st_errno != 0 ) {
- return( AFPERR_NOOBJ );
+ if (afp_errno != AFPERR_ACCESS) {
+ return( AFPERR_NOOBJ );
+ }
}
if (S_ISDIR(st->st_mode)) {
if (dbitmap) {
dir = s_path->d_dir;
- if (!dir)
+ if (!dir)
return AFPERR_NOOBJ;
ret = getdirparams(vol, dbitmap, s_path, dir,
- rbuf + 3 * sizeof( u_int16_t ), &buflen );
+ rbuf + 3 * sizeof( u_int16_t ), &buflen );
if (ret != AFP_OK )
return( ret );
}
/* this is a directory */
*(rbuf + 2 * sizeof( u_int16_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(vol, fbitmap, s_path, curdir,
+ rbuf + 3 * sizeof( u_int16_t ), &buflen )) ) {
return( ret );
}
/* this is a file */
int afp_setfildirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
{
- struct stat *st;
- struct vol *vol;
- struct dir *dir;
+ struct stat *st;
+ struct vol *vol;
+ struct dir *dir;
struct path *path;
- u_int16_t vid, bitmap;
- int did, rc;
+ u_int16_t vid, bitmap;
+ int did, rc;
*rbuflen = 0;
ibuf += 2;
ibuf += sizeof( did);
if (NULL == ( dir = dirlookup( vol, did )) ) {
- return afp_errno;
+ return afp_errno;
}
memcpy( &bitmap, ibuf, sizeof( bitmap ));
ibuf += sizeof( bitmap );
if (NULL == ( path = cname( vol, dir, &ibuf ))) {
- return get_afp_errno(AFPERR_NOOBJ);
+ return get_afp_errno(AFPERR_NOOBJ);
}
st = &path->st;
}
if ( path->st_errno != 0 ) {
- return( AFPERR_NOOBJ );
+ if (afp_errno != AFPERR_ACCESS)
+ return( AFPERR_NOOBJ );
}
/*
* If ibuf is odd, make it even.
return( rc );
}
-/* --------------------------------------------
+/* --------------------------------------------
Factorise some checks on a pathname
*/
int check_name(const struct vol *vol, char *name)
}
} else {
id = sdir->d_did; /* we already have the CNID */
- p = ctoupath( vol, sdir->d_parent, oldname );
+ p = ctoupath( vol, dirlookup(vol, sdir->d_pdid), oldname );
if (!p) {
return AFPERR_PARAM;
}
adflags = ADFLAGS_DIR;
}
-
/*
* p now points to either
* a) full pathname of the source fs object (if renameat is not available)
ad_getattr(adp, &bshort);
ad_close_metadata( adp);
- if ((bshort & htons(ATTRBIT_NORENAME)))
+ if ((bshort & htons(ATTRBIT_NORENAME)))
return(AFPERR_OLOCK);
}
if (sdir_fd != -1) {
}
}
- if (NULL == (upath = mtoupath(vol, newname, curdir->d_did, utf8_encoding()))){
+ if (NULL == (upath = mtoupath(vol, newname, curdir->d_did, utf8_encoding()))){
return AFPERR_PARAM;
}
path.u_name = upath;
- st = &path.st;
+ st = &path.st;
if (0 != (rc = check_name(vol, upath))) {
- return rc;
+ return rc;
}
/* source == destination. we just silently accept this. */
- if ((!isdir && curdir == sdir) || (isdir && curdir == sdir->d_parent)) {
+ if ((!isdir && curdir == sdir) || (isdir && curdir->d_did == sdir->d_pdid)) {
if (strcmp(oldname, newname) == 0)
return AFP_OK;
/* -------------------------------------------- */
int afp_rename(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
{
- struct vol *vol;
- struct dir *sdir;
+ struct vol *vol;
+ struct dir *sdir;
char *oldname, *newname;
struct path *path;
- u_int32_t did;
+ u_int32_t did;
int plen;
- u_int16_t vid;
+ u_int16_t vid;
int isdir = 0;
int rc;
memcpy( &did, ibuf, sizeof( did ));
ibuf += sizeof( did );
if (NULL == ( sdir = dirlookup( vol, did )) ) {
- return afp_errno;
+ return afp_errno;
}
/* source pathname */
if (NULL == ( path = cname( vol, sdir, &ibuf )) ) {
- return get_afp_errno(AFPERR_NOOBJ);
+ return get_afp_errno(AFPERR_NOOBJ);
}
sdir = curdir;
}
}
else {
- if ( sdir->d_parent == NULL ) { /* root directory */
+ if ( sdir->d_did == DIRDID_ROOT ) { /* root directory */
return( AFPERR_NORENAME );
}
/* move to destination dir */
- if ( movecwd( vol, sdir->d_parent ) < 0 ) {
+ if ( movecwd( vol, dirlookup(vol, sdir->d_pdid) ) < 0 ) {
return afp_errno;
}
- strcpy(oldname, sdir->d_m_name);
+ memcpy(oldname, cfrombstring(sdir->d_m_name), blength(sdir->d_m_name) +1);
}
/* another place where we know about the path type */
/* ------------------------------- */
int afp_delete(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
{
- struct vol *vol;
- struct dir *dir;
+ struct vol *vol;
+ struct dir *dir;
struct path *s_path;
- char *upath;
- int did, rc;
- u_int16_t vid;
+ char *upath;
+ int did, rc;
+ u_int16_t vid;
*rbuflen = 0;
ibuf += 2;
memcpy( &did, ibuf, sizeof( did ));
ibuf += sizeof( int );
+
if (NULL == ( dir = dirlookup( vol, did )) ) {
- return afp_errno;
+ return afp_errno;
}
if (NULL == ( s_path = cname( vol, dir, &ibuf )) ) {
- return get_afp_errno(AFPERR_NOOBJ);
+ return get_afp_errno(AFPERR_NOOBJ);
}
upath = s_path->u_name;
if ( path_isadir( s_path) ) {
- if (*s_path->m_name != '\0') {
- rc = AFPERR_ACCESS;
- }
- else {
+ if (*s_path->m_name != '\0' || curdir->d_did == DIRDID_ROOT)
+ rc = AFPERR_ACCESS;
+ else
rc = deletecurdir( vol);
- }
} else if (of_findname(s_path)) {
rc = AFPERR_BUSY;
} else {
}
}
if ( rc == AFP_OK ) {
- curdir->offcnt--;
+ curdir->offcnt--;
setvoltime(obj, vol );
}
/* ------------------------ */
char *absupath(const struct vol *vol, struct dir *dir, char *u)
{
- struct dir *d;
- static char path[ MAXPATHLEN + 1];
- char *p;
- int len;
+ static char pathbuf[MAXPATHLEN + 1];
+ bstring path;
- if (u == NULL)
+ if (u == NULL || dir == NULL || vol == NULL)
return NULL;
-
- p = path + sizeof( path ) - 1;
- *p = '\0';
- len = strlen( u );
- p -= len;
- memcpy( p, u, len );
- if (dir) for ( d = dir; d->d_parent; d = d->d_parent ) {
- u = d->d_u_name;
- len = strlen( u );
- if (p -len -1 < path) {
- /* FIXME
- rather rare so LOG error and/or client message ?
- */
- return NULL;
- }
- *--p = '/';
- p -= len;
- memcpy( p, u, len );
- }
- len = strlen( vol->v_path );
- if (p -len -1 < path) {
+
+ if ((path = bstrcpy(dir->d_fullpath)) == NULL)
return NULL;
- }
- *--p = '/';
- p -= len;
- memcpy( p, vol->v_path, len );
+ if (bcatcstr(path, "/") != BSTR_OK)
+ return NULL;
+ if (bcatcstr(path, u) != BSTR_OK)
+ return NULL;
+ if (path->slen > MAXPATHLEN)
+ return NULL;
+
+ LOG(log_debug, logtype_afpd, "absupath: %s", cfrombstring(path));
- return( p );
+ strncpy(pathbuf, cfrombstring(path), blength(path) + 1);
+ bdestroy(path);
+
+ return(pathbuf);
}
-/* ------------------------
- * FIXME dir could be NULL
-*/
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()));
}
/* ------------------------- */
int afp_moveandrename(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
{
- struct vol *vol;
- struct dir *sdir, *ddir;
+ struct vol *vol;
+ struct dir *sdir, *ddir;
int isdir;
- char *oldname, *newname;
+ char *oldname, *newname;
struct path *path;
- int did;
- int pdid;
+ int did;
+ int pdid;
int plen;
- u_int16_t vid;
+ u_int16_t vid;
int rc;
#ifdef DROPKLUDGE
- int retvalue;
+ int retvalue;
#endif /* DROPKLUDGE */
int sdir_fd = -1;
/* source pathname */
if (NULL == ( path = cname( vol, sdir, &ibuf )) ) {
- return get_afp_errno(AFPERR_NOOBJ);
+ return get_afp_errno(AFPERR_NOOBJ);
}
sdir = curdir;
newname = obj->newtmp;
oldname = obj->oldtmp;
-
+
isdir = path_isadir(path);
if ( *path->m_name != '\0' ) {
if (isdir) {
}
strcpy(oldname, path->m_name); /* an extra copy for of_rename */
} else {
- strcpy(oldname, sdir->d_m_name);
+ memcpy(oldname, cfrombstring(sdir->d_m_name), blength(sdir->d_m_name) + 1);
}
#ifdef HAVE_RENAMEAT
}
/* This does the work */
+ LOG(log_debug, logtype_afpd, "afp_move(oldname:'%s', newname:'%s', isdir:%u)",
+ oldname, newname, isdir);
rc = moveandrename(vol, sdir, sdir_fd, oldname, newname, isdir);
if ( rc == AFP_OK ) {
char *upath = mtoupath(vol, newname, pdid, utf8_encoding());
-
+
if (NULL == upath) {
rc = AFPERR_PARAM;
goto exit;
* otherwise, 0 is returned.
*/
{
- int i; /* index to veto_str */
- int j; /* index to path */
+ int i; /* index to veto_str */
+ int j; /* index to path */
if ((veto_str == NULL) || (path == NULL))
return 0;
} else {
if (veto_str[i] != path[j]) {
while ((veto_str[i] != '/')
- && (veto_str[i] != '\0'))
+ && (veto_str[i] != '\0'))
i++;
j = 0;
continue;
/*
- * $Id: globals.h,v 1.33 2010-03-29 15:22:57 franklahm Exp $
+ * $Id: globals.h,v 1.33 2010/03/29 15:22:57 franklahm Exp $
*
* Copyright (c) 1990,1993 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
};
struct afp_options {
- int connections, transports, tickleval, timeout, server_notif, flags;
+ int connections, transports, tickleval, timeout, server_notif, flags, dircachesize;
unsigned char passwdbits, passwdminlen, loginmaxfail;
u_int32_t server_quantum;
char hostname[MAXHOSTNAMELEN + 1], *server, *ipaddr, *port, *configfile;
extern const char *AfpNum2name (int );
extern const char *AfpErr2name(int err);
+/* directory.c */
+extern struct dir rootParent;
+
#ifndef NO_DDP
extern void afp_over_asp (AFPObj *);
#endif /* NO_DDP */
/*
- * $Id: mangle.c,v 1.19 2006-09-19 01:35:45 didg Exp $
+ * $Id: mangle.c,v 1.19.4.2 2010-02-01 14:25:45 franklahm Exp $
*
* Copyright (c) 2002. Joe Marcus Clarke (marcus@marcuscom.com)
* All Rights Reserved. See COPYRIGHT.
#include <stdio.h>
#include <ctype.h>
+
+#include <atalk/util.h>
+#include <atalk/bstradd.h>
+
#include "mangle.h"
#include "desktop.h"
-#include <atalk/util.h>
+
#define hextoint( c ) ( isdigit( c ) ? c - '0' : c + 10 - 'A' )
#define isuxdigit(x) (isdigit(x) || (isupper(x) && isxdigit(x)))
return 0;
}
-static char *demangle_checks ( const struct vol *vol, char* uname, char * mfilename, size_t prefix, char * ext)
+static char *demangle_checks(const struct vol *vol, char* uname, char * mfilename, size_t prefix, char * ext)
{
u_int16_t flags;
static char buffer[MAXPATHLEN +2]; /* for convert_charset dest_len parameter +2 */
/* We need to check, whether we really need to demangle the filename */
/* i.e. it's not just a file with a valid #HEX in the name ... */
/* but we don't want to miss valid demangle as well. */
-
/* check whether file extensions match */
- {
- char buf[MAX_EXT_LENGTH + 2]; /* for convert_charset dest_len parameter +2 */
- size_t ext_len = mangle_extension(vol, uname, buf, CH_UTF8_MAC);
- if (ext_len) {
- buf[ext_len] = '\0';
- if (strcmp(ext, buf)) return mfilename;
- } else {
- if (*ext) return mfilename;
- }
+ char buf[MAX_EXT_LENGTH + 2]; /* for convert_charset dest_len parameter +2 */
+ size_t ext_len = mangle_extension(vol, uname, buf, CH_UTF8_MAC);
+
+ if (ext_len) {
+ buf[ext_len] = '\0';
+ if (strcmp(ext, buf))
+ return mfilename;
+ } else {
+ if (*ext)
+ return mfilename;
}
/* First we convert the unix name to our volume maccharset */
}
/* is it a dir?, there's a conflict with pre OSX 'trash #2' */
- if ((dir = dirsearch(vol, id))) {
- if (dir->d_parent && dir->d_parent->d_did != did) {
+ if ((dir = dirlookup(vol, id))) {
+ if (dir->d_pdid != did) {
/* not in the same folder, there's a race with outdate cache
* but we have to live with it, hopefully client will recover
*/
}
if (!osx) {
/* it's not from cname so mfilename and dir must be the same */
- if (!strcmp(dir->d_m_name, mfilename)) {
- return dir->d_u_name;
+ if (strcmp(cfrombstring(dir->d_m_name), mfilename) == 0) {
+ return cfrombstring(dir->d_u_name);
}
- }
- else {
- return demangle_checks (vol, dir->d_u_name, mfilename, prefix, t);
- }
+ } else {
+ return demangle_checks(vol, cfrombstring(dir->d_u_name), mfilename, prefix, t);
+ }
}
else if (NULL != (u_name = cnid_resolve(vol->v_cdb, &id, buffer, len)) ) {
if (id != did) {
/*
- * $Id: ofork.c,v 1.32 2010-03-12 15:16:49 franklahm Exp $
+ * $Id: ofork.c,v 1.32 2010/03/12 15:16:49 franklahm Exp $
*
* Copyright (c) 1996 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
#include <string.h>
#include <sys/stat.h> /* works around a bug */
#include <sys/param.h>
-#include <atalk/logger.h>
#include <errno.h>
+#include <atalk/logger.h>
#include <atalk/util.h>
+#include <atalk/bstrlib.h>
+#include <atalk/bstradd.h>
#include "globals.h"
#include "volume.h"
#define OFORK_HASHSIZE 64
static struct ofork *ofork_table[OFORK_HASHSIZE];
-static struct ofork **oforks = NULL;
-static int nforks = 0;
-static u_short lastrefnum = 0;
+static struct ofork **oforks = NULL;
+static int nforks = 0;
+static u_short lastrefnum = 0;
/* OR some of each character for the hash*/
while (*name) {
i = ((i << 4) | (8*sizeof(i) - 4)) ^ *name++;
}
-#endif
+#endif
return key->inode & (OFORK_HASHSIZE - 1);
}
#ifdef DEBUG1
void of_pforkdesc( FILE *f)
{
- int ofrefnum;
+ int ofrefnum;
if (!oforks)
return;
int of_flush(const struct vol *vol)
{
- int refnum;
+ int refnum;
if (!oforks)
return 0;
for ( refnum = 0; refnum < nforks; refnum++ ) {
if (oforks[ refnum ] != NULL && (oforks[refnum]->of_vol == vol) &&
- flushfork( oforks[ refnum ] ) < 0 ) {
+ flushfork( oforks[ refnum ] ) < 0 ) {
LOG(log_error, logtype_afpd, "of_flush: %s", strerror(errno) );
}
}
if (!s_of)
return AFP_OK;
-
+
next = ofork_table[hashfn(&s_of->key)];
while ((of = next)) {
next = next->next; /* so we can unhash and still be all right. */
if (vol == of->of_vol && olddir == of->of_dir &&
- 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);
- done = 1;
- }
+ 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);
+ done = 1;
+ }
if (newdir != olddir) {
of->of_d_prev->of_d_next = of->of_d_next;
of->of_d_next->of_d_prev = of->of_d_prev;
if (of->of_dir->d_ofork == of) {
of->of_dir->d_ofork = (of == of->of_d_next) ? NULL : of->of_d_next;
- }
+ }
of->of_dir = newdir;
if (!(d_ofork = newdir->d_ofork)) {
newdir->d_ofork = of;
return AFP_OK;
}
-#define min(a,b) ((a)<(b)?(a):(b))
+#define min(a,b) ((a)<(b)?(a):(b))
struct ofork *
of_alloc(struct vol *vol,
- struct dir *dir,
- char *path,
- u_int16_t *ofrefnum,
- const int eid,
- struct adouble *ad,
- struct stat *st)
+ struct dir *dir,
+ char *path,
+ u_int16_t *ofrefnum,
+ const int eid,
+ struct adouble *ad,
+ struct stat *st)
{
struct ofork *of, *d_ofork;
- u_int16_t refnum, of_refnum;
+ u_int16_t refnum, of_refnum;
- int i;
+ int i;
if (!oforks) {
nforks = getdtablesize() - 10;
- /* protect against insane ulimit -n */
+ /* protect against insane ulimit -n */
nforks = min(nforks, 0xffff);
oforks = (struct ofork **) calloc(nforks, sizeof(struct ofork *));
if (!oforks)
}
}
/* grr, Apple and their 'uniquely identifies'
- the next line is a protection against
- of_alloc()
- refnum % nforks = 3
- lastrefnum = 3
- oforks[3] != NULL
- refnum = 4
- oforks[4] == NULL
- return 4
-
- close(oforks[4])
-
- of_alloc()
- refnum % nforks = 4
- ...
- return 4
- same if lastrefnum++ rather than ++lastrefnum.
+ the next line is a protection against
+ of_alloc()
+ refnum % nforks = 3
+ lastrefnum = 3
+ oforks[3] != NULL
+ refnum = 4
+ oforks[4] == NULL
+ return 4
+
+ close(oforks[4])
+
+ of_alloc()
+ refnum % nforks = 4
+ ...
+ return 4
+ same if lastrefnum++ rather than ++lastrefnum.
*/
lastrefnum = refnum;
if ( i == nforks ) {
of_refnum = refnum % nforks;
if (( oforks[ of_refnum ] =
- (struct ofork *)malloc( sizeof( struct ofork ))) == NULL ) {
+ (struct ofork *)malloc( sizeof( struct ofork ))) == NULL ) {
LOG(log_error, logtype_afpd, "of_alloc: malloc: %s", strerror(errno) );
return NULL;
}
}
/* -------------------------- */
-int of_stat (struct path *path)
+int of_stat(struct path *path)
{
-int ret;
+ int ret;
+
path->st_errno = 0;
path->st_valid = 1;
- if ((ret = lstat(path->u_name, &path->st)) < 0)
+
+ if ((ret = lstat(path->u_name, &path->st)) < 0) {
+ LOG(log_debug, logtype_afpd, "of_stat('%s/%s': %s)",
+ cfrombstring(curdir->d_fullpath), path->u_name, strerror(errno));
path->st_errno = errno;
- return ret;
+ }
+
+ return ret;
}
+
#ifdef HAVE_RENAMEAT
int of_fstatat(int dirfd, struct path *path)
{
stat(".") works even if "." is deleted thus
we have to stat ../name because we want to know if it's there
*/
-int of_statdir (struct vol *vol, struct path *path)
+int of_statdir(struct vol *vol, struct path *path)
{
-static char pathname[ MAXPATHLEN + 1] = "../";
-int ret;
+ static char pathname[ MAXPATHLEN + 1] = "../";
+ int ret;
+ size_t len;
+ struct dir *dir;
if (*path->m_name) {
/* not curdir */
path->st_errno = 0;
path->st_valid = 1;
/* FIXME, what about: we don't have r-x perm anymore ? */
- strlcpy(pathname +3, path->d_dir->d_u_name, sizeof (pathname) -3);
+ len = blength(path->d_dir->d_u_name);
+ if (len > (MAXPATHLEN - 3))
+ len = MAXPATHLEN - 3;
+ strncpy(pathname + 3, cfrombstring(path->d_dir->d_u_name), len + 1);
+
+ LOG(log_debug, logtype_afpd, "of_statdir: stating: '%s'", pathname);
if (!(ret = lstat(pathname, &path->st)))
return 0;
-
+
path->st_errno = errno;
+
/* hmm, can't stat curdir anymore */
- if (errno == EACCES && curdir->d_parent ) {
- if (movecwd(vol, curdir->d_parent))
+ if (errno == EACCES && (dir = dirlookup(vol, curdir->d_pdid))) {
+ if (movecwd(vol, dir))
return -1;
path->st_errno = 0;
- if ((ret = lstat(path->d_dir->d_u_name, &path->st)) < 0)
+
+ if ((ret = lstat(cfrombstring(path->d_dir->d_u_name), &path->st)) < 0)
path->st_errno = errno;
}
+
return ret;
}
{
struct ofork *of;
struct file_key key;
-
+
if (!path->st_valid) {
- of_stat(path);
+ of_stat(path);
}
-
+
if (path->st_errno)
return NULL;
int of_closefork(struct ofork *ofork)
{
struct timeval tv;
- int adflags, doflush = 0;
+ int adflags, doflush = 0;
int ret;
adflags = 0;
if ((ofork->of_flags & AFPFORK_DATA) && (ad_data_fileno( ofork->of_ad ) != -1)) {
- adflags |= ADFLAGS_DF;
+ adflags |= ADFLAGS_DF;
}
if ( (ofork->of_flags & AFPFORK_OPEN) && ad_reso_fileno( ofork->of_ad ) != -1 ) {
adflags |= ADFLAGS_HF;
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++;
+ doflush++;
}
if ( doflush ) {
- ad_flush( ofork->of_ad );
+ ad_flush( ofork->of_ad );
}
}
}
if ( ad_close( ofork->of_ad, adflags ) < 0 ) {
ret = -1;
}
-
+
of_dealloc( ofork );
return ret;
}
/* ----------------------
-*/
+ */
struct adouble *of_ad(const struct vol *vol, struct path *path, struct adouble *ad)
{
struct ofork *of;
return adp;
}
-/* ----------------------
+/* ----------------------
close all forks for a volume
*/
void of_closevol(const struct vol *vol)
{
- int refnum;
+ int refnum;
if (!oforks)
return;
/*
- * $Id: volume.c,v 1.127 2010-04-16 18:28:45 franklahm Exp $
+ * $Id$
*
* Copyright (c) 1990,1993 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
options[VOLOPT_FLAGS].i_value &= ~AFPVOL_CACHE;
else if (strcasecmp(p, "tm") == 0)
options[VOLOPT_FLAGS].i_value |= AFPVOL_TM;
-
+/* Found this in branch dir-rewrite, maybe we want to use it sometimes */
+#if 0
+ else if (strcasecmp(p, "cdrom") == 0)
+ options[VOLOPT_FLAGS].i_value |= AFPVOL_CDROM | AFPVOL_RO;
+#endif
p = strtok(NULL, ",");
}
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
+
volume->v_cdb = cnid_open(volume->v_dbpath ? volume->v_dbpath : volume->v_path,
volume->v_umask,
volume->v_cnidscheme,
volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
volume->v_cnidport ? volume->v_cnidport : Cnid_port);
- if (!volume->v_cdb) {
+
+ if ( ! volume->v_cdb && ! (flags & CNID_FLAG_MEMORY)) {
+ /* The first attempt failed and it wasn't yet an attempt to open in-memory */
flags |= CNID_FLAG_MEMORY;
LOG(log_error, logtype_afpd, "Reopen volume %s using in memory temporary CNID DB.", volume->v_path);
volume->v_cdb = cnid_open (volume->v_path, volume->v_umask, "tdb", flags, NULL, NULL);
volume->max_filename = MACFILELEN;
}
- volume->v_dir = volume->v_root = NULL;
- volume->v_hash = NULL;
-
volume->v_flags |= AFPVOL_OPEN;
volume->v_cdb = NULL;
else if (*(vol_uname + 1) != '\0')
vol_uname++;
- if ((dir = dirnew(vol_mname, vol_uname) ) == NULL) {
+ if ((dir = dir_new(vol_mname,
+ vol_uname,
+ volume,
+ DIRDID_ROOT_PARENT,
+ DIRDID_ROOT,
+ bfromcstr(volume->v_path))
+ ) == NULL) {
free(vol_mname);
LOG(log_error, logtype_afpd, "afp_openvol(%s): malloc: %s", volume->v_path, strerror(errno) );
ret = AFPERR_MISC;
}
free(vol_mname);
- dir->d_did = DIRDID_ROOT;
- dir->d_color = DIRTREE_COLOR_BLACK; /* root node is black */
- dir->d_m_name_ucs2 = strdup_w(volume->v_name);
- volume->v_dir = volume->v_root = dir;
- volume->v_curdir = NULL;
- volume->v_hash = dirhash();
+ volume->v_root = dir;
+ curdir = dir;
- curdir = volume->v_dir;
if (volume_openDB(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);
}
else {
p = Trash;
- cname( volume, volume->v_dir, &p );
+ cname( volume, volume->v_root, &p );
}
return( AFP_OK );
}
openvol_err:
- if (volume->v_dir) {
- hash_free( volume->v_hash);
- dirfree( volume->v_dir );
- volume->v_dir = volume->v_root = NULL;
+ if (volume->v_root) {
+ dir_free( volume->v_root );
+ volume->v_root = NULL;
}
volume->v_flags &= ~AFPVOL_OPEN;
if (!vol)
return;
- hash_free( vol->v_hash);
- dirfree( vol->v_root );
- vol->v_dir = NULL;
+ dir_free( vol->v_root );
+ vol->v_root = NULL;
if (vol->v_cdb != NULL) {
cnid_close(vol->v_cdb);
vol->v_cdb = NULL;
if ( ovol != NULL ) {
/* Even if chdir fails, we can't say afp_closevol fails. */
if ( chdir( ovol->v_path ) == 0 ) {
- curdir = ovol->v_dir;
+ curdir = ovol->v_root;
}
}
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
-noinst_HEADERS = cnid_dbd_private.h cnid_private.h
+noinst_HEADERS = cnid_dbd_private.h cnid_private.h bstrlib.h
--- /dev/null
+/*
+ $Id: bstradd.h,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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.
+*/
+
+/*!
+ * @file
+ * Additional functions for bstrlib.
+ */
+
+#ifndef ATALK_BSTRADD_H
+#define ATALK_BSTRADD_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <atalk/bstrlib.h>
+
+#define cfrombstring(b) ((char *)((b)->data))
+
+typedef struct tagbstring static_bstring;
+
+extern bstring brefcstr(const char *str);
+extern int bunrefcstr(bstring b);
+
+extern struct bstrList *bstListCreateMin(int min);
+extern int bstrListPush(struct bstrList *sl, bstring bs);
+extern bstring bstrListPop(struct bstrList *sl);
+extern bstring bjoinInv(const struct bstrList * bl, const_bstring sep);
+#endif /* ATALK_BSTRADD_H */
--- /dev/null
+/*\r
+ * This source file is part of the bstring string library. This code was\r
+ * written by Paul Hsieh in 2002-2008, and is covered by the BSD open source \r
+ * license and the GPL. Refer to the accompanying documentation for details \r
+ * on usage and license.\r
+ */\r
+\r
+/*!\r
+ * @file\r
+ * This file is the core module for implementing the bstring functions.\r
+ */\r
+\r
+#ifndef BSTRLIB_INCLUDE\r
+#define BSTRLIB_INCLUDE\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#include <stdarg.h>\r
+#include <string.h>\r
+#include <limits.h>\r
+#include <ctype.h>\r
+\r
+#if !defined (BSTRLIB_VSNP_OK) && !defined (BSTRLIB_NOVSNP)\r
+# if defined (__TURBOC__) && !defined (__BORLANDC__)\r
+# define BSTRLIB_NOVSNP\r
+# endif\r
+#endif\r
+\r
+#define BSTR_ERR (-1)\r
+#define BSTR_OK (0)\r
+#define BSTR_BS_BUFF_LENGTH_GET (0)\r
+\r
+typedef struct tagbstring * bstring;\r
+typedef const struct tagbstring * const_bstring;\r
+\r
+/* Copy functions */\r
+#define cstr2bstr bfromcstr\r
+extern bstring bfromcstr (const char * str);\r
+extern bstring bfromcstralloc (int mlen, const char * str);\r
+extern bstring blk2bstr (const void * blk, int len);\r
+extern char * bstr2cstr (const_bstring s, char z);\r
+extern int bcstrfree (char * s);\r
+extern bstring bstrcpy (const_bstring b1);\r
+extern int bassign (bstring a, const_bstring b);\r
+extern int bassignmidstr (bstring a, const_bstring b, int left, int len);\r
+extern int bassigncstr (bstring a, const char * str);\r
+extern int bassignblk (bstring a, const void * s, int len);\r
+\r
+/* Destroy function */\r
+extern int bdestroy (bstring b);\r
+\r
+/* Space allocation hinting functions */\r
+extern int balloc (bstring s, int len);\r
+extern int ballocmin (bstring b, int len);\r
+\r
+/* Substring extraction */\r
+extern bstring bmidstr (const_bstring b, int left, int len);\r
+\r
+/* Various standard manipulations */\r
+extern int bconcat (bstring b0, const_bstring b1);\r
+extern int bconchar (bstring b0, char c);\r
+extern int bcatcstr (bstring b, const char * s);\r
+extern int bcatblk (bstring b, const void * s, int len);\r
+extern int binsert (bstring s1, int pos, const_bstring s2, unsigned char fill);\r
+extern int binsertch (bstring s1, int pos, int len, unsigned char fill);\r
+extern int breplace (bstring b1, int pos, int len, const_bstring b2, unsigned char fill);\r
+extern int bdelete (bstring s1, int pos, int len);\r
+extern int bsetstr (bstring b0, int pos, const_bstring b1, unsigned char fill);\r
+extern int btrunc (bstring b, int n);\r
+\r
+/* Scan/search functions */\r
+extern int bstricmp (const_bstring b0, const_bstring b1);\r
+extern int bstrnicmp (const_bstring b0, const_bstring b1, int n);\r
+extern int biseqcaseless (const_bstring b0, const_bstring b1);\r
+extern int bisstemeqcaselessblk (const_bstring b0, const void * blk, int len);\r
+extern int biseq (const_bstring b0, const_bstring b1);\r
+extern int bisstemeqblk (const_bstring b0, const void * blk, int len);\r
+extern int biseqcstr (const_bstring b, const char * s);\r
+extern int biseqcstrcaseless (const_bstring b, const char * s);\r
+extern int bstrcmp (const_bstring b0, const_bstring b1);\r
+extern int bstrncmp (const_bstring b0, const_bstring b1, int n);\r
+extern int binstr (const_bstring s1, int pos, const_bstring s2);\r
+extern int binstrr (const_bstring s1, int pos, const_bstring s2);\r
+extern int binstrcaseless (const_bstring s1, int pos, const_bstring s2);\r
+extern int binstrrcaseless (const_bstring s1, int pos, const_bstring s2);\r
+extern int bstrchrp (const_bstring b, int c, int pos);\r
+extern int bstrrchrp (const_bstring b, int c, int pos);\r
+#define bstrchr(b,c) bstrchrp ((b), (c), 0)\r
+#define bstrrchr(b,c) bstrrchrp ((b), (c), blength(b)-1)\r
+extern int binchr (const_bstring b0, int pos, const_bstring b1);\r
+extern int binchrr (const_bstring b0, int pos, const_bstring b1);\r
+extern int bninchr (const_bstring b0, int pos, const_bstring b1);\r
+extern int bninchrr (const_bstring b0, int pos, const_bstring b1);\r
+extern int bfindreplace (bstring b, const_bstring find, const_bstring repl, int pos);\r
+extern int bfindreplacecaseless (bstring b, const_bstring find, const_bstring repl, int pos);\r
+\r
+/* List of string container functions */\r
+struct bstrList {\r
+ int qty, mlen;\r
+ bstring * entry;\r
+};\r
+extern struct bstrList * bstrListCreate (void);\r
+extern int bstrListDestroy (struct bstrList * sl);\r
+extern int bstrListAlloc (struct bstrList * sl, int msz);\r
+extern int bstrListAllocMin (struct bstrList * sl, int msz);\r
+\r
+/* String split and join functions */\r
+extern struct bstrList * bsplit (const_bstring str, unsigned char splitChar);\r
+extern struct bstrList * bsplits (const_bstring str, const_bstring splitStr);\r
+extern struct bstrList * bsplitstr (const_bstring str, const_bstring splitStr);\r
+extern bstring bjoin (const struct bstrList * bl, const_bstring sep);\r
+extern int bsplitcb (const_bstring str, unsigned char splitChar, int pos,\r
+ int (* cb) (void * parm, int ofs, int len), void * parm);\r
+extern int bsplitscb (const_bstring str, const_bstring splitStr, int pos,\r
+ int (* cb) (void * parm, int ofs, int len), void * parm);\r
+extern int bsplitstrcb (const_bstring str, const_bstring splitStr, int pos,\r
+ int (* cb) (void * parm, int ofs, int len), void * parm);\r
+\r
+/* Miscellaneous functions */\r
+extern int bpattern (bstring b, int len);\r
+extern int btoupper (bstring b);\r
+extern int btolower (bstring b);\r
+extern int bltrimws (bstring b);\r
+extern int brtrimws (bstring b);\r
+extern int btrimws (bstring b);\r
+\r
+#if !defined (BSTRLIB_NOVSNP)\r
+extern bstring bformat (const char * fmt, ...);\r
+extern int bformata (bstring b, const char * fmt, ...);\r
+extern int bassignformat (bstring b, const char * fmt, ...);\r
+extern int bvcformata (bstring b, int count, const char * fmt, va_list arglist);\r
+\r
+#define bvformata(ret, b, fmt, lastarg) { \\r
+bstring bstrtmp_b = (b); \\r
+const char * bstrtmp_fmt = (fmt); \\r
+int bstrtmp_r = BSTR_ERR, bstrtmp_sz = 16; \\r
+ for (;;) { \\r
+ va_list bstrtmp_arglist; \\r
+ va_start (bstrtmp_arglist, lastarg); \\r
+ bstrtmp_r = bvcformata (bstrtmp_b, bstrtmp_sz, bstrtmp_fmt, bstrtmp_arglist); \\r
+ va_end (bstrtmp_arglist); \\r
+ if (bstrtmp_r >= 0) { /* Everything went ok */ \\r
+ bstrtmp_r = BSTR_OK; \\r
+ break; \\r
+ } else if (-bstrtmp_r <= bstrtmp_sz) { /* A real error? */ \\r
+ bstrtmp_r = BSTR_ERR; \\r
+ break; \\r
+ } \\r
+ bstrtmp_sz = -bstrtmp_r; /* Doubled or target size */ \\r
+ } \\r
+ ret = bstrtmp_r; \\r
+}\r
+\r
+#endif\r
+\r
+typedef int (*bNgetc) (void *parm);\r
+typedef size_t (* bNread) (void *buff, size_t elsize, size_t nelem, void *parm);\r
+\r
+/* Input functions */\r
+extern bstring bgets (bNgetc getcPtr, void * parm, char terminator);\r
+extern bstring bread (bNread readPtr, void * parm);\r
+extern int bgetsa (bstring b, bNgetc getcPtr, void * parm, char terminator);\r
+extern int bassigngets (bstring b, bNgetc getcPtr, void * parm, char terminator);\r
+extern int breada (bstring b, bNread readPtr, void * parm);\r
+\r
+/* Stream functions */\r
+extern struct bStream * bsopen (bNread readPtr, void * parm);\r
+extern void * bsclose (struct bStream * s);\r
+extern int bsbufflength (struct bStream * s, int sz);\r
+extern int bsreadln (bstring b, struct bStream * s, char terminator);\r
+extern int bsreadlns (bstring r, struct bStream * s, const_bstring term);\r
+extern int bsread (bstring b, struct bStream * s, int n);\r
+extern int bsreadlna (bstring b, struct bStream * s, char terminator);\r
+extern int bsreadlnsa (bstring r, struct bStream * s, const_bstring term);\r
+extern int bsreada (bstring b, struct bStream * s, int n);\r
+extern int bsunread (struct bStream * s, const_bstring b);\r
+extern int bspeek (bstring r, const struct bStream * s);\r
+extern int bssplitscb (struct bStream * s, const_bstring splitStr, \r
+ int (* cb) (void * parm, int ofs, const_bstring entry), void * parm);\r
+extern int bssplitstrcb (struct bStream * s, const_bstring splitStr, \r
+ int (* cb) (void * parm, int ofs, const_bstring entry), void * parm);\r
+extern int bseof (const struct bStream * s);\r
+\r
+struct tagbstring {\r
+ int mlen;\r
+ int slen;\r
+ unsigned char * data;\r
+};\r
+\r
+/* Accessor macros */\r
+#define blengthe(b, e) (((b) == (void *)0 || (b)->slen < 0) ? (int)(e) : ((b)->slen))\r
+#define blength(b) (blengthe ((b), 0))\r
+#define bdataofse(b, o, e) (((b) == (void *)0 || (b)->data == (void*)0) ? (char *)(e) : ((char *)(b)->data) + (o))\r
+#define bdataofs(b, o) (bdataofse ((b), (o), (void *)0))\r
+#define bdatae(b, e) (bdataofse (b, 0, e))\r
+#define bdata(b) (bdataofs (b, 0))\r
+#define bchare(b, p, e) ((((unsigned)(p)) < (unsigned)blength(b)) ? ((b)->data[(p)]) : (e))\r
+#define bchar(b, p) bchare ((b), (p), '\0')\r
+\r
+/* Static constant string initialization macro */\r
+#define bsStaticMlen(q,m) {(m), (int) sizeof(q)-1, (unsigned char *) ("" q "")}\r
+#if defined(_MSC_VER)\r
+# define bsStatic(q) bsStaticMlen(q,-32)\r
+#endif\r
+#ifndef bsStatic\r
+# define bsStatic(q) bsStaticMlen(q,-__LINE__)\r
+#endif\r
+\r
+/* Static constant block parameter pair */\r
+#define bsStaticBlkParms(q) ((void *)("" q "")), ((int) sizeof(q)-1)\r
+\r
+/* Reference building macros */\r
+#define cstr2tbstr btfromcstr\r
+#define btfromcstr(t,s) { \\r
+ (t).data = (unsigned char *) (s); \\r
+ (t).slen = ((t).data) ? ((int) (strlen) ((char *)(t).data)) : 0; \\r
+ (t).mlen = -1; \\r
+}\r
+#define blk2tbstr(t,s,l) { \\r
+ (t).data = (unsigned char *) (s); \\r
+ (t).slen = l; \\r
+ (t).mlen = -1; \\r
+}\r
+#define btfromblk(t,s,l) blk2tbstr(t,s,l)\r
+#define bmid2tbstr(t,b,p,l) { \\r
+ const_bstring bstrtmp_s = (b); \\r
+ if (bstrtmp_s && bstrtmp_s->data && bstrtmp_s->slen >= 0) { \\r
+ int bstrtmp_left = (p); \\r
+ int bstrtmp_len = (l); \\r
+ if (bstrtmp_left < 0) { \\r
+ bstrtmp_len += bstrtmp_left; \\r
+ bstrtmp_left = 0; \\r
+ } \\r
+ if (bstrtmp_len > bstrtmp_s->slen - bstrtmp_left) \\r
+ bstrtmp_len = bstrtmp_s->slen - bstrtmp_left; \\r
+ if (bstrtmp_len <= 0) { \\r
+ (t).data = (unsigned char *)""; \\r
+ (t).slen = 0; \\r
+ } else { \\r
+ (t).data = bstrtmp_s->data + bstrtmp_left; \\r
+ (t).slen = bstrtmp_len; \\r
+ } \\r
+ } else { \\r
+ (t).data = (unsigned char *)""; \\r
+ (t).slen = 0; \\r
+ } \\r
+ (t).mlen = -__LINE__; \\r
+}\r
+#define btfromblkltrimws(t,s,l) { \\r
+ int bstrtmp_idx = 0, bstrtmp_len = (l); \\r
+ unsigned char * bstrtmp_s = (s); \\r
+ if (bstrtmp_s && bstrtmp_len >= 0) { \\r
+ for (; bstrtmp_idx < bstrtmp_len; bstrtmp_idx++) { \\r
+ if (!isspace (bstrtmp_s[bstrtmp_idx])) break; \\r
+ } \\r
+ } \\r
+ (t).data = bstrtmp_s + bstrtmp_idx; \\r
+ (t).slen = bstrtmp_len - bstrtmp_idx; \\r
+ (t).mlen = -__LINE__; \\r
+}\r
+#define btfromblkrtrimws(t,s,l) { \\r
+ int bstrtmp_len = (l) - 1; \\r
+ unsigned char * bstrtmp_s = (s); \\r
+ if (bstrtmp_s && bstrtmp_len >= 0) { \\r
+ for (; bstrtmp_len >= 0; bstrtmp_len--) { \\r
+ if (!isspace (bstrtmp_s[bstrtmp_len])) break; \\r
+ } \\r
+ } \\r
+ (t).data = bstrtmp_s; \\r
+ (t).slen = bstrtmp_len + 1; \\r
+ (t).mlen = -__LINE__; \\r
+}\r
+#define btfromblktrimws(t,s,l) { \\r
+ int bstrtmp_idx = 0, bstrtmp_len = (l) - 1; \\r
+ unsigned char * bstrtmp_s = (s); \\r
+ if (bstrtmp_s && bstrtmp_len >= 0) { \\r
+ for (; bstrtmp_idx <= bstrtmp_len; bstrtmp_idx++) { \\r
+ if (!isspace (bstrtmp_s[bstrtmp_idx])) break; \\r
+ } \\r
+ for (; bstrtmp_len >= bstrtmp_idx; bstrtmp_len--) { \\r
+ if (!isspace (bstrtmp_s[bstrtmp_len])) break; \\r
+ } \\r
+ } \\r
+ (t).data = bstrtmp_s + bstrtmp_idx; \\r
+ (t).slen = bstrtmp_len + 1 - bstrtmp_idx; \\r
+ (t).mlen = -__LINE__; \\r
+}\r
+\r
+/* Write protection macros */\r
+#define bwriteprotect(t) { if ((t).mlen >= 0) (t).mlen = -1; }\r
+#define bwriteallow(t) { if ((t).mlen == -1) (t).mlen = (t).slen + ((t).slen == 0); }\r
+#define biswriteprotected(t) ((t).mlen <= 0)\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif\r
/*
- * $Id: directory.h,v 1.3 2010-01-10 10:58:25 franklahm Exp $
+ * $Id: directory.h,v 1.3.2.1 2010-02-01 10:56:08 franklahm Exp $
*
* Copyright (c) 1990,1991 Regents of The University of Michigan.
* All Rights Reserved.
#include <sys/types.h>
#include <netatalk/endian.h>
#include <dirent.h>
+#include <stdint.h>
#include <atalk/cnid.h>
-#include <atalk/directory.h>
+#include <atalk/bstrlib.h>
+#include <atalk/queue.h>
/* setgid directories */
#ifndef DIRBITS
# endif /* AFS */
#endif /* DIRBITS */
-/* the did tree is now a red-black tree while the parent/child
- * tree is a circular doubly-linked list. how exciting. */
-struct dir {
- struct dir *d_left, *d_right, *d_back; /* for red-black tree */
- int d_color;
- struct dir *d_parent, *d_child; /* parent-child */
- struct dir *d_prev, *d_next; /* siblings */
- void *d_ofork; /* oforks using this directory. */
- u_int32_t d_did;
- int d_flags;
+/* reserved directory id's */
+#define DIRDID_ROOT_PARENT htonl(1) /* parent directory of root */
+#define DIRDID_ROOT htonl(2) /* root directory */
+struct dir {
+ bstring d_fullpath; /* complete unix path to dir */
+ bstring d_m_name; /* mac name */
+ bstring d_u_name; /* unix name */
+ /* be careful here! if d_m_name == d_u_name, d_u_name */
+ /* will just point to the same storage as d_m_name !! */
+ ucs2_t *d_m_name_ucs2; /* mac name as UCS2 */
+ qnode_t *qidx_node; /* pointer to position in queue index */
+ void *d_ofork; /* oforks using this directory. */
time_t ctime; /* inode ctime */
- u_int32_t offcnt; /* offspring count */
-
- char *d_m_name; /* mac name */
- char *d_u_name; /* unix name */
- ucs2_t *d_m_name_ucs2; /* mac name as UCS2 */
+ int d_flags; /* directory flags */
+ cnid_t d_pdid; /* CNID of parent directory */
+ cnid_t d_did; /* CNID of directory */
+ uint32_t offcnt; /* offspring count */
+ uint16_t d_vid; /* only needed in the dircache, because
+ we put all directories in one cache. */
};
struct path {
int m_type; /* mac name type (long name, unicode */
- char *m_name; /* mac name */
+ char *m_name; /* mac name */
char *u_name; /* unix name */
- cnid_t id; /* file id (only for getmetadata) */
+ cnid_t id; /* file id (only for getmetadata) */
struct dir *d_dir; /* */
int st_valid; /* does st_errno and st set */
int st_errno;
#endif
}
-
#endif /* ATALK_DIRECTORY_H */
--- /dev/null
+/*
+ Copyright (c) 2010 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.
+
+ 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.
+*/
+
+#ifndef ATALK_QUEUE_H
+#define ATALK_QUEUE_H
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+typedef struct qnode {
+ struct qnode *prev;
+ struct qnode *next;
+ void *data;
+} qnode_t;
+
+typedef qnode_t q_t;
+
+extern q_t *queue_init(void);
+extern void queue_destroy(q_t *q, void (*callback)(void *));
+#define queue_free(q) queue_destroy((q), free)
+extern qnode_t *enqueue(q_t *q, void *data);
+extern void *dequeue(q_t *q);
+
+#endif /* ATALK_QUEUE_H */
/*
- * $Id: util.h,v 1.21 2010-02-28 22:29:16 didg Exp $
+ * $Id: util.h,v 1.21 2010/02/28 22:29:16 didg Exp $
*/
/*!
#define EXITERR_CONF 2 /* error in config files/cmd line parameters */
#define EXITERR_SYS 3 /* local system error */
+/* LOG assert errors */
+#ifndef NDEBUG
+#define AFP_ASSERT(b) \
+ do { \
+ if (!(b)) { \
+ LOG(log_error, logtype_default, "PANIC, assert failed: %s", #b); \
+ abort(); \
+ } \
+ } while(0);
+#else
+#define AFP_ASSERT(b)
+#endif /* NDEBUG */
#ifdef WITH_SENDFILE
extern ssize_t sys_sendfile (int __out_fd, int __in_fd, off_t *__offset,size_t __count);
/*
- * $Id: volume.h,v 1.17 2010-04-10 08:24:54 franklahm Exp $
+ * $Id: volume.h,v 1.16 2010/03/31 09:47:32 franklahm Exp $
*
* Copyright (c) 1990,1994 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
u_int16_t v_vid;
int v_flags;
char *v_path;
- struct dir *v_dir, *v_root;
- struct dir *v_curdir; /* cache */
- hash_t *v_hash;
+ struct dir *v_root;
time_t v_mtime;
charset_t v_volcharset;
/*
Flags that alter volume behaviour.
- Keep in sync with include/atalk/volinfo.h and libatalk/util/volinfo.c
+ 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_INV_DOTS (1 << 22) /* dots files are invisible */
#define AFPVOL_TM (1 << 24) /* Supports TimeMachine */
#define AFPVOL_ACLS (1 << 25) /* Volume supports ACLS */
+#define AFPVOL_CDROM (1 << 25) /* Ejectable media eg CD -> in memory CNID db */
/* Extended Attributes vfs indirection */
#define AFPVOL_EA_NONE 0 /* No EAs */
# Makefile.am for libatalk/
-SUBDIRS = acl adouble asp atp compat cnid dsi nbp netddp tdb util unicode vfs
+SUBDIRS = acl adouble asp atp bstring compat cnid dsi nbp netddp tdb util unicode vfs
lib_LTLIBRARIES = libatalk.la
adouble/libadouble.la \
asp/libasp.la \
atp/libatp.la \
+ bstring/libbstring.la \
compat/libcompat.la \
dsi/libdsi.la \
nbp/libnbp.la \
adouble/libadouble.la \
asp/libasp.la \
atp/libatp.la \
+ bstring/libbstring.la \
compat/libcompat.la \
dsi/libdsi.la \
nbp/libnbp.la \
--- /dev/null
+Makefile
+Makefile.in
+*.lo
+*.la
+.deps
+.libs
--- /dev/null
+# Makefile.am for libatalk/adouble/
+
+noinst_LTLIBRARIES = libbstring.la
+
+libbstring_la_SOURCES = bstrlib.c bstradd.c
+
--- /dev/null
+/*
+ $Id: bstradd.c,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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.
+*/
+
+/*!
+ * @file
+ * Additional functions for bstrlib
+ */
+
+#include <stdio.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+
+#include <atalk/bstrlib.h>
+
+/* Optionally include a mechanism for debugging memory */
+
+#if defined(MEMORY_DEBUG) || defined(BSTRLIB_MEMORY_DEBUG)
+#include "memdbg.h"
+#endif
+
+#ifndef bstr__alloc
+#define bstr__alloc(x) malloc (x)
+#endif
+
+#ifndef bstr__free
+#define bstr__free(p) free (p)
+#endif
+
+#ifndef bstr__realloc
+#define bstr__realloc(p,x) realloc ((p), (x))
+#endif
+
+#ifndef bstr__memcpy
+#define bstr__memcpy(d,s,l) memcpy ((d), (s), (l))
+#endif
+
+#ifndef bstr__memmove
+#define bstr__memmove(d,s,l) memmove ((d), (s), (l))
+#endif
+
+#ifndef bstr__memset
+#define bstr__memset(d,c,l) memset ((d), (c), (l))
+#endif
+
+#ifndef bstr__memcmp
+#define bstr__memcmp(d,c,l) memcmp ((d), (c), (l))
+#endif
+
+#ifndef bstr__memchr
+#define bstr__memchr(s,c,l) memchr ((s), (c), (l))
+#endif
+
+/*************************************************************************
+ * Stuff for making bstrings referencing c-strings
+ ************************************************************************/
+
+/*!
+ * @brief Create a bstring referencing "str"
+ *
+ * This is usefull if a well know code path uses string, often doing strlen on string.
+ * By converting to bstring which carries the strlen, the repeated computation can be avoided.
+ */
+bstring brefcstr (const char *str) {
+ bstring b;
+ int i;
+ size_t j;
+
+ if (str == NULL)
+ return NULL;
+ j = strlen(str);
+
+ b = (bstring)bstr__alloc(sizeof(struct tagbstring));
+ if (NULL == b)
+ return NULL;
+
+ b->slen = (int) j;
+ b->mlen = -1;
+ b->data = str;
+
+ return b;
+}
+
+/*!
+ * @brief Free up the bstring, WITHOUT freeing the pointed to c-string!
+ */
+int bunrefcstr (bstring b) {
+ if (b == NULL || b->slen < 0 || b->mlen > 0 || b->data == NULL)
+ return BSTR_ERR;
+
+ /* In case there is any stale usage, there is one more chance to
+ notice this error. */
+
+ b->slen = -1;
+ b->mlen = -__LINE__;
+ b->data = NULL;
+
+ bstr__free (b);
+ return BSTR_OK;
+}
+
+/*************************************************************************
+ * stuff for bstrList
+ ************************************************************************/
+
+/*!
+ * @brief Create an empty list with preallocated storage for at least 'min' members
+ */
+struct bstrList *bstListCreateMin(int min)
+{
+ struct bstrList *sl = NULL;
+
+ if ((sl = bstrListCreate()) == NULL)
+ return NULL;
+
+ if ((bstrListAlloc(sl, min)) != BSTR_OK) {
+ bstrListDestroy(sl);
+ return NULL;
+ }
+
+ return sl;
+}
+
+/*!
+ * @brief Push a bstring to the end of a list
+ */
+int bstrListPush(struct bstrList *sl, bstring bs)
+{
+ if (sl->qty == sl->mlen) {
+ if ((bstrListAlloc(sl, sl->qty + 1)) != BSTR_OK)
+ return BSTR_ERR;
+ }
+
+ sl->entry[sl->qty] = bs;
+ sl->qty++;
+ return BSTR_OK;
+}
+
+/*!
+ * @brief Pop a bstring from the end of a list
+ */
+bstring bstrListPop(struct bstrList *sl)
+{
+ return NULL;
+}
+
+/*!
+ * @brief Inverse bjoin
+ */
+bstring bjoinInv(const struct bstrList * bl, const_bstring sep) {
+ bstring b;
+ int i, j, c, v;
+
+ if (bl == NULL || bl->qty < 0)
+ return NULL;
+ if (sep != NULL && (sep->slen < 0 || sep->data == NULL))
+ return NULL;
+
+ for (i = 0, c = 1; i < bl->qty; i++) {
+ v = bl->entry[i]->slen;
+ if (v < 0)
+ return NULL;/* Invalid input */
+ c += v;
+ if (c < 0)
+ return NULL;/* Wrap around ?? */
+ }
+
+ if (sep != NULL)
+ c += (bl->qty - 1) * sep->slen;
+
+ b = (bstring) bstr__alloc (sizeof (struct tagbstring));
+ if (NULL == b)
+ return NULL; /* Out of memory */
+ b->data = (unsigned char *) bstr__alloc (c);
+ if (b->data == NULL) {
+ bstr__free (b);
+ return NULL;
+ }
+
+ b->mlen = c;
+ b->slen = c-1;
+
+ for (i = bl->qty - 1, c = 0, j = 0; i >= 0; i--, j++) {
+ if (j > 0 && sep != NULL) {
+ bstr__memcpy (b->data + c, sep->data, sep->slen);
+ c += sep->slen;
+ }
+ v = bl->entry[i]->slen;
+ bstr__memcpy (b->data + c, bl->entry[i]->data, v);
+ c += v;
+ }
+ b->data[c] = (unsigned char) '\0';
+ return b;
+}
--- /dev/null
+/*\r
+ * This source file is part of the bstring string library. This code was\r
+ * written by Paul Hsieh in 2002-2008, and is covered by the BSD open source \r
+ * license and the GPL. Refer to the accompanying documentation for details \r
+ * on usage and license.\r
+ */\r
+\r
+/*\r
+ * bstrlib.c\r
+ *\r
+ * This file is the core module for implementing the bstring functions.\r
+ */\r
+\r
+#include <stdio.h>\r
+#include <stddef.h>\r
+#include <stdarg.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <ctype.h>\r
+\r
+#include <atalk/bstrlib.h>\r
+\r
+/* Optionally include a mechanism for debugging memory */\r
+\r
+#if defined(MEMORY_DEBUG) || defined(BSTRLIB_MEMORY_DEBUG)\r
+#include "memdbg.h"\r
+#endif\r
+\r
+#ifndef bstr__alloc\r
+#define bstr__alloc(x) malloc (x)\r
+#endif\r
+\r
+#ifndef bstr__free\r
+#define bstr__free(p) free (p)\r
+#endif\r
+\r
+#ifndef bstr__realloc\r
+#define bstr__realloc(p,x) realloc ((p), (x))\r
+#endif\r
+\r
+#ifndef bstr__memcpy\r
+#define bstr__memcpy(d,s,l) memcpy ((d), (s), (l))\r
+#endif\r
+\r
+#ifndef bstr__memmove\r
+#define bstr__memmove(d,s,l) memmove ((d), (s), (l))\r
+#endif\r
+\r
+#ifndef bstr__memset\r
+#define bstr__memset(d,c,l) memset ((d), (c), (l))\r
+#endif\r
+\r
+#ifndef bstr__memcmp\r
+#define bstr__memcmp(d,c,l) memcmp ((d), (c), (l))\r
+#endif\r
+\r
+#ifndef bstr__memchr\r
+#define bstr__memchr(s,c,l) memchr ((s), (c), (l))\r
+#endif\r
+\r
+/* Just a length safe wrapper for memmove. */\r
+\r
+#define bBlockCopy(D,S,L) { if ((L) > 0) bstr__memmove ((D),(S),(L)); }\r
+\r
+/* Compute the snapped size for a given requested size. By snapping to powers\r
+ of 2 like this, repeated reallocations are avoided. */\r
+static int snapUpSize (int i) {\r
+ if (i < 8) {\r
+ i = 8;\r
+ } else {\r
+ unsigned int j;\r
+ j = (unsigned int) i;\r
+\r
+ j |= (j >> 1);\r
+ j |= (j >> 2);\r
+ j |= (j >> 4);\r
+ j |= (j >> 8); /* Ok, since int >= 16 bits */\r
+#if (UINT_MAX != 0xffff)\r
+ j |= (j >> 16); /* For 32 bit int systems */\r
+#if (UINT_MAX > 0xffffffffUL)\r
+ j |= (j >> 32); /* For 64 bit int systems */\r
+#endif\r
+#endif\r
+ /* Least power of two greater than i */\r
+ j++;\r
+ if ((int) j >= i) i = (int) j;\r
+ }\r
+ return i;\r
+}\r
+\r
+/* int balloc (bstring b, int len)\r
+ *\r
+ * Increase the size of the memory backing the bstring b to at least len.\r
+ */\r
+int balloc (bstring b, int olen) {\r
+ int len;\r
+ if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen <= 0 || \r
+ b->mlen < b->slen || olen <= 0) {\r
+ return BSTR_ERR;\r
+ }\r
+\r
+ if (olen >= b->mlen) {\r
+ unsigned char * x;\r
+\r
+ if ((len = snapUpSize (olen)) <= b->mlen) return BSTR_OK;\r
+\r
+ /* Assume probability of a non-moving realloc is 0.125 */\r
+ if (7 * b->mlen < 8 * b->slen) {\r
+\r
+ /* If slen is close to mlen in size then use realloc to reduce\r
+ the memory defragmentation */\r
+\r
+ reallocStrategy:;\r
+\r
+ x = (unsigned char *) bstr__realloc (b->data, (size_t) len);\r
+ if (x == NULL) {\r
+\r
+ /* Since we failed, try allocating the tighest possible \r
+ allocation */\r
+\r
+ if (NULL == (x = (unsigned char *) bstr__realloc (b->data, (size_t) (len = olen)))) {\r
+ return BSTR_ERR;\r
+ }\r
+ }\r
+ } else {\r
+\r
+ /* If slen is not close to mlen then avoid the penalty of copying\r
+ the extra bytes that are allocated, but not considered part of\r
+ the string */\r
+\r
+ if (NULL == (x = (unsigned char *) bstr__alloc ((size_t) len))) {\r
+\r
+ /* Perhaps there is no available memory for the two \r
+ allocations to be in memory at once */\r
+\r
+ goto reallocStrategy;\r
+\r
+ } else {\r
+ if (b->slen) bstr__memcpy ((char *) x, (char *) b->data, (size_t) b->slen);\r
+ bstr__free (b->data);\r
+ }\r
+ }\r
+ b->data = x;\r
+ b->mlen = len;\r
+ b->data[b->slen] = (unsigned char) '\0';\r
+ }\r
+\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int ballocmin (bstring b, int len)\r
+ *\r
+ * Set the size of the memory backing the bstring b to len or b->slen+1,\r
+ * whichever is larger. Note that repeated use of this function can degrade\r
+ * performance.\r
+ */\r
+int ballocmin (bstring b, int len) {\r
+ unsigned char * s;\r
+\r
+ if (b == NULL || b->data == NULL || (b->slen+1) < 0 || b->mlen <= 0 || \r
+ b->mlen < b->slen || len <= 0) {\r
+ return BSTR_ERR;\r
+ }\r
+\r
+ if (len < b->slen + 1) len = b->slen + 1;\r
+\r
+ if (len != b->mlen) {\r
+ s = (unsigned char *) bstr__realloc (b->data, (size_t) len);\r
+ if (NULL == s) return BSTR_ERR;\r
+ s[b->slen] = (unsigned char) '\0';\r
+ b->data = s;\r
+ b->mlen = len;\r
+ }\r
+\r
+ return BSTR_OK;\r
+}\r
+\r
+/* bstring bfromcstr (const char * str)\r
+ *\r
+ * Create a bstring which contains the contents of the '\0' terminated char *\r
+ * buffer str.\r
+ */\r
+bstring bfromcstr (const char * str) {\r
+bstring b;\r
+int i;\r
+size_t j;\r
+\r
+ if (str == NULL) return NULL;\r
+ j = (strlen) (str);\r
+ i = snapUpSize ((int) (j + (2 - (j != 0))));\r
+ if (i <= (int) j) return NULL;\r
+\r
+ b = (bstring) bstr__alloc (sizeof (struct tagbstring));\r
+ if (NULL == b) return NULL;\r
+ b->slen = (int) j;\r
+ if (NULL == (b->data = (unsigned char *) bstr__alloc (b->mlen = i))) {\r
+ bstr__free (b);\r
+ return NULL;\r
+ }\r
+\r
+ bstr__memcpy (b->data, str, j+1);\r
+ return b;\r
+}\r
+\r
+/* bstring bfromcstralloc (int mlen, const char * str)\r
+ *\r
+ * Create a bstring which contains the contents of the '\0' terminated char *\r
+ * buffer str. The memory buffer backing the string is at least len \r
+ * characters in length.\r
+ */\r
+bstring bfromcstralloc (int mlen, const char * str) {\r
+bstring b;\r
+int i;\r
+size_t j;\r
+\r
+ if (str == NULL) return NULL;\r
+ j = (strlen) (str);\r
+ i = snapUpSize ((int) (j + (2 - (j != 0))));\r
+ if (i <= (int) j) return NULL;\r
+\r
+ b = (bstring) bstr__alloc (sizeof (struct tagbstring));\r
+ if (b == NULL) return NULL;\r
+ b->slen = (int) j;\r
+ if (i < mlen) i = mlen;\r
+\r
+ if (NULL == (b->data = (unsigned char *) bstr__alloc (b->mlen = i))) {\r
+ bstr__free (b);\r
+ return NULL;\r
+ }\r
+\r
+ bstr__memcpy (b->data, str, j+1);\r
+ return b;\r
+}\r
+\r
+/* bstring blk2bstr (const void * blk, int len)\r
+ *\r
+ * Create a bstring which contains the content of the block blk of length \r
+ * len.\r
+ */\r
+bstring blk2bstr (const void * blk, int len) {\r
+bstring b;\r
+int i;\r
+\r
+ if (blk == NULL || len < 0) return NULL;\r
+ b = (bstring) bstr__alloc (sizeof (struct tagbstring));\r
+ if (b == NULL) return NULL;\r
+ b->slen = len;\r
+\r
+ i = len + (2 - (len != 0));\r
+ i = snapUpSize (i);\r
+\r
+ b->mlen = i;\r
+\r
+ b->data = (unsigned char *) bstr__alloc ((size_t) b->mlen);\r
+ if (b->data == NULL) {\r
+ bstr__free (b);\r
+ return NULL;\r
+ }\r
+\r
+ if (len > 0) bstr__memcpy (b->data, blk, (size_t) len);\r
+ b->data[len] = (unsigned char) '\0';\r
+\r
+ return b;\r
+}\r
+\r
+/* char * bstr2cstr (const_bstring s, char z)\r
+ *\r
+ * Create a '\0' terminated char * buffer which is equal to the contents of \r
+ * the bstring s, except that any contained '\0' characters are converted \r
+ * to the character in z. This returned value should be freed with a \r
+ * bcstrfree () call, by the calling application.\r
+ */\r
+char * bstr2cstr (const_bstring b, char z) {\r
+int i, l;\r
+char * r;\r
+\r
+ if (b == NULL || b->slen < 0 || b->data == NULL) return NULL;\r
+ l = b->slen;\r
+ r = (char *) bstr__alloc ((size_t) (l + 1));\r
+ if (r == NULL) return r;\r
+\r
+ for (i=0; i < l; i ++) {\r
+ r[i] = (char) ((b->data[i] == '\0') ? z : (char) (b->data[i]));\r
+ }\r
+\r
+ r[l] = (unsigned char) '\0';\r
+\r
+ return r;\r
+}\r
+\r
+/* int bcstrfree (char * s)\r
+ *\r
+ * Frees a C-string generated by bstr2cstr (). This is normally unnecessary\r
+ * since it just wraps a call to bstr__free (), however, if bstr__alloc () \r
+ * and bstr__free () have been redefined as a macros within the bstrlib \r
+ * module (via defining them in memdbg.h after defining \r
+ * BSTRLIB_MEMORY_DEBUG) with some difference in behaviour from the std \r
+ * library functions, then this allows a correct way of freeing the memory \r
+ * that allows higher level code to be independent from these macro \r
+ * redefinitions.\r
+ */\r
+int bcstrfree (char * s) {\r
+ if (s) {\r
+ bstr__free (s);\r
+ return BSTR_OK;\r
+ }\r
+ return BSTR_ERR;\r
+}\r
+\r
+/* int bconcat (bstring b0, const_bstring b1)\r
+ *\r
+ * Concatenate the bstring b1 to the bstring b0.\r
+ */\r
+int bconcat (bstring b0, const_bstring b1) {\r
+int len, d;\r
+bstring aux = (bstring) b1;\r
+\r
+ if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL) return BSTR_ERR;\r
+\r
+ d = b0->slen;\r
+ len = b1->slen;\r
+ if ((d | (b0->mlen - d) | len | (d + len)) < 0) return BSTR_ERR;\r
+\r
+ if (b0->mlen <= d + len + 1) {\r
+ ptrdiff_t pd = b1->data - b0->data;\r
+ if (0 <= pd && pd < b0->mlen) {\r
+ if (NULL == (aux = bstrcpy (b1))) return BSTR_ERR;\r
+ }\r
+ if (balloc (b0, d + len + 1) != BSTR_OK) {\r
+ if (aux != b1) bdestroy (aux);\r
+ return BSTR_ERR;\r
+ }\r
+ }\r
+\r
+ bBlockCopy (&b0->data[d], &aux->data[0], (size_t) len);\r
+ b0->data[d + len] = (unsigned char) '\0';\r
+ b0->slen = d + len;\r
+ if (aux != b1) bdestroy (aux);\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bconchar (bstring b, char c)\r
+/ *\r
+ * Concatenate the single character c to the bstring b.\r
+ */\r
+int bconchar (bstring b, char c) {\r
+int d;\r
+\r
+ if (b == NULL) return BSTR_ERR;\r
+ d = b->slen;\r
+ if ((d | (b->mlen - d)) < 0 || balloc (b, d + 2) != BSTR_OK) return BSTR_ERR;\r
+ b->data[d] = (unsigned char) c;\r
+ b->data[d + 1] = (unsigned char) '\0';\r
+ b->slen++;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bcatcstr (bstring b, const char * s)\r
+ *\r
+ * Concatenate a char * string to a bstring.\r
+ */\r
+int bcatcstr (bstring b, const char * s) {\r
+char * d;\r
+int i, l;\r
+\r
+ if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen < b->slen\r
+ || b->mlen <= 0 || s == NULL) return BSTR_ERR;\r
+\r
+ /* Optimistically concatenate directly */\r
+ l = b->mlen - b->slen;\r
+ d = (char *) &b->data[b->slen];\r
+ for (i=0; i < l; i++) {\r
+ if ((*d++ = *s++) == '\0') {\r
+ b->slen += i;\r
+ return BSTR_OK;\r
+ }\r
+ }\r
+ b->slen += i;\r
+\r
+ /* Need to explicitely resize and concatenate tail */\r
+ return bcatblk (b, (const void *) s, (int) strlen (s));\r
+}\r
+\r
+/* int bcatblk (bstring b, const void * s, int len)\r
+ *\r
+ * Concatenate a fixed length buffer to a bstring.\r
+ */\r
+int bcatblk (bstring b, const void * s, int len) {\r
+int nl;\r
+\r
+ if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen < b->slen\r
+ || b->mlen <= 0 || s == NULL || len < 0) return BSTR_ERR;\r
+\r
+ if (0 > (nl = b->slen + len)) return BSTR_ERR; /* Overflow? */\r
+ if (b->mlen <= nl && 0 > balloc (b, nl + 1)) return BSTR_ERR;\r
+\r
+ bBlockCopy (&b->data[b->slen], s, (size_t) len);\r
+ b->slen = nl;\r
+ b->data[nl] = (unsigned char) '\0';\r
+ return BSTR_OK;\r
+}\r
+\r
+/* bstring bstrcpy (const_bstring b)\r
+ *\r
+ * Create a copy of the bstring b.\r
+ */\r
+bstring bstrcpy (const_bstring b) {\r
+bstring b0;\r
+int i,j;\r
+\r
+ /* Attempted to copy an invalid string? */\r
+ if (b == NULL || b->slen < 0 || b->data == NULL) return NULL;\r
+\r
+ b0 = (bstring) bstr__alloc (sizeof (struct tagbstring));\r
+ if (b0 == NULL) {\r
+ /* Unable to allocate memory for string header */\r
+ return NULL;\r
+ }\r
+\r
+ i = b->slen;\r
+ j = snapUpSize (i + 1);\r
+\r
+ b0->data = (unsigned char *) bstr__alloc (j);\r
+ if (b0->data == NULL) {\r
+ j = i + 1;\r
+ b0->data = (unsigned char *) bstr__alloc (j);\r
+ if (b0->data == NULL) {\r
+ /* Unable to allocate memory for string data */\r
+ bstr__free (b0);\r
+ return NULL;\r
+ }\r
+ }\r
+\r
+ b0->mlen = j;\r
+ b0->slen = i;\r
+\r
+ if (i) bstr__memcpy ((char *) b0->data, (char *) b->data, i);\r
+ b0->data[b0->slen] = (unsigned char) '\0';\r
+\r
+ return b0;\r
+}\r
+\r
+/* int bassign (bstring a, const_bstring b)\r
+ *\r
+ * Overwrite the string a with the contents of string b.\r
+ */\r
+int bassign (bstring a, const_bstring b) {\r
+ if (b == NULL || b->data == NULL || b->slen < 0)\r
+ return BSTR_ERR;\r
+ if (b->slen != 0) {\r
+ if (balloc (a, b->slen) != BSTR_OK) return BSTR_ERR;\r
+ bstr__memmove (a->data, b->data, b->slen);\r
+ } else {\r
+ if (a == NULL || a->data == NULL || a->mlen < a->slen || \r
+ a->slen < 0 || a->mlen == 0) \r
+ return BSTR_ERR;\r
+ }\r
+ a->data[b->slen] = (unsigned char) '\0';\r
+ a->slen = b->slen;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bassignmidstr (bstring a, const_bstring b, int left, int len)\r
+ *\r
+ * Overwrite the string a with the middle of contents of string b \r
+ * starting from position left and running for a length len. left and \r
+ * len are clamped to the ends of b as with the function bmidstr.\r
+ */\r
+int bassignmidstr (bstring a, const_bstring b, int left, int len) {\r
+ if (b == NULL || b->data == NULL || b->slen < 0)\r
+ return BSTR_ERR;\r
+\r
+ if (left < 0) {\r
+ len += left;\r
+ left = 0;\r
+ }\r
+\r
+ if (len > b->slen - left) len = b->slen - left;\r
+\r
+ if (a == NULL || a->data == NULL || a->mlen < a->slen ||\r
+ a->slen < 0 || a->mlen == 0)\r
+ return BSTR_ERR;\r
+\r
+ if (len > 0) {\r
+ if (balloc (a, len) != BSTR_OK) return BSTR_ERR;\r
+ bstr__memmove (a->data, b->data + left, len);\r
+ a->slen = len;\r
+ } else {\r
+ a->slen = 0;\r
+ }\r
+ a->data[a->slen] = (unsigned char) '\0';\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bassigncstr (bstring a, const char * str)\r
+ *\r
+ * Overwrite the string a with the contents of char * string str. Note that \r
+ * the bstring a must be a well defined and writable bstring. If an error \r
+ * occurs BSTR_ERR is returned however a may be partially overwritten.\r
+ */\r
+int bassigncstr (bstring a, const char * str) {\r
+int i;\r
+size_t len;\r
+ if (a == NULL || a->data == NULL || a->mlen < a->slen ||\r
+ a->slen < 0 || a->mlen == 0 || NULL == str) \r
+ return BSTR_ERR;\r
+\r
+ for (i=0; i < a->mlen; i++) {\r
+ if ('\0' == (a->data[i] = str[i])) {\r
+ a->slen = i;\r
+ return BSTR_OK;\r
+ }\r
+ }\r
+\r
+ a->slen = i;\r
+ len = strlen (str + i);\r
+ if (len > INT_MAX || i + len + 1 > INT_MAX ||\r
+ 0 > balloc (a, (int) (i + len + 1))) return BSTR_ERR;\r
+ bBlockCopy (a->data + i, str + i, (size_t) len + 1);\r
+ a->slen += (int) len;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bassignblk (bstring a, const void * s, int len)\r
+ *\r
+ * Overwrite the string a with the contents of the block (s, len). Note that \r
+ * the bstring a must be a well defined and writable bstring. If an error \r
+ * occurs BSTR_ERR is returned and a is not overwritten.\r
+ */\r
+int bassignblk (bstring a, const void * s, int len) {\r
+ if (a == NULL || a->data == NULL || a->mlen < a->slen ||\r
+ a->slen < 0 || a->mlen == 0 || NULL == s || len + 1 < 1) \r
+ return BSTR_ERR;\r
+ if (len + 1 > a->mlen && 0 > balloc (a, len + 1)) return BSTR_ERR;\r
+ bBlockCopy (a->data, s, (size_t) len);\r
+ a->data[len] = (unsigned char) '\0';\r
+ a->slen = len;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int btrunc (bstring b, int n)\r
+ *\r
+ * Truncate the bstring to at most n characters.\r
+ */\r
+int btrunc (bstring b, int n) {\r
+ if (n < 0 || b == NULL || b->data == NULL || b->mlen < b->slen ||\r
+ b->slen < 0 || b->mlen <= 0) return BSTR_ERR;\r
+ if (b->slen > n) {\r
+ b->slen = n;\r
+ b->data[n] = (unsigned char) '\0';\r
+ }\r
+ return BSTR_OK;\r
+}\r
+\r
+#define upcase(c) (toupper ((unsigned char) c))\r
+#define downcase(c) (tolower ((unsigned char) c))\r
+#define wspace(c) (isspace ((unsigned char) c))\r
+\r
+/* int btoupper (bstring b)\r
+ *\r
+ * Convert contents of bstring to upper case.\r
+ */\r
+int btoupper (bstring b) {\r
+int i, len;\r
+ if (b == NULL || b->data == NULL || b->mlen < b->slen ||\r
+ b->slen < 0 || b->mlen <= 0) return BSTR_ERR;\r
+ for (i=0, len = b->slen; i < len; i++) {\r
+ b->data[i] = (unsigned char) upcase (b->data[i]);\r
+ }\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int btolower (bstring b)\r
+ *\r
+ * Convert contents of bstring to lower case.\r
+ */\r
+int btolower (bstring b) {\r
+int i, len;\r
+ if (b == NULL || b->data == NULL || b->mlen < b->slen ||\r
+ b->slen < 0 || b->mlen <= 0) return BSTR_ERR;\r
+ for (i=0, len = b->slen; i < len; i++) {\r
+ b->data[i] = (unsigned char) downcase (b->data[i]);\r
+ }\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bstricmp (const_bstring b0, const_bstring b1)\r
+ *\r
+ * Compare two strings without differentiating between case. The return \r
+ * value is the difference of the values of the characters where the two \r
+ * strings first differ after lower case transformation, otherwise 0 is \r
+ * returned indicating that the strings are equal. If the lengths are \r
+ * different, then a difference from 0 is given, but if the first extra \r
+ * character is '\0', then it is taken to be the value UCHAR_MAX+1.\r
+ */\r
+int bstricmp (const_bstring b0, const_bstring b1) {\r
+int i, v, n;\r
+\r
+ if (bdata (b0) == NULL || b0->slen < 0 || \r
+ bdata (b1) == NULL || b1->slen < 0) return SHRT_MIN;\r
+ if ((n = b0->slen) > b1->slen) n = b1->slen;\r
+ else if (b0->slen == b1->slen && b0->data == b1->data) return BSTR_OK;\r
+\r
+ for (i = 0; i < n; i ++) {\r
+ v = (char) downcase (b0->data[i])\r
+ - (char) downcase (b1->data[i]);\r
+ if (0 != v) return v;\r
+ }\r
+\r
+ if (b0->slen > n) {\r
+ v = (char) downcase (b0->data[n]);\r
+ if (v) return v;\r
+ return UCHAR_MAX + 1;\r
+ }\r
+ if (b1->slen > n) {\r
+ v = - (char) downcase (b1->data[n]);\r
+ if (v) return v;\r
+ return - (int) (UCHAR_MAX + 1);\r
+ }\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bstrnicmp (const_bstring b0, const_bstring b1, int n)\r
+ *\r
+ * Compare two strings without differentiating between case for at most n\r
+ * characters. If the position where the two strings first differ is\r
+ * before the nth position, the return value is the difference of the values\r
+ * of the characters, otherwise 0 is returned. If the lengths are different\r
+ * and less than n characters, then a difference from 0 is given, but if the \r
+ * first extra character is '\0', then it is taken to be the value \r
+ * UCHAR_MAX+1.\r
+ */\r
+int bstrnicmp (const_bstring b0, const_bstring b1, int n) {\r
+int i, v, m;\r
+\r
+ if (bdata (b0) == NULL || b0->slen < 0 || \r
+ bdata (b1) == NULL || b1->slen < 0 || n < 0) return SHRT_MIN;\r
+ m = n;\r
+ if (m > b0->slen) m = b0->slen;\r
+ if (m > b1->slen) m = b1->slen;\r
+\r
+ if (b0->data != b1->data) {\r
+ for (i = 0; i < m; i ++) {\r
+ v = (char) downcase (b0->data[i]);\r
+ v -= (char) downcase (b1->data[i]);\r
+ if (v != 0) return b0->data[i] - b1->data[i];\r
+ }\r
+ }\r
+\r
+ if (n == m || b0->slen == b1->slen) return BSTR_OK;\r
+\r
+ if (b0->slen > m) {\r
+ v = (char) downcase (b0->data[m]);\r
+ if (v) return v;\r
+ return UCHAR_MAX + 1;\r
+ }\r
+\r
+ v = - (char) downcase (b1->data[m]);\r
+ if (v) return v;\r
+ return - (int) (UCHAR_MAX + 1);\r
+}\r
+\r
+/* int biseqcaseless (const_bstring b0, const_bstring b1)\r
+ *\r
+ * Compare two strings for equality without differentiating between case. \r
+ * If the strings differ other than in case, 0 is returned, if the strings \r
+ * are the same, 1 is returned, if there is an error, -1 is returned. If \r
+ * the length of the strings are different, this function is O(1). '\0' \r
+ * termination characters are not treated in any special way.\r
+ */\r
+int biseqcaseless (const_bstring b0, const_bstring b1) {\r
+int i, n;\r
+\r
+ if (bdata (b0) == NULL || b0->slen < 0 || \r
+ bdata (b1) == NULL || b1->slen < 0) return BSTR_ERR;\r
+ if (b0->slen != b1->slen) return BSTR_OK;\r
+ if (b0->data == b1->data || b0->slen == 0) return 1;\r
+ for (i=0, n=b0->slen; i < n; i++) {\r
+ if (b0->data[i] != b1->data[i]) {\r
+ unsigned char c = (unsigned char) downcase (b0->data[i]);\r
+ if (c != (unsigned char) downcase (b1->data[i])) return 0;\r
+ }\r
+ }\r
+ return 1;\r
+}\r
+\r
+/* int bisstemeqcaselessblk (const_bstring b0, const void * blk, int len)\r
+ *\r
+ * Compare beginning of string b0 with a block of memory of length len \r
+ * without differentiating between case for equality. If the beginning of b0\r
+ * differs from the memory block other than in case (or if b0 is too short), \r
+ * 0 is returned, if the strings are the same, 1 is returned, if there is an \r
+ * error, -1 is returned. '\0' characters are not treated in any special \r
+ * way.\r
+ */\r
+int bisstemeqcaselessblk (const_bstring b0, const void * blk, int len) {\r
+int i;\r
+\r
+ if (bdata (b0) == NULL || b0->slen < 0 || NULL == blk || len < 0)\r
+ return BSTR_ERR;\r
+ if (b0->slen < len) return BSTR_OK;\r
+ if (b0->data == (const unsigned char *) blk || len == 0) return 1;\r
+\r
+ for (i = 0; i < len; i ++) {\r
+ if (b0->data[i] != ((const unsigned char *) blk)[i]) {\r
+ if (downcase (b0->data[i]) != \r
+ downcase (((const unsigned char *) blk)[i])) return 0;\r
+ }\r
+ }\r
+ return 1;\r
+}\r
+\r
+/*\r
+ * int bltrimws (bstring b)\r
+ *\r
+ * Delete whitespace contiguous from the left end of the string.\r
+ */\r
+int bltrimws (bstring b) {\r
+int i, len;\r
+\r
+ if (b == NULL || b->data == NULL || b->mlen < b->slen ||\r
+ b->slen < 0 || b->mlen <= 0) return BSTR_ERR;\r
+\r
+ for (len = b->slen, i = 0; i < len; i++) {\r
+ if (!wspace (b->data[i])) {\r
+ return bdelete (b, 0, i);\r
+ }\r
+ }\r
+\r
+ b->data[0] = (unsigned char) '\0';\r
+ b->slen = 0;\r
+ return BSTR_OK;\r
+}\r
+\r
+/*\r
+ * int brtrimws (bstring b)\r
+ *\r
+ * Delete whitespace contiguous from the right end of the string.\r
+ */\r
+int brtrimws (bstring b) {\r
+int i;\r
+\r
+ if (b == NULL || b->data == NULL || b->mlen < b->slen ||\r
+ b->slen < 0 || b->mlen <= 0) return BSTR_ERR;\r
+\r
+ for (i = b->slen - 1; i >= 0; i--) {\r
+ if (!wspace (b->data[i])) {\r
+ if (b->mlen > i) b->data[i+1] = (unsigned char) '\0';\r
+ b->slen = i + 1;\r
+ return BSTR_OK;\r
+ }\r
+ }\r
+\r
+ b->data[0] = (unsigned char) '\0';\r
+ b->slen = 0;\r
+ return BSTR_OK;\r
+}\r
+\r
+/*\r
+ * int btrimws (bstring b)\r
+ *\r
+ * Delete whitespace contiguous from both ends of the string.\r
+ */\r
+int btrimws (bstring b) {\r
+int i, j;\r
+\r
+ if (b == NULL || b->data == NULL || b->mlen < b->slen ||\r
+ b->slen < 0 || b->mlen <= 0) return BSTR_ERR;\r
+\r
+ for (i = b->slen - 1; i >= 0; i--) {\r
+ if (!wspace (b->data[i])) {\r
+ if (b->mlen > i) b->data[i+1] = (unsigned char) '\0';\r
+ b->slen = i + 1;\r
+ for (j = 0; wspace (b->data[j]); j++) {}\r
+ return bdelete (b, 0, j);\r
+ }\r
+ }\r
+\r
+ b->data[0] = (unsigned char) '\0';\r
+ b->slen = 0;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int biseq (const_bstring b0, const_bstring b1)\r
+ *\r
+ * Compare the string b0 and b1. If the strings differ, 0 is returned, if \r
+ * the strings are the same, 1 is returned, if there is an error, -1 is \r
+ * returned. If the length of the strings are different, this function is\r
+ * O(1). '\0' termination characters are not treated in any special way.\r
+ */\r
+int biseq (const_bstring b0, const_bstring b1) {\r
+ if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL ||\r
+ b0->slen < 0 || b1->slen < 0) return BSTR_ERR;\r
+ if (b0->slen != b1->slen) return BSTR_OK;\r
+ if (b0->data == b1->data || b0->slen == 0) return 1;\r
+ return !bstr__memcmp (b0->data, b1->data, b0->slen);\r
+}\r
+\r
+/* int bisstemeqblk (const_bstring b0, const void * blk, int len)\r
+ *\r
+ * Compare beginning of string b0 with a block of memory of length len for \r
+ * equality. If the beginning of b0 differs from the memory block (or if b0 \r
+ * is too short), 0 is returned, if the strings are the same, 1 is returned, \r
+ * if there is an error, -1 is returned. '\0' characters are not treated in \r
+ * any special way.\r
+ */\r
+int bisstemeqblk (const_bstring b0, const void * blk, int len) {\r
+int i;\r
+\r
+ if (bdata (b0) == NULL || b0->slen < 0 || NULL == blk || len < 0)\r
+ return BSTR_ERR;\r
+ if (b0->slen < len) return BSTR_OK;\r
+ if (b0->data == (const unsigned char *) blk || len == 0) return 1;\r
+\r
+ for (i = 0; i < len; i ++) {\r
+ if (b0->data[i] != ((const unsigned char *) blk)[i]) return BSTR_OK;\r
+ }\r
+ return 1;\r
+}\r
+\r
+/* int biseqcstr (const_bstring b, const char *s)\r
+ *\r
+ * Compare the bstring b and char * string s. The C string s must be '\0' \r
+ * terminated at exactly the length of the bstring b, and the contents \r
+ * between the two must be identical with the bstring b with no '\0' \r
+ * characters for the two contents to be considered equal. This is \r
+ * equivalent to the condition that their current contents will be always be \r
+ * equal when comparing them in the same format after converting one or the \r
+ * other. If the strings are equal 1 is returned, if they are unequal 0 is \r
+ * returned and if there is a detectable error BSTR_ERR is returned.\r
+ */\r
+int biseqcstr (const_bstring b, const char * s) {\r
+int i;\r
+ if (b == NULL || s == NULL || b->data == NULL || b->slen < 0) return BSTR_ERR;\r
+ for (i=0; i < b->slen; i++) {\r
+ if (s[i] == '\0' || b->data[i] != (unsigned char) s[i]) return BSTR_OK;\r
+ }\r
+ return s[i] == '\0';\r
+}\r
+\r
+/* int biseqcstrcaseless (const_bstring b, const char *s)\r
+ *\r
+ * Compare the bstring b and char * string s. The C string s must be '\0' \r
+ * terminated at exactly the length of the bstring b, and the contents \r
+ * between the two must be identical except for case with the bstring b with \r
+ * no '\0' characters for the two contents to be considered equal. This is \r
+ * equivalent to the condition that their current contents will be always be \r
+ * equal ignoring case when comparing them in the same format after \r
+ * converting one or the other. If the strings are equal, except for case, \r
+ * 1 is returned, if they are unequal regardless of case 0 is returned and \r
+ * if there is a detectable error BSTR_ERR is returned.\r
+ */\r
+int biseqcstrcaseless (const_bstring b, const char * s) {\r
+int i;\r
+ if (b == NULL || s == NULL || b->data == NULL || b->slen < 0) return BSTR_ERR;\r
+ for (i=0; i < b->slen; i++) {\r
+ if (s[i] == '\0' || \r
+ (b->data[i] != (unsigned char) s[i] && \r
+ downcase (b->data[i]) != (unsigned char) downcase (s[i])))\r
+ return BSTR_OK;\r
+ }\r
+ return s[i] == '\0';\r
+}\r
+\r
+/* int bstrcmp (const_bstring b0, const_bstring b1)\r
+ *\r
+ * Compare the string b0 and b1. If there is an error, SHRT_MIN is returned, \r
+ * otherwise a value less than or greater than zero, indicating that the \r
+ * string pointed to by b0 is lexicographically less than or greater than \r
+ * the string pointed to by b1 is returned. If the the string lengths are \r
+ * unequal but the characters up until the length of the shorter are equal \r
+ * then a value less than, or greater than zero, indicating that the string \r
+ * pointed to by b0 is shorter or longer than the string pointed to by b1 is \r
+ * returned. 0 is returned if and only if the two strings are the same. If \r
+ * the length of the strings are different, this function is O(n). Like its\r
+ * standard C library counter part strcmp, the comparison does not proceed \r
+ * past any '\0' termination characters encountered.\r
+ */\r
+int bstrcmp (const_bstring b0, const_bstring b1) {\r
+int i, v, n;\r
+\r
+ if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL ||\r
+ b0->slen < 0 || b1->slen < 0) return SHRT_MIN;\r
+ n = b0->slen; if (n > b1->slen) n = b1->slen;\r
+ if (b0->slen == b1->slen && (b0->data == b1->data || b0->slen == 0))\r
+ return BSTR_OK;\r
+\r
+ for (i = 0; i < n; i ++) {\r
+ v = ((char) b0->data[i]) - ((char) b1->data[i]);\r
+ if (v != 0) return v;\r
+ if (b0->data[i] == (unsigned char) '\0') return BSTR_OK;\r
+ }\r
+\r
+ if (b0->slen > n) return 1;\r
+ if (b1->slen > n) return -1;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bstrncmp (const_bstring b0, const_bstring b1, int n)\r
+ *\r
+ * Compare the string b0 and b1 for at most n characters. If there is an \r
+ * error, SHRT_MIN is returned, otherwise a value is returned as if b0 and \r
+ * b1 were first truncated to at most n characters then bstrcmp was called\r
+ * with these new strings are paremeters. If the length of the strings are \r
+ * different, this function is O(n). Like its standard C library counter \r
+ * part strcmp, the comparison does not proceed past any '\0' termination \r
+ * characters encountered.\r
+ */\r
+int bstrncmp (const_bstring b0, const_bstring b1, int n) {\r
+int i, v, m;\r
+\r
+ if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL ||\r
+ b0->slen < 0 || b1->slen < 0) return SHRT_MIN;\r
+ m = n;\r
+ if (m > b0->slen) m = b0->slen;\r
+ if (m > b1->slen) m = b1->slen;\r
+\r
+ if (b0->data != b1->data) {\r
+ for (i = 0; i < m; i ++) {\r
+ v = ((char) b0->data[i]) - ((char) b1->data[i]);\r
+ if (v != 0) return v;\r
+ if (b0->data[i] == (unsigned char) '\0') return BSTR_OK;\r
+ }\r
+ }\r
+\r
+ if (n == m || b0->slen == b1->slen) return BSTR_OK;\r
+\r
+ if (b0->slen > m) return 1;\r
+ return -1;\r
+}\r
+\r
+/* bstring bmidstr (const_bstring b, int left, int len)\r
+ *\r
+ * Create a bstring which is the substring of b starting from position left\r
+ * and running for a length len (clamped by the end of the bstring b.) If\r
+ * b is detectably invalid, then NULL is returned. The section described \r
+ * by (left, len) is clamped to the boundaries of b.\r
+ */\r
+bstring bmidstr (const_bstring b, int left, int len) {\r
+\r
+ if (b == NULL || b->slen < 0 || b->data == NULL) return NULL;\r
+\r
+ if (left < 0) {\r
+ len += left;\r
+ left = 0;\r
+ }\r
+\r
+ if (len > b->slen - left) len = b->slen - left;\r
+\r
+ if (len <= 0) return bfromcstr ("");\r
+ return blk2bstr (b->data + left, len);\r
+}\r
+\r
+/* int bdelete (bstring b, int pos, int len)\r
+ *\r
+ * Removes characters from pos to pos+len-1 inclusive and shifts the tail of \r
+ * the bstring starting from pos+len to pos. len must be positive for this \r
+ * call to have any effect. The section of the string described by (pos, \r
+ * len) is clamped to boundaries of the bstring b.\r
+ */\r
+int bdelete (bstring b, int pos, int len) {\r
+ /* Clamp to left side of bstring */\r
+ if (pos < 0) {\r
+ len += pos;\r
+ pos = 0;\r
+ }\r
+\r
+ if (len < 0 || b == NULL || b->data == NULL || b->slen < 0 || \r
+ b->mlen < b->slen || b->mlen <= 0) \r
+ return BSTR_ERR;\r
+ if (len > 0 && pos < b->slen) {\r
+ if (pos + len >= b->slen) {\r
+ b->slen = pos;\r
+ } else {\r
+ bBlockCopy ((char *) (b->data + pos),\r
+ (char *) (b->data + pos + len), \r
+ b->slen - (pos+len));\r
+ b->slen -= len;\r
+ }\r
+ b->data[b->slen] = (unsigned char) '\0';\r
+ }\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bdestroy (bstring b)\r
+ *\r
+ * Free up the bstring. Note that if b is detectably invalid or not writable\r
+ * then no action is performed and BSTR_ERR is returned. Like a freed memory\r
+ * allocation, dereferences, writes or any other action on b after it has \r
+ * been bdestroyed is undefined.\r
+ */\r
+int bdestroy (bstring b) {\r
+ if (b == NULL || b->slen < 0 || b->mlen <= 0 || b->mlen < b->slen ||\r
+ b->data == NULL)\r
+ return BSTR_ERR;\r
+\r
+ bstr__free (b->data);\r
+\r
+ /* In case there is any stale usage, there is one more chance to \r
+ notice this error. */\r
+\r
+ b->slen = -1;\r
+ b->mlen = -__LINE__;\r
+ b->data = NULL;\r
+\r
+ bstr__free (b);\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int binstr (const_bstring b1, int pos, const_bstring b2)\r
+ *\r
+ * Search for the bstring b2 in b1 starting from position pos, and searching \r
+ * forward. If it is found then return with the first position where it is \r
+ * found, otherwise return BSTR_ERR. Note that this is just a brute force \r
+ * string searcher that does not attempt clever things like the Boyer-Moore \r
+ * search algorithm. Because of this there are many degenerate cases where \r
+ * this can take much longer than it needs to.\r
+ */\r
+int binstr (const_bstring b1, int pos, const_bstring b2) {\r
+int j, ii, ll, lf;\r
+unsigned char * d0;\r
+unsigned char c0;\r
+register unsigned char * d1;\r
+register unsigned char c1;\r
+register int i;\r
+\r
+ if (b1 == NULL || b1->data == NULL || b1->slen < 0 ||\r
+ b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR;\r
+ if (b1->slen == pos) return (b2->slen == 0)?pos:BSTR_ERR;\r
+ if (b1->slen < pos || pos < 0) return BSTR_ERR;\r
+ if (b2->slen == 0) return pos;\r
+\r
+ /* No space to find such a string? */\r
+ if ((lf = b1->slen - b2->slen + 1) <= pos) return BSTR_ERR;\r
+\r
+ /* An obvious alias case */\r
+ if (b1->data == b2->data && pos == 0) return 0;\r
+\r
+ i = pos;\r
+\r
+ d0 = b2->data;\r
+ d1 = b1->data;\r
+ ll = b2->slen;\r
+\r
+ /* Peel off the b2->slen == 1 case */\r
+ c0 = d0[0];\r
+ if (1 == ll) {\r
+ for (;i < lf; i++) if (c0 == d1[i]) return i;\r
+ return BSTR_ERR;\r
+ }\r
+\r
+ c1 = c0;\r
+ j = 0;\r
+ lf = b1->slen - 1;\r
+\r
+ ii = -1;\r
+ if (i < lf) do {\r
+ /* Unrolled current character test */\r
+ if (c1 != d1[i]) {\r
+ if (c1 != d1[1+i]) {\r
+ i += 2;\r
+ continue;\r
+ }\r
+ i++;\r
+ }\r
+\r
+ /* Take note if this is the start of a potential match */\r
+ if (0 == j) ii = i;\r
+\r
+ /* Shift the test character down by one */\r
+ j++;\r
+ i++;\r
+\r
+ /* If this isn't past the last character continue */\r
+ if (j < ll) {\r
+ c1 = d0[j];\r
+ continue;\r
+ }\r
+\r
+ N0:;\r
+\r
+ /* If no characters mismatched, then we matched */\r
+ if (i == ii+j) return ii;\r
+\r
+ /* Shift back to the beginning */\r
+ i -= j;\r
+ j = 0;\r
+ c1 = c0;\r
+ } while (i < lf);\r
+\r
+ /* Deal with last case if unrolling caused a misalignment */\r
+ if (i == lf && ll == j+1 && c1 == d1[i]) goto N0;\r
+\r
+ return BSTR_ERR;\r
+}\r
+\r
+/* int binstrr (const_bstring b1, int pos, const_bstring b2)\r
+ *\r
+ * Search for the bstring b2 in b1 starting from position pos, and searching \r
+ * backward. If it is found then return with the first position where it is \r
+ * found, otherwise return BSTR_ERR. Note that this is just a brute force \r
+ * string searcher that does not attempt clever things like the Boyer-Moore \r
+ * search algorithm. Because of this there are many degenerate cases where \r
+ * this can take much longer than it needs to.\r
+ */\r
+int binstrr (const_bstring b1, int pos, const_bstring b2) {\r
+int j, i, l;\r
+unsigned char * d0, * d1;\r
+\r
+ if (b1 == NULL || b1->data == NULL || b1->slen < 0 ||\r
+ b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR;\r
+ if (b1->slen == pos && b2->slen == 0) return pos;\r
+ if (b1->slen < pos || pos < 0) return BSTR_ERR;\r
+ if (b2->slen == 0) return pos;\r
+\r
+ /* Obvious alias case */\r
+ if (b1->data == b2->data && pos == 0 && b2->slen <= b1->slen) return 0;\r
+\r
+ i = pos;\r
+ if ((l = b1->slen - b2->slen) < 0) return BSTR_ERR;\r
+\r
+ /* If no space to find such a string then snap back */\r
+ if (l + 1 <= i) i = l;\r
+ j = 0;\r
+\r
+ d0 = b2->data;\r
+ d1 = b1->data;\r
+ l = b2->slen;\r
+\r
+ for (;;) {\r
+ if (d0[j] == d1[i + j]) {\r
+ j ++;\r
+ if (j >= l) return i;\r
+ } else {\r
+ i --;\r
+ if (i < 0) break;\r
+ j=0;\r
+ }\r
+ }\r
+\r
+ return BSTR_ERR;\r
+}\r
+\r
+/* int binstrcaseless (const_bstring b1, int pos, const_bstring b2)\r
+ *\r
+ * Search for the bstring b2 in b1 starting from position pos, and searching \r
+ * forward but without regard to case. If it is found then return with the \r
+ * first position where it is found, otherwise return BSTR_ERR. Note that \r
+ * this is just a brute force string searcher that does not attempt clever \r
+ * things like the Boyer-Moore search algorithm. Because of this there are \r
+ * many degenerate cases where this can take much longer than it needs to.\r
+ */\r
+int binstrcaseless (const_bstring b1, int pos, const_bstring b2) {\r
+int j, i, l, ll;\r
+unsigned char * d0, * d1;\r
+\r
+ if (b1 == NULL || b1->data == NULL || b1->slen < 0 ||\r
+ b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR;\r
+ if (b1->slen == pos) return (b2->slen == 0)?pos:BSTR_ERR;\r
+ if (b1->slen < pos || pos < 0) return BSTR_ERR;\r
+ if (b2->slen == 0) return pos;\r
+\r
+ l = b1->slen - b2->slen + 1;\r
+\r
+ /* No space to find such a string? */\r
+ if (l <= pos) return BSTR_ERR;\r
+\r
+ /* An obvious alias case */\r
+ if (b1->data == b2->data && pos == 0) return BSTR_OK;\r
+\r
+ i = pos;\r
+ j = 0;\r
+\r
+ d0 = b2->data;\r
+ d1 = b1->data;\r
+ ll = b2->slen;\r
+\r
+ for (;;) {\r
+ if (d0[j] == d1[i + j] || downcase (d0[j]) == downcase (d1[i + j])) {\r
+ j ++;\r
+ if (j >= ll) return i;\r
+ } else {\r
+ i ++;\r
+ if (i >= l) break;\r
+ j=0;\r
+ }\r
+ }\r
+\r
+ return BSTR_ERR;\r
+}\r
+\r
+/* int binstrrcaseless (const_bstring b1, int pos, const_bstring b2)\r
+ *\r
+ * Search for the bstring b2 in b1 starting from position pos, and searching \r
+ * backward but without regard to case. If it is found then return with the \r
+ * first position where it is found, otherwise return BSTR_ERR. Note that \r
+ * this is just a brute force string searcher that does not attempt clever \r
+ * things like the Boyer-Moore search algorithm. Because of this there are \r
+ * many degenerate cases where this can take much longer than it needs to.\r
+ */\r
+int binstrrcaseless (const_bstring b1, int pos, const_bstring b2) {\r
+int j, i, l;\r
+unsigned char * d0, * d1;\r
+\r
+ if (b1 == NULL || b1->data == NULL || b1->slen < 0 ||\r
+ b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR;\r
+ if (b1->slen == pos && b2->slen == 0) return pos;\r
+ if (b1->slen < pos || pos < 0) return BSTR_ERR;\r
+ if (b2->slen == 0) return pos;\r
+\r
+ /* Obvious alias case */\r
+ if (b1->data == b2->data && pos == 0 && b2->slen <= b1->slen) return BSTR_OK;\r
+\r
+ i = pos;\r
+ if ((l = b1->slen - b2->slen) < 0) return BSTR_ERR;\r
+\r
+ /* If no space to find such a string then snap back */\r
+ if (l + 1 <= i) i = l;\r
+ j = 0;\r
+\r
+ d0 = b2->data;\r
+ d1 = b1->data;\r
+ l = b2->slen;\r
+\r
+ for (;;) {\r
+ if (d0[j] == d1[i + j] || downcase (d0[j]) == downcase (d1[i + j])) {\r
+ j ++;\r
+ if (j >= l) return i;\r
+ } else {\r
+ i --;\r
+ if (i < 0) break;\r
+ j=0;\r
+ }\r
+ }\r
+\r
+ return BSTR_ERR;\r
+}\r
+\r
+\r
+/* int bstrchrp (const_bstring b, int c, int pos)\r
+ *\r
+ * Search for the character c in b forwards from the position pos \r
+ * (inclusive).\r
+ */\r
+int bstrchrp (const_bstring b, int c, int pos) {\r
+unsigned char * p;\r
+\r
+ if (b == NULL || b->data == NULL || b->slen <= pos || pos < 0) return BSTR_ERR;\r
+ p = (unsigned char *) bstr__memchr ((b->data + pos), (unsigned char) c, (b->slen - pos));\r
+ if (p) return (int) (p - b->data);\r
+ return BSTR_ERR;\r
+}\r
+\r
+/* int bstrrchrp (const_bstring b, int c, int pos)\r
+ *\r
+ * Search for the character c in b backwards from the position pos in string \r
+ * (inclusive).\r
+ */\r
+int bstrrchrp (const_bstring b, int c, int pos) {\r
+int i;\r
+ \r
+ if (b == NULL || b->data == NULL || b->slen <= pos || pos < 0) return BSTR_ERR;\r
+ for (i=pos; i >= 0; i--) {\r
+ if (b->data[i] == (unsigned char) c) return i;\r
+ }\r
+ return BSTR_ERR;\r
+}\r
+\r
+#if !defined (BSTRLIB_AGGRESSIVE_MEMORY_FOR_SPEED_TRADEOFF)\r
+#define LONG_LOG_BITS_QTY (3)\r
+#define LONG_BITS_QTY (1 << LONG_LOG_BITS_QTY)\r
+#define LONG_TYPE unsigned char\r
+\r
+#define CFCLEN ((1 << CHAR_BIT) / LONG_BITS_QTY)\r
+struct charField { LONG_TYPE content[CFCLEN]; };\r
+#define testInCharField(cf,c) ((cf)->content[(c) >> LONG_LOG_BITS_QTY] & (((long)1) << ((c) & (LONG_BITS_QTY-1))))\r
+#define setInCharField(cf,idx) { \\r
+ unsigned int c = (unsigned int) (idx); \\r
+ (cf)->content[c >> LONG_LOG_BITS_QTY] |= (LONG_TYPE) (1ul << (c & (LONG_BITS_QTY-1))); \\r
+}\r
+\r
+#else\r
+\r
+#define CFCLEN (1 << CHAR_BIT)\r
+struct charField { unsigned char content[CFCLEN]; };\r
+#define testInCharField(cf,c) ((cf)->content[(unsigned char) (c)])\r
+#define setInCharField(cf,idx) (cf)->content[(unsigned int) (idx)] = ~0\r
+\r
+#endif\r
+\r
+/* Convert a bstring to charField */\r
+static int buildCharField (struct charField * cf, const_bstring b) {\r
+int i;\r
+ if (b == NULL || b->data == NULL || b->slen <= 0) return BSTR_ERR;\r
+ memset ((void *) cf->content, 0, sizeof (struct charField));\r
+ for (i=0; i < b->slen; i++) {\r
+ setInCharField (cf, b->data[i]);\r
+ }\r
+ return BSTR_OK;\r
+}\r
+\r
+static void invertCharField (struct charField * cf) {\r
+int i;\r
+ for (i=0; i < CFCLEN; i++) cf->content[i] = ~cf->content[i];\r
+}\r
+\r
+/* Inner engine for binchr */\r
+static int binchrCF (const unsigned char * data, int len, int pos, const struct charField * cf) {\r
+int i;\r
+ for (i=pos; i < len; i++) {\r
+ unsigned char c = (unsigned char) data[i];\r
+ if (testInCharField (cf, c)) return i;\r
+ }\r
+ return BSTR_ERR;\r
+}\r
+\r
+/* int binchr (const_bstring b0, int pos, const_bstring b1);\r
+ *\r
+ * Search for the first position in b0 starting from pos or after, in which \r
+ * one of the characters in b1 is found and return it. If such a position \r
+ * does not exist in b0, then BSTR_ERR is returned.\r
+ */\r
+int binchr (const_bstring b0, int pos, const_bstring b1) {\r
+struct charField chrs;\r
+ if (pos < 0 || b0 == NULL || b0->data == NULL ||\r
+ b0->slen <= pos) return BSTR_ERR;\r
+ if (1 == b1->slen) return bstrchrp (b0, b1->data[0], pos);\r
+ if (0 > buildCharField (&chrs, b1)) return BSTR_ERR;\r
+ return binchrCF (b0->data, b0->slen, pos, &chrs);\r
+}\r
+\r
+/* Inner engine for binchrr */\r
+static int binchrrCF (const unsigned char * data, int pos, const struct charField * cf) {\r
+int i;\r
+ for (i=pos; i >= 0; i--) {\r
+ unsigned int c = (unsigned int) data[i];\r
+ if (testInCharField (cf, c)) return i;\r
+ }\r
+ return BSTR_ERR;\r
+}\r
+\r
+/* int binchrr (const_bstring b0, int pos, const_bstring b1);\r
+ *\r
+ * Search for the last position in b0 no greater than pos, in which one of \r
+ * the characters in b1 is found and return it. If such a position does not \r
+ * exist in b0, then BSTR_ERR is returned.\r
+ */\r
+int binchrr (const_bstring b0, int pos, const_bstring b1) {\r
+struct charField chrs;\r
+ if (pos < 0 || b0 == NULL || b0->data == NULL || b1 == NULL ||\r
+ b0->slen < pos) return BSTR_ERR;\r
+ if (pos == b0->slen) pos--;\r
+ if (1 == b1->slen) return bstrrchrp (b0, b1->data[0], pos);\r
+ if (0 > buildCharField (&chrs, b1)) return BSTR_ERR;\r
+ return binchrrCF (b0->data, pos, &chrs);\r
+}\r
+\r
+/* int bninchr (const_bstring b0, int pos, const_bstring b1);\r
+ *\r
+ * Search for the first position in b0 starting from pos or after, in which \r
+ * none of the characters in b1 is found and return it. If such a position \r
+ * does not exist in b0, then BSTR_ERR is returned.\r
+ */\r
+int bninchr (const_bstring b0, int pos, const_bstring b1) {\r
+struct charField chrs;\r
+ if (pos < 0 || b0 == NULL || b0->data == NULL || \r
+ b0->slen <= pos) return BSTR_ERR;\r
+ if (buildCharField (&chrs, b1) < 0) return BSTR_ERR;\r
+ invertCharField (&chrs);\r
+ return binchrCF (b0->data, b0->slen, pos, &chrs);\r
+}\r
+\r
+/* int bninchrr (const_bstring b0, int pos, const_bstring b1);\r
+ *\r
+ * Search for the last position in b0 no greater than pos, in which none of \r
+ * the characters in b1 is found and return it. If such a position does not \r
+ * exist in b0, then BSTR_ERR is returned.\r
+ */\r
+int bninchrr (const_bstring b0, int pos, const_bstring b1) {\r
+struct charField chrs;\r
+ if (pos < 0 || b0 == NULL || b0->data == NULL || \r
+ b0->slen < pos) return BSTR_ERR;\r
+ if (pos == b0->slen) pos--;\r
+ if (buildCharField (&chrs, b1) < 0) return BSTR_ERR;\r
+ invertCharField (&chrs);\r
+ return binchrrCF (b0->data, pos, &chrs);\r
+}\r
+\r
+/* int bsetstr (bstring b0, int pos, bstring b1, unsigned char fill)\r
+ *\r
+ * Overwrite the string b0 starting at position pos with the string b1. If \r
+ * the position pos is past the end of b0, then the character "fill" is \r
+ * appended as necessary to make up the gap between the end of b0 and pos.\r
+ * If b1 is NULL, it behaves as if it were a 0-length string.\r
+ */\r
+int bsetstr (bstring b0, int pos, const_bstring b1, unsigned char fill) {\r
+int d, newlen;\r
+ptrdiff_t pd;\r
+bstring aux = (bstring) b1;\r
+\r
+ if (pos < 0 || b0 == NULL || b0->slen < 0 || NULL == b0->data || \r
+ b0->mlen < b0->slen || b0->mlen <= 0) return BSTR_ERR;\r
+ if (b1 != NULL && (b1->slen < 0 || b1->data == NULL)) return BSTR_ERR;\r
+\r
+ d = pos;\r
+\r
+ /* Aliasing case */\r
+ if (NULL != aux) {\r
+ if ((pd = (ptrdiff_t) (b1->data - b0->data)) >= 0 && pd < (ptrdiff_t) b0->mlen) {\r
+ if (NULL == (aux = bstrcpy (b1))) return BSTR_ERR;\r
+ }\r
+ d += aux->slen;\r
+ }\r
+\r
+ /* Increase memory size if necessary */\r
+ if (balloc (b0, d + 1) != BSTR_OK) {\r
+ if (aux != b1) bdestroy (aux);\r
+ return BSTR_ERR;\r
+ }\r
+\r
+ newlen = b0->slen;\r
+\r
+ /* Fill in "fill" character as necessary */\r
+ if (pos > newlen) {\r
+ bstr__memset (b0->data + b0->slen, (int) fill, (size_t) (pos - b0->slen));\r
+ newlen = pos;\r
+ }\r
+\r
+ /* Copy b1 to position pos in b0. */\r
+ if (aux != NULL) {\r
+ bBlockCopy ((char *) (b0->data + pos), (char *) aux->data, aux->slen);\r
+ if (aux != b1) bdestroy (aux);\r
+ }\r
+\r
+ /* Indicate the potentially increased size of b0 */\r
+ if (d > newlen) newlen = d;\r
+\r
+ b0->slen = newlen;\r
+ b0->data[newlen] = (unsigned char) '\0';\r
+\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int binsert (bstring b1, int pos, bstring b2, unsigned char fill)\r
+ *\r
+ * Inserts the string b2 into b1 at position pos. If the position pos is \r
+ * past the end of b1, then the character "fill" is appended as necessary to \r
+ * make up the gap between the end of b1 and pos. Unlike bsetstr, binsert\r
+ * does not allow b2 to be NULL.\r
+ */\r
+int binsert (bstring b1, int pos, const_bstring b2, unsigned char fill) {\r
+int d, l;\r
+ptrdiff_t pd;\r
+bstring aux = (bstring) b2;\r
+\r
+ if (pos < 0 || b1 == NULL || b2 == NULL || b1->slen < 0 || \r
+ b2->slen < 0 || b1->mlen < b1->slen || b1->mlen <= 0) return BSTR_ERR;\r
+\r
+ /* Aliasing case */\r
+ if ((pd = (ptrdiff_t) (b2->data - b1->data)) >= 0 && pd < (ptrdiff_t) b1->mlen) {\r
+ if (NULL == (aux = bstrcpy (b2))) return BSTR_ERR;\r
+ }\r
+\r
+ /* Compute the two possible end pointers */\r
+ d = b1->slen + aux->slen;\r
+ l = pos + aux->slen;\r
+ if ((d|l) < 0) return BSTR_ERR;\r
+\r
+ if (l > d) {\r
+ /* Inserting past the end of the string */\r
+ if (balloc (b1, l + 1) != BSTR_OK) {\r
+ if (aux != b2) bdestroy (aux);\r
+ return BSTR_ERR;\r
+ }\r
+ bstr__memset (b1->data + b1->slen, (int) fill, (size_t) (pos - b1->slen));\r
+ b1->slen = l;\r
+ } else {\r
+ /* Inserting in the middle of the string */\r
+ if (balloc (b1, d + 1) != BSTR_OK) {\r
+ if (aux != b2) bdestroy (aux);\r
+ return BSTR_ERR;\r
+ }\r
+ bBlockCopy (b1->data + l, b1->data + pos, d - l);\r
+ b1->slen = d;\r
+ }\r
+ bBlockCopy (b1->data + pos, aux->data, aux->slen);\r
+ b1->data[b1->slen] = (unsigned char) '\0';\r
+ if (aux != b2) bdestroy (aux);\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int breplace (bstring b1, int pos, int len, bstring b2, \r
+ * unsigned char fill)\r
+ *\r
+ * Replace a section of a string from pos for a length len with the string b2.\r
+ * fill is used is pos > b1->slen.\r
+ */\r
+int breplace (bstring b1, int pos, int len, const_bstring b2, \r
+ unsigned char fill) {\r
+int pl, ret;\r
+ptrdiff_t pd;\r
+bstring aux = (bstring) b2;\r
+\r
+ if (pos < 0 || len < 0 || (pl = pos + len) < 0 || b1 == NULL || \r
+ b2 == NULL || b1->data == NULL || b2->data == NULL || \r
+ b1->slen < 0 || b2->slen < 0 || b1->mlen < b1->slen ||\r
+ b1->mlen <= 0) return BSTR_ERR;\r
+\r
+ /* Straddles the end? */\r
+ if (pl >= b1->slen) {\r
+ if ((ret = bsetstr (b1, pos, b2, fill)) < 0) return ret;\r
+ if (pos + b2->slen < b1->slen) {\r
+ b1->slen = pos + b2->slen;\r
+ b1->data[b1->slen] = (unsigned char) '\0';\r
+ }\r
+ return ret;\r
+ }\r
+\r
+ /* Aliasing case */\r
+ if ((pd = (ptrdiff_t) (b2->data - b1->data)) >= 0 && pd < (ptrdiff_t) b1->slen) {\r
+ if (NULL == (aux = bstrcpy (b2))) return BSTR_ERR;\r
+ }\r
+\r
+ if (aux->slen > len) {\r
+ if (balloc (b1, b1->slen + aux->slen - len) != BSTR_OK) {\r
+ if (aux != b2) bdestroy (aux);\r
+ return BSTR_ERR;\r
+ }\r
+ }\r
+\r
+ if (aux->slen != len) bstr__memmove (b1->data + pos + aux->slen, b1->data + pos + len, b1->slen - (pos + len));\r
+ bstr__memcpy (b1->data + pos, aux->data, aux->slen);\r
+ b1->slen += aux->slen - len;\r
+ b1->data[b1->slen] = (unsigned char) '\0';\r
+ if (aux != b2) bdestroy (aux);\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bfindreplace (bstring b, const_bstring find, const_bstring repl, \r
+ * int pos)\r
+ *\r
+ * Replace all occurrences of a find string with a replace string after a\r
+ * given point in a bstring.\r
+ */\r
+\r
+typedef int (*instr_fnptr) (const_bstring s1, int pos, const_bstring s2);\r
+\r
+static int findreplaceengine (bstring b, const_bstring find, const_bstring repl, int pos, instr_fnptr instr) {\r
+int i, ret, slen, mlen, delta, acc;\r
+int * d;\r
+int static_d[32];\r
+ptrdiff_t pd;\r
+bstring auxf = (bstring) find;\r
+bstring auxr = (bstring) repl;\r
+\r
+ if (b == NULL || b->data == NULL || find == NULL ||\r
+ find->data == NULL || repl == NULL || repl->data == NULL || \r
+ pos < 0 || find->slen <= 0 || b->mlen < 0 || b->slen > b->mlen || \r
+ b->mlen <= 0 || b->slen < 0 || repl->slen < 0) return BSTR_ERR;\r
+ if (pos > b->slen - find->slen) return BSTR_OK;\r
+\r
+ /* Alias with find string */\r
+ pd = (ptrdiff_t) (find->data - b->data);\r
+ if ((ptrdiff_t) (pos - find->slen) < pd && pd < (ptrdiff_t) b->slen) {\r
+ if (NULL == (auxf = bstrcpy (find))) return BSTR_ERR;\r
+ }\r
+\r
+ /* Alias with repl string */\r
+ pd = (ptrdiff_t) (repl->data - b->data);\r
+ if ((ptrdiff_t) (pos - repl->slen) < pd && pd < (ptrdiff_t) b->slen) {\r
+ if (NULL == (auxr = bstrcpy (repl))) {\r
+ if (auxf != find) bdestroy (auxf);\r
+ return BSTR_ERR;\r
+ }\r
+ }\r
+\r
+ delta = auxf->slen - auxr->slen;\r
+\r
+ /* in-place replacement since find and replace strings are of equal \r
+ length */\r
+ if (delta == 0) {\r
+ while ((pos = instr (b, pos, auxf)) >= 0) {\r
+ bstr__memcpy (b->data + pos, auxr->data, auxr->slen);\r
+ pos += auxf->slen;\r
+ }\r
+ if (auxf != find) bdestroy (auxf);\r
+ if (auxr != repl) bdestroy (auxr);\r
+ return BSTR_OK;\r
+ }\r
+\r
+ /* shrinking replacement since auxf->slen > auxr->slen */\r
+ if (delta > 0) {\r
+ acc = 0;\r
+\r
+ while ((i = instr (b, pos, auxf)) >= 0) {\r
+ if (acc && i > pos)\r
+ bstr__memmove (b->data + pos - acc, b->data + pos, i - pos);\r
+ if (auxr->slen)\r
+ bstr__memcpy (b->data + i - acc, auxr->data, auxr->slen);\r
+ acc += delta;\r
+ pos = i + auxf->slen;\r
+ }\r
+\r
+ if (acc) {\r
+ i = b->slen;\r
+ if (i > pos)\r
+ bstr__memmove (b->data + pos - acc, b->data + pos, i - pos);\r
+ b->slen -= acc;\r
+ b->data[b->slen] = (unsigned char) '\0';\r
+ }\r
+\r
+ if (auxf != find) bdestroy (auxf);\r
+ if (auxr != repl) bdestroy (auxr);\r
+ return BSTR_OK;\r
+ }\r
+\r
+ /* expanding replacement since find->slen < repl->slen. Its a lot \r
+ more complicated. */\r
+\r
+ mlen = 32;\r
+ d = (int *) static_d; /* Avoid malloc for trivial cases */\r
+ acc = slen = 0;\r
+\r
+ while ((pos = instr (b, pos, auxf)) >= 0) {\r
+ if (slen + 1 >= mlen) {\r
+ int sl;\r
+ int * t;\r
+ mlen += mlen;\r
+ sl = sizeof (int *) * mlen;\r
+ if (static_d == d) d = NULL;\r
+ if (sl < mlen || NULL == (t = (int *) bstr__realloc (d, sl))) {\r
+ ret = BSTR_ERR;\r
+ goto done;\r
+ }\r
+ if (NULL == d) bstr__memcpy (t, static_d, sizeof (static_d));\r
+ d = t;\r
+ }\r
+ d[slen] = pos;\r
+ slen++;\r
+ acc -= delta;\r
+ pos += auxf->slen;\r
+ if (pos < 0 || acc < 0) {\r
+ ret = BSTR_ERR;\r
+ goto done;\r
+ }\r
+ }\r
+ d[slen] = b->slen;\r
+\r
+ if (BSTR_OK == (ret = balloc (b, b->slen + acc + 1))) {\r
+ b->slen += acc;\r
+ for (i = slen-1; i >= 0; i--) {\r
+ int s, l;\r
+ s = d[i] + auxf->slen;\r
+ l = d[i+1] - s;\r
+ if (l) {\r
+ bstr__memmove (b->data + s + acc, b->data + s, l);\r
+ }\r
+ if (auxr->slen) {\r
+ bstr__memmove (b->data + s + acc - auxr->slen, \r
+ auxr->data, auxr->slen);\r
+ }\r
+ acc += delta; \r
+ }\r
+ b->data[b->slen] = (unsigned char) '\0';\r
+ }\r
+\r
+ done:;\r
+ if (static_d == d) d = NULL;\r
+ bstr__free (d);\r
+ if (auxf != find) bdestroy (auxf);\r
+ if (auxr != repl) bdestroy (auxr);\r
+ return ret;\r
+}\r
+\r
+/* int bfindreplace (bstring b, const_bstring find, const_bstring repl, \r
+ * int pos)\r
+ *\r
+ * Replace all occurrences of a find string with a replace string after a\r
+ * given point in a bstring.\r
+ */\r
+int bfindreplace (bstring b, const_bstring find, const_bstring repl, int pos) {\r
+ return findreplaceengine (b, find, repl, pos, binstr);\r
+}\r
+\r
+/* int bfindreplacecaseless (bstring b, const_bstring find, const_bstring repl, \r
+ * int pos)\r
+ *\r
+ * Replace all occurrences of a find string, ignoring case, with a replace \r
+ * string after a given point in a bstring.\r
+ */\r
+int bfindreplacecaseless (bstring b, const_bstring find, const_bstring repl, int pos) {\r
+ return findreplaceengine (b, find, repl, pos, binstrcaseless);\r
+}\r
+\r
+/* int binsertch (bstring b, int pos, int len, unsigned char fill)\r
+ *\r
+ * Inserts the character fill repeatedly into b at position pos for a \r
+ * length len. If the position pos is past the end of b, then the \r
+ * character "fill" is appended as necessary to make up the gap between the \r
+ * end of b and the position pos + len.\r
+ */\r
+int binsertch (bstring b, int pos, int len, unsigned char fill) {\r
+int d, l, i;\r
+\r
+ if (pos < 0 || b == NULL || b->slen < 0 || b->mlen < b->slen ||\r
+ b->mlen <= 0 || len < 0) return BSTR_ERR;\r
+\r
+ /* Compute the two possible end pointers */\r
+ d = b->slen + len;\r
+ l = pos + len;\r
+ if ((d|l) < 0) return BSTR_ERR;\r
+\r
+ if (l > d) {\r
+ /* Inserting past the end of the string */\r
+ if (balloc (b, l + 1) != BSTR_OK) return BSTR_ERR;\r
+ pos = b->slen;\r
+ b->slen = l;\r
+ } else {\r
+ /* Inserting in the middle of the string */\r
+ if (balloc (b, d + 1) != BSTR_OK) return BSTR_ERR;\r
+ for (i = d - 1; i >= l; i--) {\r
+ b->data[i] = b->data[i - len];\r
+ }\r
+ b->slen = d;\r
+ }\r
+\r
+ for (i=pos; i < l; i++) b->data[i] = fill;\r
+ b->data[b->slen] = (unsigned char) '\0';\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bpattern (bstring b, int len)\r
+ *\r
+ * Replicate the bstring, b in place, end to end repeatedly until it \r
+ * surpasses len characters, then chop the result to exactly len characters. \r
+ * This function operates in-place. The function will return with BSTR_ERR \r
+ * if b is NULL or of length 0, otherwise BSTR_OK is returned.\r
+ */\r
+int bpattern (bstring b, int len) {\r
+int i, d;\r
+\r
+ d = blength (b);\r
+ if (d <= 0 || len < 0 || balloc (b, len + 1) != BSTR_OK) return BSTR_ERR;\r
+ if (len > 0) {\r
+ if (d == 1) return bsetstr (b, len, NULL, b->data[0]);\r
+ for (i = d; i < len; i++) b->data[i] = b->data[i - d];\r
+ }\r
+ b->data[len] = (unsigned char) '\0';\r
+ b->slen = len;\r
+ return BSTR_OK;\r
+}\r
+\r
+#define BS_BUFF_SZ (1024)\r
+\r
+/* int breada (bstring b, bNread readPtr, void * parm)\r
+ *\r
+ * Use a finite buffer fread-like function readPtr to concatenate to the \r
+ * bstring b the entire contents of file-like source data in a roughly \r
+ * efficient way.\r
+ */\r
+int breada (bstring b, bNread readPtr, void * parm) {\r
+int i, l, n;\r
+\r
+ if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen ||\r
+ b->mlen <= 0 || readPtr == NULL) return BSTR_ERR;\r
+\r
+ i = b->slen;\r
+ for (n=i+16; ; n += ((n < BS_BUFF_SZ) ? n : BS_BUFF_SZ)) {\r
+ if (BSTR_OK != balloc (b, n + 1)) return BSTR_ERR;\r
+ l = (int) readPtr ((void *) (b->data + i), 1, n - i, parm);\r
+ i += l;\r
+ b->slen = i;\r
+ if (i < n) break;\r
+ }\r
+\r
+ b->data[i] = (unsigned char) '\0';\r
+ return BSTR_OK;\r
+}\r
+\r
+/* bstring bread (bNread readPtr, void * parm)\r
+ *\r
+ * Use a finite buffer fread-like function readPtr to create a bstring \r
+ * filled with the entire contents of file-like source data in a roughly \r
+ * efficient way.\r
+ */\r
+bstring bread (bNread readPtr, void * parm) {\r
+bstring buff;\r
+\r
+ if (0 > breada (buff = bfromcstr (""), readPtr, parm)) {\r
+ bdestroy (buff);\r
+ return NULL;\r
+ }\r
+ return buff;\r
+}\r
+\r
+/* int bassigngets (bstring b, bNgetc getcPtr, void * parm, char terminator)\r
+ *\r
+ * Use an fgetc-like single character stream reading function (getcPtr) to \r
+ * obtain a sequence of characters which are concatenated to the end of the\r
+ * bstring b. The stream read is terminated by the passed in terminator \r
+ * parameter.\r
+ *\r
+ * If getcPtr returns with a negative number, or the terminator character \r
+ * (which is appended) is read, then the stream reading is halted and the \r
+ * function returns with a partial result in b. If there is an empty partial\r
+ * result, 1 is returned. If no characters are read, or there is some other \r
+ * detectable error, BSTR_ERR is returned.\r
+ */\r
+int bassigngets (bstring b, bNgetc getcPtr, void * parm, char terminator) {\r
+int c, d, e;\r
+\r
+ if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen ||\r
+ b->mlen <= 0 || getcPtr == NULL) return BSTR_ERR;\r
+ d = 0;\r
+ e = b->mlen - 2;\r
+\r
+ while ((c = getcPtr (parm)) >= 0) {\r
+ if (d > e) {\r
+ b->slen = d;\r
+ if (balloc (b, d + 2) != BSTR_OK) return BSTR_ERR;\r
+ e = b->mlen - 2;\r
+ }\r
+ b->data[d] = (unsigned char) c;\r
+ d++;\r
+ if (c == terminator) break;\r
+ }\r
+\r
+ b->data[d] = (unsigned char) '\0';\r
+ b->slen = d;\r
+\r
+ return d == 0 && c < 0;\r
+}\r
+\r
+/* int bgetsa (bstring b, bNgetc getcPtr, void * parm, char terminator)\r
+ *\r
+ * Use an fgetc-like single character stream reading function (getcPtr) to \r
+ * obtain a sequence of characters which are concatenated to the end of the\r
+ * bstring b. The stream read is terminated by the passed in terminator \r
+ * parameter.\r
+ *\r
+ * If getcPtr returns with a negative number, or the terminator character \r
+ * (which is appended) is read, then the stream reading is halted and the \r
+ * function returns with a partial result concatentated to b. If there is \r
+ * an empty partial result, 1 is returned. If no characters are read, or \r
+ * there is some other detectable error, BSTR_ERR is returned.\r
+ */\r
+int bgetsa (bstring b, bNgetc getcPtr, void * parm, char terminator) {\r
+int c, d, e;\r
+\r
+ if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen ||\r
+ b->mlen <= 0 || getcPtr == NULL) return BSTR_ERR;\r
+ d = b->slen;\r
+ e = b->mlen - 2;\r
+\r
+ while ((c = getcPtr (parm)) >= 0) {\r
+ if (d > e) {\r
+ b->slen = d;\r
+ if (balloc (b, d + 2) != BSTR_OK) return BSTR_ERR;\r
+ e = b->mlen - 2;\r
+ }\r
+ b->data[d] = (unsigned char) c;\r
+ d++;\r
+ if (c == terminator) break;\r
+ }\r
+\r
+ b->data[d] = (unsigned char) '\0';\r
+ b->slen = d;\r
+\r
+ return d == 0 && c < 0;\r
+}\r
+\r
+/* bstring bgets (bNgetc getcPtr, void * parm, char terminator)\r
+ *\r
+ * Use an fgetc-like single character stream reading function (getcPtr) to \r
+ * obtain a sequence of characters which are concatenated into a bstring. \r
+ * The stream read is terminated by the passed in terminator function.\r
+ *\r
+ * If getcPtr returns with a negative number, or the terminator character \r
+ * (which is appended) is read, then the stream reading is halted and the \r
+ * result obtained thus far is returned. If no characters are read, or \r
+ * there is some other detectable error, NULL is returned.\r
+ */\r
+bstring bgets (bNgetc getcPtr, void * parm, char terminator) {\r
+bstring buff;\r
+\r
+ if (0 > bgetsa (buff = bfromcstr (""), getcPtr, parm, terminator) || 0 >= buff->slen) {\r
+ bdestroy (buff);\r
+ buff = NULL;\r
+ }\r
+ return buff;\r
+}\r
+\r
+struct bStream {\r
+ bstring buff; /* Buffer for over-reads */\r
+ void * parm; /* The stream handle for core stream */\r
+ bNread readFnPtr; /* fread compatible fnptr for core stream */\r
+ int isEOF; /* track file's EOF state */\r
+ int maxBuffSz;\r
+};\r
+\r
+/* struct bStream * bsopen (bNread readPtr, void * parm)\r
+ *\r
+ * Wrap a given open stream (described by a fread compatible function \r
+ * pointer and stream handle) into an open bStream suitable for the bstring \r
+ * library streaming functions.\r
+ */\r
+struct bStream * bsopen (bNread readPtr, void * parm) {\r
+struct bStream * s;\r
+\r
+ if (readPtr == NULL) return NULL;\r
+ s = (struct bStream *) bstr__alloc (sizeof (struct bStream));\r
+ if (s == NULL) return NULL;\r
+ s->parm = parm;\r
+ s->buff = bfromcstr ("");\r
+ s->readFnPtr = readPtr;\r
+ s->maxBuffSz = BS_BUFF_SZ;\r
+ s->isEOF = 0;\r
+ return s;\r
+}\r
+\r
+/* int bsbufflength (struct bStream * s, int sz)\r
+ *\r
+ * Set the length of the buffer used by the bStream. If sz is zero, the \r
+ * length is not set. This function returns with the previous length.\r
+ */\r
+int bsbufflength (struct bStream * s, int sz) {\r
+int oldSz;\r
+ if (s == NULL || sz < 0) return BSTR_ERR;\r
+ oldSz = s->maxBuffSz;\r
+ if (sz > 0) s->maxBuffSz = sz;\r
+ return oldSz;\r
+}\r
+\r
+int bseof (const struct bStream * s) {\r
+ if (s == NULL || s->readFnPtr == NULL) return BSTR_ERR;\r
+ return s->isEOF && (s->buff->slen == 0);\r
+}\r
+\r
+/* void * bsclose (struct bStream * s)\r
+ *\r
+ * Close the bStream, and return the handle to the stream that was originally\r
+ * used to open the given stream.\r
+ */\r
+void * bsclose (struct bStream * s) {\r
+void * parm;\r
+ if (s == NULL) return NULL;\r
+ s->readFnPtr = NULL;\r
+ if (s->buff) bdestroy (s->buff);\r
+ s->buff = NULL;\r
+ parm = s->parm;\r
+ s->parm = NULL;\r
+ s->isEOF = 1;\r
+ bstr__free (s);\r
+ return parm;\r
+}\r
+\r
+/* int bsreadlna (bstring r, struct bStream * s, char terminator)\r
+ *\r
+ * Read a bstring terminated by the terminator character or the end of the\r
+ * stream from the bStream (s) and return it into the parameter r. This \r
+ * function may read additional characters from the core stream that are not \r
+ * returned, but will be retained for subsequent read operations.\r
+ */\r
+int bsreadlna (bstring r, struct bStream * s, char terminator) {\r
+int i, l, ret, rlo;\r
+char * b;\r
+struct tagbstring x;\r
+\r
+ if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0 ||\r
+ r->slen < 0 || r->mlen < r->slen) return BSTR_ERR;\r
+ l = s->buff->slen;\r
+ if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR;\r
+ b = (char *) s->buff->data;\r
+ x.data = (unsigned char *) b;\r
+\r
+ /* First check if the current buffer holds the terminator */\r
+ b[l] = terminator; /* Set sentinel */\r
+ for (i=0; b[i] != terminator; i++) ;\r
+ if (i < l) {\r
+ x.slen = i + 1;\r
+ ret = bconcat (r, &x);\r
+ s->buff->slen = l;\r
+ if (BSTR_OK == ret) bdelete (s->buff, 0, i + 1);\r
+ return BSTR_OK;\r
+ }\r
+\r
+ rlo = r->slen;\r
+\r
+ /* If not then just concatenate the entire buffer to the output */\r
+ x.slen = l;\r
+ if (BSTR_OK != bconcat (r, &x)) return BSTR_ERR;\r
+\r
+ /* Perform direct in-place reads into the destination to allow for\r
+ the minimum of data-copies */\r
+ for (;;) {\r
+ if (BSTR_OK != balloc (r, r->slen + s->maxBuffSz + 1)) return BSTR_ERR;\r
+ b = (char *) (r->data + r->slen);\r
+ l = (int) s->readFnPtr (b, 1, s->maxBuffSz, s->parm);\r
+ if (l <= 0) {\r
+ r->data[r->slen] = (unsigned char) '\0';\r
+ s->buff->slen = 0;\r
+ s->isEOF = 1;\r
+ /* If nothing was read return with an error message */\r
+ return BSTR_ERR & -(r->slen == rlo);\r
+ }\r
+ b[l] = terminator; /* Set sentinel */\r
+ for (i=0; b[i] != terminator; i++) ;\r
+ if (i < l) break;\r
+ r->slen += l;\r
+ }\r
+\r
+ /* Terminator found, push over-read back to buffer */\r
+ i++;\r
+ r->slen += i;\r
+ s->buff->slen = l - i;\r
+ bstr__memcpy (s->buff->data, b + i, l - i);\r
+ r->data[r->slen] = (unsigned char) '\0';\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bsreadlnsa (bstring r, struct bStream * s, bstring term)\r
+ *\r
+ * Read a bstring terminated by any character in the term string or the end \r
+ * of the stream from the bStream (s) and return it into the parameter r. \r
+ * This function may read additional characters from the core stream that \r
+ * are not returned, but will be retained for subsequent read operations.\r
+ */\r
+int bsreadlnsa (bstring r, struct bStream * s, const_bstring term) {\r
+int i, l, ret, rlo;\r
+unsigned char * b;\r
+struct tagbstring x;\r
+struct charField cf;\r
+\r
+ if (s == NULL || s->buff == NULL || r == NULL || term == NULL ||\r
+ term->data == NULL || r->mlen <= 0 || r->slen < 0 ||\r
+ r->mlen < r->slen) return BSTR_ERR;\r
+ if (term->slen == 1) return bsreadlna (r, s, term->data[0]);\r
+ if (term->slen < 1 || buildCharField (&cf, term)) return BSTR_ERR;\r
+\r
+ l = s->buff->slen;\r
+ if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR;\r
+ b = (unsigned char *) s->buff->data;\r
+ x.data = b;\r
+\r
+ /* First check if the current buffer holds the terminator */\r
+ b[l] = term->data[0]; /* Set sentinel */\r
+ for (i=0; !testInCharField (&cf, b[i]); i++) ;\r
+ if (i < l) {\r
+ x.slen = i + 1;\r
+ ret = bconcat (r, &x);\r
+ s->buff->slen = l;\r
+ if (BSTR_OK == ret) bdelete (s->buff, 0, i + 1);\r
+ return BSTR_OK;\r
+ }\r
+\r
+ rlo = r->slen;\r
+\r
+ /* If not then just concatenate the entire buffer to the output */\r
+ x.slen = l;\r
+ if (BSTR_OK != bconcat (r, &x)) return BSTR_ERR;\r
+\r
+ /* Perform direct in-place reads into the destination to allow for\r
+ the minimum of data-copies */\r
+ for (;;) {\r
+ if (BSTR_OK != balloc (r, r->slen + s->maxBuffSz + 1)) return BSTR_ERR;\r
+ b = (unsigned char *) (r->data + r->slen);\r
+ l = (int) s->readFnPtr (b, 1, s->maxBuffSz, s->parm);\r
+ if (l <= 0) {\r
+ r->data[r->slen] = (unsigned char) '\0';\r
+ s->buff->slen = 0;\r
+ s->isEOF = 1;\r
+ /* If nothing was read return with an error message */\r
+ return BSTR_ERR & -(r->slen == rlo);\r
+ }\r
+\r
+ b[l] = term->data[0]; /* Set sentinel */\r
+ for (i=0; !testInCharField (&cf, b[i]); i++) ;\r
+ if (i < l) break;\r
+ r->slen += l;\r
+ }\r
+\r
+ /* Terminator found, push over-read back to buffer */\r
+ i++;\r
+ r->slen += i;\r
+ s->buff->slen = l - i;\r
+ bstr__memcpy (s->buff->data, b + i, l - i);\r
+ r->data[r->slen] = (unsigned char) '\0';\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bsreada (bstring r, struct bStream * s, int n)\r
+ *\r
+ * Read a bstring of length n (or, if it is fewer, as many bytes as is \r
+ * remaining) from the bStream. This function may read additional \r
+ * characters from the core stream that are not returned, but will be \r
+ * retained for subsequent read operations. This function will not read\r
+ * additional characters from the core stream beyond virtual stream pointer.\r
+ */\r
+int bsreada (bstring r, struct bStream * s, int n) {\r
+int l, ret, orslen;\r
+char * b;\r
+struct tagbstring x;\r
+\r
+ if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0\r
+ || r->slen < 0 || r->mlen < r->slen || n <= 0) return BSTR_ERR;\r
+\r
+ n += r->slen;\r
+ if (n <= 0) return BSTR_ERR;\r
+\r
+ l = s->buff->slen;\r
+\r
+ orslen = r->slen;\r
+\r
+ if (0 == l) {\r
+ if (s->isEOF) return BSTR_ERR;\r
+ if (r->mlen > n) {\r
+ l = (int) s->readFnPtr (r->data + r->slen, 1, n - r->slen, s->parm);\r
+ if (0 >= l || l > n - r->slen) {\r
+ s->isEOF = 1;\r
+ return BSTR_ERR;\r
+ }\r
+ r->slen += l;\r
+ r->data[r->slen] = (unsigned char) '\0';\r
+ return 0;\r
+ }\r
+ }\r
+\r
+ if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR;\r
+ b = (char *) s->buff->data;\r
+ x.data = (unsigned char *) b;\r
+\r
+ do {\r
+ if (l + r->slen >= n) {\r
+ x.slen = n - r->slen;\r
+ ret = bconcat (r, &x);\r
+ s->buff->slen = l;\r
+ if (BSTR_OK == ret) bdelete (s->buff, 0, x.slen);\r
+ return BSTR_ERR & -(r->slen == orslen);\r
+ }\r
+\r
+ x.slen = l;\r
+ if (BSTR_OK != bconcat (r, &x)) break;\r
+\r
+ l = n - r->slen;\r
+ if (l > s->maxBuffSz) l = s->maxBuffSz;\r
+\r
+ l = (int) s->readFnPtr (b, 1, l, s->parm);\r
+\r
+ } while (l > 0);\r
+ if (l < 0) l = 0;\r
+ if (l == 0) s->isEOF = 1;\r
+ s->buff->slen = l;\r
+ return BSTR_ERR & -(r->slen == orslen);\r
+}\r
+\r
+/* int bsreadln (bstring r, struct bStream * s, char terminator)\r
+ *\r
+ * Read a bstring terminated by the terminator character or the end of the\r
+ * stream from the bStream (s) and return it into the parameter r. This \r
+ * function may read additional characters from the core stream that are not \r
+ * returned, but will be retained for subsequent read operations.\r
+ */\r
+int bsreadln (bstring r, struct bStream * s, char terminator) {\r
+ if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0)\r
+ return BSTR_ERR;\r
+ if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR;\r
+ r->slen = 0;\r
+ return bsreadlna (r, s, terminator);\r
+}\r
+\r
+/* int bsreadlns (bstring r, struct bStream * s, bstring term)\r
+ *\r
+ * Read a bstring terminated by any character in the term string or the end \r
+ * of the stream from the bStream (s) and return it into the parameter r. \r
+ * This function may read additional characters from the core stream that \r
+ * are not returned, but will be retained for subsequent read operations.\r
+ */\r
+int bsreadlns (bstring r, struct bStream * s, const_bstring term) {\r
+ if (s == NULL || s->buff == NULL || r == NULL || term == NULL \r
+ || term->data == NULL || r->mlen <= 0) return BSTR_ERR;\r
+ if (term->slen == 1) return bsreadln (r, s, term->data[0]);\r
+ if (term->slen < 1) return BSTR_ERR;\r
+ if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR;\r
+ r->slen = 0;\r
+ return bsreadlnsa (r, s, term);\r
+}\r
+\r
+/* int bsread (bstring r, struct bStream * s, int n)\r
+ *\r
+ * Read a bstring of length n (or, if it is fewer, as many bytes as is \r
+ * remaining) from the bStream. This function may read additional \r
+ * characters from the core stream that are not returned, but will be \r
+ * retained for subsequent read operations. This function will not read\r
+ * additional characters from the core stream beyond virtual stream pointer.\r
+ */\r
+int bsread (bstring r, struct bStream * s, int n) {\r
+ if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0\r
+ || n <= 0) return BSTR_ERR;\r
+ if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR;\r
+ r->slen = 0;\r
+ return bsreada (r, s, n);\r
+}\r
+\r
+/* int bsunread (struct bStream * s, const_bstring b)\r
+ *\r
+ * Insert a bstring into the bStream at the current position. These \r
+ * characters will be read prior to those that actually come from the core \r
+ * stream.\r
+ */\r
+int bsunread (struct bStream * s, const_bstring b) {\r
+ if (s == NULL || s->buff == NULL) return BSTR_ERR;\r
+ return binsert (s->buff, 0, b, (unsigned char) '?');\r
+}\r
+\r
+/* int bspeek (bstring r, const struct bStream * s)\r
+ *\r
+ * Return the currently buffered characters from the bStream that will be \r
+ * read prior to reads from the core stream.\r
+ */\r
+int bspeek (bstring r, const struct bStream * s) {\r
+ if (s == NULL || s->buff == NULL) return BSTR_ERR;\r
+ return bassign (r, s->buff);\r
+}\r
+\r
+/* bstring bjoin (const struct bstrList * bl, const_bstring sep);\r
+ *\r
+ * Join the entries of a bstrList into one bstring by sequentially \r
+ * concatenating them with the sep string in between. If there is an error \r
+ * NULL is returned, otherwise a bstring with the correct result is returned.\r
+ */\r
+bstring bjoin (const struct bstrList * bl, const_bstring sep) {\r
+bstring b;\r
+int i, c, v;\r
+\r
+ if (bl == NULL || bl->qty < 0) return NULL;\r
+ if (sep != NULL && (sep->slen < 0 || sep->data == NULL)) return NULL;\r
+\r
+ for (i = 0, c = 1; i < bl->qty; i++) {\r
+ v = bl->entry[i]->slen;\r
+ if (v < 0) return NULL; /* Invalid input */\r
+ c += v;\r
+ if (c < 0) return NULL; /* Wrap around ?? */\r
+ }\r
+\r
+ if (sep != NULL) c += (bl->qty - 1) * sep->slen;\r
+\r
+ b = (bstring) bstr__alloc (sizeof (struct tagbstring));\r
+ if (NULL == b) return NULL; /* Out of memory */\r
+ b->data = (unsigned char *) bstr__alloc (c);\r
+ if (b->data == NULL) {\r
+ bstr__free (b);\r
+ return NULL;\r
+ }\r
+\r
+ b->mlen = c;\r
+ b->slen = c-1;\r
+\r
+ for (i = 0, c = 0; i < bl->qty; i++) {\r
+ if (i > 0 && sep != NULL) {\r
+ bstr__memcpy (b->data + c, sep->data, sep->slen);\r
+ c += sep->slen;\r
+ }\r
+ v = bl->entry[i]->slen;\r
+ bstr__memcpy (b->data + c, bl->entry[i]->data, v);\r
+ c += v;\r
+ }\r
+ b->data[c] = (unsigned char) '\0';\r
+ return b;\r
+}\r
+\r
+#define BSSSC_BUFF_LEN (256)\r
+\r
+/* int bssplitscb (struct bStream * s, const_bstring splitStr, \r
+ * int (* cb) (void * parm, int ofs, const_bstring entry), void * parm)\r
+ *\r
+ * Iterate the set of disjoint sequential substrings read from a stream \r
+ * divided by any of the characters in splitStr. An empty splitStr causes \r
+ * the whole stream to be iterated once.\r
+ *\r
+ * Note: At the point of calling the cb function, the bStream pointer is \r
+ * pointed exactly at the position right after having read the split \r
+ * character. The cb function can act on the stream by causing the bStream\r
+ * pointer to move, and bssplitscb will continue by starting the next split\r
+ * at the position of the pointer after the return from cb.\r
+ *\r
+ * However, if the cb causes the bStream s to be destroyed then the cb must\r
+ * return with a negative value, otherwise bssplitscb will continue in an \r
+ * undefined manner.\r
+ */\r
+int bssplitscb (struct bStream * s, const_bstring splitStr, \r
+ int (* cb) (void * parm, int ofs, const_bstring entry), void * parm) {\r
+struct charField chrs;\r
+bstring buff;\r
+int i, p, ret;\r
+\r
+ if (cb == NULL || s == NULL || s->readFnPtr == NULL \r
+ || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR;\r
+\r
+ if (NULL == (buff = bfromcstr (""))) return BSTR_ERR;\r
+\r
+ if (splitStr->slen == 0) {\r
+ while (bsreada (buff, s, BSSSC_BUFF_LEN) >= 0) ;\r
+ if ((ret = cb (parm, 0, buff)) > 0) \r
+ ret = 0;\r
+ } else {\r
+ buildCharField (&chrs, splitStr);\r
+ ret = p = i = 0;\r
+ for (;;) {\r
+ if (i >= buff->slen) {\r
+ bsreada (buff, s, BSSSC_BUFF_LEN);\r
+ if (i >= buff->slen) {\r
+ if (0 < (ret = cb (parm, p, buff))) ret = 0;\r
+ break;\r
+ }\r
+ }\r
+ if (testInCharField (&chrs, buff->data[i])) {\r
+ struct tagbstring t;\r
+ unsigned char c;\r
+\r
+ blk2tbstr (t, buff->data + i + 1, buff->slen - (i + 1));\r
+ if ((ret = bsunread (s, &t)) < 0) break;\r
+ buff->slen = i;\r
+ c = buff->data[i];\r
+ buff->data[i] = (unsigned char) '\0';\r
+ if ((ret = cb (parm, p, buff)) < 0) break;\r
+ buff->data[i] = c;\r
+ buff->slen = 0;\r
+ p += i + 1;\r
+ i = -1;\r
+ }\r
+ i++;\r
+ }\r
+ }\r
+\r
+ bdestroy (buff);\r
+ return ret;\r
+}\r
+\r
+/* int bssplitstrcb (struct bStream * s, const_bstring splitStr, \r
+ * int (* cb) (void * parm, int ofs, const_bstring entry), void * parm)\r
+ *\r
+ * Iterate the set of disjoint sequential substrings read from a stream \r
+ * divided by the entire substring splitStr. An empty splitStr causes \r
+ * each character of the stream to be iterated.\r
+ *\r
+ * Note: At the point of calling the cb function, the bStream pointer is \r
+ * pointed exactly at the position right after having read the split \r
+ * character. The cb function can act on the stream by causing the bStream\r
+ * pointer to move, and bssplitscb will continue by starting the next split\r
+ * at the position of the pointer after the return from cb.\r
+ *\r
+ * However, if the cb causes the bStream s to be destroyed then the cb must\r
+ * return with a negative value, otherwise bssplitscb will continue in an \r
+ * undefined manner.\r
+ */\r
+int bssplitstrcb (struct bStream * s, const_bstring splitStr, \r
+ int (* cb) (void * parm, int ofs, const_bstring entry), void * parm) {\r
+bstring buff;\r
+int i, p, ret;\r
+\r
+ if (cb == NULL || s == NULL || s->readFnPtr == NULL \r
+ || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR;\r
+\r
+ if (splitStr->slen == 1) return bssplitscb (s, splitStr, cb, parm);\r
+\r
+ if (NULL == (buff = bfromcstr (""))) return BSTR_ERR;\r
+\r
+ if (splitStr->slen == 0) {\r
+ for (i=0; bsreada (buff, s, BSSSC_BUFF_LEN) >= 0; i++) {\r
+ if ((ret = cb (parm, 0, buff)) < 0) {\r
+ bdestroy (buff);\r
+ return ret;\r
+ }\r
+ buff->slen = 0;\r
+ }\r
+ return BSTR_OK;\r
+ } else {\r
+ ret = p = i = 0;\r
+ for (i=p=0;;) {\r
+ if ((ret = binstr (buff, 0, splitStr)) >= 0) {\r
+ struct tagbstring t;\r
+ blk2tbstr (t, buff->data, ret);\r
+ i = ret + splitStr->slen;\r
+ if ((ret = cb (parm, p, &t)) < 0) break;\r
+ p += i;\r
+ bdelete (buff, 0, i);\r
+ } else {\r
+ bsreada (buff, s, BSSSC_BUFF_LEN);\r
+ if (bseof (s)) {\r
+ if ((ret = cb (parm, p, buff)) > 0) ret = 0;\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ bdestroy (buff);\r
+ return ret;\r
+}\r
+\r
+/* int bstrListCreate (void)\r
+ *\r
+ * Create a bstrList.\r
+ */\r
+struct bstrList * bstrListCreate (void) {\r
+struct bstrList * sl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList));\r
+ if (sl) {\r
+ sl->entry = (bstring *) bstr__alloc (1*sizeof (bstring));\r
+ if (!sl->entry) {\r
+ bstr__free (sl);\r
+ sl = NULL;\r
+ } else {\r
+ sl->qty = 0;\r
+ sl->mlen = 1;\r
+ }\r
+ }\r
+ return sl;\r
+}\r
+\r
+/* int bstrListDestroy (struct bstrList * sl)\r
+ *\r
+ * Destroy a bstrList that has been created by bsplit, bsplits or bstrListCreate.\r
+ */\r
+int bstrListDestroy (struct bstrList * sl) {\r
+int i;\r
+ if (sl == NULL || sl->qty < 0) return BSTR_ERR;\r
+ for (i=0; i < sl->qty; i++) {\r
+ if (sl->entry[i]) {\r
+ bdestroy (sl->entry[i]);\r
+ sl->entry[i] = NULL;\r
+ }\r
+ }\r
+ sl->qty = -1;\r
+ sl->mlen = -1;\r
+ bstr__free (sl->entry);\r
+ sl->entry = NULL;\r
+ bstr__free (sl);\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bstrListAlloc (struct bstrList * sl, int msz)\r
+ *\r
+ * Ensure that there is memory for at least msz number of entries for the\r
+ * list.\r
+ */\r
+int bstrListAlloc (struct bstrList * sl, int msz) {\r
+bstring * l;\r
+int smsz;\r
+size_t nsz;\r
+ if (!sl || msz <= 0 || !sl->entry || sl->qty < 0 || sl->mlen <= 0 || sl->qty > sl->mlen) return BSTR_ERR;\r
+ if (sl->mlen >= msz) return BSTR_OK;\r
+ smsz = snapUpSize (msz);\r
+ nsz = ((size_t) smsz) * sizeof (bstring);\r
+ if (nsz < (size_t) smsz) return BSTR_ERR;\r
+ l = (bstring *) bstr__realloc (sl->entry, nsz);\r
+ if (!l) {\r
+ smsz = msz;\r
+ nsz = ((size_t) smsz) * sizeof (bstring);\r
+ l = (bstring *) bstr__realloc (sl->entry, nsz);\r
+ if (!l) return BSTR_ERR;\r
+ }\r
+ sl->mlen = smsz;\r
+ sl->entry = l;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bstrListAllocMin (struct bstrList * sl, int msz)\r
+ *\r
+ * Try to allocate the minimum amount of memory for the list to include at\r
+ * least msz entries or sl->qty whichever is greater.\r
+ */\r
+int bstrListAllocMin (struct bstrList * sl, int msz) {\r
+bstring * l;\r
+size_t nsz;\r
+ if (!sl || msz <= 0 || !sl->entry || sl->qty < 0 || sl->mlen <= 0 || sl->qty > sl->mlen) return BSTR_ERR;\r
+ if (msz < sl->qty) msz = sl->qty;\r
+ if (sl->mlen == msz) return BSTR_OK;\r
+ nsz = ((size_t) msz) * sizeof (bstring);\r
+ if (nsz < (size_t) msz) return BSTR_ERR;\r
+ l = (bstring *) bstr__realloc (sl->entry, nsz);\r
+ if (!l) return BSTR_ERR;\r
+ sl->mlen = msz;\r
+ sl->entry = l;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bsplitcb (const_bstring str, unsigned char splitChar, int pos,\r
+ * int (* cb) (void * parm, int ofs, int len), void * parm)\r
+ *\r
+ * Iterate the set of disjoint sequential substrings over str divided by the\r
+ * character in splitChar.\r
+ *\r
+ * Note: Non-destructive modification of str from within the cb function \r
+ * while performing this split is not undefined. bsplitcb behaves in \r
+ * sequential lock step with calls to cb. I.e., after returning from a cb \r
+ * that return a non-negative integer, bsplitcb continues from the position \r
+ * 1 character after the last detected split character and it will halt \r
+ * immediately if the length of str falls below this point. However, if the \r
+ * cb function destroys str, then it *must* return with a negative value, \r
+ * otherwise bsplitcb will continue in an undefined manner.\r
+ */\r
+int bsplitcb (const_bstring str, unsigned char splitChar, int pos,\r
+ int (* cb) (void * parm, int ofs, int len), void * parm) {\r
+int i, p, ret;\r
+\r
+ if (cb == NULL || str == NULL || pos < 0 || pos > str->slen) \r
+ return BSTR_ERR;\r
+\r
+ p = pos;\r
+ do {\r
+ for (i=p; i < str->slen; i++) {\r
+ if (str->data[i] == splitChar) break;\r
+ }\r
+ if ((ret = cb (parm, p, i - p)) < 0) return ret;\r
+ p = i + 1;\r
+ } while (p <= str->slen);\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bsplitscb (const_bstring str, const_bstring splitStr, int pos,\r
+ * int (* cb) (void * parm, int ofs, int len), void * parm)\r
+ *\r
+ * Iterate the set of disjoint sequential substrings over str divided by any \r
+ * of the characters in splitStr. An empty splitStr causes the whole str to\r
+ * be iterated once.\r
+ *\r
+ * Note: Non-destructive modification of str from within the cb function \r
+ * while performing this split is not undefined. bsplitscb behaves in \r
+ * sequential lock step with calls to cb. I.e., after returning from a cb \r
+ * that return a non-negative integer, bsplitscb continues from the position \r
+ * 1 character after the last detected split character and it will halt \r
+ * immediately if the length of str falls below this point. However, if the \r
+ * cb function destroys str, then it *must* return with a negative value, \r
+ * otherwise bsplitscb will continue in an undefined manner.\r
+ */\r
+int bsplitscb (const_bstring str, const_bstring splitStr, int pos,\r
+ int (* cb) (void * parm, int ofs, int len), void * parm) {\r
+struct charField chrs;\r
+int i, p, ret;\r
+\r
+ if (cb == NULL || str == NULL || pos < 0 || pos > str->slen \r
+ || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR;\r
+ if (splitStr->slen == 0) {\r
+ if ((ret = cb (parm, 0, str->slen)) > 0) ret = 0;\r
+ return ret;\r
+ }\r
+\r
+ if (splitStr->slen == 1) \r
+ return bsplitcb (str, splitStr->data[0], pos, cb, parm);\r
+\r
+ buildCharField (&chrs, splitStr);\r
+\r
+ p = pos;\r
+ do {\r
+ for (i=p; i < str->slen; i++) {\r
+ if (testInCharField (&chrs, str->data[i])) break;\r
+ }\r
+ if ((ret = cb (parm, p, i - p)) < 0) return ret;\r
+ p = i + 1;\r
+ } while (p <= str->slen);\r
+ return BSTR_OK;\r
+}\r
+\r
+/* int bsplitstrcb (const_bstring str, const_bstring splitStr, int pos,\r
+ * int (* cb) (void * parm, int ofs, int len), void * parm)\r
+ *\r
+ * Iterate the set of disjoint sequential substrings over str divided by the \r
+ * substring splitStr. An empty splitStr causes the whole str to be \r
+ * iterated once.\r
+ *\r
+ * Note: Non-destructive modification of str from within the cb function \r
+ * while performing this split is not undefined. bsplitstrcb behaves in \r
+ * sequential lock step with calls to cb. I.e., after returning from a cb \r
+ * that return a non-negative integer, bsplitscb continues from the position \r
+ * 1 character after the last detected split character and it will halt \r
+ * immediately if the length of str falls below this point. However, if the \r
+ * cb function destroys str, then it *must* return with a negative value, \r
+ * otherwise bsplitscb will continue in an undefined manner.\r
+ */\r
+int bsplitstrcb (const_bstring str, const_bstring splitStr, int pos,\r
+ int (* cb) (void * parm, int ofs, int len), void * parm) {\r
+int i, p, ret;\r
+\r
+ if (cb == NULL || str == NULL || pos < 0 || pos > str->slen \r
+ || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR;\r
+\r
+ if (0 == splitStr->slen) {\r
+ for (i=pos; i < str->slen; i++) {\r
+ if ((ret = cb (parm, i, 1)) < 0) return ret;\r
+ }\r
+ return BSTR_OK;\r
+ }\r
+\r
+ if (splitStr->slen == 1) \r
+ return bsplitcb (str, splitStr->data[0], pos, cb, parm);\r
+\r
+ for (i=p=pos; i <= str->slen - splitStr->slen; i++) {\r
+ if (0 == bstr__memcmp (splitStr->data, str->data + i, splitStr->slen)) {\r
+ if ((ret = cb (parm, p, i - p)) < 0) return ret;\r
+ i += splitStr->slen;\r
+ p = i;\r
+ }\r
+ }\r
+ if ((ret = cb (parm, p, str->slen - p)) < 0) return ret;\r
+ return BSTR_OK;\r
+}\r
+\r
+struct genBstrList {\r
+ bstring b;\r
+ struct bstrList * bl;\r
+};\r
+\r
+static int bscb (void * parm, int ofs, int len) {\r
+struct genBstrList * g = (struct genBstrList *) parm;\r
+ if (g->bl->qty >= g->bl->mlen) {\r
+ int mlen = g->bl->mlen * 2;\r
+ bstring * tbl;\r
+\r
+ while (g->bl->qty >= mlen) {\r
+ if (mlen < g->bl->mlen) return BSTR_ERR;\r
+ mlen += mlen;\r
+ }\r
+\r
+ tbl = (bstring *) bstr__realloc (g->bl->entry, sizeof (bstring) * mlen);\r
+ if (tbl == NULL) return BSTR_ERR;\r
+\r
+ g->bl->entry = tbl;\r
+ g->bl->mlen = mlen;\r
+ }\r
+\r
+ g->bl->entry[g->bl->qty] = bmidstr (g->b, ofs, len);\r
+ g->bl->qty++;\r
+ return BSTR_OK;\r
+}\r
+\r
+/* struct bstrList * bsplit (const_bstring str, unsigned char splitChar)\r
+ *\r
+ * Create an array of sequential substrings from str divided by the character\r
+ * splitChar. \r
+ */\r
+struct bstrList * bsplit (const_bstring str, unsigned char splitChar) {\r
+struct genBstrList g;\r
+\r
+ if (str == NULL || str->data == NULL || str->slen < 0) return NULL;\r
+\r
+ g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList));\r
+ if (g.bl == NULL) return NULL;\r
+ g.bl->mlen = 4;\r
+ g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring));\r
+ if (NULL == g.bl->entry) {\r
+ bstr__free (g.bl);\r
+ return NULL;\r
+ }\r
+\r
+ g.b = (bstring) str;\r
+ g.bl->qty = 0;\r
+ if (bsplitcb (str, splitChar, 0, bscb, &g) < 0) {\r
+ bstrListDestroy (g.bl);\r
+ return NULL;\r
+ }\r
+ return g.bl;\r
+}\r
+\r
+/* struct bstrList * bsplitstr (const_bstring str, const_bstring splitStr)\r
+ *\r
+ * Create an array of sequential substrings from str divided by the entire\r
+ * substring splitStr.\r
+ */\r
+struct bstrList * bsplitstr (const_bstring str, const_bstring splitStr) {\r
+struct genBstrList g;\r
+\r
+ if (str == NULL || str->data == NULL || str->slen < 0) return NULL;\r
+\r
+ g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList));\r
+ if (g.bl == NULL) return NULL;\r
+ g.bl->mlen = 4;\r
+ g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring));\r
+ if (NULL == g.bl->entry) {\r
+ bstr__free (g.bl);\r
+ return NULL;\r
+ }\r
+\r
+ g.b = (bstring) str;\r
+ g.bl->qty = 0;\r
+ if (bsplitstrcb (str, splitStr, 0, bscb, &g) < 0) {\r
+ bstrListDestroy (g.bl);\r
+ return NULL;\r
+ }\r
+ return g.bl;\r
+}\r
+\r
+/* struct bstrList * bsplits (const_bstring str, bstring splitStr)\r
+ *\r
+ * Create an array of sequential substrings from str divided by any of the \r
+ * characters in splitStr. An empty splitStr causes a single entry bstrList\r
+ * containing a copy of str to be returned.\r
+ */\r
+struct bstrList * bsplits (const_bstring str, const_bstring splitStr) {\r
+struct genBstrList g;\r
+\r
+ if ( str == NULL || str->slen < 0 || str->data == NULL ||\r
+ splitStr == NULL || splitStr->slen < 0 || splitStr->data == NULL)\r
+ return NULL;\r
+\r
+ g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList));\r
+ if (g.bl == NULL) return NULL;\r
+ g.bl->mlen = 4;\r
+ g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring));\r
+ if (NULL == g.bl->entry) {\r
+ bstr__free (g.bl);\r
+ return NULL;\r
+ }\r
+ g.b = (bstring) str;\r
+ g.bl->qty = 0;\r
+\r
+ if (bsplitscb (str, splitStr, 0, bscb, &g) < 0) {\r
+ bstrListDestroy (g.bl);\r
+ return NULL;\r
+ }\r
+ return g.bl;\r
+}\r
+\r
+#if defined (__TURBOC__) && !defined (__BORLANDC__)\r
+# ifndef BSTRLIB_NOVSNP\r
+# define BSTRLIB_NOVSNP\r
+# endif\r
+#endif\r
+\r
+/* Give WATCOM C/C++, MSVC some latitude for their non-support of vsnprintf */\r
+#if defined(__WATCOMC__) || defined(_MSC_VER)\r
+#define exvsnprintf(r,b,n,f,a) {r = _vsnprintf (b,n,f,a);}\r
+#else\r
+#ifdef BSTRLIB_NOVSNP\r
+/* This is just a hack. If you are using a system without a vsnprintf, it is \r
+ not recommended that bformat be used at all. */\r
+#define exvsnprintf(r,b,n,f,a) {vsprintf (b,f,a); r = -1;}\r
+#define START_VSNBUFF (256)\r
+#else\r
+\r
+#ifdef __GNUC__\r
+/* Something is making gcc complain about this prototype not being here, so \r
+ I've just gone ahead and put it in. */\r
+extern int vsnprintf (char *buf, size_t count, const char *format, va_list arg);\r
+#endif\r
+\r
+#define exvsnprintf(r,b,n,f,a) {r = vsnprintf (b,n,f,a);}\r
+#endif\r
+#endif\r
+\r
+#if !defined (BSTRLIB_NOVSNP)\r
+\r
+#ifndef START_VSNBUFF\r
+#define START_VSNBUFF (16)\r
+#endif\r
+\r
+/* On IRIX vsnprintf returns n-1 when the operation would overflow the target \r
+ buffer, WATCOM and MSVC both return -1, while C99 requires that the \r
+ returned value be exactly what the length would be if the buffer would be\r
+ large enough. This leads to the idea that if the return value is larger \r
+ than n, then changing n to the return value will reduce the number of\r
+ iterations required. */\r
+\r
+/* int bformata (bstring b, const char * fmt, ...)\r
+ *\r
+ * After the first parameter, it takes the same parameters as printf (), but \r
+ * rather than outputting results to stdio, it appends the results to \r
+ * a bstring which contains what would have been output. Note that if there \r
+ * is an early generation of a '\0' character, the bstring will be truncated \r
+ * to this end point.\r
+ */\r
+int bformata (bstring b, const char * fmt, ...) {\r
+va_list arglist;\r
+bstring buff;\r
+int n, r;\r
+\r
+ if (b == NULL || fmt == NULL || b->data == NULL || b->mlen <= 0 \r
+ || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR;\r
+\r
+ /* Since the length is not determinable beforehand, a search is\r
+ performed using the truncating "vsnprintf" call (to avoid buffer\r
+ overflows) on increasing potential sizes for the output result. */\r
+\r
+ if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF;\r
+ if (NULL == (buff = bfromcstralloc (n + 2, ""))) {\r
+ n = 1;\r
+ if (NULL == (buff = bfromcstralloc (n + 2, ""))) return BSTR_ERR;\r
+ }\r
+\r
+ for (;;) {\r
+ va_start (arglist, fmt);\r
+ exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist);\r
+ va_end (arglist);\r
+\r
+ buff->data[n] = (unsigned char) '\0';\r
+ buff->slen = (int) (strlen) ((char *) buff->data);\r
+\r
+ if (buff->slen < n) break;\r
+\r
+ if (r > n) n = r; else n += n;\r
+\r
+ if (BSTR_OK != balloc (buff, n + 2)) {\r
+ bdestroy (buff);\r
+ return BSTR_ERR;\r
+ }\r
+ }\r
+\r
+ r = bconcat (b, buff);\r
+ bdestroy (buff);\r
+ return r;\r
+}\r
+\r
+/* int bassignformat (bstring b, const char * fmt, ...)\r
+ *\r
+ * After the first parameter, it takes the same parameters as printf (), but \r
+ * rather than outputting results to stdio, it outputs the results to \r
+ * the bstring parameter b. Note that if there is an early generation of a \r
+ * '\0' character, the bstring will be truncated to this end point.\r
+ */\r
+int bassignformat (bstring b, const char * fmt, ...) {\r
+va_list arglist;\r
+bstring buff;\r
+int n, r;\r
+\r
+ if (b == NULL || fmt == NULL || b->data == NULL || b->mlen <= 0 \r
+ || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR;\r
+\r
+ /* Since the length is not determinable beforehand, a search is\r
+ performed using the truncating "vsnprintf" call (to avoid buffer\r
+ overflows) on increasing potential sizes for the output result. */\r
+\r
+ if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF;\r
+ if (NULL == (buff = bfromcstralloc (n + 2, ""))) {\r
+ n = 1;\r
+ if (NULL == (buff = bfromcstralloc (n + 2, ""))) return BSTR_ERR;\r
+ }\r
+\r
+ for (;;) {\r
+ va_start (arglist, fmt);\r
+ exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist);\r
+ va_end (arglist);\r
+\r
+ buff->data[n] = (unsigned char) '\0';\r
+ buff->slen = (int) (strlen) ((char *) buff->data);\r
+\r
+ if (buff->slen < n) break;\r
+\r
+ if (r > n) n = r; else n += n;\r
+\r
+ if (BSTR_OK != balloc (buff, n + 2)) {\r
+ bdestroy (buff);\r
+ return BSTR_ERR;\r
+ }\r
+ }\r
+\r
+ r = bassign (b, buff);\r
+ bdestroy (buff);\r
+ return r;\r
+}\r
+\r
+/* bstring bformat (const char * fmt, ...)\r
+ *\r
+ * Takes the same parameters as printf (), but rather than outputting results\r
+ * to stdio, it forms a bstring which contains what would have been output.\r
+ * Note that if there is an early generation of a '\0' character, the \r
+ * bstring will be truncated to this end point.\r
+ */\r
+bstring bformat (const char * fmt, ...) {\r
+va_list arglist;\r
+bstring buff;\r
+int n, r;\r
+\r
+ if (fmt == NULL) return NULL;\r
+\r
+ /* Since the length is not determinable beforehand, a search is\r
+ performed using the truncating "vsnprintf" call (to avoid buffer\r
+ overflows) on increasing potential sizes for the output result. */\r
+\r
+ if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF;\r
+ if (NULL == (buff = bfromcstralloc (n + 2, ""))) {\r
+ n = 1;\r
+ if (NULL == (buff = bfromcstralloc (n + 2, ""))) return NULL;\r
+ }\r
+\r
+ for (;;) {\r
+ va_start (arglist, fmt);\r
+ exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist);\r
+ va_end (arglist);\r
+\r
+ buff->data[n] = (unsigned char) '\0';\r
+ buff->slen = (int) (strlen) ((char *) buff->data);\r
+\r
+ if (buff->slen < n) break;\r
+\r
+ if (r > n) n = r; else n += n;\r
+\r
+ if (BSTR_OK != balloc (buff, n + 2)) {\r
+ bdestroy (buff);\r
+ return NULL;\r
+ }\r
+ }\r
+\r
+ return buff;\r
+}\r
+\r
+/* int bvcformata (bstring b, int count, const char * fmt, va_list arglist)\r
+ *\r
+ * The bvcformata function formats data under control of the format control \r
+ * string fmt and attempts to append the result to b. The fmt parameter is \r
+ * the same as that of the printf function. The variable argument list is \r
+ * replaced with arglist, which has been initialized by the va_start macro.\r
+ * The size of the output is upper bounded by count. If the required output\r
+ * exceeds count, the string b is not augmented with any contents and a value\r
+ * below BSTR_ERR is returned. If a value below -count is returned then it\r
+ * is recommended that the negative of this value be used as an update to the\r
+ * count in a subsequent pass. On other errors, such as running out of \r
+ * memory, parameter errors or numeric wrap around BSTR_ERR is returned. \r
+ * BSTR_OK is returned when the output is successfully generated and \r
+ * appended to b.\r
+ *\r
+ * Note: There is no sanity checking of arglist, and this function is\r
+ * destructive of the contents of b from the b->slen point onward. If there \r
+ * is an early generation of a '\0' character, the bstring will be truncated \r
+ * to this end point.\r
+ */\r
+int bvcformata (bstring b, int count, const char * fmt, va_list arg) {\r
+int n, r, l;\r
+\r
+ if (b == NULL || fmt == NULL || count <= 0 || b->data == NULL\r
+ || b->mlen <= 0 || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR;\r
+\r
+ if (count > (n = b->slen + count) + 2) return BSTR_ERR;\r
+ if (BSTR_OK != balloc (b, n + 2)) return BSTR_ERR;\r
+\r
+ exvsnprintf (r, (char *) b->data + b->slen, count + 2, fmt, arg);\r
+\r
+ /* Did the operation complete successfully within bounds? */\r
+\r
+ if (n >= (l = b->slen + (int) (strlen) ((const char *) b->data + b->slen))) {\r
+ b->slen = l;\r
+ return BSTR_OK;\r
+ }\r
+\r
+ /* Abort, since the buffer was not large enough. The return value \r
+ tries to help set what the retry length should be. */\r
+\r
+ b->data[b->slen] = '\0';\r
+ if (r > count+1) l = r; else {\r
+ l = count+count;\r
+ if (count > l) l = INT_MAX;\r
+ }\r
+ n = -l;\r
+ if (n > BSTR_ERR-1) n = BSTR_ERR-1;\r
+ return n;\r
+}\r
+\r
+#endif\r
/*
- * $Id: cnid_dbd.c,v 1.17 2010-03-31 09:47:32 franklahm Exp $
+ * $Id: cnid_dbd.c,v 1.17 2010/03/31 09:47:32 franklahm Exp $
*
* Copyright (C) Joerg Lenneis 2003
* All Rights Reserved. See COPYING.
ssize_t len;
size_t len1;
- LOG(log_maxdebug, logtype_cnid, "write_vec: request to write %d bytes", towrite);
-
len1 = iov[1].iov_len;
while (towrite > 0) {
if (((len = writev(fd, iov, 2)) == -1 && errno == EINTR) || !len)
struct iovec iov[2];
size_t towrite;
- LOG(log_maxdebug, logtype_cnid, "send_packet: BEGIN");
-
if (!rqst->namelen) {
if (write(db->fd, rqst, sizeof(struct cnid_dbd_rqst)) != sizeof(struct cnid_dbd_rqst)) {
LOG(log_warning, logtype_cnid, "send_packet: Error/short write rqst (db_dir %s): %s",
return -1;
}
- LOG(log_maxdebug, logtype_cnid, "send_packet: OK");
+ LOG(log_maxdebug, logtype_cnid, "send_packet: {done}");
return 0;
}
char *nametmp;
size_t len;
- LOG(log_maxdebug, logtype_cnid, "dbd_rpc: BEGIN");
-
if (send_packet(db, rqst) < 0) {
return -1;
}
return -1;
}
- LOG(log_maxdebug, logtype_cnid, "dbd_rpc: END");
+ LOG(log_maxdebug, logtype_cnid, "dbd_rpc: {done}");
return 0;
}
time_t orig, t;
int clean = 1; /* no errors so far - to prevent sleep on first try */
- LOG(log_debug7, logtype_cnid, "transmit: BEGIN");
-
if (db->changed) {
/* volume and db don't have the same timestamp
*/
struct cnid_dbd_rply rply_stamp;
char stamp[ADEDLEN_PRIVSYN];
- LOG(log_debug, logtype_cnid, "transmit: connecting to cnid_dbd ...");
+ LOG(log_maxdebug, logtype_cnid, "transmit: connecting to cnid_dbd ...");
if ((db->fd = init_tsock(db)) < 0) {
goto transmit_fail;
}
memcpy(db->client_stamp, stamp, ADEDLEN_PRIVSYN);
memcpy(db->stamp, stamp, ADEDLEN_PRIVSYN);
}
- LOG(log_debug, logtype_cnid, "transmit: succesfully attached to cnid_dbd for volume '%s' with stamp '%08lx'.",
+ LOG(log_debug, logtype_cnid, "transmit: attached to '%s', stamp: '%08lx'.",
db->db_dir, *(uint64_t *)stamp);
}
if (!dbd_rpc(db, rqst, rply)) {
- LOG(log_debug7, logtype_cnid, "transmit: END OK");
+ LOG(log_maxdebug, logtype_cnid, "transmit: {done}");
return 0;
}
transmit_fail:
locking.c \
logger.c \
module.c \
+ queue.c \
server_child.c \
server_ipc.c \
server_lock.c \
--- /dev/null
+/*
+ $Id: queue.c,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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.
+*/
+
+/*!
+ * @file
+ * Netatalk utility functions: queue
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <stdlib.h>
+
+#include <atalk/queue.h>
+
+static qnode_t *alloc_init_node(void *data)
+{
+ qnode_t *node;
+ if ((node = malloc(sizeof(qnode_t))) == NULL)
+ return NULL;
+ node->data = data;
+
+ return node;
+}
+
+/********************************************************************************
+ * Interface
+ *******************************************************************************/
+
+q_t *queue_init(void)
+{
+ q_t *queue;
+
+ if ((queue = alloc_init_node(NULL)) == NULL)
+ return NULL;
+
+ queue->prev = queue->next = queue;
+ return queue;
+}
+
+qnode_t *enqueue(q_t *q, void *data)
+{
+ qnode_t *node;
+
+ if ((node = alloc_init_node(data)) == NULL)
+ return NULL;
+
+ /* insert at tail */
+ node->next = q;
+ node->prev = q->prev;
+ q->prev->next = node;
+ q->prev = node;
+
+ return node;
+}
+
+void *dequeue(q_t *q)
+{
+ qnode_t *node;
+ void *data;
+
+ if (q == NULL || q->next == q)
+ return NULL;
+
+ /* take first node from head */
+ node = q->next;
+ data = node->data;
+ q->next = node->next;
+ node->next->prev = node->prev;
+ free(node);
+
+ return data;
+}
+
+void queue_destroy(q_t *q, void (*callback)(void *))
+{
+ void *p;
+
+ while ((p = dequeue(q)) != NULL)
+ callback(p);
+
+ free(q);
+ q = NULL;
+}
+
--- /dev/null
+Makefile
+Makefile.in
--- /dev/null
+SUBDIRS = afpd
--- /dev/null
+Makefile
+Makefile.in
+.deps
+.libs
+test
+test.conf
+test.default
\ No newline at end of file
--- /dev/null
+# Makefile.am for test/afpd/
+
+pkgconfdir = @PKGCONFDIR@
+
+TESTS = test.sh test
+
+check_PROGRAMS = test
+noinst_HEADERS = test.h subtests.h afpfunc_helpers.h
+
+test_SOURCES = test.c subtests.c afpfunc_helpers.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/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/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
+
+test_CFLAGS = -I$(top_srcdir)/include -I$(top_srcdir)/etc/afpd \
+ @SLP_CFLAGS@ \
+ -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\" \
+ -DAPPLCNAME \
+ -DSERVERTEXT=\"$(SERVERTEXT)/\"
+
+test_LDADD = $(top_builddir)/libatalk/cnid/libcnid.la \
+ $(top_builddir)/libatalk/libatalk.la \
+ @QUOTA_LIBS@ @SLP_LIBS@ @WRAP_LIBS@ @LIBADD_DL@
+
+test_LDFLAGS = -export-dynamic
--- /dev/null
+/*
+ $Id: afpfunc_helpers.c,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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 <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <atalk/util.h>
+#include <atalk/cnid.h>
+#include <atalk/logger.h>
+#include <atalk/volume.h>
+#include <atalk/directory.h>
+#include <atalk/queue.h>
+#include <atalk/bstrlib.h>
+
+#include "file.h"
+#include "filedir.h"
+#include "directory.h"
+#include "dircache.h"
+#include "hash.h"
+#include "globals.h"
+#include "afp_config.h"
+#include "volume.h"
+
+#include "test.h"
+#include "subtests.h"
+
+
+#define rbufsize 128000
+static char rbuf[rbufsize];
+static size_t rbuflen;
+
+#define ADD(a, b, c) (a) += (c); \
+ (b) += (c)
+
+#define PUSHBUF(p, val, size, len) \
+ memcpy((p), (val), (size)); \
+ (p) += (size); \
+ (len) += (size)
+
+#define PUSHVAL(p, type, val, len) \
+ { \
+ type type = val; \
+ memcpy(p, &type, sizeof(type)); \
+ (p) += sizeof(type); \
+ (len) += sizeof(type); \
+ }
+
+static int push_path(char **bufp, const char *name)
+{
+ int len = 0;
+ int slen = strlen(name);
+ char *p = *bufp;
+
+ PUSHVAL(p, uint8_t, 3, len); /* path type */
+ PUSHVAL(p, uint32_t, kTextEncodingUTF8, len); /* text encoding hint */
+ PUSHVAL(p, uint16_t, htons(slen), len);
+ if (slen) {
+ for (int i = 0; i < slen; i++) {
+ if (name[i] == '/')
+ p[i] = 0;
+ else
+ p[i] = name[i];
+ }
+ len += slen;
+ }
+
+ *bufp += len;
+ return len;
+}
+
+/***********************************************************************************
+ * Interface
+ ***********************************************************************************/
+
+char **cnamewrap(const char *name)
+{
+ static char buf[256];
+ static char *p = buf;
+ int len = 0;
+
+ PUSHVAL(p, uint8_t, 3, len); /* path type */
+ PUSHVAL(p, uint32_t, kTextEncodingUTF8, len); /* text encoding hint */
+ PUSHVAL(p, uint16_t, ntohs(strlen(name)), len);
+ strcpy(p, name);
+
+ p = buf;
+ return &p;
+}
+
+int getfiledirparms(AFPObj *obj, uint16_t vid, cnid_t did, const char *name)
+{
+ const int bufsize = 256;
+ char buf[bufsize];
+ char *p = buf;
+ int len = 0;
+
+ ADD(p, len , 2);
+
+ PUSHVAL(p, uint16_t, vid, len);
+ PUSHVAL(p, cnid_t, did, len);
+ PUSHVAL(p, uint16_t, htons(FILPBIT_FNUM | FILPBIT_PDINFO), len);
+ PUSHVAL(p, uint16_t, htons(DIRPBIT_DID | DIRPBIT_PDINFO), len);
+
+ len += push_path(&p, name);
+
+ return afp_getfildirparams(obj, buf, len, rbuf, &rbuflen);
+}
+
+int createdir(AFPObj *obj, uint16_t vid, cnid_t did, const char *name)
+{
+ const int bufsize = 256;
+ char buf[bufsize];
+ char *p = buf;
+ int len = 0;
+
+ ADD(p, len , 2);
+
+ PUSHVAL(p, uint16_t, vid, len);
+ PUSHVAL(p, cnid_t, did, len);
+ len += push_path(&p, name);
+
+ return afp_createdir(obj, buf, len, rbuf, &rbuflen);
+}
+
+int createfile(AFPObj *obj, uint16_t vid, cnid_t did, const char *name)
+{
+ const int bufsize = 256;
+ char buf[bufsize];
+ char *p = buf;
+ int len = 0;
+
+ PUSHVAL(p, uint16_t, htons(128), len); /* hard create */
+ PUSHVAL(p, uint16_t, vid, len);
+ PUSHVAL(p, cnid_t, did, len);
+ len += push_path(&p, name);
+
+ return afp_createfile(obj, buf, len, rbuf, &rbuflen);
+}
+
+int delete(AFPObj *obj, uint16_t vid, cnid_t did, const char *name)
+{
+ const int bufsize = 256;
+ char buf[bufsize];
+ char *p = buf;
+ int len = 0;
+
+ PUSHVAL(p, uint16_t, htons(128), len); /* hard create */
+ PUSHVAL(p, uint16_t, vid, len);
+ PUSHVAL(p, cnid_t, did, len);
+ len += push_path(&p, name);
+
+ return afp_delete(obj, buf, len, rbuf, &rbuflen);
+}
+
+int enumerate(AFPObj *obj, uint16_t vid, cnid_t did)
+{
+ const int bufsize = 256;
+ char buf[bufsize];
+ char *p = buf;
+ int len = 0;
+
+ ADD(p, len , 2);
+
+ PUSHVAL(p, uint16_t, vid, len);
+ PUSHVAL(p, cnid_t, did, len);
+ PUSHVAL(p, uint16_t, htons(FILPBIT_PDID | FILPBIT_FNUM | FILPBIT_PDINFO), len);
+ PUSHVAL(p, uint16_t, htons(DIRPBIT_PDID | DIRPBIT_DID | DIRPBIT_PDINFO), len);
+ PUSHVAL(p, uint16_t, htons(20), len); /* reqcount */
+ PUSHVAL(p, uint32_t, htonl(1), len); /* startindex */
+ PUSHVAL(p, uint32_t, htonl(rbufsize), len); /* max replysize */
+
+ len += push_path(&p, "");
+
+ return afp_enumerate_ext2(obj, buf, len, rbuf, &rbuflen);
+}
+
+uint16_t openvol(AFPObj *obj, const char *name)
+{
+ int ret;
+ uint16_t bitmap;
+ uint16_t vid;
+ const int bufsize = 32;
+ char buf[bufsize];
+ char *p = buf;
+ char len = strlen(name);
+
+ memset(p, 0, bufsize);
+ p += 2;
+
+ /* bitmap */
+ bitmap = htons(1<<VOLPBIT_VID);
+ memcpy(p, &bitmap, 2);
+ p += 2;
+
+ /* name */
+ *p = len;
+ p++;
+ memcpy(p, name, len);
+ p += len;
+
+ len += 2 + 2 + 1; /* (command+pad) + bitmap + len */
+ if (len & 1)
+ len++;
+
+ rbuflen = 0;
+ if ((ret = afp_openvol(obj, buf, len, rbuf, &rbuflen)) != AFP_OK)
+ return 0;
+
+ p = rbuf;
+ memcpy(&bitmap, p, 2);
+ p += 2;
+ bitmap = ntohs(bitmap);
+ if ( ! (bitmap & 1<<VOLPBIT_VID))
+ return 0;
+
+ memcpy(&vid, p, 2);
+ return vid;
+}
+
--- /dev/null
+/*
+ $Id: afpfunc_helpers.h,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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 AFPFUNC_HELPERS
+#define AFPFUNC_HELPERS
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <atalk/util.h>
+#include <atalk/cnid.h>
+#include <atalk/logger.h>
+#include <atalk/volume.h>
+#include <atalk/directory.h>
+#include <atalk/queue.h>
+#include <atalk/bstrlib.h>
+
+#include "file.h"
+#include "filedir.h"
+#include "directory.h"
+#include "dircache.h"
+#include "hash.h"
+#include "globals.h"
+#include "afp_config.h"
+#include "volume.h"
+
+#include "test.h"
+#include "subtests.h"
+
+extern char **cnamewrap(const char *name);
+
+extern int getfiledirparms(AFPObj *obj, uint16_t vid, cnid_t did, const char *name);
+extern int createdir(AFPObj *obj, uint16_t vid, cnid_t did, const char *name);
+extern int createfile(AFPObj *obj, uint16_t vid, cnid_t did, const char *name);
+extern int delete(AFPObj *obj, uint16_t vid, cnid_t did, const char *name);
+extern int enumerate(AFPObj *obj, uint16_t vid, cnid_t did);
+extern uint16_t openvol(AFPObj *obj, const char *name);
+
+#endif /* AFPFUNC_HELPERS */
--- /dev/null
+/*
+ $Id: subtests.c,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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 <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <atalk/util.h>
+#include <atalk/cnid.h>
+#include <atalk/logger.h>
+#include <atalk/volume.h>
+#include <atalk/directory.h>
+#include <atalk/queue.h>
+#include <atalk/bstrlib.h>
+
+#include "directory.h"
+#include "dircache.h"
+#include "hash.h"
+#include "globals.h"
+#include "afp_config.h"
+#include "volume.h"
+
+#include "test.h"
+#include "subtests.h"
+
+static int reti; /* for the TEST_int macro */
+
+int test001_add_x_dirs(const struct vol *vol, cnid_t start, cnid_t end)
+{
+ struct dir *dir;
+ char dirname[20];
+ while (start++ < end) {
+ sprintf(dirname, "dir%04u", start);
+ dir = dir_new(dirname, dirname, vol, DIRDID_ROOT, htonl(start), bfromcstr(vol->v_path));
+ if (dir == NULL)
+ return -1;
+ if (dircache_add(dir) != 0)
+ return -1;
+ }
+
+ return 0;
+}
+
+int test002_rem_x_dirs(const struct vol *vol, cnid_t start, cnid_t end)
+{
+ struct dir *dir;
+ while (start++ < end) {
+ if ((dir = dircache_search_by_did(vol, htonl(start))))
+ if (dir_remove(vol, dir) != 0)
+ return -1;
+ }
+
+ return 0;
+}
--- /dev/null
+/*
+ $Id: subtests.h,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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 SUBTESTS_H
+#define SUBTESTS_H
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <atalk/util.h>
+#include <atalk/cnid.h>
+#include <atalk/logger.h>
+#include <atalk/volume.h>
+#include <atalk/directory.h>
+#include <atalk/queue.h>
+#include <atalk/bstrlib.h>
+
+#include "directory.h"
+#include "dircache.h"
+#include "hash.h"
+#include "globals.h"
+#include "afp_config.h"
+#include "volume.h"
+
+extern int test001_add_x_dirs(const struct vol *vol, cnid_t start, cnid_t end);
+extern int test002_rem_x_dirs(const struct vol *vol, cnid_t start, cnid_t end);
+#endif /* SUBTESTS_H */
--- /dev/null
+/*
+ $Id: test.c,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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 <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <atalk/util.h>
+#include <atalk/cnid.h>
+#include <atalk/logger.h>
+#include <atalk/volume.h>
+#include <atalk/directory.h>
+#include <atalk/queue.h>
+#include <atalk/bstrlib.h>
+
+#include "file.h"
+#include "filedir.h"
+#include "directory.h"
+#include "dircache.h"
+#include "hash.h"
+#include "globals.h"
+#include "afp_config.h"
+#include "volume.h"
+
+#include "test.h"
+#include "subtests.h"
+#include "afpfunc_helpers.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 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;
+ struct dir *dir;
+ struct dir *retdir;
+ 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);
+
+ printf("\n");
+
+ /* now run tests */
+ printf("Running tests\n=============\n");
+
+ TEST_expr(vid = openvol(&configs->obj, "test"), vid != 0);
+ TEST_expr(vol = getvolbyvid(vid), vol != NULL);
+
+ /* test dircache.c stuff*/
+ TEST_expr(dir = dir_new("dir", "dir", vol, DIRDID_ROOT, htonl(20), bfromcstr(vol->v_path)),
+ dir != NULL);
+ TEST_int(dircache_add(dir), 0);
+ TEST_expr(retdir = dircache_search_by_did(vol, dir->d_did ),
+ retdir != NULL && retdir == dir && bstrcmp(retdir->d_u_name, dir->d_u_name) == 0);
+ TEST_expr(retdir = dircache_search_by_name(vol, DIRDID_ROOT, "dir", strlen("dir")),
+ retdir != NULL && retdir == dir && bstrcmp(retdir->d_u_name, dir->d_u_name) == 0);
+ TEST_int(dir_remove(vol, dir), 0);
+ TEST_int(test001_add_x_dirs(vol, 100, 100000), 0);
+ TEST_int(test002_rem_x_dirs(vol, 100, 100000), 0);
+
+ /* test directory.c stuff */
+ TEST_expr(retdir = dirlookup(vol, DIRDID_ROOT_PARENT), retdir != NULL);
+ TEST_expr(retdir = dirlookup(vol, DIRDID_ROOT), retdir != NULL);
+ 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_expr(reti = createdir(&configs->obj, vid, DIRDID_ROOT, "dir1"),
+ reti == 0 || reti == AFPERR_EXIST);
+ TEST_expr(retdir = dircache_search_by_name(vol, DIRDID_ROOT, "dir1", strlen("dir1")),
+ retdir != NULL);
+
+ TEST_int(getfiledirparms(&configs->obj, vid, DIRDID_ROOT, "dir1"), 0);
+ TEST_int(getfiledirparms(&configs->obj, vid, retdir->d_did, "//"), 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(&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 enumerate.c stuff */
+ TEST_int(enumerate(&configs->obj, vid, DIRDID_ROOT), 0);
+}
--- /dev/null
+/*
+ $Id: test.h,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
+ Copyright (c) 2010 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 TEST_H
+#define TEST_H
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <atalk/util.h>
+#include <atalk/cnid.h>
+#include <atalk/logger.h>
+#include <atalk/volume.h>
+#include <atalk/directory.h>
+#include <atalk/queue.h>
+#include <atalk/bstrlib.h>
+
+#include "directory.h"
+#include "dircache.h"
+#include "hash.h"
+#include "globals.h"
+#include "afp_config.h"
+#include "volume.h"
+#include "subtests.h"
+
+static inline void alignok(int len)
+{
+ int i = 1;
+ if (len < 80)
+ i = 80 - len;
+ while (i--)
+ printf(" ");
+}
+
+#define TEST(a) \
+ printf("Testing: %s ... ", (#a) ); \
+ alignok(strlen(#a)); \
+ a; \
+ printf("[ok]\n");
+
+#define TEST_int(a, b) \
+ printf("Testing: %s ... ", (#a) ); \
+ alignok(strlen(#a)); \
+ if ((reti = (a)) != b) { \
+ printf("[error]\n"); \
+ exit(1); \
+ } else { printf("[ok]\n"); }
+
+#define TEST_expr(a, b) \
+ printf("Testing: %s ... ", (#a) ); \
+ alignok(strlen(#a)); \
+ a; \
+ if (b) { \
+ printf("[ok]\n"); \
+ } else { \
+ printf("[error]\n"); \
+ exit(1); \
+ }
+#endif /* TEST_H */
--- /dev/null
+#!/bin/sh
+if [ ! -d /tmp/AFPtestvolume ] ; then
+ mkdir -p /tmp/AFPtestvolume
+ if [ $? -ne 0 ] ; then
+ echo Error creating AFP test volume /tmp/AFPtestvolume
+ exit 1
+ fi
+fi
+
+if [ ! -f test.conf ] ; then
+ echo -n "Creating configuration template ... "
+ cat > test.conf <<EOF
+test -noddp -port 10548
+EOF
+ echo [ok]
+fi
+
+if [ ! -f test.default ] ; then
+ echo -n "Creating volume config template ... "
+ cat > test.default <<EOF
+/tmp/AFPtestvolume "test" ea:none
+EOF
+ echo [ok]
+fi