ccnx: Final customizations. Adding java and apps variants (enabled by
default), ccnx user is automatically created, and daemon is running as
ccnx, instead of root
diff --git a/.gitignore b/.gitignore
index 190c56d..6eb86c7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
 PortIndex*
 .DS*
+work
diff --git a/net/ccnx/Portfile b/net/ccnx/Portfile
index 5a53738..33d9136 100644
--- a/net/ccnx/Portfile
+++ b/net/ccnx/Portfile
@@ -22,46 +22,72 @@
             contributing to its evolution. 
 homepage    http://www.ccnx.org/
 
-fetch.type git
-git.url    https://github.com/ProjectCCNx/ccnx.git
-git.branch ccnx-0.6.1
+# fetch.type git
+# git.url    https://github.com/ProjectCCNx/ccnx.git
+# git.branch ccnx-0.6.1
 
-# master_sites http://www.ccnx.org/releases/
-# checksums   rmd160 9c8eb49aa8d2edfe5eb873312f6273ca469255a4 \
-#             sha256 7ac8f2ac3b6bcda85e9b4df34c025f68d576d98dcadf16eea2ed1c3dcee4d557
+master_sites http://www.ccnx.org/releases/
+checksums   rmd160 073478f3d5818b0e4fe09e21a727e5f3207e4277 \
+            sha256 bfaae10c2c1a327d77f752737b60243e23fd8f3a7c7025ae92221ba0a700b889 
 
-# use_parallel_build  yes
+use_parallel_build  yes
 
 depends_lib port:openssl \
             port:expat \
             port:libpcap \
             port:libxml2
 
-# default_variants   +java
+set ccnxuser  ccnx
+set ccnxgroup ccnx
+set ccnxdir   ${prefix}/etc/ccnx
+
+add_users ${ccnxuser} shell=/bin/sh group=${ccnxgroup} \
+    home=${ccnxdir} \
+    realname=CCNx\ Account
+
+default_variants   +java +apps
+
+variant java description {Enable Java API build} {
+    configure.env-delete BUILD_JAVA=false
+}
+
+variant apps requires java description {Enable build of reference applications} {
+    configure.env-delete BUILD_APPS=false
+}
 
 configure.env-append OPENSSL_CFLAGS=-I${prefix}/include
 configure.env-append OPENSSL_LIBS=-L${prefix}/lib
 configure.env-append INSTALL_BASE=${prefix}
+configure.env-append BUILD_JAVA=false
+configure.env-append BUILD_APPS=false
 configure.cflags -DCCNX_DIR=\\\"${prefix}/etc/ccnx\\\" 
 
 pre-build {
     reinplace "s|\$HOME/.ccnx/|${prefix}/etc/ccnx/|g" ${worksrcpath}/csrc/util/ccndstart.sh 
 }
 
+post-destroot {
+    system "mkdir -p ${destroot}${prefix}/var/log"
+    system "touch ${destroot}${prefix}/var/log/ccnd.log"
+    system "chown ${ccnxuser}:${ccnxgroup} ${destroot}${prefix}/var/log/ccnd.log"
+
+    file mkdir ${destroot}${prefix}/etc/ccnx
+    file copy ${worksrcpath}/csrc/libexec/ccnd.conf.sample ${destroot}${prefix}/etc/ccnx/
+
+    system "echo CCND_LOG=${prefix}/var/log/ccnd.log > ${destroot}${prefix}/etc/ccnx/ccndrc.sample"
+    system "echo CCND_DEBUG=16 >> ${destroot}${prefix}/etc/ccnx/ccndrc.sample"
+}
+
 build.env-append OPENSSL_CFLAGS=-I${prefix}/include
 build.env-append OPENSSL_LIBS=-L${prefix}/lib
-build.env-append INSTALL_BASE=${destroot}${prefix}
-build.env-append CCNX_DIR=${destroot}${prefix}/etc/ccnx
-
-destroot.env-append INSTALL_BASE=${destroot}${prefix}
-destroot.env-append CCNX_DIR=${destroot}${prefix}/etc/ccnx
+build.env-append INSTALL_BASE=${prefix}
 
 patchfiles    patch-macports-customizations.diff
 
 startupitem.pidfile     none
-startupitem.start       "${prefix}/bin/ccndstart"
-startupitem.stop        "${prefix}/bin/ccndstop"
-startupitem.restart     "${prefix}/bin/ccndstop && sleep 3 && ${prefix}/bin/ccndstart"
+startupitem.start       "su ${ccnxuser} -c \"${prefix}/bin/ccndstart\""
+startupitem.stop        "su ${ccnxuser} -c \"${prefix}/bin/ccndstop\""
+startupitem.restart     "su ${ccnxuser} -c \"${prefix}/bin/ccndstop && sleep 3 && ${prefix}/bin/ccndstart\""
 
 startupitem.create      yes
 startupitem.name        ccnx
diff --git a/net/ccnx/files/patch-macports-customizations.diff b/net/ccnx/files/patch-macports-customizations.diff
index 5c98dda..2f27835 100644
--- a/net/ccnx/files/patch-macports-customizations.diff
+++ b/net/ccnx/files/patch-macports-customizations.diff
@@ -1,139 +1,555 @@
+diff --git Makefile Makefile
+index 2748ac8..cf3292a 100644
+--- Makefile
++++ Makefile
+@@ -13,37 +13,48 @@
+ #
+ 
+ # Subdirectories we build in
+-TOPSUBDIRS = doc/manpages doc/technical csrc schema javasrc apps `cat local.subdirs 2>/dev/null || :`
++TOPSUBDIRS = doc/manpages doc/technical csrc schema `cat local.subdirs 2>/dev/null || :`
+ # Packing list for packaging
+ PACKLIST = Makefile README LICENSE NEWS NOTICES configure doc/index.txt $(TOPSUBDIRS) android experiments
+ BLDMSG = printf '=== %s ' 'Building $@ in' && pwd
+ 
++# Include build parameters
++include csrc/conf.mk
++
+ default all: _always
+ 	for i in $(TOPSUBDIRS); do         \
+ 	  (cd "$$i" && pwd && $(MAKE) $@) || exit 1;	\
+ 	done
+-	(cd csrc/lib && { test -f "$$HOME/.ccnx/.ccnx_keystore" || $(MAKE) test; }; )
++	if [ "x$(BUILD_JAVA)" = "xtrue" ]; then \
++	  (cd javasrc && $(MAKE) $@); \
++	  if [ "x$(BUILD_APPS)" = "xtrue" ]; then \
++	    (cd apps && $(MAKE) $@); \
++	  fi; \
++	fi
+ 	mkdir -p ./lib ./bin
+ 	test -d ./include || ln -s ./csrc/include
+ 	(cd csrc && $(MAKE) install INSTALL_BASE=`pwd`/..)
+-	(cd javasrc && $(MAKE) install INSTALL_BASE=`pwd`/..)
+-	(cd apps && $(MAKE) install INSTALL_BASE=`pwd`/..)
++	if [ "x$(BUILD_JAVA)" = "xtrue" ]; then \
++	  (cd javasrc && $(MAKE) install INSTALL_BASE=`pwd`/..); \
++	  if [ "x$(BUILD_APPS)" = "xtrue" ]; then \
++	    (cd apps && $(MAKE) install INSTALL_BASE=`pwd`/..); \
++	  fi ;\
++	fi
+ 
+ clean depend test check shared: _always
+-	for i in $(TOPSUBDIRS); do         \
++	for i in $(TOPSUBDIRS) javasrc apps; do         \
+ 	  (cd "$$i" && pwd && $(MAKE) $@) || exit 1;	\
+ 	done
+ 	@rm -f _always
+ 
+ testinstall install uninstall: _always
+-	IB=`[ -z '$(INSTALL_BASE)' ] && grep ^INSTALL_BASE csrc/conf.mk 2>/dev/null | sed -e 's/ //g' || echo INSTALL_BASE=$(INSTALL_BASE)`; \
+-	for i in $(TOPSUBDIRS); do         \
+-	  (cd "$$i" && pwd && $(MAKE) $$IB $@) || exit 1;	\
++	for i in $(TOPSUBDIRS) javasrc apps; do         \
++	  (cd "$$i" && pwd && $(MAKE) $@) || exit 1;	\
+ 	done
+ 	@rm -f _always
+ 
+ documentation dist-docs: _always
+-	for i in $(TOPSUBDIRS) android; do         \
++	for i in $(TOPSUBDIRS) javasrc apps android; do         \
+ 	  (cd "$$i" && pwd && $(MAKE) $@) || exit 1;	\
+ 	done
+ 	@rm -f _always
+diff --git apps/Makefile apps/Makefile
+index acc347c..f0d8638 100644
+--- apps/Makefile
++++ apps/Makefile
+@@ -19,7 +19,7 @@
+ 
+ SUBDIRS = HttpProxy ccnChat ccnFileProxy `cat local.subdirs 2>/dev/null || :`
+ MAKEF =  -f ../conf.mk -f dir.mk -f ../subr.mk $(PASSTHRU)
+-PASSTHRU = `[ -z '$(INSTALL_BASE)' ] || echo INSTALL_BASE=$(INSTALL_BASE)`
++PASSTHRU = `[ -z '$(INSTALL_BASE)' ] || echo INSTALL_BASE=$(DESTDIR)$(INSTALL_BASE)`
+ CFLAGS = -g
+ CSRCDIR = ../csrc
+ 
+diff --git apps/java.mk apps/java.mk
+index df9358e..d1cf718 100644
+--- apps/java.mk
++++ apps/java.mk
+@@ -12,28 +12,22 @@
+ # FOR A PARTICULAR PURPOSE.
+ #
+ 
++include ../conf.mk
++
+ ANT = `command -v ant || echo echo SKIPPING ant`
+ LIBS = $(JAR)
+ WHINE = sh -c "type $(ANT) 2>/dev/null ||                  \
+                echo Skipping java build in $$(pwd -L) -    \
+                     $(ANT) is not installed; "
+-# Default, the top-level Makefile default target will
+-# call the install target here but override INSTALL_BASE
+-# with dir in the source tree
+-INSTALL_LIB = $(INSTALL_BASE)/lib
+-INSTALL_BIN = $(INSTALL_BASE)/bin
+-INSTALL = cp 
+-CP = cp
+-LS = /bin/ls
+ 
+ default all: jar
+ check: test
+ 
+ install:
+ 	@test -f $(JAR) && $(MAKE) real_install \
+-            INSTALL_BASE=$(INSTALL_BASE)        \
+-            INSTALL_LIB=$(INSTALL_LIB)          \
+-            INSTALL_BIN=$(INSTALL_BIN) || $(WARN_NO_INSTALL)
++            INSTALL_BASE=$(DESTDIR)$(INSTALL_BASE)        \
++            INSTALL_LIB=$(DESTDIR)$(INSTALL_LIB)          \
++            INSTALL_BIN=$(DESTDIR)$(INSTALL_BIN) || $(WARN_NO_INSTALL)
+ 
+ real_install: _always
+ 	test -d $(INSTALL_LIB) 
+@@ -43,8 +37,8 @@ real_install: _always
+ 	$(CP) -R tools/. $(INSTALL_BIN)
+ 
+ uninstall:
+-	for i in $(LIBS) ""; do test -z "$$i" || rm -f $(INSTALL_LIB)/`basename $$i`; done
+-	for i in `$(LS) tools` "" ; do test -z "$$i" || rm -f $(INSTALL_BIN)/`basename $$i`; done
++	for i in $(LIBS) ""; do test -z "$$i" || rm -f $(DESTDIR)$(INSTALL_LIB)/`basename $$i`; done
++	for i in `$(LS) tools` "" ; do test -z "$$i" || rm -f $(DESTDIR)$(INSTALL_BIN)/`basename $$i`; done
+ 
+ # Use ant to actually do the work for these targets
+ jar test: _always
+diff --git csrc/ccnd/ccnd-init-keystore-helper.sh csrc/ccnd/ccnd-init-keystore-helper.sh
+deleted file mode 100755
+index ede0153..0000000
+--- csrc/ccnd/ccnd-init-keystore-helper.sh
++++ /dev/null
+@@ -1,47 +0,0 @@
+-#!/bin/sh
+-# ccnd/ccnd-init-keystore-helper.sh
+-# 
+-# Part of the CCNx distribution.
+-#
+-# Copyright (C) 2009 Palo Alto Research Center, Inc.
+-#
+-# This work is free software; you can redistribute it and/or modify it under
+-# the terms of the GNU General Public License version 2 as published by the
+-# Free Software Foundation.
+-# This work 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.
+-#
+-: ${RSA_KEYSIZE:=1024}
+-exec >&2
+-Fail () {
+-  echo '*** Failed' "$*"
+-  exit 1
+-}
+-cd `dirname "$1"` || Fail bad setup
+-umask 077
+-trap 'rm -f *.pem openssl.cnf p' 0
+-cat <<EOF >openssl.cnf
+-# This is not really relevant because we're not sending cert requests anywhere,
+-# but openssl req can refuse to go on if it has no config file.
+-[ req ]
+-distinguished_name	= req_distinguished_name
+-[ req_distinguished_name ]
+-countryName			= Country Name (2 letter code)
+-countryName_default		= AU
+-countryName_min			= 2
+-countryName_max			= 2
+-EOF
+-openssl req -config openssl.cnf       \
+-            -newkey rsa:$RSA_KEYSIZE  \
+-            -x509                     \
+-            -keyout private_key.pem   \
+-            -out certout.pem          \
+-            -subj /CN="CCND-internal" \
+-            -nodes                   || Fail openssl req
+-openssl pkcs12 -export                \
+-            -name "CCND"              \
+-            -out "$1"                 \
+-            -in certout.pem           \
+-            -inkey private_key.pem    \
+-            -password file:p         || Fail openssl pkcs12
+diff --git csrc/ccnd/dir.mk csrc/ccnd/dir.mk
+index 72c8438..2ec0946 100644
+--- csrc/ccnd/dir.mk
++++ csrc/ccnd/dir.mk
+@@ -15,7 +15,7 @@
+ LDLIBS = -L$(CCNLIBDIR) $(MORE_LDLIBS) -lccn
+ CCNLIBDIR = ../lib
+ 
+-INSTALLED_PROGRAMS = ccnd ccndsmoketest ccnd-init-keystore-helper
++INSTALLED_PROGRAMS = ccnd ccndsmoketest 
+ PROGRAMS = $(INSTALLED_PROGRAMS)
+ DEBRIS = anything.ccnb contentobjecthash.ccnb contentmishash.ccnb \
+          contenthash.ccnb
+@@ -24,7 +24,7 @@ BROKEN_PROGRAMS =
+ CSRC = ccnd_main.c ccnd.c ccnd_msg.c ccnd_stats.c ccnd_internal_client.c ccndsmoketest.c
+ HSRC = ccnd_private.h
+ SCRIPTSRC = testbasics fortunes.ccnb contentobjecthash.ref anything.ref \
+-            ccnd-init-keystore-helper.sh minsuffix.ref
++            minsuffix.ref
+  
+ default: $(PROGRAMS)
+ 
+@@ -40,10 +40,6 @@ ccnd: $(CCND_OBJ) ccnd_built.sh
+ ccnd_built.sh:
+ 	touch ccnd_built.sh
+ 
+-ccnd-init-keystore-helper: ccnd-init-keystore-helper.sh
+-	sed -e 's@/bin/sh@'`which sh`'@g' ccnd-init-keystore-helper.sh > $@
+-	chmod +x $@
+-
+ ccndsmoketest: ccndsmoketest.o
+ 	$(CC) $(CFLAGS) -o $@ ccndsmoketest.o $(LDLIBS)
+ 
 diff --git csrc/configure csrc/configure
-index 962d76a..43ec3ea 100755
+index 962d76a..e838792 100755
 --- csrc/configure
 +++ csrc/configure
-@@ -39,7 +39,7 @@ TryAppend "`uname -sr | sed -e 's/ /-/g'`"
+@@ -39,16 +39,22 @@ TryAppend "`uname -sr | sed -e 's/ /-/g'`"
  TryAppend "local"
  TryScript "`uname`" "$@"
  TryScript "local" "$@"
 -ProvideDefault CPREFLAGS = -I../include
+-ProvideDefault PCAP_PROGRAMS = ccndumppcap
+-ProvideDefault RESOLV_LIBS = -lresolv
++ProvideDefault CC = ${CC:=cc}
 +ProvideDefault CPREFLAGS = -I../include ${CFLAGS:-}
- ProvideDefault PCAP_PROGRAMS = ccndumppcap
- ProvideDefault RESOLV_LIBS = -lresolv
++ProvideDefault PCAP_PROGRAMS = ${PCAP_PROGRAMS:-ccndumppcap}
++ProvideDefault RESOLV_LIBS = ${RESOLV_LIBS:--lresolv}
  ProvideDefault INSTALL_BASE = ${INSTALL_BASE:-/usr/local}
+-ProvideDefault INSTALL_INCLUDE = '$(INSTALL_BASE)/include'
+-ProvideDefault INSTALL_LIB = '$(INSTALL_BASE)/lib'
+-ProvideDefault INSTALL_BIN = '$(INSTALL_BASE)/bin'
+-ProvideDefault INSTALL = install
+-ProvideDefault RM = rm -f
+-ProvideDefault SH = /bin/sh
++ProvideDefault INSTALL_INCLUDE = ${INSTALL_INCLUDE:-\$(INSTALL_BASE)/include}
++ProvideDefault INSTALL_LIB = ${INSTALL_LIB:-\$(INSTALL_BASE)/lib}
++ProvideDefault INSTALL_BIN = ${INSTALL_BIN:-\$(INSTALL_BASE)/bin}
++ProvideDefault INSTALL = ${INSTALL:-install}
++ProvideDefault CP = ${CP:-cp}
++ProvideDefault RM = ${RM:-rm -f}
++ProvideDefault SH = ${SH:-/bin/sh}
++ProvideDefault LS = ${LS:-/bin/ls}
++
++ProvideDefault BUILD_JAVA = ${BUILD_JAVA:-true}
++ProvideDefault BUILD_APPS = ${BUILD_APPS:-true}
+ 
+ echo ============= conf.mk =============>&2
+ cat conf.mk				>&2
+diff --git csrc/include/ccn/ccn.h csrc/include/ccn/ccn.h
+index 548d5d4..22990fb 100644
+--- csrc/include/ccn/ccn.h
++++ csrc/include/ccn/ccn.h
+@@ -911,7 +911,7 @@ int ccn_encode_StatusResponse(struct ccn_charbuf *buf,
+  * error encountered during a call using the given handle.
+  * ccn_seterror records error info, ccn_geterror gets it.
+  */
+-void ccn_perror(struct ccn *h, const char *s);
++void ccn_perror(struct ccn *h, const char *s, ...);
+ int ccn_seterror(struct ccn *h, int error_code);
+ int ccn_geterror(struct ccn *h);
+ 
 diff --git csrc/lib/ccn_client.c csrc/lib/ccn_client.c
-index 606fd36..a3392fc 100644
+index 606fd36..35f2b43 100644
 --- csrc/lib/ccn_client.c
 +++ csrc/lib/ccn_client.c
-@@ -2607,23 +2607,58 @@ ccn_chk_signing_params(struct ccn *h,
+@@ -163,9 +163,12 @@ tv_earlier(const struct timeval *a, const struct timeval *b)
+  *        where available.
+  */
+ void
+-ccn_perror(struct ccn *h, const char *s)
++ccn_perror(struct ccn *h, const char *s, ...)
+ {
+     const char *dlm = ": ";
++    va_list ap;
++    va_start(ap, s);
++    
+     if (s == NULL) {
+         if (h->err > 0)
+             s = strerror(h->err);
+@@ -173,8 +176,10 @@ ccn_perror(struct ccn *h, const char *s)
+             dlm = s = "";
+     }
+     // XXX - time stamp
+-    fprintf(stderr, "ccn_client.c:%d[%d] - error %d%s%s\n",
+-                        h->errline, (int)getpid(), h->err, dlm, s);
++    fprintf(stderr, "ccn_client.c:%d[%d] - error %d%s",
++                        h->errline, (int)getpid(), h->err, dlm);
++    vfprintf(stderr, s, ap);
++    fprintf(stderr, "\n");
+ }
+ 
+ static int
+@@ -2562,6 +2567,62 @@ ccn_get_public_key(struct ccn *h,
+     return(res);
+ }
+ 
++int
++ccn_load_key_or_create(struct ccn *h,
++                       const char *keystore,
++                       struct ccn_charbuf *default_pubid,
++                       size_t key_size)
++{
++  const char *password = NULL;
++  int res = 0;
++  
++  password = getenv ("CCNX_KEYSTORE_PASSWORD");
++  if (password == 0) {
++    password = "Th1s1sn0t8g00dp8ssw0rd.";
++  }
++            
++  res = ccn_load_private_key(h,
++                             keystore,
++                             password,
++                             default_pubid);
++              
++  if (res != 0 || default_pubid->length != key_size) {
++    // two cases, either file exists and we password is wrong or file does not exist
++
++    if (access (keystore, R_OK) == 0) {
++      ccn_perror (h, "Keystore file [%s] exists, but private key cannot be loaded.  "
++                  "Check if CCNX_KEYSTORE_PASSWORD is set to a correct password, "
++                  "otherwise remove [%s] and it will be automatically created.",
++                  keystore, keystore);
++      res = NOTE_ERR (h, -1);
++      return res;
++    }
++    
++    ccn_perror (h, "Keystore [%s] does not exist and will be automatically created", keystore);
++    
++    res = ccn_keystore_file_init ((char*)keystore, (char*)password,
++                                  "ccnxuser", 0, 3650); // create a key valid for 10 years
++    if (res != 0) {
++      ccn_perror (h, "Cannot create keystore [%s]", keystore);
++      res = NOTE_ERRNO (h);
++      return res;
++    }
++    
++    res = ccn_load_private_key(h,
++                               keystore,
++                               password,
++                               default_pubid);
++    if (res != 0 || default_pubid->length != key_size) {
++      // this definitely should not happen
++      ccn_perror (h, "Cannot load keystore [%s] just after it has been created", keystore);
++      res = NOTE_ERRNO (h);
++      return res;
++    }
++  }
++
++  return res;
++}
++
+ /**
+  * This is mostly for use within the library,
+  * but may be useful for some clients.
+@@ -2582,6 +2643,7 @@ ccn_chk_signing_params(struct ccn *h,
+     int i;
+     int conflicting;
+     int needed;
++    struct stat sb;
+     
+     if (params != NULL)
+         *result = *params;
+@@ -2607,23 +2669,57 @@ ccn_chk_signing_params(struct ccn *h,
              temp = ccn_charbuf_create();
              if (default_pubid == NULL || temp == NULL)
                  return(NOTE_ERRNO(h));
--            ccnx_dir = getenv("CCNX_DIR");
++
++            res = -1;
++            
++            // check CCNX_DIR
+             ccnx_dir = getenv("CCNX_DIR");
 -            if (ccnx_dir == NULL || ccnx_dir[0] == 0) {
 -                home = getenv("HOME");
 -                if (home == NULL)
 -                    home = "";
--                ccn_charbuf_putf(temp, "%s/.ccnx/.ccnx_keystore", home);
++            if (ccnx_dir != NULL && ccnx_dir[0] != 0) {
++              ccn_charbuf_reset(temp);
++              ccn_charbuf_putf(temp, "%s/.ccnx_keystore", ccnx_dir);
 +
-+            res = -1;
-+#ifdef CCNX_DIR
-+            if (res < 0 || default_pubid->length != sizeof(result->pubid)) {
-+              // check preconfigured directory
-+              ccnx_dir = CCNX_DIR;
-+              if (ccnx_dir != NULL && ccnx_dir[0] != 0) {
++              res = ccn_load_key_or_create (h,
++                                            ccn_charbuf_as_string (temp),
++                                            default_pubid,
++                                            sizeof(result->pubid));
++            }
++            
++            if (res < 0) {
++              // check HOME
++              home = getenv("HOME");
++              if (home != NULL) {
++                // step 1. Check if home directory exists
 +                ccn_charbuf_reset(temp);
-+                ccn_charbuf_putf(temp, "%s/.ccnx_keystore", ccnx_dir);
-+
-+                res = ccn_load_private_key(h,
-+                                           ccn_charbuf_as_string(temp),
-+                                           "Th1s1sn0t8g00dp8ssw0rd.",
-+                                           default_pubid);
++                ccn_charbuf_putf(temp, "%s/.ccnx", home);
++                
++                res = stat (ccn_charbuf_as_string (temp), &sb);
++                if (res != 0 || !(sb.st_mode & S_IFDIR))
++                  {
++                    res = mkdir (ccn_charbuf_as_string (temp), S_IRWXU);
++                    if (res != 0)
++                      {
++                        ccn_perror (h, "Failed to create directory [%s]", ccn_charbuf_as_string (temp));
++                      }
++                  }
++                
++                ccn_charbuf_reset(temp);
+                 ccn_charbuf_putf(temp, "%s/.ccnx/.ccnx_keystore", home);
++                
++                res = ccn_load_key_or_create (h,
++                                              ccn_charbuf_as_string (temp),
++                                              default_pubid,
++                                              sizeof(result->pubid));
 +              }
              }
 -            else
-+#endif
-+            
-+            if (res < 0 || default_pubid->length != sizeof(result->pubid)) {
-+              // check CCNX_DIR
-+              ccnx_dir = getenv("CCNX_DIR");
-+              if (ccnx_dir != NULL && ccnx_dir[0] != 0) {
-+                ccn_charbuf_reset(temp);
-                 ccn_charbuf_putf(temp, "%s/.ccnx_keystore", ccnx_dir);
+-                ccn_charbuf_putf(temp, "%s/.ccnx_keystore", ccnx_dir);
 -            res = ccn_load_private_key(h,
 -                                       ccn_charbuf_as_string(temp),
 -                                       "Th1s1sn0t8g00dp8ssw0rd.",
 -                                       default_pubid);
+-            if (res == 0 && default_pubid->length == sizeof(result->pubid)) {
 +
-+                res = ccn_load_private_key(h,
-+                                           ccn_charbuf_as_string(temp),
-+                                           "Th1s1sn0t8g00dp8ssw0rd.",
-+                                           default_pubid);
-+              }
-+            }
-+            
-+            if (res < 0 || default_pubid->length != sizeof(result->pubid)) {
-+              // check HOME
-+              home = getenv("HOME");
-+              if (home != NULL) {
-+                ccn_charbuf_reset(temp);
-+                ccn_charbuf_putf(temp, "%s/.ccnx/.ccnx_keystore", home);
-+                res = ccn_load_private_key(h,
-+                                           ccn_charbuf_as_string(temp),
-+                                           "Th1s1sn0t8g00dp8ssw0rd.",
-+                                           default_pubid);
-+              }
-+            }
-+            
-             if (res == 0 && default_pubid->length == sizeof(result->pubid)) {
++            if (res == 0) {
                  h->default_pubid = default_pubid;
                  default_pubid = NULL;
              }
 +            else {
-+              ccn_perror(h, ccn_charbuf_as_string(temp));
++              ccn_perror(h, "Fail to load private key from keystore");
++              res = NOTE_ERRNO (h);
 +            }
          }
          if (h->default_pubid == NULL)
              res = NOTE_ERRNO(h);
 diff --git csrc/lib/ccn_initkeystore.sh csrc/lib/ccn_initkeystore.sh
-index 12bc9e3..a171a0e 100755
+deleted file mode 100755
+index 12bc9e3..0000000
 --- csrc/lib/ccn_initkeystore.sh
-+++ csrc/lib/ccn_initkeystore.sh
-@@ -15,6 +15,7 @@
- # Create a ccn keystore without relying on java
- : ${RSA_KEYSIZE:=1024}
- : ${CCN_USER:=`id -n -u`}
-+: ${CCNX_HOME:=.ccnx}
- Fail () {
-   echo '*** Failed' "$*"
-   exit 1
-@@ -37,6 +38,7 @@ countryName_default		= AU
- countryName_min			= 2
- countryName_max			= 2
- EOF
-+RANDFILE=.rnd
- openssl req    -config openssl.cnf      \
-                -newkey rsa:$RSA_KEYSIZE \
-                -x509                    \
++++ /dev/null
+@@ -1,51 +0,0 @@
+-#!/bin/sh
+-# lib/ccn_initkeystore.sh
+-# 
+-# Part of the CCNx distribution.
+-#
+-# Copyright (C) 2009-2010 Palo Alto Research Center, Inc.
+-#
+-# This work is free software; you can redistribute it and/or modify it under
+-# the terms of the GNU General Public License version 2 as published by the
+-# Free Software Foundation.
+-# This work 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.
+-#
+-# Create a ccn keystore without relying on java
+-: ${RSA_KEYSIZE:=1024}
+-: ${CCN_USER:=`id -n -u`}
+-Fail () {
+-  echo '*** Failed' "$*"
+-  exit 1
+-}
+-test -d .ccnx && rm -rf .ccnx
+-test $RSA_KEYSIZE -ge 512 || Fail \$RSA_KEYSIZE too small to sign CCN content
+-(umask 077 && mkdir .ccnx) || Fail $0 Unable to create .ccnx directory
+-cd .ccnx
+-umask 077
+-# Set a trap to cleanup on the way out
+-trap 'rm -f *.pem openssl.cnf' 0
+-cat <<EOF >openssl.cnf
+-# This is not really relevant because we're not sending cert requests anywhere,
+-# but openssl req can refuse to go on if it has no config file.
+-[ req ]
+-distinguished_name	= req_distinguished_name
+-[ req_distinguished_name ]
+-countryName			= Country Name (2 letter code)
+-countryName_default		= AU
+-countryName_min			= 2
+-countryName_max			= 2
+-EOF
+-openssl req    -config openssl.cnf      \
+-               -newkey rsa:$RSA_KEYSIZE \
+-               -x509                    \
+-               -keyout private_key.pem  \
+-               -out certout.pem         \
+-               -subj /CN="$CCN_USER"    \
+-               -nodes                                   || Fail openssl req
+-openssl pkcs12 -export -name "ccnxuser" \
+-               -out .ccnx_keystore      \
+-               -in certout.pem          \
+-               -inkey private_key.pem   \
+-               -password pass:'Th1s1sn0t8g00dp8ssw0rd.' || Fail openssl pkcs12
 diff --git csrc/lib/dir.mk csrc/lib/dir.mk
-index 6489299..145eec7 100644
+index 6489299..c03316d 100644
 --- csrc/lib/dir.mk
 +++ csrc/lib/dir.mk
-@@ -78,7 +78,7 @@ shlib: $(SHLIBNAME)
+@@ -21,7 +21,6 @@ PROGRAMS = hashtbtest skel_decode_test \
+ 
+ BROKEN_PROGRAMS =
+ DEBRIS = ccn_verifysig _bt_*
+-SCRIPTSRC = ccn_initkeystore.sh
+ CSRC = ccn_bloom.c \
+        ccn_btree.c ccn_btree_content.c ccn_btree_store.c \
+        ccn_buf_decoder.c ccn_buf_encoder.c ccn_bulkdata.c \
+@@ -56,28 +55,28 @@ default all: dtag_check lib $(PROGRAMS)
+ # Don't try to build shared libs right now.
+ # all: shlib
+ 
+-all: basicparsetest ccn_verifysig
++# all: basicparsetest ccn_verifysig
+ 
+ install: install_headers
+ install_headers:
+-	@test -d $(INSTALL_INCLUDE) || (echo $(INSTALL_INCLUDE) does not exist.  Please mkdir -p $(INSTALL_INCLUDE) if this is what you intended. && exit 2)
+-	mkdir -p $(INSTALL_INCLUDE)/ccn
++	@test -d $(DESTDIR)$(INSTALL_INCLUDE) || (echo $(DESTDIR)$(INSTALL_INCLUDE) does not exist.  Please mkdir -p $(DESTDIR)$(INSTALL_INCLUDE) if this is what you intended. && exit 2)
++	mkdir -p $(DESTDIR)$(INSTALL_INCLUDE)/ccn
+ 	for i in `cd ../include/ccn && echo *.h`; do                \
+-	    cmp -s ../include/ccn/$$i $(INSTALL_INCLUDE)/ccn/$$i || \
+-	        cp ../include/ccn/$$i $(INSTALL_INCLUDE)/ccn/$$i || \
++	    cmp -s ../include/ccn/$$i $(DESTDIR)$(INSTALL_INCLUDE)/ccn/$$i || \
++	        cp ../include/ccn/$$i $(DESTDIR)$(INSTALL_INCLUDE)/ccn/$$i || \
+ 	        exit 1;                                             \
+ 	done
+ 
+ uninstall: uninstall_headers
+ uninstall_headers:
+-	test -L $(INSTALL_INCLUDE)/ccn && $(RM) $(INSTALL_INCLUDE)/ccn ||:
+-	test -L $(INSTALL_INCLUDE) || $(RM) -r $(INSTALL_INCLUDE)/ccn
++	test -L $(DESTDIR)$(INSTALL_INCLUDE)/ccn && $(RM) $(DESTDIR)$(INSTALL_INCLUDE)/ccn ||:
++	test -L $(DESTDIR)$(INSTALL_INCLUDE) || $(RM) -r $(DESTDIR)$(INSTALL_INCLUDE)/ccn
+ 
+ shlib: $(SHLIBNAME)
+ 
  lib: libccn.a
  
- test: default keystore_check encodedecodetest ccnbtreetest
--	./encodedecodetest -o /dev/null
-+	./encodedecodetest -k $(CCNX_DIR)/.ccnx_keystore -o /dev/null
+-test: default keystore_check encodedecodetest ccnbtreetest
++test: default encodedecodetest ccnbtreetest
+ 	./encodedecodetest -o /dev/null
  	./ccnbtreetest
  	./ccnbtreetest - < q.dat
- 	rm -R _bt_*
-@@ -87,12 +87,12 @@ dtag_check: _always
+@@ -86,14 +85,6 @@ test: default keystore_check encodedecodetest ccnbtreetest
+ dtag_check: _always
  	@./gen_dtag_table 2>/dev/null | diff - ccn_dtag_table.c | grep '^[<]' >/dev/null && echo '*** Warning: ccn_dtag_table.c may be out of sync with tagnames.cvsdict' || :
  
- keystore_check: ccn_initkeystore.sh
+-keystore_check: ccn_initkeystore.sh
 -	test -f "$$HOME/.ccnx/.ccnx_keystore" || $(MAKE) -f dir.mk new_keystore
-+	test -f "$(CCNX_DIR)/.ccnx_keystore" || $(MAKE) -f dir.mk new_keystore
- 
- new_keystore:
- 	@echo === CCNx Keystore not found in your home directory
- 	@echo === I will create one for you now '(^C to abort)'
+-
+-new_keystore:
+-	@echo === CCNx Keystore not found in your home directory
+-	@echo === I will create one for you now '(^C to abort)'
 -	sleep 1 && sh ccn_initkeystore.sh && sleep 3 && mv .ccnx "$$HOME"
-+	sleep 1 && sh ccn_initkeystore.sh && sleep 3 && mkdir -p "$(CCNX_DIR)/" && mv .ccnx/.ccnx_keystore "$(CCNX_DIR)/"
- 
+-
  libccn.a: $(LIB_OBJS)
  	ar crus $@ $(LIB_OBJS)
-@@ -113,7 +113,7 @@ skel_decode_test: skel_decode_test.o
+ 
+@@ -113,7 +104,7 @@ skel_decode_test: skel_decode_test.o
  basicparsetest: basicparsetest.o libccn.a
  	$(CC) $(CFLAGS) -o $@ basicparsetest.o $(LDLIBS) $(OPENSSL_LIBS) -lcrypto
  
@@ -142,7 +558,7 @@
  	$(CC) $(CFLAGS) -o $@ encodedecodetest.o $(LDLIBS) $(OPENSSL_LIBS) -lcrypto
  
  ccn_digest.o:
-@@ -149,16 +149,16 @@ ccn_fetch.o:
+@@ -149,16 +140,16 @@ ccn_fetch.o:
  ccn_verifysig.o:
  	$(CC) $(CFLAGS) $(OPENSSL_CFLAGS) -c ccn_verifysig.c
  
@@ -162,3 +578,158 @@
  	$(CC) $(CFLAGS) -o $@ ccndumppcap.o $(LDLIBS) $(OPENSSL_LIBS) -lcrypto -lpcap
  
  ccnbtreetest.o:
+diff --git csrc/lib/encodedecodetest.c csrc/lib/encodedecodetest.c
+index be6a853..09e02ea 100644
+--- csrc/lib/encodedecodetest.c
++++ csrc/lib/encodedecodetest.c
+@@ -210,17 +210,19 @@ main (int argc, char *argv[]) {
+                        NULL};
+     struct path * cur_path = NULL;
+     struct ccn_keystore *keystore = ccn_keystore_create();
+-    char *home = getenv("HOME");
+-    char *keystore_suffix = "/.ccnx/.ccnx_keystore";
+     char *keystore_name = NULL;
++    char *keystore_password = NULL;
+ 
+     int i;
+ 
+-    while ((i = getopt(argc, argv, "k:o:")) != -1) {
++    while ((i = getopt(argc, argv, "k:p:o:")) != -1) {
+         switch (i) {
+             case 'k':
+                 keystore_name = optarg;
+                 break;
++            case 'p':
++                keystore_password = optarg;
++                break;
+             case 'o':
+                 outname = optarg;
+                 break;
+@@ -231,21 +233,38 @@ main (int argc, char *argv[]) {
+     }
+     
+ 
+-    if (keystore_name == NULL && home == NULL) {
+-        printf("Unable to determine home directory for keystore\n");
+-        exit(1);
+-    }
+     if (keystore_name == NULL) {
+-        keystore_name = calloc(1, strlen(home) + strlen(keystore_suffix) + 1);
+-        strcat(keystore_name, home);
+-        strcat(keystore_name, keystore_suffix);
++      keystore_name = tmpnam (NULL); // should be ok, there is just single thread
+     }
+ 
+-    if (0 != ccn_keystore_init(keystore, keystore_name, "Th1s1sn0t8g00dp8ssw0rd.")) {
+-        printf("Failed to initialize keystore\n");
+-        exit(1);
++    if (keystore_password == NULL) {
++      keystore_password = "Th1s1sn0t8g00dp8ssw0rd.";
+     }
+ 
++    res = ccn_keystore_init (keystore, keystore_name, keystore_password);
++    if (res != 0)
++      {
++        printf ("Initializing keystore in %s\n", keystore_name);
++        
++        res = ccn_keystore_file_init (keystore_name, keystore_password,
++                                      "ccnxuser", 0, 3650); // create a key valid for 10 years
++        if (res != 0) {
++          fprintf (stderr, "Cannot create keystore [%s]", keystore_name);
++          return res;
++        }
++
++        // init again
++        res = ccn_keystore_init(keystore, keystore_name, keystore_password);
++        if (res != 0) {
++          printf("Failed to initialize keystore\n");
++          exit(1);
++        }
++      }        
++
++    
++
++    
++
+     printf("Creating signed_info\n");
+     res = ccn_signed_info_create(signed_info,
+                                  /*pubkeyid*/ccn_keystore_public_key_digest(keystore),
+diff --git csrc/subr.mk csrc/subr.mk
+index e24c230..3361a49 100644
+--- csrc/subr.mk
++++ csrc/subr.mk
+@@ -31,20 +31,20 @@ $(OBJDIR)/dir.mk: dir.mk
+ 	cp -p dir.mk $(OBJDIR)/dir.mk
+ 
+ install_libs: $(LIBS)
+-	@test -d $(INSTALL_LIB) || (echo $(INSTALL_LIB) does not exist.  Please mkdir -p $(INSTALL_LIB) if this is what you intended. && exit 2)
+-	for i in $(LIBS) ""; do test -z "$$i" || $(INSTALL) $$i $(INSTALL_LIB); done
++	@test -d $(DESTDIR)$(INSTALL_LIB) || (echo $(DESTDIR)$(INSTALL_LIB) does not exist.  Please mkdir -p $(DESTDIR)$(INSTALL_LIB) if this is what you intended. && exit 2)
++	for i in $(LIBS) ""; do test -z "$$i" || $(INSTALL) $$i $(DESTDIR)$(INSTALL_LIB); done
+ 
+ install_programs: $(INSTALLED_PROGRAMS)
+-	@test -d $(INSTALL_BIN) || (echo $(INSTALL_BIN) does not exist.  Please mkdir -p $(INSTALL_BIN) if this is what you intended. && exit 2)
+-	for i in $(INSTALLED_PROGRAMS) ""; do test -z "$$i" || $(INSTALL) $$i $(INSTALL_BIN); done
++	@test -d $(DESTDIR)$(INSTALL_BIN) || (echo $(DESTDIR)$(INSTALL_BIN) does not exist.  Please mkdir -p $(DESTDIR)$(INSTALL_BIN) if this is what you intended. && exit 2)
++	for i in $(INSTALLED_PROGRAMS) ""; do test -z "$$i" || $(INSTALL) $$i $(DESTDIR)$(INSTALL_BIN); done
+ 
+ install: install_libs install_programs
+ 
+ uninstall_libs:
+-	for i in $(LIBS) ""; do test -z "$$i" || $(RM) $(INSTALL_LIB)/$$i; done
++	for i in $(LIBS) ""; do test -z "$$i" || $(RM) $(DESTDIR)$(INSTALL_LIB)/$$i; done
+ 
+ uninstall_programs:
+-	for i in $(PROGRAMS) ""; do test -z "$$i" || $(RM) $(INSTALL_BIN)/$$i; done
++	for i in $(PROGRAMS) ""; do test -z "$$i" || $(RM) $(DESTDIR)$(INSTALL_BIN)/$$i; done
+ 
+ uninstall: uninstall_libs uninstall_programs
+ 
+diff --git javasrc/Makefile javasrc/Makefile
+index c5b8444..d2237b6 100644
+--- javasrc/Makefile
++++ javasrc/Makefile
+@@ -12,6 +12,8 @@
+ # FOR A PARTICULAR PURPOSE.
+ #
+ 
++include ../csrc/conf.mk
++
+ ANT = `command -v ant || echo echo SKIPPING ant`
+ JAR = ccn.jar
+ LIBS = $(JAR) lib/bcprov-jdk16-143.jar lib/kxml2-2.3.0.jar $(EXTRA_LIBS)
+@@ -23,20 +25,15 @@ WARN_NO_INSTALL = echo Nothing installed from javasrc/
+ # Default, the top-level Makefile default target will
+ # call the install target here but override INSTALL_BASE
+ # with dir in the source tree
+-INSTALL_LIB = $(INSTALL_BASE)/lib
+-INSTALL_BIN = $(INSTALL_BASE)/bin
+-INSTALL = cp 
+-CP = cp
+-LS = /bin/ls
+ 
+ default all: jar
+ check: test
+ 
+ install:
+ 	@test -f $(JAR) && $(MAKE) real_install \
+-            INSTALL_BASE=$(INSTALL_BASE)        \
+-            INSTALL_LIB=$(INSTALL_LIB)          \
+-            INSTALL_BIN=$(INSTALL_BIN) || $(WARN_NO_INSTALL)
++            INSTALL_BASE=$(DESTDIR)$(INSTALL_BASE)        \
++            INSTALL_LIB=$(DESTDIR)$(INSTALL_LIB)          \
++            INSTALL_BIN=$(DESTDIR)$(INSTALL_BIN) || $(WARN_NO_INSTALL)
+ 
+ real_install: _always
+ 	test -d $(INSTALL_LIB) 
+@@ -46,8 +43,8 @@ real_install: _always
+ 	$(CP) -R tools/. $(INSTALL_BIN)
+ 
+ uninstall:
+-	for i in $(LIBS) ""; do test -z "$$i" || rm -f $(INSTALL_LIB)/`basename $$i`; done
+-	for i in `$(LS) tools` "" ; do test -z "$$i" || rm -f $(INSTALL_BIN)/`basename $$i`; done
++	for i in $(LIBS) ""; do test -z "$$i" || rm -f $(DESTDIR)$(INSTALL_LIB)/`basename $$i`; done
++	for i in `$(LS) tools` "" ; do test -z "$$i" || rm -f $(DESTDIR)$(INSTALL_BIN)/`basename $$i`; done
+ 
+ # Use ant to actually do the work for these targets
+ jar test: _always