OSDN Git Service

aix feeadback
authorSeiji Munetoh <munetoh@jp.ibm.com>
Fri, 9 Dec 2011 23:30:09 +0000 (08:30 +0900)
committerSeiji Munetoh <munetoh@jp.ibm.com>
Fri, 9 Dec 2011 23:30:09 +0000 (08:30 +0900)
50 files changed:
ChangeLog
README
configure.in
dist/debian/rules
dist/openpts.spec.in
include/openpts.h
include/openpts_fsm.h
include/openpts_ifm.h
src/Makefile.am
src/action.c
src/aide.c
src/base64.c
src/collector.c
src/conf.c
src/ctx.c
src/fsm.c
src/ifm.c
src/imc.c
src/iml.c
src/iml2aide.c
src/iml2text.c
src/imv.c
src/ir.c
src/ir2text.c
src/log.c
src/misc.c
src/nonce.c
src/openpts.c
src/policy.c
src/prop.c
src/ptsc.c
src/reason.c
src/rm.c
src/rm2dot.c
src/smbios.c
src/snapshot.c
src/ssh.c
src/target.c
src/tboot2iml.c
src/tpm.c
src/tpm_createkey.c
src/tpm_extendpcr.c
src/tpm_readpcr.c
src/tss.c
src/uml.c
src/uml2dot.c
src/uuid.c
src/uuid_libc.c
src/uuid_libuuid.c
src/verifier.c

index a785a87..48ccc12 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,16 @@
+openpts (0.2.6) unstable; urgency=low
+
+  * Update src/base64.c
+  * Wrap malloc/free by xmallox/xfree to keep away free(NULL)
+  * Added NLS() macro for i18n, (catgets or gettext)
+  * Added support of "transparent" digest.
+  * Locking to ensure only one instance of ptsc and openpts will run at the same time.
+  * Added the doorbell ringer(ptsevt) and the listener (ptsevtd)
+  * Added clear option. e.g. ptsc -e
+  * Improved error handling and messages
+
+ -- Seiji Munetoh <munetoh@users.sourceforge.jp>  Fri, 7 Oct 2011 12:00:00 +0900
+
 openpts (0.2.5) unstable; urgency=low
 
   * scan by coverity
diff --git a/README b/README
index 00a950d..335dd8c 100644 (file)
--- a/README
+++ b/README
  BUILDING openpts
  -------- ----------------
  $ sh ./bootstrap.sh
- $ ./configure --with-tss --with-aide --enable-tnc --prefix=/usr
+
+ 32-bit
+ $ ./configure --with-tss --with-aru --enable-tnc --prefix=/usr
+
+ 64-bit
+ $ ./configure --with-tss --with-aru --enable-tnc --prefix=/usr --libdir=/usr/lib64
+
  $ make
  # make install
 
@@ -64,6 +70,7 @@
  --with-tboot     build with tboot support
 
 
+
  BUILDING a OPENPTS RPM
  -------- - ------- ---
 
index 33952d4..c5b8af4 100644 (file)
 
 AC_INIT(openpts, 0.2.6, openpts-users@lists.sourceforge.jp)
 
-# use pkg-config
-# check /usr/lib64/pkgconfig/
-PKG_PROG_PKG_CONFIG
-
 PTS_SPEC_MAJOR=0
 PTS_SPEC_MINOR=0
 PTS_VER_MAJOR=2
-PTS_VER_MINOR=5
+PTS_VER_MINOR=6
+
+# set PCR index used by OpenPTS
 OPENPTS_PCR_INDEX=11
 
+# use pkg-config
+# check /usr/lib64/pkgconfig/
+PKG_PROG_PKG_CONFIG
+
 AC_CONFIG_AUX_DIR([.])
 
 AC_CONFIG_MACRO_DIR([m4])
index 9f2dd8a..ad9a19d 100755 (executable)
@@ -20,7 +20,7 @@ configure-stamp:
 
 build: build-stamp
 
-build-stamp: configure-stamp  
+build-stamp: configure-stamp
        dh_testdir
 
        # Add here commands to compile the package.
@@ -36,12 +36,12 @@ clean:
 
        $(MAKE) clean
 
-       dh_clean 
+       dh_clean
 
 install: build
        dh_testdir
        dh_testroot
-       dh_clean -k 
+       dh_clean -k
        dh_installdirs
 
        $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install
index e99d766..22e0518 100644 (file)
@@ -6,7 +6,7 @@
 Name:           %{name}
 Version:        %{version}
 Release:        %{release}
-Summary:        TCG Platform Trust Service (PTS) for emdedded devices
+Summary:        TCG Platform Trust Service (PTS)
 
 Group:          Applications/System
 License:        CPL
@@ -39,7 +39,7 @@ specifications set forth by the Trusted Computing Group (TCG).
 
 %build
 
-%configure --disable-static --prefix=/usr --libdir=%{_libdir} --with-tss --with-aide --enable-tnc \
+%configure --disable-static --prefix=/usr --libdir=%{_libdir} --with-tss --enable-tnc \
 %if %{with_tboot}
   --with-tboot \
 %endif
@@ -127,15 +127,15 @@ getent group ptsc >/dev/null || groupadd -r ptsc
 
 %post -p /sbin/ldconfig
 
-
 %postun -p /sbin/ldconfig
 
 %changelog
+* Fri Oct  7 2011 Seiji Munetoh <munetoh@users.sourceforge.jp> - 0.2.6
 * Fri Jun 24 2011 Seiji Munetoh <munetoh@users.sourceforge.jp> - 0.2.5
 - added TNC IMV/IMC, configure --enable-tnc
 - added libopenpts.so
 
-* Fri May 6 2011 Seiji Munetoh <munetoh@users.sourceforge.jp> - 0.2.4
+* Fri May  6 2011 Seiji Munetoh <munetoh@users.sourceforge.jp> - 0.2.4
 * Thu Mar 10 2011 Seiji Munetoh <munetoh@users.sourceforge.jp> - 0.2.3
 * Sun Jul 25 2010 Seiji Munetoh <munetoh@users.sourceforge.jp> - 0.2.0
 * Fri Mar 12 2010 Seiji Munetoh <munetoh@users.sourceforge.jp> - 0.0.1
index 8018e85..1de7ba0 100644 (file)
@@ -53,6 +53,8 @@
 /* TCG IWG IF-PTS definitions */
 #include <iwgifpts.h>
 
+#include <openpts_log.h>
+
 #include <openpts_ifm.h>
 #include <openpts_fsm.h>
 #include <openpts_tpm.h>
 #include <openpts_tboot.h>
 #endif
 
-// TODO
-#ifdef AIX
-#define PPC
-#endif
-
-/* NLS */
-#ifdef ENABLE_NLS
-#ifdef HAVE_CATGETS
-#include <nl_types.h>
-extern nl_catd catd;
-#define NLS(a, b, x) catgets(catd, a, b, x)
-#else  // !HAVE_CATGETS
-#include <locale.h>
-#include <libintl.h>
-#define NLS(a, b, x) gettext(x)
-// #define N_(x) gettext_noop(x)
-// #define gettext_noop(x) (x)
-#endif  // HAVE_CATGETS
-#else  // !ENABLE_NLS
-#ifdef NLS
-#undef NLS
-#endif
-#define NLS(a, b, x) x
-#endif  // ENABLE_NLS
-
-
-
-/* OpenPTS default configulations  */
 
+/* OpenPTS default configurations  */
+// port NUM
+//   http://www.iana.org/assignments/port-numbers
+//   http://www.iana.org/cgi-bin/usr-port-number.pl
+//   User ports [1024:49151]
+//     6674-6686  Unassigned
+// TODO 5556 is comfrict with Freeciv, => 6678
+// note) The port is local. for the remote access, we use SSH tunnel (port 22)
 #define PTSC_CONFIG_FILE  "/etc/ptsc.conf"
 #define PTSV_CONFIG_FILE  "/etc/ptsv.conf"
 
 #define PTSC_GROUP_NAME    "ptsc"
-#define PTSC_IFM_TIMEOUT   5
-#define PTSC_IFM_TIMEOUT_MAX   30
 
 #define MAXDATA 1024
 
@@ -149,12 +129,23 @@ extern nl_catd catd;
 #define OPENPTS_SELFTEST_RENEWED   301
 #define OPENPTS_SELFTEST_FALLBACK  302
 #define OPENPTS_SELFTEST_FAILED    303
+#define OPENPTS_FILE_EXISTS        311
+#define OPENPTS_FILE_MISSING       312
+#define OPENPTS_DIR_EXISTS         313
+#define OPENPTS_DIR_MISSING        314
+#define OPENPTS_IML_MISSING        315
 
 // IMV
 #define IMV_ENROLLMENT_NONE          0
 #define IMV_ENROLLMENT_CREDENTIAL    1
 #define IMV_ENROLLMENT_AUTO          2
 
+// malloc should never really fail
+// #define ALWAYS_ASSERT_ON_BAD_ALLOC
+// Undefined this for daemons
+// #define NEVER_FREE_MEMORY
+
+#define isFlagSet(bits, flagToTest) (flagToTest == ((bits) & (flagToTest)))
 
 /* structures */
 
@@ -432,6 +423,29 @@ typedef struct {
     int status;
 } OPENPTS_UUID;
 
+/* information about the components described by the models */
+typedef struct {
+    char *SimpleName;
+    char *ModelName;
+    char *ModelNumber;
+    char *ModelSerialNumber;
+    char *ModelSystemClass;
+    char *VersionMajor;
+    char *VersionMinor;
+    char *VersionBuild;
+    char *VersionString;
+    char *MfgDate;
+    char *PatchLevel;
+    char *DiscretePatches;
+    char *VendorID_Name;
+    enum {
+        VENDORID_TYPE_TCG,
+        VENDORID_TYPE_SMI,
+        VENDORID_TYPE_GUID,
+    } VendorID_type;
+    char *VendorID_Value;
+} OPENPTS_COMPID;
+
 /**
  * Config
  */
@@ -455,7 +469,6 @@ typedef struct {
     OPENPTS_UUID * tmp_uuid;     /**< Platform(collector) UUID - changed */
     OPENPTS_UUID * tmp_rm_uuid;  /**< RM(now) UUID - changed */
 
-
     /* Daemon UUID */
     PTS_UUID     *daemon_uuid;
     char         *str_daemon_uuid;
@@ -494,10 +507,13 @@ typedef struct {
     int iml_endian;                /**< 0: same, 2:conv */
     int iml_aligned;               /**< 0: byte, 4: 4-byte aligned */
 
-    /* FSM models (Linux) */
+    /* FSM models */
     char *model_dir; /**< */
-    char *platform_model_filename[MAX_PCRNUM]; /**< */  // BIOS
-    char *runtime_model_filename[MAX_PCRNUM];  /**< */  // IPL/VMM/OS
+    char *model_filename[MAX_RM_NUM][MAX_PCRNUM];
+    int iml_maxcount;
+
+    /* Component ID */
+    OPENPTS_COMPID compIDs[MAX_RM_NUM];
 
     /* verifier setting */
     char *verifier_logging_dir;
@@ -530,17 +546,17 @@ typedef struct {
     char *hostname;
     char *ssh_username;
     char *ssh_port;
-    int   ifm_timeout;
 
     /* IF-M verifier(IMV) */
     int enrollment;
 
 #ifdef CONFIG_AUTO_RM_UPDATE
-    int enable_aru;            /**> Enable update scan */
-    int update_exist;          /**> Update exist, used by collector */
-    int newrm_exist;           /**> NewRM exist, used by verifier */
-    PTS_UUID *aru_newrm_uuid;  /**> NewRM UUID */
-    void *update;              /**> Hold update*/
+    int enable_aru;              /**> Enable update scan */
+    int update_exist;            /**> Update exist, used by collector */
+    int target_newrm_exist;      /**> NewRM exist, used by verifier */
+    PTS_UUID *target_newrm_uuid; /**> NewRM UUID */
+    void *update;                /**> Hold update*/
+    BYTE *newRmSet;
 #endif
 
     /* misc */
@@ -553,6 +569,7 @@ typedef struct {
  */
 typedef struct {
     int num;       /**< */
+    int pcr;
     char *message; /**< */
     void * next;   /**< */
 } OPENPTS_REASON;
@@ -610,6 +627,7 @@ typedef struct {
 
     /* Integrity Report */
     OPENPTS_IR_CONTEXT *ir_ctx;
+    char *ir_filename;
 
 
 
@@ -624,6 +642,8 @@ typedef struct {
     int  ima_unknown;
     int  ima_ignore;  // they are included in the valid count
 
+    /* Component ID */
+    OPENPTS_COMPID compIDs[MAX_RM_NUM];
 
     /* IF-M */
     BYTE *read_msg;
@@ -786,11 +806,10 @@ int makeNewRmSetDir(OPENPTS_CONFIG *conf);
 /* ir.c */
 OPENPTS_IR_CONTEXT *newIrContext();
 void freeIrContext(OPENPTS_IR_CONTEXT *ctx);
-// TODO remove file
-int writeIr(OPENPTS_CONTEXT *ctx, const char *file);
-// int writeIr(OPENPTS_CONTEXT *ctx);
-int validateIr(OPENPTS_CONTEXT *ctx, const char *file);
-int genIr(OPENPTS_CONTEXT *ctx);
+int writeIr(OPENPTS_CONTEXT *ctx, const char *filename, int *savedFd);
+// int validateIr(OPENPTS_CONTEXT *ctx, const char *file);
+int validateIr(OPENPTS_CONTEXT *ctx);
+int genIr(OPENPTS_CONTEXT *ctx, int *savedFd);
 
 /* action.c */
 int doActivity(
@@ -823,10 +842,11 @@ int saveProperties(OPENPTS_CONTEXT *ctx, char * filename);
 void printProperties(OPENPTS_CONTEXT *ctx);
 int validateProperty(
     OPENPTS_CONTEXT *ctx, char *name, char *value, char *action);
+int addPropertiesFromConfig(OPENPTS_CONFIG *conf, OPENPTS_CONTEXT *ctx);
 
 /* reason.c */
-int addReason(OPENPTS_CONTEXT *ctx, const char *format, ...);
-void printReason(OPENPTS_CONTEXT *ctx);
+int addReason(OPENPTS_CONTEXT *ctx, int pcr, const char *format, ...);
+void printReason(OPENPTS_CONTEXT *ctx, int print_pcr_hints);
 
 
 /* log.c */
@@ -869,27 +889,36 @@ int genSmbiosFileByDmidecode(char * filename);
 int parseSmbios(OPENPTS_CONTEXT *ctx, BYTE *data, int length);
 
 /* misc.c */
-char * smalloc(char *str);
-char * snmalloc(char *str, int len);
-BYTE * snmalloc2(BYTE * buf, int offset, int len);
-void sfree(char *str);
+void *xmalloc_assert(size_t len);
+char *smalloc_assert(char *str);
+#ifdef ALWAYS_ASSERT_ON_BAD_ALLOC
+#define xmalloc(len) xmalloc_assert(len)
+#define smalloc(str) smalloc_assert(str)
+#else
+void *xmalloc(size_t len);
+char *smalloc(char *str);
+#endif
+char *snmalloc(char *str, int len);
+BYTE *snmalloc2(BYTE * buf, int offset, int len);
+void xfree(void *ptr);
 UINT32 byte2uint32(BYTE *b);
 char * trim(char *str);
 char *getHexString(BYTE *bin, int size);
 void printHex(char *head, BYTE *data, int num, char *tail);
+void fprintHex(FILE *fp, BYTE *data, int num);
 UINT32 b2l(UINT32 in);
+void debugHex(char *head, BYTE *data, int num, char *tail);
 
 int saveToFile(char * filename, int len, BYTE * msg);
 int getUint32(BYTE *buf);
 int makeDir(char *dirname);
 int checkDir(char *dirname);
+int checkFile(char *filename);
 ssize_t wrapRead(int fd, void *buf, size_t count);
 ssize_t wrapWrite(int fd, const void *buf, size_t count);
 char *getFullpathName(char *base_path, char *filename);
 char *getFullpathDir(char *filename);
-
-/* log.c */
-void writeLog(int priority, const char *format, ...);
+int unlinkDir(const char *dirPath);
 
 /* uuid.c */
 PTS_UUID *newUuid();
@@ -898,6 +927,8 @@ char * getStringOfUuid(PTS_UUID *uuid);
 PTS_UUID *getUuidFromString(char *str);
 PTS_DateTime * getDateTimeOfUuid(PTS_UUID *uuid);
 PTS_DateTime * getDateTime();
+int writeUuidFile(char *str_uuid, char *filename, int overwrite);
+int readUuidFile(char *filename, char **str_uuid, PTS_UUID **uuid);
 int getRmList(OPENPTS_CONFIG *conf, char * config_dir);
 int purgeRenewedRm(OPENPTS_CONFIG *conf);
 void printRmList(OPENPTS_CONFIG *conf, char *indent);
@@ -905,6 +936,7 @@ int getTargetList(OPENPTS_CONFIG *conf, char * config_dir);
 void printTargetList(OPENPTS_CONFIG *conf, char *indent);
 char *getTargetConfDir(OPENPTS_CONFIG *conf);
 OPENPTS_TARGET *getTargetCollector(OPENPTS_CONFIG *conf);
+OPENPTS_TARGET *getTargetCollectorByUUID(OPENPTS_CONFIG *conf, const char *uuid);
 /* OPENPTS_UUID */
 OPENPTS_UUID *newOpenptsUuid();
 OPENPTS_UUID *newOpenptsUuid2(PTS_UUID *pts_uuid);
@@ -919,7 +951,7 @@ int init(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OPE
 int printCollectorStatus(OPENPTS_CONFIG *conf);
 int selftest(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OPENPTS_PROPERTY *prop_end);
 int newrm(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OPENPTS_PROPERTY *prop_end);
-
+int clear(OPENPTS_CONFIG *conf, int force);
 
 #ifdef CONFIG_AUTO_RM_UPDATE
 #include "./openpts_aru.h"
@@ -928,92 +960,4 @@ int newrm(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OP
 /* ssh.c */
 pid_t ssh_connect(char *host, char *ssh_username, char *ssh_port, char *key_file, int *socket);
 
-/* print controll */
-
-#define logDebug(fmt, ...) \
-syslog(LOG_NOTICE, "%s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-#define logInfo(fmt, ...)  \
-syslog(LOG_INFO, fmt, ##__VA_ARGS__)
-#define logError(fmt, ...) \
-syslog(LOG_ERR, "%s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-
-/* main.c and check_*.c */
-extern int verbose;
-
-#define DEBUG_FLAG     0x01
-#define DEBUG_FSM_FLAG 0x02
-#define DEBUG_XML_FLAG 0x04
-#define DEBUG_IFM_FLAG 0x08
-#define DEBUG_SAX_FLAG 0x10
-#define DEBUG_TPM_FLAG 0x20
-#define DEBUG_CAL_FLAG 0x40
-
-#if 0
-#define ERROR(fmt, ...) \
-fprintf(stderr, "ERROR     %s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define TODO(fmt, ...) \
-fprintf(stderr, "TODO      %s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define INFO(fmt, ...) \
-fprintf(stderr, "INFO      %s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)v
-
-#define DEBUG(fmt, ...) if (verbose & DEBUG_FLAG) \
-fprintf(stdout, "DEBUG     %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_FSM(fmt, ...) if (verbose & DEBUG_FSM_FLAG) \
-fprintf(stdout, "DEBUG_FSM %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_XML(fmt, ...) if (verbose & DEBUG_XML_FLAG) \
-fprintf(stdout, "DEBUG_XML %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_IFM(fmt, ...) if (verbose & DEBUG_IFM_FLAG) \
-fprintf(stdout, "DEBUG_IFM %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_SAX(fmt, ...) if (verbose & DEBUG_SAX_FLAG) \
-fprintf(stdout, "DEBUG_SAX %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_TPM(fmt, ...) if (verbose & DEBUG_TPM_FLAG) \
-fprintf(stdout, "DEBUG_TPM %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_CAL(fmt, ...) if (verbose & DEBUG_CAL_FLAG) \
-fprintf(stdout, "DEBUG_TPM %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#else
-
-// #include <syslog.h>
-
-#define ERROR(fmt, ...) \
-writeLog(LOG_ERR, "%s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define TODO(fmt, ...) \
-writeLog(LOG_INFO, "(TODO) %s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define INFO(fmt, ...) \
-writeLog(LOG_INFO, fmt, ##__VA_ARGS__)
-// writeLog(LOG_INFO, "%s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG(fmt, ...) if (verbose & DEBUG_FLAG) \
-writeLog(LOG_DEBUG, "DEBUG     %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_FSM(fmt, ...) if (verbose & DEBUG_FSM_FLAG) \
-writeLog(LOG_DEBUG, "DEBUG_FSM %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_XML(fmt, ...) if (verbose & DEBUG_XML_FLAG) \
-writeLog(LOG_DEBUG, "DEBUG_XML %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_IFM(fmt, ...) if (verbose & DEBUG_IFM_FLAG) \
-writeLog(LOG_DEBUG, "DEBUG_IFM %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_SAX(fmt, ...) if (verbose & DEBUG_SAX_FLAG) \
-writeLog(LOG_DEBUG, "DEBUG_SAX %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_TPM(fmt, ...) if (verbose & DEBUG_TPM_FLAG) \
-writeLog(LOG_DEBUG, "DEBUG_TPM %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG_CAL(fmt, ...) if (verbose & DEBUG_CAL_FLAG) \
-writeLog(LOG_DEBUG, "DEBUG_CAL %s:%4d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-#endif
-
 #endif  // INCLUDE_OPENPTS_H_
index 6f40777..6259c14 100644 (file)
 #define EVENTTYPE_FLAG_NOT_EQUAL 2  // !=
 
 /* digest flag */
-#define DIGEST_FLAG_SKIP      0
-#define DIGEST_FLAG_EQUAL     1  // BIN-FSM
-#define DIGEST_FLAG_IGNORE    2  // BHV-FSM
+#define DIGEST_FLAG_SKIP        0
+#define DIGEST_FLAG_EQUAL       1  // BIN-FSM
+#define DIGEST_FLAG_IGNORE      2  // BHV-FSM
+#define DIGEST_FLAG_TRANSPARENT 3
 
 /* Counter flag */
 #define COUNTER_FLAG_SKIP   0
@@ -121,6 +122,10 @@ typedef struct {
     int counter_flag; /**< */
     char *counter_name;   /**< */
 
+    /* counter */
+    int fatal_counter_flag; /**< */
+    char *fatal_counter_name;   /**< */
+
     /* last */
     int last_flag; /**< */
 
@@ -159,6 +164,7 @@ typedef struct {
     int status; /**< FSM status */
     int pcr_index;
     int level;
+    int numTransparencies;
 
     char * uml_file;
 
@@ -188,6 +194,7 @@ typedef struct {
     int event_type;
     int push_count;
     int index; /**< index */
+    int transparent;
 
 #ifdef CONFIG_AIDE
     /* AIDE */
@@ -239,7 +246,7 @@ char * getSubvertexId(OPENPTS_FSM_CONTEXT *ctx, char * name);
 OPENPTS_FSM_CONTEXT *copyFsm(OPENPTS_FSM_CONTEXT *src_fsm);
 int getTypeFlag(char * cond, UINT32 *eventtype);
 int getDigestFlag(char * cond, BYTE **digest, int *digest_size);
-int getCounterFlag(char * cond, char **name);
+int getCounterFlag(char *cond, char *name, char **flag);
 int getLastFlag(char * cond);
 int addFsmTransition(
     OPENPTS_FSM_CONTEXT *ctx,
index 8fa872f..8046583 100644 (file)
@@ -70,6 +70,7 @@ typedef struct {
 #define TNC_VENDORID_TNCFHH     0x0080AB  // 32939  Fachhochschule Hannover
 #define TNC_VENDORID_OSC        0x002358  //  9048  Open System Consultants (libtnc)
 #define TNC_VENDORID_OPENPTS    0x00950E  // 38158  OpenPTS
+#define TNC_VENDORID_PA_TNC     0x000000  //     0  RFC5792
 
 #define TNC_SUBTYPE_TCG_PTS 0x01
 
@@ -197,12 +198,13 @@ typedef struct {
 
 /* OPENPTS_CAPABILITIES */
 typedef struct {
-        BYTE        flag[4];        // 4
-        TPM_VERSION tpm_version;    // 4
-        TSS_VERSION tss_version;    // 4
-        TSS_VERSION pts_version;    // 4 set by configure.in
-        PTS_UUID    platform_uuid;  // 16
-        PTS_UUID    manifest_uuid;  // 16
+        BYTE        flag[4];            // 4
+        TPM_VERSION tpm_version;        // 4
+        TSS_VERSION tss_version;        // 4
+        TSS_VERSION pts_version;        // 4 set by configure.in
+        PTS_UUID    platform_uuid;      // 16
+        PTS_UUID    manifest_uuid;      // 16
+        PTS_UUID    new_manifest_uuid;  // 16
 } OPENPTS_IF_M_Capability;
 
 
index f90b3f0..fc357b9 100644 (file)
@@ -23,7 +23,7 @@
 # http://www.opensource.org/licenses/cpl1.0.php.
 #
 
-RELEASE = "0.0.2.5"
+RELEASE = "0.0.2.6"
 
 # Gettext support
 localedir = $(datadir)/locale
@@ -40,7 +40,7 @@ endif
 
 
 sbin_PROGRAMS = ptsc
-bin_PROGRAMS = openpts uml2dot rm2dot ir2text
+bin_PROGRAMS = openpts uml2dot rm2dot ir2text ptsevt ptsevtd
 
 #
 # Common Library
@@ -97,8 +97,13 @@ ir2text_SOURCES = ir2text.c
 
 #base64.c log.c
 
+ptsevt_CFLAGS = $(AM_CFLAGS)
+ptsevt_LDFLAGS = $(AM_LDFLAGS)
+ptsevt_SOURCES = ptsevt.c
 
-
+ptsevtd_CFLAGS = $(AM_CFLAGS)
+ptsevtd_LDFLAGS = $(AM_LDFLAGS) -lrt
+ptsevtd_SOURCES = ptsevtd.c
 
 
 if HAVE_LIBUUID
@@ -206,6 +211,7 @@ tboot2iml_SOURCES = tboot2iml.c
 endif
 
 
+
 if OPENPTS_BUILD_SQLITE
 AM_CPPFLAGS += -DCONFIG_SQLITE
 #LDADD += -lsqlite3
index e498c2c..9020799 100644 (file)
@@ -54,6 +54,7 @@
 #include <openssl/sha.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 typedef struct {
     char *name;
@@ -84,9 +85,7 @@ typedef struct {
  */
 int resetPCR(OPENPTS_CONTEXT *ctx, char *value) {
     int rc;
-    int pcr_index = -1;
-
-    pcr_index = atoi(value);
+    int pcr_index = atoi(value);
 
     DEBUG_FSM("resetPCR(%d)\n", pcr_index);
     rc = resetTpmPcr(&ctx->tpm, pcr_index);
@@ -134,7 +133,6 @@ int addBIOSAction(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrapper)
     /* value = eventdata */
     value = snmalloc((char *)event->rgbEvent, event->ulEventLength);
     if (value == NULL) {
-        ERROR("no memory\n");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -148,7 +146,7 @@ int addBIOSAction(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrapper)
 
     updateProperty(ctx, name, value);
 
-    free(value);
+    xfree(value);
 
     return PTS_SUCCESS;
 }
@@ -190,6 +188,17 @@ int addBIOSSpecificProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eve
     // DEBUG("event data size = %d\n", event->ulEventLength);
     // printHex("", event->rgbEvent, event->ulEventLength, "\n");
 
+    /* check EventData */
+    if (event->ulEventLength == 0) {
+        ERROR("addBIOSSpecificProperty - Bad IML, ulEventLength is 0.");
+        return PTS_FATAL;
+    }
+    if (&event->rgbEvent[0] == NULL) {
+        ERROR("addBIOSSpecificProperty - Bad IML, rgbEvent is NULL.");
+        return PTS_FATAL;
+    }
+
+
     event_id = byte2uint32(&event->rgbEvent[0]);
     event_length = byte2uint32(&event->rgbEvent[4]);
 
@@ -202,13 +211,11 @@ int addBIOSSpecificProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eve
                 int buf_len;
 
                 /* SMBIOS */
-                // bios.smbios=base64()
                 ctx->conf->smbios_length = event_length;
                 ctx->conf->smbios = &event->rgbEvent[8];
 
                 /* base64 */
                 buf = encodeBase64(
-                        //(unsigned char *)b64,
                         (unsigned char *)ctx->conf->smbios,
                         ctx->conf->smbios_length,
                         &buf_len);
@@ -223,7 +230,7 @@ int addBIOSSpecificProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eve
                     updateProperty(ctx, "bios.smbios", buf);
                 }
                 // rc = 0;
-                free(buf);
+                xfree(buf);
             }
             break;
         default:
@@ -337,18 +344,16 @@ int setModuleProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrap
         return PTS_INTERNAL_ERROR;
     }
     updateProperty(ctx, "kernel.initrd.digest", buf);
-    free(buf);
+    xfree(buf);
 
     // updateProperty(ctx, "kernel.initrd.filename", (char*)event->rgbEvent);
     /* add \n */
-    buf = malloc(event->ulEventLength + 1);
-    if (buf == NULL) {
-        ERROR("no memory\n");
-    } else {
+    buf = xmalloc(event->ulEventLength + 1);
+    if (buf != NULL) {
         memcpy(buf, event->rgbEvent, event->ulEventLength);
         buf[event->ulEventLength] = 0;
         updateProperty(ctx, "kernel.initrd.filename", buf);
-        free(buf);
+        xfree(buf);
     }
 
     return PTS_SUCCESS;  // -1;
@@ -428,7 +433,7 @@ int setLinuxKernelCmdlineAssertion(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPP
     // DEBUG("setLinuxKernelCmdlineAssertion  event data[%d] = %s\n", event->ulEventLength, event->rgbEvent);
 
     /* free */
-    sfree(cmdline);
+    xfree(cmdline);
     return PTS_SUCCESS;
 }
 
@@ -499,38 +504,38 @@ int validateImaAggregate(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventW
         /* MISS */
         updateProperty(ctx, "ima.aggregate", "invalid");
 
-        if (verbose && DEBUG_FLAG) {
+        if (isDebugFlagSet(DEBUG_FLAG)) {
             int j;
             BYTE pcr[SHA1_DIGEST_SIZE];
             TODO("validateImaAggregate - "
                  "Wrong IMA aggregete - check FSM, "
                  "maybe it should use validateOldImaAggregate()\n");
-            printf("PCR   =  ");
+            OUTPUT("PCR   =  ");
             for (j = 0; j < (int) event->ulPcrValueLength; j ++) {
-                printf("%02x", event->rgbPcrValue[j]);
+                OUTPUT("%02x", event->rgbPcrValue[j]);
             }
-            printf("\n");
+            OUTPUT("\n");
 
             for (i = 0; i < 8; i++) {
-                printf("PCR[%d] = ", i);
+                OUTPUT("PCR[%d] = ", i);
                 getTpmPcrValue(&ctx->tpm, i, pcr);
                 for (j = 0; j < SHA1_DIGEST_SIZE; j ++) {
-                    printf("%02x", pcr[j]);
+                    OUTPUT("%02x", pcr[j]);
                 }
-                printf("\n");
+                OUTPUT("\n");
             }
 
-            printf("EDATA  = ");
+            OUTPUT("EDATA  = ");
             for (j = 0; j < SHA1_DIGEST_SIZE; j ++) {
-                printf("%02x", event->rgbEvent[j]);
+                OUTPUT("%02x", event->rgbEvent[j]);
             }
-            printf(" (extended value)\n");
+            OUTPUT(" (extended value)\n");
 
-            printf("AGGREG = ");
+            OUTPUT("AGGREG = ");
             for (j = 0; j < SHA1_DIGEST_SIZE; j ++) {
-                printf("%02x", digest[j]);
+                OUTPUT("%02x", digest[j]);
             }
-            printf(" (cal value)\n");
+            OUTPUT(" (cal value)\n");
         }
     }
 
@@ -683,15 +688,15 @@ int validateImaMeasurement(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *even
                 return PTS_INTERNAL_ERROR;
             }
             updateImaProperty(ctx, md->name, buf, "valid");
-            free(buf);
+            xfree(buf);
 #endif
             eventWrapper->status = OPENPTS_RESULT_VALID;
-            free(name);
+            xfree(name);
             return PTS_SUCCESS;
         } else if (rc == 1) {
             // IGNORE
             eventWrapper->status = OPENPTS_RESULT_IGNORE;  // TODO
-            free(name);
+            xfree(name);
             return PTS_SUCCESS;
         } else if (rc == 2) {
             // MISS
@@ -708,27 +713,27 @@ int validateImaMeasurement(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *even
             }
             updateImaProperty(ctx, name, buf, "unknown");  // action.c
             eventWrapper->status = OPENPTS_RESULT_UNKNOWN;
-            free(buf);
+            xfree(buf);
 
             /* add to */
             {
                 char *hex;
                 hex = getHexString(event->rgbEvent, SHA1_DIGEST_SIZE);
-                addReason(ctx, "[IMA-AIDE] missing, digest(hex) = %s, name = \"%s\"", hex, name);
-                free(hex);
+                addReason(ctx, -1, "[IMA-AIDE] missing, digest(hex) = %s, name = \"%s\"", hex, name);
+                xfree(hex);
             }
-            free(name);
+            xfree(name);
             return PTS_SUCCESS;
         } else {
             // ERROR
             ERROR("validateImaMeasurement - checkEventByAide fail, rc - %d\n", rc);
             eventWrapper->status = PTS_INTERNAL_ERROR;  // OPENPTS_RESULT_INT_ERROR;
-            free(name);
+            xfree(name);
             return PTS_INTERNAL_ERROR;  // -1;
         }
         // TODO free md
         // freeAideMetadata(md);
-        // free(name);
+        // xfree(name);
     } else if (ctx->conf->ima_validation_mode == OPENPTS_VALIDATION_MODE_IIDB) {
         ERROR("validateImaMeasurementNG w/ IIDB - NA\n");
     }
@@ -793,20 +798,18 @@ int startCollector(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrapper
     TSS_PCR_EVENT *event;
     OPENPTS_EVENT_COLLECTOR_START *start = NULL;
 
-    /* check */
-    if (ctx == NULL) {
-        ERROR("startCollector() - ctx is null\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != ctx, "startCollector() - ctx is null\n");
 
     if (ctx->target_conf == NULL) {
         /* collector */
-        ERROR("startCollector() - target_conf is NULL, collector side - skip\n");
+        /* If this is an ERROR should we be returning SUCCESS?? */
+        ERROR("startCollector() - collector side - skip\n");
         return PTS_SUCCESS;
     }
 
     if (ctx->target_conf->uuid == NULL) {
         /* collector */
+        /* If this is an ERROR should we be returning SUCCESS?? */
         ERROR("startCollector() - uuid is NULL\n");
         return PTS_SUCCESS;
     }
@@ -892,7 +895,7 @@ int startCollector(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrapper
             goto free;
         }
         ERROR("EventData: %s\n", buf);
-        free(buf);
+        xfree(buf);
 
         memcpy(&start->pts_version, &ctx->target_conf->pts_version, 4);
         memcpy(&start->collector_uuid, ctx->target_conf->uuid->uuid, 16);
@@ -910,9 +913,9 @@ int startCollector(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrapper
             goto free;
         }
         ERROR("EventData: %s\n", buf);
-        free(buf);
+        xfree(buf);
   free:
-        free(start);
+        xfree(start);
     }
 
     return rc;  // TODO
@@ -940,7 +943,7 @@ int addIntelTxtTbootProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *ev
                 data = (OPENPTS_EVENT_TBOOT_SINIT_V6 *) event->rgbEvent;
                 buf = getHexString(data->sinit_hash, 20);
                 updateProperty(ctx, "intel.txt.tboot.sinit.hash.hex", buf);
-                free(buf);
+                xfree(buf);
                 // TODO add rest
             }
             break;
@@ -951,7 +954,7 @@ int addIntelTxtTbootProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *ev
                 data = (OPENPTS_EVENT_TBOOT_SINIT_V7 *) event->rgbEvent;
                 buf = getHexString(data->sinit_hash, 32);
                 updateProperty(ctx, "intel.txt.tboot.sinit.hash.hex", buf);
-                free(buf);
+                xfree(buf);
                 // TODO add rest
             }
             break;
@@ -962,7 +965,7 @@ int addIntelTxtTbootProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *ev
                 data = (OPENPTS_EVENT_TBOOT_STM_V6 *) event->rgbEvent;
                 buf = getHexString(data->bios_acm_id, 20);
                 updateProperty(ctx, "intel.txt.tboot.bios.acm.id.hex", buf);
-                free(buf);
+                xfree(buf);
                 // TODO add rest
             }
             break;
@@ -973,10 +976,10 @@ int addIntelTxtTbootProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *ev
                 data = (OPENPTS_EVENT_TBOOT_POLCTL *) event->rgbEvent;
                 buf = getHexString(data->pol_control, 4);
                 updateProperty(ctx, "intel.txt.tboot.pol.control.hex", buf);
-                free(buf);
+                xfree(buf);
                 buf = getHexString(data->pol_hash, 20);
                 updateProperty(ctx, "intel.txt.tboot.pol.hash.hex", buf);
-                free(buf);
+                xfree(buf);
                 // TODO add rest
             }
             break;
@@ -985,7 +988,7 @@ int addIntelTxtTbootProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *ev
                 char *buf;
                 buf = getHexString(event->rgbPcrValue, 20);
                 updateProperty(ctx, "intel.txt.tboot.mle.hash.hex", buf);
-                free(buf);
+                xfree(buf);
             }
             break;
 
@@ -1010,14 +1013,14 @@ int addIntelTxtTbootProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *ev
                         event->ulPcrIndex);
                     value = getHexString(data->command_hash, 20);
                     updateProperty(ctx, name, value);
-                    free(value);
+                    xfree(value);
 
                     snprintf(name, sizeof(name),
                         "intel.txt.tboot.pcr.%d.module.file.hash.hex",
                         event->ulPcrIndex);
                     value = getHexString(data->file_hash, 20);
                     updateProperty(ctx, name, value);
-                    free(value);
+                    xfree(value);
 
                     snprintf(name, sizeof(name),
                         "intel.txt.tboot.pcr.%d.module.command",
@@ -1025,11 +1028,11 @@ int addIntelTxtTbootProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *ev
                     ptr = (BYTE *)&event->rgbEvent[40];
                     size = *(UINT32*) ptr;
                     ptr += 4;
-                    value = malloc(size + 1);
+                    value = xmalloc_assert(size + 1);
                     memcpy(value, (BYTE *)ptr, size);
                     value[size] = 0;
                     updateProperty(ctx, name, value);
-                    free(value);
+                    xfree(value);
 
                     snprintf(name, sizeof(name),
                         "intel.txt.tboot.pcr.%d.module.filename",
@@ -1037,11 +1040,11 @@ int addIntelTxtTbootProperty(OPENPTS_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *ev
                     ptr += size;
                     size = *(UINT32*) ptr;
                     ptr += 4;
-                    value = malloc(size + 1);
+                    value = xmalloc_assert(size + 1);
                     memcpy(value, (BYTE *)ptr, size);
                     value[size] = 0;
                     updateProperty(ctx, name, value);
-                    free(value);
+                    xfree(value);
                 }
             }
             break;
@@ -1262,15 +1265,8 @@ int doActivity(
     int i;
 
     /* check */
-    if (ctx == NULL) {
-        ERROR("doActivity - ctx is NULL\n");
-        return PTS_INTERNAL_ERROR;  // -1;
-    }
-
-    if (action == NULL) {
-        ERROR("doActivity - action is NULL\n");
-        return PTS_INTERNAL_ERROR;  // -1;
-    }
+    ASSERT(NULL != ctx, "doActivity - ctx is NULL\n");
+    ASSERT(NULL != action, "doActivity - action is NULL\n");
 
     if (eventWrapper == NULL) {
         /* NULL event, skip evaluation */
@@ -1281,7 +1277,6 @@ int doActivity(
     /* copy */
     buf = smalloc(action);
     if (buf == NULL) {
-        ERROR("doActivity - no memory\n");
         return PTS_FATAL;  // -1;
     }
 
@@ -1354,11 +1349,11 @@ int doActivity(
 
     /* error */
     ERROR("unknown action '%s'\n", action);
-    addReason(ctx, "[FSM] Unknown action='%s'", action);
+    addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_ACTION_UNKNOWN, "[FSM] Unknown action='%s'"), action);
     rc = OPENPTS_FSM_ERROR;
 
   end:
-    if (buf != NULL) free(buf);
+    if (buf != NULL) xfree(buf);
     /* check the RC */
     if (rc == OPENPTS_FSM_ERROR) {
         DEBUG("doActivity rc = %d\n", rc);
index 5c23957..323c2b2 100644 (file)
@@ -80,9 +80,9 @@
  */
 AIDE_METADATA * newAideMetadata() {
     AIDE_METADATA *metadata;
-    metadata = (AIDE_METADATA *) malloc(sizeof(AIDE_METADATA));
+    metadata = (AIDE_METADATA *) xmalloc(sizeof(AIDE_METADATA));
     if (metadata == NULL) {
-        ERROR("no memory\n");
+        // ERROR("no memory\n");
         return NULL;
     }
     memset(metadata, 0, sizeof(AIDE_METADATA));
@@ -105,14 +105,14 @@ void freeAideMetadata(AIDE_METADATA *md) {
     }
 
     /* free */
-    if (md->name != NULL) free(md->name);
-    if (md->lname != NULL) free(md->lname);
-    if (md->sha1 != NULL) free(md->sha1);
-    if (md->sha256 != NULL) free(md->sha256);
-    if (md->ima_name != NULL) free(md->ima_name);
-    if (md->hash_key != NULL) free(md->hash_key);
-
-    free(md);
+    if (md->name != NULL) xfree(md->name);
+    if (md->lname != NULL) xfree(md->lname);
+    if (md->sha1 != NULL) xfree(md->sha1);
+    if (md->sha256 != NULL) xfree(md->sha256);
+    if (md->ima_name != NULL) xfree(md->ima_name);
+    if (md->hash_key != NULL) xfree(md->hash_key);
+
+    xfree(md);
     md = NULL;
 
     return;
@@ -160,16 +160,15 @@ AIDE_CONTEXT * newAideContext() {
 
     // DEBUG("newAideContext()\n");
 
-    ctx = malloc(sizeof(AIDE_CONTEXT));
+    ctx = xmalloc(sizeof(AIDE_CONTEXT));
     if (ctx == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memset(ctx, 0, sizeof(AIDE_CONTEXT));
 
     /* hash tables */
     // TODO set the size in openpts.h
-    ctx->aide_md_table = malloc(sizeof(struct hsearch_data));
+    ctx->aide_md_table = xmalloc(sizeof(struct hsearch_data));
     // TODO ck null
     memset(ctx->aide_md_table, 0, sizeof(struct hsearch_data));
     rc = hcreate_r(AIDE_HASH_TABLE_SIZE, ctx->aide_md_table);  // hash table for metadata
@@ -179,7 +178,7 @@ AIDE_CONTEXT * newAideContext() {
     }
     ctx->aide_md_table_size = 0;
 
-    ctx->aide_in_table = malloc(sizeof(struct hsearch_data));
+    ctx->aide_in_table = xmalloc(sizeof(struct hsearch_data));
     // TODO ck null
     memset(ctx->aide_in_table, 0, sizeof(struct hsearch_data));
     //  4096 full
@@ -194,7 +193,7 @@ AIDE_CONTEXT * newAideContext() {
     return ctx;
 
   error:
-    if (ctx != NULL) free(ctx);
+    if (ctx != NULL) xfree(ctx);
     return NULL;
 }
 
@@ -213,10 +212,10 @@ void freeAideIgnoreList(AIDE_LIST *list) {
 
     /* Free */
     if (list->name != NULL) {
-        free(list->name);
+        xfree(list->name);
     }
 
-    free(list);
+    xfree(list);
 
     return;
 }
@@ -239,8 +238,8 @@ void freeAideContext(AIDE_CONTEXT *ctx) {
     hdestroy_r(ctx->aide_md_table);
     hdestroy_r(ctx->aide_in_table);
 
-    free(ctx->aide_md_table);
-    free(ctx->aide_in_table);
+    xfree(ctx->aide_md_table);
+    xfree(ctx->aide_in_table);
 
 #ifdef CONFIG_SQLITE
     if (ctx->sqlite_db != NULL) {
@@ -260,7 +259,7 @@ void freeAideContext(AIDE_CONTEXT *ctx) {
         freeAideIgnoreList(ctx->ignore_name_start);
     }
 
-    free(ctx);
+    xfree(ctx);
     return;
 }
 
@@ -445,12 +444,12 @@ int loadAideDatabaseFile(AIDE_CONTEXT *ctx, char *filename) {
                 switch (items[i]) {
                     case AIDE_ITEM_NAME:   // char
                         if (!is_null) {
-                            md->name = smalloc(ptr);
+                            md->name = smalloc_assert(ptr);
                         }
                         break;
                     case AIDE_ITEM_LNAME:  // char
                         if (!is_null) {
-                            md->lname = smalloc(ptr);
+                            md->lname = smalloc_assert(ptr);
                         }
                         break;
                     case AIDE_ITEM_ATTR:   // int
@@ -534,7 +533,7 @@ int loadAideDatabaseFile(AIDE_CONTEXT *ctx, char *filename) {
                 // TODO SHA1 only, add hash agility later
                 /* alloc hash key */
                 sha1_b64_ptr[SHA1_BASE64_DIGEST_SIZE] = 0;  // jXgiZyt0yUbP4QhAq9WFsLF/FL4=  28
-                md->hash_key = malloc(strlen(sha1_b64_ptr) +1);
+                md->hash_key = xmalloc(strlen(sha1_b64_ptr) +1);
                 // TODO check NULL
                 memcpy(md->hash_key, sha1_b64_ptr, strlen(sha1_b64_ptr) + 1);
 
@@ -622,14 +621,14 @@ int readAideIgnoreNameFile(AIDE_CONTEXT *ctx, char *filename) {
             DEBUG("%4d [%s]\n", cnt, line);
 
             /* new  */
-            list = malloc(sizeof(AIDE_LIST));
+            list = xmalloc(sizeof(AIDE_LIST));
             if (list == NULL) {
                 ERROR("no mem\n");
                 rc = PTS_OS_ERROR;
                 goto error;  // return -1;
             }
             memset(list, 0, sizeof(AIDE_LIST));
-            list->name = smalloc(line);
+            list->name = smalloc_assert(line);
 
             /* add to chain */
             if (ctx->ignore_name_start == NULL) {
@@ -723,7 +722,7 @@ int hexcmp(BYTE *d1, BYTE *d2, int len) {
 // TODO(munetoh) how this work?
 void copyAideMetadata(AIDE_METADATA *dst, AIDE_METADATA *src) {
     if (dst->name == NULL) {
-        dst->name = malloc(strlen(src->name) + 1);
+        dst->name = xmalloc(strlen(src->name) + 1);
         memcpy(dst->name, src->name, strlen(src->name) + 1);
     }
 }
@@ -880,7 +879,7 @@ int checkEventByAide(AIDE_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrapper)
         return -1;
     }
     rc = verifyBySQLite(ctx, (char*)buf);
-    free(buf);
+    xfree(buf);
 
     if (rc == OPENPTS_RESULT_VALID) {
         /* hit */
@@ -976,14 +975,14 @@ int checkEventByAide(AIDE_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrapper)
     rc = checkIgnoreList(ctx, name);
     if (rc == 0) {
         // HIT
-        free(name);
+        xfree(name);
         return 1;  // IGNORE
     }
 
-    free(name);
+    xfree(name);
     return 2;
 #else
-    free(name);
+    xfree(name);
     return 1;  // force
 #endif
 }
@@ -1052,9 +1051,8 @@ int escapeFilename(char **out, char *in) {
     len = strlen(in);
 
     /*  rough malloc new buffer */
-    buf = malloc(len*3);
+    buf = xmalloc(len*3);
     if (buf == NULL) {
-        ERROR("no memory\n");
         return -1;
     }
 
@@ -1203,7 +1201,7 @@ int convertImlToAideDbFile(OPENPTS_CONTEXT *ctx, char *filename) {
             gzprintf(fp, "bad_filename ");
         } else {
             gzprintf(fp, "%s ", aide_filename);
-            free(aide_filename);
+            xfree(aide_filename);
             aide_filename = NULL;
         }
 
@@ -1217,7 +1215,7 @@ int convertImlToAideDbFile(OPENPTS_CONTEXT *ctx, char *filename) {
             goto close;
         }
         gzprintf(fp, "%s \n", buf);
-        free(buf);
+        xfree(buf);
 
         // printf("%d %s\n", i, buf);
 
@@ -1233,7 +1231,7 @@ int convertImlToAideDbFile(OPENPTS_CONTEXT *ctx, char *filename) {
     gzseek(fp, 1L, SEEK_CUR);  // add one \n
   close:
     gzclose(fp);
-    if (aide_filename != NULL) free(aide_filename);
+    if (aide_filename != NULL) xfree(aide_filename);
 
     DEBUG("convertImlToAideDbFile - done\n");
 
@@ -1302,7 +1300,7 @@ int writeReducedAidbDatabase(AIDE_CONTEXT *ctx, char *filename) {
             }
             gzprintf(fp, "%s ", md->name);
             gzprintf(fp, "%s \n", buf);
-            free(buf);
+            xfree(buf);
             cnt++;
         }
 
index 4784095..adfa30e 100644 (file)
@@ -41,6 +41,7 @@
 #include <string.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 /**
  * calc base64 size
@@ -56,6 +57,30 @@ int _sizeofBase64Encode(int len) {
     return (len + 2 - ((len + 2) % 3)) * 4 / 3 + 1;
 }
 
+int getDecodedBase64Size(unsigned char *in, int inLen) {
+    int inCount;
+    int outCount;
+
+    inCount = inLen / 4;
+    if (inCount > 0) {
+        --inCount;
+    }
+    outCount = inCount * 3;
+    inCount *= 4;
+
+    if ( in[inCount+1] == '=' ) {
+        outCount += 1;
+    } else if ( in[inCount+2] == '=' ) {
+        outCount += 1;
+    } else if ( in[inCount+3] == '=' ) {
+        outCount += 2;
+    } else {
+        outCount += 3;
+    }
+
+    return outCount;
+}
+
 /**
  * calc original data size from base64 string size
  *
@@ -154,18 +179,18 @@ char *encodeBase64(unsigned char * in, int inlen, int *outlen) {
     int len2;
 
     *outlen = _sizeofBase64Encode(inlen);
-    out = (char *) malloc(*outlen);
+    out = (char *) xmalloc_assert(*outlen);
     if (out == NULL) {
         ERROR("no memory");
         *outlen = 0;
         return NULL;
     }
-    memset(out,0,*outlen);
+    memset(out, 0, *outlen);
 
     len2 = _encodeBase64(out, in, inlen);
     if (len2 > *outlen) {
         ERROR("fatal error");
-        free(out);
+        xfree(out);
         *outlen = 0;
         return NULL;
     }
@@ -196,7 +221,7 @@ int _strippedlength(char * in, int len) {
     /* last char */
     i = len - 1;
 
-    while(1) {
+    while (1) {
         if (in[i] == '\n') {
             /* skip */
             skip++;
@@ -223,12 +248,12 @@ int _strippedlength(char * in, int len) {
   * return size of BYTE[] array
   */
 int _decodeBase64(unsigned char *out, char * in, int len) {
-    int ptr1 = 0; // in
-    int ptr2 = 0; // out
+    int ptr1 = 0;  // in
+    int ptr2 = 0;  // out
     int len2;
     char * in2;
     char inbuf[4];
-    int i,j;
+    int i, j;
     int skip;
 
     /* check */
@@ -347,18 +372,18 @@ unsigned char *decodeBase64(char * in, int inlen, int *outlen) {
     int len2;
 
     len1 = _sizeofBase64Decode(inlen);
-    out = (unsigned char *) malloc(len1);
+    out = (unsigned char *) xmalloc_assert(len1);
     if (out == NULL) {
         ERROR("no memory");
         *outlen = 0;
         return NULL;
     }
-    memset(out,0,len1);
+    memset(out, 0, len1);
 
     len2 = _decodeBase64(out, in, inlen);
     if (len2 < 0) {
         ERROR("fatal error");
-        free(out);
+        xfree(out);
         *outlen = 0;
         return NULL;
     }
index f23319b..dfe395c 100644 (file)
@@ -44,6 +44,7 @@
 #include <netinet/in.h>
 #include <arpa/inet.h>  // inet_ntoa
 #include <unistd.h>
+#include <grp.h>
 
 #include <signal.h>
 
@@ -54,7 +55,6 @@
 
 #include <openpts.h>
 
-
 /**
  * print FSM info
  */
@@ -62,16 +62,16 @@ void printFsmInfo(OPENPTS_CONTEXT *ctx, char * indent) {
     int i;
     OPENPTS_SNAPSHOT *ss;
 
-    printf("%sPCR lv  FSM files\n", indent);
-    printf("%s-----------------------------------------------------\n", indent);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_FSM_INFO_HEADER, "%sPCR lv  FSM files\n"), indent);
+    OUTPUT("%s-----------------------------------------------------\n", indent);
 
     for (i = 0; i < MAX_PCRNUM; i++) {
         ss = getSnapshotFromTable(ctx->ss_table, i, 0);
 
         if (ss != NULL) {
             if (ss->fsm_behavior != NULL) {
-                printf("%s%2d  0  ", indent, i);
-                printf("%s\n", ss->fsm_behavior->uml_file);
+                OUTPUT("%s%2d  0  ", indent, i);
+                OUTPUT("%s\n", ss->fsm_behavior->uml_file);
             }
         }
 
@@ -79,12 +79,12 @@ void printFsmInfo(OPENPTS_CONTEXT *ctx, char * indent) {
         ss = getSnapshotFromTable(ctx->ss_table, i, 1);
         if (ss != NULL) {
             if (ss->fsm_behavior != NULL) {
-                printf("%s%2d  1  ", indent, i);
-                printf("%s\n", ss->fsm_behavior->uml_file);
+                OUTPUT("%s%2d  1  ", indent, i);
+                OUTPUT("%s\n", ss->fsm_behavior->uml_file);
             }
         }
     }
-    printf("%s-----------------------------------------------------\n", indent);
+    OUTPUT("%s-----------------------------------------------------\n", indent);
 }
 
 /**
@@ -102,8 +102,8 @@ int extendEvCollectorStart(OPENPTS_CONFIG *conf) {
 
 
     /* malloc eventlog */
-    collector_start = malloc(sizeof(OPENPTS_EVENT_COLLECTOR_START));
-    event = malloc(sizeof(TSS_PCR_EVENT));
+    collector_start = xmalloc_assert(sizeof(OPENPTS_EVENT_COLLECTOR_START));
+    event = xmalloc_assert(sizeof(TSS_PCR_EVENT));
 
     /*fill collector_start */
     memcpy(&collector_start->pts_version, &conf->pts_version, 4);
@@ -112,7 +112,7 @@ int extendEvCollectorStart(OPENPTS_CONFIG *conf) {
 
 
     /* get PCR value*/
-    // memcpy(&collector_start->pcr_value;make
+    // memcpy(&collector_start->pcr_value;
     readPcr(conf->openpts_pcr_index, pcr);
     memcpy(&collector_start->pcr_value, pcr, SHA1_DIGEST_SIZE);
 
@@ -138,8 +138,8 @@ int extendEvCollectorStart(OPENPTS_CONFIG *conf) {
     extendEvent(event);
 
     /* free */
-    free(collector_start);
-    free(event);
+    xfree(collector_start);
+    xfree(event);
 
     return PTS_SUCCESS;
 }
@@ -169,15 +169,74 @@ int init(
     OPENPTS_PROPERTY *prop_end) {
     int rc = PTS_SUCCESS;
     UINT32 ps_type = TSS_PS_TYPE_SYSTEM;
-    OPENPTS_CONTEXT *ctx;
+    OPENPTS_CONTEXT *ctx = NULL;
     int i;
     int keygen = 1;
+    TSS_VERSION tpm_version;
+
+    /* check */
+    if (conf == NULL) {
+        ERROR("FATAL");
+        return PTS_FATAL;
+    }
+    if (conf->uuid == NULL) {
+        ERROR("FATAL");
+        return PTS_FATAL;
+    }
+    if (conf->uuid->filename == NULL) {
+        ERROR("FATAL");
+        return PTS_FATAL;
+    }
+
+    /*
+     * Common misconfigulations
+     *
+     *  1) cannot access the IML through TSS.
+     *     default /etc/tcsd.conf does not configured to access the IML file at
+     *     securityfs.
+     *     => ERROR : OPENPTS_MISSING_IML
+     *
+     *  2) TPM not taken ownership.
+     *     in this case, Keygen was failed
+     *  3) Missing TCS Daemon
+     *     So ptsc can not access TPM/TSS, may got tspi 0x0311 error.
+     *  4) /etc/ptsc.conf did not configured for this platform yet
+     *     missing PCR - Model convination
+     */
+
+    /* Check the existing configulation */
+    rc = checkFile(conf->uuid->filename);
+    if (rc == OPENPTS_FILE_EXISTS) {
+        char *str_uuid;
+        PTS_DateTime *time;
+        /* if UUID file exist => exit, admin must delete the UUID file, then init again */
+        /* check existing UUID */
+        rc = readOpenptsUuidFile(conf->uuid);
+        str_uuid = getStringOfUuid(conf->uuid->uuid);
+        time = getDateTimeOfUuid(conf->uuid->uuid);
+
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_UUID_FILE_EXISTS,
+                "The ptsc has been initialized. "
+                "If you want to re-intialize the platform, please clear the collector. "
+                "To see the detail of current ptsc, use ptsc -D. "
+                "To clear the ptsc, use ptsc -e\n"));
+        OUTPUT("    existing uuid = %s\n", str_uuid);
+        OUTPUT("    creation date = %d-%d-%d\n",
+            time->year + 1900,
+            time->mon + 1,
+            time->mday);
+        /* free */
+        xfree(str_uuid);
+        xfree(time);
+        return PTS_FATAL;  // TODO assign error code
+    }
+
 
     /* ctx for init */
     ctx = newPtsContext(conf);
     if (ctx == NULL) {
-        ERROR("no memory\n");
-        return PTS_INTERNAL_ERROR;
+        ERROR("no memory?");
+        return PTS_FATAL;
     }
 
     /* add property */
@@ -186,12 +245,92 @@ int init(
         ctx->prop_end = prop_end;
         ctx->prop_count = prop_count;
     }
+    addPropertiesFromConfig(conf, ctx);
+
+    /* get TPM and TSS version */
+    rc = getTpmVersion(&tpm_version);
+    if (rc != PTS_SUCCESS) {
+        addReason(ctx, -1,
+            "[PTSC-INIT] Couldn't get the TPM version. Check the TSS and TPM driver.");
+        rc = PTS_FATAL;
+        goto error;
+    }
+
+    /* read FSM */
+    rc = readFsmFromPropFile(ctx, conf->config_file);
+    if (rc != PTS_SUCCESS) {
+        addReason(ctx, -1,
+            "[PTSC-INIT] Couldn't load validation models. Check the ptsc configlation, %s.",
+            conf->config_file);
+        rc = PTS_FATAL;
+        goto error;
+    }
+
+    /* read IML to fill the BIOS binary measurement, and translate BHV->BIN FSM */
+    /* load current IML using FSMs */
+    if (conf->iml_mode == 0) {  // TODO use def
+        rc = getIml(ctx, 0);  // iml.c, return event num
+        if (rc == 0) {
+            addReason(ctx, -1,
+                "[PTSC-INIT] Couldn't access IML through TSS. "
+                "Check the TSS configuration /etc/tcsd.conf");
+            rc = OPENPTS_IML_MISSING;
+            goto error;
+        }
 
+        rc = getPcr(ctx);  // iml.c, return pcr num
+        if (rc == 0) {
+            addReason(ctx, -1,
+                "[PTSC-INIT] Couldn't get the PCR value");
+            rc = PTS_FATAL;
+            goto error;
+        }
+    } else if (conf->iml_mode == 1) {
+        // TODO change to generic name?  conf->iml_filename[0]  conf->iml_filename[1]
+        /* from  securityfs */
+        /* BIOS IML */
+        rc = readBiosImlFile(
+                ctx,
+                conf->bios_iml_filename, conf->iml_endian);
+        if (rc != PTS_SUCCESS) {
+            addReason(ctx, -1,
+                "[PTSC-INIT] Couldn't read the IML file, %s. Check the ptsc configuration, %s.",
+                conf->bios_iml_filename, conf->config_file);
+            rc = PTS_FATAL;
+            goto error;
+        }
+
+        /* RUNTIME IML (Linux-IMA) */
+        if (ctx->conf->runtime_iml_filename != NULL) {
+            int count;
+            rc = readImaImlFile(
+                    ctx,
+                    conf->runtime_iml_filename,
+                    conf->runtime_iml_type, 0, &count);  // TODO endian?
+            if (rc != PTS_SUCCESS) {
+                addReason(ctx, -1,
+                    "[PTSC-INIT] Couldn't read IML file, %s. Check the ptsc configuration, %s.",
+                    conf->runtime_iml_filename, conf->config_file);
+                rc = PTS_INTERNAL_ERROR;
+                goto error;
+            }
+        }
+    } else {
+        addReason(ctx, -1,
+            "[PTSC-INIT] Unknown IML mode, %d, Check the ptsc configuration (iml.mode), %s .",
+            conf->iml_mode, conf->config_file);
+        rc = PTS_FATAL;
+        goto error;
+    }
 
-    /* config dir */
+    /* config dir, /var/lib/openpts */
     if (conf->config_dir == NULL) {
-        ERROR("missing config dir, check your config file %s\n", conf->config_file);
-        return PTS_INTERNAL_ERROR;
+        addReason(ctx, -1,
+            NLS(MS_OPENPTS, OPENPTS_COLLECTOR_MISSING_CONFIG_DIR,
+            "[PTSC-INIT] Configuration directory is not defined. Check the ptsc configuration file, %s"),
+            conf->config_file);
+        rc = PTS_INTERNAL_ERROR;
+        goto error;
     } else {
         /* check */
         rc = checkDir(conf->config_dir);
@@ -199,22 +338,56 @@ int init(
             /* OK */
         } else {
             /* Missing */
-            INFO("create new config dir, %s", conf->config_dir);
+            struct group *ptsc_grp;
+            VERBOSE(1, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_NEW_CONFIG_DIR,
+                "Creating new configuration directory '%s'\n"), conf->config_dir);
             makeDir(conf->config_dir);
+
+            // TODO Consider using getgrnam_r(...)
+            if ((ptsc_grp = getgrnam(PTSC_GROUP_NAME)) != NULL) {
+                if (-1 == chown(conf->config_dir, 0, ptsc_grp->gr_gid)) {
+                    addReason(ctx, -1,
+                        NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CHANGE_OWNSHIP_FAIL,
+                        "[PTSC-INIT] Could not change ownership of %s to " PTSC_GROUP_NAME "\n"),
+                        conf->config_dir);
+                    rc = PTS_FATAL;
+                    goto error;
+                }
+                if (-1 == chmod(conf->config_dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP)) {
+                    addReason(ctx, -1,
+                        NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CHANGE_MODE_FAIL,
+                        "[PTSC-INIT] Could not change file mode of %s (rwxr-w---)\n"), conf->config_dir);
+                    rc = PTS_FATAL;
+                    goto error;
+                }
+            } else {
+                addReason(ctx, -1,
+                    NLS(MS_OPENPTS, OPENPTS_COLLECTOR_FIND_GROUP_FAIL,
+                    "[PTSC-INIT] Failed to look up group '%s'\n"), PTSC_GROUP_NAME);
+                    rc = PTS_FATAL;
+                    goto error;
+            }
         }
     }
-    // DEBUG("config dir : %s\n", conf->config_dir);
 
     /* Generate UUID of this platform */
-    // TODO TODO TODO
     if (conf->uuid == NULL) {
         // TODO UUID filename is missing
-        ERROR(" bad conf file\n");
-        return PTS_INTERNAL_ERROR;
+        addReason(ctx, -1,
+            NLS(MS_OPENPTS, OPENPTS_COLLECTOR_BAD_CONFIG_FILE,
+            "[PTSC-INIT] Bad configuration file, %s"),
+            conf->config_file);
+        rc = PTS_INTERNAL_ERROR;
+        goto error;
     } else if (conf->uuid->status == OPENPTS_UUID_FILENAME_ONLY) {
         /* gen new UUID */
         rc = genOpenptsUuid(conf->uuid);
-        // TODO check rc
+        if (rc != PTS_SUCCESS) {
+            addReason(ctx, -1,
+                "[PTSC-INIT] Generation of UUID was failed");
+            rc = PTS_INTERNAL_ERROR;
+            goto error;
+        }
     } else {
         DEBUG("init() - use given UUID %s (for TEST)\n", conf->uuid->str);
         keygen = 0;
@@ -228,159 +401,127 @@ int init(
     if (keygen == 1) {
         rc = createTssSignKey(conf->uuid->uuid, ps_type, NULL, 0, conf->srk_password_mode);
         if (rc == 0x0001) {  // 0x0001
-            fprintf(stderr, "createSignKey failed. "
-                            "if you uses well known SRK secret, "
-                            "all zeros (20 bytes of zeros) try -z option\n");
+            addReason(ctx, -1,
+                NLS(MS_OPENPTS, OPENPTS_COLLECTOR_SIGN_KEY_FAIL,
+                "[PTSC-INIT] Failed to create the signed key. "
+                "If you are using the well known SRK secret key (all zeroes) "
+                "then please try again with the '-z' option\n"));
             rc = PTS_INTERNAL_ERROR;
-            goto free;
+            goto error;
         } else if (rc != PTS_SUCCESS) {
-            fprintf(stderr, "createSignKey failed, rc = 0x%x\n", rc);
+            addReason(ctx, -1,
+                "[PTSC-INIT] Could not create the Key (rc = 0x%x).", rc);
             rc = PTS_INTERNAL_ERROR;
-            goto free;
+            goto error;
         }
-        printf("Sign key  location          : SYSTEM\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_INIT_PTSCD, "Sign key  location: SYSTEM\n"));
     } else {
         DEBUG("init() - skip key gen for the given UUID\n");
     }
 
-
-    /* Write UUID file */
-    rc = writeOpenptsUuidFile(conf->uuid, 0);
-    if (rc == PTS_DENIED) {
-        char *str_uuid;
-        PTS_DateTime *time;
-        /* if UUID file exist => exit, admin must delete the UUID file, then init again */
-        /* check existing UUID */
-        rc = readOpenptsUuidFile(conf->uuid);
-        str_uuid = getStringOfUuid(conf->uuid->uuid);
-        time = getDateTimeOfUuid(conf->uuid->uuid);
-
-        fprintf(stderr, "uuid file, '%s' exist, please remove this file if you want to re-intialize the platform\n",
-            conf->uuid->filename);
-        fprintf(stderr, "    existing uuid = %s\n", str_uuid);
-        fprintf(stderr, "    creation date = %d-%d-%d\n",
-            time->year + 1900,
-            time->mon + 1,
-            time->mday);
-        /* free */
-        free(str_uuid);
-        free(time);
-        goto free;
-    } else if (rc != PTS_SUCCESS) {
-        /* internal error */
-        fprintf(stderr, "uuid file, '%s' generation was failed\n", conf->uuid->filename);
-        rc = PTS_INTERNAL_ERROR;
-        goto free;
-    }
-
     /* print uuid */
-    printf("Generate uuid               : %s \n", conf->uuid->str);
-
-
-
-    /* read FSM */
-    rc = readFsmFromPropFile(ctx, conf->config_file);
-    if (rc != PTS_SUCCESS) {
-        ERROR("read FSM failed\n");
-        rc = PTS_INTERNAL_ERROR;
-        goto free;
-    }
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_INIT_GEN_UUID, "Generate uuid: %s \n"), conf->uuid->str);
 
     /* UUID for RM */
     if (conf->rm_uuid == NULL) {
         // init/set by readPtsConf
-        ERROR("conf->rm_uuid == NULL\n");
+        // ERROR("conf->rm_uuid == NULL\n");
+        addReason(ctx, -1,
+            "[PTSC-INIT] RM_UUID file is not defined (rm.uuid.file) in the ptsc configulation, %s",
+            conf->config_file);
+        rc = PTS_INTERNAL_ERROR;
+        goto error;
     } else if (conf->rm_uuid->status == OPENPTS_UUID_FILENAME_ONLY) {
         rc = genOpenptsUuid(conf->rm_uuid);
-        // TODO
+        if (rc != PTS_SUCCESS) {
+            addReason(ctx, -1,
+                "[PTSC-INIT] Generation of RM UUID was failed");
+            rc = PTS_INTERNAL_ERROR;
+            goto error;
+        }
+
     } else {
         DEBUG("init() - use given RM UUID %s\n", conf->rm_uuid->str);
     }
 
-    /* save to rm_uuid file */
-    rc = writeOpenptsUuidFile(conf->rm_uuid, 0);  // do not overwrite
-    if (rc != PTS_SUCCESS) {
-        ERROR("writeOpenptsUuidFile fail\n");
-    }
-    // TODO check rc
-
     /* RM set DIR */
     rc = makeRmSetDir(conf);
     if (rc != PTS_SUCCESS) {
-        ERROR("mkdir of RM set dir was failed\n");
-        goto free;
+        addReason(ctx, -1,
+            "[PTSC-INIT] Couldn't create Reference Maniferst directory");
+        rc = PTS_INTERNAL_ERROR;
+        goto error;
     }
 
     /* print rm uuid */
-    printf("Generate UUID (for RM)      : %s \n", conf->rm_uuid->str);
-
-    /* read IML to fill the BIOS binary measurement, and translate BHV->BIN FSM */
-
-    /* load current IML using FSMs */
-    if (conf->iml_mode == 0) {  // TODO use def
-#ifdef CONFIG_NO_TSS
-        ERROR("Build with --without-tss. iml.mode=tss is not supported\n");
-#else
-        rc = getIml(ctx, 0);
-        rc = getPcr(ctx);
-#endif
-    } else if (conf->iml_mode == 1) {
-        // TODO change to generic name?  conf->iml_filename[0]  conf->iml_filename[1]
-        /* from  securityfs */
-        /* BIOS IML */
-        rc = readBiosImlFile(
-                ctx,
-                conf->bios_iml_filename, conf->iml_endian);
-        if (rc != PTS_SUCCESS) {
-            DEBUG("getBiosImlFile() was failed\n");
-            fprintf(stderr, "Oops! Something is wrong. Please see the reason below\n");
-            printReason(ctx);
-            goto free;
-        }
-
-        /* RUNTIME IML (Linux-IMA) */
-        if (ctx->conf->runtime_iml_filename != NULL) {
-            int count;
-            rc = readImaImlFile(
-                    ctx,
-                    conf->runtime_iml_filename,
-                    conf->runtime_iml_type, 0, &count);  // TODO endian?
-            if (rc != PTS_SUCCESS) {
-                fprintf(stderr, "read IMA IML, %s was failed\n", conf->runtime_iml_filename);
-                rc = PTS_INTERNAL_ERROR;
-                goto free;
-            }
-        }
-    } else {
-        ERROR("unknown IML mode, %d\n", conf->iml_mode);
-    }
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_INIT_GEN_RM_UUID,
+        "Generate UUID (for RM): %s \n"), conf->rm_uuid->str);
 
     /* get SMBIOS data */
-    // TODO
+    // TODO Platform information - TBD
+    //      Use ptsc.conf to set the platform info, malually
 
     /* create Reference Manifest */
     for (i = 0; i < conf->rm_num; i++) {
         if (conf->rm_filename[i] != NULL) {
             rc = writeRm(ctx, conf->rm_filename[i], i);
             if (rc != PTS_SUCCESS) {
-                fprintf(stderr, "ERROR, initialization was failed\n");
-                addReason(ctx,
-                    "[INIT] Failed to create the manifest file, %s",
+                ERROR("ERROR, initialization was failed\n");
+                // WORK NEEDED: Reason need putting in NLS
+                addReason(ctx, -1,
+                    "[PTSC-INIT] Couldn't create the manifest file, %s",
                     conf->rm_filename[i]);
-                printReason(ctx);
+                //printReason(ctx, 0);
                 rc = PTS_FATAL;
-                goto free;
+                goto error;
             }
-            printf("level %d Reference Manifest  : %s\n", i, conf->rm_filename[i]);
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_INIT_RM,
+                "level %d Reference Manifest  : %s\n"), i, conf->rm_filename[i]);
         } else {
-            ERROR("missing RM file for level %d\n", i);
+            addReason(ctx, -1,
+                NLS(MS_OPENPTS, OPENPTS_COLLECTOR_MISSING_RM_FILE,
+                "[PTSC-INIT] Missing reference manifest file for level %d\n"), i);
+            rc = PTS_FATAL;
+            goto error;
         }
     }
-    printf("\nptsc is successfully initialized!\n");
+
+    /* Finaly wrote the UUID files */
+
+    /* Write UUID file */
+    rc = writeOpenptsUuidFile(conf->uuid, 0);
+    if (rc != PTS_SUCCESS) {
+        /* internal error */
+        addReason(ctx, -1,
+            "[PTSC-INIT] Couldn't write the uuid file, '%s'.\n",
+            conf->uuid->filename);
+        rc = PTS_INTERNAL_ERROR;
+        goto error;
+    }
+
+    /* save to rm_uuid file */
+    rc = writeOpenptsUuidFile(conf->rm_uuid, 0);
+    if (rc != PTS_SUCCESS) {
+        addReason(ctx, -1,
+            "[PTSC-INIT] Couldn't write the UUID file, %s",
+            conf->rm_uuid->filename);
+        rc = PTS_INTERNAL_ERROR;
+        goto error;
+    }
+
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_INIT_SUCCESS,
+        "\nptsc has successfully initialized!\n"));
+    goto free;
+
+ error:
+    /* initialization was faild */
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_INIT_FAIL,
+        "ptsc initialization was failed\n"));
+    printReason(ctx, 0);
 
  free:
     /* free */
-    freePtsContext(ctx);
+    if (ctx != NULL) freePtsContext(ctx);
 
     return rc;
 }
@@ -416,6 +557,7 @@ int selftest(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start,
     OPENPTS_CONTEXT *ctx;
     int i;
     OPENPTS_PROPERTY *prop;
+    char * ir_filename;
 
     DEBUG("selftest() start\n");
 
@@ -424,7 +566,6 @@ int selftest(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start,
     /* new */
     ctx = newPtsContext(conf);
     if (ctx == NULL) {
-        ERROR("no memory\n");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -439,26 +580,31 @@ int selftest(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start,
         prop = prop->next;
     }
 
+    /* additional properties from the pts config file */
+    addPropertiesFromConfig(conf, ctx);
 
     /* set dummy nonce for IR gen */
     ctx->nonce->nonce_length = 20;
-    ctx->nonce->nonce = malloc(20);
+    ctx->nonce->nonce = xmalloc_assert(20);
     memset(ctx->nonce->nonce, 0x5A, 20);
     // dummy target uuid
     ctx->str_uuid = smalloc("SELFTEST");
 
     /* gen IR */
-    rc = genIr(ctx);  // ir.c
+    rc = genIr(ctx, NULL);
     if (rc != PTS_SUCCESS) {
         ERROR("selftest() - genIR failed\n");
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
 
+    /* hold the IR filename */
+    ir_filename = ctx->ir_filename;
+    ctx->ir_filename = NULL;
+
     /* free */
     freePtsContext(ctx);
 
-
     // DEBUG("selftest() - generate IR file => %s\n", conf->ir_filename);
     DEBUG("selftest() - generate IR - done\n");
 
@@ -473,9 +619,9 @@ int selftest(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start,
     /* new */
     ctx = newPtsContext(conf);
     if (ctx == NULL) {
-        ERROR("no memory\n");
         return PTS_INTERNAL_ERROR;
     }
+    ctx->ir_filename = ir_filename;
 
     /* setup RMs */
     rc = getRmSetDir(conf);
@@ -513,18 +659,19 @@ int selftest(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start,
 
 
 
-    result = validateIr(ctx, conf->ir_filename);  /* ir.c */
-
+    //result = validateIr(ctx, conf->ir_filename);  /* ir.c */
+    // TODO 
+    result = validateIr(ctx);  /* ir.c */
 
 
     /* check RM integrity status */
     DEBUG("selftest() - validate IR - done (rc = %d)\n", result);
-    if ((rc != OPENPTS_RESULT_VALID) && (verbose & DEBUG_FLAG)) {
-        printReason(ctx);
+    if ((rc != OPENPTS_RESULT_VALID) && isDebugFlagSet(DEBUG_FLAG)) {
+        printReason(ctx, 0);
     }
 
     if (result != OPENPTS_RESULT_VALID) {
-        addReason(ctx, "[SELFTEST] selftest was failed");
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_SELFTEST_FAILED, "[SELFTEST] The self test failed"));
         if ((conf->newrm_uuid != NULL) && (conf->newrm_uuid->uuid != NULL)) {
             /* New RM exist (for reboot after the update), Try the new RM */
 
@@ -560,13 +707,13 @@ int selftest(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start,
             } else {
                 /* fail */
                 TODO("\n");
-                addReason(ctx, "[SELFTEST] selftest using both current and new UUID was failed");
-                printReason(ctx);
+                addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_SELFTEST_FAILED_2,
+                               "[SELFTEST] The self test using both current and new UUIDs has failed"));
+                printReason(ctx, 0);
                 rc = OPENPTS_SELFTEST_FAILED;
             }
         } else {
-            addReason(ctx, "[SELFTEST] selftest was failed");
-            printReason(ctx);
+            printReason(ctx, 0);
             rc = OPENPTS_SELFTEST_FAILED;
         }
     } else {
@@ -574,6 +721,13 @@ int selftest(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start,
         rc = OPENPTS_SELFTEST_SUCCESS;
     }
 
+    /* leaving lots of temp 100K+ files lying around quickly fills up certain
+       filesystems, i.e. on AIX /tmp is typically small, so we 
+       unlink them after use */
+    if (NULL != conf->ir_filename) {
+        unlink(conf->ir_filename);
+    }
+
  free:
     /* free */
     freePtsContext(ctx);
@@ -605,7 +759,6 @@ int newrm(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OP
     /* ctx for init */
     ctx = newPtsContext(conf);
     if (ctx == NULL) {
-        ERROR("no memory\n");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -629,10 +782,12 @@ int newrm(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OP
     }
 #endif
 
+    addPropertiesFromConfig(conf, ctx);
+
     /* read FSM */
     rc = readFsmFromPropFile(ctx, conf->config_file);
     if (rc != PTS_SUCCESS) {
-        ERROR("read FSM failed\n");
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_FAILED_READ_FSM, "Failed to read the FSM file\n"));
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -656,12 +811,13 @@ int newrm(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OP
     /* RM set DIR */
     rc = makeRmSetDir(conf);
     if (rc != PTS_SUCCESS) {
-        ERROR("mkdir of RM set dir was failed\n");
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_MKDIR_RM_SET_FAILED,
+            "Failed to create the reference manifest set directory\n"));
         goto free;
     }
 
     /* print rm uuid */
-    printf("Generate UUID (for RM)      : %s \n", conf->rm_uuid->str);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_NEW_RM_UUID, "Generate UUID (for RM): %s \n"), conf->rm_uuid->str);
 
     /* read IML to fill the BIOS binary measurement, and translate BHV->BIN FSM */
 
@@ -682,8 +838,8 @@ int newrm(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OP
                 conf->bios_iml_filename, conf->iml_endian);
         if (rc != PTS_SUCCESS) {
             DEBUG("getBiosImlFile() was failed\n");
-            fprintf(stderr, "Oops! Something is wrong. Please see the reason below\n");
-            printReason(ctx);
+            ERROR("Oops! Something is wrong. Please see the reason below\n");
+            printReason(ctx, 0);
             goto free;
         }
 
@@ -695,7 +851,7 @@ int newrm(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OP
                     conf->runtime_iml_filename,
                     conf->runtime_iml_type, 0, &count);  // TODO endian?
             if (rc != PTS_SUCCESS) {
-                fprintf(stderr, "read IMA IML, %s was failed\n", conf->runtime_iml_filename);
+                ERROR("read IMA IML, %s was failed\n", conf->runtime_iml_filename);
                 rc = PTS_INTERNAL_ERROR;
                 goto free;
             }
@@ -712,18 +868,23 @@ int newrm(OPENPTS_CONFIG *conf, int prop_count, OPENPTS_PROPERTY *prop_start, OP
         if (conf->rm_filename[i] != NULL) {
             rc = writeRm(ctx, conf->rm_filename[i], i);
             if (rc != PTS_SUCCESS) {
-                fprintf(stderr, "write RM, %s was failed\n", conf->rm_filename[i]);
+                ERROR("write RM, %s was failed\n", conf->rm_filename[i]);
                 rc = PTS_INTERNAL_ERROR;
                 goto free;
             }
-            printf("level %d Reference Manifest  : %s\n", i, conf->rm_filename[i]);
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_NEW_RM_RM, "level %d Reference Manifest: %s\n"), i, conf->rm_filename[i]);
         } else {
             ERROR("missing RM file for level %d\n", i);
         }
     }
-    // printf("\nptsc is successfully initialized!\n");
+    // OUTPUT("\nptsc is successfully initialized!\n");
 
  free:
+
+    if ( rc == PTS_INTERNAL_ERROR ) {
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_NEW_RM_FAILED, "Failed to generate Reference Manifest\n"));
+    }
+
     /* free */
     freePtsContext(ctx);
 
@@ -743,20 +904,21 @@ int printCollectorStatus(OPENPTS_CONFIG *conf) {
 
     ctx = newPtsContext(conf);
 
-    printf("%s version %s \n\n", PACKAGE, VERSION);
-
-    printf("config file                 : %s\n", conf->config_file);
-    /* UUID */
-    printf("UUID                        : %s (%s)\n", ctx->conf->uuid->str, conf->uuid->filename);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_HEADER,
+               "%s version %s\n\n"
+               "config file: %s\n"
+               "UUID: %s (%s)\n"),
+           PACKAGE, VERSION, conf->config_file, ctx->conf->uuid->str, conf->uuid->filename);
 
     /* IML */
     if (conf->iml_mode == 0) {
-        printf("IML access mode             : TSS\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_IML_1, "IML access mode             : TSS\n"));
     } else if (conf->iml_mode == 1) {
-        printf("IML access                  : SecurityFS\n");
-        printf("  BIOS IML file             : %s\n", conf->bios_iml_filename);
-        printf("  Runtime IML file          : %s\n", conf->runtime_iml_filename);
-        printf("  PCR file                  : %s\n", conf->pcrs_filename);
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_IML_2,
+               "IML access: SecurityFS\n"
+               "  BIOS IML file: %s\n"
+               "  Runtime IML file: %s\n"
+               "  PCR file: %s\n"), conf->bios_iml_filename, conf->runtime_iml_filename, conf->pcrs_filename);
     } else {
         ERROR("unknown IML mode, %d\n", conf->iml_mode);
     }
@@ -764,36 +926,46 @@ int printCollectorStatus(OPENPTS_CONFIG *conf) {
     /* Linux IMA mode */
     switch (conf->runtime_iml_type) {
     case BINARY_IML_TYPE_IMA_ORIGINAL:
-        printf("  Runtime IML type          : Linux-IMA patch (kernel 2.6.18-2.6.29)\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_KERN_1,
+            "  Runtime IML type: Linux-IMA patch (kernel 2.6.18-2.6.29)\n"));
         break;
     case BINARY_IML_TYPE_IMA_31:
-        printf("  Runtime IML type          : IMA (kernel 2.6.30-31)\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_KERN_2,
+            "  Runtime IML type: IMA (kernel 2.6.30-31)\n"));
         break;
     case BINARY_IML_TYPE_IMA:
-        printf("  Runtime IML type          : IMA (kernel 2.6.32)\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_KERN_3,
+            "  Runtime IML type: IMA (kernel 2.6.32)\n"));
         break;
     case BINARY_IML_TYPE_IMA_NG:
-        printf("  Runtime IML type          : IMA NG (kernel 2.6.XX)\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_KERN_4,
+            "  Runtime IML type: IMA NG (kernel 2.6.XX)\n"));
         break;
     case BINARY_IML_TYPE_IMA_NGLONG:
-        printf("  Runtime IML type          : IMA NG LONG (kernel 2.6.XX)\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_KERN_5,
+            "  Runtime IML type: IMA NG LONG (kernel 2.6.XX)\n"));
         break;
     default:
-        printf("  Runtime IML type          : unknown type 0x%x\n", conf->runtime_iml_type);
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_KERN_6,
+            "  Runtime IML type: unknown type 0x%x\n"), conf->runtime_iml_type);
         break;
     }  // switch
 
     /* Reference Manifest */
 
     /* UUID of this platform */
-    printf("RM UUID (current)           : %s\n", conf->rm_uuid->str);
-    printf("RM UUID (for next boot)     : %s\n", conf->newrm_uuid->str);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_RM_UUID_CUR,
+        "RM UUID (current): %s\n"), conf->rm_uuid->str);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_RM_UUID_NEXT,
+        "RM UUID (for next boot): %s\n"), conf->newrm_uuid->str);
 
     /* List RMs */
     getRmList(conf, conf->config_dir);
-    printf("List of RM set              : %d RM set in config dir\n", conf->rmsets->rmset_num);
-    printRmList(conf, "                             ");
-    printf("Integrity Report            : %s\n", conf->ir_filename);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_LIST_RM,
+        "List of RM set: %d RM set in config dir\n"), conf->rmsets->rmset_num);
+    printRmList(conf, "  ");
+    // OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_IR, "Integrity Report: %s\n"), conf->ir_filename);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_IR, "Integrity Report dir: %s\n"), conf->ir_dir);
 
 
     // TODO remove ctx from readFsmFromPropFile
@@ -804,9 +976,9 @@ int printCollectorStatus(OPENPTS_CONFIG *conf) {
         goto free;
     }
 
-    printf("Model dir                   : %s\n", conf->model_dir);
-    printf("                              Behavior Models\n");
-    printFsmInfo(ctx, "                              ");
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_MODEL_DIR, "Model dir: %s\n"), conf->model_dir);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_STATUS_BEHAVIOUR_MODELS, "Behavior Models\n"));
+    printFsmInfo(ctx, "  ");
 
     /* Manifest */
 
@@ -820,4 +992,77 @@ int printCollectorStatus(OPENPTS_CONFIG *conf) {
     return rc;
 }
 
+/**
+ * Clear PTS collector
+ * delete /var/lib/openpts
+ *
+ */
+int clear(
+    OPENPTS_CONFIG *conf,
+    int force) {
+    char ans[32];
+    int ansIsYes = 0, ansIsNo = 1;
+    int rc;
+
+    /* check */
+    if (conf == NULL) {
+        ERROR("conf == NULL");
+        return PTS_FATAL;
+    }
+    if (conf->config_dir == NULL) {
+        ERROR("conf->config_dir == NULL");
+        return PTS_FATAL;
+    }
+
+#if 0
+    // lock file exist
+    /* check */
+    rc = checkDir(conf->config_dir);
+    if (rc == PTS_INTERNAL_ERROR) {
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CLEAR_FAIL_NODIR,
+            "%s is missing"), conf->config_dir);
+        return PTS_FATAL;
+    } else {
+TODO("HOGE DDD %s\n",conf->config_dir);
+    }
+
+TODO("HOGE %s\n",conf->config_dir);
+#endif
 
+    if (isatty(STDIN_FILENO) && (force == 0) ) {
+        char *lineFeed;
+        printf(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CLEAR,
+            "Clear the PTS collector [y/N]\n"));
+        if ( NULL != fgets(ans, 32, stdin) ) {
+            // strip the ending line-feed
+            if ((lineFeed = strrchr(ans, '\n')) != NULL) {
+                *lineFeed = '\0';
+            }
+
+            ansIsYes = (strcasecmp(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CLEAR_YES, "y"), ans) == 0);
+            ansIsNo = (strcasecmp(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CLEAR_NO, "n"), ans) == 0);
+            ansIsNo |= (strlen(ans) == 0);  // default answer case
+        } else {
+            ansIsYes = 0;
+            ansIsNo  = 1;
+        }
+    } else {
+        ansIsYes = force;
+        ansIsNo  = !force;
+    }
+
+    if (ansIsYes) {
+
+        rc = unlinkDir(conf->config_dir);
+        if (rc != PTS_SUCCESS) {
+            ERROR("unlinkDir(%s) fail", conf->config_dir);
+        }
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CLEAR_YES_DONE,
+            "%s has been cleared\n") , conf->config_dir);
+    } else {
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CLEAR_NO_DONE, "keep\n"));
+    }
+
+
+    return PTS_SUCCESS;
+}
index b230728..9d2dc9a 100644 (file)
@@ -46,7 +46,6 @@
  *  config.dir
  *  config.dir
  *  hostname
- *  ifm.timeout
  *  ima.validation.mode
  *  iml.aligned
  *  iml.endian
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <ctype.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 /**
  * new Target list
@@ -102,9 +103,8 @@ OPENPTS_TARGET_LIST *newTargetList(int num) {
 
     size = sizeof(OPENPTS_TARGET_LIST) + sizeof(OPENPTS_TARGET) * (num);
 
-    list = (OPENPTS_TARGET_LIST *) malloc(size);
+    list = (OPENPTS_TARGET_LIST *) xmalloc(size);
     if (list == NULL) {
-        ERROR("no memory");
         return NULL;
     }
     memset(list, 0, size);
@@ -131,17 +131,24 @@ void freeTargetList(OPENPTS_TARGET_LIST *list) {
             ERROR("no memory cnt=%d\n", i);
         } else {
             if (target->uuid != NULL) freeUuid(target->uuid);
-            if (target->str_uuid != NULL) free(target->str_uuid);
-            if (target->time != NULL) free(target->time);
-            if (target->dir != NULL) free(target->dir);
-            if (target->target_conf_filename != NULL) free(target->target_conf_filename);
+            if (target->str_uuid != NULL) xfree(target->str_uuid);
+            if (target->time != NULL) xfree(target->time);
+            if (target->dir != NULL) xfree(target->dir);
+            if (target->target_conf_filename != NULL) xfree(target->target_conf_filename);
             if (target->target_conf != NULL) {
                 // DEBUG("target->target_conf => free\n");
-                freePtsConfig((OPENPTS_CONFIG *)target->target_conf);
+                /* WORK NEEDED: freePtsConfig -> freeTargetList -> freePtsConfig .
+                        Can we have cases where freePtsConfig is called twice on
+                        the same structure?! This leads to double free errors. Set the
+                        member variable to NULL before calling so we don't get circular
+                        dependencies! */
+                OPENPTS_CONFIG *conf = target->target_conf;
+                target->target_conf = NULL;
+                freePtsConfig(conf);
             }
         }
     }
-    free(list);
+    xfree(list);
 }
 
 /**
@@ -153,9 +160,8 @@ OPENPTS_CONFIG * newPtsConfig() {
     // DEBUG("newPtsConfig()\n");
 
     /* config */
-    conf = (OPENPTS_CONFIG *) malloc(sizeof(OPENPTS_CONFIG));
+    conf = (OPENPTS_CONFIG *) xmalloc(sizeof(OPENPTS_CONFIG));
     if (conf == NULL) {
-        ERROR("newPtsConfig - no memory\n");
         return NULL;
     }
     memset(conf, 0, sizeof(OPENPTS_CONFIG));
@@ -171,8 +177,6 @@ OPENPTS_CONFIG * newPtsConfig() {
     // set by configure.in
     conf->openpts_pcr_index = OPENPTS_PCR_INDEX;
 
-    conf->ifm_timeout = PTSC_IFM_TIMEOUT;
-
     return conf;
 }
 
@@ -184,144 +188,296 @@ int freePtsConfig(OPENPTS_CONFIG * conf) {
     int i;
     // DEBUG("freePtsConfig()\n");
 
-    if (conf == NULL) {
-        ERROR("conf is NULL\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != conf, "conf is NULL\n");
 
     if (conf->config_dir != NULL) {
-        free(conf->config_dir);
+        xfree(conf->config_dir);
+        conf->config_dir = NULL;
     }
 
     if (conf->bios_iml_filename != NULL) {
-        free(conf->bios_iml_filename);
+        xfree(conf->bios_iml_filename);
+        conf->bios_iml_filename = NULL;
     }
 
     if (conf->runtime_iml_filename != NULL) {
-        free(conf->runtime_iml_filename);
+        xfree(conf->runtime_iml_filename);
+        conf->runtime_iml_filename = NULL;
     }
 
     if (conf->pcrs_filename != NULL) {
-        free(conf->pcrs_filename);
+        xfree(conf->pcrs_filename);
+        conf->pcrs_filename = NULL;
     }
 
     if (conf->ir_filename != NULL) {
-        free(conf->ir_filename);
+        xfree(conf->ir_filename);
+        conf->ir_filename = NULL;
     }
+
     if (conf->ir_dir != NULL) {
-        free(conf->ir_dir);
+        xfree(conf->ir_dir);
+        conf->ir_dir = NULL;
     }
 
     if (conf->prop_filename != NULL) {
-        free(conf->prop_filename);
+        xfree(conf->prop_filename);
+        conf->prop_filename = NULL;
     }
 
     if (conf->model_dir != NULL) {
         // TODO double free
-        free(conf->model_dir);
+        xfree(conf->model_dir);
+        conf->model_dir = NULL;
     }
 
     if (conf->verifier_logging_dir != NULL) {
         // TODO dounle free
-        free(conf->verifier_logging_dir);
+        xfree(conf->verifier_logging_dir);
+        conf->verifier_logging_dir = NULL;
     }
+
     if (conf->policy_filename != NULL) {
-        free(conf->policy_filename);
+        xfree(conf->policy_filename);
+        conf->policy_filename = NULL;
     }
 
 #ifdef CONFIG_AIDE
     if (conf->aide_database_filename != NULL) {
-        free(conf->aide_database_filename);
+        xfree(conf->aide_database_filename);
+        conf->aide_database_filename = NULL;
     }
 #ifdef CONFIG_SQLITE
     if (conf->aide_sqlite_filename != NULL) {
-        free(conf->aide_sqlite_filename);
+        xfree(conf->aide_sqlite_filename);
+        conf->aide_sqlite_filename = NULL;
     }
 #endif  // CONFIG_SQLITE
     if (conf->aide_ignorelist_filename != NULL) {
-        free(conf->aide_ignorelist_filename);
+        xfree(conf->aide_ignorelist_filename);
+        conf->aide_ignorelist_filename = NULL;
     }
 #endif  // CONFIG_AIDE
 
-
     if (conf->pubkey != NULL) {
-        free(conf->pubkey);
+        xfree(conf->pubkey);
+        conf->pubkey = NULL;
     }
 
     if (conf->property_filename != NULL) {
-        free(conf->property_filename);
+        xfree(conf->property_filename);
+        conf->property_filename = NULL;
     }
 
     /* OPENPTS_TARGET_LIST */
     if (conf->target_list  != NULL) {
         // DEBUG("conf->target_list  != NULL => free\n");
-        freeTargetList(conf->target_list);  // conf.c
+        /* WORK NEEDED: freePtsConfig -> freeTargetList -> freePtsConfig .
+                        Can we have cases where freePtsConfig is called twice on
+                        the same structure?! This leads to double free errors. Set the
+                        member variable to NULL before calling so we don't get circular
+                        dependencies! */
+        OPENPTS_TARGET_LIST *list = conf->target_list;
+        conf->target_list = NULL;
+        freeTargetList(list);  // conf.c
     }
 
     /* UUID */
     if (conf->uuid  != NULL) {
         freeOpenptsUuid(conf->uuid);
+        conf->uuid = NULL;
     }
     /* RM UUID */
     if (conf->rm_uuid != NULL) {
         freeOpenptsUuid(conf->rm_uuid);
+        conf->rm_uuid = NULL;
     }
     /* NEWRM UUID */
     if (conf->newrm_uuid != NULL) {
         freeOpenptsUuid(conf->newrm_uuid);
+        conf->newrm_uuid = NULL;
     }
     /* OLDRM UUID */
     if (conf->oldrm_uuid != NULL) {
         freeOpenptsUuid(conf->oldrm_uuid);
+        conf->oldrm_uuid = NULL;
     }
 
     /* target UUID */
     if (conf->target_uuid  != NULL) {
-        free(conf->target_uuid);
+        xfree(conf->target_uuid);
+        conf->target_uuid = NULL;
     }
     if (conf->str_target_uuid  != NULL) {
-        free(conf->str_target_uuid);
+        xfree(conf->str_target_uuid);
+        conf->str_target_uuid = NULL;
     }
 
 
     /* RM filenames */
     for (i = 0; i< conf->rm_num; i++) {
-        if (conf->rm_filename[i] != NULL) free(conf->rm_filename[i]);
+        if (conf->rm_filename[i] != NULL) {
+            xfree(conf->rm_filename[i]);
+            conf->rm_filename[i] = NULL;
+        }
     }
     for (i = 0; i< conf->newrm_num; i++) {
-        if (conf->newrm_filename[i] != NULL) free(conf->newrm_filename[i]);
+        if (conf->newrm_filename[i] != NULL) {
+            xfree(conf->newrm_filename[i]);
+            conf->newrm_filename[i] = NULL;
+        }
     }
 
 
     /* */
     if (conf->rm_basedir != NULL) {
-        free(conf->rm_basedir);
+        xfree(conf->rm_basedir);
+        conf->rm_basedir = NULL;
     }
 
     /* */
     if (conf->hostname != NULL) {
-        free(conf->hostname);
+        xfree(conf->hostname);
+        conf->hostname = NULL;
     }
     if (conf->ssh_username != NULL) {
-        free(conf->ssh_username);
+        xfree(conf->ssh_username);
+        conf->ssh_username = NULL;
     }
     if (conf->ssh_port != NULL) {
-        free(conf->ssh_port);
+        xfree(conf->ssh_port);
+        conf->ssh_port = NULL;
     }
 
     if (conf->config_file != NULL) {
         // DEBUG("conf->config_file => free\n");
-        free(conf->config_file);
+        xfree(conf->config_file);
+        conf->config_file = NULL;
     }
 
-    free(conf);
+#ifdef CONFIG_AUTO_RM_UPDATE
+    if (conf->newRmSet != NULL) {
+        xfree(conf->newRmSet);
+        conf->newRmSet = NULL;
+    }
+#endif
+
+    for (i = 0; i < MAX_RM_NUM; i++) {
+        if (conf->compIDs[i].SimpleName != NULL) xfree(conf->compIDs[i].SimpleName);
+        if (conf->compIDs[i].ModelName != NULL) xfree(conf->compIDs[i].ModelName);
+        if (conf->compIDs[i].ModelNumber != NULL) xfree(conf->compIDs[i].ModelNumber);
+        if (conf->compIDs[i].ModelSerialNumber != NULL) xfree(conf->compIDs[i].ModelSerialNumber);
+        if (conf->compIDs[i].ModelSystemClass != NULL) xfree(conf->compIDs[i].ModelSystemClass);
+        if (conf->compIDs[i].VersionMajor != NULL) xfree(conf->compIDs[i].VersionMajor);
+        if (conf->compIDs[i].VersionMinor != NULL) xfree(conf->compIDs[i].VersionMinor);
+        if (conf->compIDs[i].VersionBuild != NULL) xfree(conf->compIDs[i].VersionBuild);
+        if (conf->compIDs[i].VersionString != NULL) xfree(conf->compIDs[i].VersionString);
+        if (conf->compIDs[i].MfgDate != NULL) xfree(conf->compIDs[i].MfgDate);
+        if (conf->compIDs[i].PatchLevel != NULL) xfree(conf->compIDs[i].PatchLevel);
+        if (conf->compIDs[i].DiscretePatches != NULL) xfree(conf->compIDs[i].DiscretePatches);
+        if (conf->compIDs[i].VendorID_Name != NULL) xfree(conf->compIDs[i].VendorID_Name);
+        if (conf->compIDs[i].VendorID_Value != NULL) xfree(conf->compIDs[i].VendorID_Value);
+    }
+
+    xfree(conf);
 
     return PTS_SUCCESS;
 }
 
+/* parse Component ID related properties */
+static int readPtsConfig_CompID(
+    OPENPTS_CONFIG *conf,
+    char *name,
+    char *value) {
+
+    char *attributeName;
+    const char *levelStr;
+    uint64_t level;
+    char **attributeValue;
 
+    /****************/
+    /* line parsing */
+    /****************/
 
+    // 01234567890123456
+    // rm.compid.0.SimpleName
+    if (strncmp(name, "rm.compid.", 10) != 0) return PTS_SUCCESS;
 
+    levelStr = name + 10;
+    level = strtoul(levelStr, &attributeName, 10);
+
+    if (levelStr == attributeName) {
+        ERROR("readPtsConfig_CompID()- invalid level number ('%s')\n", name);
+        return PTS_FATAL;
+    }
+
+    if (*attributeName != '.') {
+        ERROR("readPtsConfig_CompID()- missing '.' after level ('%s')\n", name);
+        return PTS_FATAL;
+    }
+
+    attributeName++;
+
+    /******************/
+    /* interpretation */
+    /******************/
+
+    if (level >= MAX_RM_NUM) {
+        ERROR("readPtsConfig_CompID()- trying to affect a CompID(%s) to a level(%d) greater than MAX_RM_NUM(%d)\n",
+            attributeName, level, MAX_RM_NUM);
+        return PTS_FATAL;
+    }
+
+    if      (strcmp(attributeName, "SimpleName") == 0)
+        attributeValue = &conf->compIDs[level].SimpleName;
+    else if (strcmp(attributeName, "ModelName") == 0)
+        attributeValue = &conf->compIDs[level].ModelName;
+    else if (strcmp(attributeName, "ModelNumber") == 0)
+        attributeValue = &conf->compIDs[level].ModelNumber;
+    else if (strcmp(attributeName, "ModelSerialNumber") == 0)
+        attributeValue = &conf->compIDs[level].ModelSerialNumber;
+    else if (strcmp(attributeName, "ModelSystemClass") == 0)
+        attributeValue = &conf->compIDs[level].ModelSystemClass;
+    else if (strcmp(attributeName, "VersionMajor") == 0)
+        attributeValue = &conf->compIDs[level].VersionMajor;
+    else if (strcmp(attributeName, "VersionMinor") == 0)
+        attributeValue = &conf->compIDs[level].VersionMinor;
+    else if (strcmp(attributeName, "VersionBuild") == 0)
+        attributeValue = &conf->compIDs[level].VersionBuild;
+    else if (strcmp(attributeName, "VersionString") == 0)
+        attributeValue = &conf->compIDs[level].VersionString;
+    else if (strcmp(attributeName, "MfgDate") == 0)
+        attributeValue = &conf->compIDs[level].MfgDate;
+    else if (strcmp(attributeName, "PatchLevel") == 0)
+        attributeValue = &conf->compIDs[level].PatchLevel;
+    else if (strcmp(attributeName, "DiscretePatches") == 0)
+        attributeValue = &conf->compIDs[level].DiscretePatches;
+    else if (strcmp(attributeName, "VendorID_Name") == 0)
+        attributeValue = &conf->compIDs[level].VendorID_Name;
+    else if (strcmp(attributeName, "TcgVendorId") == 0) {
+        conf->compIDs[level].VendorID_type = VENDORID_TYPE_TCG;
+        attributeValue = &conf->compIDs[level].VendorID_Value;
+    } else if (strcmp(attributeName, "SmiVendorId") == 0) {
+        conf->compIDs[level].VendorID_type = VENDORID_TYPE_SMI;
+        attributeValue = &conf->compIDs[level].VendorID_Value;
+    } else if (strcmp(attributeName, "VendorGUID") == 0) {
+        conf->compIDs[level].VendorID_type = VENDORID_TYPE_GUID;
+        attributeValue = &conf->compIDs[level].VendorID_Value;
+    } else {
+        ERROR("unknown Component ID attribute: '%s'\n", attributeName);
+        return PTS_FATAL;
+    }
+
+    if (*attributeValue != NULL) {
+        xfree(*attributeValue);
+    }
+    *attributeValue = smalloc(value);
+    if (*attributeValue == NULL) {
+        return PTS_FATAL;
+    }
+
+    return PTS_SUCCESS;
+}
 
 /**
  * Read pts config file
@@ -344,14 +500,13 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
     FILE *fp;
     char line[LINE_BUF_SIZE];
     char *eq;
-    char *name;
-    char *value = NULL;
-    // char *config_path = NULL;
     int cnt = 1;
-    int len;
     char *path;
     char *filename2 = NULL;  // fullpath
     int buf_len;
+    int isFileFound = 0;
+    int isFileIncorrect = 0;
+
 
     DEBUG("readPtsConfig()            : %s\n", filename);
 
@@ -373,24 +528,22 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
         filename2 = smalloc(filename);
     }
     if (filename2 == NULL) {
-        ERROR("no memory?\n");
         return PTS_INTERNAL_ERROR;
     }
 
     /* set config filename (fullpath) to conf*/
     if (conf->config_file != NULL) {
         /* replace, free old conf path */
-        free(conf->config_file);
+        xfree(conf->config_file);
     }
-    conf->config_file = smalloc(filename2);
+    conf->config_file = smalloc_assert(filename2);
 
     /* dir where config file -> config_dir */
     if (conf->config_dir != NULL) {
         // free old one
-        free(conf->config_dir);
+        xfree(conf->config_dir);
     }
     conf->config_dir = getFullpathDir(filename2);
-    // config_path  = conf->config_dir;
 
 
     /* open */
@@ -400,17 +553,28 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
         goto free;
     }
 
-    /* parse */
+    isFileFound = 1;
 
+    /* parse */
     while (fgets(line, LINE_BUF_SIZE, fp) != NULL) {  // read line
-        // DEBUG("\t%s", line);
-        /* ignore comment, null line */
+        size_t line_len;
+        line_len = strlen(line);
+
+        /* check for line length */
+        if (line_len == LINE_BUF_SIZE) {
+            ERROR("Line too long in %s at line %d\n", filename2, cnt);
+            isFileIncorrect = 1;
+            goto free;
+        }
+
+        /* strip trailing CR */
+        if (line[line_len-1] == '\n') line[--line_len] = '\0';
+
         if (line[0] == '#') {
-            // comment
+            // comment -> skip
         } else if ((eq = strstr(line, "=")) != NULL) { /* name=value line*/
-            /* remove CR */
-            len = strlen(line);
-            if (line[len-1] == 0x0a) line[len-1] = 0;
+            char *name;
+            char *value;
 
             name = line;
             value = eq + 1;
@@ -428,12 +592,12 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 if (value[0] != '/') {
                     /* => get fullpath */
                     path = getFullpathName(conf->config_dir, value);
-                    free(conf->config_dir);
+                    xfree(conf->config_dir);
                     conf->config_dir = path;
                 } else {
                     /* started by /, seems full path, just replace */
-                    free(conf->config_dir);
-                    conf->config_dir = smalloc(value);
+                    xfree(conf->config_dir);
+                    conf->config_dir = smalloc_assert(value);
                 }
             }
 
@@ -450,7 +614,9 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 } else if (!strncmp(value, "tss", 3)) {
                     conf->iml_mode = 0;
                 } else {
-                    ERROR("TBD\n");  // TODO
+                    ERROR("iml.mode is neither 'securityfs' or 'tss'\n");
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
 
@@ -465,6 +631,8 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 } else {
                     ERROR("Bad srk.password.mode flag '%s' in %s\n",
                         value, filename);
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
 
@@ -479,6 +647,8 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 } else {
                     ERROR("Bad tpm.resetdalock flag '%s' in %s\n",
                         value, filename);
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
 
@@ -492,6 +662,8 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                     DEBUG("conf->tpm_quote_type       : quote\n");
                 } else {
                     ERROR("Bad tpm.quote.type flag %s\n", value);
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
 
@@ -513,7 +685,9 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                     DEBUG("endian mode            : convert\n");
 #endif
                 } else {
-                    ERROR("\n");  // TODO
+                    ERROR("iml.endian is neither 'big' or 'little'\n");
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
 
@@ -525,13 +699,11 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
 
             /* BIOS IML */
             if (!strncmp(name, "bios.iml.file", 13)) {
-                // conf->bios_iml_filename = getFullpathName(config_path, value);
                 conf->bios_iml_filename = getFullpathName(conf->config_dir, value);
                 DEBUG("conf->bios_iml_filename    : %s\n", conf->bios_iml_filename);
             }
             /* RUNTIME IML */
             if (!strncmp(name, "runtime.iml.file", 16)) {
-                // conf->runtime_iml_filename = getFullpathName(config_path, value);
                 conf->runtime_iml_filename = getFullpathName(conf->config_dir, value);
                 DEBUG("conf->runtime_iml_filename : %s\n", conf->runtime_iml_filename);
             }
@@ -543,12 +715,13 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 } else if (!strncmp(value, "IMA", 3)) {
                     conf->runtime_iml_type = BINARY_IML_TYPE_IMA_ORIGINAL;
                 } else {
-                    ERROR("unknown runtime.iml.type %s\n", value);  // TODO
+                    ERROR("unknown runtime.iml.type %s\n", value);
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
             /* PCR */
             if (!strncmp(name, "pcrs.file", 9)) {
-                // conf->pcrs_filename = getFullpathName(config_path, value);
                 conf->pcrs_filename = getFullpathName(conf->config_dir, value);
                 DEBUG("conf->pcrs_filename        : %s\n", conf->pcrs_filename);
             }
@@ -557,42 +730,47 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
             if (!strncmp(name, "rm.basedir", 10)) {
                 if (conf->rm_basedir != NULL) {
                     // DEBUG("realloc conf->rm_basedir");  // TODO realloc happen
-                    free(conf->rm_basedir);
+                    xfree(conf->rm_basedir);
                 }
-                // conf->rm_basedir = getFullpathName(config_path, value);
                 conf->rm_basedir = getFullpathName(conf->config_dir, value);
             }
             if (!strncmp(name, "rm.num", 6)) {
                 conf->rm_num = atoi(value);
                 if (conf->rm_num > MAX_RM_NUM) {
-                    ERROR("RM number %d is larger the %d\n", conf->rm_num, MAX_RM_NUM);
+                    ERROR("RM number rm.num=%d is larger than MAX_RM_NUM=%d - truncking\n", conf->rm_num, MAX_RM_NUM);
+                    conf->rm_num = MAX_RM_NUM;
                 }
                 DEBUG("conf->rm_num               : %d\n", conf->rm_num);
             }
 
             /* IR file (verifier side) */
+            /* Depricated - we use a temporary file in /tmp on collector side */
             if (!strncmp(name, "ir.file", 7)) {
                 if (conf->ir_filename != NULL) {
                     // DEBUG("realloc conf->ir_filename");  // TODO realloc happen
-                    free(conf->ir_filename);
+                    xfree(conf->ir_filename);
                 }
                 conf->ir_filename = getFullpathName(conf->config_dir, value);
                 DEBUG("conf->ir_filename          : %s\n", conf->ir_filename);
+                // ERROR("ir.file is obsolute, please use ir.dir");  /// Collectror TODO 
             }
             /* IR dir (collector side) */
             if (!strncmp(name, "ir.dir", 6)) {
                 if (conf->ir_dir != NULL) {
                     // DEBUG("realloc conf->ir_filename");  // TODO realloc happen
-                    free(conf->ir_dir);
+                    xfree(conf->ir_dir);
                 }
                 conf->ir_dir = getFullpathName(conf->config_dir, value);
-                DEBUG("conf->ir_filename          : %s\n", conf->ir_dir);
-            }
+                DEBUG("conf->ir_dir          : %s\n", conf->ir_dir);
+            } // BAD else {
+            //    /* set this to some sensible default value so that ptsc.c doesn't seg fault */
+            //    conf->ir_dir = smalloc("/tmp");
+            //}
 
             if (!strncmp(name, "prop.file", 9)) {
                 if (conf->prop_filename != NULL) {
                     // DEBUG("realloc conf->prop_filename");  // TODO realloc happen
-                    free(conf->prop_filename);
+                    xfree(conf->prop_filename);
                 }
                 conf->prop_filename = getFullpathName(conf->config_dir, value);
             }
@@ -610,10 +788,15 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 conf->model_dir = getFullpathName(conf->config_dir, value);
             }
 
+            if (!strncmp(name, "iml.ipl.maxcount", 16)) {
+                conf->iml_maxcount = atoi(value);
+                DEBUG("conf->iml_maxcount         : %d\n", conf->iml_maxcount);
+            }
+
             /* Verifier */
             if (!strncmp(name, "verifier.logging.dir", 20)) {
                 if (conf->verifier_logging_dir != NULL) {
-                    free(conf->verifier_logging_dir);
+                    xfree(conf->verifier_logging_dir);
                 }
                 conf->verifier_logging_dir = getFullpathName(conf->config_dir, value);
             }
@@ -622,7 +805,7 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
             if (!strncmp(name, "policy.file", 11)) {
                 if (conf->policy_filename != NULL) {
                     // DEBUG("realloc conf->policy_filename\n");  // TODO realloc happen
-                    free(conf->policy_filename);
+                    xfree(conf->policy_filename);
                 }
                 conf->policy_filename = getFullpathName(conf->config_dir, value);
             }
@@ -645,14 +828,16 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 } else if (!strncmp(value, "none", 4)) {
                     conf->ima_validation_mode = OPENPTS_VALIDATION_MODE_NONE;
                 } else {
-                    ERROR("unknown ima.validation.mode [%s]\n", value);  // TODO
+                    ERROR("unknown ima.validation.mode [%s]\n", value);
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
 #ifdef CONFIG_AIDE
             if (!strncmp(name, "aide.database.file", 18)) {
                 if (conf->aide_database_filename != NULL) {
                     // DEBUG("realloc conf->aide_database_filename\n");   // TODO realloc happen
-                    free(conf->aide_database_filename);
+                    xfree(conf->aide_database_filename);
                 }
                 conf->aide_database_filename = getFullpathName(conf->config_dir, value);
             }
@@ -664,7 +849,7 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
             if (!strncmp(name, "aide.ignorelist.file", 20)) {
                 if (conf->aide_ignorelist_filename != NULL) {
                     // DEBUG("realloc conf->aide_ignorelist_filename\n");   // TODO realloc happen
-                    free(conf->aide_ignorelist_filename);
+                    xfree(conf->aide_ignorelist_filename);
                 }
                 conf->aide_ignorelist_filename = getFullpathName(conf->config_dir, value);
             }
@@ -694,7 +879,7 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 }
                 if (conf->uuid->uuid != NULL) {
                     TODO("free conf->uuid \n");
-                    free(conf->uuid->uuid);
+                    xfree(conf->uuid->uuid);
                 }
                 /* set */
                 conf->uuid->uuid = getUuidFromString(value);
@@ -714,7 +899,7 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 }
                 if (conf->rm_uuid->filename != NULL) {
                     // DEBUG("realloc conf->rm_uuid->filename");  // TODO realloc happen
-                    free(conf->rm_uuid->filename);
+                    xfree(conf->rm_uuid->filename);
                 }
                 conf->rm_uuid->filename = getFullpathName(conf->config_dir, value);
                 conf->rm_uuid->status = OPENPTS_UUID_FILENAME_ONLY;
@@ -738,7 +923,7 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 }
                 if (conf->newrm_uuid->filename != NULL) {
                     // DEBUG("realloc conf->rm_uuid->filename");  // TODO realloc happen
-                    free(conf->newrm_uuid->filename);
+                    xfree(conf->newrm_uuid->filename);
                 }
                 conf->newrm_uuid->filename = getFullpathName(conf->config_dir, value);
                 conf->newrm_uuid->status = OPENPTS_UUID_FILENAME_ONLY;
@@ -749,7 +934,9 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                     //  DEBUG("no UUID file %s\n", conf->uuid->filename);
                     conf->newrm_uuid->status = OPENPTS_UUID_FILENAME_ONLY;
                 } else {
-                    // DEBUG("read UUID from file %s, UUID=%s\n", conf->uuid->filename, conf->uuid->str);
+                    conf->pts_flag[0] |= OPENPTS_FLAG0_NEWRM_EXIST;
+                    DEBUG("Read new RM UUID from file %s, UUID=%s. New pts_flag[0]=0x%02x\n",
+                          conf->newrm_uuid->filename, conf->newrm_uuid->str, conf->pts_flag[0]);
                 }
                 DEBUG("conf->newrm_uuid->str      : %s\n", conf->newrm_uuid->str);
             }
@@ -760,7 +947,7 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 }
                 if (conf->oldrm_uuid->filename != NULL) {
                     // DEBUG("realloc conf->oldrm_uuid->filename");  // TODO realloc happen
-                    free(conf->oldrm_uuid->filename);
+                    xfree(conf->oldrm_uuid->filename);
                 }
                 conf->oldrm_uuid->filename = getFullpathName(conf->config_dir, value);
                 conf->oldrm_uuid->status = OPENPTS_UUID_FILENAME_ONLY;
@@ -780,7 +967,7 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
             if (!strncmp(name, "target.uuid", 11)) {
                 if (conf->target_uuid != NULL) {
                     // DEBUG("realloc conf->target_uuid\n");  // TODO realloc happen
-                    free(conf->target_uuid);
+                    xfree(conf->target_uuid);
                 }
                 conf->target_uuid = getUuidFromString(value);
                 if (conf->target_uuid == NULL) {
@@ -789,7 +976,7 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                     // add string too
                     if (conf->str_target_uuid != NULL) {
                         // DEBUG("realloc conf->str_target_uuid\n");  // TODO realloc happen
-                        free(conf->str_target_uuid);
+                        xfree(conf->str_target_uuid);
                     }
                     conf->str_target_uuid = getStringOfUuid(conf->target_uuid);
                     if (conf->str_target_uuid == NULL) {
@@ -797,10 +984,11 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                     }
                 }
             }
+
             /* PUBKEY */
             if (!strncmp(name, "target.pubkey", 13)) {
                 if (conf->pubkey != NULL) {
-                    free(conf->pubkey);
+                    xfree(conf->pubkey);
                 }
                 conf->pubkey = decodeBase64(
                     (char *)value,
@@ -821,11 +1009,11 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
             conf->ssh_port = NULL;
 
             if (!strncmp(name, "ssh.username", 12)) {
-                conf->ssh_username = smalloc(value);
+                conf->ssh_username = smalloc_assert(value);
                 DEBUG("conf->ssh_username         : %s\n", conf->ssh_username);
             }
             if (!strncmp(name, "ssh.port", 8)) {
-                conf->ssh_port = smalloc(value);
+                conf->ssh_port = smalloc_assert(value);
                 DEBUG("conf->ssh_port             : %s\n", conf->ssh_port);
             }
 
@@ -833,25 +1021,12 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
             if (!strncmp(name, "hostname", 8)) {
                 if (conf->hostname != NULL) {
                     // DEBUG("realloc conf->hostname\n");  // TODO realloc happen
-                    free(conf->hostname);
+                    xfree(conf->hostname);
                 }
-                conf->hostname = smalloc(value);
+                conf->hostname = smalloc_assert(value);
                 DEBUG("conf->hostname             : %s\n", conf->hostname);
             }
 
-            /* IF-M timeout  */
-            if (!strncmp(name, "ifm.timeout", 11)) {
-                conf->ifm_timeout = atoi(value);
-                if (conf->ifm_timeout > PTSC_IFM_TIMEOUT_MAX) {
-                    DEBUG("conf->ifm_timeout          : %d => %d(MAX)\n",
-                        conf->ifm_timeout, PTSC_IFM_TIMEOUT_MAX);
-                    conf->ifm_timeout = PTSC_IFM_TIMEOUT_MAX;
-                } else {
-                    DEBUG("conf->ifm_timeout          : %d\n",
-                        conf->ifm_timeout);
-                }
-            }
-
             /* Selftest */
             if (!strncmp(name, "selftest", 8)) {
                 if (!strncmp(value, "on", 2)) {
@@ -859,7 +1034,9 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                 } else if (!strncmp(value, "off", 3)) {
                     conf->selftest = 0;  // default
                 } else {
-                    ERROR("unknown selftest %s\n", value);  // TODO
+                    ERROR("unknown selftest %s\n", value);
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
             /* Autoupdate */
@@ -872,9 +1049,17 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
                     DEBUG("conf->autoupdate           : off\n");
                 } else {
                     ERROR("unknown autoupdate %s\n", value);  // TODO
+                    isFileIncorrect = 1;
+                    goto free;
                 }
             }
 
+            /* Component IDs */
+            if ((rc = readPtsConfig_CompID(conf, name, value)) != PTS_SUCCESS) {
+                isFileIncorrect = 1;
+                goto free;
+            }
+
             /* PTSV Enrollment */
             if (!strncmp(name, "enrollment", 10)) {
                 if (!strncmp(value, "none", 4)) {
@@ -894,13 +1079,24 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
 
             cnt++;
         } else {
-            // TODO
+            /* accept only blank lines */
+            char *ptr;
+
+            ptr = line;
+            while (*ptr != '\0') {
+                if (!isspace(*ptr)) {
+                    ERROR("Syntax error in %s at line %d\n", filename2, cnt);
+                    isFileIncorrect = 1;
+                    goto free;
+                }
+                ptr++;
+            }
         }
     }
 
     if (conf->verifier_logging_dir == NULL) {
         /* set default logging dir */
-        conf->verifier_logging_dir = smalloc("~/.openpts");
+        conf->verifier_logging_dir = smalloc_assert("~/.openpts");
     }
 
 #if 0
@@ -916,17 +1112,71 @@ int readPtsConfig(OPENPTS_CONFIG *conf, char *filename) {
     }
 #endif
 
-    rc =  PTS_SUCCESS;
-
-  // close:
     fclose(fp);
 
   free:
-    if (filename2 != NULL) free(filename2);
+    if (isFileFound) {
+        if (isFileIncorrect) {
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_BAD_CONFIG_FILE, "Bad configuration file\n"));
+            rc = PTS_INTERNAL_ERROR;
+        } else {
+            /* not incorrect */
+            rc = PTS_SUCCESS;
+        }
+    } else {
+        /* not found */
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_CONFIG_MISSING, "Cannot open config file '%s'\n"), filename2);
+        rc = PTS_INTERNAL_ERROR;
+    }
+
+    if (filename2 != NULL) xfree(filename2);
 
     return rc;
 }
 
+#if 0
+static void writeTargetConf_CompID(OPENPTS_CONFIG *conf, FILE *fp) {
+    int level;
+
+    for (level = 0; level < MAX_RM_NUM; level++) {
+        if (conf->compIDs[level].SimpleName != NULL)
+            fprintf(fp, "rm.compid.%d.SimpleName=%s\n", level, conf->compIDs[level].SimpleName);
+        if (conf->compIDs[level].ModelName != NULL)
+            fprintf(fp, "rm.compid.%d.ModelName=%s\n", level, conf->compIDs[level].ModelName);
+        if (conf->compIDs[level].ModelNumber != NULL)
+            fprintf(fp, "rm.compid.%d.ModelNumber=%s\n", level, conf->compIDs[level].ModelNumber);
+        if (conf->compIDs[level].ModelSerialNumber != NULL)
+            fprintf(fp, "rm.compid.%d.ModelSerialNumber=%s\n", level, conf->compIDs[level].ModelSerialNumber);
+        if (conf->compIDs[level].ModelSystemClass != NULL)
+            fprintf(fp, "rm.compid.%d.ModelSystemClass=%s\n", level, conf->compIDs[level].ModelSystemClass);
+        if (conf->compIDs[level].VersionMajor != NULL)
+            fprintf(fp, "rm.compid.%d.VersionMajor=%s\n", level, conf->compIDs[level].VersionMajor);
+        if (conf->compIDs[level].VersionMinor != NULL)
+            fprintf(fp, "rm.compid.%d.VersionMinor=%s\n", level, conf->compIDs[level].VersionMinor);
+        if (conf->compIDs[level].VersionBuild != NULL)
+            fprintf(fp, "rm.compid.%d.VersionBuild=%s\n", level, conf->compIDs[level].VersionBuild);
+        if (conf->compIDs[level].VersionString != NULL)
+            fprintf(fp, "rm.compid.%d.VersionString=%s\n", level, conf->compIDs[level].VersionString);
+        if (conf->compIDs[level].MfgDate != NULL)
+            fprintf(fp, "rm.compid.%d.MfgDate=%s\n", level, conf->compIDs[level].MfgDate);
+        if (conf->compIDs[level].PatchLevel != NULL)
+            fprintf(fp, "rm.compid.%d.PatchLevel=%s\n", level, conf->compIDs[level].PatchLevel);
+        if (conf->compIDs[level].DiscretePatches != NULL)
+            fprintf(fp, "rm.compid.%d.DiscretePatches=%s\n", level, conf->compIDs[level].DiscretePatches);
+        if (conf->compIDs[level].VendorID_Name != NULL)
+            fprintf(fp, "rm.compid.%d.VendorID_Name=%s\n", level, conf->compIDs[level].VendorID_Name);
+        if (conf->compIDs[level].VendorID_Value != NULL) {
+            fprintf(fp, "rm.compid.%d.", level);
+            switch (conf->compIDs[level].VendorID_type) {
+                case VENDORID_TYPE_TCG: fprintf(fp, "TcgVendorId="); break;
+                case VENDORID_TYPE_SMI: fprintf(fp, "SmiVendorId="); break;
+                case VENDORID_TYPE_GUID: fprintf(fp, "VendorGUID="); break;
+            }
+            fprintf(fp, "%s\n", conf->compIDs[level].VendorID_Value);
+        }
+    }
+}
+#endif
 
 /**
  * Write target conf
@@ -965,7 +1215,7 @@ int writeTargetConf(OPENPTS_CONFIG *conf, PTS_UUID *uuid, char *filename) {
             conf->pubkey_length,
             &buf_len);
         fprintf(fp, "target.pubkey=%s\n", buf);  // base64
-        free(buf);
+        xfree(buf);
     }
 
     fprintf(fp, "verifier.logging.dir=./\n");
@@ -1012,7 +1262,7 @@ int writeTargetConf(OPENPTS_CONFIG *conf, PTS_UUID *uuid, char *filename) {
     fprintf(fp, "hostname=%s\n", conf->hostname);
 
     fclose(fp);
-    free(str_uuid);
+    xfree(str_uuid);
 
     return rc;
 }
@@ -1097,30 +1347,22 @@ int readOpenptsConf(OPENPTS_CONFIG *conf, char *filename) {
  */
 int setModelFile(OPENPTS_CONFIG *conf, int index, int level, char *filename) {
     /* check */
-    if (conf == NULL) {
-        ERROR("setModelFile()- conf is NULL\n");
-        return PTS_INTERNAL_ERROR;
+    ASSERT(NULL != conf, "setModelFile()- conf is NULL\n");
+
+    if (level >= MAX_RM_NUM) {
+        ERROR("setModelFile()- PCR[%d] trying to affect a model file(%s) to a level(%d) greater than MAX_RM_NUM(%d)\n",
+        index, filename, level, MAX_RM_NUM);
+        return PTS_FATAL;
     }
 
-    if (level == 0) {
-        /* Platform */
-        if (conf->platform_model_filename[index] != NULL) {
-            /* free previous filename */
-            free(conf->platform_model_filename[index]);
-        }
-        /* copy */
-        conf->platform_model_filename[index] = smalloc(filename);
-    } else if (level == 1) {
-        /* Runtime */
-        if (conf->runtime_model_filename[index] != NULL) {
-            /* free previous filename */
-            free(conf->runtime_model_filename[index]);
-        }
-        /* copy */
-        conf->runtime_model_filename[index] = smalloc(filename);
-    } else {
-        ERROR("setModelFile()- conf is NULL\n");
-        return PTS_INTERNAL_ERROR;
+    if (conf->model_filename[level][index] != NULL) {
+        xfree(conf->model_filename[level][index]);
+    }
+
+    conf->model_filename[level][index] = smalloc(filename);
+
+    if (conf->model_filename[level][index] == NULL) {
+        return PTS_FATAL;
     }
 
     return PTS_SUCCESS;
index f534591..d65a2ba 100644 (file)
--- a/src/ctx.c
+++ b/src/ctx.c
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <ctype.h>
+
 #include <openssl/sha.h>
+
 #include <openpts.h>
 
 /**
@@ -46,9 +49,8 @@ OPENPTS_CONTEXT  * newPtsContext(OPENPTS_CONFIG *conf) {
 
     DEBUG_CAL("newPtsContext - start\n");
 
-    ctx = (OPENPTS_CONTEXT *) malloc(sizeof(OPENPTS_CONTEXT));
+    ctx = (OPENPTS_CONTEXT *) xmalloc(sizeof(OPENPTS_CONTEXT));
     if (ctx == NULL) {
-        ERROR("newPtsContext - no memory");
         return NULL;
     }
     memset(ctx, 0, sizeof(OPENPTS_CONTEXT));
@@ -62,7 +64,6 @@ OPENPTS_CONTEXT  * newPtsContext(OPENPTS_CONFIG *conf) {
     /* IF-M nonce */
     ctx->nonce = newNonceContext();
     if (ctx->nonce == NULL) {
-        ERROR("newPtsContext - no memory\n");
         goto error;
     }
 
@@ -71,7 +72,7 @@ OPENPTS_CONTEXT  * newPtsContext(OPENPTS_CONFIG *conf) {
     return ctx;
 
   error:
-    free(ctx);
+    xfree(ctx);
     return NULL;
 }
 
@@ -82,6 +83,7 @@ OPENPTS_CONTEXT  * newPtsContext(OPENPTS_CONFIG *conf) {
  * TODO(munetoh) check memory leak
  */
 int freePtsContext(OPENPTS_CONTEXT *ctx) {
+    int i;
     DEBUG_CAL("freePtsContext - start\n");
 
     if (ctx == NULL) {
@@ -95,31 +97,31 @@ int freePtsContext(OPENPTS_CONTEXT *ctx) {
     /* PCRs - free, malloc at ifm.c */
     if (ctx->pcrs != NULL) {
         if (ctx->pcrs->pcr_select_byte != NULL) {
-            free(ctx->pcrs->pcr_select_byte);
+            xfree(ctx->pcrs->pcr_select_byte);
         }
-        free(ctx->pcrs);
+        xfree(ctx->pcrs);
     }
 
     /* Quote - free, malloc at ifm.c, ir.c */
     if (ctx->validation_data != NULL) {
         if (ctx->validation_data->rgbExternalData != NULL) {
-            free(ctx->validation_data->rgbExternalData);
+            xfree(ctx->validation_data->rgbExternalData);
         }
         if (ctx->validation_data->rgbData != NULL) {
-            free(ctx->validation_data->rgbData);
+            xfree(ctx->validation_data->rgbData);
         }
         if (ctx->validation_data->rgbValidationData != NULL) {
-            free(ctx->validation_data->rgbValidationData);
+            xfree(ctx->validation_data->rgbValidationData);
         }
-        free(ctx->validation_data);
+        xfree(ctx->validation_data);
     }
 
     /* UUIDs */
     if (ctx->uuid != NULL) {
-        free(ctx->uuid);
+        xfree(ctx->uuid);
     }
     if (ctx->str_uuid != NULL) {
-        free(ctx->str_uuid);
+        xfree(ctx->str_uuid);
     }
 
     /* IML - reset & free */
@@ -144,7 +146,7 @@ int freePtsContext(OPENPTS_CONTEXT *ctx) {
 
     /* IF-M - free */
     if (ctx->read_msg != NULL) {
-        free(ctx->read_msg);
+        xfree(ctx->read_msg);
     }
 
     if (ctx->nonce != NULL) {
@@ -152,11 +154,28 @@ int freePtsContext(OPENPTS_CONTEXT *ctx) {
     }
 
     if (ctx->target_conf_filename != NULL) {
-        free(ctx->target_conf_filename);
+        xfree(ctx->target_conf_filename);
+    }
+
+    for (i = 0; i < MAX_RM_NUM; i++) {
+        if (ctx->compIDs[i].SimpleName != NULL) xfree(ctx->compIDs[i].SimpleName);
+        if (ctx->compIDs[i].ModelName != NULL) xfree(ctx->compIDs[i].ModelName);
+        if (ctx->compIDs[i].ModelNumber != NULL) xfree(ctx->compIDs[i].ModelNumber);
+        if (ctx->compIDs[i].ModelSerialNumber != NULL) xfree(ctx->compIDs[i].ModelSerialNumber);
+        if (ctx->compIDs[i].ModelSystemClass != NULL) xfree(ctx->compIDs[i].ModelSystemClass);
+        if (ctx->compIDs[i].VersionMajor != NULL) xfree(ctx->compIDs[i].VersionMajor);
+        if (ctx->compIDs[i].VersionMinor != NULL) xfree(ctx->compIDs[i].VersionMinor);
+        if (ctx->compIDs[i].VersionBuild != NULL) xfree(ctx->compIDs[i].VersionBuild);
+        if (ctx->compIDs[i].VersionString != NULL) xfree(ctx->compIDs[i].VersionString);
+        if (ctx->compIDs[i].MfgDate != NULL) xfree(ctx->compIDs[i].MfgDate);
+        if (ctx->compIDs[i].PatchLevel != NULL) xfree(ctx->compIDs[i].PatchLevel);
+        if (ctx->compIDs[i].DiscretePatches != NULL) xfree(ctx->compIDs[i].DiscretePatches);
+        if (ctx->compIDs[i].VendorID_Name != NULL) xfree(ctx->compIDs[i].VendorID_Name);
+        if (ctx->compIDs[i].VendorID_Value != NULL) xfree(ctx->compIDs[i].VendorID_Value);
     }
 
     /* free */
-    free(ctx);
+    xfree(ctx);
 
     DEBUG_CAL("freePtsContext - done\n");
 
@@ -182,8 +201,8 @@ char * getAlgString(int type) {
 
 /**
  * properties
- *  platform.model.pcr.1=bios_pcr1.uml
- *  runtime.model.pcr.4=grub_pcr4.uml
+ *  rm.model.0.pcr.1=bios_pcr1.uml
+ *  rm.model.0.pcr.4=grub_pcr4.uml
  *
  * snapshots
  *   level 0 = Platform(BIOS)
@@ -205,7 +224,6 @@ int readFsmFromPropFile(OPENPTS_CONTEXT *ctx, char * filename) {
 
     char buf[FSM_BUF_SIZE];
     char buf2[FSM_BUF_SIZE];
-    // char *np = NULL;
     char *eqp = NULL;
     int pcr_index;
     int level;
@@ -225,12 +243,22 @@ int readFsmFromPropFile(OPENPTS_CONTEXT *ctx, char * filename) {
 
     /* Open prop file */
     if ((fp = fopen(filename, "r")) == NULL) {
-        ERROR("File %s open was failed\n", filename);  // TODO(munetoh)
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_CONFIG_MISSING, "Cannot open config file '%s'\n"), filename);
         return PTS_OS_ERROR;
     }
 
     /* parse */
     while (fgets(buf, FSM_BUF_SIZE, fp) != NULL) {  // read line
+        len = strlen(buf);
+
+        /* check for line length */
+        if (len == FSM_BUF_SIZE) {
+            ERROR("Line too long in %s\n", filename);
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_BAD_CONFIG_FILE, "Bad configuration file\n"));
+            rc = PTS_FATAL;
+            goto error;
+        }
+
         /* ignore comment, null line */
         if (buf[0] == '#') {
             // comment
@@ -238,8 +266,7 @@ int readFsmFromPropFile(OPENPTS_CONTEXT *ctx, char * filename) {
             /* this is property line */
 
             /* remove CR */
-            len = strlen(buf);
-            if (buf[len-1] == 0x0a) buf[len-1] = 0;
+            if (buf[len-1] == '\n') buf[len-1] = '\0';
 
             model_filename = NULL;
 
@@ -248,12 +275,16 @@ int readFsmFromPropFile(OPENPTS_CONTEXT *ctx, char * filename) {
             if (strstr(buf, "platform.model.") != NULL) {
                 ERROR("ptsc.conf has old format <=v0.2.3 %s\n", filename);
                 ERROR("change platform.model to rm.model.0\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_BAD_CONFIG_FILE, "Bad configuration file\n"));
+                rc = PTS_FATAL;
                 goto error;
             }
 
             if (strstr(buf, "runtime.model.") != NULL) {
                 ERROR("ptsc.conf has old format <=v0.2.3 %s\n", filename);
                 ERROR("change runtime.model to rm.model.1\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_BAD_CONFIG_FILE, "Bad configuration file\n"));
+                rc = PTS_FATAL;
                 goto error;
             }
 #endif
@@ -261,8 +292,6 @@ int readFsmFromPropFile(OPENPTS_CONTEXT *ctx, char * filename) {
             //           1111111
             // 01234567890123456
             // rm.model.0.pcr.7
-            // if ((np = strstr(buf, "rm.model.")) != NULL) {  // 11
-            // np = 0;
             if (!strncmp(buf, "rm.model.", 9)) {
                 level = (int) strtol(&buf[9], NULL, 10);
                 pcr_index = (int) strtol(&buf[15], NULL, 10);
@@ -292,7 +321,7 @@ int readFsmFromPropFile(OPENPTS_CONTEXT *ctx, char * filename) {
                 /* setup the NEW snapshots, BIOS, GRUB */
                 ss = getNewSnapshotFromTable(ctx->ss_table, pcr_index, level);
                 if (ss == NULL) {
-                    ERROR("FSM has been assigned at %d %d  %s. check the config file\n",
+                    ERROR("FSM has been assigned at lvl=%d pcr=%d  %s. check the config file\n",
                         level, pcr_index, buf);
                     rc = PTS_FATAL;
                     goto error;
@@ -305,25 +334,34 @@ int readFsmFromPropFile(OPENPTS_CONTEXT *ctx, char * filename) {
                 // ss->pcrIndex = pcr_index;
 
                 // 2011-02-07 SM added
-                if (ctx->pcrs != NULL) {
+                if (ctx->pcrs != NULL && OPENPTS_PCR_INDEX != pcr_index) {
                     ctx->pcrs->pcr_select[pcr_index] = 1;
                 }
 
                 DEBUG_FSM("platform(level%d) pcr[%d] [%s] ss=%p\n",
                     level,
                     pcr_index,
-                    conf->platform_model_filename[pcr_index],
+                    conf->model_filename[level][pcr_index],
                     ss);
             }
         } else {
-            /* not find = */
-            // ERROR("= not found");
-            // goto err;
+            /* accept only blank lines */
+            char *ptr;
+
+            ptr = buf;
+            while (*ptr != '\0') {
+                if (!isspace(*ptr)) {
+                    ERROR("Syntax error in %s\n", filename);
+                    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_BAD_CONFIG_FILE, "Bad configuration file\n"));
+                    rc =  PTS_FATAL;
+                    goto error;
+                }
+                ptr++;
+            }
         }
     }
 
   error:
-    // ERROR("readFsmFromPropFile() - Error\n");
     fclose(fp);
 
     return rc;
index 4ce4dcb..c655a61 100644 (file)
--- a/src/fsm.c
+++ b/src/fsm.c
@@ -56,9 +56,8 @@ OPENPTS_FSM_CONTEXT *newFsmContext() {
     OPENPTS_FSM_CONTEXT *ctx = NULL;
 
     /* malloc */
-    ctx = (OPENPTS_FSM_CONTEXT *) malloc(sizeof(OPENPTS_FSM_CONTEXT));
+    ctx = (OPENPTS_FSM_CONTEXT *) xmalloc(sizeof(OPENPTS_FSM_CONTEXT));
     if (ctx == NULL) {
-        ERROR("ERROR\n");
         return NULL;
     }
     /* init */
@@ -82,10 +81,10 @@ void freeFsmTransitionChain(OPENPTS_FSM_Transition *fsm_trans) {
 
     /* free */
     if (fsm_trans->digest != NULL) {
-        free(fsm_trans->digest);
+        xfree(fsm_trans->digest);
     }
 
-    free(fsm_trans);
+    xfree(fsm_trans);
 }
 
 /**
@@ -96,17 +95,14 @@ void freeFsmSubvertexChain(OPENPTS_FSM_Subvertex *fsm_sub) {
         freeFsmSubvertexChain(fsm_sub->next);
     }
 
-    free(fsm_sub);
+    xfree(fsm_sub);
 }
 
 /**
  * free FSM context
  */
 int freeFsmContext(OPENPTS_FSM_CONTEXT *ctx) {
-    if (ctx == NULL) {
-        ERROR("ERROR\n");
-        return -1;
-    }
+    ASSERT(NULL != ctx, "ctx is NULL\n");
 
     /* Transition */
     if (ctx->fsm_trans != NULL) {
@@ -123,11 +119,11 @@ int freeFsmContext(OPENPTS_FSM_CONTEXT *ctx) {
 
     /* UML filename */
     if (ctx->uml_file != NULL) {
-        free(ctx->uml_file);
+        xfree(ctx->uml_file);
         ctx->uml_file = NULL;
     }
 
-    free(ctx);
+    xfree(ctx);
     return 0;
 }
 
@@ -176,9 +172,8 @@ void addFsmSubvertex(
 
             /* malloc OPENPTS_FSM_Subvertex */
             ptr = (OPENPTS_FSM_Subvertex *)
-                    malloc(sizeof(OPENPTS_FSM_Subvertex));
+                    xmalloc(sizeof(OPENPTS_FSM_Subvertex));
             if (ptr == NULL) {
-                ERROR("addFsmSubvertex - no memory\n");
                 return;
             }
 
@@ -203,7 +198,7 @@ void addFsmSubvertex(
                 ptr->prev = ptr_pre;
             } else {
                 ERROR("\n");
-                free(ptr);  // free last one
+                xfree(ptr);  // free last one
                 return;
             }
 
@@ -271,6 +266,35 @@ char * getSubvertexId(OPENPTS_FSM_CONTEXT *ctx, char * name) {
 
 /// TRANSITION ///
 
+static char *skipWhiteSpace(char *str, int *len) {
+    char *cur = str, *end = str + *len;
+    /* skip space */
+    while (cur < end &&
+           '\0' != *cur &&
+           ' '  == *cur) {
+        cur++;
+    }
+    *len -= cur - str;
+    return cur;
+}
+
+static int isEndOfString(char *str) {
+    return '\0' == *str;
+}
+
+static char *skipParameter(char *str, int *len) {
+    char *cur = str, *end = str + *len;
+    /* skip space */
+    while (cur < end &&
+           '\0' != *cur &&
+           ' '  != *cur &&
+           ','  != *cur) {
+        cur++;
+    }
+    *len -= cur - str;
+    return cur;
+}
+
 /**
  *   <body>eventtype == 0x01, digest == base64</body>
  * -1: error
@@ -285,7 +309,7 @@ int getTypeFlag(char * cond, UINT32 *eventtype) {
     char * loc;
     int len;
     int rc = 0;
-    long int val;  // TODO uint64_t but fail to build on i386 platform
+    long int val;  // TODO uint64_t? but build fail on i386 platform
 
     len = strlen(cond);
 
@@ -299,15 +323,9 @@ int getTypeFlag(char * cond, UINT32 *eventtype) {
         loc += 9;
         len -= (loc - cond);
 
-        /* skip space */
-        while (len > 0) {
-            if (loc[0] == 0) return -1;  // end
-            else if (loc[0] == ' ') {    // space
-                loc++;
-                len--;
-            } else {
-                break;
-            }
+        loc = skipWhiteSpace(loc, &len);
+        if (isEndOfString(loc)) {
+            return -1;
         }
 
         /* operation */
@@ -326,16 +344,11 @@ int getTypeFlag(char * cond, UINT32 *eventtype) {
         loc += 2;
         len -= 2;
 
-        /* skip space */
-        while (len > 0) {
-            if (loc[0] == 0) return -1;  // end
-            else if (loc[0] == ' ') {  // space
-                loc++;
-                len--;
-            } else {
-                break;
-            }
+        loc = skipWhiteSpace(loc, &len);
+        if (isEndOfString(loc)) {
+            return -1;
         }
+
         /* value */
         // 20110117 Ubuntu i386, 0x80000002 => 7FFFFFFF, => use strtoll
         if (len > 2) {
@@ -360,7 +373,7 @@ int getTypeFlag(char * cond, UINT32 *eventtype) {
  * Return
  *   0: don't care
  *   1: valid (=binary model),  return the digest => freed at freeFsmTransitionChain()
- *   2: ignore now (=behavior model)
+ *   2: ignore now (=behavior model or ignored digests in binary model)
  *  -1: Error?
  *
  * Unit Test : check_fsm.c / test_getDigestFlag
@@ -369,7 +382,6 @@ int getTypeFlag(char * cond, UINT32 *eventtype) {
  */
 int getDigestFlag(char * cond, BYTE **digest, int *digest_size) {
     char * loc;   // loc at value
-    char * loc2;  // loc at "base64"
     int len;
     BYTE *buf;
     int buf_len;
@@ -381,21 +393,15 @@ int getDigestFlag(char * cond, BYTE **digest, int *digest_size) {
     loc = strstr(cond, "digest");
     if (loc == NULL) {  // miss
         *digest_size = 0;
-        return 0;
+        return DIGEST_FLAG_SKIP;
     } else {  // hit
         /* skip  digest */
         loc += 6;
         len -= (loc - cond);
 
-        /* skip space */
-        while (len > 0) {
-            if (loc[0] == 0) return -1;  // end
-            else if (loc[0] == ' ') {  // space
-                loc++;
-                len--;
-            } else {
-                break;
-            }
+        loc = skipWhiteSpace(loc, &len);
+        if (isEndOfString(loc)) {
+            return -1;
         }
 
         /* operation, "==" only */
@@ -406,24 +412,20 @@ int getDigestFlag(char * cond, BYTE **digest, int *digest_size) {
         if ((loc[0] == '=') && (loc[1] == '=')) {  // ==
             // operand is ==
         } else {
-            ERROR("ERROR 002 [%c%c]  not  == \n", loc[0], loc[1]);
+            ERROR("ERROR 002 [%c%c]  not  ==, (cond = %s)\n", loc[0], loc[1], cond);
             return -1;  // unknown operand
         }
         loc +=2;
         len -=2;
 
         /* skip space */
-        while (len > 0) {
-            if (loc[0] == 0) return -1;  // end
-            else if (loc[0] == ' ') {  // space
-                loc++;
-                len--;
-            } else {
-                break;
-            }
+        loc = skipWhiteSpace(loc, &len);
+        if (isEndOfString(loc)) {
+            return -1;
         }
 
         /* digest == base64 (behavior model) */
+#if 0
         loc2 = strstr(loc, "base64");
         if (loc2 != NULL) {  // HIT, temp
             /* Behavior Model */
@@ -446,6 +448,63 @@ int getDigestFlag(char * cond, BYTE **digest, int *digest_size) {
             *digest_size = SHA1_DIGEST_SIZE;
             return 1;
         }
+#endif
+        if (NULL != strstr(loc, "base64!")) {  // HIT, temp
+            /* Behavior Model */
+            return DIGEST_FLAG_IGNORE;
+        } else if (NULL != strstr(loc, "base64")) {  // HIT, temp
+            /* Behavior Model */
+            return DIGEST_FLAG_IGNORE;
+        } else if (NULL != strstr(loc, "transparent!")) {
+            /* we have been told to ignore this digest from the binary model */
+            /* and use the behaviour version instead */
+            return DIGEST_FLAG_TRANSPARENT;
+        } else {
+            /* Binary Model */
+            /* Base64 str -> BYTE[] */
+            buf = decodeBase64(
+                (char *)loc,
+                SHA1_BASE64_DIGEST_SIZE,
+                &buf_len);
+            if (buf == NULL) {
+                ERROR("decodeBase64 fail");
+                *digest = NULL;
+                *digest_size = 0;
+                return -1;
+            } else if (buf_len == SHA1_DIGEST_SIZE) {
+                *digest = buf;
+                *digest_size = SHA1_DIGEST_SIZE;
+                return DIGEST_FLAG_EQUAL;  // 1
+            } else {
+                ERROR("getDigestFlag() - decodeBase64() was failed \n");
+                xfree(buf);
+                *digest = NULL;
+                *digest_size = 0;
+                return -1;
+            }
+#if 0
+            buf = (BYTE *) xmalloc(SHA1_DIGEST_SIZE + 1);
+            if (buf == NULL) {
+                return -1;
+            }
+
+            // TODO(munetoh) get len, "<"
+            rc = decodeBase64(buf, SHA1_DIGEST_SIZE + 1, (unsigned char *)loc, SHA1_BASE64_DIGEST_SIZE);
+            if (rc == SHA1_DIGEST_SIZE) {
+                // TODO(munetoh) digest size change by alg
+                // this code is SHA1 only
+                *digest = buf;
+                *digest_size = rc;
+                return DIGEST_FLAG_EQUAL;
+            } else {
+                ERROR("getDigestFlag() - decodeBase64() was failed \n");
+                xfree(buf);
+                *digest = NULL;
+                *digest_size = 0;
+                return -1;
+            }
+#endif
+        }
     }
 }
 
@@ -459,89 +518,81 @@ int getDigestFlag(char * cond, BYTE **digest, int *digest_size) {
  *   COUNTER_FLAG_LT   1:  < name
  *   COUNTER_FLAG_GTE  2:  >= name 
  *
- *   set counter name to name 
- *
  * Unit Test : check_fsm.c / test_getCounterFlag
  */
-int getCounterFlag(char * cond, char **name) {
+int getCounterFlag(char *cond, char *name, char **flag) {
     char * loc;   // loc at value
-    char * loc2;  // loc at name
+    char * loc2;  // loc at flag
     int len;
     int rc = COUNTER_FLAG_SKIP;
 
     // DEBUG_CAL("getCounterFlag\n");
 
-    /* check */
-    if (cond == NULL) {
-        ERROR("getCounterFlag()");
-        return COUNTER_FLAG_SKIP;
-    }
+    ASSERT(cond != NULL, "Null condition found\n");
 
     len = strlen(cond);
-    loc = strstr(cond, "count");
+    loc = strstr(cond, name);
 
     if (loc == NULL) {
         /* miss */
         return 0;
     } else {
+        int param_len = 0;
         /* hit */
 
         /* skip  count */
-        loc += 5;
+        loc += strlen(name);
         len -= (loc - cond);
 
-        /* skip space */
-        while (len > 0) {
-            if (loc[0] == 0) return -1;  // end
-            else if (loc[0] == ' ') {  // space
-                loc++;
-                len--;
-            } else {
-                break;
-            }
+        loc = skipWhiteSpace(loc, &len);
+        if (isEndOfString(loc)) {
+            return -1;
         }
 
         /* operation, "&lt;" ">=" only */
         if ((len >= 2) && (loc[0] == 'l') && (loc[1] == 't')) {
-            /* >= */
+            /* <, lt */
+            // DEBUG("COUNTER_FLAG_LT");
             rc = COUNTER_FLAG_LT;
             loc +=2;
             len -=2;
         } else if ((len >= 2) && (loc[0] == '>') && (loc[1] == '=')) {
             /* >= */
+            // DEBUG("COUNTER_FLAG_GTE");
             rc = COUNTER_FLAG_GTE;
             loc +=2;
             len -=2;
         } else {
-            // ERROR("ERROR 002 [%s]  not  >= \n", &loc[0];
+            ERROR("unknown operand [%s]", &loc[0]);
             return -1;  // unknown operand
         }
 
-        /* skip space */
-        while (len > 0) {
-            if (loc[0] == 0) return -1;  // end
-            else if (loc[0] == ' ') {  // space
-                loc++;
-                len--;
-            } else {
-                break;
-            }
+        loc = skipWhiteSpace(loc, &len);
+        if (isEndOfString(loc)) {
+            return -1;
         }
 
-        // TODO check the end, this code only support if counter is the last equation
+        // TODO check the end, this code only support if counter is the last
 
-        loc2 = loc;
-        len = strlen(loc2);
+        loc2 = skipParameter(loc, &len);
+        param_len = loc2 - loc;
+        if (0 == param_len) {
+            /* we haven't moved along the string - no valid parameter found */
+            return -1;
+        }
+
+        /* DEBUG_FSM("[%d][%s][%s]\n",len, loc, loc2); */
 
-        *name = malloc(len + 1);
-        if (*name == NULL) {
-            ERROR("no memory\n");
+        *flag = xmalloc(param_len + 1);
+        if (*flag == NULL) {
             return -1;
         }
-        memset(*name, 0, len + 1);
-        memcpy(*name, loc2, len);
+        memset(*flag, 0, param_len + 1);
+        memcpy(*flag, loc, param_len);
     }
-    DEBUG_FSM("getCounterFlag cond=[%s],  prop=[%s] rc=%d (0:1:2=skip:<:>=),\n", cond,  *name, rc);
+
+    DEBUG_FSM("getCounterFlag  %s #=> %d %s\n", cond, rc, *flag);
+
     return rc;
 }
 
@@ -580,15 +631,9 @@ int getLastFlag(char * cond) {
         loc += 5;
         len -= (loc - cond);
 
-        /* skip space */
-        while (len > 0) {
-            if (loc[0] == 0) return -1;  // end
-            else if (loc[0] == ' ') {  // space
-                loc++;
-                len--;
-            } else {
-                break;
-            }
+        loc = skipWhiteSpace(loc, &len);
+        if (isEndOfString(loc)) {
+            return -1;
         }
 
         /* operation, "&lt;" ">=" only */
@@ -607,15 +652,9 @@ int getLastFlag(char * cond) {
             return -1;  // unknown operand
         }
 
-        /* skip space */
-        while (len > 0) {
-            if (loc[0] == 0) return -1;  // end
-            else if (loc[0] == ' ') {  // space
-                loc++;
-                len--;
-            } else {
-                break;
-            }
+        loc = skipWhiteSpace(loc, &len);
+        if (isEndOfString(loc)) {
+            return -1;
         }
 
         /* value */
@@ -676,31 +715,31 @@ int addFsmTransition(
 
             /* malloc OPENPTS_FSM_Transition */
             ptr = (OPENPTS_FSM_Transition *)
-                    malloc(sizeof(OPENPTS_FSM_Transition));
+                    xmalloc(sizeof(OPENPTS_FSM_Transition));
             if (ptr == NULL) {
-                ERROR("no memory\n");
                 return PTS_INTERNAL_ERROR;
             }
             /* init */
             memset(ptr, 0, sizeof(OPENPTS_FSM_Transition));
             memcpy(ptr->source, source, FSM_BUF_SIZE);
             memcpy(ptr->target, target, FSM_BUF_SIZE);
-            // memcpy(ptr->cond, cond, FSM_BUF_SIZE);
             ptr->num = ctx->transition_num;
             if (cond == NULL) {
                 ptr->eventTypeFlag = 0;
-                ptr->digestFlag = 0;
+                ptr->digestFlag = DIGEST_FLAG_SKIP;
             } else if  (cond[0] == 0) {
                 ptr->eventTypeFlag = 0;
-                ptr->digestFlag = 0;
+                ptr->digestFlag = DIGEST_FLAG_SKIP;
                 memcpy(ptr->cond, cond, FSM_BUF_SIZE);
             } else {
                 // 0:don't care, 1:care
                 ptr->eventTypeFlag = getTypeFlag(cond, &ptr->eventType);
-                // 0:don't care, 1:care, 2:temp
+                // 0:don't care, 1:care, 2:temp, 3:transparent
                 ptr->digestFlag = getDigestFlag(cond, &ptr->digest, &ptr->digestSize);
                 // 0:don't care, 1:<, 2:>=
-                ptr->counter_flag = getCounterFlag(cond, &ptr->counter_name);
+                ptr->counter_flag = getCounterFlag(cond, "digest_count", &ptr->counter_name);
+                // 0:don't care, 1:<, 2:>=
+                ptr->fatal_counter_flag = getCounterFlag(cond, "fatal_count", &ptr->fatal_counter_name);
                 // 0:don't care 1: ==last 2: != last
                 ptr->last_flag = getLastFlag(cond);
                 memcpy(ptr->cond, cond, FSM_BUF_SIZE);
@@ -709,6 +748,11 @@ int addFsmTransition(
             ptr->source_subvertex = getSubvertex(ctx, ptr->source);
             ptr->target_subvertex = getSubvertex(ctx, ptr->target);
 
+            if (DIGEST_FLAG_TRANSPARENT == ptr->digestFlag) {
+                DEBUG_FSM("Found transparent digest\n");
+                ctx->numTransparencies++;
+            }
+
             /* ptr */
             ptr->next = NULL;
             if (ctx->transition_num == 0) {
@@ -720,7 +764,7 @@ int addFsmTransition(
                 ptr->next = NULL;  // last trans
             } else {
                 ERROR("\n");
-                free(ptr);  // free last one
+                xfree(ptr);  // free last one
                 return PTS_INTERNAL_ERROR;
             }
             ctx->transition_num++;
@@ -747,9 +791,8 @@ char *getEventString(OPENPTS_PCR_EVENT_WRAPPER *eventWrapper) {
     char *buf;
 
     /* malloc */
-    buf = malloc(size);
+    buf = xmalloc(size);
     if (buf == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
 
@@ -759,7 +802,7 @@ char *getEventString(OPENPTS_PCR_EVENT_WRAPPER *eventWrapper) {
         // len = snprintf(buf, size, "PCR[%d],TYPE=%d", (int)event->ulPcrIndex, event->eventType);
     } else {
         ERROR("NULL event\n");  // TODO(munetoh)
-        free(buf);
+        xfree(buf);
         return NULL;
     }
 
@@ -820,7 +863,7 @@ int updateFsm(
     TSS_PCR_EVENT *event;
     int type_check;
     int digest_check;
-    int counter_check;
+    int fatal_counter_check;
     int last_check;
     int dont_care;
     int hit = 0;
@@ -843,7 +886,7 @@ int updateFsm(
 
         /* dummy wrapper */
         eventWrapper = (OPENPTS_PCR_EVENT_WRAPPER *)
-            malloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
+            xmalloc_assert(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
         memset(eventWrapper, 0, sizeof(OPENPTS_PCR_EVENT_WRAPPER));
         eventWrapper->event_type = OPENPTS_DUMMY_EVENT;
         eventWrapper->push_count = 0;
@@ -859,7 +902,7 @@ int updateFsm(
         }
 
         /* free dummy wrapper */
-        free(eventWrapper);
+        xfree(eventWrapper);
         eventWrapper = NULL;
         return rc;
     } else if (eventWrapper->event == NULL) {
@@ -887,12 +930,12 @@ int updateFsm(
         fsm->level, fsm->pcr_index,
         curr_state->name, curr_state->action);
 
-    if ((event != NULL) && (verbose & DEBUG_FSM_FLAG)) {
+    if ((event != NULL) && isDebugFlagSet(DEBUG_FSM_FLAG)) {
         hex = getHexString(event->rgbPcrValue, event->ulPcrValueLength);
         DEBUG_FSM("[RM%02d-PCR%02d] eventtype=0x%x, digest=0x%s\n",
             fsm->level, fsm->pcr_index,
             event->eventType, hex);
-        free(hex);
+        xfree(hex);
     }
 
     if (eventWrapper->event_type == OPENPTS_DUMMY_EVENT) {
@@ -1074,7 +1117,8 @@ int updateFsm(
                         digest_check = -1;
                         // DEBUG_FSM("- invalid\n");
                     }
-                } else if (trans->digestFlag == DIGEST_FLAG_IGNORE) {
+                } else if (trans->digestFlag == DIGEST_FLAG_IGNORE ||
+                           trans->digestFlag == DIGEST_FLAG_TRANSPARENT) {
                     /* Behavior Model */
                     // DEBUG_FSM("digest - ignore\n");
                     digest_check = 2;
@@ -1085,47 +1129,56 @@ int updateFsm(
                 }
 
                 /* check the counter */
-                counter_check = 3;
-                if (trans->counter_flag == COUNTER_FLAG_LT) {
+                fatal_counter_check = 3;
+                if (trans->fatal_counter_flag == COUNTER_FLAG_LT) {
                     /* count < name */
-                    int count;
-                    count = getCountFromProperty(ctx, trans->counter_name);
+                    int fatal_count = getCountFromProperty(ctx, trans->fatal_counter_name);
 
-                    if (ctx->count < count) {
-                        DEBUG_FSM("COUNTER[%s] %d < %d - HIT\n",
-                            trans->counter_name, ctx->count, count);
-                        counter_check = 1;  // HIT
+                    if (ctx->count < fatal_count) {
+                        DEBUG_FSM("FATAL COUNTER %d < %d - HIT\n", ctx->count, fatal_count);
+                        fatal_counter_check = 1;  // HIT
                     } else {
-                        DEBUG_FSM("COUNTER[%s] %d < %d - MISS\n",
-                            trans->counter_name, ctx->count, count);
-                        counter_check = -1;  // MISS
+                        DEBUG_FSM("FATAL COUNTER %d < %d - MISS\n", ctx->count, fatal_count);
+                        fatal_counter_check = -1;  // MISS
                     }
-
-                } else if (trans->counter_flag == COUNTER_FLAG_GTE) {
+                } else if (trans->fatal_counter_flag == COUNTER_FLAG_GTE) {
                     /* count >= name */
-                    int count;
-                    count = getCountFromProperty(ctx, trans->counter_name);
+                    int fatal_count = getCountFromProperty(ctx, trans->fatal_counter_name);
 
                     // TODO at this moment we ignore >= condition,
-                    if (ctx->count >= count) {
-                        DEBUG_FSM("[RM%02d-PCR%02d] COUNTER[%s] %d >=  %d - HIT\n",
-                            fsm->level, fsm->pcr_index,
-                            trans->counter_name,
-                            ctx->count, count);
-                        counter_check = 1;  // HIT
+                    if (ctx->count >= fatal_count) {
+                        DEBUG_FSM("FATAL COUNTER %d >= %d - HIT\n", ctx->count, fatal_count);
+                        fatal_counter_check = 1;  // HIT
                     } else {
-                        DEBUG_FSM("COUNTER[%s] %d >=  %d - MISS\n",
-                            trans->counter_name, ctx->count, count);
-                        counter_check = -1;  // MISS
+                        DEBUG_FSM("FATAL COUNTER %d >= %d - MISS\n", ctx->count, fatal_count);
+                        fatal_counter_check = -1;  // MISS
                     }
                 } else {
                     // DEBUG_FSM("counter - don't care\n");
                 }
 
+                if (trans->counter_flag != COUNTER_FLAG_SKIP) {
+                    int thisCount = 1 + trans->event_num;
+                    int maxCount = getCountFromProperty(ctx, trans->counter_name);
+                    if (trans->counter_flag == COUNTER_FLAG_GTE &&
+                        thisCount >= maxCount) {
+                        DEBUG_FSM("DIGEST COUNTER %d >= %d ('%s') - digest is transparent\n",
+                            thisCount, maxCount, trans->counter_name);
+                        eventWrapper->transparent = 1;
+                    } else if (trans->counter_flag == COUNTER_FLAG_LT &&
+                               thisCount < maxCount) {
+                        DEBUG_FSM("DIGEST COUNTER %d < %d ('%s') - digest is transparent\n",
+                            thisCount, maxCount, trans->counter_name);
+                        eventWrapper->transparent = 1;
+                    }
+                }
 
                 /* Judge */
                 // if ((type_check == 1) && (digest_check == 1)) {
-                if ((type_check > 0) && (digest_check > 0) && (counter_check > 0) && (last_check > 0)) {
+                if ((type_check > 0) &&
+                    (digest_check > 0) &&
+                    (fatal_counter_check > 0) &&
+                    (last_check > 0)) {
                     /* Hit this Trans */
                     /* If Final state, switch to next snapshot */
                     if (!strcmp(trans->target, UML2_SD_FINAL_STATE_STRING)) {
@@ -1141,6 +1194,8 @@ int updateFsm(
                     eventWrapper->fsm_trans = trans;
                     trans->event = (void *) event;   // note) hold the last link of looped trans
                     trans->event_num++;  // # of shared trans > 1
+                    DEBUG_FSM("[RM%02d-PCR%02d] trans->event_num = %d\n",
+                        fsm->level, fsm->pcr_index, (int)trans->event_num);
                     hit = 1;
 
                     /* next trans */
@@ -1183,7 +1238,8 @@ int updateFsm(
                                 DEBUG("updateFsm - doActivity error\n");
                                 // INFO("FSM validation of doActivity() was failed.
                                 // (FSM state = %s)\n",fsm->curr_state->name);
-                                addReason(ctx, "[PCR%02d-FSM] action '%s' fail at state '%s'",
+                                addReason(ctx, fsm->pcr_index, NLS(MS_OPENPTS, OPENPTS_FSM_ACTION_FAILED,
+                                               "[PCR%02d-FSM] The action '%s' failed at state '%s'"),
                                     fsm->pcr_index, (char *)fsm->curr_state->action, fsm->curr_state->name);
                                 return rc;
                             } else if (rc == OPENPTS_FSM_MIGRATE_EVENT) {
@@ -1199,10 +1255,11 @@ int updateFsm(
                         break;
                     } else {
                         /* Trans */
-                        DEBUG_FSM("[RM%02d-PCR%02d] %s -> %s - HIT (type=%d, digest=%d) <== new curr_state\n",
+                        DEBUG_FSM("[RM%02d-PCR%02d] %s -> %s - HIT (type=%d, digest=%d)\n",
                             fsm->level, fsm->pcr_index,
-                            trans->source, trans->target, type_check, digest_check);
-
+                            trans->source,
+                            trans->target,
+                            type_check, digest_check);
                         fsm->curr_state = getSubvertex(fsm, trans->target);
 
                         if (fsm->curr_state != NULL) {
@@ -1247,7 +1304,7 @@ int updateFsm(
                                 rc = OPENPTS_FSM_SUCCESS;
                             }
                         } else {
-                            ERROR("curr_state is NULL\n");
+                            ERROR("curr_state is NULL, missing %s\n", trans->target);
                             rc = OPENPTS_FSM_ERROR;
                             return rc;
                         }
@@ -1303,9 +1360,8 @@ OPENPTS_FSM_CONTEXT *copyFsm(OPENPTS_FSM_CONTEXT *src_fsm) {
     }
 
     /* New FSM */
-    dst_fsm = (OPENPTS_FSM_CONTEXT *) malloc(sizeof(OPENPTS_FSM_CONTEXT));
+    dst_fsm = (OPENPTS_FSM_CONTEXT *) xmalloc(sizeof(OPENPTS_FSM_CONTEXT));
     if (dst_fsm  == NULL) {
-        ERROR("copyFsm - no memory\n");
         return NULL;
     }
     memcpy((void *)dst_fsm, (void *)src_fsm, sizeof(OPENPTS_FSM_CONTEXT));
@@ -1324,7 +1380,7 @@ OPENPTS_FSM_CONTEXT *copyFsm(OPENPTS_FSM_CONTEXT *src_fsm) {
     while (src_fsm_sub != NULL) {
         /* malloc new sub */
         dst_fsm_sub = (OPENPTS_FSM_Subvertex *)
-            malloc(sizeof(OPENPTS_FSM_Subvertex));
+            xmalloc_assert(sizeof(OPENPTS_FSM_Subvertex));
         /* copy */
         memcpy((void *)dst_fsm_sub,
                (void *)src_fsm_sub,
@@ -1362,7 +1418,7 @@ OPENPTS_FSM_CONTEXT *copyFsm(OPENPTS_FSM_CONTEXT *src_fsm) {
     while (src_fsm_trans != NULL) {
         /* malloc new sub */
         dst_fsm_trans = (OPENPTS_FSM_Transition *)
-            malloc(sizeof(OPENPTS_FSM_Transition));
+            xmalloc_assert(sizeof(OPENPTS_FSM_Transition));
         /* copy */
         memcpy((void *)dst_fsm_trans,
                (void *)src_fsm_trans,
@@ -1408,7 +1464,7 @@ OPENPTS_FSM_CONTEXT *copyFsm(OPENPTS_FSM_CONTEXT *src_fsm) {
 
   error:
     if (dst_fsm != NULL) {
-        free(dst_fsm);
+        xfree(dst_fsm);
     }
     return NULL;
 }
@@ -1565,10 +1621,8 @@ int insertFsmNew(
     DEBUG_FSM("insertFsm - start\n");
 
     /* check input */
-    if (fsm_trans == NULL) {
-        ERROR("ERROR fsm_trans == NULL\n");
-        return -1;
-    }
+    ASSERT(NULL != fsm_trans, "ERROR fsm_trans == NULL\n");
+
     if (fsm_trans->source_subvertex == NULL) {
         ERROR("ERROR fsm_trans->source_subvertex == NULL, %s -> %s\n",
             fsm_trans->source, fsm_trans->target);
@@ -1598,9 +1652,8 @@ int insertFsmNew(
         /* Add new subvertex, BN (->B) */
 
         new_sub = (OPENPTS_FSM_Subvertex *)
-            malloc(sizeof(OPENPTS_FSM_Subvertex));
+            xmalloc(sizeof(OPENPTS_FSM_Subvertex));
         if (new_sub == NULL) {
-            ERROR("no memory");
             return -1;
         }
         /* copy */
@@ -1644,9 +1697,8 @@ int insertFsmNew(
 
             /* malloc */
             new_trans = (OPENPTS_FSM_Transition*)
-                malloc(sizeof(OPENPTS_FSM_Transition));
+                xmalloc(sizeof(OPENPTS_FSM_Transition));
             if (new_trans == NULL) {
-                ERROR("no memory");
                 return -1;
             }
             /* copy */
@@ -1686,14 +1738,18 @@ int insertFsmNew(
             fsm_trans->copy_num++;
 
             /* Copy digest value to trans  */
-            new_trans->digestFlag = DIGEST_FLAG_EQUAL;
-            new_trans->digestSize = event->ulPcrValueLength;
-            new_trans->digest = malloc(event->ulPcrValueLength);
-            if (new_trans->digest == NULL) {
-                ERROR("no memory\n");
-                return -1;
+            if (0 == eventWrapper->transparent) {
+                new_trans->digestFlag = DIGEST_FLAG_EQUAL;
+                new_trans->digestSize = event->ulPcrValueLength;
+                new_trans->digest = xmalloc(event->ulPcrValueLength);
+                if (new_trans->digest == NULL) {
+                    return -1;
+                }
+                memcpy(new_trans->digest, event->rgbPcrValue, event->ulPcrValueLength);
+            } else {
+                DEBUG_FSM("Changing digestFlag == DIGEST_FLAG_TRANSPARENT\n");
+                new_trans->digestFlag = DIGEST_FLAG_TRANSPARENT;
             }
-            memcpy(new_trans->digest, event->rgbPcrValue, event->ulPcrValueLength);
 
             DEBUG_FSM("new  Trans BIN(%s -> %s)\n",
                       new_trans->source, new_trans->target);
@@ -1709,24 +1765,27 @@ int insertFsmNew(
                      "%s", new_sub->id);
 
             /* Copy digest value to FSM */
-            fsm_trans->digestFlag = DIGEST_FLAG_EQUAL;
-            fsm_trans->digestSize = event->ulPcrValueLength;
-            fsm_trans->digest = malloc(event->ulPcrValueLength);
-            if (fsm_trans->digest == NULL) {
-                ERROR("no memory\n");
-                return -1;
+            if (0 == eventWrapper->transparent) {
+                fsm_trans->digestFlag = DIGEST_FLAG_EQUAL;
+                fsm_trans->digestSize = event->ulPcrValueLength;
+                fsm_trans->digest = xmalloc(event->ulPcrValueLength);
+                if (fsm_trans->digest == NULL) {
+                    return -1;
+                }
+                memcpy(fsm_trans->digest, event->rgbPcrValue, event->ulPcrValueLength);
+            } else {
+                fsm_trans->digestFlag = DIGEST_FLAG_TRANSPARENT;
             }
-            memcpy(fsm_trans->digest, event->rgbPcrValue, event->ulPcrValueLength);
 
             // DEBUG_FSM("\tupdate Trans %p->%p->%p\n",
             //          fsm_trans->prev, fsm_trans, fsm_trans->next);
             DEBUG_FSM("\tUpdate Trans BIN(%s -> %s)\n",
                       fsm_trans->source, fsm_trans->target);
         } else {
-            ERROR("BAD LOOP\n");
+            ASSERT(0, "BAD LOOP\n");
         }
     } else {
-        ERROR("Not a loop");
+        ASSERT(0, "Not a loop");
     }
 
     DEBUG_FSM("insertFsm - done\n");
@@ -1813,10 +1872,7 @@ int cleanupFsm(OPENPTS_FSM_CONTEXT *fsm_ctx) {
     OPENPTS_FSM_Subvertex * sub;
     OPENPTS_FSM_Subvertex * sub_next;
 
-    if (fsm_ctx == NULL) {
-        ERROR("ERROR No FSM TRANS\n");
-        return -1;
-    }
+    ASSERT(NULL != fsm_ctx, "ERROR No FSM TRANS\n");
 
     DEBUG_FSM("cleanupFsm - start, PCR[%d]\n", fsm_ctx->pcrIndex);
 
@@ -1909,7 +1965,7 @@ int cleanupFsm(OPENPTS_FSM_CONTEXT *fsm_ctx) {
     trans = fsm_ctx->fsm_trans;
 
     if (trans == NULL) {
-        printf("ERROR No FSM TRANS\n");
+        ERROR("No FSM TRANS\n");
         return -1;
     }
 
@@ -1969,10 +2025,7 @@ int writeDotModel(OPENPTS_FSM_CONTEXT *ctx, char * filename) {
     DEBUG("writeDotModel - start %s\n", filename);
 
     /* check */
-    if (ctx == NULL) {
-        ERROR("writeDotModel() - OPENPTS_FSM_CONTEXT is NULL\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != ctx, "writeDotModel() - OPENPTS_FSM_CONTEXT is NULL\n");
 
     if (filename == NULL) {
         fp = stdout;
@@ -2090,12 +2143,14 @@ int writeCsvTable(OPENPTS_FSM_CONTEXT *ctx, char * filename) {
         }
 
 
-        if (ptr->digestFlag == 1) {
+        if (ptr->digestFlag == DIGEST_FLAG_EQUAL) {
             fprintf(fp, "digest==0x");
             // for (i=0;i<DIGEST_SIZE;i++) fprintf(fp,"%02x",ptr->digest[i]);
             fprintf(fp, ",");
-        } else if (ptr->digestFlag == 2) {
-            fprintf(fp, "digest==base64,");
+        } else if (ptr->digestFlag == DIGEST_FLAG_IGNORE) {
+            fprintf(fp, "digest==base64!,");
+        } else if (ptr->digestFlag == DIGEST_FLAG_TRANSPARENT) {
+            fprintf(fp, "digest==transparent!,");
         } else {
             fprintf(fp, ",");
         }
@@ -2120,11 +2175,11 @@ int printFsmModel(OPENPTS_FSM_CONTEXT *ctx) {
     int i, j;
     OPENPTS_FSM_Transition *ptr;
 
-    printf("ctx->transition_num = %d\n", ctx->transition_num);
-
-    printf("trans\t\tcurrent state\t\t\tcondition\t\t\\ttnext state\n");
-    printf("  id  \t\t\t\t\ttype(hex)\tdigest(hex)\n");
-    printf("----------------------------------------------------------------------------------------------\n");
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_FSM_HEADER,
+           "ctx->transition_num = %d\n"
+           "trans\t\tcurrent state\t\t\tcondition\t\t\\ttnext state\n"
+           "  id  \t\t\t\t\ttype(hex)\tdigest(hex)\n"), ctx->transition_num);
+    OUTPUT("----------------------------------------------------------------------------------------------\n");
 
 
     ptr = ctx->fsm_trans;
@@ -2133,27 +2188,30 @@ int printFsmModel(OPENPTS_FSM_CONTEXT *ctx) {
             ERROR("PTR is NULL at %d\n", i);
             return -1;
         }
-        printf("%5d ", i);
-        printf("%30s ", getSubvertexName(ctx, ptr->source));
+        OUTPUT("%5d ", i);
+        OUTPUT("%30s ", getSubvertexName(ctx, ptr->source));
 
         if (ptr->eventTypeFlag == 1) {
-            printf(" 0x%08x  ", ptr->eventType);
+            OUTPUT(" 0x%08x  ", ptr->eventType);
         } else if (ptr->eventTypeFlag == 1) {
-            printf("!0x%08x  ", ptr->eventType);
+            OUTPUT("!0x%08x  ", ptr->eventType);
         } else {
-            printf("             ");
+            OUTPUT("             ");
         }
 
-        if (ptr->digestFlag == 1) {
-            printf("0x");
-            for (j = 0; j < ptr->digestSize; j++) printf("%02x", ptr->digest[j]);
-            printf(" ");
-        } else if (ptr->digestFlag == 2) {
-            printf("base64                                     ");
+        if (ptr->digestFlag == DIGEST_FLAG_EQUAL) {
+            OUTPUT("0x");
+            for (j = 0; j < ptr->digestSize; j++) OUTPUT("%02x", ptr->digest[j]);
+            OUTPUT(" ");
+        } else if (ptr->digestFlag == DIGEST_FLAG_IGNORE) {
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_FSM_BASE64, "base64                                     "));
+        } else if (ptr->digestFlag == DIGEST_FLAG_TRANSPARENT) {
+            /* WORK NEEDED: say transparent here? */
+            OUTPUT("                                           ");
         } else {
-            printf("                                           ");
+            OUTPUT("                                           ");
         }
-        printf("%-30s\n", getSubvertexName(ctx, ptr->target));
+        OUTPUT("%-30s\n", getSubvertexName(ctx, ptr->target));
 
         ptr = ptr->next;
     }
index 75a009d..fd0a240 100644 (file)
--- a/src/ifm.c
+++ b/src/ifm.c
 #endif
 
 #include <openpts.h>
+// #include <log.h>
 
 // TODO
 #define MAX_TLV_MESSAGE_LENGTH 5120000
 
+void htoncl(uint8_t *ptr, uint32_t value) {
+    /* Convert value to network endian */
+    *ptr++ = (uint8_t)(value >> 24);
+    *ptr++ = (uint8_t)(value >> 16);
+    *ptr++ = (uint8_t)(value >> 8);
+    *ptr   = (uint8_t)(value);
+}
+
+uint32_t nctohl(uint8_t *ptr) {
+    return ((uint32_t)ptr[0] << 24) | ((uint32_t)ptr[1] << 16) |
+           ((uint32_t)ptr[2] << 8)  | ptr[3];
+}
 
 // DEBUG
 // 2011-02-24 SM make check => pass
@@ -167,9 +180,8 @@ PTS_IF_M_Attribute *readPtsTlv(int fdin) {
     memset(head, 0, 12);
 
     /* malloc TLV for read */
-    read_tlv = (PTS_IF_M_Attribute *)malloc(sizeof(PTS_IF_M_Attribute));
+    read_tlv = (PTS_IF_M_Attribute *)xmalloc(sizeof(PTS_IF_M_Attribute));
     if (read_tlv == NULL) {
-        ERROR("no memory");
         return NULL;
     }
     memset(read_tlv, 0, sizeof(PTS_IF_M_Attribute));
@@ -204,9 +216,8 @@ PTS_IF_M_Attribute *readPtsTlv(int fdin) {
     /* read msg body */
     rest = read_tlv->length;
     if (rest > 0) {
-        read_msg = (PTS_Byte *)malloc(rest + 1);
+        read_msg = (PTS_Byte *)xmalloc(rest + 1);
         if (read_msg == NULL) {
-            ERROR("no memory (size = %d)\n", rest +1);
             goto error;
         } else {
             ptr = 0;
@@ -240,7 +251,9 @@ PTS_IF_M_Attribute *readPtsTlv(int fdin) {
 
   error:
     // if (read_msg != NULL) free(read_msg);
-    if (read_tlv != NULL) freePtsTlv(read_tlv);
+    if (read_tlv != NULL) {
+        freePtsTlv(read_tlv);
+    }
     return NULL;
 }
 
@@ -255,9 +268,9 @@ void freePtsTlv(PTS_IF_M_Attribute *tlv) {
 
     /* free*/
     if (tlv->value != NULL) {
-        free(tlv->value);
+        xfree(tlv->value);
     }
-    free(tlv);
+    xfree(tlv);
 }
 
 
@@ -274,8 +287,7 @@ BYTE *getTlvBuffer(int type, int length) {
     BYTE *buf;
     PTS_IF_M_Attribute *write_tlv;
 
-    if ((buf = malloc(12 + length)) == NULL) {
-        ERROR("no memory");
+    if ((buf = xmalloc(12 + length)) == NULL) {
         return NULL;
     }
     /* setup TLV header */
@@ -314,15 +326,10 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
     DEBUG("writePtsTlvToSock - start\n");
 
     /* check */
-    if (ctx == NULL) {
-        ERROR("ctx is NULL\n");
-        return NULL;
-    }
+    ASSERT(NULL != ctx, "ctx is NULL\n");
+
     conf = ctx->conf;
-    if (conf == NULL) {
-        ERROR("conf is NULL\n");
-        return NULL;
-    }
+    ASSERT(NULL != conf, "conf is NULL\n");
 
     /* init fd[] */
     for (i = 0; i < MAX_RM_NUM; i++) {
@@ -342,16 +349,23 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
 #ifdef CONFIG_AIDE
     case REQUEST_AIDE_DATABASE:
 #endif
+//    {
         buf = getTlvBuffer(type, 0);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
         break;
+//    }
 
     /* Collector <-> Verifier */
     case OPENPTS_CAPABILITIES:
+    {
         length = sizeof(OPENPTS_IF_M_Capability);
 
         buf = getTlvBuffer(type, length);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
 
         ptr = 12;
         /* Send versions */
@@ -376,17 +390,31 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
         } else {
             memcpy(&buf[ptr + 32], ctx->conf->rm_uuid->uuid, 16);
         }
+
+        if (isFlagSet(ctx->conf->pts_flag[0], OPENPTS_FLAG0_NEWRM_EXIST) &&
+            ctx->conf->newrm_uuid != NULL &&
+            ctx->conf->newrm_uuid->uuid != NULL) {
+            memcpy(&buf[ptr + 48], ctx->conf->newrm_uuid->uuid, 16);
+        } else {
+            DEBUG("New RM unavailable -> sending platform UUID");
+            memcpy(&buf[ptr + 48], ctx->conf->uuid->uuid, 16);
+        }
+
         break;
+    }
 
 
 
     /* Collector --> Verifier */
     case TPM_PUBKEY:
+    {
         if ((ctx->conf->pubkey != NULL) && (ctx->conf->pubkey_length > 0)) {
             /* PUB key exist */
             length = ctx->conf->pubkey_length;
             buf = getTlvBuffer(type, length);
-            if (buf == NULL) goto error;
+            if (buf == NULL) {
+                goto error;
+            }
 
             /* copy PUBKEY */
             memcpy(&buf[12], ctx->conf->pubkey, ctx->conf->pubkey_length);
@@ -395,14 +423,16 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
             /* PUB key is missing */
             ERROR("writePtsTlvToSock - PUBKEY blob is missing\n");
             ctx->ifm_errno = PTS_FATAL;
-            ctx->ifm_strerror = smalloc("Piblic key is missing");
+            ctx->ifm_strerror = smalloc_assert("Public key is missing");
             length = 0;
             goto error;
         }
         break;
+    }
 
     /* Collector --> Verifier */
     case RIMM_SET:
+    {
         /* open/read RM files */
         length = 4;  // for RM num
         for (i = 0; i < conf->rm_num; i++) {
@@ -415,11 +445,14 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
                 /* send Error massage */
                 ctx->ifm_errno = PTS_FATAL;
                 ctx->ifm_strerror =
-                    smalloc("Manifest not found, initialize the collector");
+                    smalloc_assert("Manifest not found, initialize the collector");
                 goto error;
             }
             /* size */
-            fstat(fd[i], &st[i]);
+            if (-1 == fstat(fd[i], &st[i])) {
+                ERROR("fstat failed with errno %d\n", errno);
+                goto error;
+            }
             fsize[i] = st[i].st_size;
             length += 4 + fsize[i];
         }
@@ -453,14 +486,16 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
             DEBUG_IFM("RM[%d] len = %d\n", i, count[i]);
         }
         break;
+    }
 
     /* Collector --> Verifier */
     case NEW_RIMM_SET:
+    {
         /* check */
         if (conf->newrm_num == 0) {
             /* New RM is missing => send Error massage */
             ctx->ifm_errno = PTS_FATAL;
-            ctx->ifm_strerror = smalloc("New Manifest not found, check the collector");
+            ctx->ifm_strerror = smalloc_assert("New Manifest not found, check the collector");
             goto error;
         }
 
@@ -474,11 +509,14 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
                 /* send Error massage */
                 ctx->ifm_errno = PTS_FATAL;
                 ctx->ifm_strerror =
-                    smalloc("New Manifest file not found, check the collector");
+                    smalloc_assert("New Manifest file not found, check the collector");
                 goto error;
             }
             /* check the size */
-            fstat(fd[i], &st[i]);
+            if (-1 == fstat(fd[i], &st[i])) {
+                ERROR("fstat failed with errno %d\n", errno);
+                goto error;
+            }
             fsize[i] = st[i].st_size;
             length += 4 + fsize[i];
         }
@@ -487,7 +525,9 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
         DEBUG_IFM("writePtsTlv - NEW_RIMM_SET, length = %d", length);
 
         buf = getTlvBuffer(type, length);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
         ptr = 12;
 
 
@@ -514,48 +554,50 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
             DEBUG_IFM("RM[%d] len = %d\n", i, count[i]);
         }
         break;
+    }
 
     case NONCE:
+    {
         length = ctx->nonce->nonce_length;
         buf = getTlvBuffer(type, length);
         if (buf == NULL) goto error;
         memcpy(&buf[12], ctx->nonce->nonce, length);
         break;
+    }
 
     case INTEGRITY_REPORT:
-        /* generate new IR */
-        rc = genIr(ctx);
+    {
+        /* generate new IR, giving us a file descriptor corresponding
+           to an already deleted file for added security - once the file
+           gets closed you lose the IR! */
+        rc = genIr(ctx, &fd[0]);
         if (rc != PTS_SUCCESS) {
             ERROR("writePtsTlvToSock - gen IR failed\n");
             /* send Error massage */
             ctx->ifm_errno = PTS_FATAL;
-            ctx->ifm_strerror = smalloc("Generation of IR failed");
+            ctx->ifm_strerror = smalloc_assert("Generation of IR failed");
             goto error;
         }
 
         /* check the IR size */
-        fd[0] = open(ctx->conf->ir_filename, O_RDONLY);  // TODO(munetoh)
-        if (fd[0] < 0) {
-            ERROR("Error %s not found\n", ctx->conf->ir_filename);
-            /* send Error massage */
-            ctx->ifm_errno = PTS_FATAL;
-            ctx->ifm_strerror = smalloc("IR file is missing");
+        if (-1 == fstat(fd[0], &st[0])) {
+            ERROR("fstat failed with errno %d\n", errno);
             goto error;
         }
-
-        fstat(fd[0], &st[0]);
         fsize[0] = st[0].st_size;
         length = fsize[0];
-        /* close */
-        close(fd[0]);
-        fd[0] = -1;
-
 
         buf = getTlvBuffer(type, length);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
         ptr = 12;
 
-        fd[0] = open(ctx->conf->ir_filename, O_RDONLY);
+        if (-1 == lseek(fd[0], 0, SEEK_SET)) {
+            ERROR("Could not seek to start of %s (fd '%d')\n", ctx->conf->ir_filename, fd[0]);
+            goto error;
+        }
+
         count[0] = copyfile(&buf[ptr], fd[0], fsize[0]);
         if (count[0] != fsize[0]) {
             ERROR("copyfile() faild %d != %d\n", count[0], fsize[0]);
@@ -566,16 +608,18 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
         fd[0] = -1;
 
         break;
+    }
 
 #ifdef CONFIG_AIDE
     case AIDE_DATABASE:  /* AIDE DATABASE: C -> V */
+    {
         /* setup TLV header  (2/2) */
         /* body */
         if (ctx->conf->aide_database_filename == NULL) {
             // Test
             DEBUG("writePtsTlvToSock - Error AIDE DB file is not configured\n");
             ctx->ifm_errno = PTS_FATAL;
-            ctx->ifm_strerror = smalloc("AIDE DB file is not configured");
+            ctx->ifm_strerror = smalloc_assert("AIDE DB file is not configured");
             goto error;
         } else {
             fd[0] = open(ctx->conf->aide_database_filename, O_RDONLY);
@@ -585,27 +629,28 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
                     ctx->conf->aide_database_filename);
                 /* send Error massage */
                 ctx->ifm_errno = PTS_FATAL;
-                ctx->ifm_strerror = smalloc("AIDE file not found");
+                ctx->ifm_strerror = smalloc_assert("AIDE file not found");
                 goto error;
             } else {
                 /* OK */
-                fstat(fd[0], &st[0]);
+                if (-1 == fstat(fd[0], &st[0])) {
+                    ERROR("fstat failed with errno %d\n", errno);
+                    goto error;
+                }
                 fsize[0] = st[0].st_size;
                 length = fsize[0];
-                /* close */
-                close(fd[0]);
-                fd[0] = -1;
             }
         }
 
         buf = getTlvBuffer(type, length);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
         ptr = 12;
 
 
         if (length > 0) {
             // BODY1
-            fd[0] = open(ctx->conf->aide_database_filename, O_RDONLY);
             count[0] = copyfile(&buf[ptr], fd[0], fsize[0]);
             if (count[0] != fsize[0]) {
                 ERROR("copyfile() faild %d != %d\n", count[0], fsize[0]);
@@ -621,14 +666,18 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
         }
         DEBUG_IFM("writePtsTlv - AIDE_DATABASE, length = %d", length);
         break;
+    }
 #endif  // CONFIG_AIDE
 
 
     case DH_NONCE_PARAMETERS_REQUEST:  /* DH: Initiator -> Respondor */
+    {
         /* setup TLV header  (2/2) */
         length = 4;
         buf = getTlvBuffer(type, length);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
         ptr = 12;
 
         /* Send DH Nonce */
@@ -643,8 +692,10 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
 
         DEBUG_IFM("writePtsTlv - DH_NONCE_PARAMETERS_REQUEST, length = %d", length);
         break;
+    }
 
     case DH_NONCE_PARAMETORS_RESPONSE:  /* DH: IRespondor -> Initiator */
+    {
         /* setup TLV header  (2/2) */
         length =
             4 + 4 +
@@ -652,7 +703,9 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
             ctx->nonce->pubkey_length;
 
         buf = getTlvBuffer(type, length);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
         ptr = 12;
 
         /* Send DH param  */
@@ -687,8 +740,10 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
 
         DEBUG_IFM("writePtsTlv - DH_NONCE_PARAMETORS_RESPONSE, length = %d", length);
         break;
+    }
 
     case DH_NONCE_FINISH: /* DH: Initiator -> Respondor */
+    {
         /* setup TLV header  (2/2) */
         length =
             4 +
@@ -696,7 +751,9 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
             ctx->nonce->pubkey_length;
 
         buf = getTlvBuffer(type, length);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
         ptr = 12;
 
         /* Send IF-M TLV header */
@@ -724,9 +781,10 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
 
         DEBUG_IFM("writePtsTlv - DH_NONCE_FINISH, length = %d", length);
         break;
-
+    }
 
     case OPENPTS_ERROR:
+    {
         /* setup TLV header  (2/2) */
         // TODO
         if (ctx->ifm_strerror != NULL) {
@@ -736,7 +794,9 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
         }
 
         buf = getTlvBuffer(type, length);
-        if (buf == NULL) goto error;
+        if (buf == NULL) {
+            goto error;
+        }
         ptr = 12;
 
         {
@@ -759,7 +819,7 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
                 memcpy(&buf[ptr], (BYTE *)&ctx->ifm_strerror, len);
                 ptr += len;
                 /* free */
-                free(ctx->ifm_strerror);
+                xfree(ctx->ifm_strerror);
             } else {
                 size = 0;
                 memcpy(&buf[ptr], (BYTE *)&size, 4);
@@ -769,9 +829,10 @@ BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
 
         DEBUG_IFM("writePtsTlv - OPENPTS_ERROR, length = %d", length);
         break;
+    }
 
     default:
-        // BAT type
+        // BAD type
         ERROR("BAD IF-M OPENPTS MESSAGE TYPE, type=0x%x\n", type);
         return NULL;
     }
@@ -811,23 +872,6 @@ int writePtsTlv(OPENPTS_CONTEXT *ctx, int fdout, int type) {
     int length = 0;
     int len;
 
-    OPENPTS_CONFIG *conf;
-
-    /* check */
-    if (ctx == NULL) {
-        ERROR("ctx is NULL\n");
-        return -1;
-    }
-    conf = ctx->conf;
-    if (conf == NULL) {
-        ERROR("conf is NULL\n");
-        return -1;
-    }
-    if (conf->uuid == NULL) {
-        ERROR("writePtsTlvToSock() - conf->uuid is NULL\n");
-        return -1;
-    }
-
     DEBUG_CAL("writePtsTlvToSock - start\n");
 
     message = getPtsTlvMessage(ctx, type, &length);
index c00a955..cc07830 100644 (file)
--- a/src/imc.c
+++ b/src/imc.c
 #include <stdio.h>
 #include <string.h>
 
-#include <openpts.h>
-
 #include <tncifimc.h>
+#include <openpts.h>
 
 // ifm.c
 char* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len);
 
-
 /* global variables */
 static int initialized = 0;
 static TNC_IMCID id = -1;
@@ -74,7 +72,7 @@ static TNC_TNCC_SendMessagePointer           sendMessagePtr;
 static OPENPTS_CONFIG *conf = NULL;
 static OPENPTS_CONTEXT *ctx = NULL;
 
-int verbose = 0;
+// int verbose = 0;
 // int verbose = DEBUG_IFM_FLAG;
 // int verbose = DEBUG_FLAG | DEBUG_IFM_FLAG;
 
@@ -129,7 +127,7 @@ TNC_IMC_API TNC_Result TNC_IMC_Initialize(
     /* initialize PTS Collector */
     conf = newPtsConfig();
     if (conf == NULL) {
-        ERROR("Can not allocate OPENPTS_CONFIG\n");
+        // ERROR("Can not allocate OPENPTS_CONFIG\n");
         rc = TNC_RESULT_FATAL;
         goto error;
     }
@@ -200,10 +198,14 @@ TNC_IMC_API TNC_Result TNC_IMC_Initialize(
     return TNC_RESULT_SUCCESS;
 
   error:
-    if (ctx != NULL) freePtsContext(ctx);
-    ctx = NULL;
-    if (conf != NULL) freePtsConfig(conf);
-    conf = NULL;
+    if (ctx != NULL) {
+        freePtsContext(ctx);
+        ctx = NULL;
+    }
+    if (conf != NULL) {
+        freePtsConfig(conf);
+        conf = NULL;
+    }
 
     return rc;
 }
@@ -376,7 +378,7 @@ TNC_IMC_API TNC_Result TNC_IMC_ReceiveMessage(
         case NONCE:
             DEBUG_IFM("[C<-V]  NONCE[%d]\n", 12 + length);
             ctx->nonce->nonce_length = length;
-            ctx->nonce->nonce = malloc(length);
+            ctx->nonce->nonce = xmalloc_assert(length);
             memcpy(ctx->nonce->nonce, value, length);
             break;
 
index 70fc250..7c4a93e 100644 (file)
--- a/src/iml.c
+++ b/src/iml.c
 #include <stdlib.h>
 #include <string.h>
 #include <openssl/sha.h>
-#include <openpts.h>
 
+#include <openpts.h>
 
 void printEventWrapper(OPENPTS_PCR_EVENT_WRAPPER *eventWrapper);
 
-
 /**
  * reset snapshot array
  *
@@ -65,18 +64,18 @@ int resetSnapshot(OPENPTS_SNAPSHOT * snapshots) {
             event = eventWrapper->event;
             if (event != NULL) {
                 if (event->rgbPcrValue != NULL)
-                    free(event->rgbPcrValue);
+                    xfree(event->rgbPcrValue);
                 if (event->rgbEvent != NULL)
-                    free(event->rgbEvent);
-                free(event);
+                    xfree(event->rgbEvent);
+                xfree(event);
             } else {
                 ERROR("resetSnapshot - NULL event\n");  // TODO(munetoh)
             }
             eventWrapper_next = eventWrapper->next_pcr;
-            free(eventWrapper);
+            xfree(eventWrapper);
             eventWrapper = eventWrapper_next;
         }
-        // if (iml[i].eventList != NULL) free(iml[i].eventList);
+        // if (iml[i].eventList != NULL) xfree(iml[i].eventList);
         ss->pcrIndex = i;
         ss->event_num = 0;
         ss->level = 0;
@@ -93,9 +92,8 @@ int resetSnapshot(OPENPTS_SNAPSHOT * snapshots) {
 OPENPTS_PCR_EVENT_WRAPPER * newEventWrapper() {
     OPENPTS_PCR_EVENT_WRAPPER *ew;
 
-    ew = (OPENPTS_PCR_EVENT_WRAPPER *)malloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
+    ew = (OPENPTS_PCR_EVENT_WRAPPER *)xmalloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
     if (ew == NULL) {
-        ERROR("newEventWrapper() - no memory\n");
         return NULL;
     }
 
@@ -109,7 +107,7 @@ OPENPTS_PCR_EVENT_WRAPPER * newEventWrapper() {
  */
 void freeEventWrapper(OPENPTS_PCR_EVENT_WRAPPER * ew) {
     // TODO
-    free(ew);
+    xfree(ew);
 }
 
 /**
@@ -118,10 +116,7 @@ void freeEventWrapper(OPENPTS_PCR_EVENT_WRAPPER * ew) {
 void freeEventWrapperChain(OPENPTS_PCR_EVENT_WRAPPER * ew) {
     TSS_PCR_EVENT *event;
 
-    if (ew == NULL) {
-        ERROR("OPENPTS_PCR_EVENT_WRAPPE is NULL\n");
-        return;
-    }
+    ASSERT(NULL != ew, "OPENPTS_PCR_EVENT_WRAPPER is NULL\n");
 
     if (ew->next_pcr != NULL) {
         freeEventWrapperChain(ew->next_pcr);
@@ -135,14 +130,14 @@ void freeEventWrapperChain(OPENPTS_PCR_EVENT_WRAPPER * ew) {
             //    ew->index, event->ulPcrIndex, ss->level, event->eventType);
         // }
         if (event->rgbPcrValue != NULL)
-            free(event->rgbPcrValue);
+            xfree(event->rgbPcrValue);
         if (event->rgbEvent != NULL)
-            free(event->rgbEvent);
-        free(event);
+            xfree(event->rgbEvent);
+        xfree(event);
     } else {
         ERROR("freeSnapshot - NULL event\n");  // TODO(munetoh)
     }
-    free(ew);
+    xfree(ew);
     ew = NULL;
 }
 
@@ -179,10 +174,7 @@ int addEventToSnapshotBhv(
 
     DEBUG_CAL("addEventToSnapshot - start\n");
 
-    if (eventWrapper == NULL) {
-        ERROR("null eventWrapper\n");
-        return PTS_INTERNAL_ERROR;  // OPENPTS_FSM_ERROR;
-    }
+    ASSERT(NULL != eventWrapper, "addEventToSnapshotBhv - eventWrapper is NULL\n");
 
     index = eventWrapper->event->ulPcrIndex;
 
@@ -217,7 +209,9 @@ int addEventToSnapshotBhv(
             /* level 0 SS is null => check Level 1 SS */
             ss = getSnapshotFromTable(ctx->ss_table, index, 1);
             if (ss == NULL) {
-                addReason(ctx, "[PCR%02d] Snapshot(FSM) is missing for PCR%d. Please check the configuration file '%s'",
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_SNAPSHOT_MISSING,
+                    "[PCR%02d] Snapshot(FSM) is missing for PCR%d. "
+                    "Please check the configuration file '%s'"),
                     index,
                     index, ctx->conf->config_file);
                 ctx->ss_table->error[index] = PTS_INTERNAL_ERROR;
@@ -230,11 +224,12 @@ int addEventToSnapshotBhv(
                 setActiveSnapshotLevel(ctx->ss_table, index, 1);
                 active_level = 1;
                 // DEBUG_FSM("pcr%d SKIP to level 1\n", index);
-                DEBUG_FSM("[PCR%02d] RM0 -> RM1 (RM0 is missing)\n");
+                DEBUG_FSM("[PCR%02d] RM0 -> RM1 (RM0 is missing)\n", index);
             } else {
                 /* FSM is missing */
-                addReason(ctx,
-                    "[RM01-PCR%02d] FSM is missing for PCR%d, Level 1. Please check the configuration file '%s'",
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_FSM_MISSING,
+                    "[RM01-PCR%02d] FSM is missing for PCR%d, Level 1. "
+                    "Please check the configuration file '%s'"),
                     index,
                     index, ctx->conf->config_file);
                 ctx->ss_table->error[index] = PTS_INTERNAL_ERROR;
@@ -251,9 +246,9 @@ int addEventToSnapshotBhv(
             ss = getSnapshotFromTable(ctx->ss_table, index, 1);
             if (ss == NULL) {
                 /* SS is missing */
-                addReason(ctx,
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_SNAPSHOT_MISSING_2,
                     "[PCR%02d] Snapshot is missing for PCR%d for Level 0 and 1. "
-                    "Please check the configuration file '%s'",
+                    "Please check the configuration file '%s'"),
                     index,
                     index,
                     ctx->conf->config_file);
@@ -269,8 +264,8 @@ int addEventToSnapshotBhv(
                 active_level = 1;
             } else {
                 /* FSM is missing*/
-                addReason(ctx,
-                    "[RM01-PCR%02d] FSM is missing for PCR%d, Level 1. Please check the configuration file '%s'",
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_FSM_MISSING_2,
+                    "[RM01-PCR%02d] FSM is missing for PCR%d, Level 1. Please check the configuration file '%s'"),
                     index,
                     index, ctx->conf->config_file);
                 ctx->ss_table->error[index] = PTS_INTERNAL_ERROR;
@@ -283,8 +278,8 @@ int addEventToSnapshotBhv(
         if (ss == NULL) {
             /* SS is missing */
             DEBUG("ss == NULL  =>  Reason\n");
-            addReason(ctx,
-                "[RM%02d-PCR%02d] Snapshot is missing for PCR%d, Level %d. Please check the configuration file '%s'",
+            addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_SNAPSHOT_MISSING_6,
+                "[RM%02d-PCR%02d] Snapshot is missing for PCR%d, Level %d. Please check the configuration file '%s'"),
                 active_level,
                 index,
                 index,
@@ -297,8 +292,8 @@ int addEventToSnapshotBhv(
         if (ss->fsm_behavior == NULL) {
             /* FSm is missing */
             DEBUG("ss->fsm_behavior == NULL  =>  Reason\n");
-            addReason(ctx,
-                "[RM%02d-PCR%02d] FSM is missing for PCR%d, Level %d. Please check the configuration file '%s'",
+            addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_FSM_MISSING_3,
+                "[RM%02d-PCR%02d] FSM is missing for PCR%d, Level %d. Please check the configuration file '%s'"),
                 active_level,
                 index,
                 active_level,
@@ -324,13 +319,31 @@ int addEventToSnapshotBhv(
         /* FSM detect invalid IML, or bad FSM for this IML */
         DEBUG("[RM%02d-PCR%02d] updateFsm() => OPENPTS_FSM_ERROR   ===>  rc=PTS_INVALID_SNAPSHOT, added Reason\n",
             active_level, index);
-        addReason(ctx, "[RM%02d-PCR%02d] IML validation by FSM was faild. State='%s' at the FSM is '%s'",
-            active_level,
-            index,
-            ss->fsm_behavior->curr_state->name,
-            ss->fsm_behavior->uml_file);
+        if (ss->fsm_behavior->curr_state == NULL) {
+            ERROR("ss->fsm_behavior->curr_state == NULL");
+            addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_VALIDATION_FAILED,
+                           "[RM%02d-PCR%02d] IML validation by FSM has failed. State='%s' at the FSM is '%s'"),
+                active_level,
+                index,
+                "unknown",
+                ss->fsm_behavior->uml_file);
+        } else if (ss->fsm_behavior->curr_state->name == NULL) {
+            ERROR("ss->fsm_behavior->curr_state->name == NULL");
+            // TODO
+        } else if (ss->fsm_behavior->uml_file == NULL) {
+            ERROR("ss->fsm_behavior->uml_file == NULL");
+            // TODO
+        } else {
+            addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_VALIDATION_FAILED,
+                           "[RM%02d-PCR%02d] IML validation by FSM has failed. State='%s' at the FSM is '%s'"),
+                active_level,
+                index,
+                ss->fsm_behavior->curr_state->name,
+                ss->fsm_behavior->uml_file);
+        }
         ctx->ss_table->error[index] = PTS_INVALID_SNAPSHOT;
         rc = PTS_INVALID_SNAPSHOT;
+        goto end;
     } else if (rc == OPENPTS_FSM_FINISH) {
         /* OK, FSM finish successfly */
         ss->fsm_behavior->status = OPENPTS_FSM_FINISH;
@@ -404,10 +417,7 @@ int addEventToSnapshotBin(
     DEBUG_CAL("addEventToSnapshotBin - start\n");
 
     /* check */
-    if (eventWrapper == NULL) {
-        ERROR("null eventWrapper\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != eventWrapper, "null eventWrapper\n");
 
     index = eventWrapper->event->ulPcrIndex;
 
@@ -424,7 +434,7 @@ int addEventToSnapshotBin(
         /* check next level (1) */
         if (ss == NULL) {
             // ERROR("addEventToSnapshotBin() - pcr=%d Level=%d snapshots is missing\n",index, active_level);
-            addReason(ctx, "[PCR%02d] Snapshot(FSM) is missing",
+            addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_SNAPSHOT_MISSING_3, "[PCR%02d] Snapshot(FSM) is missing"),
                 index);
             ctx->ss_table->error[index] = PTS_INTERNAL_ERROR;
             return PTS_INTERNAL_ERROR;
@@ -455,21 +465,25 @@ int addEventToSnapshotBin(
             // TODO Broken FSM - 20110115 SM under ARU test
             if (ss->fsm_binary == NULL) {
                 ERROR("ss->fsm_binary == NULLn");
-                addReason(ctx,  "[RM%02d-PCR%02d-MissingFSM] IR validation by RM was faild",
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_IR_VALIDATION_FAILED_1,
+                                "[RM%02d-PCR%02d-MissingFSM] IR validation by RM has failed"),
                     active_level,
                     index);
             } else if (ss->fsm_binary->curr_state == NULL) {
                 ERROR("ss->fsm_binary->curr_state == NULL\n");
-                addReason(ctx,  "[RM%02d-PCR%02d-MissingState] IR validation by RM was faild",
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_IR_VALIDATION_FAILED_2,
+                                "[RM%02d-PCR%02d-MissingState] IR validation by RM has failed"),
                     active_level,
                     index);
-            } else if (ss->fsm_binary->curr_state->name[0] == 0) {  // TODO malloc the name
+            } else if (ss->fsm_binary->curr_state->name == NULL) {
                 ERROR("ss->fsm_binary->curr_state->name == NULL\n");
-                addReason(ctx,  "[RM%02d-PCR%02d-MissingStateName] IR validation by RM was faild",
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_IR_VALIDATION_FAILED_3,
+                                "[RM%02d-PCR%02d-MissingStateName] IR validation by RM has failed"),
                     active_level,
                     index);
             } else {
-                addReason(ctx,  "[RM%02d-PCR%02d-%s] IR validation by RM was faild",
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_IR_VALIDATION_FAILED_4,
+                                "[RM%02d-PCR%02d-%s] IR validation by RM has failed"),
                     active_level,
                     index,
                     ss->fsm_binary->curr_state->name);
@@ -485,7 +499,8 @@ int addEventToSnapshotBin(
             ss = getSnapshotFromTable(ctx->ss_table, index, 1);
             if (ss == NULL) {
                 // ERROR("no BIN-FSM at level 0,  no SS at level 1\n");
-                addReason(ctx,  "[PCR%02d] Snapshot(FSM) is missing",
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_SNAPSHOT_MISSING_4,
+                    "[PCR%02d] Snapshot(FSM) is missing"),
                     index);
                 ctx->ss_table->error[index] = PTS_INTERNAL_ERROR;
                 return PTS_INTERNAL_ERROR;
@@ -507,18 +522,20 @@ int addEventToSnapshotBin(
                     if (rc == OPENPTS_FSM_ERROR) {
                         DEBUG_FSM("No trans, return PTS_INVALID_SNAPSHOT at %s\n", ss->fsm_binary->curr_state->name);
                         DEBUG("updateFsm fail\n");
-                        addReason(ctx, "[RM%02d-PCR%02d-%s] IR validation by RM was faild",
-                            active_level + 1,
-                            index,
-                            ss->fsm_binary->curr_state->name);
+                        addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_IR_VALIDATION_FAILED_5,
+                                  "[RM%02d-PCR%02d-%s] IR validation by RM has failed"),
+                                  active_level + 1,
+                                  index,
+                                  ss->fsm_binary->curr_state->name);
                         ctx->ss_table->error[index] = PTS_INVALID_SNAPSHOT;
                         return PTS_INVALID_SNAPSHOT;
                     }
                 }
             } else {
                 ERROR("no BIN-FSM at level 0,  no BIN-FSM at level 1\n");
-                addReason(ctx, "[PCR%02d] Snapshot(FSM) is missing",
-                    index);
+                addReason(ctx, index, NLS(MS_OPENPTS, OPENPTS_IML_SNAPSHOT_MISSING_5,
+                          "[PCR%02d] Snapshot(FSM) is missing"),
+                          index);
                 ctx->ss_table->error[index] = PTS_INTERNAL_ERROR;
                 return PTS_INTERNAL_ERROR;
             }
@@ -706,10 +723,7 @@ int getIml(OPENPTS_CONTEXT * ctx, int option) {
     resetTpm(&ctx->tpm, 0);  // reset TPM DRTM=off
 
     /* check SS table */
-    if (ctx->ss_table == NULL) {
-        ERROR("SS table is null\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != ctx->ss_table, "getIml - ctx->ss_table is NULL\n");
 
     /* Connect to TCSD */
     result = Tspi_Context_Create(&hContext);
@@ -753,7 +767,7 @@ int getIml(OPENPTS_CONTEXT * ctx, int option) {
             tpe_tss = &pcrEvents[i];
 
             /* copy event to local */
-            tpe = (TSS_PCR_EVENT *) malloc(sizeof(TSS_PCR_EVENT));
+            tpe = (TSS_PCR_EVENT *) xmalloc(sizeof(TSS_PCR_EVENT));
             if (tpe == NULL) {
                 return -1;  // TODO(munetoh)
             }
@@ -761,7 +775,7 @@ int getIml(OPENPTS_CONTEXT * ctx, int option) {
             // index = tpe->ulPcrIndex;
 
             /* copy digest */
-            tpe->rgbPcrValue = (BYTE *) malloc(tpe->ulPcrValueLength);
+            tpe->rgbPcrValue = (BYTE *) xmalloc(tpe->ulPcrValueLength);
             if (tpe->rgbPcrValue == NULL) {
                 return -1;  // TODO(munetoh)
             }
@@ -771,7 +785,7 @@ int getIml(OPENPTS_CONTEXT * ctx, int option) {
 
             if (tpe->ulEventLength > 0) {
                 /* copy eventdata */
-                tpe->rgbEvent = (BYTE *) malloc(tpe->ulEventLength);
+                tpe->rgbEvent = (BYTE *) xmalloc(tpe->ulEventLength);
                 if (tpe->rgbEvent == NULL) {
                     return -1;  // TODO(munetoh)
                 }
@@ -785,9 +799,8 @@ int getIml(OPENPTS_CONTEXT * ctx, int option) {
             /* create wrapper */
             // ew_last = ew_new;
             ew_new = (OPENPTS_PCR_EVENT_WRAPPER *)
-                malloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
+                xmalloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
             if (ew_new == NULL) {
-                ERROR("no memory\n");
                 return -1;
             }
             memset(ew_new, 0, sizeof(OPENPTS_PCR_EVENT_WRAPPER));
@@ -842,8 +855,8 @@ int getIml(OPENPTS_CONTEXT * ctx, int option) {
 
     if (error > 0) {
         char buf[BUF_SIZE];
-        snprintf(buf, BUF_SIZE, "[IML] Load IML (via TSS) was faild");
-        addReason(ctx, buf);
+        snprintf(buf, BUF_SIZE, NLS(MS_OPENPTS, OPENPTS_IML_LOAD_FAILED, "[IML] Load IML (via TSS) has failed"));
+        addReason(ctx, -1, buf);
         return PTS_INVALID_SNAPSHOT;
     }
 
@@ -935,15 +948,8 @@ int readBiosImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int mode) {
     DEBUG_CAL("getBiosImlFile - start\n");
     // DEBUG("read BIOS IML, file %s\n", filename);
 
-    /* check */
-    if (ctx == NULL) {
-        ERROR("ERROR\n");  // TODO(munetoh)
-        return PTS_INTERNAL_ERROR;
-    }
-    if (filename == NULL) {
-        ERROR("ERROR\n");  // TODO(munetoh)
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != ctx, "ERROR\n");  // TODO(munetoh)
+    ASSERT(NULL != filename, "ERROR\n");  // TODO(munetoh)
 
     /* open file */
     if ((fp = fopen(filename, "rb")) == NULL) {
@@ -953,6 +959,7 @@ int readBiosImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int mode) {
 
     // TODO
     if (mode == USE_BHV_FSM_EC) {
+        DEBUG("endian=1, aligned=4\n");
         mode = USE_BHV_FSM;
         endian = 1;  // TODO conf->iml_endian?
         aligned = 4;  // TODO conf->iml_aligned?
@@ -967,7 +974,7 @@ int readBiosImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int mode) {
             break;
         }
         if (pcrIndex > MAX_PCRNUM) {
-            ERROR("BIOS IML File %s, bad pcr index value %d at %d event\n",
+            DEBUG("BIOS IML File %s, bad pcr index value %d at %d event\n",
                 filename, pcrIndex, i);
             rc = PTS_INTERNAL_ERROR;
             goto close;
@@ -975,9 +982,9 @@ int readBiosImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int mode) {
 
         /* Event type */
         eventType = freadUint32(fp, endian);
-        event = (TSS_PCR_EVENT *) malloc(sizeof(TSS_PCR_EVENT));
+
+        event = (TSS_PCR_EVENT *) xmalloc(sizeof(TSS_PCR_EVENT));
         if (event == NULL) {
-            ERROR("no memory\n");
             rc = PTS_FATAL;
             goto close;
         }
@@ -989,9 +996,8 @@ int readBiosImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int mode) {
 
         /* Digest */
         event->ulPcrValueLength = SHA1_DIGEST_SIZE;
-        event->rgbPcrValue = (BYTE *) malloc(SHA1_DIGEST_SIZE);  // leaked
+        event->rgbPcrValue = (BYTE *) xmalloc(SHA1_DIGEST_SIZE);  // leaked
         if (event->rgbPcrValue == NULL) {
-            ERROR("no memory\n");
             rc = PTS_FATAL;
             goto close;
         }
@@ -1014,15 +1020,14 @@ int readBiosImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int mode) {
             }
         }
         /* malloc EventData */
-        if ((event->rgbEvent = malloc(eventLength)) == NULL) {
-            ERROR("no memory\n");
+        if ((event->rgbEvent = xmalloc_assert(eventLength)) == NULL) {
             rc = PTS_FATAL;
             goto close;
         }
         // TODO if rgbevent is huge 0x4000000 #=> check the endian
         size = fread(event->rgbEvent, 1, eventLength, fp);
         if (size != eventLength) {
-            ERROR("BIOS IML File %s, bad eventdata size 0x%x != 0x%xat %d event\n",
+            ERROR("BIOS IML File %s, bad eventdata size 0x%x != 0x%x at %d event\n",
                 filename, (int)size, (int)eventLength, i);
             rc = PTS_INTERNAL_ERROR;
             goto close;
@@ -1038,9 +1043,8 @@ int readBiosImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int mode) {
 
         /* create event wrapper */
         ew_new = (OPENPTS_PCR_EVENT_WRAPPER *)
-            malloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
+            xmalloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
         if (ew_new == NULL) {
-            ERROR("no memory\n");
             rc = PTS_FATAL;
             goto close;
         }
@@ -1123,18 +1127,24 @@ int readBiosImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int mode) {
     DEBUG("read BIOS IML, file %s => %d events\n", filename, ctx->ss_table->event_num);
 
     if (error > 0) {
-        addReason(ctx, "[IML] Load IML(file:%s) was faild",
-            filename);
+        // WORK NEEDED: Needs i18n using NLS
+        addReason(ctx, -1, "[IML] Failed to load IML(file:%s)", filename);
         rc = PTS_INVALID_SNAPSHOT;
     }
 
     /* free (for ERROR) */
     if (event != NULL) {
-        if (event->rgbPcrValue != NULL) free(event->rgbPcrValue);
-        if (event->rgbEvent != NULL) free(event->rgbEvent);
-        free(event);
+        if (event->rgbPcrValue != NULL) {
+            xfree(event->rgbPcrValue);
+        }
+        if (event->rgbEvent != NULL) {
+            xfree(event->rgbEvent);
+        }
+        xfree(event);
+    }
+    if (ew_new != NULL) {
+        xfree(ew_new);
     }
-    if (ew_new != NULL) free(ew_new);
 
     DEBUG_CAL("iml.c - getBiosImlFile - done\n");
 
@@ -1331,15 +1341,8 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
 
     DEBUG_CAL("readImaImlFile - start\n");
 
-    /* check */
-    if (ctx == NULL) {
-        ERROR("readImaImlFile - ctx is NULL\n");  // TODO(munetoh)
-        return -1;
-    }
-    if (filename == NULL) {
-        ERROR("readImaImlFile - no filename\n");  // TODO(munetoh)
-        return -1;
-    }
+    ASSERT(NULL != ctx, "getImaImlFile - ctx is NULL\n");  // TODO(munetoh)
+    ASSERT(NULL != filename, "getImaImlFile - no filename\n");  // TODO(munetoh)
 
     /* open file */
     if ((fp = fopen(filename, "rb")) == NULL) {
@@ -1369,9 +1372,8 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
         }
 
         /* alloc event structure */
-        event = (TSS_PCR_EVENT *) malloc(sizeof(TSS_PCR_EVENT));
+        event = (TSS_PCR_EVENT *) xmalloc(sizeof(TSS_PCR_EVENT));
         if (event == NULL) {
-            ERROR("no memory\n");
             rc = PTS_FATAL;
             goto close;
         }
@@ -1395,9 +1397,8 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
 
             /* read Digest (SHA1) */
             event->ulPcrValueLength = SHA1_DIGEST_SIZE;
-            event->rgbPcrValue = (BYTE *) malloc(SHA1_DIGEST_SIZE);
+            event->rgbPcrValue = (BYTE *) xmalloc(SHA1_DIGEST_SIZE);
             if (event->rgbPcrValue == NULL) {
-                ERROR("no memory\n");
                 rc = PTS_FATAL;
                 goto close;
             }
@@ -1418,9 +1419,7 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
                 goto close;
             }
             /* alloc eventdata */
-            event->rgbEvent = malloc(event->ulEventLength);
-            if (event->rgbEvent == NULL) {
-                ERROR("no memory\n");
+            if ((event->rgbEvent = xmalloc(event->ulEventLength)) == NULL) {
                 rc = PTS_FATAL;
                 goto close;
             }
@@ -1447,9 +1446,8 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
 
             /* read Digest (SHA1) */
             event->ulPcrValueLength = SHA1_DIGEST_SIZE;
-            event->rgbPcrValue = (BYTE *) malloc(SHA1_DIGEST_SIZE);
+            event->rgbPcrValue = (BYTE *) xmalloc(SHA1_DIGEST_SIZE);
             if (event->rgbPcrValue == NULL) {
-                ERROR("no memory\n");
                 rc = PTS_FATAL;
                 goto close;
             }
@@ -1473,9 +1471,8 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
 
             /* alloc template (=event data) */
             event->ulEventLength = 20 + 256;  // TODO(munetoh)
-            event->rgbEvent = malloc(event->ulEventLength);
+            event->rgbEvent = xmalloc(event->ulEventLength);
             if (event->rgbEvent == NULL) {
-                ERROR("no memory\n");
                 rc = PTS_FATAL;
                 goto close;
             }
@@ -1503,7 +1500,7 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
         } else {
             /* read Digest (SHA1) */
             event->ulPcrValueLength = SHA1_DIGEST_SIZE;
-            event->rgbPcrValue = (BYTE *) malloc(SHA1_DIGEST_SIZE);
+            event->rgbPcrValue = (BYTE *) xmalloc_assert(SHA1_DIGEST_SIZE);
 
             size = fread(event->rgbPcrValue, 1, SHA1_DIGEST_SIZE, fp);
             if (size != SHA1_DIGEST_SIZE) {
@@ -1546,9 +1543,8 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
 
                 /* alloc template (=event data) */
                 event->ulEventLength = 20 + 256;  // TODO(munetoh)
-                event->rgbEvent = malloc(event->ulEventLength);
+                event->rgbEvent = xmalloc(event->ulEventLength);
                 if (event->rgbEvent == NULL) {
-                    ERROR("no memory\n");
                     rc = PTS_FATAL;
                     goto close;
                 }
@@ -1596,9 +1592,8 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
         /* create wrapper */
         // ew_last = ew_new;  // TODO
         ew = (OPENPTS_PCR_EVENT_WRAPPER *)
-            malloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
+            xmalloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
         if (ew == NULL) {
-            ERROR("no memory\n");
             rc = PTS_FATAL;
             goto close;
         }
@@ -1663,11 +1658,17 @@ int readImaImlFile(OPENPTS_CONTEXT * ctx, const char *filename, int type, int mo
     *count = event_num;
     /* free (for error) */
     if (event != NULL) {
-        if (event->rgbPcrValue != NULL) free(event->rgbPcrValue);
-        if (event->rgbEvent != NULL) free(event->rgbEvent);
-        free(event);
+        if (event->rgbPcrValue != NULL) {
+            xfree(event->rgbPcrValue);
+        }
+        if (event->rgbEvent != NULL) {
+            xfree(event->rgbEvent);
+        }
+        xfree(event);
+    }
+    if (ew  != NULL) {
+        xfree(ew);
     }
-    if (ew  != NULL) free(ew);
 
     return rc;
 }
@@ -1745,7 +1746,7 @@ int getPcr(OPENPTS_CONTEXT * ctx) {
     // DEBUG("getPcr is deprecated\n");
 
     int i;
-    int pcrNum = 16;
+    int pcrNum = 0;
 
     /* Connect to TCSD */
     result = Tspi_Context_Create(&hContext);
@@ -1791,11 +1792,13 @@ int getPcr(OPENPTS_CONTEXT * ctx) {
 
         if (result != TSS_SUCCESS) {
             ERROR("ERROR: Tspi_TPM_PcrRead failed rc=0x%x\n", result);
+            pcrNum = 0;
             goto free;
         }
 
         if (blobLength != SHA1_DIGEST_SIZE) {
             Tspi_Context_FreeMemory(hContext, blob);
+            pcrNum = 0;
             goto free;
         }
 
@@ -1950,20 +1953,20 @@ int validatePcr(OPENPTS_CONTEXT * ctx) {
 
     DEBUG("validatePcr - done, rc=%d\n", rc);
 
-    if (verbose & DEBUG_FLAG) {
+    if (isDebugFlagSet(DEBUG_FLAG)) {
         for (i = 0; i < ctx->pcr_num; i++) {
-            printf("PCR %2d ", i);
+            OUTPUT("PCR %2d ", i);
             ss = getActiveSnapshotFromTable(ctx->ss_table, i);
             if (ss != NULL) {
                 for (j = 0; j < SHA1_DIGEST_SIZE; j++) {
-                    printf("%02x-%02x ", tpm->pcr[i][j], ss->tpm_pcr[j]);
+                    OUTPUT("%02x-%02x ", tpm->pcr[i][j], ss->tpm_pcr[j]);
                 }
             } else {
                 for (j = 0; j < SHA1_DIGEST_SIZE; j++) {
-                    printf("%02x-   ", tpm->pcr[i][j]);
+                    OUTPUT("%02x-   ", tpm->pcr[i][j]);
                 }
             }
-            printf("\n");
+            OUTPUT("\n");
         }
     }
 
@@ -1981,12 +1984,12 @@ void printEventWrapper(OPENPTS_PCR_EVENT_WRAPPER *eventWrapper) {
     event = eventWrapper->event;
 
     if (event != NULL) {
-        printf("%4d ", (int)event->ulPcrIndex);
-        printf("%8x ", event->eventType);
+        OUTPUT("%4d ", (int)event->ulPcrIndex);
+        OUTPUT("%8x ", event->eventType);
         for (j = 0; j < (int)event->ulPcrValueLength; j++) {
-            printf("%02x", event->rgbPcrValue[j]);
+            OUTPUT("%02x", event->rgbPcrValue[j]);
         }
-        printf("eventdata[%4d]\n", event->ulEventLength);
+        OUTPUT("eventdata[%4d]\n", event->ulEventLength);
     } else {
         ERROR("NULL event\n");  // TODO(munetoh)
     }
@@ -2017,16 +2020,16 @@ int printImlByPcr(
 
     eventWrapper = ss->start;
 
-    printf("PCR[%d]\n", index);
+    OUTPUT("PCR[%d]\n", index);
 
     for (i = 0; i < ctx->ss_table->event_num; i++) {
-        printf(" %3d %3d %08x ",
+        OUTPUT(" %3d %3d %08x ",
             offset + i,
             eventWrapper->event->ulPcrIndex,
             eventWrapper->event->eventType);
         /* hex */
         for (j = 0; j < 20; j++) {
-            printf("%02x", eventWrapper->event->rgbPcrValue[j]);
+            OUTPUT("%02x", eventWrapper->event->rgbPcrValue[j]);
         }
 
         /* base64 */
@@ -2035,7 +2038,7 @@ int printImlByPcr(
         //     (unsigned char *)eventWrapper->event->rgbPcrValue,
          //   20);
 
-        printf(" (%s) \n", buf);
+        OUTPUT(" (%s) \n", buf);
         eventWrapper = eventWrapper->next_pcr;
         if (eventWrapper == NULL) break;
     }
@@ -2077,12 +2080,12 @@ void printEvent(TSS_PCR_EVENT *event) {
         int pcr5_grub = 0;
         char buf[256];
 
-        printf("%4d ", index);
-        printf("%8x ", type);
+        OUTPUT("%4d ", index);
+        OUTPUT("%8x ", type);
         for (i = 0; i < (int)event->ulPcrValueLength; i++) {
-            printf("%02x", event->rgbPcrValue[i]);
+            OUTPUT("%02x", event->rgbPcrValue[i]);
         }
-        printf(" eventdata[%4d] ", event->ulEventLength);
+        OUTPUT(" eventdata[%4d] ", event->ulEventLength);
 
         if (len < 256) {
             memcpy(buf, event->rgbEvent, event->ulEventLength);
@@ -2094,206 +2097,206 @@ void printEvent(TSS_PCR_EVENT *event) {
 
         if (index == 10) {  // Linux-IMA
             if (type == 2) {
-                printf("[IMA-LKM:%s] ", buf);
+                OUTPUT("[IMA-LKM:%s] ", buf);
             } else if (type == 1) {
-                printf("[IMA-EXE:%s] ", buf);
+                OUTPUT("[IMA-EXE:%s] ", buf);
             } else if (type == 0) {
-                // printf("[IMA:%s] ", buf);
-                printf("[IMA] ");
+                // OUTPUT("[IMA:%s] ", buf);
+                OUTPUT("[IMA] ");
             } else if ((type & 0xFFFF) == 4) {
-                printf("[IMA-USR,0x%04x:%s] ", (type >> 16), buf);
+                OUTPUT("[IMA-USR,0x%04x:%s] ", (type >> 16), buf);
             } else {
-                printf("[???:%s] ", buf);
+                OUTPUT("[???:%s] ", buf);
             }
         } else if (index <= 8) {  // BIOS + Grub
             switch (type) {
                 case 0:
-                    printf("[BIOS:EV_PREBOOT_CERT(EV_CODE_CERT)]");
+                    OUTPUT("[BIOS:EV_PREBOOT_CERT(EV_CODE_CERT)]");
                     break;
                 case 1:
-                    printf("[BIOS:EV_POST_CODE(EV_CODE_NOCERT)]");
+                    OUTPUT("[BIOS:EV_POST_CODE(EV_CODE_NOCERT)]");
                     break;
                 case 2:
-                    printf("[BIOS:EV_UNUSED(EV_XML_CONFIG)]");
+                    OUTPUT("[BIOS:EV_UNUSED(EV_XML_CONFIG)]");
                     break;
                 case 3:
-                    printf("[BIOS:EV_NO_ACTION]");
+                    OUTPUT("[BIOS:EV_NO_ACTION]");
                     break;
                 case 4:
                     if ((pcr4_grub > 1) && (index == 4)) {
-                        printf("[GRUB:EV_SEPARATOR, %s]", buf);
+                        OUTPUT("[GRUB:EV_SEPARATOR, %s]", buf);
                     } else if ((pcr5_grub > 0) && (index == 5)) {
-                        printf("[GRUB:EV_SEPARATOR, %s]", buf);
+                        OUTPUT("[GRUB:EV_SEPARATOR, %s]", buf);
                     } else if (index == 8) {
-                        printf("[GRUB:EV_SEPARATOR, %s]", buf);
+                        OUTPUT("[GRUB:EV_SEPARATOR, %s]", buf);
                     } else if (len == 4) {  // V1.2
-                        printf("[BIOS:EV_SEPARATOR, %02x%02x%02x%02x]",
+                        OUTPUT("[BIOS:EV_SEPARATOR, %02x%02x%02x%02x]",
                                 (unsigned char) buf[0],
                                 (unsigned char) buf[1],
                                 (unsigned char) buf[2],
                                 (unsigned char) buf[3]);
                     } else {
-                            printf("[BIOS:EV_SEPARATOR, %s]", buf);
+                            OUTPUT("[BIOS:EV_SEPARATOR, %s]", buf);
                     }
                     break;
                 case 5:
                     if ((pcr5_grub > 0) && (index == 5)) {
-                            printf("[GRUB:EV_ACTION, %s]", buf);
+                            OUTPUT("[GRUB:EV_ACTION, %s]", buf);
                     } else {
-                            printf("[BIOS:EV_ACTION, %s]", buf);
+                            OUTPUT("[BIOS:EV_ACTION, %s]", buf);
                     }
                     break;
                 case 6:
                     if ((pcr4_grub > 1) && (index == 4)) {
-                            printf("[GRUB: measure MBR again]");
+                            OUTPUT("[GRUB: measure MBR again]");
                     } else {
-                            printf("[BIOS:EV_EVENT_TAG(EV_PLATFORM_SPECIFIC)]");
+                            OUTPUT("[BIOS:EV_EVENT_TAG(EV_PLATFORM_SPECIFIC)]");
                     }
                     break;
                 case 7:
-                    printf("[BIOS:EV_S_CRTM_CONTENTS]");
+                    OUTPUT("[BIOS:EV_S_CRTM_CONTENTS]");
                     break;
                 case 8:
-                    printf("[BIOS:EV_S_CRTM_VERSION]");
+                    OUTPUT("[BIOS:EV_S_CRTM_VERSION]");
                     break;
                 case 9:
-                    printf("[BIOS:EV_CPU_MICROCODE]");
+                    OUTPUT("[BIOS:EV_CPU_MICROCODE]");
                     break;
                 case 0x0a:
-                    printf("[BIOS:EV_PLATFORM_CONFIG_FLAG)]");
+                    OUTPUT("[BIOS:EV_PLATFORM_CONFIG_FLAG)]");
                     break;
                 case 0x0b:
-                    printf("[BIOS:EV_TABLE_OF_CONTENTS)]");
+                    OUTPUT("[BIOS:EV_TABLE_OF_CONTENTS)]");
                     break;
                 case 0x0c:
-                    printf("[BIOS:EV_COMPACT_HASH]");
+                    OUTPUT("[BIOS:EV_COMPACT_HASH]");
                     break;
                 case 0x0d:
                     if (pcr4_grub == 0) {
                         // BIOS
-                        printf("[BIOS:EV_IPL]");
+                        OUTPUT("[BIOS:EV_IPL]");
                         pcr4_grub = 1;
                     } else if (pcr4_grub == 1) {
                         // GRUB
-                        printf("[GRUB:EV_IPL, Stage1(MBR)]");
+                        OUTPUT("[GRUB:EV_IPL, Stage1(MBR)]");
                         pcr4_grub = 2;
                     } else if (pcr4_grub == 2) {
                         // GRUB
-                        printf("[GRUB:EV_IPL, Stage1.5]");
+                        OUTPUT("[GRUB:EV_IPL, Stage1.5]");
                         pcr4_grub = 3;
                     } else if (pcr4_grub == 3) {
                         // GRUB
-                        printf("[GRUB:EV_IPL, Stage1.5(filesystem)]");
+                        OUTPUT("[GRUB:EV_IPL, Stage1.5(filesystem)]");
                         pcr4_grub = 4;
                     } else {
                         // GRUB
-                        printf("[GRUB:EV_IPL]");
+                        OUTPUT("[GRUB:EV_IPL]");
                     }
                     break;
                 case 0x0e:
                     if (pcr5_grub == 0) {
-                        printf("[BIOS:EV_IPL_PERTITION_DATA]");
+                        OUTPUT("[BIOS:EV_IPL_PARTITION_DATA]");
                         pcr5_grub = 1;
                     } else {
-                        printf("[GRUB:grub.conf]");
+                        OUTPUT("[GRUB:grub.conf]");
                     }
                     break;
                 case 0x0f:
-                    printf("[BIOS:EV_NOHOST_CODE)]");
+                    OUTPUT("[BIOS:EV_NOHOST_CODE)]");
                     break;
                 case 0x10:
-                    printf("[BIOS:EV_NOHOST_CONFIG]");
+                    OUTPUT("[BIOS:EV_NOHOST_CONFIG]");
                     break;
                 case 0x11:
-                    printf("[BIOS:EV_NOHOST_INFO]");
+                    OUTPUT("[BIOS:EV_NOHOST_INFO]");
                     break;
                 case 0x12:
-                    printf("[BIOS:EV_SPECIFICATION_IDENTIFIER 0x");
+                    OUTPUT("[BIOS:EV_SPECIFICATION_IDENTIFIER 0x");
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 case 0x80000001:  // EFI
-                    printf("[BIOS:EV_EFI_VARIABLE_DRIVER_CONFIG len=%d,", len);
+                    OUTPUT("[BIOS:EV_EFI_VARIABLE_DRIVER_CONFIG len=%d,", len);
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 case 0x80000002:  // EFI
-                    printf("[BIOS:EV_EFI_VARIABLE_BOOT len=%d,", len);
+                    OUTPUT("[BIOS:EV_EFI_VARIABLE_BOOT len=%d,", len);
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 case 0x80000003:  // EFI
-                    printf("[BIOS:EV_EFI_BOOT_SERVICES_APPLICATION len=%d,", len);
+                    OUTPUT("[BIOS:EV_EFI_BOOT_SERVICES_APPLICATION len=%d,", len);
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 case 0x80000004:  // EFI
-                    printf("[BIOS:EV_EFI_BOOT_SERVICES_DRIVER len=%d,", len);
+                    OUTPUT("[BIOS:EV_EFI_BOOT_SERVICES_DRIVER len=%d,", len);
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 case 0x80000005:  // EFI
-                    printf("[BIOS:EV_EFI_RUNTIME_SERVICES_DRIVER len=%d,", len);
+                    OUTPUT("[BIOS:EV_EFI_RUNTIME_SERVICES_DRIVER len=%d,", len);
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 case 0x80000006:  // EFI
-                    printf("[BIOS:EV_EFI_GPT_EVENT len=%d,", len);
+                    OUTPUT("[BIOS:EV_EFI_GPT_EVENT len=%d,", len);
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 case 0x80000007:  // EFI
-                    printf("[BIOS:EV_EFI_ACTION len=%d,", len);
+                    OUTPUT("[BIOS:EV_EFI_ACTION len=%d,", len);
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 case 0x80000009:  // EFI
-                    printf("[BIOS:EV_EFI_HANDOFF_TABLES len=%d,", len);
+                    OUTPUT("[BIOS:EV_EFI_HANDOFF_TABLES len=%d,", len);
                     for (i = 0; i < len; i++) {
-                        printf("%02x", (unsigned char)buf[i]);
+                        OUTPUT("%02x", (unsigned char)buf[i]);
                     }
-                    printf("]");
+                    OUTPUT("]");
                     break;
                 // GRUB-IMA
                 case 0x1005:
-                    printf("[GRUB:ACTION, %s]", buf);
+                    OUTPUT("[GRUB:ACTION, %s]", buf);
                     break;
                 case 0x1105:
-                    printf("[GRUB:KERNEL_OPT %s]", buf);
+                    OUTPUT("[GRUB:KERNEL_OPT %s]", buf);
                     break;
                 case 0x1205:
-                    printf("[GRUB:KERNEL %s]", buf);
+                    OUTPUT("[GRUB:KERNEL %s]", buf);
                     break;
                 case 0x1305:
-                    printf("[GRUB:INITRD %s]", buf);
+                    OUTPUT("[GRUB:INITRD %s]", buf);
                     break;
                 case 0x1405:
-                    printf("[GRUB:MODULE %s]", buf);
+                    OUTPUT("[GRUB:MODULE %s]", buf);
                     break;
                 default:
-                    printf("[Unknown BIOS Event:size=%d]", len);
+                    OUTPUT("[Unknown BIOS Event:size=%d]", len);
                     break;
             }
         }
 
         encodeBase64((unsigned char *)buf, (unsigned char *)event->rgbPcrValue, event->ulPcrValueLength);
-        printf(" b64(%s)\n", buf);
+        OUTPUT(" b64(%s)\n", buf);
 
     } else {
         ERROR("NULL event\n");  // TODO(munetoh)
@@ -2331,14 +2334,14 @@ void printSnapshots(OPENPTS_CONTEXT * ctx) {
     int level0_num = 0;
     int level1_num = 0;
 
-    printf("events\n");
-    printf(" \n");
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML_EVENTS, "events\n"));
+    OUTPUT(" \n");
     for (i = 0; i < MAX_PCRNUM; i++) {
         ss = getSnapshotFromTable(ctx->ss_table, i, 0);
         if (ss != NULL) {
             if (ss->event_num > 0) {
-                printf("PCR[%2d] - ", i);
-                printf("%d events at level 0\n", ss->event_num);
+                OUTPUT("PCR[%2d] - ", i);
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML_EVENTS_AT_LEVEL0, "%d events at level 0\n"), ss->event_num);
             }
             level0_num += ss->event_num;
             printSnapshot(ss);
@@ -2350,18 +2353,19 @@ void printSnapshots(OPENPTS_CONTEXT * ctx) {
         ss = getSnapshotFromTable(ctx->ss_table, i, 1);
         if (ss != NULL) {
             if (ss->event_num > 0) {
-                printf("PCR[%2d] - ", i);
-                printf("%d events at level 1\n", ss->event_num);
+                OUTPUT("PCR[%2d] - ", i);
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML_EVENTS_AT_LEVEL1, "%d events at level 1\n"), ss->event_num);
             }
             level1_num += ss->event_num;
             if (ss->level != 1) ERROR("bad level %d\n", ss->level);
             printSnapshot(ss);
         }
     }
-    printf("---------------------------\n");
-    printf("level 0 total = %d\n", level0_num);
-    printf("level 1 total = %d\n", level1_num);
-    printf("---------------------------\n");
+    OUTPUT("---------------------------\n");
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML_LEVEL_TOTALS,
+           "level 0 total = %d\n"
+           "level 1 total = %d\n"), level0_num, level1_num);
+    OUTPUT("---------------------------\n");
 }
 #endif
 
@@ -2375,35 +2379,36 @@ void printSnapshotsInfo(OPENPTS_CONTEXT * ctx) {
     int level0_num = 0;
     int level1_num = 0;
 
-    printf("Number of event\n");
-    printf(" \n");
-    printf("PCR Level0 Level1 \n");
-    printf("--------------------------\n");
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML_SNAPSHOT_HEADER,
+           "Number of event\n"
+           "PCR Level0 Level1\n"));
+    OUTPUT("--------------------------\n");
 
     for (i = 0; i < MAX_PCRNUM; i++) {
         /* level 0 */
         ss = getSnapshotFromTable(ctx->ss_table, i, 0);
         if (ss != NULL) {
-            printf("%2d ", i);
-            printf("%6d", ss->event_num);
+            OUTPUT("%2d ", i);
+            OUTPUT("%6d", ss->event_num);
             level0_num += ss->event_num;
         } else {
-            printf("        ");
+            OUTPUT("        ");
         }
 
         /* level 1 */
         ss = getSnapshotFromTable(ctx->ss_table, i, 1);
         if (ss != NULL) {
-            printf(" %6d\n", ss->event_num);
+            OUTPUT(" %6d\n", ss->event_num);
             level1_num += ss->event_num;
             if (ss->level != 1) ERROR("bad level %d\n", ss->level);
         } else {
-            printf("\n");
+            OUTPUT("\n");
         }
     }
-    printf("---------------------------\n");
-    printf("level 0 total = %d\n", level0_num);
-    printf("level 1 total = %d\n", level1_num);
-    printf("---------------------------\n");
+    OUTPUT("---------------------------\n");
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML_SNAPSHOT_LEVEL_TOTALS,
+           "level 0 total = %d\n"
+           "level 1 total = %d\n"), level0_num, level1_num);
+    OUTPUT("---------------------------\n");
 }
 
index 7f3c334..df5c8ea 100644 (file)
@@ -86,8 +86,6 @@
 
 #include <openpts.h>
 
-int verbose = 0; /**< DEBUG  */
-
 /**
  * print FSM status (location)
  */
@@ -97,9 +95,8 @@ void printFsmInfo2(OPENPTS_CONTEXT *ctx) {
     int level0_num = 0;
     int level1_num = 0;
 
-    printf("Number of event\n");
-    printf(" \n");
-    printf("PCR Level0 Level1 \n");
+    printf(NLS(MS_OPENPTS, OPENPTS_IML2AIDE_EVENT, "Number of events\n"
+           "PCR Level0 Level1\n"));
     printf("--------------------------\n");
 
     for (i = 0; i < MAX_PCRNUM; i++) {
@@ -140,16 +137,16 @@ void printFsmInfo2(OPENPTS_CONTEXT *ctx) {
  * usage
  */
 void usage(void) {
-    fprintf(stderr, "OpenPTS command\n\n");
-    fprintf(stderr, "Usage: iml2aide [options]\n\n");
-    fprintf(stderr, "Options:\n");
-    fprintf(stderr, "  -c filename           Set config file\n");
-    fprintf(stderr, "  -i filename           Set IMA IML file. default, get IML via TSS\n");
-    fprintf(stderr, "  -r filename           Set AIDE DB file as reference of fullpathname\n");
-    fprintf(stderr, "  -o filename           Set output file (AIDE DB format, gziped)\n");
-    fprintf(stderr, "  -w filename           Set output file (Ignore name list, plain text format)\n");
-    fprintf(stderr, "  -h                    Show this help message\n");
-    fprintf(stderr, "\n");
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_IML2AIDE_USAGE, "OpenPTS command\n\n"
+                    "Usage: iml2aide [options]\n\n"
+                    "Options:\n"
+                    "  -c filename           Set config file\n"
+                    "  -i filename           Set IMA IML file. default, get IML via TSS\n"
+                    "  -r filename           Set AIDE DB file as reference of fullpathname\n"
+                    "  -o filename           Set output file (AIDE DB format, gziped)\n"
+                    "  -w filename           Set output file (Ignore name list, plain text format)\n"
+                    "  -h                    Show this help message\n"
+                    "\n"));
 }
 
 /**
@@ -167,13 +164,12 @@ int main(int argc, char *argv[]) {
     OPENPTS_CONFIG *conf = NULL;
     OPENPTS_CONTEXT *ctx = NULL;
 
-    verbose = 0;
 
     /* args */
     while ((c = getopt(argc, argv, "do:i:c:r:w:h")) != EOF) {
         switch (c) {
         case 'd':
-            verbose = 1;
+            setDebugFlags(DEBUG_FLAG);
             break;
         case 'i':
             ima_filename = optarg;
@@ -202,12 +198,12 @@ int main(int argc, char *argv[]) {
 
     /* check */
     if (aide_filename == NULL) {
-        fprintf(stderr, "Set output file (AIDE DB file)\n\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML2AIDE_SET_OUTPUT, "Set output file (AIDE DB file)\n\n"));
         usage();
         return -1;
     }
     if (config_filename == NULL) {
-        fprintf(stderr, "Set config file\n\n");
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML2AIDE_CONFIG, "Set config file\n\n"));
         usage();
         return -1;
     }
@@ -216,13 +212,13 @@ int main(int argc, char *argv[]) {
     /* ctx */
     conf = newPtsConfig();
     if (conf == NULL) {
-        fprintf(stderr, "Internal Error\n");
+        ERROR("Internal Error\n");
         return -1;
     }
 
     ctx = newPtsContext(conf);
     if (ctx == NULL) {
-        fprintf(stderr, "Internal Error\n");
+        ERROR("Internal Error\n");
         return -1;
     }
 
@@ -248,10 +244,11 @@ int main(int argc, char *argv[]) {
 
         rc = loadAideDatabaseFile(ctx->aide_ctx, aideref_filename);  // ir.c
         if (rc < 0) {
-            fprintf(stderr, "Internal Error, load AIDE DB() was failed\n");
+            ERROR("Internal Error, load AIDE DB() was failed\n");
             return -1;
         }
-        printf("AIDE DB(ref) : %d entries (< %s)\n", rc, aideref_filename);
+        printf(NLS(MS_OPENPTS, OPENPTS_IML2AIDE_DATABASE,
+            "AIDE Database(ref): %d entries (< %s)\n"), rc, aideref_filename);
 
         /* set flags */
         ctx->conf->ima_validation_mode = OPENPTS_VALIDATION_MODE_AIDE;
@@ -264,7 +261,7 @@ int main(int argc, char *argv[]) {
     if (ima_filename == NULL) {
         /* IML -> TSS -> Struct */
         rc = getIml(ctx, 0);
-        printf("IML          : %d events (< TSS)\n", rc);
+        printf(NLS(MS_OPENPTS, OPENPTS_IML2AIDE_EVENTS, "IML: %d events (< TSS)\n"), rc);
     } else {
         int count;
         /* IML(file) -> Struct */
@@ -274,13 +271,13 @@ int main(int argc, char *argv[]) {
                 ima_type, 0, &count);
 
         if (rc != PTS_SUCCESS) {
-            fprintf(stderr, "Internal Error, raild atr ead IMA's IML\n");
+            ERROR("Internal Error, raild atr ead IMA's IML\n");
             return -1;
         }
-        printf("IML          : %d events (< %s)\n", rc, ima_filename);
+        printf(NLS(MS_OPENPTS, OPENPTS_IML2AIDE_EVENTS_2, "IML: %d events (< %s)\n"), rc, ima_filename);
     }
     if (rc < 0) {
-        fprintf(stderr, "Internal Error\n");
+        ERROR("Internal Error\n");
         return -1;
     }
 
@@ -293,15 +290,17 @@ int main(int argc, char *argv[]) {
         rc = writeReducedAidbDatabase(ctx->aide_ctx, aide_filename);
     }
     if (rc < 0) {
-        fprintf(stderr, "Internal Error\n");
+        ERROR("Internal Error\n");
         return -1;
     }
 
-    printf("AIDE DB      : %d entries (> %s) \n", rc, aide_filename);
+    printf(NLS(MS_OPENPTS, OPENPTS_IML2AIDE_DATABASE_2,
+        "AIDE Database      : %d entries (> %s) \n"), rc, aide_filename);
 
     if (ignorelist_filename != NULL) {
         rc = writeAideIgnoreList(ctx, ignorelist_filename);
-        printf("Ignore list  : %d entries (> %s) \n", rc, ignorelist_filename);
+        printf(NLS(MS_OPENPTS, OPENPTS_IML2AIDE_IGN_LIST,
+            "Ignore list  : %d entries (> %s) \n"), rc, ignorelist_filename);
     }
 
     /* free */
index 1fccca3..791fd80 100644 (file)
@@ -90,6 +90,7 @@
 #include <openssl/sha.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 #ifdef CONFIG_TBOOT
 #include <openpts_tboot.h>
@@ -106,8 +107,6 @@ BYTE pcr[24][20];
 //       0 no
 // -v    1 show event data contents
 // -v -v 2 DEBUG
-int verbose_cnt = 0;
-int verbose = 0;
 
 char *indent = "                                                              ";
 
@@ -124,7 +123,6 @@ int verify = 0;
  */
 
 int hex2bin(void *dest, const void *src, size_t n);
-void printhex(char *str, unsigned char *buf, int len);
 
 
 #define BUFSIZE 4096
@@ -206,13 +204,6 @@ void fprintBin(FILE* fp, BYTE* data, UINT32 len) {
     }
 }
 
-void fprintHex(FILE* fp, BYTE* data, UINT32 len) {
-    int i;
-    for (i = 0; i < (int)len; i++) {
-        fprintf(fp, "%02x", data[i]);
-    }
-}
-
 
 void fprintChar(FILE* fp, BYTE* data, UINT32 len) {
     int i;
@@ -258,9 +249,10 @@ void fprintEventData(
         UINT32 len,  // event length
         UINT32 pcrindex,
         UINT32 type,
-        BYTE*  digest) {
+        BYTE*  digest,
+        int endian) {
     char buf[BUFSIZE];
-    char *b64buf; //[BUFSIZE];
+    char *b64buf;  // [BUFSIZE];
     int b64buf_len;
     int i;
 
@@ -380,7 +372,7 @@ EventData
                 fprintHex(fp, digest2, 20);
                 fprintf(fp, " <= SHA1(Version[%d])", len);
             }
-            if (verbose_cnt > 0) {
+            if (getVerbosity() > 0) {
                 fprintf(fp, "\n");
                 fprintf(fp, "%sVersion(hex) : ", indent);
                 fprintHex(fp, data, len);
@@ -424,7 +416,7 @@ EventData
             break;
         case 0x0e:
             if (pcr5_grub == 0) {
-                fprintf(fp, "[BIOS:EV_IPL_PERTITION_DATA]");
+                fprintf(fp, "[BIOS:EV_IPL_PARTITION_DATA]");
                 pcr5_grub = 1;
             } else {
                 fprintf(fp, "[GRUB:grub.conf]");
@@ -558,22 +550,79 @@ EventData
             /* OpenPTS*/
         case EV_COLLECTOR_START:
             fprintf(fp, "[OpenPTS:EV_COLLECTOR_START[%d]]", len);
-#if 0
-            if (verbose_cnt > 0) {
-                fprintf(fp, "%sUUID");
-                for (i = 0; i < (int)len; i++) {
-                    fprintf(fp, "%02x", (BYTE)buf[i]);
+            if (getVerbosity() > 0) {
+                OPENPTS_EVENT_COLLECTOR_START *start = (OPENPTS_EVENT_COLLECTOR_START*) buf;
+                char * ptsc_uuid;
+                char * rm_uuid;
+
+                ptsc_uuid  = getStringOfUuid((PTS_UUID *)&start->collector_uuid);
+                rm_uuid =  getStringOfUuid((PTS_UUID *)&start->manifest_uuid);
+
+                fprintf(fp, "\n");
+
+                // fprintHex(fp, (BYTE *)buf, len);
+                // fprintf(fp, "\n");
+
+                fprintf(fp, "%sptsc UUID     : %s\n", indent, ptsc_uuid);
+                fprintf(fp, "%smanifest UUID : %s\n", indent, rm_uuid);
+                fprintf(fp, "%sPCR           : ", indent);
+                fprintHex(fp, start->pcr_value, SHA1_DIGEST_SIZE);
+                fprintf(fp, "\n");
+            }
+            break;
+#ifdef CONFIG_AUTO_RM_UPDATE
+        case EV_UPDATE_START:
+            fprintf(fp, "[OpenPTS:EV_UPDATE_START]");
+            if (getVerbosity() > 0) {
+                OPENPTS_EVENT_UPDATE_START *start = (OPENPTS_EVENT_UPDATE_START*) buf;
+                fprintf(fp, "\n");
+
+                if (endian == 0) {
+                    fprintf(fp, "%starget pcr index      : 0x%x\n", indent, start->target_pcr_index);
+                    fprintf(fp, "%starget snapshot level : 0x%x\n", indent, start->target_snapshot_level);
+                    fprintf(fp, "%sevent num             : 0x%x\n", indent, start->event_num);
+
+                    if (start->update_type == UPDATE_IPL_IMAGE) {
+                        // start->data_length must be 4
+                        fprintf(fp, "%supdate type           : 0x%x (IPL IMAGE)\n", indent, start->update_type);
+                        fprintf(fp, "%siml.ipl.count         : 0x%x\n", indent, start->data[0]);
+                    } else {
+                        fprintf(fp, "%supdate type           : 0x%x\n", indent, start->update_type);
+                        fprintf(fp, "%sdata length           : 0x%x\n", indent, start->data_length);
+                    }
+                } else {
+                    fprintf(fp, "%starget pcr index      : 0x%x\n", indent, b2l(start->target_pcr_index));
+                    fprintf(fp, "%starget snapshot level : 0x%x\n", indent, b2l(start->target_snapshot_level));
+                    fprintf(fp, "%sevent num             : 0x%x\n", indent, b2l(start->event_num));
+                    fprintf(fp, "%supdate type           : 0x%x\n", indent, b2l(start->update_type));
+                    fprintf(fp, "%sdata length           : 0x%x\n", indent, b2l(start->data_length));
                 }
-                encodeBase64(
-                    (unsigned char *)b64buf,
-                    (unsigned char *)buf, len);
-                fprintf(fp, ", base64(%s)", b64buf);
             }
-#endif
             break;
+        case EV_NEW_EVENTS:
+            fprintf(fp, "[OpenPTS:EV_NEW_EVENTS]");
+            break;
+        case EV_UPDATE_END:
+            fprintf(fp, "[OpenPTS:EV_UPDATE_END]");
+            break;
+        case EV_COLLECTOR_UPDATE:
+            fprintf(fp, "[OpenPTS:EV_COLLECTOR_UPDATE[%d]]", len);
+            // fprintHex(fp, (BYTE*)buf, len);
+            if (getVerbosity() > 0) {
+                char * ptsc_uuid;
+                char * rm_uuid;
+                OPENPTS_EVENT_COLLECTOR_UPDATE *update = (OPENPTS_EVENT_COLLECTOR_UPDATE*) buf;
+                fprintf(fp, "\n");
+                ptsc_uuid  = getStringOfUuid((PTS_UUID *)&update->collector_uuid);
+                rm_uuid =  getStringOfUuid((PTS_UUID *)&update->new_manifest_uuid);
+                fprintf(fp, "%sptsc UUID     : %s\n", indent, ptsc_uuid);
+                fprintf(fp, "%smanifest UUID : %s\n", indent, rm_uuid);
+            }
+            break;
+#endif  // CONFIG_AUTO_RM_UPDATE
         case EV_FILE_SCAN:
             fprintf(fp, "[OpenPTS:EV_FILE_SCAN]");
-            if (verbose_cnt > 0) {
+            if (getVerbosity() > 0) {
                 OPENPTS_EVENT_FILE_SCAN *fscan;
                 fscan = (OPENPTS_EVENT_FILE_SCAN *) buf;
                 /* show event data */
@@ -603,7 +652,7 @@ EventData
                 fprintf(fp, " <= SHA1(%d(pcrindex) || %d(eventtype) || eventdata[%d])",
                     pcrindex, type, len);
             }
-            if (verbose_cnt > 0) {
+            if (getVerbosity() > 0) {
                 OPENPTS_EVENT_FILE_SCAN *fscan;
                 fscan = (OPENPTS_EVENT_FILE_SCAN *) buf;
                 /* show event data */
@@ -620,7 +669,7 @@ EventData
 #ifdef CONFIG_TBOOT
         case EV_TBOOT_SINIT_V6:
             fprintf(fp, "[tboot:sinit(v6)]");
-            if (verbose_cnt > 0) {
+            if (getVerbosity() > 0) {
                 OPENPTS_EVENT_TBOOT_SINIT_V6 *ed;
                 ed = (OPENPTS_EVENT_TBOOT_SINIT_V6 *) buf;
                 /* show event data */
@@ -634,7 +683,7 @@ EventData
             break;
         case EV_TBOOT_SINIT_V7:
             fprintf(fp, "[tboot:sinit(v7)]");
-            if (verbose_cnt > 0) {
+            if (getVerbosity() > 0) {
                 OPENPTS_EVENT_TBOOT_SINIT_V7 *ed;
                 ed = (OPENPTS_EVENT_TBOOT_SINIT_V7 *) buf;
                 /* show event data */
@@ -648,7 +697,7 @@ EventData
             break;
         case EV_TBOOT_STM_V6:
             fprintf(fp, "[tboot:stm(v6)]");
-            if (verbose_cnt > 0) {
+            if (getVerbosity() > 0) {
                 OPENPTS_EVENT_TBOOT_STM_V6 *ed;
                 ed = (OPENPTS_EVENT_TBOOT_STM_V6 *) buf;
                 /* show event data */
@@ -665,7 +714,7 @@ EventData
             break;
         case EV_TBOOT_POLCTL:
             fprintf(fp, "[tboot:tb_policy_control]");
-            if (verbose_cnt > 0) {
+            if (getVerbosity() > 0) {
                 OPENPTS_EVENT_TBOOT_POLCTL *pc;
                 pc = (OPENPTS_EVENT_TBOOT_POLCTL *) buf;
                 /* show event data */
@@ -679,7 +728,7 @@ EventData
             break;
         case EV_TBOOT_MODULE:
             fprintf(fp, "[tboot:module]");
-            if (verbose_cnt > 0) {
+            if (getVerbosity() > 0) {
                 OPENPTS_EVENT_TBOOT_MODULE *ed;
                 ed = (OPENPTS_EVENT_TBOOT_MODULE *) buf;
                 UINT32 size;
@@ -713,13 +762,13 @@ EventData
             break;
 #endif
         default:
-            if ((verbose) && (len < 64)) {
+            if (isAnyDebugFlagSet() && (len < 64)) {
                 fprintf(fp, "[Unknown Event[%d]=0x", len);
                 for (i = 0; i < (int)len; i++) {
                     fprintf(fp, "%02x", (BYTE)buf[i]);
                 }
                 b64buf = encodeBase64(
-                    //(unsigned char *)b64buf,
+                    // (unsigned char *)b64buf,
                     (unsigned char *)buf,
                     len,
                     &b64buf_len);
@@ -809,7 +858,7 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
 
     /* open file */
     if ((fp = fopen(filename, "rb")) == NULL) {
-        ERROR("%s missing", filename);
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_IML2TEXT_FILE_MISSING, "Could not open file '%s'\n"), filename);
         return TSS_E_INTERNAL_ERROR;
     }
 
@@ -827,18 +876,16 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
             break;
 
         /* create wrapper */
-        ew = (OPENPTS_PCR_EVENT_WRAPPER *)malloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
+        ew = (OPENPTS_PCR_EVENT_WRAPPER *)xmalloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
         if (ew == NULL) {
-            ERROR("no memory\n");
             rc =  TSS_E_INTERNAL_ERROR;
             goto close;
         }
         memset(ew, 0, sizeof(OPENPTS_PCR_EVENT_WRAPPER));
 
         /* alloc new event */
-        ew->event = (TSS_PCR_EVENT *) malloc(sizeof(TSS_PCR_EVENT));
+        ew->event = (TSS_PCR_EVENT *) xmalloc(sizeof(TSS_PCR_EVENT));
         if (ew->event == NULL) {
-            printf("no memory\n");
             rc =  TSS_E_INTERNAL_ERROR;
             goto close;
         }
@@ -858,8 +905,7 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
 
         /* Digest */
         ew->event->ulPcrValueLength = SHA1_DIGEST_SIZE;
-        if ((ew->event->rgbPcrValue = (BYTE *) malloc(SHA1_DIGEST_SIZE)) == NULL) {
-            ERROR("no memory");
+        if ((ew->event->rgbPcrValue = (BYTE *) xmalloc(SHA1_DIGEST_SIZE)) == NULL) {
             rc =  TSS_E_INTERNAL_ERROR;
             goto close;
         }
@@ -870,9 +916,9 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
             goto close;
         }
 
-        if (verbose == DEBUG_FLAG) {
+        if (isDebugFlagSet(DEBUG_FLAG)) {
             DEBUG("digest");
-            printHex("\t\t\t\t", ew->event->rgbPcrValue, 20, "\n");
+            debugHex("\t\t\t\t", ew->event->rgbPcrValue, 20, "\n");
         }
 
         /* EventData len */
@@ -900,8 +946,7 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
         DEBUG("\tevent size = 0x%x (%d)\n", ew->event->ulEventLength, ew->event->ulEventLength);
 
         /* EventData  */
-        if ((ew->event->rgbEvent = malloc(aligned_length)) == NULL) {
-            ERROR("no memory");
+        if ((ew->event->rgbEvent = xmalloc(aligned_length)) == NULL) {
             rc =  TSS_E_INTERNAL_ERROR;
             goto close;
         }
@@ -915,9 +960,10 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
             goto close;
         }
 
-        if (verbose == DEBUG_FLAG) {
+        if (isDebugFlagSet(DEBUG_FLAG)) {
             DEBUG("");
-            printHex("\tevent data", ew->event->rgbEvent, ew->event->ulEventLength, "\n");
+            debugHex(NLS(MS_OPENPTS, OPENPTS_IML2TEXT_EVENT_DATA, "\tevent data"),
+                ew->event->rgbEvent, ew->event->ulEventLength, "\n");
         }
 
         /* move to EW chain */
@@ -943,7 +989,6 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
     /* maloc */
     *pcr_events = calloc(*event_num, sizeof(TSS_PCR_EVENT));
     if ((*pcr_events) == NULL) {
-        ERROR("no memory\n");
         rc = TSS_E_INTERNAL_ERROR;
         goto close;
     }
@@ -958,8 +1003,8 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
         /* free event, ew (PCR.EventData are linked to pcr_events) */
         ew_last->event->rgbPcrValue = NULL;
         ew_last->event->rgbEvent = NULL;
-        free(ew_last->event);
-        free(ew_last);
+        xfree(ew_last->event);
+        xfree(ew_last);
     }
     ew = NULL;
 
@@ -974,11 +1019,15 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
     /* free for error */
     if (ew != NULL) {
         if (ew->event != NULL) {
-            if (ew->event->rgbPcrValue != NULL) free(ew->event->rgbPcrValue);
-            if (ew->event->rgbEvent != NULL) free(ew->event->rgbEvent);
-            free(ew->event);
+            if (ew->event->rgbPcrValue != NULL) {
+                xfree(ew->event->rgbPcrValue);
+            }
+            if (ew->event->rgbEvent != NULL) {
+                xfree(ew->event->rgbEvent);
+            }
+            xfree(ew->event);
         }
-        free(ew);
+        xfree(ew);
     }
 
     return rc;  // TSS_E_INTERNAL_ERROR;
@@ -988,17 +1037,18 @@ TSS_RESULT getEventLog(char *filename, int endian, int aligned, UINT32 *event_nu
  * Usage
  */
 void usage(void) {
-    fprintf(stderr, "OpenPTS command\n\n");
-    fprintf(stderr, "Usage: iml2text [options]\n\n");
-    fprintf(stderr, "Options:\n");
-    fprintf(stderr, "  -i filename           Set binary eventlog file (at securityfs)\n");
-    fprintf(stderr, "  -p pcr_index          Select pcr (TSS)\n");
-    fprintf(stderr, "  -I mode               Select IMA's log format (Kernel 2.6.32:32)\n");
-    fprintf(stderr, "  -V                    Verify\n");
-    fprintf(stderr, "  -D                    DRTM\n");
-    fprintf(stderr, "  -E                    Enable endian conversion (BE->LE or LE->BE)\n");
-    fprintf(stderr, "  -h                    Show this help message\n");
-    fprintf(stderr, "\n");
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_IML2TEXT_USAGE,
+        "OpenPTS command\n\n"
+        "Usage: iml2text [options]\n\n"
+        "Options:\n"
+        "  -i filename           Set binary eventlog file (at securityfs)\n"
+        "  -p pcr_index          Select pcr (TSS)\n"
+        "  -I mode               Select IMA's log format (Kernel 2.6.32:32)\n"
+        "  -V                    Verify\n"
+        "  -D                    DRTM\n"
+        "  -E                    Enable endian conversion (BE->LE or LE->BE)\n"
+        "  -h                    Show this help message\n"
+        "\n"));
 }
 
 /**
@@ -1027,6 +1077,8 @@ int main(int argc, char *argv[]) {
     BYTE *blob;
     UINT32 blobLength;
 
+    initCatalog();
+
     /* init */
     memset(zero, 0, 20);
     memset(fox, 0xff, 20);
@@ -1053,7 +1105,7 @@ int main(int argc, char *argv[]) {
             aligned = 4;
             break;
         case 'v':  /* DEBUG */
-            verbose_cnt++;
+            incVerbosity();
             break;
         case 'V':  /* verify  */
             verify = 1;
@@ -1065,7 +1117,7 @@ int main(int argc, char *argv[]) {
             usage();
             return 0;
         default:
-            fprintf(stderr, "bad option '%c'\n", c);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_IML2TEXT_BAD_OPTION_C, "bad option '%c'\n"), c);
             usage();
             return -1;
         }
@@ -1086,8 +1138,9 @@ int main(int argc, char *argv[]) {
         }
     }
 
-    if (verbose_cnt > 1) {
-       verbose = DEBUG_FLAG;
+
+    if (getVerbosity() > 1) {
+       setDebugFlags(DEBUG_FLAG);
     }
 
     /* TSS and Verify */
@@ -1095,14 +1148,14 @@ int main(int argc, char *argv[]) {
         /* in both cases, we have to connect to TCSD */
         result = Tspi_Context_Create(&hContext);
         if (result != TSS_SUCCESS) {
-            printf("ERROR: Tspi_Context_Create failed rc=0x%x\n",
+            ERROR("ERROR: Tspi_Context_Create failed rc=0x%x\n",
                    result);
             goto close;
         }
 
         result = Tspi_Context_Connect(hContext, SERVER);
         if (result != TSS_SUCCESS) {
-            printf("ERROR: Tspi_Context_Connect failed rc=0x%x\n",
+            ERROR("ERROR: Tspi_Context_Connect failed rc=0x%x\n",
                    result);
             goto close;
         }
@@ -1110,7 +1163,7 @@ int main(int argc, char *argv[]) {
         /* Get TPM handles */
         result = Tspi_Context_GetTpmObject(hContext, &hTPM);
         if (result != TSS_SUCCESS) {
-            printf("ERROR: Tspi_Context_GetTpmObject failed rc=0x%x\n",
+            ERROR("ERROR: Tspi_Context_GetTpmObject failed rc=0x%x\n",
                    result);
             goto close;
         }
@@ -1124,7 +1177,7 @@ int main(int argc, char *argv[]) {
                     &ulEventNumber,
                     &PcrEvents);
         if (result != TSS_SUCCESS) {  // ERROR
-            printf("ERROR: Tspi_TPM_GetEventLog failed rc=0x%x\n",
+            ERROR("ERROR: Tspi_TPM_GetEventLog failed rc=0x%x\n",
                    result);
             goto close;
         }
@@ -1157,7 +1210,8 @@ int main(int argc, char *argv[]) {
                 PcrEvents[i].ulEventLength,
                 PcrEvents[i].ulPcrIndex,
                 PcrEvents[i].eventType,
-                PcrEvents[i].rgbPcrValue);
+                PcrEvents[i].rgbPcrValue,
+                endian);
 
             fprintf(fp, "\n");
 
@@ -1243,10 +1297,14 @@ int main(int argc, char *argv[]) {
     } else {
         // TODO free PcrEvents
         for (i = 0; i < (int)ulEventNumber; i++) {
-            if (PcrEvents[i].rgbPcrValue != NULL) free(PcrEvents[i].rgbPcrValue);
-            if (PcrEvents[i].rgbEvent != NULL) free(PcrEvents[i].rgbEvent);
+            if (PcrEvents[i].rgbPcrValue != NULL) {
+                xfree(PcrEvents[i].rgbPcrValue);
+            }
+            if (PcrEvents[i].rgbEvent != NULL) {
+                xfree(PcrEvents[i].rgbEvent);
+            }
         }
-        free(PcrEvents);
+        xfree(PcrEvents);
     }
     /* Close TSS/TPM */
 
index ef4afa9..be520a6 100644 (file)
--- a/src/imv.c
+++ b/src/imv.c
@@ -50,8 +50,8 @@
 #include <string.h>
 
 #include <tncifimv.h>
-
 #include <openpts.h>
+// #include <log.h>
 
 // ifm.c
 BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len);
@@ -64,7 +64,7 @@ static OPENPTS_CONFIG *conf = NULL;
 static OPENPTS_CONTEXT *ctx = NULL;
 static int result = OPENPTS_RESULT_UNKNOWN;
 
-int verbose = 0;
+// int verbose = 0;
 // int verbose = DEBUG_IFM_FLAG;
 // int verbose = DEBUG_FLAG | DEBUG_IFM_FLAG;
 
@@ -98,11 +98,22 @@ static TNC_TNCS_SendMessagePointer           sendMessagePtr;
 
 
 /* List of receive message types */
+// static TNC_MessageType messageTypes[] = {
+//    TNCMESSAGENUM(TNC_VENDORID_TCG, TNC_SUBTYPE_ANY),  // generic
+//    TNCMESSAGENUM(VENDORID,  0),
+//    TNCMESSAGENUM(VENDORID,  2),
+//    TNCMESSAGENUM(VENDORID,  4),
+//    TNCMESSAGENUM(VENDORID,  6),
+//    TNCMESSAGENUM(VENDORID,  8),
+//    TNCMESSAGENUM(VENDORID, 10),
+// };
 static TNC_MessageType messageTypes[] = {
-    ((TNC_VENDORID_TCG_PEN << 8) | TNC_SUBTYPE_TCG_PTS),  // generic
+    ((TNC_VENDORID_PA_TNC << 8) | TNC_VENDORID_PA_TNC),   // TNC generic (Error)
+//    ((TNC_VENDORID_TCG_PEN << 8) | TNC_SUBTYPE_TCG_PTS),  // PTS generic
     ((TNC_VENDORID_OPENPTS << 8) | TNC_SUBTYPE_OPENPTS)   // OpenPTS
 };
 
+
 /* IMV Functions */
 
 /**
@@ -173,14 +184,14 @@ TNC_IMV_API TNC_Result TNC_IMV_Initialize(
     /* initialize PTS */
     conf =  newPtsConfig();
     if (conf == NULL) {
-        ERROR("Can not allocate OPENPTS_CONFIG\n");
+        // ERROR("Can not allocate OPENPTS_CONFIG\n");
         rc = TNC_RESULT_FATAL;
         goto error;
     }
 
     ctx =  newPtsContext(conf);
     if (ctx == NULL) {
-        ERROR("Can not allocate OPENPTS_CONTEXT\n");
+        // ERROR("Can not allocate OPENPTS_CONTEXT\n");
         rc = TNC_RESULT_FATAL;
         goto error;
     }
@@ -496,7 +507,7 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
                     (TNC_BufferReference)msg,
                     len,
                     ((TNC_VENDORID_OPENPTS << 8) | TNC_SUBTYPE_OPENPTS));
-            free(msg);
+            xfree(msg);
             DEBUG_IFM("[C<-V] OPENPTS_CAPABILITIES[%d]\n", len);
 
 
@@ -510,13 +521,13 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
                         (TNC_BufferReference)msg,
                         len,
                         ((TNC_VENDORID_OPENPTS << 8) | TNC_SUBTYPE_OPENPTS));
-                free(msg);
+                xfree(msg);
                 DEBUG_IFM("[C<-V] REQUEST_TPM_PUBKEY[%d]\n", len);
             } else {
                 /*start verify, send NONCE and IR REQ*/
                 /* Next : Send NONCE */
                 ctx->nonce->nonce_length = 20;
-                ctx->nonce->nonce = malloc(20);
+                ctx->nonce->nonce = xmalloc_assert(20);
                 rc = getRandom(ctx->nonce->nonce, 20);
                 if (rc != PTS_SUCCESS) {
                     ERROR("getRandom() fail\n");
@@ -530,7 +541,7 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
                         (TNC_BufferReference)msg,
                         len,
                         ((TNC_VENDORID_OPENPTS << 8) | TNC_SUBTYPE_OPENPTS));
-                free(msg);
+                xfree(msg);
                 DEBUG_IFM("[C<-V] NONCE[%d]\n", len);
 
                 /* Next : REQ IR */
@@ -542,7 +553,7 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
                         (TNC_BufferReference)msg,
                         len,
                         ((TNC_VENDORID_OPENPTS << 8) | TNC_SUBTYPE_OPENPTS));
-                free(msg);
+                xfree(msg);
                 DEBUG_IFM("[C<-V] REQUEST_INTEGRITY_REPORT[%d]\n", len);
             }
             break;
@@ -556,9 +567,8 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
             } else {
                 /* PUBKEY -> target_conf */
                 ctx->target_conf->pubkey_length = length;
-                ctx->target_conf->pubkey = malloc(ctx->target_conf->pubkey_length);
+                ctx->target_conf->pubkey = xmalloc(ctx->target_conf->pubkey_length);
                 if (ctx->target_conf->pubkey == NULL) {
-                    ERROR("no memory");
                     return TNC_RESULT_FATAL;
                 }
 
@@ -578,7 +588,7 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
                         (TNC_BufferReference)msg,
                         len,
                         ((TNC_VENDORID_OPENPTS << 8) | TNC_SUBTYPE_OPENPTS));
-                free(msg);
+                xfree(msg);
                 DEBUG_IFM("[C<-V] REQUEST_RIMM_SET[%d]\n", len);
             }
             break;
@@ -601,7 +611,7 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
 
             /* Next : Send NONCE */
             ctx->nonce->nonce_length = 20;
-            ctx->nonce->nonce = malloc(20);
+            ctx->nonce->nonce = xmalloc_assert(20);
             rc = getRandom(ctx->nonce->nonce, 20);
             if (rc != PTS_SUCCESS) {
                 ERROR("getRandom() fail\n");
@@ -615,7 +625,7 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
                     (TNC_BufferReference)msg,
                     len,
                     ((TNC_VENDORID_OPENPTS << 8) | TNC_SUBTYPE_OPENPTS));
-            free(msg);
+            xfree(msg);
             DEBUG_IFM("[C<-V] NONCE[%d]\n", len);
 
             /* Next : REQ IR */
@@ -627,7 +637,7 @@ TNC_IMV_API TNC_Result TNC_IMV_ReceiveMessage(
                     (TNC_BufferReference)msg,
                     len,
                     ((TNC_VENDORID_OPENPTS << 8) | TNC_SUBTYPE_OPENPTS));
-            free(msg);
+            xfree(msg);
             DEBUG_IFM("[C<-V] REQUEST_INTEGRITY_REPORT[%d]\n", len);
 
             break;
index 2cb9a51..fd64665 100644 (file)
--- a/src/ir.c
+++ b/src/ir.c
  *
  */
 
+#include <sys/stat.h>
 #include <stdio.h>
 #include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
 
 #include <libxml/encoding.h>
 #include <libxml/xmlwriter.h>
 #include <libxml/parser.h>
 
 #include <openpts.h>
+// #include <log.h>
+
+enum {
+    TEXT_WRITER_START_ELEMENT,
+    TEXT_WRITER_WRITE_ATTR,
+    TEXT_WRITER_WRITE_FORMAT_ELEMENT,
+    TEXT_WRITER_END_ELEMENT,
+    TEXT_WRITER_WRITE_BASE64,
+    TEXT_WRITER_START_DOC,
+    TEXT_WRITER_FLUSH,
+    TEXT_WRITER_END_DOC,
+    XML_FUNC_END
+};
+
+void displayXmlError(int errorIndex, int rc) {
+    char *xmlFuncStrings[XML_FUNC_END] = {
+        "xmlTextWriterStartElement",
+        "xmlTextWriterWriteAttribute",
+        "xmlTextWriterWriteFormatElement",
+        "xmlTextWriterEndElement",
+        "xmlTextWriterWriteBase64",
+        "xmlTextWriterStartDocument",
+        "xmlTextWriterFlush",
+        "xmlTextWriterEndDocument",
+    };
+
+    ERROR("XML function '%s' returned '%d'\n", xmlFuncStrings[errorIndex], rc);
+}
 
 /**
  * free  All FSM in ctx
@@ -121,17 +153,15 @@ int freeAllFsm(OPENPTS_CONTEXT *ctx) {
 OPENPTS_IR_CONTEXT *newIrContext() {
     OPENPTS_IR_CONTEXT *ctx;
 
-    ctx = (OPENPTS_IR_CONTEXT *) malloc(sizeof(OPENPTS_IR_CONTEXT));
+    ctx = (OPENPTS_IR_CONTEXT *) xmalloc(sizeof(OPENPTS_IR_CONTEXT));
     if (ctx == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memset(ctx, 0, sizeof(OPENPTS_IR_CONTEXT));
 
-    ctx->buf = malloc(EVENTDATA_BUF_SIZE);
+    ctx->buf = xmalloc(EVENTDATA_BUF_SIZE);
     if (ctx->buf == NULL) {
-        ERROR("no memory\n");
-        free(ctx);
+        xfree(ctx);
         return NULL;
     }
     memset(ctx->buf, 0, EVENTDATA_BUF_SIZE);
@@ -151,10 +181,10 @@ void freeIrContext(OPENPTS_IR_CONTEXT *ctx) {
     }
 
     if (ctx->buf != NULL) {
-        free(ctx->buf);
+        xfree(ctx->buf);
     }
 
-    free(ctx);
+    xfree(ctx);
 }
 
 
@@ -193,7 +223,7 @@ int writeComponentID(
     /* element "core:ComponentID" */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "core:ComponentID");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");  // TODO(munetoh) SYSLOG
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);  // TODO(munetoh) SYSLOG
         goto error;
     }
 
@@ -204,7 +234,7 @@ int writeComponentID(
             BAD_CAST "Id",
             BAD_CAST id);  // TODO(munetoh)
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
     }
 
@@ -214,7 +244,7 @@ int writeComponentID(
             BAD_CAST "ModelSystemClass",
             BAD_CAST "745749J");  // TODO(munetoh)
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
     }
 
@@ -224,7 +254,7 @@ int writeComponentID(
             BAD_CAST "SimpleName",
             BAD_CAST simpleName);  // "745749J 6DET58WW (3.08 )");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
     }
 
@@ -234,7 +264,7 @@ int writeComponentID(
             BAD_CAST "VersionBuild",
             BAD_CAST "1250694000000");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
     }
 
@@ -245,7 +275,7 @@ int writeComponentID(
             BAD_CAST "VersionString",
             BAD_CAST versionString);  // "6DET58WW (3.08 )");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
     }
 
@@ -254,7 +284,7 @@ int writeComponentID(
             writer,
             BAD_CAST "core:VendorID");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         goto error;
     }
 
@@ -264,7 +294,7 @@ int writeComponentID(
             BAD_CAST "Name",
             BAD_CAST vendor);  // "LENOVO");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
     }
 
@@ -274,7 +304,7 @@ int writeComponentID(
             writer,
             BAD_CAST "core:SmiVendorId", "%d", 0);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteFormatElement\n");
+        displayXmlError(TEXT_WRITER_WRITE_FORMAT_ELEMENT, rc);
         goto error;
     }
 
@@ -284,21 +314,21 @@ int writeComponentID(
             writer,
             BAD_CAST "core:TcgVendorId", "%s", "DEMO");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteFormatElement\n");
+        displayXmlError(TEXT_WRITER_WRITE_FORMAT_ELEMENT, rc);
         goto error;
     }
 
     /* Close the element "core:VendorID". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        printf("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         goto error;
     }
 
     /* Close the element"core:ComponentID". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         goto error;
     }
 
@@ -310,11 +340,11 @@ int writeComponentID(
 
  free:
     if (simpleName != NULL)
-        free(simpleName);
+        xfree(simpleName);
     if (vendor != NULL)
-        free(vendor);
+        xfree(vendor);
     if (versionString != NULL)
-        free(versionString);
+        xfree(versionString);
 
     return rc;
 }
@@ -334,7 +364,7 @@ int writeDigestMethod(xmlTextWriterPtr writer) {
             writer,
             BAD_CAST "core:DigestMethod");
     if (rc < 0) {
-        printf("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -344,7 +374,7 @@ int writeDigestMethod(xmlTextWriterPtr writer) {
             BAD_CAST "Algorithm",
             BAD_CAST "unknown");
     if (rc < 0) {
-        printf("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -354,14 +384,14 @@ int writeDigestMethod(xmlTextWriterPtr writer) {
             BAD_CAST "Id",
             BAD_CAST "sha1");
     if (rc < 0) {
-        printf("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Close the element named "core:DigestMethod". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        printf("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -391,97 +421,129 @@ int writeStuffObjects(
         int ss_level,
         int eventindex) {
     char id[256];  // TODO(munetoh)
+    int rc;
 
-    if (event == NULL) {
-        ERROR("writeStuffObjects, event == NULL\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != event, "writeStuffObjects, event == NULL\n");
 
     snprintf(id, sizeof(id), "PCR_%d_LV%d_%d_%d_EVENT",
         event->ulPcrIndex, ss_level, event->eventType, eventindex);
 
-    DEBUG_XML("writeStuffObjects - pcr %d,id %s\n", event->ulPcrIndex, id);
+    DEBUG_XML("addStuffObjects - pcr %d,id %s\n", event->ulPcrIndex, id);
 
     /* start "stuff:Objects" */
-    if (xmlTextWriterStartElement(
+    rc = xmlTextWriterStartElement(
             writer,
-            BAD_CAST "stuff:Objects") < 0)
+            BAD_CAST "stuff:Objects");
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         goto error;
+    }
 
     /* start "stuff:Hash" */
-    if (xmlTextWriterStartElement(
+    rc = xmlTextWriterStartElement(
             writer,
-            BAD_CAST "stuff:Hash") < 0)
+            BAD_CAST "stuff:Hash");
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         goto error;
+    }
 
     /* Add an attribute with name "AlgRef" */
-    if (xmlTextWriterWriteAttribute(
+    rc = xmlTextWriterWriteAttribute(
             writer,
             BAD_CAST "AlgRef",
             // BAD_CAST ALG_NAME[algtype]) < 0)
-            BAD_CAST getAlgString(algtype)) < 0)
+            BAD_CAST getAlgString(algtype));
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
+    }
 
     /* Add an attribute with name "Id" */
-    if (xmlTextWriterWriteAttribute(
+    rc = xmlTextWriterWriteAttribute(
             writer,
             BAD_CAST "Id",
-            BAD_CAST id) < 0)
+            BAD_CAST id);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
+    }
 
     /* Write a text  */
-    if (xmlTextWriterWriteBase64(
+    rc = xmlTextWriterWriteBase64(
             writer,
             (const char *) event->rgbPcrValue,
             0,
-            event->ulPcrValueLength) < 0)
+            event->ulPcrValueLength);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_BASE64, rc);
         goto error;
+    }
 
     /* Close the element named "stuff:Hash". */
-    if (xmlTextWriterEndElement(writer) < 0)
+    rc = xmlTextWriterEndElement(writer);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         goto error;
+    }
 
     /* Write an element named "pcrindex" */
-    if (xmlTextWriterWriteFormatElement(
+    rc = xmlTextWriterWriteFormatElement(
             writer,
             BAD_CAST "pcrindex",
-            "%d", event->ulPcrIndex) < 0)
+            "%d", event->ulPcrIndex);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_FORMAT_ELEMENT, rc);
         goto error;
+    }
 
     /* Write an element named "eventtype" */
-    if (xmlTextWriterWriteFormatElement(
+    rc = xmlTextWriterWriteFormatElement(
             writer,
             BAD_CAST "eventtype",
-            "%d", event->eventType) < 0)
+            "%d", event->eventType);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_FORMAT_ELEMENT, rc);
         goto error;
+    }
 
     if (event->ulEventLength > 0) {
         /* Start an element named "eventdata" as child of "eventdata". */
-        if (xmlTextWriterStartElement(
+        rc = xmlTextWriterStartElement(
                 writer,
-                BAD_CAST "eventdata") < 0)
+                BAD_CAST "eventdata");
+        if (rc < 0) {
+            displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
             goto error;
+        }
 
         /* Write a text */
-        if (xmlTextWriterWriteBase64(
+        rc = xmlTextWriterWriteBase64(
                 writer,
                 (const char *) event->rgbEvent,
                 0,
-                event->ulEventLength) < 0) {
-            ERROR("rgbEvent  len %d \n", event->ulEventLength);
+                event->ulEventLength);
+        if (rc < 0) {
+            displayXmlError(TEXT_WRITER_WRITE_BASE64, rc);
             goto error;
         }
 
         /* Close the element named "eventdata". */
-        if (xmlTextWriterEndElement(writer) < 0)
+        rc = xmlTextWriterEndElement(writer);
+        if (rc < 0) {
+            displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
             goto error;
+        }
     } else {
         // printf("SM DEBUG no eventdata\n");
     }
 
     /* Close the element named "stuff:Objects". */
-    if (xmlTextWriterEndElement(writer) < 0)
+    rc = xmlTextWriterEndElement(writer);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         goto error;
+    }
 
     return PTS_SUCCESS;
 
@@ -515,57 +577,80 @@ int writePcrHash(
         int algtype) {
     // int rc = PTS_SUCCESS;
     char id[256];  // TODO(munetoh) 11+1+1 = 12?
+    int rc;
 
     DEBUG_CAL("writePcrHash - PCR[%d] level %d \n", pcrIndex, ss_level);
 
     snprintf(id, sizeof(id), "PCR_%d_LV%d_HASH", pcrIndex, ss_level);
 
     /* Start an element named "eventdata" as child of "PcrHash". */
-    if (xmlTextWriterStartElement(writer, BAD_CAST "PcrHash") < 0)
+    rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrHash");
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         goto error;
+    }
 
     /* Add an attribute with name "AlgRef" */
-    if (xmlTextWriterWriteAttribute(
+    rc = xmlTextWriterWriteAttribute(
             writer,
             BAD_CAST "AlgRef",
             // BAD_CAST ALG_NAME[algtype]) < 0)
-            BAD_CAST getAlgString(algtype)) < 0)
+            BAD_CAST getAlgString(algtype));
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
+    }
 
     /* Add an attribute with name "Id" */
-    if (xmlTextWriterWriteAttribute(writer, BAD_CAST "Id", BAD_CAST id)
-            < 0)
+    rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "Id", BAD_CAST id);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
+    }
 
     /* Add an attribute with name "IsResetable" */
-    if (xmlTextWriterWriteAttribute(
+    rc = xmlTextWriterWriteAttribute(
             writer,
             BAD_CAST "IsResetable",
-            BAD_CAST "false") < 0)
+            BAD_CAST "false");
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
+    }
 
     /* Add an attribute with name "Number" */
     snprintf(id, sizeof(id), "%d", pcrIndex);
-    if (xmlTextWriterWriteAttribute(writer, BAD_CAST "Number", BAD_CAST id) < 0)
+    rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "Number", BAD_CAST id);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
+    }
 
     /* Add an attribute with name "StartHash" */
     // TODO(munetoh) convert startHash to base64 string
-    if (xmlTextWriterWriteAttribute(
+    rc = xmlTextWriterWriteAttribute(
             writer,
             BAD_CAST "StartHash",
-            BAD_CAST "AAAAAAAAAAAAAAAAAAAAAAAAAAA=") < 0)
+            BAD_CAST "AAAAAAAAAAAAAAAAAAAAAAAAAAA=");
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         goto error;
+    }
 
     /* Write a text */
-    if (xmlTextWriterWriteBase64(writer, (const char *) hash, 0, 20) < 0) {
-        printf("SM DEBUG ERROR  digest len %d \n", 20);
+    rc = xmlTextWriterWriteBase64(writer, (const char *) hash, 0, 20);
+    if (rc < 0) {
+        // printf("SM DEBUG ERROR  digest len %d \n", 20);
+        displayXmlError(TEXT_WRITER_WRITE_BASE64, rc);
         goto error;
     }
 
     /* Close the element named "PcrHash". */
-    if (xmlTextWriterEndElement(writer) < 0)
+    rc = xmlTextWriterEndElement(writer);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         goto error;
+    }
 
     return PTS_SUCCESS;
 
@@ -589,7 +674,7 @@ int writeSnapshot(
     int j;
     PTS_UUID *ir_uuid;
     char *str_ir_uuid;
-    char id[256]; // TODO 3 + UUID = 3 + 36 = 39
+    char id[256];  // TODO 3 + UUID = 3 + 36 = 39
     int level;
 
     level = ss->level;
@@ -613,7 +698,7 @@ int writeSnapshot(
     /* Start an element named "SnapshotCollection" as child of Report. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "SnapshotCollection");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         rc = PTS_INTERNAL_ERROR;
         goto error;
     }
@@ -629,7 +714,7 @@ int writeSnapshot(
     if (str_ir_uuid == NULL) {
         ERROR("UUID \n");
         rc = PTS_INTERNAL_ERROR;
-        free(ir_uuid);
+        xfree(ir_uuid);
         goto error;
     }
 
@@ -638,7 +723,7 @@ int writeSnapshot(
     /* Add an attribute with name "Id" */
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "Id", BAD_CAST id);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -647,14 +732,14 @@ int writeSnapshot(
     rc = xmlTextWriterWriteAttribute(
             writer, BAD_CAST "UUID", BAD_CAST str_ir_uuid);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
     /* Add an attribute with name "RevLevel" */
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "RevLevel", BAD_CAST "0");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -666,7 +751,7 @@ int writeSnapshot(
     /* Start an element named "core:Values" as child of "SnapshotCollection". */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "core:Values");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -675,7 +760,7 @@ int writeSnapshot(
     rc = xmlTextWriterStartElement(
             writer, BAD_CAST "stuff:SimpleSnapshotObject");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -703,7 +788,7 @@ int writeSnapshot(
     /* Close the element named "stuff:SimpleSnapshotObject". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        printf("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -711,7 +796,7 @@ int writeSnapshot(
     /* Close the element named "core:Values". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        printf("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -730,7 +815,7 @@ int writeSnapshot(
     /* Close the element named "SnapshotCollection". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        printf("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -738,8 +823,8 @@ int writeSnapshot(
     rc = PTS_SUCCESS;
 
   free:
-    free(ir_uuid);
-    free(str_ir_uuid);
+    xfree(ir_uuid);
+    xfree(str_ir_uuid);
 
   error:
     DEBUG_CAL("addSnapshot - done, rc=%d\n", rc);
@@ -788,7 +873,7 @@ int writeQuote(
     int b64buf_len;
     int size_of_select = 0;
     int select_int = 0;
-    BYTE select_byte[3]; // TODO TPM1.2, 24PCRs => 3 bytes
+    BYTE select_byte[3];  // TODO TPM1.2, 24PCRs => 3 bytes
     char tagbuf[128];
 
     if (ctx->pcrs == NULL) {
@@ -803,28 +888,28 @@ int writeQuote(
     /* Start an element named "QuoteData" as child of Report. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "QuoteData");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Add an attribute with name "ID" */
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "ID", BAD_CAST "TBD");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Start an element named "Quote" as child of QuoteData. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "Quote");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Start an element named "PcrComposit" as child of Quote. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrComposit");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -856,7 +941,7 @@ int writeQuote(
     /* Start an element named "PcrSelection" as child of PcrComposit. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrSelection");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -864,7 +949,7 @@ int writeQuote(
     snprintf(tagbuf, sizeof(tagbuf), "%d", size_of_select);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "SizeOfSelect", BAD_CAST tagbuf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -874,12 +959,13 @@ int writeQuote(
         size_of_select,
         &b64buf_len);
     if (b64buf == NULL) {
-        ERROR("encodeBase64 fail");
+        ERROR("encodeBase64 fail");  // TODO ERROR => displayXmlError
         return PTS_INTERNAL_ERROR;
     }
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "PcrSelect", BAD_CAST b64buf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     free(b64buf);
@@ -888,7 +974,8 @@ int writeQuote(
     /* Close the element named "PcrSelection". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        // ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -897,7 +984,7 @@ int writeQuote(
     /* Write an element named "ValueSize" as child of PcrComposit */
     rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "ValueSize", "%d", ctx->pcrs->value_size);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteFormatElement\n");
+        displayXmlError(TEXT_WRITER_WRITE_FORMAT_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -908,7 +995,7 @@ int writeQuote(
             /* Start an element named "PcrValue" as child of PcrComposit. */
             rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrValue");
             if (rc < 0) {
-                ERROR("Error at xmlTextWriterStartElement\n");
+                displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
                 return PTS_INTERNAL_ERROR;
             }
             /* Add an attribute with name "PcrNumber", int */
@@ -916,7 +1003,7 @@ int writeQuote(
             rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "PcrNumber", BAD_CAST tagbuf);
             // rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "PcrNumber", BAD_CAST "0");
             if (rc < 0) {
-                ERROR("Error at xmlTextWriterWriteAttribute\n");
+                displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
                 return PTS_INTERNAL_ERROR;
             }
 
@@ -927,14 +1014,14 @@ int writeQuote(
                     0,
                     20);  // TODO add length to OPENPTS_PCRS
             if (rc < 0) {
-                ERROR("Error at xmlTextWriterWriteBase64\n");
+                displayXmlError(TEXT_WRITER_WRITE_BASE64, rc);
                 return PTS_INTERNAL_ERROR;
             }
 
             /* Close the element named "PcrValue" */
             rc = xmlTextWriterEndElement(writer);
             if (rc < 0) {
-                ERROR("Error at xmlTextWriterEndElement\n");
+                displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
                 return PTS_INTERNAL_ERROR;
             }
         }  // selected
@@ -943,7 +1030,7 @@ int writeQuote(
     /* Close the element named "PcrComposit". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -951,7 +1038,7 @@ int writeQuote(
     /* Start an element named "QuoteInfo" as child of Quote. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "QuoteInfo");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -959,21 +1046,24 @@ int writeQuote(
     snprintf(tagbuf, sizeof(tagbuf), "%d", ctx->validation_data->versionInfo.bMajor);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "VersionMajor", BAD_CAST tagbuf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "VersionMinor", int */
     snprintf(tagbuf, sizeof(tagbuf), "%d", ctx->validation_data->versionInfo.bMinor);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "VersionMinor", BAD_CAST tagbuf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "VersionRevMajor", int */
     snprintf(tagbuf, sizeof(tagbuf), "%d", ctx->validation_data->versionInfo.bRevMajor);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "VersionRevMajor", BAD_CAST tagbuf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -981,14 +1071,16 @@ int writeQuote(
     snprintf(tagbuf, sizeof(tagbuf), "%d", ctx->validation_data->versionInfo.bRevMinor);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "VersionRevMinor", BAD_CAST tagbuf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Add an attribute with name "Fixed", int */
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "Fixed", BAD_CAST "QUOT");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return -1;
     }
 
@@ -1003,11 +1095,11 @@ int writeQuote(
     }
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "DigestValue", BAD_CAST b64buf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     free(b64buf);
-    b64buf=NULL;
+    b64buf = NULL;
 
     // TODO we used DH-nonce exchange but here, we put plain nonce:-P
     // TODO is this option attribute? can we suppress?
@@ -1022,23 +1114,26 @@ int writeQuote(
     }
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "ExternalData", BAD_CAST b64buf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     free(b64buf);
-    b64buf=NULL;
+    b64buf = NULL;
 
     /* Close the element named "QuoteInfo". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        // ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Close the element named "Quote". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        // ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1047,7 +1142,7 @@ int writeQuote(
     /* Start an element named "TpmSignature" as child of QuoteData. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "TpmSignature");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1056,7 +1151,7 @@ int writeQuote(
     /* Start an element named "SignatureMethod" as child of TpmSignature. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "SignatureMethod");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "Algorithm", string */
@@ -1064,13 +1159,13 @@ int writeQuote(
             BAD_CAST "Algorithm",
             BAD_CAST "http://www.w3.org/2000/09/xmldsig#rsa-sha1");  // TODO
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Close the element named "SignatureMethod". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1079,7 +1174,7 @@ int writeQuote(
     /* Start an element named "SignatureValue" as child of TpmSignature. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "SignatureValue");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Write a text, signature, base64  */
@@ -1089,27 +1184,27 @@ int writeQuote(
             0,
             ctx->validation_data->ulValidationDataLength);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteBase64\n");
+        displayXmlError(TEXT_WRITER_WRITE_BASE64, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Close the element named "SignatureValue". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Close the element named "TpmSignature". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Close the element named "QuoteData". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1187,28 +1282,28 @@ int writeQuote2(
     /* QuoteData - start */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "QuoteData");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "ID" */
     // TODO Set UUID based on now
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "ID", BAD_CAST "TBD");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Quote2 - start */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "Quote2");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* QuoteInfo2 - start */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "QuoteInfo2");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1216,15 +1311,15 @@ int writeQuote2(
     snprintf(tagbuf, sizeof(tagbuf), "%d", tag);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "Tag", BAD_CAST tagbuf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* QuoteInfo2 - attribute - Fixed - char */
     DEBUG("fixed : %s", fixed);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "Fixed", BAD_CAST fixed);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute, rc = %d\n", rc);
-        return -1;
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
+        return PTS_INTERNAL_ERROR;
     }
     /* QuoteInfo2 - attribute - ExternalData - base64 */
     b64buf = encodeBase64(
@@ -1238,28 +1333,32 @@ int writeQuote2(
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "ExternalData", BAD_CAST b64buf);
     free(b64buf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* PcrInfoShort - start */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrInfoShort");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        // ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* PcrSelection - start */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrSelection");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        // ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "SizeOfSelect", int */
     snprintf(tagbuf, sizeof(tagbuf), "%d", size_of_select);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "SizeOfSelect", BAD_CAST tagbuf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "PcrSelect", base64 */
@@ -1274,13 +1373,13 @@ int writeQuote2(
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "PcrSelect", BAD_CAST b64buf);
     free(b64buf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* PcrSelection - end */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1288,7 +1387,7 @@ int writeQuote2(
     /* LocalityAtRelease - element */
     rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "LocalityAtRelease", "%d", locality);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteFormatElement\n");
+        displayXmlError(TEXT_WRITER_WRITE_FORMAT_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1304,7 +1403,7 @@ int writeQuote2(
     rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "CompositeHash", "%s", b64buf);
     free(b64buf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteFormatElement\n");
+        displayXmlError(TEXT_WRITER_WRITE_FORMAT_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1312,21 +1411,24 @@ int writeQuote2(
     /* PcrComposite - start */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrComposit");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        // ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* PcrSelection - start */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrSelection");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        // ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "SizeOfSelect", int */
     snprintf(tagbuf, sizeof(tagbuf), "%d", size_of_select);
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "SizeOfSelect", BAD_CAST tagbuf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        // ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "PcrSelect", base64 */
@@ -1341,19 +1443,19 @@ int writeQuote2(
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "PcrSelect", BAD_CAST b64buf);
     free(b64buf);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* PcrSelection - end */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* ValueSize - element */
     rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "ValueSize", "%d", ctx->pcrs->value_size);
     if (rc < 0) {
-         ERROR("Error at xmlTextWriterWriteFormatElement\n");
+         displayXmlError(TEXT_WRITER_WRITE_FORMAT_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* PcrValue, loop */
@@ -1362,14 +1464,16 @@ int writeQuote2(
             /* PcrValue - start */
             rc = xmlTextWriterStartElement(writer, BAD_CAST "PcrValue");
             if (rc < 0) {
-                ERROR("Error at xmlTextWriterStartElement\n");
+                // ERROR("Error at xmlTextWriterStartElement\n");
+                displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
                 return PTS_INTERNAL_ERROR;
             }
             /* Add an attribute - PcrNumber - int */
             snprintf(tagbuf, sizeof(tagbuf), "%d", i);
             rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "PcrNumber", BAD_CAST tagbuf);
             if (rc < 0) {
-                ERROR("Error at xmlTextWriterWriteAttribute\n");
+                // ERROR("Error at xmlTextWriterWriteAttribute\n");
+                displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
                 return PTS_INTERNAL_ERROR;
             }
 
@@ -1381,14 +1485,14 @@ int writeQuote2(
                     0,
                     20);  // TODO add length to OPENPTS_PCRS
             if (rc < 0) {
-                ERROR("Error at xmlTextWriterWriteBase64\n");
+                displayXmlError(TEXT_WRITER_WRITE_BASE64, rc);
                 return PTS_INTERNAL_ERROR;
             }
 
             /* PcrValue - end */
             rc = xmlTextWriterEndElement(writer);
             if (rc < 0) {
-                ERROR("Error at xmlTextWriterEndElement\n");
+                displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
                 return PTS_INTERNAL_ERROR;
             }
         }  // selected
@@ -1396,14 +1500,14 @@ int writeQuote2(
     /* PcrComposite - end */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* PcrInfoShort - end */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1413,14 +1517,14 @@ int writeQuote2(
     /* QuoteInfo2 - end  */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Quote2 - end */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1429,7 +1533,7 @@ int writeQuote2(
     /* Start an element named "TpmSignature" as child of QuoteData. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "TpmSignature");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1438,7 +1542,7 @@ int writeQuote2(
     /* Start an element named "SignatureMethod" as child of TpmSignature. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "SignatureMethod");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Add an attribute with name "Algorithm", string */
@@ -1446,13 +1550,13 @@ int writeQuote2(
             BAD_CAST "Algorithm",
             BAD_CAST "http://www.w3.org/2000/09/xmldsig#rsa-sha1");  // TODO
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Close the element named "SignatureMethod". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1461,7 +1565,7 @@ int writeQuote2(
     /* Start an element named "SignatureValue" as child of TpmSignature. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "SignatureValue");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Write a text, signature, base64  */
@@ -1471,27 +1575,27 @@ int writeQuote2(
             0,
             ctx->validation_data->ulValidationDataLength);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteBase64\n");
+        displayXmlError(TEXT_WRITER_WRITE_BASE64, rc);
         return PTS_INTERNAL_ERROR;
     }
     /* Close the element named "SignatureValue". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Close the element named "TpmSignature". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
     /* Close the element named "QuoteData". */
     rc = xmlTextWriterEndElement(writer);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterEndElement\n");
+        displayXmlError(TEXT_WRITER_END_ELEMENT, rc);
         return PTS_INTERNAL_ERROR;
     }
 
@@ -1515,17 +1619,21 @@ int writeQuote2(
  *
  */
 // TODO remove file
-int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
+int writeIr(OPENPTS_CONTEXT *ctx, const char *filenameDP, int *savedFd) {
+//int writeIr(OPENPTS_CONTEXT *ctx, int *savedFd) {
     int rc = PTS_SUCCESS;
     int i;
+    int irFd;
+    int lengthOfIrFile;
     xmlTextWriterPtr writer;
     xmlBufferPtr xmlbuf;
-    FILE *fp;
+    // FILE *fp;
     PTS_ComponentId cid;
     OPENPTS_TPM_CONTEXT tpm;  // to calc snapshot PCR
     PTS_UUID *ir_uuid;
     char *str_ir_uuid;
-    char filename[256];  // TODO UUID_UUID.xml
+    char *filename = NULL;
+    // char filename[256];  // TODO UUID_UUID.xml
 
     PTS_Byte smbios[12] = { 0x4A, 0x4A, 0x4A, 0x4A, 0x4A,
                             0x4A, 0x4A, 0x4A, 0x4A, 0x4A,
@@ -1534,7 +1642,17 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
     char id[256];
     OPENPTS_SNAPSHOT *ss;
 
-    DEBUG_CAL("genIr - start\n");
+    DEBUG_CAL("writeIr - start\n");
+
+    /* check */
+    if (ctx == NULL) {
+        ERROR("ctx == NULL");
+        return PTS_FATAL;
+    }
+    //if (filename == NULL) {
+    //    ERROR("filename == NULL");
+    //    return PTS_FATAL;
+    //}
 
     // TODO(munetoh) dummy data
     cid.vendor.offset = 0;
@@ -1595,7 +1713,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
     /* Start the document */
     rc = xmlTextWriterStartDocument(writer, "1.0", XML_ENCODING, "no");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartDocument\n");
+        displayXmlError(TEXT_WRITER_START_DOC, rc);
         rc = PTS_INTERNAL_ERROR;
         goto freexml;
     }
@@ -1603,7 +1721,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
     /* Start an element named "Report", the root element of the document. */
     rc = xmlTextWriterStartElement(writer, BAD_CAST "Report");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterStartElement\n");
+        displayXmlError(TEXT_WRITER_START_ELEMENT, rc);
         rc = PTS_INTERNAL_ERROR;
         goto freexml;
     }
@@ -1618,7 +1736,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
             BAD_CAST "xmlns:core",
             BAD_CAST XMLNS_CORE);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto freexml;
     }
@@ -1628,7 +1746,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
             BAD_CAST "xmlns:stuff",
             BAD_CAST XMLNS_STUFF);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto freexml;
     }
@@ -1639,7 +1757,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
             BAD_CAST "xmlns:xsi",
             BAD_CAST "http://www.w3.org/2001/XMLSchema-instance");
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto freexml;
     }
@@ -1649,7 +1767,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
             BAD_CAST "xmlns",
             BAD_CAST XMLNS_IR);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto freexml;
     }
@@ -1666,7 +1784,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
     if (str_ir_uuid == NULL) {
         ERROR("fail UUID generation\n");
         rc = PTS_INTERNAL_ERROR;
-        free(ir_uuid);
+        xfree(ir_uuid);
         goto freexml;
     }
 
@@ -1675,7 +1793,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
 
     rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "ID", BAD_CAST id);
     if (rc < 0) {
-        printf("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -1684,7 +1802,7 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
     rc = xmlTextWriterWriteAttribute(
             writer, BAD_CAST "UUID", BAD_CAST str_ir_uuid);
     if (rc < 0) {
-        ERROR("Error at xmlTextWriterWriteAttribute\n");
+        displayXmlError(TEXT_WRITER_WRITE_ATTR, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -1737,14 +1855,29 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
         if (ss != NULL) {
             if (ss->event_num > 0) {
                 // ERROR("writeIr PCR[%d] LV1 num=%d\n", i,ss->event_num);
-                writeSnapshot(writer, &tpm, &cid, i, ss);
+                // writeSnapshot(writer, &tpm, &cid, i, ss);
+                if (i == OPENPTS_PCR_INDEX) {
+                    DEBUG("genIr - Not writing snapshot for OPENPTS_PCR_INDEX (%d)\n",
+                        OPENPTS_PCR_INDEX);
+                } else {
+                    writeSnapshot(writer, &tpm, &cid, i, ss);
+                }
             }
         }
     }  // PCR LOOP
 
+    /* Close all elements */
+    rc = xmlTextWriterEndDocument(writer);
+    if (rc < 0) {
+        displayXmlError(TEXT_WRITER_END_DOC, rc);
+        rc = PTS_INTERNAL_ERROR;
+        goto free;
+    }
+
     rc = xmlTextWriterFlush(writer);
     if (rc < 0) {
-        ERROR("writeRm: Error at xmlTextWriterFlush\n");
+        // ERROR("writeRm: Error at xmlTextWriterFlush\n");
+        displayXmlError(TEXT_WRITER_FLUSH, rc);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -1757,9 +1890,9 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
         goto free;
     }
 
-
+#if 0
     /* set IR file */
-    if (file != NULL) {
+    if (filename != NULL) {
         /* use given filename */
         ctx->conf->ir_filename = smalloc((char *)file);
     } else {
@@ -1777,10 +1910,31 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
 
         ctx->conf->ir_filename = getFullpathName(ctx->conf->ir_dir, filename);
     }
+#endif
+    if (ctx->ir_filename != NULL) {
+        /* use given filename  for the Unit Test*/
+        // filename = smalloc(ctx->conf->ir_filename);        filename = ctx->conf->ir_filename;
+    } else {
+        char buf[1024];
+        /* use default filename */
+        if (ctx->conf->ir_dir == NULL) {
+            ERROR("Set ir.dir in %s.\n", ctx->conf->config_file);
+            ctx->conf->ir_dir = smalloc("/tmp/.ptsc");
+        }
+        snprintf(buf, sizeof(buf), "%s_%s.xml",
+            ctx->str_uuid,
+            str_ir_uuid);
+
+        ctx->ir_filename = getFullpathName(ctx->conf->ir_dir, buf);
+    }
+
+    filename = ctx->ir_filename;
+    DEBUG("Write Integrity Report (IR)  : %s\n", filename);
 
     /* write to file */
     xmlFreeTextWriter(writer);
 
+#if 0
     fp = fopen(ctx->conf->ir_filename, "w");
     if (fp == NULL) {
         ERROR("testXmlwriterMemory: Error at fopen, %s\n", ctx->conf->ir_filename);
@@ -1793,18 +1947,54 @@ int writeIr(OPENPTS_CONTEXT *ctx, const char *file) {
     rc = PTS_SUCCESS;  // 0
 
     fclose(fp);
+#endif
+
+    irFd = open(filename, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
+    if (-1 == irFd) {
+        ERROR("Failed to open ir file '%s' for writing, errno = %d\n", filename, errno);
+        rc = PTS_INTERNAL_ERROR;
+        goto free;
+    }
+
+    /* If savedFd is not NULL, the user wanted a little bit extra security
+       by not leaving the file lying around on the filesystem to be read/hacked/etc.
+       This is most useful during verification when running "ptsc -m". Anyway,
+       serious hackers probably wouldn't be deterred by this ... */
+    if (NULL != savedFd &&
+        -1 == unlink(filename)) {
+        ERROR("Failed to unlink file '%s', errno = %d\n", filename, errno);
+    }
+
+    lengthOfIrFile = xmlbuf->use;
+    {
+        int writeRc = write(irFd, xmlbuf->content, lengthOfIrFile);
+        if ( lengthOfIrFile != writeRc ) {
+            ERROR("Failed to write contents to IR file - rc %d, errno %d\n", writeRc, errno);
+            rc = PTS_INTERNAL_ERROR;
+            close(irFd);
+        } else {
+            rc = PTS_SUCCESS;  // 0
+            if (NULL != savedFd) {
+                *savedFd = irFd;
+                /* keep the file open - the caller will close it later */
+            } else {
+                close(irFd);
+            }
+        }
+    }
 
  free:
-    free(ir_uuid);
-    free(str_ir_uuid);
+    xfree(ir_uuid);
+    xfree(str_ir_uuid);
+    //if (filename != NULL) xfree(filename);
 
  freexml:
     xmlBufferFree(xmlbuf);
 
  error:
 
-    DEBUG("Write Integrity Report (IR)  : %s\n", file);
-    DEBUG_CAL("genIr - done\n");
+    
+    DEBUG_CAL("writeIr - done\n");
 
     return rc;
 }
@@ -1860,6 +2050,19 @@ void  irEndDocument(void * ctx) {
     // printf("END DOC \n");
 }
 
+/* This prevents real world buffer over-run attacks using malformed IRs
+   where pcr is basically an index onto the heap or stack. It has been 
+   already been demonstrated that this type of attack could fool the verifier
+   wrongly into presenting a valid attestation of a compromised system. */
+static int getPcrIndexFromIR(char *value) {
+    unsigned int index = atoi(value);
+    if ( index > MAX_PCRNUM ) {
+        return -1;
+    } else {
+        return index;
+    }
+}
+
 /**
  * SAX parser - Start of Element
  */
@@ -1924,7 +2127,7 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                     value= (char *)atts[i];
                     // printf("%s'", value);
                     if (!strcmp(type, "Number")) {
-                        ir_ctx->pcr_index = atoi(value);
+                        ir_ctx->pcr_index = getPcrIndexFromIR(value);
                     }
                 }
             }
@@ -1932,9 +2135,8 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
     } else if (!strcmp((char *)name, "stuff:Objects")) {
         /* New event */
         /* malloc */
-        ir_ctx->event = (TSS_PCR_EVENT *) malloc(sizeof(TSS_PCR_EVENT));
+        ir_ctx->event = (TSS_PCR_EVENT *) xmalloc(sizeof(TSS_PCR_EVENT));
         if (ir_ctx->event == NULL) {
-            ERROR("no memory\n");
             return;
         }
         memset(ir_ctx->event, 0, sizeof(TSS_PCR_EVENT));
@@ -1944,14 +2146,14 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
         // <QuoteData ID="TBD">...
         // TODO check ID?
         if (pcrs == NULL) {
-            pcrs = malloc(sizeof(OPENPTS_PCRS));
+            pcrs = xmalloc_assert(sizeof(OPENPTS_PCRS));
             // TODO check
             memset(pcrs, 0, sizeof(OPENPTS_PCRS));
             pctx->pcrs = pcrs;
             // DEBUG("malloc OPENPTS_PCRS %p\n", pcrs);
         }
         if (validation_data == NULL) {
-            validation_data = malloc(sizeof(TSS_VALIDATION));
+            validation_data = xmalloc_assert(sizeof(TSS_VALIDATION));
             // TODO check
             memset(validation_data, 0, sizeof(TSS_VALIDATION));
             pctx->validation_data = validation_data;
@@ -1992,8 +2194,15 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                             (char *)value,
                             strlen(value),
                             &b64buf_len);
-                        attr_cnt++;
+                        // attr_cnt++;
                         // DEBUG("PcrSelect = 0x%02x %02x %02x \n", buf[0],buf[1],buf[2]);
+                        if (b64buf == NULL) {
+                            ERROR("Failed to decode base64 string\n");
+                            ir_ctx->sax_error++;
+                            pcrs->pcr_select_size = 0;
+                        } else {
+                            attr_cnt++;
+                        }
                     }
                 }
             }
@@ -2003,17 +2212,17 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
         if (attr_cnt == 2) {
             // ir_ctx->pcrs->pcr_select_byte
             if (pcrs->pcr_select_byte != NULL) {
-                free(pcrs->pcr_select_byte);
+                xfree(pcrs->pcr_select_byte);
             }
-            pcrs->pcr_select_byte = malloc(pcrs->pcr_select_size);
-            if (pcrs->pcr_select_byte == NULL) {
-                ERROR("no memory\n");
-            } else {
+            pcrs->pcr_select_byte = xmalloc(pcrs->pcr_select_size);
+            if (pcrs->pcr_select_byte != NULL) {
                 if (b64buf != NULL) {
                     memcpy(pcrs->pcr_select_byte, b64buf, pcrs->pcr_select_size);
                 } else {
                     ERROR("pcr_select_byte is missing");
                 }
+            } else {
+                ERROR("no memory\n");
             }
         } else {
             /* BAD IR */
@@ -2022,7 +2231,7 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
         /* free Base64 buffer */
         if (b64buf != NULL) {
             free(b64buf);
-            b64buf=NULL;
+            b64buf = NULL;
         }
     } else if (!strcmp((char *)name, "ValueSize")) {
         // <ValueSize>200</ValueSize>
@@ -2039,7 +2248,7 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                     value= (char *)atts[i];
                     // printf("%s'", value);
                     if (!strcmp(type, "PcrNumber")) {
-                        ir_ctx->pcr_index = atoi(value);
+                        ir_ctx->pcr_index = getPcrIndexFromIR(value);
                     }
                 }
             }
@@ -2059,7 +2268,7 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                 if (validation_data->rgbData == NULL) {
                     // TODO 1.2 only
                     validation_data->ulDataLength = 48;
-                    validation_data->rgbData = malloc(48);
+                    validation_data->rgbData = xmalloc_assert(48);
                 }
 
                 // printf(", %s='", type);
@@ -2098,14 +2307,16 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                         if (b64buf == NULL) {
                             ERROR("decodeBase64 fail");
                             ir_ctx->sax_error++;
-                            return;
+                            return;  // TODO  return?
                         }
-                        if (b64buf_len < 20) {
-                            ERROR("decodeBase64 out is too small, %d < 20", b64buf_len);
+                        if (b64buf_len == 20) {
+                            memcpy(&validation_data->rgbData[8], b64buf, 20);
+                        } else {
+                            ERROR("size of decodeBase64 out is not 20 but %d", b64buf_len);
                             ir_ctx->sax_error++;
-                            return;
+                            return;  // TODO
                         }
-                        memcpy(&validation_data->rgbData[8], b64buf, 20);
+
                         free(b64buf);
                     }
                     if (!strcmp(type, "ExternalData")) {
@@ -2116,15 +2327,22 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                         if (b64buf == NULL) {
                             ERROR("decodeBase64 fail");
                             ir_ctx->sax_error++;
-                            return;
+                            return;  // TODO
                         }
-                        validation_data->ulExternalDataLength = b64buf_len;
-                        if (validation_data->rgbExternalData != NULL) {
-                            free(validation_data->rgbExternalData);
+                        if (b64buf_len == 20) {
+                            validation_data->ulExternalDataLength = b64buf_len;
+                            if (validation_data->rgbExternalData != NULL) {
+                                free(validation_data->rgbExternalData);
+                            }
+                            validation_data->rgbExternalData = b64buf;
+                            // TODO remove?
+                            // memcpy(validation_data->rgbExternalData, buf, rc);
+                            memcpy(&validation_data->rgbData[28], b64buf, 20);
+                        } else {
+                            ERROR("Failed to decode base64 string, len = %d not 20\n", b64buf_len);
+                            ir_ctx->sax_error++;
+                            return;  // TODO
                         }
-                        validation_data->rgbExternalData = b64buf;
-                        //memcpy(validation_data->rgbExternalData, buf, rc);
-                        memcpy(&validation_data->rgbData[28], b64buf, 20);
                     }
                 }
             }
@@ -2138,7 +2356,7 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                 if (validation_data->rgbData == NULL) {
                     // TODO 1.2 only
                     validation_data->ulDataLength = 52;
-                    validation_data->rgbData = malloc(52);
+                    validation_data->rgbData = xmalloc_assert(52);
                 }
 
                 // printf(", %s='", type);
@@ -2167,10 +2385,16 @@ void  irStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                             ir_ctx->sax_error++;
                             return;
                         }
-                        validation_data->ulExternalDataLength = b64buf_len;
-                        validation_data->rgbExternalData = b64buf;
-                        //memcpy(validation_data->rgbExternalData, b64buf, rc);
-                        memcpy(&validation_data->rgbData[6], b64buf, 20);
+                        if (b64buf_len == 20) {
+                            validation_data->ulExternalDataLength = b64buf_len;
+                            validation_data->rgbExternalData = b64buf;
+                            // memcpy(validation_data->rgbExternalData, b64buf, rc);
+                            memcpy(&validation_data->rgbData[6], b64buf, 20);
+                        } else {
+                            ERROR("Failed to decode base64 string, len = %d not 20\n", b64buf_len);
+                            ir_ctx->sax_error++;
+                            return;  // TODO
+                        }
                     }
                 }
             }
@@ -2221,9 +2445,8 @@ void irEndElement(void * ctx, const xmlChar * name) {
         ir_ctx->ew_last = ir_ctx->ew_new;
         /* malloc */
         ir_ctx->ew_new = (OPENPTS_PCR_EVENT_WRAPPER *)
-            malloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
+            xmalloc(sizeof(OPENPTS_PCR_EVENT_WRAPPER));
         if (ir_ctx->ew_new == NULL) {
-            ERROR("no memory\n");
             ir_ctx->sax_error++;
             return;
         }
@@ -2276,7 +2499,8 @@ void irEndElement(void * ctx, const xmlChar * name) {
         }
     } else if (!strcmp((char *)name, "pcrindex")) {
         ir_ctx->buf[ir_ctx->char_size] = 0;
-        ir_ctx->event->ulPcrIndex = atoi(ir_ctx->buf);
+        // ir_ctx->event->ulPcrIndex = atoi(ir_ctx->buf);
+        ir_ctx->event->ulPcrIndex = getPcrIndexFromIR(ir_ctx->buf);
     } else if (!strcmp((char *)name, "stuff:Hash")) {
         ir_ctx->buf[ir_ctx->char_size] = 0;
         /* base64 -> plain */
@@ -2287,9 +2511,10 @@ void irEndElement(void * ctx, const xmlChar * name) {
         if (ir_ctx->event->rgbPcrValue == NULL) {
             ERROR("decodeBase64 fail");
             ir_ctx->sax_error++;
-            return;
+            return;  // TODO
+        } else {
+            ir_ctx->event->ulPcrValueLength = b64buf_len;
         }
-        ir_ctx->event->ulPcrValueLength = b64buf_len;
     } else if (!strcmp((char *)name, "eventtype")) {
         ir_ctx->buf[ir_ctx->char_size] = 0;
         ir_ctx->event->eventType = atoi(ir_ctx->buf);
@@ -2303,9 +2528,10 @@ void irEndElement(void * ctx, const xmlChar * name) {
         if (ir_ctx->event->rgbEvent == NULL) {
             ERROR("decodeBase64 fail");
             ir_ctx->sax_error++;
-            return;
+            return;  // TODO
+        } else {
+            ir_ctx->event->ulEventLength = b64buf_len;
         }
-        ir_ctx->event->ulEventLength = b64buf_len;
     } else if (!strcmp((char *)name, "PcrHash")) {
         /* PCR value */
         ir_ctx->buf[ir_ctx->char_size] = 0;  // null terminate
@@ -2317,29 +2543,29 @@ void irEndElement(void * ctx, const xmlChar * name) {
         if (b64buf == NULL) {
             ERROR("decodeBase64 fail");
             ir_ctx->sax_error++;
-            return;
+            return;  // TODO
         }
         if (b64buf_len > MAX_DIGEST_SIZE) {
             ERROR("decodeBase64 out is too latge, %d > %d",
                 b64buf_len, MAX_DIGEST_SIZE);
             ir_ctx->sax_error++;
-            return;
+            return;  // TODO
+        } else {
+            memcpy(ir_ctx->pcr, b64buf, b64buf_len);
         }
-        memcpy(ir_ctx->pcr, b64buf, b64buf_len);
         free(b64buf);
-
         /* Check with PCR in TPM */
         rc = checkTpmPcr2(&pctx->tpm, ir_ctx->pcr_index, ir_ctx->pcr);
         if (rc != 0) {
             ERROR("ERROR PCR[%d] != IML\n", ir_ctx->pcr_index);
             ir_ctx->sax_error = 1;
             // verbose = DEBUG_FLAG | DEBUG_TPM_FLAG;  // switch DEBUG MODE
-            if (verbose & DEBUG_FLAG) {
+            if (isDebugFlagSet(DEBUG_FLAG)) {
                 BYTE pcr[20];
                 DEBUG("PCR[%d]\n", ir_ctx->pcr_index);
                 getTpmPcrValue(&pctx->tpm, ir_ctx->pcr_index, pcr);
-                printHex("", pcr, 20, " (emulated)\n");
-                printHex("", ir_ctx->pcr, 20, " (IR)\n");
+                debugHex("", pcr, 20, " (emulated)\n");
+                debugHex("", ir_ctx->pcr, 20, " (IR)\n");
             }
         } else {
             /* IML and PCR are consistent :-) */
@@ -2351,7 +2577,7 @@ void irEndElement(void * ctx, const xmlChar * name) {
                 if (pcrs == NULL) {
                     /* malloc OPENPTS_PCRS */
                     // ERROR("PCR is not intialized - No QuoteData element\n");
-                    pcrs = malloc(sizeof(OPENPTS_PCRS));
+                    pcrs = xmalloc(sizeof(OPENPTS_PCRS));
                     if (pcrs == NULL) {
                         ERROR("no memory\n");
                         return;
@@ -2424,9 +2650,19 @@ void irEndElement(void * ctx, const xmlChar * name) {
         {
             // tpm.quote.pcr.0=base64
             // note) Do not use PCR10(IMA) as policy
-            char buf2[20];
-            snprintf(buf2, sizeof(buf2), "tpm.quote.pcr.%d", ir_ctx->pcr_index);
-            addProperty(ctx, buf2, ir_ctx->buf);
+            char name[64];
+            snprintf(name, sizeof(name), "disable.quote.pcr.%d", ir_ctx->pcr_index);
+            if (NULL != getProperty(ctx, name)) {
+                DEBUG("Found disabled quote property '%s'\n", name);
+                snprintf(name, sizeof(name), "# tpm.quote.pcr.%d", ir_ctx->pcr_index);
+            } else {
+                snprintf(name, sizeof(name), "tpm.quote.pcr.%d", ir_ctx->pcr_index);
+            }
+            addProperty(ctx, name, ir_ctx->buf);
+
+            // char buf2[20];
+            // snprintf(buf2, sizeof(buf2), "tpm.quote.pcr.%d", ir_ctx->pcr_index);
+            // addProperty(ctx, buf2, ir_ctx->buf);
         }
     } else if (!strcmp((char *)name, "QuoteInfo2")) {
         /* pcr select => validation_data */
@@ -2446,7 +2682,7 @@ void irEndElement(void * ctx, const xmlChar * name) {
             ir_ctx->sax_error++;
         } else {
             if (validation_data->rgbValidationData != NULL) {
-                free(validation_data->rgbValidationData);
+                xfree(validation_data->rgbValidationData);
             }
             /* base64 -> plain */
             validation_data->rgbValidationData = decodeBase64(
@@ -2456,7 +2692,7 @@ void irEndElement(void * ctx, const xmlChar * name) {
             if (validation_data->rgbValidationData == NULL) {
                 ERROR("decodeBase64 fail");
                 ir_ctx->sax_error++;
-                return;
+                return;  // TODO
             }
             validation_data->ulValidationDataLength = b64buf_len;
         }
@@ -2480,25 +2716,28 @@ void irEndElement(void * ctx, const xmlChar * name) {
         /* check Nonce */
         /* Validate QuoteData */
 
-        rc = validateQuoteData(pcrs, validation_data);
-        // DEBUG("validateQuoteData = %d\n", rc);
-        if (rc != PTS_SUCCESS) {
-            ERROR("---------------------------------------------------------------------------\n");
-            ERROR("BAD QUOTE DATA!!!  BAD QUOTE DATA!!!  BAD QUOTE DATA!!!  BAD QUOTE DATA!!!\n");
-            ERROR("---------------------------------------------------------------------------\n");
-            addProperty(pctx, "tpm.quote.signature", "invalid");
-            // TODO set error
-            ir_ctx->bad_quote = 1;
+        if ( ir_ctx->sax_error > 0 ) {
+            ERROR("Unable to validate quote data due to %d SAX parse errors\n", ir_ctx->sax_error);
         } else {
+            rc = validateQuoteData(pcrs, validation_data);
+            // DEBUG("validateQuoteData = %d\n", rc);
+            if (rc != PTS_SUCCESS) {
+                ERROR("---------------------------------------------------------------------------\n");
+                ERROR("BAD QUOTE DATA!!!  BAD QUOTE DATA!!!  BAD QUOTE DATA!!!  BAD QUOTE DATA!!!\n");
+                ERROR("---------------------------------------------------------------------------\n");
+                addProperty(pctx, "tpm.quote.signature", "invalid");
+                // TODO set error
+                ir_ctx->bad_quote = 1;
+            } else {
 #if 0
-            TODO("---------------------------------------------------------------------------\n");
-            TODO("GOOD QUOTE DATA!!! GOOD QUOTE DATA!!! GOOD QUOTE DATA!!! GOOD QUOTE DATA!!!\n");
-            TODO("---------------------------------------------------------------------------\n");
+                TODO("---------------------------------------------------------------------------\n");
+                TODO("GOOD QUOTE DATA!!! GOOD QUOTE DATA!!! GOOD QUOTE DATA!!! GOOD QUOTE DATA!!!\n");
+                TODO("---------------------------------------------------------------------------\n");
 #endif
-            addProperty(pctx, "tpm.quote.signature", "valid");
+                addProperty(pctx, "tpm.quote.signature", "valid");
+            }
         }
 
-
         pctx->conf->ir_without_quote = 0;
     } else {
         /* Else? */
@@ -2518,8 +2757,9 @@ void irCharacters(void* ctx, const xmlChar * ch, int len) {
     OPENPTS_CONTEXT * pctx = (OPENPTS_CONTEXT *)ctx;
     OPENPTS_IR_CONTEXT * ir_ctx = pctx->ir_ctx;
 
-    /* copy to buf at ir_ctx */
-    if (ir_ctx->char_size + len > EVENTDATA_BUF_SIZE) {
+    /* copy to buf at ir_ctx, but check length first, ensuring additional space
+       for NULL terminator */
+    if ((ir_ctx->char_size + len + 1) > EVENTDATA_BUF_SIZE) {
         ERROR("Buffer for EVENTDATA is too small, %d + %d > %d\n", ir_ctx->char_size, len, EVENTDATA_BUF_SIZE);
         return;
     }
@@ -2557,9 +2797,10 @@ void irCharacters(void* ctx, const xmlChar * ch, int len) {
  *    valgrind --leak-check=full --show-reachable=yes -v tests/check_fsm
  *
  */
-int validateIr(OPENPTS_CONTEXT *ctx, const char *filename) {
+// int validateIr(OPENPTS_CONTEXT *ctx, const char *filenameNG) {
+int validateIr(OPENPTS_CONTEXT *ctx) {
     xmlSAXHandler  sax_handler;
-    int rc = PTS_SUCCESS;
+    int rc = PTS_VERIFY_FAILED;  // guilty until proven innocent
     OPENPTS_CONFIG *conf;
     OPENPTS_PCRS *pcrs;
 
@@ -2567,22 +2808,17 @@ int validateIr(OPENPTS_CONTEXT *ctx, const char *filename) {
     DEBUG("validateIr - start\n");
 
     /* check */
-    if (ctx == NULL) {
-        ERROR("ctx == NULL\n");
-        return PTS_FATAL;
-    }
-    if (ctx->target_conf == NULL) {
-        ERROR("ctx->target_conf == NULL\n");
-        return PTS_FATAL;
-    }
+    ASSERT(NULL != ctx, "ctx == NULL\n");
+    ASSERT(NULL != ctx->target_conf, "ctx->target_conf == NULL\n");
+    ASSERT(NULL != ctx->ir_filename, "ctx->ir_filename == NULL\n");
+
     conf = ctx->target_conf;
 
     /* new */
     if (ctx->pcrs == NULL) {
         /* malloc OPENPTS_PCRS */
-        ctx->pcrs = malloc(sizeof(OPENPTS_PCRS));
+        ctx->pcrs = xmalloc(sizeof(OPENPTS_PCRS));
         if (ctx->pcrs == NULL) {
-            ERROR("no memory\n");
             rc = PTS_FATAL;
             goto free;
         }
@@ -2596,7 +2832,6 @@ int validateIr(OPENPTS_CONTEXT *ctx, const char *filename) {
     if (ctx->ir_ctx == NULL) {
         ctx->ir_ctx = newIrContext();
         if (ctx->ir_ctx == NULL) {
-            ERROR("no memory\n");
             rc = PTS_FATAL;
             goto free;
         }
@@ -2651,10 +2886,10 @@ int validateIr(OPENPTS_CONTEXT *ctx, const char *filename) {
 
     /* read IR, IR -> IML SAX */
 
-    DEBUG("validateIr - Validate IR     : %s\n", filename);
+    DEBUG("validateIr - Validate IR     : %s\n", ctx->ir_filename);
 
     // http://xmlsoft.org/html/libxml-parser.html#xmlSAXUserParseFile
-    if ((rc = xmlSAXUserParseFile(&sax_handler, (void *)ctx, filename)) != 0) {
+    if ((rc = xmlSAXUserParseFile(&sax_handler, (void *)ctx, ctx->ir_filename)) != 0) {
         // SAX parse error
         DEBUG("validateIr() - SAX parse error rc=%d\n", rc);
         rc = PTS_INTERNAL_ERROR;
@@ -2693,13 +2928,14 @@ int validateIr(OPENPTS_CONTEXT *ctx, const char *filename) {
             if (rc == PTS_SUCCESS) {
                 addProperty(ctx, "tpm.quote.pcrs", "valid");
             } else if (rc == PTS_VERIFY_FAILED) {
-                // ptscd - if FSM config in ptscd.conf is wrong this happen
-                addReason(ctx,
-                    "[QUOTE] verification of PCR Composite was failed, (tscd - bad FSM configuration in ptscd.conf)");
+                // ptsc - if FSM config in ptsc.conf is wrong this happen
+                addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_IR_PCR_COMPOSITE_VERIFY_FAILED,
+                    "[QUOTE] verification of PCR Composite has failed, "
+                    "(tscd - bad FSM configuration in /etc/ptsc.conf)"));
                 addProperty(ctx, "tpm.quote.pcrs", "invalid");
             } else {
-                addReason(ctx,
-                    "[QUOTE] verification of PCR Composite was failed");
+                addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_IR_PCR_COMPOSITE_VERIFY_FAILED,
+                               "[QUOTE] verification of PCR Composite has failed"));
                 addProperty(ctx, "tpm.quote.pcrs", "invalid");
             }
         } else {
@@ -2734,15 +2970,16 @@ int validateIr(OPENPTS_CONTEXT *ctx, const char *filename) {
     if (ctx->ima_unknown > 0) {
         if (conf->ima_validation_unknown == 1) {
             DEBUG("ctx->ima_unknown = %d, result is INVALID\n", ctx->ima_unknown);
-            addReason(ctx,
-                "[LINUX-IMA] There are several unknown IMA measurments. check and update your AIDE ignore list");
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_IR_SEVERAL_UNKNOWN_IMA,
+                "[LINUX-IMA] There are several unknown IMA measurements. "
+                "Please check and update your AIDE ignore list."));
             rc = OPENPTS_RESULT_UNKNOWN;
         }
     }
 
     if (ctx->ir_ctx->bad_quote == 1) {
-        addReason(ctx,
-            "[QUOTE] verification of quote signature was failed");
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_IR_QUOTE_VERIFY_FAILED,
+            "[QUOTE] verification of quote signature has failed."));
         rc = OPENPTS_RESULT_INVALID;
     }
 
@@ -2757,14 +2994,16 @@ int validateIr(OPENPTS_CONTEXT *ctx, const char *filename) {
 #endif
     // TODO Keep PCRs?
     if (ctx->pcrs != NULL) {
-        free(ctx->pcrs);
+        xfree(ctx->pcrs);
         ctx->pcrs = NULL;
     }
 
 
     if (ctx->ir_ctx != NULL) {
-        if (ctx->ir_ctx->buf != NULL) free(ctx->ir_ctx->buf);
-        free(ctx->ir_ctx);
+        if (ctx->ir_ctx->buf != NULL) {
+            xfree(ctx->ir_ctx->buf);
+        }
+        xfree(ctx->ir_ctx);
         ctx->ir_ctx = NULL;
     }
 
@@ -2780,7 +3019,7 @@ int validateIr(OPENPTS_CONTEXT *ctx, const char *filename) {
  * @retval PTS_SUCCESS
  * @retval PTS_INTERNAL_ERROR
  */
-int genIrFromSecurityfs(OPENPTS_CONTEXT *ctx) {
+int genIrFromSecurityfs(OPENPTS_CONTEXT *ctx, int *savedFd) {
     int rc;
     /* get IML via securityfs */
 
@@ -2830,8 +3069,14 @@ int genIrFromSecurityfs(OPENPTS_CONTEXT *ctx) {
         // return -1;
     }
 
+    // do not use tempnum,
+    // if (ctx->conf->ir_filename != NULL) {
+    //    ERROR("Redefining the IR file location %s", ctx->conf->ir_filename);
+    // }
+    // ctx->conf->ir_filename = tempnam(NULL, "ir_");
+
     /* save IR */
-    rc = writeIr(ctx, ctx->conf->ir_filename);
+    rc = writeIr(ctx, ctx->conf->ir_filename, savedFd);
     if (rc != 0) {
         ERROR("fail to write IR, rc = %d\n", rc);
         return PTS_INTERNAL_ERROR;
@@ -2847,7 +3092,7 @@ int genIrFromSecurityfs(OPENPTS_CONTEXT *ctx) {
  * @retval PTS_SUCCESS
  * @retval PTS_INTERNAL_ERROR 
  */
-int genIrFromTss(OPENPTS_CONTEXT *ctx) {
+int genIrFromTss(OPENPTS_CONTEXT *ctx, int *savedFd) {
     int rc;
     UINT32 ps_type = TSS_PS_TYPE_SYSTEM;  // TODO move to context?
 
@@ -2861,7 +3106,7 @@ int genIrFromTss(OPENPTS_CONTEXT *ctx) {
 
     /* reset OPENPTS_PCRS */
     if (ctx->pcrs == NULL) {
-        ctx->pcrs = malloc(sizeof(OPENPTS_PCRS));  // TODO NULL check, or gen at newCtx
+        ctx->pcrs = xmalloc_assert(sizeof(OPENPTS_PCRS));  // TODO NULL check, or gen at newCtx
         // TODO check
     }
     memset(ctx->pcrs, 0, sizeof(OPENPTS_PCRS));
@@ -2876,13 +3121,23 @@ int genIrFromTss(OPENPTS_CONTEXT *ctx) {
 
     /* TSS_VALIDATION */
     if (ctx->validation_data == NULL) {
-        ctx->validation_data = malloc(sizeof(TSS_VALIDATION));
+        ctx->validation_data = xmalloc_assert(sizeof(TSS_VALIDATION));
     }
 
     /* Nonce */
     if (ctx->nonce->nonce_length > 0) {
         ctx->validation_data->ulExternalDataLength = ctx->nonce->nonce_length;
-        ctx->validation_data->rgbExternalData= ctx->nonce->nonce;
+        // NG ctx->validation_data->rgbExternalData= ctx->nonce->nonce;
+        /* copy */
+        ctx->validation_data->rgbExternalData = malloc(ctx->nonce->nonce_length);
+        if (ctx->validation_data->rgbExternalData == NULL) {
+            ERROR("no memory");
+            return PTS_FATAL;
+        }
+        memcpy(
+            ctx->validation_data->rgbExternalData,
+            ctx->nonce->nonce,
+            ctx->nonce->nonce_length);
     } else {
         ERROR("genIrFromTss - nonce is missing, DH-nonce? \n");
         ctx->validation_data->ulExternalDataLength = 0;
@@ -2937,8 +3192,14 @@ int genIrFromTss(OPENPTS_CONTEXT *ctx) {
         return PTS_INTERNAL_ERROR;
     }
 
+    if (ctx->conf->ir_filename != NULL) {
+        ERROR("Redefining the IR file location %s", ctx->conf->ir_filename);
+    }
+    //ctx->conf->ir_filename = tempnam(NULL, "ir_");
+    //DEBUG("ctx->conf->ir_filename : %s\n", ctx->conf->ir_filename);
+
     /* save IR */
-    rc = writeIr(ctx, ctx->conf->ir_filename);  // ir.c
+    rc = writeIr(ctx, ctx->conf->ir_filename, savedFd);  // ir.c
     if (rc != 0) {
         ERROR("fail to write IR, rc = %d\n", rc);
         return PTS_INTERNAL_ERROR;
@@ -2954,10 +3215,10 @@ int genIrFromTss(OPENPTS_CONTEXT *ctx) {
  * @retval PTS_SUCCESS
  * @retval PTS_INTERNAL_ERROR
  */
-int genIr(OPENPTS_CONTEXT *ctx) {
+int genIr(OPENPTS_CONTEXT *ctx, int *savedFd) {
     int rc = PTS_INTERNAL_ERROR;
     if (ctx->conf->iml_mode == 1) {
-        rc = genIrFromSecurityfs(ctx);
+        rc = genIrFromSecurityfs(ctx, savedFd);
         if (rc != PTS_SUCCESS) {
             ERROR("writePtsTlvToSock - gen IR failed\n");
             return rc;
@@ -2967,7 +3228,7 @@ int genIr(OPENPTS_CONTEXT *ctx) {
         TODO("OpenPTS was build with --without-tss and config option iml.mode=tssand, skip IR gen.\n");
 #else
         // DEBUG("get IML/PCR via TSS is not ready\n");
-        rc = genIrFromTss(ctx);
+        rc = genIrFromTss(ctx, savedFd);
         if (rc != PTS_SUCCESS) {
             ERROR("gen IR failed\n");
             return rc;
index f832220..a354f3e 100644 (file)
@@ -45,6 +45,8 @@
 
 #include <tss/tss_structs.h>
 
+#include <openpts.h>
+
 /* Convert endian - 32bit */
 #define econv(x) ((UINT32)( \
     (((UINT32)(x) & (UINT32)0x000000ffUL) << 24) | \
     (((UINT32)(x) & (UINT32)0x00ff0000UL) >>  8) | \
     (((UINT32)(x) & (UINT32)0xff000000UL) >> 24)))
 
-
-
-// #include <openpts.h>
-
-/* base64.c */
-int base64size(int len);
-int encodeBase64(unsigned char *out, unsigned char * in, int len);
-int decodeBase64(unsigned char *out, unsigned char * in, int len);
-int decodeBase64core(unsigned char *out, unsigned char * in, int len);
-
-
-/* debug */
-int verbose = 0;
-
-#define DEBUG_FLAG     0x01
-#define DEBUG_FSM_FLAG 0x02
-#define DEBUG_XML_FLAG 0x04
-#define DEBUG_IFM_FLAG 0x08
-#define DEBUG_SAX_FLAG 0x10
-#define DEBUG_TPM_FLAG 0x20
-#define DEBUG_CAL_FLAG 0x40
-
-#define ERROR(fmt, ...) \
-fprintf(stderr, "ERROR     %s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define TODO(fmt, ...) \
-fprintf(stderr, "TODO      %s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define INFO(fmt, ...) \
-fprintf(stderr, "INFO      %s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
-#define DEBUG(fmt, ...) if (verbose & DEBUG_FLAG) \
-fprintf(stdout, "DEBUG     %s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
-
 #define MAX_DIGEST_SIZE 64
 #define EVENTDATA_BUF_SIZE 100000
 
@@ -268,16 +236,6 @@ void fprintEventData(FILE *fp, UINT32 type, UINT32 len, BYTE *eventdata) {
 }
 
 
-/**
- * print Hex string
- */
-void fprintHex(FILE *fp, BYTE *data, int num) {
-    int i;
-    for (i = 0; i < num; i++) {
-        fprintf(fp, "%02X", data[i]);
-    }
-}
-
 /*
 <Report xmlns:core="http://www.trustedcomputinggroup.org/XML/SCHEMA/1_0_1/core_integrity#" xmlns:stuff="http://www.trustedcomputinggroup.org/XML/SCHEMA/1_0/simple_object#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.trustedcomputinggroup.org/XML/SCHEMA/1_0/integrity_report#" ID="IR_24868831-1b3c-4eb5-8e15-83b74f54d033" UUID="24868831-1b3c-4eb5-8e15-83b74f54d033">
   <SnapshotCollection Id="IR_1bd0ac8f-d091-4a14-af05-651386f312a1" UUID="1bd0ac8f-d091-4a14-af05-651386f312a1" RevLevel="0">
@@ -387,9 +345,8 @@ void  irStartElement(void* context, const xmlChar* name, const xmlChar** atts) {
     } else if (!strcmp((char *)name, "stuff:Objects")) {
         /* New event */
         /* malloc */
-        ctx->event = (TSS_PCR_EVENT *) malloc(sizeof(TSS_PCR_EVENT));
+        ctx->event = (TSS_PCR_EVENT *) xmalloc(sizeof(TSS_PCR_EVENT));
         if (ctx->event == NULL) {
-            ERROR("no memory\n");
             return;
         }
         memset(ctx->event, 0, sizeof(TSS_PCR_EVENT));
@@ -496,24 +453,27 @@ void irEndElement(void * context, const xmlChar * name) {
         ctx->event->ulPcrIndex = atoi(ctx->buf);
     } else if (!strcmp((char *)name, "stuff:Hash")) {
         ctx->buf[ctx->char_size] = 0;
-        ctx->event->rgbPcrValue = malloc(MAX_DIGEST_SIZE);  // TODO(munetoh) alg -> size
-        rc = decodeBase64(ctx->event->rgbPcrValue, (unsigned char *)ctx->buf, ctx->char_size);
-        ctx->event->ulPcrValueLength = rc;
+        ctx->event->rgbPcrValue = decodeBase64(
+            (char *)ctx->buf,
+            ctx->char_size,
+            (int *)&ctx->event->ulPcrValueLength);
+        if (ctx->event->rgbEvent == NULL) {
+            // ERROR()
+            ctx->event->ulPcrValueLength = 0;
+        }
     } else if (!strcmp((char *)name, "eventtype")) {
         ctx->buf[ctx->char_size] = 0;
         ctx->event->eventType = atoi(ctx->buf);
     } else if (!strcmp((char *)name, "eventdata")) {
         ctx->buf[ctx->char_size] = 0;  // null terminate
-        /* malloc */
-        ctx->event->rgbEvent = malloc(ctx->char_size + 1);
+        ctx->event->rgbEvent = decodeBase64(
+            (char *)ctx->buf,
+            ctx->char_size,
+            (int *)&ctx->event->ulEventLength);
         if (ctx->event->rgbEvent == NULL) {
-            ERROR("no memory\n");
-            ctx->sax_error++;
-            return;
+            // ERROR()
+            ctx->event->ulEventLength = 0;
         }
-        /* base64 -> plain */
-        rc = decodeBase64(ctx->event->rgbEvent, (unsigned char *)ctx->buf, ctx->char_size);
-        ctx->event->ulEventLength = rc;
     } else if (!strcmp((char *)name, "PcrHash")) {
         /* PCR value */
         ctx->buf[ctx->char_size] = 0;  // null terminate
@@ -536,9 +496,8 @@ void irEndElement(void * context, const xmlChar * name) {
                 if (pcrs == NULL) {
                     /* malloc OPENPTS_PCRS */
                     // ERROR("PCR is not intialized - No QuoteData element\n");
-                    pcrs = malloc(sizeof(OPENPTS_PCRS));
+                    pcrs = xmalloc(sizeof(OPENPTS_PCRS));
                     if (pcrs == NULL) {
-                        ERROR("no memory\n");
                         return;
                     }
                     memset(pcrs, 0, sizeof(OPENPTS_PCRS));
@@ -621,16 +580,16 @@ int readIr(IR_CONTEXT *context, const char *filename) {
  * Usage
  */
 void usage(void) {
-    fprintf(stderr, "OpenPTS command\n\n");
-    fprintf(stderr, "Usage: ir2text [options]\n\n");
-    fprintf(stderr, "Options:\n");
-    fprintf(stderr, "  -i filename           Set IR file\n");
-    fprintf(stderr, "  -o filename           Set output file, else stdout\n");
-    fprintf(stderr, "  -P filename           Set PCR output file (option)\n");
-    fprintf(stderr, "  -b                    Binary, (Convert IR to IML)\n");
-    fprintf(stderr, "  -E                    Enable endian conversion (BE->LE or LE->BE)\n");
-    fprintf(stderr, "  -h                    Show this help message\n");
-    fprintf(stderr, "\n");
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_IR2TEXT_USAGE, "OpenPTS command\n\n"
+                    "Usage: ir2text [options]\n\n"
+                    "Options:\n"
+                    "  -i filename           Set IR file\n"
+                    "  -o filename           Set output file, else stdout\n"
+                    "  -P filename           Set PCR output file (option)\n"
+                    "  -b                    Binary, (Convert IR to IML)\n"
+                    "  -E                    Enable endian conversion (BE->LE or LE->BE)\n"
+                    "  -h                    Show this help message\n"
+                    "\n"));
 }
 
 int main(int argc, char *argv[]) {
@@ -641,20 +600,20 @@ int main(int argc, char *argv[]) {
     int c;
     IR_CONTEXT *ctx;
 
+    initCatalog();
+
     resetPcr();
 
-    // ctx = malloc(sizeof(IR_CONTEXT));
-    ctx = (IR_CONTEXT *) malloc(sizeof(IR_CONTEXT));
+    ctx = xmalloc(sizeof(IR_CONTEXT));
+    ctx = (IR_CONTEXT *) xmalloc(sizeof(IR_CONTEXT));
     if (ctx == NULL) {
-        ERROR("no memory\n");
         return -1;
     }
     memset(ctx, 0, sizeof(IR_CONTEXT));
 
-    ctx->buf = malloc(EVENTDATA_BUF_SIZE);
+    ctx->buf = xmalloc(EVENTDATA_BUF_SIZE);
     if (ctx->buf == NULL) {
-        ERROR("no memory\n");
-        free(ctx);
+        xfree(ctx);
         return -1;
     }
 
@@ -684,13 +643,13 @@ int main(int argc, char *argv[]) {
             ctx->aligned = 4;
             break;
         case 'd':  /* DEBUG */
-            verbose = DEBUG_FLAG;
+            setDebugFlags(DEBUG_FLAG);
             break;
         case 'h':
             usage();
             return 0;
         default:
-            fprintf(stderr, "bad option %c\n", c);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_IR2TEXT_BAD_OPTION_C, "bad option %c\n"), c);
             usage();
             return -1;
         }
@@ -714,7 +673,8 @@ int main(int argc, char *argv[]) {
     } else {
         /* print IR in binary text, with -o option */
         if (out_filename == NULL) {
-            fprintf(stderr, "set the output file for the binary mode\n");
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_IR2TEXT_OUTPUT_BINARY_MODE,
+                "set the output file for the binary mode\n"));
             usage();
             return -1;
         }
index ec229b4..887cbce 100644 (file)
--- a/src/log.c
+++ b/src/log.c
  *
  *
  *  LOG("msg",format)
+ *
+ *  OUTPUT   console/stderr
+ *  VERBOSE  console/stderr
+ *  ASSERT   console/stderr
+ *
+ *  ERROR    console|file|syslog
+ *  INFO     console|file|syslog
+ *  TODO     console|file|syslog
+ *  DEBUG    console|file|syslog
+ *
  */
 
 #include <stdio.h>
 #include <stdarg.h> /* va_ */
 #include <syslog.h>
 
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/shm.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <openpts_log.h>
+
+
 #define SYSLOG_BUF_SIZE 1024
 
+
+
+#ifdef AIX
+
+#ifndef DEFAULT_LOG_LOCATION
+#define DEFAULT_LOG_LOCATION   OPENPTS_LOG_FILE
+#endif
+
+#ifndef DEFAULT_LOG_FILE
+#define DEFAULT_LOG_FILE       "/var/adm/ras/openpts/log"
+#endif
+
+#define DEFAULT_LOG_FILE_PERM  (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH)
+#define DEFAULT_LOG_FILE_SIZE  0x100000
+#else  // AIX
+#define DEFAULT_LOG_LOCATION   OPENPTS_LOG_FILE
+#define DEFAULT_LOG_FILE       "~/.openpts/log"
+#define DEFAULT_LOG_FILE_PERM  (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH)
+#define DEFAULT_LOG_FILE_SIZE  0x100000
+#endif
+
+#ifdef ENABLE_NLS
+#ifdef HAVE_CATGETS
+#include <nl_types.h>
+nl_catd catd;
+#endif
+#endif
+
+/* external variables for logging macros */
+int debugBits = 0;
+int verbosity = 0;
+
+/* global variables for this file */
+static int logLocation = OPENPTS_LOG_UNDEFINED;
+static char logFileName[256];
+static FILE *logFile = NULL;
+static int logFileFd = -1;
+static int alreadyWarnedAboutLogFile = 0;
+
+static int openLogFile(void);
+static void addToLog(char* log_entry);
+
+/**
+ *
+ */
+void initCatalog(void) {
+#ifdef ENABLE_NLS
+    (void) setlocale(LC_ALL, "");
+#ifdef HAVE_CATGETS
+    catd = catopen(MF_OPENPTS, NL_CAT_LOCALE);
+#else
+    bindtextdomain(PACKAGE, LOCALEDIR);
+    textdomain(PACKAGE);
+#endif
+#endif
+}
+
+/**
+ *
+ */
+static void expandLogFilePath(char *unexpandedPath) {
+    char *srcPtr = unexpandedPath;
+    char *destPtr = logFileName;
+    char *destEnd = destPtr + 255; /* leave space for '\0' */
+    char *homeDir = NULL;
+    int homeDirLen = 0;
+
+    while ((destPtr < destEnd) && ('\0' != srcPtr[0])) {
+        int destCharsWritten;
+        if ('~' == srcPtr[0]) {
+            int destSpaceLeft = destEnd - destPtr;
+            if (NULL == homeDir) {
+                homeDir = getenv("HOME");
+                homeDirLen = strlen(homeDir);
+            }
+            destCharsWritten = MIN(destSpaceLeft, homeDirLen);
+            memcpy(destPtr, homeDir, destCharsWritten);
+        } else {
+            destPtr[0] = srcPtr[0];
+            destCharsWritten = 1;
+        }
+        srcPtr++;
+        destPtr += destCharsWritten;
+    }
+
+    destPtr[0] = '\0';
+}
+
+/**
+ *
+ */
+static void determineLogLocation(void) {
+    char *tempLogFileName = NULL;
+
+    if (getenv("OPENPTS_LOG_SYSLOG") != NULL) {
+        logLocation = OPENPTS_LOG_SYSLOG;
+    } else if (getenv("OPENPTS_LOG_CONSOLE") != NULL) {
+        logLocation = OPENPTS_LOG_CONSOLE;
+        logFile = stderr;
+    } else if ((tempLogFileName = getenv("OPENPTS_LOG_FILE")) != NULL) {
+        logLocation = OPENPTS_LOG_FILE;
+    } else if (getenv("OPENPTS_LOG_NULL") != NULL) {
+        logLocation = OPENPTS_LOG_NULL;
+    } else {
+        logLocation = DEFAULT_LOG_LOCATION;
+        tempLogFileName = DEFAULT_LOG_FILE;
+    }
+
+    if (logLocation == OPENPTS_LOG_FILE) {
+        expandLogFilePath(tempLogFileName);
+    }
+}
+
+/**
+ * Force custom log location by app itself
+ */
+void setLogLocation(int ll, char *filename) {
+    logLocation = ll;
+
+    if (ll == OPENPTS_LOG_FILE) {
+        expandLogFilePath(filename);
+    }
+}
+
+/**
+ *
+ */
+static void createLogEntry(
+    int priority,
+    char *buf,
+    int bufLen,
+    const char *format,
+    va_list list) {
+
+    const char *priorities[1 + LOG_DEBUG] = {
+        "[EMERGENCY] ",
+        "[ALERT] ",
+        "[CRITICAL] ",
+        "[ERROR] ",
+        "[WARNING] ",
+        "[NOTICE] ",
+        "[INFO] ",
+        "[DEBUG] "
+    };
+    /* number of chars written (not including '\0') */
+    int charsWritten = 0;
+
+    if (priority > LOG_DEBUG) {
+        charsWritten = snprintf(buf, bufLen, "[UNKNOWN (%d)] ", priority);
+    } else {
+        charsWritten = snprintf(buf, bufLen, "%s", priorities[priority]);
+    }
+
+    if ( charsWritten >= bufLen ) {
+        /* string was truncated */
+        return;
+    }
+
+    charsWritten += vsnprintf(&buf[charsWritten], bufLen - charsWritten, format, list);
+
+    if ( charsWritten >= bufLen ) {
+        /* string was truncated */
+        return;
+    }
+
+    if ( (charsWritten + 1) < bufLen ) {
+        buf[charsWritten] = '\n';
+        buf[++charsWritten] = '\0';
+    }
+}
+
+/**
+ *
+ */
 void writeLog(int priority, const char *format, ...) {
     int len;
     char *format2 = NULL;
     va_list list;
-    char buf[SYSLOG_BUF_SIZE];
+    // char buf[SYSLOG_BUF_SIZE];
+    va_start(list, format);
+
+
+    if (logLocation == OPENPTS_LOG_UNDEFINED) {
+        determineLogLocation();
+    }
+
+    if (logLocation == OPENPTS_LOG_NULL) {
+        return;
+    }
 
     // TODO \n
     /* remove \n */
@@ -54,11 +258,57 @@ void writeLog(int priority, const char *format, ...) {
     if (format[len - 1] == '\n') {
         // format2 = malloc(len + 1);  // +1 space
         format2 = (char *) malloc(len);
-        memcpy(format2, format, len - 1);
-        format2[len - 1] = 0;
-        format = format2;
+        if (format2 != NULL) {
+            memcpy(format2, format, len - 1);
+            format2[len - 1] = 0;
+            format = format2;
+        }
+    }
+
+    switch (logLocation) {
+    case OPENPTS_LOG_SYSLOG:
+        {
+            char buf[SYSLOG_BUF_SIZE];
+
+            /* daemon -> syslog */
+            openlog("ptsc", LOG_NDELAY|LOG_PID, LOG_LOCAL5);
+
+            /* vsyslog is not supported by some unix */
+            vsnprintf(buf, SYSLOG_BUF_SIZE, format, list);
+            if (priority >= LOG_DEBUG) priority = LOG_INFO;
+            syslog(priority, "%s", buf);
+
+            closelog();
+            break;
+        }
+    case OPENPTS_LOG_FILE:
+        {
+            if ( -1 == openLogFile() ) {
+                if ( !alreadyWarnedAboutLogFile ) {
+                    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_CANNOT_OPEN_LOGFILE,
+                        "Unable to open logfile '%s'\n"), logFileName);
+                    alreadyWarnedAboutLogFile = 1;
+                }
+                /* fall through to next case */
+            } else {
+                char logEntry[1024];
+                createLogEntry(priority, logEntry, 1024, format, list);
+                addToLog(logEntry);
+                break;
+            }
+        }
+    case OPENPTS_LOG_CONSOLE:
+        {
+            char logEntry[1024];
+            createLogEntry(priority, logEntry, 1024, format, list);
+            fprintf(stderr, "%s", logEntry);
+            break;
+        }
+    // TODO default?
     }
 
+
+#if 0
     va_start(list, format);
 
     // if (getenv("PTSCD_DAEMON") != NULL) {
@@ -86,8 +336,28 @@ void writeLog(int priority, const char *format, ...) {
         vfprintf(stdout, format, list);
         fprintf(stdout, "\n");
     }
-
     va_end(list);
+#endif
+
+
     if (format2 != NULL) free(format2);
 }
 
+
+
+static int openLogFile(void) {
+    if (logFileFd != -1) {
+        return logFileFd;
+    }
+
+    logFileFd = open(logFileName, O_RDWR|O_CREAT|O_TRUNC, DEFAULT_LOG_FILE_PERM);
+    return logFileFd;
+}
+
+static void addToLog(char* log_entry) {
+    /* Warnings are treated as errors so need this ugly code to build */
+    ssize_t n = write(logFileFd, log_entry, strlen(log_entry));
+    (void)n;
+}
+
+
index 16f4986..c0d86a5 100644 (file)
@@ -33,6 +33,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <dirent.h>
 
 #include <netdb.h>
 #include <errno.h>
 #include <fcntl.h>
 
 #include <openpts.h>
+// #include <log.h>
 
+/**
+   Due to the frequent use of malloc/free in the code base (as opposed to
+   stack based allocation) these wrapper routines were added for easier debugging
+   - after their introduction several asserts fired that found genuine bugs. In
+   theory, for most programs that are not daemons we never really need to free memory
+   since it gets freed on program exit anyway. In addition, malloc should never
+   really fail - if so it usually indicates a programming error.
+   NOTE: On AIX the address 0x00000000 is a valid address, corresponding to a 
+   read-only map present in the address space of all running programs.
+**/
+
+#ifndef ALWAYS_ASSERT_ON_BAD_ALLOC
+void *xmalloc(size_t size) {
+    char *result = malloc(size);
+    if (NULL == result) {
+        ERROR("Failed to allocate %d bytes of memory\n", size);
+        // if ( size > 0 ) {
+        //     ERROR("malloc");
+        // }
+    }
+    return result;
+}
+#endif
+
+void *xmalloc_assert(size_t size) {
+    char *result = malloc(size);
+    if (NULL == result) {
+        ERROR("Failed to allocate %d bytes of memory\n", size);
+        ASSERT(0, "About to return NULL pointer - cannot continue\n");
+    }
+    return result;
+}
+
+void xfree(void *buf) {
+    ASSERT(NULL != buf, "Freeing a NULL pointer is bad\n");
+#ifndef NEVER_FREE_MEMORY
+    free(buf);
+#endif
+}
 
+
+#ifndef ALWAYS_ASSERT_ON_BAD_ALLOC
 /**
  * malloc and copy string
  */
-char * smalloc(char *str) {
+char *smalloc(char *str) {
     char *out;
-    int len;
-    int i;
 
     if (str == NULL) {
         DEBUG("smalloc - string is NULL\n");
@@ -64,6 +105,12 @@ char * smalloc(char *str) {
     }
 
     /* check string length */
+    out = strdup(str);
+    if (out == NULL) {
+        ERROR("Failed to duplicate string '%s'\n", str);
+    }
+
+#if 0
     len = (int)strlen(str);
 
     /* malloc */
@@ -84,6 +131,30 @@ char * smalloc(char *str) {
             out[i] = '_';
         }
     }
+#endif
+
+    return out;
+}
+#endif
+
+
+/**
+ * malloc and copy string
+ */
+char *smalloc_assert(char *str) {
+    char *out;
+
+    if (str == NULL) {
+        DEBUG("smalloc - string is NULL\n");
+        return NULL;
+    }
+
+    /* check string length */
+    out = strdup(str);
+    if (NULL == out) {
+        ERROR("Failed to duplicate string '%s'\n", str);
+        ASSERT(0, "About to return NULL pointer - cannot continue\n");
+    }
 
     return out;
 }
@@ -97,7 +168,7 @@ char * smalloc(char *str) {
  *  AAAAA  5     AAAA\n
  *  AAAAA  4     AAA\n
  */
-char * snmalloc(char *str, int len) {
+char *snmalloc(char *str, int len) {
     char *out;
 
     /* check */
@@ -107,21 +178,17 @@ char * snmalloc(char *str, int len) {
     }
 
     if (len == 0) {
-        TODO("snmalloc called but len=0\n");
         return NULL;
     }
 
-    /* malloc len + 1 (\n) */
-    out = malloc(len + 1);
-    if (out == NULL) {
-        ERROR("snmalloc() - no memory\n");
-        return NULL;
-    }
-
-    /* copy */
-    memcpy(out, str, len);
-    out[len] = 0;
-
+#ifdef MACOS
+    out = xmalloc_assert(len);
+    strncpy(out, str, len);
+    /* ensure always NULL-terminated */
+    out[len - 1] = '\0';
+#else
+    out = strndup(str, len);
+#endif
     return out;
 }
 
@@ -135,17 +202,12 @@ char * snmalloc(char *str, int len) {
  * @param offset
  * @param len
  */
-BYTE *snmalloc2(BYTE * buf, int offset, int len) {
-    BYTE *output;
-
-    output = (BYTE *) malloc(len + 1);
-
+BYTE *snmalloc2(BYTE *buf, int offset, int len) {
+    BYTE *output = (BYTE *) xmalloc(len + 1);
     if (output == NULL) {
-        ERROR("snmalloc2 - no memory\n");
         return NULL;
     }
 
-
     memcpy((void *) output, (void *) &buf[offset], len);
     output[len] = 0;
 
@@ -157,11 +219,7 @@ BYTE *snmalloc2(BYTE * buf, int offset, int len) {
  * free string buffer
  */
 void sfree(char *str) {
-    if (str == NULL) {
-        DEBUG("smalloc - string is NULL\n");
-        return;
-    }
-    free(str);
+    xfree(str);
 }
 
 
@@ -183,28 +241,19 @@ char *getFullpathName(char *basepath, char *filename) {
     int slash = 0;
 
     /* check */
-    if (filename == NULL) {
-        ERROR("getFullpathName - filename is NULL\n");
-        return NULL;
-    }
+    ASSERT(filename != NULL, "getFullpathName - filename is NULL\n");
+    ASSERT(basepath != NULL, "getFullpathName - basepath is NULL\n");
 
     /* start from root */
     if (filename[0] == '/') {
         /* seems fullpath, copy the filename to new buf */
-        fullpath = smalloc(filename);
-        return fullpath;
+        return smalloc(filename);
     }
 
     /* basepath + filename */
-    if (basepath == NULL) {
-        ERROR("getFullpathName - basepath is NULL, filename is %s\n", filename);
-        return NULL;
-    }
-
-
     if (basepath[0] != '/') {
         /* relative path -> error when it run as daemon */
-        DEBUG("getFullpathName() - basepath, '%s' is not started from root\n", basepath);
+        TODO("getFullpathName() - basepath, '%s' is not started from root\n", basepath);
     }
 
 
@@ -237,21 +286,21 @@ char *getFullpathName(char *basepath, char *filename) {
     switch (slash) {
         case 0x00:
             /* /AAA/ +   BBB => /AAA/BBB */
-            fullpath = malloc(basepath_len + filename_len + 1);
+            fullpath = xmalloc_assert(basepath_len + filename_len + 1);
             memcpy(fullpath, basepath, basepath_len);
             memcpy(&fullpath[basepath_len], filename, filename_len);
             fullpath[basepath_len + filename_len] = 0;
             break;
         case 0x01:
             /* /AAA/ + ./BBB => /AAA/BBB */
-            fullpath = malloc(basepath_len + filename_len + 1 - 2);
+            fullpath = xmalloc_assert(basepath_len + filename_len + 1 - 2);
             memcpy(fullpath, basepath, basepath_len);
             memcpy(&fullpath[basepath_len], filename + 2, filename_len - 2);
             fullpath[basepath_len + filename_len - 2] = 0;
             break;
         case 0x10:
             /* /AAA  +   BBB => /AAA/BBB */
-            fullpath = malloc(basepath_len + 1 + filename_len + 1);
+            fullpath = xmalloc_assert(basepath_len + 1 + filename_len + 1);
             memcpy(fullpath, basepath, basepath_len);
             fullpath[basepath_len] = '/';
             memcpy(&fullpath[basepath_len + 1], filename, filename_len);
@@ -259,7 +308,7 @@ char *getFullpathName(char *basepath, char *filename) {
             break;
         case 0x11:
             /* /AAA  + ./BBB => /AAA/BBB */
-            fullpath = malloc(basepath_len + 1 + filename_len + 1 - 2);
+            fullpath = xmalloc_assert(basepath_len + 1 + filename_len + 1 - 2);
             memcpy(fullpath, basepath, basepath_len);
             fullpath[basepath_len] = '/';
             memcpy(&fullpath[basepath_len + 1], filename + 2, filename_len - 2);
@@ -287,6 +336,8 @@ char *getFullpathDir(char *filename) {
     int filename_len;
     int i;
 
+    ASSERT(filename != NULL, "getFullpathDir - filename is NULL\n");
+
     filename_len = strlen(filename);
 
     for (i = filename_len; i > 0; i--) {
@@ -296,7 +347,7 @@ char *getFullpathDir(char *filename) {
         }
     }
 
-    fullpath = malloc(i+2);
+    fullpath = xmalloc_assert(i+2);
     memcpy(fullpath, filename, i+1);
     fullpath[i+1] = 0;
     return fullpath;
@@ -310,6 +361,12 @@ char *getFullpathDir(char *filename) {
  */
 UINT32 byte2uint32(BYTE *b) {
     UINT32 a = 0;
+
+    if (b == NULL) {
+        ERROR("byte2uint32 - NULL");
+        exit(-1);
+    }
+
 #if 0  // BE
     a = b[0];
     a = a << 8;
@@ -338,10 +395,18 @@ UINT32 byte2uint32(BYTE *b) {
  * TODO
  */
 char * trim(char *str) {
-    char *start = str;
-    char *end;
+    size_t strLen;
+    char *start, *end;
+
+    ASSERT(str != NULL, "trim - str is NULL\n");
+
+    strLen = strlen(str);
+    if (0 == strLen) {
+        return str;
+    }
 
-    end = str + strlen(str) - 1;
+    start = str;
+    end = str + strLen - 1;
 
     /* skip space at start */
     while (*str == ' ') {
@@ -370,23 +435,26 @@ char *getHexString(BYTE *bin, int size) {
     int len;
 
     /* check */
-    if (bin == NULL) {
-        ERROR("getHexString() buf is null\n");
-        return NULL;
-    }
+    // if (bin == NULL) {
+    //    ERROR("getHexString() buf is null\n");
+    //    return NULL;
+    // }
+    ASSERT(bin != NULL, "getHexString - bin is NULL\n");
 
-    buf = malloc(size * 2 + 1);
+
+    buf = xmalloc_assert(size * 2 + 1);
     ptr = buf;
     for (i = 0; i < size; i++) {
-        //len = snprintf(ptr, sizeof(ptr), "%02x", bin[i]);
+        // len = snprintf(ptr, sizeof(ptr), "%02x", bin[i]);
         len = snprintf(ptr, 3, "%02x", bin[i]);
         if (len != 2) {
             ERROR("FATAL");
             free(buf);
             return NULL;
         }
-        ptr += 2; //len;
+        ptr += 2;  // len;
     }
+    ptr[0] = '\0';
 
     return buf;
 }
@@ -394,15 +462,48 @@ char *getHexString(BYTE *bin, int size) {
 /**
  * print Hex string 
  */
-void printHex(char *head, BYTE *data, int num, char *tail) {
+void snprintHex(
+    char *outBuf, int outBufLen, char *head, BYTE *data, int num, char *tail) {
+    int outSoFar = 0;
     int i;
-    printf("%s[%d]=", head, num);
+
+    ASSERT(outBuf != NULL, "snprintHex - outBuf is NULL\n");
+    ASSERT(head != NULL, "snprintHex - head is NULL\n");
+    ASSERT(data != NULL, "snprintHex - data is NULL\n");
+    ASSERT(tail != NULL, "snprintHex - tail is NULL\n");
+
+    outSoFar += snprintf(outBuf, outBufLen, "%s[%d]=", head, num);
+
     for (i = 0; i < num; i++) {
-        printf("%02X", data[i]);
+        if ( outSoFar < outBufLen ) {
+            outSoFar += snprintf(&outBuf[outSoFar], outBufLen - outSoFar, "%02X", data[i]);
+        }
     }
-    printf("%s", tail);
+    if ( outSoFar < outBufLen ) {
+        snprintf(&outBuf[outSoFar], outBufLen - outSoFar, "%s", tail);
+    }
+}
+
+void printHex(char *head, BYTE *data, int num, char *tail) {
+    char outBuf[1024];
+    snprintHex(outBuf, 1023, head, data, num, tail);
+    /* I could just use OUTPUT(outBuf), but since warnings are errors
+       I have to use this less efficient form */
+    OUTPUT("%s", outBuf);
+}
+
+void debugHex(char *head, BYTE *data, int num, char *tail) {
+    char outBuf[1024];
+    snprintHex(outBuf, 1023, head, data, num, tail);
+    writeLog(LOG_DEBUG, outBuf);
 }
 
+void fprintHex(FILE *fp, BYTE *data, int num) {
+    int i;
+    for (i = 0; i < num; i++) {
+        fprintf(fp, "%02X", data[i]);
+    }
+}
 
 /**
  *  Convert Endian 
@@ -434,38 +535,53 @@ UINT32 b2l(UINT32 in) {
  *
  */
 int saveToFile(
-    char * filename, int len, BYTE * msg) {
+    char *filename, int len, BYTE * msg) {
     FILE *fp;
-    int rc;
+    const int max_retries = 10;
+    int n_tries = 0;
     int ptr = 0;
 
     if (len < 0) {
-        ERROR("ERROR len <0 \n");
-        return -1;
+        ERROR("len <0 \n");
+        return PTS_FATAL;
     }
     if (msg == NULL) {
-        ERROR("ERROR msg is NULL \n");
-        return -1;
+        ERROR("msg is NULL \n");
+        return PTS_FATAL;
+    }
+    if (filename == NULL) {
+        ERROR("filename is NULL \n");
+        return PTS_FATAL;
     }
 
     if ((fp = fopen(filename, "w+b")) == NULL) {
-        ERROR("ERROR: File open failed, %s \n", filename);
-        return -1;  // TODO(munetoh): set PTS error code.
+        ERROR("File open failed, %s \n", filename);
+        return PTS_FATAL;  // TODO(munetoh): set PTS error code.
     }
 
-    while (1) {
-        rc = fwrite(&msg[ptr], 1, len, fp);
-        DEBUG_IFM(" %s %d %d\n", filename, rc, len);
-        ptr += rc;
-        len -= rc;
-        if (len <= 0) break;
+    /* If the filesystem is full, we shouldn't hang whilst trying to
+       write the file to disk -> we only allow so many attempts. */
+    while (n_tries < max_retries) {
+        int bytes_written = fwrite(&msg[ptr], 1, len, fp);
+        /* DEBUG_IFM(" %s %d %d\n", filename, rc, len); */
+        ptr += bytes_written;
+        len -= bytes_written;
+        n_tries++;
+        if (len <= 0) {
+            break;
+        }
     }
 
-    DEBUG_IFM(" %s %d \n", filename, len);
+    /* DEBUG_IFM(" %s %d \n", filename, len); */
 
     fclose(fp);
 
-    return 0;
+    if (len > 0) {
+        ERROR("After %d retries still have %d bytes unwritten to '%s'\n", max_retries, len, filename);
+        return PTS_FATAL;
+    } else {
+        return PTS_SUCCESS;
+    }
 }
 
 /**
@@ -535,25 +651,46 @@ int makeDir(char *dirname) {
  * Return
  *   PTS_SUCCESS           - exist
  *   PTS_INTERNAL_ERROR    - not exist or not a dir
+ *
  */
 int checkDir(char *dirname) {
     struct stat st;
 
     if (dirname == NULL) {
-        return PTS_INTERNAL_ERROR;
+        return PTS_FATAL;
     }
 
     if (lstat(dirname, &st) == -1) {
         /* Missing dir */
-        return PTS_INTERNAL_ERROR;
+        return PTS_INTERNAL_ERROR;  // TODO OPENPTS_DIR_MISSING;
     } else if ((st.st_mode & S_IFMT) != S_IFDIR) {
         /* not DIR */
         return PTS_INTERNAL_ERROR;
     }
 
-    return PTS_SUCCESS;
+    return PTS_SUCCESS;  // TODO OPENPTS_DIR_EXIST;
 }
 
+/**
+ * Check file (reguler file)
+ */
+int checkFile(char *filename) {
+    struct stat st;
+
+    if (filename == NULL) {
+        return PTS_FATAL;
+    }
+
+    if (lstat(filename, &st) == -1) {
+        /* Missing dir */
+        return OPENPTS_FILE_MISSING;
+    } else if ((st.st_mode & S_IFMT) != S_IFREG) {
+        /* not FILE */
+        return PTS_INTERNAL_ERROR;
+    }
+
+    return OPENPTS_FILE_EXISTS;
+}
 
 /**
  * wrap read()
@@ -583,3 +720,85 @@ ssize_t wrapWrite(int fd, const void *buf, size_t count) {
     }
 }
 
+/**
+ * recursive part of unlinkDir()
+ */
+static int unlinkDir_(char *dirPath) {
+    DIR *dirHandle;
+    struct dirent *entry;
+    // int retVal;
+    char path[PATH_MAX + 1];
+    struct dirent dr;
+    int rc;
+
+
+    dirHandle = opendir(dirPath);
+    if (dirHandle == NULL) {
+        ERROR("opendir(%s) fail", dirPath);
+        return PTS_FATAL;
+    }
+
+    while (1) {
+        struct stat st;
+
+        rc = readdir_r(dirHandle, &dr, &entry);
+        if (rc != 0) break;
+        if (entry == NULL) break;
+
+        if (strcmp(".", entry->d_name) == 0) continue;
+        if (strcmp("..", entry->d_name) == 0) continue;
+
+        snprintf(path, sizeof(path), "%s/%s", dirPath, entry->d_name);
+        if (stat(path, &st) != 0) {
+            ERROR("stat(%s) fail", path);
+            rc = PTS_FATAL;
+            goto free_error;
+        }
+
+        if (S_ISDIR(st.st_mode)) {
+            if (unlinkDir_(path) != 0) {
+                rc = PTS_FATAL;
+                goto free_error;
+            }
+        } else if (S_ISREG(st.st_mode)) {
+            if (unlink(path) != 0) {
+                ERROR("unlink(%s) fail", path);
+                rc = PTS_FATAL;
+                goto free_error;
+            }
+        }
+    }
+
+    /* rm this dir */
+    if (rmdir(dirPath) != 0) {
+        ERROR("rmdir(%s) fail", dirPath);
+        rc = PTS_FATAL;
+        goto free_error;
+    }
+
+    rc = PTS_SUCCESS;
+
+  free_error:
+    closedir(dirHandle);
+
+    return rc;
+}
+
+/**
+ * Recursively destroy the content of a directory
+ */
+int unlinkDir(const char *dirPath) {
+    char path[PATH_MAX + 1];
+
+    if (dirPath == NULL || dirPath[0] == '\0' || strlen(dirPath) >= PATH_MAX) {
+        return -1;
+    }
+
+    strncpy(path, dirPath, sizeof(path));
+    // there is at least one byte free before path[PATH_MAX]
+
+    return unlinkDir_(path);
+}
+
+
+
index 84dcdbc..ec48e72 100644 (file)
@@ -117,39 +117,35 @@ OPENPTS_NONCE *newNonceContext() {
     DEBUG_CAL("newNonceContext\n");
 
     /* malloc */
-    ctx = malloc(sizeof(OPENPTS_NONCE));
+    ctx = xmalloc(sizeof(OPENPTS_NONCE));
     if (ctx == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memset(ctx, 0, sizeof(OPENPTS_NONCE));
 
     /* malloc req */
-    ctx->req = (PTS_IF_M_DH_Nonce_Parameters_Request *)malloc(sizeof(PTS_IF_M_DH_Nonce_Parameters_Request));
+    ctx->req = (PTS_IF_M_DH_Nonce_Parameters_Request *)xmalloc(sizeof(PTS_IF_M_DH_Nonce_Parameters_Request));
     if (ctx->req == NULL) {
-        ERROR("no memory\n");
-        free(ctx);
+        xfree(ctx);
         return NULL;
     }
     memset(ctx->req, 0, sizeof(PTS_IF_M_DH_Nonce_Parameters_Request));
 
     /* malloc res */
-    ctx->res = malloc(sizeof(PTS_IF_M_DH_Nonce_Parameters_Responce));
+    ctx->res = xmalloc(sizeof(PTS_IF_M_DH_Nonce_Parameters_Responce));
     if (ctx->res == NULL) {
-        ERROR("no memory\n");
-        free(ctx->req);
-        free(ctx);
+        xfree(ctx->req);
+        xfree(ctx);
         return NULL;
     }
     memset(ctx->res, 0, sizeof(PTS_IF_M_DH_Nonce_Parameters_Responce));
 
     /* malloc fin */
-    ctx->fin = malloc(sizeof(PTS_IF_M_DH_Nonce_Finish));
+    ctx->fin = xmalloc(sizeof(PTS_IF_M_DH_Nonce_Finish));
     if (ctx->fin == NULL) {
-        ERROR("no memory\n");
-        free(ctx->req);
-        free(ctx->res);
-        free(ctx);
+        xfree(ctx->req);
+        xfree(ctx->res);
+        xfree(ctx);
         return NULL;
     }
     memset(ctx->fin, 0, sizeof(PTS_IF_M_DH_Nonce_Finish));
@@ -176,37 +172,36 @@ int freeNonceContext(OPENPTS_NONCE *ctx) {
 
     /* free req */
     if (ctx->req != NULL) {
-        free(ctx->req);
+        xfree(ctx->req);
     }
     /* free res */
     if (ctx->res != NULL) {
         if (ctx->res->dh_respondor_nonce != NULL) {
-            free(ctx->res->dh_respondor_nonce);
+            xfree(ctx->res->dh_respondor_nonce);
         }
         if (ctx->res->dh_respondor_public != NULL) {
-            free(ctx->res->dh_respondor_public);
+            xfree(ctx->res->dh_respondor_public);
         }
-        free(ctx->res);
+        xfree(ctx->res);
     }
     /* free fin */
     if (ctx->fin != NULL) {
         if (ctx->fin->dh_initiator_nonce != NULL) {
-            free(ctx->fin->dh_initiator_nonce);
+            xfree(ctx->fin->dh_initiator_nonce);
         }
         if (ctx->fin->dh_initiator_public != NULL) {
-            free(ctx->fin->dh_initiator_public);
+            xfree(ctx->fin->dh_initiator_public);
         }
-        free(ctx->fin);
+        xfree(ctx->fin);
     }
     /* free secret */
     if (ctx->secret != NULL) {
         memset(ctx->secret, 0, ctx->secret_length);
-        free(ctx->secret);
+        xfree(ctx->secret);
     }
     /* free nonce */
     if (ctx->nonce != NULL) {
-        // TODO corrupted double-linked list: 0x00000000007b3240 ***
-        // free(ctx->nonce);
+        xfree(ctx->nonce);
     }
 
     /* free DH */
@@ -214,22 +209,11 @@ int freeNonceContext(OPENPTS_NONCE *ctx) {
         DH_free(ctx->dh);
     }
 
-    free(ctx);
+    xfree(ctx);
 
     return PTS_SUCCESS;
 }
 
-
-// TODO move to misc.c?
-void printHex3(char *msg, BYTE *data, int len) {
-    int i;
-    printf("%s[%d] = ", msg, len);
-    for (i = 0; i < len; i ++) {
-        printf("%02x", data[i]);
-    }
-    printf("\n");
-}
-
 /**
  * Calc ExternalDataValue (=nonce)
  *
@@ -242,7 +226,7 @@ int calcExternalDataValue(OPENPTS_NONCE *ctx) {
     // DEBUG("calcExternalDataValue\n");
 
     ctx->nonce_length = SHA1_DIGEST_SIZE;
-    ctx->nonce = malloc(SHA1_DIGEST_SIZE);
+    ctx->nonce = xmalloc_assert(SHA1_DIGEST_SIZE);
 
     SHA1_Init(&sha_ctx);
     SHA1_Update(&sha_ctx, &c, 1);
@@ -251,12 +235,12 @@ int calcExternalDataValue(OPENPTS_NONCE *ctx) {
     SHA1_Update(&sha_ctx, ctx->secret, ctx->secret_length);
     SHA1_Final(ctx->nonce, &sha_ctx);
 
-    if (verbose == DEBUG_FLAG) {
+    if (isDebugFlagSet(DEBUG_FLAG)) {
         TODO("calcExternalDataValue - nonce\n");
-        printHex("\t\tinitiator_nonce:", ctx->initiator_nonce, ctx->initiator_nonce_length, "\n");
-        printHex("\t\trespondor_nonce:", ctx->respondor_nonce, ctx->respondor_nonce_length, "\n");
-        printHex("\t\tsecret         :", ctx->secret, ctx->secret_length, "\n");
-        printHex("\t\tnonce          :", ctx->nonce, 20, "\n");
+        debugHex("\t\tinitiator_nonce:", ctx->initiator_nonce, ctx->initiator_nonce_length, "\n");
+        debugHex("\t\trespondor_nonce:", ctx->respondor_nonce, ctx->respondor_nonce_length, "\n");
+        debugHex("\t\tsecret         :", ctx->secret, ctx->secret_length, "\n");
+        debugHex("\t\tnonce          :", ctx->nonce, 20, "\n");
     }
 
     return PTS_SUCCESS;
@@ -334,9 +318,8 @@ int getDhResponce(OPENPTS_NONCE *ctx) {
     /* respondor nonce */
 
     /* malloc */
-    res->dh_respondor_nonce = malloc(res->nonce_length);
+    res->dh_respondor_nonce = xmalloc(res->nonce_length);
     if (res->dh_respondor_nonce == NULL) {
-        ERROR("no memory");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -354,9 +337,8 @@ int getDhResponce(OPENPTS_NONCE *ctx) {
     /* pubkey */
 
     /* malloc */
-    res->dh_respondor_public = malloc(DH_size(ctx->dh));
+    res->dh_respondor_public = xmalloc(DH_size(ctx->dh));
     if (res->dh_respondor_public == NULL) {
-        ERROR("no memory");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -474,9 +456,8 @@ int calcDh(OPENPTS_NONCE *ctx) {
     ctx->secret_length = DH_size(ctx->dh);
 
     /* malloc */
-    ctx->secret = malloc(ctx->secret_length);
+    ctx->secret = xmalloc(ctx->secret_length);
     if (ctx->secret == NULL) {
-        ERROR("no memory");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -484,9 +465,8 @@ int calcDh(OPENPTS_NONCE *ctx) {
     DH_compute_key(ctx->secret, pub_key, ctx->dh);
 
     /* initiator nonce */
-    fin->dh_initiator_nonce = malloc(fin->nonce_length);
+    fin->dh_initiator_nonce = xmalloc(fin->nonce_length);
     if (fin->dh_initiator_nonce == NULL) {
-        ERROR("no memory");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -502,9 +482,8 @@ int calcDh(OPENPTS_NONCE *ctx) {
     ctx->initiator_nonce = fin->dh_initiator_nonce;
 
     /* pubkey */
-    fin->dh_initiator_public = malloc(DH_size(ctx->dh));
+    fin->dh_initiator_public = xmalloc(DH_size(ctx->dh));
     if (fin->dh_initiator_public == NULL) {
-        ERROR("no memory");
         return PTS_INTERNAL_ERROR;
     }
     BN_bn2bin(ctx->dh->pub_key, fin->dh_initiator_public);
@@ -543,7 +522,7 @@ int calcDhFin(OPENPTS_NONCE *ctx) {
 
     /* calc secret */
     ctx->secret_length = DH_size(ctx->dh);
-    ctx->secret = malloc(ctx->secret_length);
+    ctx->secret = xmalloc_assert(ctx->secret_length);
     DH_compute_key(ctx->secret, pub_key, ctx->dh);
 
     /* calc ExternalDataValue */
index f0bd6de..5a7d1b5 100644 (file)
 #include <dirent.h>
 #include <limits.h>
 
-// #define USE_SCANDIR
-
 #include <openpts.h>
 
-int verbose = 0; /**< DEBUG */
+/* Well defined return values that can be interpreted by the GUI */
+#define RETVAL_OK_TRUSTED       0
+#define RETVAL_NOTTRUSTED       1
+#define RETVAL_TARGET_ERROR     2
+#define RETVAL_GLOBAL_ERROR     3
+#define RETVAL_NOTENROLLED      4
+#ifdef CONFIG_AUTO_RM_UPDATE
+#define RETVAL_OK_PENDINGUPDATE 5
+#endif
 
-// DEBUG
-// /usr/sbin/ptsc -m
-// /PATH/ptsc -m -c XXX
-// openpts -P PATH -C CONF
-extern char *ptsc_command;
 
 #define LINE "--------------------------------------------------------------------"
 
+// TODO
+extern char *ptsc_command;
+
+
 /**
  * Usage
  */
 void usage(void) {
+#if 0
     fprintf(stderr, "OpenPTS command\n\n");
     fprintf(stderr, "Usage: openpts [options] {-i [-f]|[-v]|-D} <target>\n");
     fprintf(stderr, "       openpts -D\n\n");
@@ -90,29 +96,104 @@ void usage(void) {
     fprintf(stderr, "  -p port               ssh port number [ssh default]\n");
     fprintf(stderr, "  -c configfile         Set configuration file [~/.openpts/openpts.conf]\n");
     fprintf(stderr, "\n");
+#endif
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_USAGE, "OpenPTS command\n\n"
+        "Usage: openpts [options] {-i [-f]|[-v]||-r|-D} <target>\n"
+        "       openpts -D\n\n"
+        "Commands:\n"
+        "  -i [-f]               Enroll a target node and acquire [overwrite (-f)] the reference measurement.\n"
+        "  [-v]                  Verify target (collector) integrity against known measurement.\n"
+        "  -r                    Remove the target from the set of known reference measurements.\n"
+        "  -D                    Display the configuration (target/ALL)\n"
+        "\n"
+        "Miscellaneous:\n"
+        "  -h                    Show this help message\n"
+        "  -V                    Verbose mode. Multiple -V options increase the verbosity.\n"
+        "\n"
+        "Options:\n"
+        "  -u                    Accept a measurement update during attestation, if there are any available.\n"
+        "  -l username           ssh username [ssh default]\n"
+        "  -p port               ssh port number [ssh default]\n"
+        "  -c configfile         Set configuration file [~/.openpts/openpts.conf]\n"
+        "\n"));
 }
 
 #define INIT    0
 #define VERIFY  1
 #define UPDATE  2
-#define DISPLAY 3
-#define NONE    4
+#define REMOVE  3
+#define DISPLAY 4
+#define NONE    5
 
 /**
  * get Default Config File
  */
 int getDefaultConfigfile(OPENPTS_CONFIG *conf) {
-    int rc;
+    int rc = -1;  // TODO
     /* use system default config file */
+    int createBasicConfig = 0;
+    int configDirExists;
+
     char dirbuf[BUF_SIZE];
     char confbuf[BUF_SIZE];
     char uuidbuf[BUF_SIZE];
+    char *homeDir = getenv("HOME");
 
-    snprintf(dirbuf, BUF_SIZE, "%s/.openpts", getenv("HOME"));
-    snprintf(confbuf, BUF_SIZE, "%s/.openpts/openpts.conf", getenv("HOME"));
-    snprintf(uuidbuf, BUF_SIZE, "%s/.openpts/uuid", getenv("HOME"));
+
+    snprintf(dirbuf, BUF_SIZE, "%s/.openpts", homeDir);
+    snprintf(confbuf, BUF_SIZE, "%s/.openpts/openpts.conf", homeDir);
+    snprintf(uuidbuf, BUF_SIZE, "%s/.openpts/uuid", homeDir);
 
     /* check dir */
+    configDirExists = (checkDir(dirbuf) == PTS_SUCCESS);
+
+    if (!configDirExists) {
+        // create and initialize the $HOME/.openpts directory
+        rc = mkdir(dirbuf, S_IRUSR | S_IWUSR | S_IXUSR);
+        if (rc != 0) {
+            ERROR("mkdir on $HOME/.openpts failed (errno=%d)", errno);
+            perror(dirbuf);
+            goto error;
+        }
+        createBasicConfig = 1;
+    } else {
+        struct stat statBuf;
+        if (-1 == stat(confbuf, &statBuf) && ENOENT == errno) {
+            ERROR("Found openpts dir '%s', but no config file - will create one.", dirbuf);
+            createBasicConfig = 1;
+        }
+    }
+
+    if (createBasicConfig) {
+        /* new UUID */
+        conf->uuid = newOpenptsUuid();
+        conf->uuid->filename = smalloc_assert(uuidbuf);
+        conf->uuid->status = OPENPTS_UUID_FILENAME_ONLY;
+
+        genOpenptsUuid(conf->uuid);
+        rc = writeOpenptsUuidFile(conf->uuid, 1);
+        if (rc != 0) {
+            // rollback
+            if (configDirExists) {
+                unlink(dirbuf);  // will fail if log file exists
+            }
+            goto error;
+        }
+
+        rc = writeOpenptsConf(conf, confbuf);
+        if (rc != 0) {
+            // rollback
+            unlink(uuidbuf);
+            if (configDirExists) {
+                unlink(dirbuf);  // will fail if log file exists
+            }
+            goto error;
+        }
+    }
+
+
+
+#if 0
     if (checkDir(dirbuf) != PTS_SUCCESS) {
         char ans;
         if (isatty(STDIN_FILENO)) {
@@ -152,21 +233,50 @@ int getDefaultConfigfile(OPENPTS_CONFIG *conf) {
             goto error;
         }
     }
-
+#endif
     /* check conf  */
 
     DEBUG("read conf file          : %s\n", confbuf);
     rc = readOpenptsConf(conf, confbuf);
     if (rc != 0) {
         ERROR("readOpenptsConf() failed\n");
-        goto error;
     }
-    return PTS_SUCCESS;
 
   error:
-    return PTS_FATAL;
+
+    return rc;
 }
 
+void global_lock(int type) {
+    int fd;
+    struct flock fl;
+    char *home, path[PATH_MAX];
+
+    home = getenv("HOME");
+    if (home == NULL) {
+        ERROR("HOME environment variable not defined\n");
+        exit(1);
+    }
+    snprintf(path, PATH_MAX, "%s/.openpts", home);
+    if (mkdir(path, 0700) < 0 && errno != EEXIST) {
+        perror(path);
+    exit(1);
+    }
+    snprintf(path, PATH_MAX, "%s/.openpts/rwlock", home);
+    fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
+    if (fd < 0) {
+        perror(path);
+        exit(1);
+    }
+    fl.l_start = 0;
+    fl.l_len = 0;
+    fl.l_whence = SEEK_SET;
+    fl.l_type = type;
+    if (fcntl(fd, F_SETLKW, &fl) < 0) {
+        perror(path);
+        exit(1);
+    }
+}
 
 /**
  * main of "openpts" command 
@@ -177,12 +287,14 @@ int getDefaultConfigfile(OPENPTS_CONFIG *conf) {
  */
 int main(int argc, char *argv[]) {
     int command = NONE;
-    int rc = 0;
+    int rc = 0;       // temporary return code
+    int retVal = -1;  // main() actual return value
     int opt;
 
     OPENPTS_CONFIG *conf = NULL;  // conf for openpts
     OPENPTS_CONTEXT *ctx = NULL;
     char * config_filename = NULL;
+    char * cmdline_hostname = NULL;
     char * target_hostname = NULL;
     int initialized = 0;  // 0 -> 1 -> 2
     char * target_conf_dir = NULL;
@@ -193,52 +305,52 @@ int main(int argc, char *argv[]) {
 #ifdef CONFIG_AUTO_RM_UPDATE
     int update_by_default = 0;
 #endif
+    int print_pcr_hints = 0;
     int i;
     OPENPTS_TARGET *target_collector = NULL;
     OPENPTS_CONFIG *target_conf = NULL;    // conf for target
     int new_target = 0;  // indicate new target
-    int debug = 0;
-    // DEBUG
     char *ptsc_path = NULL;
     char *ptsc_conf = NULL;
 
-    verbose = 0;
+    initCatalog();
 
     /* args */
-    while ((opt = getopt(argc, argv, "ivuDVc:dfuyl:p:P:C:h")) != -1) {
+    while ((opt = getopt(argc, argv, "givruDVc:dfuyl:p:P:C:h")) != -1) {
         switch (opt) {
         case 'i':
             if (command == NONE) {
                 command = INIT;
                 break;
             }
-            ERROR("Only one command may be given at a time.");
-            usage();
-            return -1;
         case 'v':
             if (command == NONE) {
                 command = VERIFY;
                 break;
             }
-            ERROR("Only one command may be given at a time.");
-            usage();
-            return -1;
+        case 'r':
+            if (command == NONE) {
+                command = REMOVE;
+                break;
+            }
         case 'D':
             if (command == NONE) {
                 command = DISPLAY;
                 break;
             }
-            ERROR("Only one command may be given at a time.");
+
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_ONE_COMMAND_ONLY, "Only one command may be given at a time."));
             usage();
             return -1;
+
         case 'V':
-            debug++;
+            incVerbosity();
             break;
         case 'c':
             config_filename = optarg;
             break;
         case 'd':
-            verbose = DEBUG_FLAG | DEBUG_FSM_FLAG;
+            setDebugFlags(DEBUG_FLAG | DEBUG_FSM_FLAG);
             break;
         case 'f':
             force = 1;
@@ -260,8 +372,13 @@ int main(int argc, char *argv[]) {
         case 'C':
             ptsc_conf = optarg;
             break;
+        case 'g':
+            print_pcr_hints = 1;
+            break;
         case 'h':
-            /* fall through */
+            usage();
+            /* we succeeded in asking for help, so return 0 */
+            return 0;
         default:
             usage();
             return -1;
@@ -271,14 +388,18 @@ int main(int argc, char *argv[]) {
     argc -= optind;
     argv += optind;
 
-    target_hostname = argv[0];
+    cmdline_hostname = argv[0];
 
     /* check */
     if ((ptsc_path != NULL) && (ptsc_conf != NULL)) {
         int len;
+        // char ptsc_command[PATH_MAX];
         INFO("ptsc debug mode\n");
+        // len = strlen(ptsc_path) + strlen(ptsc_conf) + 13;
+        // snprintf(ptsc_command, PATH_MAX - 1, "%s -m -v -c %s", ptsc_path, ptsc_conf);
+
         len =  strlen(ptsc_path) + strlen(ptsc_conf) + 13;
-        ptsc_command = malloc(len);
+        ptsc_command = xmalloc(len);
         snprintf(ptsc_command, len, "%s -m -v -c %s", ptsc_path, ptsc_conf);
         INFO("command: %s\n", ptsc_command);
     }
@@ -286,64 +407,123 @@ int main(int argc, char *argv[]) {
     /* default command is to verify */
     if (command == NONE) command = VERIFY;
 
-    /* set the DEBUG level, 1,2,3 */
-    if (debug > 2) {
-        verbose = DEBUG_FLAG | DEBUG_FSM_FLAG | DEBUG_IFM_FLAG;
-    } else if (debug > 1) {
-        verbose = DEBUG_FLAG | DEBUG_IFM_FLAG;
-    } else if (debug > 0) {
-        verbose = DEBUG_FLAG;
+#ifdef OPENPTS_DEBUG
+    setDebugFlags(DEBUG_FLAG | DEBUG_FSM_FLAG | DEBUG_IFM_FLAG);
+#else
+    /* set the DEBUG level, 1,2,3
+       WORK NEEDED - should have a debug flag too. */
+    if (getVerbosity() > 2) {
+        setDebugFlags(DEBUG_FLAG | DEBUG_FSM_FLAG | DEBUG_IFM_FLAG);
+    } else if (getVerbosity() > 1) {
+        setDebugFlags(DEBUG_FLAG | DEBUG_IFM_FLAG);
+    } else if (getVerbosity() > 0) {
+        setDebugFlags(DEBUG_FLAG);
     }
+#endif
 
-    DEBUG("DEBUG mode (%d)\n", debug);
+    /* global locks solve concurrency issues */
+    if (command == VERIFY || command == DISPLAY) {
+        global_lock(F_RDLCK);
+    } else {
+        global_lock(F_WRLCK);
+    }
 
     /* new config */
     conf = newPtsConfig();
     if (conf == NULL) {
-        printf("ERROR\n");  // TODO(munetoh)
-        return -1;
+        retVal = RETVAL_GLOBAL_ERROR;
+        goto out_free;
     }
 
-    /* check/create config file */
+    /* check/create config file - HOME./openpts/openpts.conf */
     if (config_filename == NULL) {
         /* use default config file, HOME./openpts/openpts.conf  */
+        DEBUG("Using system default config file\n");
         rc = getDefaultConfigfile(conf);
-        if (rc != PTS_SUCCESS) {
-            ERROR("getDefaultConfigfile() failed\n");
-            rc = -1;
-            goto error;
-        } else {
-            initialized++;  // 0->1
-        }
     } else {
         /* use given config file */
         DEBUG("read conf file       : %s\n", config_filename);
         rc = readOpenptsConf(conf, config_filename);
-        if (rc != 0) {
-            ERROR("config file [%s] - missing\n", config_filename);
-            rc = -1;
-            goto error;
+    }
+
+    if (rc != 0) {
+        ERROR("Failed to read config file\n");
+        retVal = RETVAL_GLOBAL_ERROR;
+        goto out_free;
+    } else {
+        initialized++;  // 0->1
+    }
+
+    DEBUG("VERBOSITY (%d), DEBUG mode (0x%x)\n", getVerbosity(), getDebugFlags());
+
+    /* we always need the target list */
+    rc = getTargetList(conf, conf->config_dir);
+    if (rc != PTS_SUCCESS) {
+        retVal = RETVAL_GLOBAL_ERROR;
+        goto out_free;
+    }
+
+    /* check/create target conf dir */
+    if (cmdline_hostname != NULL) {
+        /* parse ssh notation */
+        char *ptr;
+        ptr = strchr(cmdline_hostname, '@');
+        if (ptr != NULL) {
+            ssh_username = cmdline_hostname;
+            cmdline_hostname = ptr + 1;
+            *ptr = '\0';
+        }
+        ptr = strchr(cmdline_hostname, ':');
+        if (ptr != NULL) {
+            ssh_port = ptr + 1;
+            *ptr = '\0';
+        }
+
+        /* look up the conf of target(hostname) */
+        /* set the target hostname:port and search */
+        if (conf->hostname != NULL) {
+            TODO("realloc conf->hostname\n");
+            xfree(conf->hostname);
+        }
+        conf->hostname = smalloc_assert(cmdline_hostname);
+        target_hostname = smalloc_assert(cmdline_hostname);
+        target_collector =  getTargetCollector(conf);
+        if (target_collector == NULL) {
+            // user may have given the UUID instead of the hostname of the target
+            target_collector = getTargetCollectorByUUID(conf, cmdline_hostname);
+            if (target_collector != NULL) {
+                /* HIT with UUID */
+                // fake we were called with target name
+                xfree(conf->hostname);
+                conf->hostname = smalloc_assert(((OPENPTS_CONFIG*)target_collector->target_conf)->hostname);
+                xfree(target_hostname);
+                target_hostname = smalloc_assert(((OPENPTS_CONFIG*)target_collector->target_conf)->hostname);
+            }
+        }
+
+        if (target_collector == NULL) {
+            /* missing, new target => malloc temp target */
+            new_target = 1;
+            target_conf = newPtsConfig();
+            if (target_conf == NULL) {
+                retVal = RETVAL_GLOBAL_ERROR;
+                goto out_free;
+            }
         } else {
-            initialized++;  // 0->1
+            /* HIT exist */
+            target_conf_dir = getTargetConfDir(conf);  // HOME/.openpts/UUID
+            target_conf_filename = smalloc_assert(target_collector->target_conf_filename);
+            target_conf = (OPENPTS_CONFIG*)target_collector->target_conf;
         }
     }
 
     /* Display (no remote access) */
     if (command == DISPLAY) {
-        /* target List */
-        rc = getTargetList(conf, conf->config_dir);
-        if (rc != PTS_SUCCESS) {
-            TODO("main() - getTargetList rc =%d\n", rc);
-        }
-
         if (target_hostname != NULL) {
             /* given target (by hostname) */
             /* look up */
-            conf->hostname = smalloc(target_hostname);
-            target_collector =  getTargetCollector(conf);
             if (target_collector != NULL) {
-                target_conf = (OPENPTS_CONFIG*)target_collector->target_conf;
-
+                // WORK NEEDED: Please use NLS for i18n output
                 printf("hostname  : %s\n", target_hostname);
                 printf("UUID      : %s\n", target_collector->str_uuid);
                 printf("State     : %d\n", target_collector->state);
@@ -353,52 +533,37 @@ int main(int argc, char *argv[]) {
                 getRmList(target_conf, target_conf->config_dir);
                 printRmList(target_conf, "");
             } else {
-                printf("hostname  : %s --- unknown host, check the list\n", target_hostname);
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_TARGET_NOT_INITIALIZED,
+                       "The target %s is not initialized yet. Please enroll with '%s' first\n\n"),
+                        target_hostname, target_hostname);
+                retVal = RETVAL_NOTENROLLED;
             }
-            goto free;  // exit
+            goto out_free;  // exit
         } else {
             /* all target (simple) */
-            printTargetList(conf, "");  // target.c
-            goto free;  // exit anyway
+            printTargetList(conf, "");
+            goto out_free;  // exit
         }
-    }
-
-
-    /* Other commands use Remote Access (SSH) */
-
-    if (target_hostname == NULL) {
-        printf("set the target.\n");
+    } else if ( NULL == target_hostname ) {
+        /* Other commands use Remote Access (SSH) */
         usage();
-        goto free;
+        goto out_free;
     }
 
-    /* check/create target conf dir */
-    /* look up the conf of target(hostname) */
-    rc = getTargetList(conf, conf->config_dir);
-    if (rc != PTS_SUCCESS) {
-        TODO("main() - getTargetList rc =%d\n", rc);
-    }
-    if (verbose & DEBUG_FLAG) {
-        DEBUG("target list\n");
-        printTargetList(conf, "");  // uuid.c
-    }
-
-    /* set the target hostname:port and search */
-    if (conf->hostname != NULL) {
-        TODO("realloc conf->hostname\n");
-        free(conf->hostname);
-    }
-    conf->hostname = smalloc(target_hostname);
-    target_collector =  getTargetCollector(conf);
-    if (target_collector == NULL) {
-        /* missing, new target => malloc temp target */
-        new_target = 1;
-        target_conf = newPtsConfig();
-    } else {
-        /* HIT exist */
-        target_conf_dir  = getTargetConfDir(conf);  // HOME/.openpts/UUID
-        target_conf_filename = smalloc(target_collector->target_conf_filename);
-        target_conf = (OPENPTS_CONFIG*)target_collector->target_conf;
+    if (command == REMOVE) {
+        if (target_conf_dir == NULL) {
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TARGET_NOT_INITIALIZED,
+                        "The target %s is not initialized yet. Please enroll with '%s' first\n\n"),
+                    target_hostname, target_hostname);
+            retVal = RETVAL_NOTENROLLED;
+            goto out_free;
+        }
+        if (unlinkDir(target_conf_dir) != 0) {
+            retVal = RETVAL_TARGET_ERROR;
+            goto out_free;
+        }
+        retVal = RETVAL_NOTENROLLED;
+        goto out_free;
     }
 
     /* verify -> read target conf */
@@ -408,6 +573,8 @@ int main(int argc, char *argv[]) {
             initialized++;  // 1->2
         } else {
             ERROR("target_conf_dir, %s is missing", target_conf_dir);
+            retVal = RETVAL_GLOBAL_ERROR;
+            goto out_free;
         }
     }
 
@@ -416,7 +583,8 @@ int main(int argc, char *argv[]) {
         target_conf->ssh_username = strdup(ssh_username);
         if (target_conf->ssh_username == NULL) {
             ERROR("No memory");
-            goto free;
+            retVal = RETVAL_GLOBAL_ERROR;
+            goto out_free;
         }
     } else {
         ssh_username = target_conf->ssh_username;
@@ -426,109 +594,119 @@ int main(int argc, char *argv[]) {
     if (ssh_port != NULL) {
         target_conf->ssh_port = smalloc(ssh_port);
         if (target_conf->ssh_port == NULL) {
-            ERROR("No memory");
-            goto free;
+            retVal = RETVAL_GLOBAL_ERROR;
+            goto out_free;
         }
     } else {
         ssh_port = target_conf->ssh_port;
     }
 
-    // TODO Wrong?
+    // TODO reset old settings if exist (previous config)
     if (command == INIT) {
         if (target_conf->hostname != NULL) {
             // DEBUG("realloc target_conf->hostname\n"); TODO realloc happen
-            free(target_conf->hostname);
+            xfree(target_conf->hostname);
         }
-        target_conf->hostname = smalloc(target_hostname);
-        target_conf->ssh_port = smalloc(ssh_port);
+        target_conf->hostname = smalloc_assert(target_hostname);
+        target_conf->ssh_port = smalloc_assert(ssh_port);
     }
 
     /* new context */
     ctx = newPtsContext(conf);
     if (ctx == NULL) {
-        printf("ERROR\n");  // TODO(munetoh)
-        rc = -1;
-        goto error;
+        // TODO(munetoh)
+        retVal = RETVAL_GLOBAL_ERROR;
+        goto out_free;
     }
-    ctx->target_conf = target_conf;
 
     /* command */
     switch (command) {
     case INIT:
-        /* */
-        ctx->target_conf = NULL;
-
-
+    {
         /* get UUID, RMs, AIDE DB */
-        DEBUG("enroll with %s  (SSH uses localost)\n", target_hostname);
+        DEBUG("enroll with %s\n", target_hostname);
         DEBUG("conf->config_dir %s\n", conf->config_dir);
-        rc =  enroll(ctx, target_hostname, ssh_username, ssh_port, conf->config_dir, force);  // verifier.c
+        rc = enroll(ctx, target_hostname, ssh_username, ssh_port, conf->config_dir, force);  // verifier.c
         if (rc != 0) {
-            fprintf(stderr, "enroll was failed, rc = %d\n", rc);
-            printReason(ctx);
-            goto error;
+            ERROR("enroll was failed, rc = %d\n", rc);
+            printReason(ctx, print_pcr_hints);
+            retVal = RETVAL_NOTENROLLED;
+            goto out_free;
         }
 
         DEBUG("conf->config_dir %s\n", conf->config_dir);
         rc =  verifier(ctx, target_hostname, ssh_username, ssh_port, conf->config_dir, 1);  // init
         if (rc != OPENPTS_RESULT_VALID) {
-            fprintf(stderr, "initial verification was failed, rc = %d\n", rc);
-            printReason(ctx);
-            goto error;
+            ERROR("initial verification was failed, rc = %d\n", rc);
+            printReason(ctx, print_pcr_hints);
+            retVal = RETVAL_NOTTRUSTED;
+            goto out_free;
         }
 
+        retVal = RETVAL_OK_TRUSTED;
+
         /* message */
-        printf("Target            : %s\n", target_hostname);
+        printf(NLS(MS_OPENPTS, OPENPTS_INIT_TARGET, "Target: %s\n"), target_hostname);
 
         if (ctx->target_conf != NULL) {
             if (ctx->target_conf->rm_uuid != NULL) {
-                printf("Manifest UUID     : %s\n", ctx->target_conf->rm_uuid->str);
+                printf(NLS(MS_OPENPTS, OPENPTS_INIT_MANIFEST_UUID,
+                    "Manifest UUID: %s\n"), ctx->target_conf->rm_uuid->str);
                 for (i = 0; i< ctx->conf->rm_num; i ++) {
-                    printf("manifest[%d]       : %s\n", i, ctx->target_conf->rm_filename[i]);
+                    printf(NLS(MS_OPENPTS, OPENPTS_INIT_MANIFEST,
+                        "Manifest[%d]: %s\n"), i, ctx->target_conf->rm_filename[i]);
                 }
             }
-            printf("Collector UUID    : %s\n", ctx->target_conf->uuid->str);
-            printf("configuration     : %s\n", ctx->target_conf->config_file);
-            printf("validation policy : %s\n", ctx->target_conf->policy_filename);
+            /* having indentation specific to one language will make the
+               translated versions (i.e. french, japanese) look ugly */
+            printf(NLS(MS_OPENPTS, OPENPTS_INIT_COLLECTOR_UUID,
+                "Collector UUID: %s\n"), ctx->target_conf->uuid->str);
+            printf(NLS(MS_OPENPTS, OPENPTS_INIT_CONFIG,
+                "Configuration: %s\n"), ctx->target_conf->config_file);
+            printf(NLS(MS_OPENPTS, OPENPTS_INIT_VALIDATION,
+                "Validation policy: %s\n"), ctx->target_conf->policy_filename);
         } else {
             // TODO never happen?
-            printf("configuration     : new target\n");
+            printf(NLS(MS_OPENPTS, OPENPTS_INIT_NEW_CONFIG, "Configuration: new target\n"));
         }
         break;
+    }
     case VERIFY:
+    {
         /* verify */
         if (initialized < 2) {
-            fprintf(stderr, "ERROR: target %s is not initialized yet. please enroll with %s first\n\n",
-                target_hostname, target_hostname);
-            usage();
-            rc = -1;
-            goto error;
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TARGET_NOT_INITIALIZED,
+                   "The target %s is not initialized yet. Please enroll with '%s' first\n\n"),
+                   target_hostname, target_hostname);
+            retVal = RETVAL_NOTENROLLED;
+            goto out_free;
         }
 
         // TODO(munetoh) control by policy? or conf?
         ctx->conf->ima_validation_unknown = 1;
 
         /* vefify*/
-        rc =  verifier(ctx, target_hostname, ssh_username, ssh_port, conf->config_dir, 0);  // normal
+        rc = verifier(ctx, target_hostname, ssh_username, ssh_port, conf->config_dir, 0);  // normal
 
         /* messages */
         // printf("target        : %s\n", argv[0]);
-        printf("Target            : %s\n", argv[0]);
+        printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_TARGET, "Target: %s\n"), target_hostname);
         if (target_conf != NULL) {
-            printf("Collector UUID    : %s ", target_conf->uuid->str);
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_COLLECTOR_UUID, "Collector UUID: %s "), target_conf->uuid->str);
             // TODO set this when load the uuid
             if (target_conf->uuid->time == NULL) {
                 target_conf->uuid->time = getDateTimeOfUuid(target_conf->uuid->uuid);
             }
-            printf("(date: %04d-%02d-%02d-%02d:%02d:%02d)\n",
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_DATE, "(date: %04d-%02d-%02d-%02d:%02d:%02d)\n"),
                 target_conf->uuid->time->year + 1900,
                 target_conf->uuid->time->mon + 1,
                 target_conf->uuid->time->mday,
                 target_conf->uuid->time->hour,
                 target_conf->uuid->time->min,
                 target_conf->uuid->time->sec);
-            printf("Manifest UUID     : %s ", target_conf->rm_uuid->str);
-            printf("(date: %04d-%02d-%02d-%02d:%02d:%02d)\n",
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_MANIFEST_UUID,
+                "Manifest UUID: %s "), target_conf->rm_uuid->str);
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_DATE, "(date: %04d-%02d-%02d-%02d:%02d:%02d)\n"),
                 target_conf->rm_uuid->time->year + 1900,
                 target_conf->rm_uuid->time->mon + 1,
                 target_conf->rm_uuid->time->mday,
@@ -536,154 +714,213 @@ int main(int argc, char *argv[]) {
                 target_conf->rm_uuid->time->min,
                 target_conf->rm_uuid->time->sec);
 
-            printf("username(ssh)     : %s\n",
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_USERNAME, "username(ssh): %s\n"),
                 conf->ssh_username ? conf->ssh_username : "default");
-            printf("port(ssh)         : %s\n",
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_PORT, "port(ssh): %s\n"),
                 conf->ssh_port ? conf->ssh_port : "default");
-            printf("policy file       : %s\n", target_conf->policy_filename);
-            printf("property file     : %s\n", target_conf->prop_filename);  // TODO ptoperty or prop
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_POLICY, "policy file: %s\n"), target_conf->policy_filename);
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_PROPERTY,
+                "property file: %s\n"), target_conf->prop_filename);  // TODO property or prop
         } else {
-            // ERROR("\n");
+            retVal = RETVAL_GLOBAL_ERROR;
+            goto out_free;
         }
 
         if (rc == OPENPTS_RESULT_VALID) {
-            printf("integrity         : valid\n");
-        } else if (rc == OPENPTS_RESULT_INVALID) {
-            printf("integrity         : invalid\n");
-            printReason(ctx);
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_VALID, "integrity: valid\n"));
+            retVal = RETVAL_OK_TRUSTED;
+        } else if (rc == OPENPTS_RESULT_INVALID ||
+                   rc == PTS_VERIFY_FAILED ||
+                   rc == PTS_NOT_INITIALIZED ||  // <-- happens when a target changed its UUID (re-init)
+                   rc == PTS_RULE_NOT_FOUND) {   // <-- happens when a target has updated its RM
+                                                 //     (failed selftest using -s)
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_INVALID, "integrity: invalid\n"));
+            printReason(ctx, print_pcr_hints);
+            retVal = RETVAL_NOTTRUSTED;
+            goto out_free;
         } else if (rc == OPENPTS_RESULT_UNKNOWN) {
-            printf("integrity         : unknown\n");
-            printReason(ctx);
-        } else if (rc == PTS_VERIFY_FAILED) {
-            printf("integrity         : invalid ()\n");
-            printReason(ctx);
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_UNKNOWN, "integrity: unknown\n"));
+            printReason(ctx, print_pcr_hints);
+            retVal = RETVAL_TARGET_ERROR;
+            goto out_free;
         } else {
-            printf("integrity         : unknown (INTERNAL ERROR) rc=%d\n", rc);
-            printReason(ctx);
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_ERROR, "integrity: unknown (INTERNAL ERROR) rc=%d\n"), rc);
+            printReason(ctx, print_pcr_hints);
+            retVal = RETVAL_TARGET_ERROR;
+            goto out_free;
         }
 
+
 #ifdef CONFIG_AUTO_RM_UPDATE
         // Verify() check the ARU
-        // remote : conf->aru_newrm_uuid
+        // remote : conf->target_newrm_uuid
         // local  : target_conf->newrm_uuid
-        if ((target_conf != NULL) && (conf->newrm_exist > 0)) {
-            char *uuid_str;
+        if (NULL != target_conf && conf->target_newrm_exist > 0) {
+            char *uuid_str = NULL;  // 37?
             PTS_DateTime *uuid_time;
-            char ans;
-            int same = 0;
+            char ans[32];
+            int ansIsYes, ansIsNo;
 
-            if (verbose & DEBUG_FLAG) {
+            if (getVerbosity() > 0) {
                 DEBUG("NEWRM_UUID\n");
-                printHex("NEWRM UUID (remote)  : ", (BYTE*)conf->aru_newrm_uuid, 16, "\n");
-                if (target_conf->newrm_uuid != NULL) {
-                    printHex("NEWRM UUID (local)   : ", (BYTE*)target_conf->newrm_uuid->uuid, 16, "\n");
+                printHex(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_UUID_REMOTE,
+                    "NEWRM UUID (remote): "), (BYTE*)conf->target_newrm_uuid, 16, "\n");
+                if ( NULL != target_conf->newrm_uuid &&
+                     NULL != target_conf->newrm_uuid->uuid ) {
+                    printHex(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_UUID_LOCAL,
+                        "NEWRM UUID (local): "), (BYTE*)target_conf->newrm_uuid->uuid, 16, "\n");
                 } else {
-                    printf("NEWRM UUID (local)   : missing\n");
+                    printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_UUID_MISSING, "NEWRM UUID (local): missing\n"));
                 }
             }
 
             /* Check local newrm vs remote newrm */
-            if ((target_conf->newrm_uuid != NULL) && (target_conf->newrm_uuid->uuid != NULL)) {
-                if (memcmp(
-                        (BYTE*)conf->aru_newrm_uuid,
-                        (BYTE*)target_conf->newrm_uuid->uuid, 16) == 0) {
+            if ( NULL != target_conf->newrm_uuid &&
+                 NULL != target_conf->newrm_uuid->uuid) {
+                if (0 == memcmp((BYTE*)conf->target_newrm_uuid,
+                                (BYTE*)target_conf->newrm_uuid->uuid, 16) &&
+                    0 == isNewRmStillValid(ctx, conf->config_dir) ) {
                     /* HIT */
                     printf("---------------------------------------------------------\n");
-                    printf("New Manifest UUID : %s ", target_conf->newrm_uuid->str);
-                    printf("(date: %04d-%02d-%02d-%02d:%02d:%02d) - local\n",
+                    printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_MANIFEST_UUID,
+                        "New Manifest UUID: %s "), target_conf->newrm_uuid->str);
+                    printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_DATE, "(date: %04d-%02d-%02d-%02d:%02d:%02d)\n"),
                         target_conf->newrm_uuid->time->year + 1900,
                         target_conf->newrm_uuid->time->mon + 1,
                         target_conf->newrm_uuid->time->mday,
                         target_conf->newrm_uuid->time->hour,
                         target_conf->newrm_uuid->time->min,
                         target_conf->newrm_uuid->time->sec);
-                    goto free;
+                    retVal = RETVAL_OK_TRUSTED;
+                    goto out_free;
                 } else {
                     /* local is old? */
-                    same = 1;
+                    printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_MANIFEST_ALREADY_EXISTS,
+                           "A new reference manifest has been received, but an update exists\n"));
                 }
             }
 
             /* msg */
             printf("---------------------------------------------------------\n");
-            uuid_time = getDateTimeOfUuid(conf->aru_newrm_uuid);
-            uuid_str = getStringOfUuid(conf->aru_newrm_uuid);
-            printf("New Manifest UUID : %s ", uuid_str);
-            printf("(date: %04d-%02d-%02d-%02d:%02d:%02d)\n",
+            uuid_time = getDateTimeOfUuid(conf->target_newrm_uuid);
+            uuid_str = getStringOfUuid(conf->target_newrm_uuid);
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_MANIFEST_UUID, "New Manifest UUID: %s "), uuid_str);
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_DATE, "(date: %04d-%02d-%02d-%02d:%02d:%02d)\n"),
                 uuid_time->year + 1900,
                 uuid_time->mon + 1,
                 uuid_time->mday,
                 uuid_time->hour,
                 uuid_time->min,
                 uuid_time->sec);
-            free(uuid_str);
+            xfree(uuid_str);
+
+            if (isatty(STDIN_FILENO) && !update_by_default) {
+                char *lineFeed;
+                printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_MANIFEST_UPDATE,
+                    "A new reference manifest exists. Update? [Y/n]\n"));
+                if ( NULL != fgets(ans, 32, stdin) ) {
+                    // strip the ending line-feed
+                    if ((lineFeed = strrchr(ans, '\n')) != NULL) {
+                        *lineFeed = '\0';
+                    }
 
-            if (same == 0) {
-                if (isatty(STDIN_FILENO)) {
-                    printf("New reference manifest exist. update? [Y/n]\n");
-                    rc = scanf("%[YyNn]", &ans);
+                    ansIsYes = (strcasecmp(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_MANIFEST_UPDATE_YES, "y"), ans) == 0);
+                    ansIsYes |= (strlen(ans) == 0);  // default answer case
+                    ansIsNo = (strcasecmp(NLS(MS_OPENPTS, OPENPTS_VERIFY_NEW_MANIFEST_UPDATE_NO, "n"), ans) == 0);
                 } else {
-                    rc = 1;
-                    ans = update_by_default ? 'Y' : 'N';
+                    ansIsYes = 0;
+                    ansIsNo  = 1;
                 }
+            } else {
+                // non-interractive
+                ansIsYes = update_by_default;
+                ansIsNo = !update_by_default;
+            }
 
-                DEBUG("conf->config_dir %s\n", conf->config_dir);
+            DEBUG("conf->config_dir %s\n", conf->config_dir);
 
-                if ((ans == 'Y') || (ans == 'y')) {
-                    rc = updateNewRm(ctx, target_hostname, ssh_username, ssh_port, conf->config_dir);  // aru.c
-                    if (rc == PTS_SUCCESS) {
-                        printf("Save new reference manifest\n");
-                        // TODO UUID
-                    } else {
-                    }
-                } else if ((ans == 'N') || (ans == 'n')) {
-                    printf("keep current manifest\n");
+            if (ansIsYes) {
+                rc = updateNewRm(ctx, target_hostname, conf->config_dir);  // aru.c
+                if (rc == PTS_SUCCESS) {
+                    printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_SAVE_NEW_MANIFEST, "Save new reference manifest\n"));
+                    // TODO UUID
+                    retVal = RETVAL_OK_TRUSTED;
                 } else {
-                    printf("Bad answer %c, exit\n", ans);
-                    rc = -1;
-                    goto error;
+                    retVal = RETVAL_TARGET_ERROR;
                 }
+            } else if (ansIsNo) {
+                printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_KEEP_CURRENT_MANIFEST, "Keep current manifest\n"));
+                retVal = RETVAL_OK_PENDINGUPDATE;
+            } else {
+                ERROR("Bad answer %s, exit\n", ans);
+                retVal = RETVAL_GLOBAL_ERROR;
+                goto out_free;
             }
 
             // TODO validate new RM
             // TODO e.g. gen new RM by verifier and compare both
         } else if (rc == PTS_RULE_NOT_FOUND) {
-            // char ans;
-            printf("New reference manifest exist. if this is expected change, update the manifest by openpts -i -f \n");
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_RUN_OPENPTS,
+                "A new reference manifest exists. If this is expected, "
+                "please update the manifest with 'openpts -i -f'\n"));
+            retVal = RETVAL_NOTENROLLED;
         } else {
             DEBUG("no newrm\n");
+            retVal = RETVAL_OK_TRUSTED;
         }
 #else
         if (rc == PTS_RULE_NOT_FOUND) {
-            // char ans;
-            printf("New reference manifest exist. if this is expected change, update the manifest by openpts -i -f \n");
+            printf(NLS(MS_OPENPTS, OPENPTS_VERIFY_RUN_OPENPTS,
+                "A new reference manifest exists. If this is expected, "
+                "please update the manifest with 'openpts -i -f'\n"));
+            retVal = RETVAL_NOTENROLLED;
         }
 #endif
         break;
+    }
     case UPDATE:
         TODO("TBD\n");
+        retVal = RETVAL_GLOBAL_ERROR;
         break;
     default:
-        ERROR("Bad command?");
         usage();
+        retVal = RETVAL_GLOBAL_ERROR;
         break;
-    }
-    rc = 0;
+    }  // switch
 
- error:
- free:
-    if (target_conf_dir != NULL) free(target_conf_dir);
-    if (target_conf_filename != NULL) free(target_conf_filename);
+  out_free:
+    if (target_conf_dir != NULL) {
+        xfree(target_conf_dir);
+    }
+    if (target_conf_filename != NULL) {
+        xfree(target_conf_filename);
+    }
     if ((new_target == 1) && (target_conf != NULL)) {
         /* free new target conf */
-        freePtsConfig(target_conf);
+        /* freePtsConfig(target_conf); */
     }
     if (ctx != NULL) {
         ctx->target_conf = NULL;
         freePtsContext(ctx);
     }
 
-    freePtsConfig(conf);
+    if (target_hostname != NULL) {
+        xfree(target_hostname);
+    }
 
-    return rc;
+    /* WORK NEEDED: remove the circular dependency where conf (below) has a
+                    target list that points to target_conf (above), which has
+                    already been freed by this point and will get freed again
+                    in the following call. This is because freePtsConfig ->
+                    freeTargetList -> freePtsConfig. Ideally we should have one of
+                    the following:
+                    1. configs would be static class members instead of being
+                       dynamically allocated.
+                    2. set the NEVER_FREE_MEMORY macro, which ensures we never call
+                       free() because for short-lived programs that need little memory
+                       this has little benefit. it will all be freed on program
+                       exit anyway. */
+    /* freePtsConfig(conf); */
+
+    return retVal;
 }
index 0d4a8e5..72a2b1b 100644 (file)
@@ -42,6 +42,7 @@
 #include <string.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 /**
  * Free policy chain
@@ -55,7 +56,7 @@ int freePolicyChain(OPENPTS_POLICY *pol) {
         freePolicyChain(pol->next);
     }
 
-    free(pol);
+    xfree(pol);
 
     return PTS_SUCCESS;
 }
@@ -80,7 +81,8 @@ int loadPolicyFile(OPENPTS_CONTEXT *ctx, char * filename) {
     /* open */
 
     if ((fp = fopen(filename, "r")) == NULL) {
-        ERROR("File %s open was failed\n", filename);
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_POLICY_FILE_OPEN_FAILED,
+            "Failed to open policy file '%s'\n"), filename);
         return -1;
     }
 
@@ -104,7 +106,7 @@ int loadPolicyFile(OPENPTS_CONTEXT *ctx, char * filename) {
             DEBUG("%4d [%s]=[%s]\n", cnt, name, value);
 
             /* new  */
-            pol = malloc(sizeof(OPENPTS_POLICY));
+            pol = xmalloc(sizeof(OPENPTS_POLICY));
             if (pol == NULL) {
                 ERROR("no mem");
                 cnt = -1;  // return -1;
@@ -182,7 +184,7 @@ int checkPolicy(OPENPTS_CONTEXT *ctx) {
         /* status */
         if (prop == NULL) {
             /* no prop -> Unknown */
-            addReason(ctx, "[POLICY-L%03d] %s is missing",
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_POLICY_MISSING, "[POLICY-L%03d] %s is missing"),
                 pol->line,
                 pol->name);
             unknown++;
@@ -191,7 +193,11 @@ int checkPolicy(OPENPTS_CONTEXT *ctx) {
                 // hit
                 valid++;
             } else {
-                addReason(ctx, "[POLICY-L%03d] %s is %s, not %s",
+                int pcrIndex = -1;
+                if ( 0 == strncmp("tpm.quote.pcr.", pol->name, 14) ) {
+                    pcrIndex = atoi(&pol->name[14]);
+                }
+                addReason(ctx, pcrIndex, NLS(MS_OPENPTS, OPENPTS_POLICY_WRONG, "[POLICY-L%03d] %s is %s, not %s"),
                     pol->line,
                     pol->name, prop->value, pol->value);
                 invalid++;
@@ -226,19 +232,20 @@ int printPolicy(OPENPTS_CONTEXT *ctx) {
 
     pol = ctx->policy_start;
 
-    printf("   id ");  // id
-    printf("  name                  ");  // name
-    printf("  value(exp)  ");  // value
-    printf("  value(prop) ");  // value
-    printf("  status ");  // status
-    printf("\n");
-
-    printf("------");  // id
-    printf("-------------------------");  // name
-    printf("-------------");  // value
-    printf("-------------");  // value
-    printf("----------");  // value
-    printf("\n");
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_POLICY,
+           "  id "
+           "  name "
+           "  value(exp) "
+           "  value(prop) "
+           "  status "
+           "\n"));
+
+    OUTPUT("------");  // id
+    OUTPUT("-------------------------");  // name
+    OUTPUT("-------------");  // value
+    OUTPUT("-------------");  // value
+    OUTPUT("----------");  // value
+    OUTPUT("\n");
 
     while (pol != NULL) {
         /* look up prop */
@@ -259,11 +266,11 @@ int printPolicy(OPENPTS_CONTEXT *ctx) {
 
         /* print */
 #if 0
-        printf("%5d %-25s %-13s\n",
+        OUTPUT("%5d %-25s %-13s\n",
             pol->num,
             pol->name, pol->value);
 #else
-        printf("%5d %-35s %-28s %-28s %-10s\n",
+        OUTPUT("%5d %-35s %-28s %-28s %-10s\n",
             pol->num,
             pol->name, pol->value,
             proc_value, status);
@@ -271,7 +278,7 @@ int printPolicy(OPENPTS_CONTEXT *ctx) {
         pol = pol->next;
     }
 
-    printf("\n");
+    OUTPUT("\n");
 
     return 0;
 }
index bd62e64..c7e9347 100644 (file)
@@ -49,7 +49,6 @@
 #include <string.h>
 #include <stdarg.h> /* va_ */
 
-
 #include <openpts.h>
 
 /**
 OPENPTS_PROPERTY * newProperty(char *name, char *value) {
     OPENPTS_PROPERTY *prop;
 
-    prop = (OPENPTS_PROPERTY *) malloc(sizeof(OPENPTS_PROPERTY));
+    prop = (OPENPTS_PROPERTY *) xmalloc(sizeof(OPENPTS_PROPERTY));
     if (prop == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memset(prop, 0, sizeof(OPENPTS_PROPERTY));
 
-    prop->name = smalloc(name);
-    prop->value = smalloc(value);
+    prop->name = smalloc_assert(name);
+    prop->value = smalloc_assert(value);
 
     return prop;
 }
@@ -82,9 +80,9 @@ void freeProperty(OPENPTS_PROPERTY *prop) {
 
     // DEBUG("freeProperty() - free - name=%s, value=%s\n",prop->name, prop->value);
 
-    free(prop->name);
-    free(prop->value);
-    free(prop);
+    xfree(prop->name);
+    xfree(prop->value);
+    xfree(prop);
 }
 
 /**
@@ -119,24 +117,29 @@ int freePropertyChain(OPENPTS_PROPERTY *prop) {
 OPENPTS_PROPERTY* getProperty(OPENPTS_CONTEXT *ctx, char *name) {
     OPENPTS_PROPERTY *prop;
 
-    prop = ctx->prop_start;
-
-    // ERROR("getProperty - [%s]\n", name);
+    /* check */
+    if (name == NULL) {
+        ERROR("getProperty(NULL), bad call");
+        return NULL;
+    }
 
+    /* look for the prop with name */
+    prop = ctx->prop_start;
     while (prop != NULL) {
         // ERROR("getProperty - [%s] 1\n", prop->name);
+        if (prop->name == NULL) {
+            ERROR("getProperty(%s) fail, bad property entry exist", name);
+            return NULL;
+        }
+
         if (!strcmp(name, prop->name)) {
-            // HIT;
-            // ERROR("getProperty - HIT - [%s] [%s]\n", prop->name, prop->value);
+            // HIT
             return prop;
         }
-        // ERROR("getProperty - [%s] 2\n", prop->name);
+
         prop = (OPENPTS_PROPERTY *) prop->next;
-        // prop = NULL;
-        // ERROR("getProperty - 3\n");
     }
 
-    // ERROR("getProperty - MISS\n");
     return NULL;
 }
 
@@ -156,7 +159,6 @@ int addProperty(OPENPTS_CONTEXT *ctx, char *name, char *value) {
     /* malloc new prop */
     prop = newProperty(name, value);
     if (prop == NULL) {
-        ERROR("addProperty() - no memory\n");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -200,8 +202,8 @@ int setProperty(OPENPTS_CONTEXT *ctx, char *name, char *value) {
     } else {
         /* name hit? update the value */
         // DEBUG("updateProperty() - TBD\n");
-        free(hit->value);
-        hit->value = smalloc(value);
+        xfree(hit->value);
+        hit->value = smalloc_assert(value);
         // memcpy(hit->value, value, strlen(value) + 1); // TODO size
     }
 
@@ -222,18 +224,9 @@ int setEventProperty(OPENPTS_CONTEXT *ctx, char *name, char *value, OPENPTS_PCR_
     int rc = PTS_SUCCESS;
 
     /* check */
-    if (ctx == NULL) {
-        ERROR("ctx is NULL\n");
-        return PTS_INTERNAL_ERROR;
-    }
-    if (name == NULL) {
-        ERROR("name is NULL\n");
-        return PTS_INTERNAL_ERROR;
-    }
-    if (value == NULL) {
-        ERROR("value is NULL\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != ctx, "setEventProperty - ctx is NULL\n");
+    ASSERT(NULL != name, "setEventProperty - name is NULL\n");
+    ASSERT(NULL != value, "setEventProperty - value is NULL\n");
 
 
     // DEBUG("setEventProperty - [%s] [%s]\n", name, value);
@@ -282,11 +275,10 @@ int setEventProperty(OPENPTS_CONTEXT *ctx, char *name, char *value, OPENPTS_PCR_
         event = eventWrapper->event;
         str = snmalloc((char*)event->rgbEvent, event->ulEventLength);
         if (str == NULL) {
-            ERROR("no memory");
             return PTS_INTERNAL_ERROR;
         }
         setProperty(ctx, name, str);  // TODO 2011-02-03 SM implement
-        free(str);
+        xfree(str);
         // NULL
     } else if (!strcmp(value, "notexist")) {
         setProperty(ctx, name, value);  // TODO
@@ -317,18 +309,9 @@ int validateProperty(OPENPTS_CONTEXT *ctx, char *name, char *value, char *action
     int rc = OPENPTS_FSM_ERROR;
     OPENPTS_PROPERTY* prop;
 
-    if (ctx == NULL) {
-        ERROR("ctx is NULL\n");
-        return OPENPTS_FSM_ERROR;
-    }
-    if (name == NULL) {
-        ERROR("name is NULL\n");
-        return OPENPTS_FSM_ERROR;
-    }
-    if (value == NULL) {
-        ERROR("value is NULL\n");
-        return OPENPTS_FSM_ERROR;
-    }
+    ASSERT(NULL != ctx, "validateProperty - ctx is NULL\n");
+    ASSERT(NULL != name, "validateProperty - name is NULL\n");
+    ASSERT(NULL != value, "validateProperty - value is NULL\n");
 
     /* trim */
     // trim(value);
@@ -380,9 +363,9 @@ void printProperties(OPENPTS_CONTEXT *ctx) {
     int i = 0;
     prop = ctx->prop_start;
 
-    printf("Properties name-value\n");
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_PROPS, "Properties name-value\n"));
     while (prop != NULL) {
-        printf("%5d %s=%s\n", i, prop->name, prop->value);
+        OUTPUT("%5d %s=%s\n", i, prop->name, prop->value);
         prop = prop->next;
         i++;
     }
@@ -420,3 +403,14 @@ int saveProperties(OPENPTS_CONTEXT *ctx, char * filename) {
 
     return PTS_SUCCESS;
 }
+
+int addPropertiesFromConfig(OPENPTS_CONFIG *conf, OPENPTS_CONTEXT *ctx) {
+    /* additional properties from the pts config file */
+    if (conf->iml_maxcount > 0) {
+        char buf[32];
+        snprintf(buf, sizeof(buf), "%d", conf->iml_maxcount);
+        addProperty(ctx, "iml.ipl.maxcount", buf);
+        DEBUG("Added automatic property iml.ipl.maxcount=%d\n", conf->iml_maxcount);
+    }
+    return 0;
+}
index 3e4f73c..92d0c4d 100644 (file)
  *
  */
 
+#ifdef AIX
+#include <sys/lockf.h>
+#endif
+
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/un.h>
 #include <sys/socketvar.h>
 #include <errno.h>
+#include <fcntl.h>
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>
 #include <sys/stat.h>  // chmod
 
 #include <openpts.h>
+// #include <log.h>
 
 
-int verbose = 0; /**< DEBUG */
-static int terminate = 0;
-
-#define STDIN 0
-#define STDOUT 1
-
 int prop_num = 0;
 OPENPTS_PROPERTY *start = NULL;
 OPENPTS_PROPERTY *end = NULL;
@@ -66,10 +66,9 @@ OPENPTS_PROPERTY *end = NULL;
  */ 
 int collector2(OPENPTS_CONFIG *conf) {
     int rc;
+    int terminate = 0;
     OPENPTS_CONTEXT *ctx = NULL;
     PTS_IF_M_Attribute *read_tlv = NULL;
-    int count = 0;
-    int len;
 
     /* Init RMs */
     rc = getRmSetDir(conf);
@@ -84,62 +83,65 @@ int collector2(OPENPTS_CONFIG *conf) {
         DEBUG("collector() - getNewRmSetDir() was failed - never mind\n");
     }
 
-    /* syslog message */
-    INFO("start collector (System UUID=%s, RM UUID = %s, timeout=%d)\n",
-        conf->uuid->str, conf->rm_uuid->str, conf->ifm_timeout);
+
+    INFO("start collector (System UUID=%s, RM UUID = %s)\n",
+        conf->uuid->str, conf->rm_uuid->str);
 
     /* Collector <-> Verifier - handshake loop */
-    do {
-        INFO("open  IF-M PTS connection\n");
 
-        ctx = newPtsContext(conf);
+    ctx = newPtsContext(conf);
 
-        // TODO new ctx for the new connection
+    addPropertiesFromConfig(conf, ctx);
 
-        /* handshake loop */
-        for (;;) {
-            /* V->C request */
+    /* protocol loop */
+    while (!terminate) {
+        /* V->C request */
 
-            read_tlv = readPtsTlv(STDIN);  // ifm.c, malloc tlv
-            if (read_tlv == NULL) {
-                INFO("close IF-M PTS connection\n");
-                /* free current context */
-                freePtsContext(ctx);
-                sleep(1);
-                count++;
-                if (count >= conf->ifm_timeout) {  // 5sec
-                    terminate = 1;
-                    TODO("collector2 terminate\n");
-                }
-                break;
-            }
+        /* read() will block forever unless STDIN was explicitly set to
+           be non-blocking or we receive an interrupt. even then wrapRead() will
+           ignore EAGAIN and EINTR and keep attempting to call read(). the only way
+           this could fail is if the other end of the connection closed, in which case
+           we should exit. if timeouts are required then poll() or select() can be
+           used on blocking file descriptors to listen for input. */
+        read_tlv = readPtsTlv(STDIN_FILENO);  // ifm.c, malloc tlv
+        if (read_tlv == NULL) {
+            DEBUG("close IF-M PTS connection\n");
+            break;
+        }
 
-            /* check bad TLV */
-            if (read_tlv->type == 0)
-                break;
+        /* check bad TLV */
+        if (read_tlv->type == 0) {
+            ERROR("Bad TLV type received - quit");
+            break;
+        }
 
-            if (read_tlv->length > 0 && read_tlv->value == NULL)
-                break;
+        if (read_tlv->length > 0 && read_tlv->value == NULL) {
+            ERROR("Malformed TLV message (ghost body) - quit");
+            break;
+        }
 
-            INFO("IF-M read type = 0x%X, len %d\n",
+        INFO("IF-M read type = 0x%X, len %d\n",
                 read_tlv->type,
                 read_tlv->length);
 
-            /* C->V responces */
-            switch (read_tlv->type) {
+        /* C->V responces */
+        switch (read_tlv->type) {
             case OPENPTS_CAPABILITIES:
                 // TODO define CAPABILITIES structure
-                TODO("IF-M OPENPTS_CAPABILITIES\n");
+                DEBUG("IF-M OPENPTS_CAPABILITIES\n");
                 /* check the UUID */
                 if (read_tlv->length != sizeof(OPENPTS_IF_M_Capability)) {  // TODO use defined name
-                    ERROR("Bad PTS_CAPABILITIES, len = %d != 32\n", read_tlv->length);
+                    ERROR("Bad PTS_CAPABILITIES, len = %d != %d\n",
+                        read_tlv->length, sizeof(OPENPTS_IF_M_Capability));
+                    terminate = 1;
                 } else {
+                    // TODO copy
                     OPENPTS_IF_M_Capability *cap;
                     cap = (OPENPTS_IF_M_Capability *) read_tlv->value;
                     /* get version */
                     // TODO
                     /* get verifier's UUID */
-                    ctx->uuid = malloc(sizeof(PTS_UUID));
+                    ctx->uuid = xmalloc_assert(sizeof(PTS_UUID));
                     memcpy(ctx->uuid, &cap->platform_uuid, 16);
                     ctx->str_uuid = getStringOfUuid(ctx->uuid);
 
@@ -147,19 +149,20 @@ int collector2(OPENPTS_CONFIG *conf) {
                     INFO("verifier (UUID=%s)\n", ctx->str_uuid);
 
                     /* send PTS_CAPABILITIES msg. to verifier (=UUID) */
-                    len = writePtsTlv(ctx, STDOUT, OPENPTS_CAPABILITIES);
-                    if (len < 0) {
-                        ERROR("send OPENPTS_CAPABILITIES was failed\n");
+                    rc = writePtsTlv(ctx, STDOUT_FILENO, OPENPTS_CAPABILITIES);
+                    if (rc < 0) {
+                        ERROR("Send CAPABILITY answer failed - quit");
+                        terminate = 1;
                     }
-                    TODO("IF-M OPENPTS_CAPABILITIES rc=%d (0x%x)\n", rc, rc);
                 }
                 break;
 
             case DH_NONCE_PARAMETERS_REQUEST:
-                TODO("IF-M DH_NONCE_PARAMETERS_REQUEST\n");
+                DEBUG("IF-M DH_NONCE_PARAMETERS_REQUEST\n");
                 /* check */
                 if (read_tlv->length != 4) {
                     ERROR("Bad DH_NONCE_PARAMETERS_REQUEST, len = %d != 4\n", read_tlv->length);
+                    terminate = 1;
                 } else {
                     /* req -> res */
                     ctx->nonce->req->reserved      = read_tlv->value[0];
@@ -170,18 +173,20 @@ int collector2(OPENPTS_CONFIG *conf) {
                     rc = getDhResponce(ctx->nonce);
 
                     /* send responce */
-                    len = writePtsTlv(
-                            ctx, STDOUT, DH_NONCE_PARAMETORS_RESPONSE);
-                    if (len < 0) {
-                        ERROR("send DH_NONCE_PARAMETORS_RESPONSE was failed\n");
+                    rc = writePtsTlv(
+                            ctx, STDOUT_FILENO, DH_NONCE_PARAMETORS_RESPONSE);
+                    if (rc < 0) {
+                        ERROR("Send NONCE answer failed - quit");
+                        terminate = 1;
                     }
                 }
                 break;
             case DH_NONCE_FINISH:
-                TODO("IF-M DH_NONCE_FINISH\n");
+                DEBUG("IF-M DH_NONCE_FINISH\n");
                 /* check */
                 if (read_tlv->length != 152) {  // TODO  how to calc this size?
                     ERROR("Bad DH_NONCE_FINISH, len = %d != 152\n", read_tlv->length);
+                    terminate = 1;
                 } else {
                     /* finish  */
                     ctx->nonce->fin->reserved            = read_tlv->value[0];
@@ -190,14 +195,14 @@ int collector2(OPENPTS_CONFIG *conf) {
                     ctx->nonce->fin->selected_hash_alg   = (read_tlv->value[2]<<8) | read_tlv->value[3];
 
                     /* public */
-                    ctx->nonce->fin->dh_initiator_public = malloc(ctx->nonce->pubkey_length);
+                    ctx->nonce->fin->dh_initiator_public = xmalloc_assert(ctx->nonce->pubkey_length);
                     memcpy(
                         ctx->nonce->fin->dh_initiator_public,
                         &read_tlv->value[4],
                         ctx->nonce->pubkey_length);
 
                     /* nonce */
-                    ctx->nonce->fin->dh_initiator_nonce = malloc(ctx->nonce->fin->nonce_length);
+                    ctx->nonce->fin->dh_initiator_nonce = xmalloc_assert(ctx->nonce->fin->nonce_length);
                     memcpy(
                         ctx->nonce->fin->dh_initiator_nonce,
                         &read_tlv->value[4 + ctx->nonce->pubkey_length],
@@ -209,43 +214,47 @@ int collector2(OPENPTS_CONFIG *conf) {
                 }
                 break;
             case REQUEST_RIMM_SET:  // 5
-                TODO("IF-M REQUEST_RIMM_SET\n");
+                DEBUG("IF-M REQUEST_RIMM_SET\n");
                 /* check */
                 if (read_tlv->length != 0) {
                     ERROR("Bad REQUEST__RIMM_SET, len = %d != 0\n", read_tlv->length);
+                    terminate = 1;
                 } else {
-                    len = writePtsTlv(
-                            ctx, STDOUT, RIMM_SET);
-                    if (len < 0) {
-                        ERROR("send RIMM_SET was failed\n");
+                    rc = writePtsTlv(
+                            ctx, STDOUT_FILENO, RIMM_SET);
+                    if (rc < 0) {
+                        ERROR("Send RIMM_SET answer failed - quit");
+                        terminate = 1;
                     }
                 }
                 break;
             case REQUEST_NEW_RIMM_SET:
-                TODO("IF-M REQUEST_NEW_RIMM_SET\n");
+                DEBUG("IF-M REQUEST_NEW_RIMM_SET\n");
                 /* check */
                 if (read_tlv->length != 0) {
                     ERROR("Bad REQUEST_NEW_RIMM_SET, len = %d != 0\n", read_tlv->length);
+                    terminate = 1;
                 } else {
-                    len = writePtsTlv(
-                            ctx, STDOUT, NEW_RIMM_SET);
-                    if (len < 0) {
-                        ERROR("sendNEW_RIMM_SET was failed\n");
+                    rc = writePtsTlv(
+                            ctx, STDOUT_FILENO, NEW_RIMM_SET);
+                    if (rc < 0) {
+                        ERROR("Send NEW_RIMM_SET answer failed - quit");
+                        terminate = 1;
                     }
-                    TODO("IF-M REQUEST_NEW_RIMM_SET, len = %d\n", rc);
                 }
                 break;
             case REQUEST_INTEGRITY_REPORT:
-                TODO("IF-M REQUEST_INTEGRITY_REPORT\n");
+                DEBUG("IF-M REQUEST_INTEGRITY_REPORT\n");
                 /* check */
                 if (read_tlv->length != 0) {
                     ERROR("Bad REQUEST_INTEGRITY_REPORT, len = %d != 0\n", read_tlv->length);
+                    terminate = 1;
                 } else {
-                    len = writePtsTlv(ctx, STDOUT, INTEGRITY_REPORT);
-                    if (len < 0) {
-                        ERROR("send INTEGRITY_REPORT was failed\n");
+                    rc = writePtsTlv(ctx, STDOUT_FILENO, INTEGRITY_REPORT);
+                    if (rc < 0) {
+                        ERROR("Send INTEGRITY_REPORT answer failed - quit");
+                        terminate = 1;
                     }
-                    TODO("IF-M INTEGRITY_REPORT len=%d (0x%x)\n", rc, rc);
                 }
                 break;
             case VERIFICATION_RESULT:
@@ -260,10 +269,12 @@ int collector2(OPENPTS_CONFIG *conf) {
                 /* check */
                 if (read_tlv->length != 0) {
                     ERROR("Bad REQUEST_AIDE_DATABASE, len = %d != 0\n", read_tlv->length);
+                    terminate = 1;
                 } else {
-                    len = writePtsTlv(ctx, STDOUT, AIDE_DATABASE);
-                    if (len < 0) {
-                        ERROR("send AIDE_DATABASE was failed\n");
+                    rc = writePtsTlv(ctx, STDOUT_FILENO, AIDE_DATABASE);
+                    if (rc < 0) {
+                        ERROR("Send REQUEST_AIDE_DATABASE answer failed - quit");
+                        terminate = 1;
                     }
                 }
                 break;
@@ -272,10 +283,12 @@ int collector2(OPENPTS_CONFIG *conf) {
                 /* check */
                 if (read_tlv->length != 0) {
                     ERROR("Bad REQUEST_TPM_PUBKEY, len = %d != 0\n", read_tlv->length);
+                    terminate = 1;
                 } else {
-                    len = writePtsTlv(ctx, STDOUT, TPM_PUBKEY);  // ifm.c
-                    if (len < 0) {
-                        ERROR("send TPM_PUBKEY was failed\n");
+                    rc = writePtsTlv(ctx, STDOUT_FILENO, TPM_PUBKEY);  // ifm.c
+                    if (rc < 0) {
+                        ERROR("Send TPM_PUBKEY answer failed - quit");
+                        terminate = 1;
                     }
                 }
                 break;
@@ -283,13 +296,14 @@ int collector2(OPENPTS_CONFIG *conf) {
                 /* check */
                 if (read_tlv->length != 20) {
                     ERROR("Bad NONCE, len = %d != 20\n", read_tlv->length);
+                    terminate = 1;
                 } else {
                     /* set nonce */
                     ctx->nonce->nonce_length = 20;
                     if (ctx->nonce->nonce != NULL) {
-                        free(ctx->nonce->nonce);
+                        xfree(ctx->nonce->nonce);
                     }
-                    ctx->nonce->nonce = malloc(20);
+                    ctx->nonce->nonce = xmalloc_assert(20);
                     memcpy(ctx->nonce->nonce, read_tlv->value, 20);
                     DEBUG_IFM("nonce[%d] : \n", ctx->nonce->nonce_length);
                 }
@@ -302,31 +316,24 @@ int collector2(OPENPTS_CONFIG *conf) {
                 ERROR("PTS IF-M type 0x%08x is not supported\n", read_tlv->type);
                 INFO("send OPENPTS_ERROR msg to verifier, then terminate the conenction");
                 ctx->ifm_errno = PTS_UNRECOGNIZED_COMMAND;
-                if (ctx->ifm_strerror != NULL) free(ctx->ifm_strerror);
-                ctx->ifm_strerror = smalloc("Unknown message type");
-
-                len = writePtsTlv(ctx, STDOUT, OPENPTS_ERROR);  // ifm.c
-                if (len < 0) {
-                    ERROR("send OPENPTS_ERROR was failed\n");
+                if (ctx->ifm_strerror != NULL) {
+                    xfree(ctx->ifm_strerror);
                 }
+                ctx->ifm_strerror = smalloc_assert("Unknown message type");
+                rc = writePtsTlv(ctx, STDOUT_FILENO, OPENPTS_ERROR);  // ifm.c
                 terminate = 1;
                 break;
-            }  // switch case
+        }  // switch case
 
-            /* free TLV */
-            if (read_tlv != NULL) {
-                freePtsTlv(read_tlv);
-            }
-        }  // GET loop
-        /* out */
-        /* free TLV for break out */
+        /* free TLV */
         if (read_tlv != NULL) {
             freePtsTlv(read_tlv);
         }
-    } while (terminate == 0);
+    }
+
+    freePtsContext(ctx);
 
-  // err:
-    return (-1);
+    return 0;
 }
 
 
@@ -334,33 +341,31 @@ int collector2(OPENPTS_CONFIG *conf) {
  * Usage
  */
 void usage(void) {
-    fprintf(stderr, NLS(1,  1, "OpenPTS Collector\n\n"));
-    fprintf(stderr, NLS(1,  2, "Usage: ptsc [options] [command]\n\n"));
-    fprintf(stderr, NLS(1,  3, "Commands: (forgrand)\n"));
-    fprintf(stderr, NLS(1,  4, "  -i                    Initialize PTS collector\n"));
-    fprintf(stderr, NLS(1,  5, "  -t                    Self test (attestation)\n"));
-    fprintf(stderr, NLS(1,  6, "  -s                    Startup (selftest + timestamp)\n"));
-    fprintf(stderr, NLS(1,  7, "  -u                    Update the RM\n"));
+    fprintf(stderr, NLS(MS_OPENPTS,  OPENPTS_COLLECTOR_USAGE_1, "OpenPTS Collector\n\n"
+                    "Usage: ptsc [options] [command]\n\n"
+                    "Commands: (foreground)\n"
+                    "  -i                    Initialize PTS collector\n"
+                    "  -t                    Self test (attestation)\n"
+                    "  -s                    Startup (selftest + timestamp)\n"
+                    "  -u                    Update the RM\n"
+                    "  -e                    Clear PTS collector\n"));
 #ifdef CONFIG_AUTO_RM_UPDATE
-    fprintf(stderr, NLS(1,  8, "  -U                    Update the RM (auto)\n"));
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_USAGE_2,
+                    "  -U                    Update the RM (auto)\n"));
 #endif
-    fprintf(stderr, NLS(1,  9, "  -D                    Display the configuration\n"));
-    fprintf(stderr, NLS(1, 10, "  -m                    IF-M mode\n"));
-    fprintf(stderr, "\n");
-    fprintf(stderr, NLS(1, 11, "Miscellaneous:\n"));
-    fprintf(stderr, NLS(1, 12, "  -h                    Show this help message\n"));
-    fprintf(stderr, NLS(1, 13, "  -v                    Verbose mode. Multiple -v options increase the verbosity.\n"));
-    fprintf(stderr, "\n");
-    fprintf(stderr, NLS(1, 14, "Options:\n"));
-    fprintf(stderr, NLS(1, 15, "  -c configfile         Set configuration file. defalt is %s\n"), PTSC_CONFIG_FILE);
-    // fprintf(stderr, NLS(1, 14, "  -f                    foreground, run in the foreground."));
-    // fprintf(stderr, NLS(1, 15, "                        Logging goes to stderr " "instead of syslog.\n"));
-    fprintf(stderr, NLS(1, 16, "  -P name=value         Set properties.\n"));
-    fprintf(stderr, NLS(1, 17, "  -R                    Remove RMs\n"));
-    fprintf(stderr, NLS(1, 18, "  -z                    Use the SRK secret to all zeros (20 bytes of zeros)"));
-    // fprintf(stderr, "  -d dirname            Debug\n");
-
-    fprintf(stderr, "\n");
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_USAGE_3,
+                    "  -D                    Display the configuration\n"
+                    "  -m                    IF-M mode\n"
+                    "\n"
+                    "Miscellaneous:\n"
+                    "  -h                    Show this help message\n"
+                    "  -v                    Verbose mode. Multiple -v options increase the verbosity.\n"
+                    "\n"
+                    "Options:\n"
+                    "  -c configfile         Set configuration file. defalt is %s\n"
+                    "  -P name=value         Set properties.\n"
+                    "  -R                    Remove RMs\n"
+                    "  -z                    Set the SRK secret to all zeros (20 bytes of zeros)\n"), PTSC_CONFIG_FILE);
 }
 
 enum COMMAND {
@@ -370,6 +375,7 @@ enum COMMAND {
     COMMAND_SELFTEST,
     COMMAND_UPDATE,
     COMMAND_STARTUP,
+    COMMAND_CLEAR,
 #ifdef CONFIG_AUTO_RM_UPDATE
     COMMAND_AUTO_UPDATE,
 #endif
@@ -393,37 +399,130 @@ OPENPTS_PROPERTY *getPropertyFromArg(char *arg) {
         prop = newProperty(name, value);
         return prop;
     } else {
-        fprintf(stderr, "bad property %s\n", arg);
+        ERROR("bad property %s\n", arg);
         return NULL;
     }
 }
 
+#ifdef AIX
+#define LOCK_DIR    "/var/ptsc/"
+#else  // LINUX
+#define LOCK_DIR    "/var/lib/openpts/"
+#endif
+#define LOCK_FILE    LOCK_DIR "ptsc.lock"
+
+void ptsc_lock(void) {
+    int fd, oldmask, oldgrp = 0;
+    struct group *grpent = NULL;
+    struct group grp;
+    char *buf = NULL;
+    size_t buf_len;
+    int rc;
+
+    if (geteuid() == 0) {
+        // grpent = getgrnam(PTSC_GROUP_NAME);
+        // if (grpent) {
+        //     oldgrp = getegid();
+        //     setegid(grpent->gr_gid);
+        // }
+        buf_len = sysconf(_SC_GETGR_R_SIZE_MAX);
+        if (buf_len < 0) {
+            buf_len = 4096;
+        }
+        buf = xmalloc(buf_len);
+        if (buf == NULL) {
+            ERROR("no memory");
+            exit(1);
+        }
+
+        rc = getgrnam_r(PTSC_GROUP_NAME, &grp, buf, buf_len, &grpent);
+        if (rc != 0) {
+            // TODO
+            exit(1);
+        }
+        if (grpent == NULL) {
+            // TODO
+            exit(1);
+        }
+        oldgrp = getegid();
+        setegid(grp.gr_gid);
+    }
+
+    oldmask = umask(0);
+    if (mkdir(LOCK_DIR, 0775) < 0 && errno != EEXIST) {
+        perror(LOCK_DIR);
+        exit(1);
+    }
+    if (grpent) {
+        chmod(LOCK_DIR, 02775);
+        setegid(oldgrp);
+    }
+    fd = open(LOCK_FILE, O_RDWR | O_CREAT | O_TRUNC, 0660);
+    if (fd < 0) {
+        perror(LOCK_FILE);
+        exit(1);
+    }
+    umask(oldmask);
+    if (lockf(fd, F_LOCK, 0) < 0) {
+        perror(LOCK_FILE);
+        exit(1);
+    }
+
+    if (buf != NULL) xfree(buf);
+}
 
 static int preparePriv() {
-    int rc = 0;
-    struct group *ptsc_grp;
+    int rc = PTS_SUCCESS;
+    struct group *ptsc_grp = NULL;
+    struct group grp;
+    char *buf = NULL;
+    size_t buf_len;
 
 #if 0
     /* check UID */
-    if ((ptscd_pwd = getpwnam(PTSCD_USER_NAME)) == NULL) {
+    if ((ptscd_pwd = getpwnam_r(PTSCD_USER_NAME)) == NULL) {
         ERROR("Looking up for user %s", PTSCD_USER_NAME);
         return PTS_FATAL;
     }
 #endif
 
     /* check GID */
-    ptsc_grp = getgrnam(PTSC_GROUP_NAME);  // TODO use getgrnam_r
-    if (ptsc_grp == NULL) {
-        ERROR("Looking up for group %s", PTSC_GROUP_NAME);
+    // ptsc_grp = getgrnam(PTSC_GROUP_NAME);  // TODO use getgrnam_r
+    // if (ptsc_grp == NULL) {
+    //     ERROR("Looking up for group (name=%s) fail", PTSC_GROUP_NAME);
+    //     return PTS_FATAL;
+    // }
+    buf_len = sysconf(_SC_GETGR_R_SIZE_MAX);
+    if (buf_len < 0) {
+        buf_len = 4096;
+    }
+    buf = xmalloc(buf_len);
+    if (buf == NULL) {
+        ERROR("no memory");
         return PTS_FATAL;
     }
 
+    rc = getgrnam_r(PTSC_GROUP_NAME, &grp, buf, buf_len, &ptsc_grp);
+    if (rc != 0) {
+        ERROR("getgrnam_r");
+        rc = PTS_FATAL;
+        goto free;
+    }
+    if (ptsc_grp == NULL) {
+        ERROR("ptsc_grp == NULL");
+        rc = PTS_FATAL;
+        goto free;
+    }
+
     /* set GID */
-    rc = setgid(ptsc_grp->gr_gid);
+    // rc = setgid(ptsc_grp->gr_gid);
+    rc = setgid(grp.gr_gid);
     if (rc < 0) {
         // TODO do not need for IF-M access (read only)
-        ERROR("Switching group fail. %s\n", strerror(errno));
-        return PTS_FATAL;
+        ERROR("Switching group (gid=%d) fail. %s\n", grp.gr_gid, strerror(errno));
+        // TODO 20110927 FAIL
+        rc = PTS_FATAL;
+        goto free;
     }
 
 #if 0
@@ -434,8 +533,10 @@ static int preparePriv() {
 #endif
 
     /*  */
+  free:
+    if (buf != NULL) xfree(buf);
 
-    return PTS_SUCCESS;
+    return rc;
 }
 
 /**
@@ -444,23 +545,49 @@ static int preparePriv() {
  * flag 0:read, 1:read/write
  */
 static int chmodDir(char *dirpath, int flag) {
-    int rc;
+    int rc = PTS_SUCCESS;
     struct group *ptsc_grp;
+    struct group grp;
+    char *buf = NULL;
+    size_t buf_len;
+
 
     /* check GID */
-    ptsc_grp = getgrnam(PTSC_GROUP_NAME);  // TODO use getgrnam_r
-    if (ptsc_grp == NULL) {
-        ERROR("Looking up for group %s", PTSC_GROUP_NAME);
+    // ptsc_grp = getgrnam(PTSC_GROUP_NAME);  // TODO use getgrnam_r
+    // if (ptsc_grp == NULL) {
+    //     ERROR("Looking up for group %s", PTSC_GROUP_NAME);
+    //     return PTS_FATAL;
+    // }
+    buf_len = sysconf(_SC_GETGR_R_SIZE_MAX);
+    if (buf_len < 0) {
+        buf_len = 4096;
+    }
+    buf = xmalloc(buf_len);
+    if (buf == NULL) {
+        ERROR("no memory");
         return PTS_FATAL;
     }
 
+    rc = getgrnam_r(PTSC_GROUP_NAME, &grp, buf, buf_len, &ptsc_grp);
+    if (rc != 0) {
+        ERROR("getgrnam_r");
+        rc = PTS_FATAL;
+        goto free;
+    }
+    if (ptsc_grp == NULL) {
+        ERROR("ptsc_grp == NULL");
+        rc = PTS_FATAL;
+        goto free;
+    }
+
     /* chgep */
     rc = chown(
             dirpath,
             -1,
             ptsc_grp->gr_gid);
     if (rc <0) {
-        return PTS_FATAL;
+        rc = PTS_FATAL;
+        goto free;
     }
 
     if (flag == 0) {
@@ -469,7 +596,8 @@ static int chmodDir(char *dirpath, int flag) {
                 S_IRUSR | S_IWUSR | S_IXUSR |
                 S_IRGRP | S_IXGRP);
         if (rc <0) {
-            return PTS_FATAL;
+            rc = PTS_FATAL;
+            goto free;
         }
     } else {  // write
         rc = chmod(
@@ -477,10 +605,14 @@ static int chmodDir(char *dirpath, int flag) {
                 S_IRUSR | S_IWUSR | S_IXUSR |
                 S_IRGRP | S_IWGRP | S_IXGRP);
         if (rc <0) {
-            return PTS_FATAL;
+            rc = PTS_FATAL;
+            goto free;
         }
     }
-    return PTS_SUCCESS;
+
+  free:
+    if (buf != NULL) xfree(buf);
+    return rc;
 }
 
 
@@ -489,31 +621,22 @@ static int chmodDir(char *dirpath, int flag) {
  */
 int main(int argc, char *argv[]) {
     int rc;
-    int debug = 0;
     OPENPTS_CONFIG *conf = NULL;
     char *config_filename = NULL;
     int command = COMMAND_STATUS;
     int c;
+    int force = 0;
 #ifdef CONFIG_AUTO_RM_UPDATE
     int remove = 0;
 #endif
+    // extern int logLocation;
+    // void setLogLocation(int ll);
 
     /* properties by cmdline  */
     OPENPTS_PROPERTY *prop;
 
-#ifdef ENABLE_NLS
-#ifdef HAVE_CATGETS
-    /* catgets */
-    // nl_catd catd;
-    catd = catopen("ptscd", 0);
-#else
-    /* gettext */
-    setlocale(LC_ALL, "");
-    bindtextdomain(PACKAGE, LOCALEDIR);
-    textdomain(PACKAGE);
-#endif
-#endif
-
+#if 0
+    initCatalog();
 
     // TODO chgrp
     rc = preparePriv();
@@ -521,15 +644,15 @@ int main(int argc, char *argv[]) {
         ERROR("preparePriv fail\n");
     }
 
-
     conf = newPtsConfig();
     if (conf == NULL) {
         ERROR("internal error\n");  // TODO(munetoh)
         return -1;
     }
+#endif
 
     /* command option */
-    while ((c = getopt(argc, argv, "ic:uUDtsmvP:Rzh")) != EOF) {
+    while ((c = getopt(argc, argv, "ic:uUefDtsmvP:Rzh")) != EOF) {
         switch (c) {
         case 'i':
             command = COMMAND_INIT;
@@ -551,15 +674,26 @@ int main(int argc, char *argv[]) {
         case 's':
             command = COMMAND_STARTUP;
             break;
+        case 'e':
+            command = COMMAND_CLEAR;
+            break;
+        case 'f':
+            force = 1;
+            break;
         case 'm':
             command = COMMAND_IFM;
-            setenv("OPENPTS_SYSLOG", "1", 1);
+            /* not everything should go to syslog - on some systems
+               this could go to a log file - let default behaviour
+               in log.c decide this */
+            // setLogLocation(OPENPTS_LOG_SYSLOG, NULL);
+            // OK setLogLocation(OPENPTS_LOG_CONSOLE, NULL);  // OK
+            // setLogLocation(OPENPTS_LOG_FILE, "/var/log/ptsc.log");  // OK call this before any out
             break;
         case 'c':
             config_filename = optarg;
             break;
         case 'v':
-            debug++;
+            incVerbosity();
             break;
         case 'R':
 #ifdef CONFIG_AUTO_RM_UPDATE
@@ -571,16 +705,21 @@ int main(int argc, char *argv[]) {
             break;
         case 'P':
             prop = getPropertyFromArg(optarg);
-            if (start == NULL) {
-                start = prop;
-                end = prop;
-                prop->next = NULL;
+            if (prop != NULL) {
+                if (start == NULL) {
+                    start = prop;
+                    end = prop;
+                    prop->next = NULL;
+                } else {
+                    end->next = prop;
+                    end = prop;
+                    prop->next = NULL;
+                }
+                prop_num++;
             } else {
-                end->next = prop;
-                end = prop;
-                prop->next = NULL;
+                usage();
+                return -1;
             }
-            prop_num++;
             break;
         case 'h':
             /* help */
@@ -593,34 +732,57 @@ int main(int argc, char *argv[]) {
     argc -= optind;
     argv += optind;
 
+    if (command == COMMAND_IFM) {
+        setLogLocation(OPENPTS_LOG_SYSLOG, NULL);
+    } else {
+        setLogLocation(OPENPTS_LOG_CONSOLE, NULL);
+    }
+
+    initCatalog();
+
+    // TODO chgrp
+    rc = preparePriv();
+    if (rc != PTS_SUCCESS) {
+        ERROR("preparePriv fail\n");
+    }
+
+    conf = newPtsConfig();
+    if (conf == NULL) {
+        ERROR("internal error\n");  // TODO(munetoh)
+        return -1;
+    }
+
 
     /* DEBUG level, 1,2,3 */
-    if (debug > 2) {
-        verbose = DEBUG_FLAG | DEBUG_FSM_FLAG | DEBUG_IFM_FLAG;
-        INFO("verbose mode 3");
-    } else if (debug > 1) {
-        verbose = DEBUG_FLAG | DEBUG_IFM_FLAG;
-        INFO("verbose mode 2");
-    } else if (debug > 0) {
-        verbose = DEBUG_FLAG;
-        INFO("verbose mode 1");
+#ifdef OPENPTS_DEBUG
+    setDebugFlags(DEBUG_FLAG | DEBUG_FSM_FLAG | DEBUG_IFM_FLAG);
+#else
+    /* set the DEBUG level, 1,2,3 */
+    if (getVerbosity() > 2) {
+        setDebugFlags(DEBUG_FLAG | DEBUG_IFM_FLAG | DEBUG_FSM_FLAG | DEBUG_CAL_FLAG );
+    } else if (getVerbosity() > 1) {
+        setDebugFlags(DEBUG_FLAG | DEBUG_IFM_FLAG);
+    } else if (getVerbosity() > 0) {
+        setDebugFlags(DEBUG_FLAG);
     }
+#endif
+
+    DEBUG("VERBOSITY (%d), DEBUG mode (0x%x)\n", getVerbosity(), getDebugFlags());
 
-    // verbose = DEBUG_FLAG | DEBUG_IFM_FLAG;
+    ptsc_lock();
 
     /* load config */
     if (config_filename == NULL) {
-        DEBUG("config file               : %s\n", PTSC_CONFIG_FILE);
+        // this goto stdout and bad with "-m"
+        // VERBOSE(1, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CONFIG_FILE, "Config file: %s\n"), PTSC_CONFIG_FILE);
         rc = readPtsConfig(conf, PTSC_CONFIG_FILE);
         if (rc != PTS_SUCCESS) {
-            ERROR("read config file, '%s' was failed - abort\n", PTSC_CONFIG_FILE);
             goto free;
         }
     } else {
-        DEBUG("config file               : %s\n", config_filename);
+        // VERBOSE(1, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CONFIG_FILE, "Config file: %s\n"), config_filename);
         rc = readPtsConfig(conf, config_filename);
         if (rc != PTS_SUCCESS) {
-            ERROR("read config file, '%s' was failed - abort\n", config_filename);
             goto free;
         }
     }
@@ -628,32 +790,49 @@ int main(int argc, char *argv[]) {
     /* check dir */
     // TODO root only
 
-    /* check IR dir */
-    if (checkDir(conf->ir_dir) != PTS_SUCCESS) {
-        rc = makeDir(conf->ir_dir);
-        if (rc != PTS_SUCCESS) {
-            ERROR("Can not create the dir to store IR, %s\n", conf->ir_dir);
-            goto free;
-        }
-        rc = chmodDir(conf->ir_dir, 1);
-        if (rc != PTS_SUCCESS) {
-            ERROR("Can not create the dir to store IR, %s\n", conf->ir_dir);
-            goto free;
+    /* only do this when needed */
+    if (command != COMMAND_STATUS) {
+        /* check IR dir */
+        if (checkDir(conf->ir_dir) != PTS_SUCCESS) {
+            rc = makeDir(conf->ir_dir);
+            if (rc != PTS_SUCCESS) {
+                ERROR("Can not create the dir to store IR, %s\n", conf->ir_dir);
+                goto free;
+            }
+            rc = chmodDir(conf->ir_dir, 1);
+            if (rc != PTS_SUCCESS) {
+                ERROR("Can not create the dir to store IR, %s\n", conf->ir_dir);
+                goto free;
+            }
         }
     }
 
-    /* initialize the  collector */
+    /* initialize the PTS collector */
     if (command == COMMAND_INIT) {
-        DEBUG("Initialize Reference Manifest\n");
+        VERBOSE(1, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_INIT_RM, "Initializing Reference Manifest\n"));
         rc = init(conf, prop_num, start, end);
         /* Exit */
         goto free;
     }
 
+    /* Clear the PTS collector */
+    if (command == COMMAND_CLEAR) {
+        VERBOSE(1, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_CLEAR, "Clear PTS collector\n"));
+        rc = clear(conf, force);
+        /* Exit */
+        goto free;
+    }
+
+
     /* RM UUID */
     rc = readOpenptsUuidFile(conf->rm_uuid);
     if (rc != PTS_SUCCESS) {
-        ERROR("read RM UUID file %s was failed, initialize ptscd first\n", conf->rm_uuid->filename);
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_FAILED_READ_RM_UUID,
+               "Failed to read the Reference Manifest UUID file '%s':\n"
+               "Please ensure on the target that:\n"
+               "  * ptsc has been initialized (ptsc -i)\n"
+               "  * you (uid==%d) are allowed to attest (i.e. a member of group '%s')"),
+               conf->rm_uuid->filename, getuid(), PTSC_GROUP_NAME);
         goto free;
     } else {
         DEBUG("conf->str_rm_uuid         : %s\n", conf->rm_uuid->str);
@@ -671,10 +850,12 @@ int main(int argc, char *argv[]) {
     /* load RSA PUB key */
     // TODO single key => multiple keys?
 #ifdef CONFIG_NO_TSS
-        TODO("CONFIG_NO_TSS, no TPM_PUBKEY\n");
-        conf->pubkey_length = 0;
-        conf->pubkey = NULL;
+    TODO("CONFIG_NO_TSS, no TPM_PUBKEY\n");
+    conf->pubkey_length = 0;
+    conf->pubkey = NULL;
 #else
+    /* only do this when needed */
+    if (command != COMMAND_STATUS) {
         /* get PUBKEY */
         rc = getTssPubKey(
                 conf->uuid->uuid,
@@ -687,7 +868,11 @@ int main(int argc, char *argv[]) {
         if (rc != TSS_SUCCESS) {
             ERROR("getTssPubKey() fail rc=0x%x srk password mode=%d, key =%s\n",
                 rc, conf->srk_password_mode, conf->uuid->str);
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE,
+                "TSS communications failure. Is tcsd running?\n"));
+            goto free;
         }
+    }
 #endif
 
     /* run */
@@ -695,11 +880,12 @@ int main(int argc, char *argv[]) {
 #ifdef CONFIG_AUTO_RM_UPDATE
         case COMMAND_AUTO_UPDATE:
             /* update by command, but HUP is better */
-            DEBUG("Update Reference Manifest\n");
+            VERBOSE(1, "Updating Reference Manifest\n");
+            //addDebugFlags(DEBUG_CAL_FLAG);
             /* update RMs */
             rc = update(conf, prop_num, start, end, remove);
             if (rc != PTS_SUCCESS) {
-                printf("update was fail\n");
+                ERROR("update was fail\n");
             }
             break;
 #endif
@@ -709,40 +895,40 @@ int main(int argc, char *argv[]) {
         case COMMAND_SELFTEST:
             rc = selftest(conf, prop_num, start, end);
             if (rc == OPENPTS_SELFTEST_SUCCESS) {
-                printf("selftest - OK\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_SUCCESS, "selftest - OK\n"));
             } else if (rc == OPENPTS_SELFTEST_RENEWED) {
-                printf("selftest - Renewed\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_RENEWED, "selftest - Renewed\n"));
             } else if (rc == OPENPTS_SELFTEST_FALLBACK) {
-                printf("selftest -> fallback - TBD\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_FALLBACK, "selftest - fallback\n"));
             } else if (rc == OPENPTS_SELFTEST_FAILED) {
-                printf("selftest -> fail\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_FAIL, "selftest - fail\n"));
             } else {
-                printf("TBD\n");
+                ERROR("TBD\n");
             }
             break;
         case COMMAND_STARTUP:
             rc = selftest(conf, prop_num, start, end);
             if (rc == OPENPTS_SELFTEST_SUCCESS) {
-                INFO("selftest - OK\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_SUCCESS, "selftest - OK\n"));
                 /* timestamp */
                 extendEvCollectorStart(conf);  // collector.c
             } else if (rc == OPENPTS_SELFTEST_RENEWED) {
-                INFO("selftest - Renewed\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_RENEWED, "selftest - Renewed\n"));
                 /* timestamp */
                 extendEvCollectorStart(conf);
             } else if (rc == OPENPTS_SELFTEST_FALLBACK) {
-                INFO("selftest -> fallback - TBD\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_FALLBACK, "selftest - fallback\n"));
                 /* timestamp */
                 extendEvCollectorStart(conf);
             } else if (rc == OPENPTS_SELFTEST_FAILED) {
-                INFO("selftest -> fail\n");
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_FAIL, "selftest - fail\n"));
                 if (conf->autoupdate == 1) {
-                    TODO("selftest was failed, Try to generate new manifest\n");
+                    ERROR("selftest failed, trying to generate a new manifest\n");
                     /* del RM_UUID */
                     conf->rm_uuid->status = OPENPTS_UUID_FILENAME_ONLY;
                     if (conf->rm_uuid->uuid != NULL) freeUuid(conf->rm_uuid->uuid);
-                    if (conf->rm_uuid->str != NULL) free(conf->rm_uuid->str);
-                    if (conf->rm_uuid->time != NULL) free(conf->rm_uuid->time);
+                    if (conf->rm_uuid->str != NULL) xfree(conf->rm_uuid->str);
+                    if (conf->rm_uuid->time != NULL) xfree(conf->rm_uuid->time);
                     conf->rm_uuid->uuid = NULL;
                     conf->rm_uuid->str = NULL;
                     conf->rm_uuid->time = NULL;
@@ -750,31 +936,34 @@ int main(int argc, char *argv[]) {
                     /* gen new RM_UUID and RM */
                     rc = newrm(conf, prop_num, start, end);
                     if (rc != PTS_SUCCESS) {
-                        ERROR("newrm() fail\n");
+                        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_UPDATE_RM_FAIL,
+                            "Failed to generated a reference manifest\n"));
                         goto free;
                     }
                     rc = selftest(conf, prop_num, start, end);
                     if (rc == OPENPTS_SELFTEST_SUCCESS) {
-                        DEBUG("selftest - OK\n");
-                        INFO("selftest was faild, new manifests has been generated\n");
+                        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_SUCCESS, "selftest - OK\n"));
+                        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_UPDATE_RM_SUCCESS,
+                            "Successfully generated the reference manifest\n"));
                     } else if (rc == OPENPTS_SELFTEST_RENEWED) {
-                        DEBUG("selftest - Renewed\n");
+                        OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_RENEWED, "selftest - Renewed\n"));
                     } else {
-                        TODO("TBD\n");
+                        ERROR("TBD\n");
                     }
                 } else {
-                    INFO("selftest was faild, but keep existing manifests\n");
+                    OUTPUT(NLS(MS_OPENPTS, OPENPTS_COLLECTOR_UPDATE_RM_WONT,
+                        "selftest failed, keeping existing manifests as requested by configuration\n"));
                 }
             } else {
-                INFO("TBD\n");
+                ERROR("TBD\n");
             }
             break;
         case COMMAND_UPDATE:
             /* del RM_UUID */
             conf->rm_uuid->status = OPENPTS_UUID_FILENAME_ONLY;
             if (conf->rm_uuid->uuid != NULL) freeUuid(conf->rm_uuid->uuid);
-            if (conf->rm_uuid->str != NULL) free(conf->rm_uuid->str);
-            if (conf->rm_uuid->time != NULL) free(conf->rm_uuid->time);
+            if (conf->rm_uuid->str != NULL) xfree(conf->rm_uuid->str);
+            if (conf->rm_uuid->time != NULL) xfree(conf->rm_uuid->time);
             conf->rm_uuid->uuid = NULL;
             conf->rm_uuid->str = NULL;
             conf->rm_uuid->time = NULL;
@@ -789,7 +978,8 @@ int main(int argc, char *argv[]) {
             /* self test */
             rc = selftest(conf, prop_num, start, end);
             if (rc == OPENPTS_SELFTEST_SUCCESS) {
-                INFO("manifest generation - success\n");
+                VERBOSE(1, NLS(MS_OPENPTS, OPENPTS_COLLECTOR_UPDATE_RM_SUCCESS,
+                    "Successfully generated the reference manifest\n"));
             } else if (rc == OPENPTS_SELFTEST_RENEWED) {
                 TODO("TBD\n");
             } else {
@@ -805,7 +995,7 @@ int main(int argc, char *argv[]) {
             break;
     }
 
 free:
+ free:
     freePtsConfig(conf);
 
     return rc;
index 866fdd3..7d732d9 100644 (file)
@@ -38,8 +38,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <stdarg.h> /* va_ */
-
+#include <stdarg.h>  /* va_ */
 
 #include <openpts.h>
 
@@ -52,8 +51,8 @@ void freeReason(OPENPTS_REASON *reason) {
         return;
     }
 
-    free(reason->message);
-    free(reason);
+    xfree(reason->message);
+    xfree(reason);
 
     return;  // PTS_SUCCESS;
 }
@@ -78,7 +77,7 @@ int freeReasonChain(OPENPTS_REASON *reason) {
 /**
  * add reason
  */
-int addReason_old(OPENPTS_CONTEXT *ctx, char *message) {
+int addReason_old(OPENPTS_CONTEXT *ctx, int pcr, char *message) {
     OPENPTS_REASON *start;
     OPENPTS_REASON *end;
     OPENPTS_REASON *reason;
@@ -91,7 +90,7 @@ int addReason_old(OPENPTS_CONTEXT *ctx, char *message) {
     start = ctx->reason_start;
     end   = ctx->reason_end;
 
-    reason = (OPENPTS_REASON *) malloc(sizeof(OPENPTS_REASON));
+    reason = (OPENPTS_REASON *) xmalloc(sizeof(OPENPTS_REASON));
     if (reason == NULL) {
         ERROR("");
         return -1;
@@ -111,8 +110,8 @@ int addReason_old(OPENPTS_CONTEXT *ctx, char *message) {
         ctx->reason_end = reason;
         reason->next = NULL;
     }
-
-    reason->message = malloc(len +1);
+    reason->pcr = pcr;
+    reason->message = xmalloc(len +1);
     memcpy(reason->message, message, len);
     reason->message[len] = 0;
     ctx->reason_count++;
@@ -126,39 +125,62 @@ int addReason_old(OPENPTS_CONTEXT *ctx, char *message) {
  * addReason with format
  */
 #define MAX_REASON_SIZE 2048
-int addReason(OPENPTS_CONTEXT *ctx, const char *format, ...) {
+int addReason(OPENPTS_CONTEXT *ctx, int pcr, const char *format, ...) {
     char buf[MAX_REASON_SIZE +1];  // TODO size
     int rc;
     va_list list;
-
     va_start(list, format);
 
     vsnprintf(buf, MAX_REASON_SIZE, format, list);
-    // DEBUG("buf %s\n", buf);
 
-    va_end(list);
-
-    rc = addReason_old(ctx, (char *)buf);
+    rc = addReason_old(ctx, pcr, (char *)buf);
 
     return rc;
 }
 
+#ifdef AIX_TARGET
+char *reason_pcr_hints[] = {
+    "IBM Partition Firmware Images",
+    "Basic Partition Configuration (e.g. CPUs, memory)",
+    "Third-party Adapter Firmware",
+    "Partition Device Tree",
+    "OS Boot Image",
+    "OS Boot Info (e.g. boot device, or firmware prompt)",
+    NULL, /* PCR6 Unused */
+    NULL, /* PCR7 Unused */
+    NULL, /* PCR8 Unused */
+    NULL, /* PCR9 Unused */
+    "Trusted Execution Database"
+};
+#else
+char *reason_pcr_hints[] = {
+    NULL
+};
+#endif
 
 /**
  * print Reason
  *
  */
-void printReason(OPENPTS_CONTEXT *ctx) {
+void printReason(OPENPTS_CONTEXT *ctx, int print_pcr_hints) {
     OPENPTS_REASON *reason;
-    int i = 0;
+    unsigned int i = 0, pcrmask = 0;
     reason = ctx->reason_start;
 
-    printf("Reasons\n");
     while (reason != NULL) {
-        printf("%5d %s\n", i, reason->message);
+    if (reason->pcr >= 0)
+        pcrmask |= 1 << reason->pcr;
+        OUTPUT("%5d %s\n", i, reason->message);
         reason = reason->next;
         i++;
     }
+    if (print_pcr_hints) {
+    for (i = 0; i < sizeof(reason_pcr_hints) / sizeof(char *); i++) {
+        if (!(pcrmask & (1 << i)) || reason_pcr_hints[i] == NULL)
+        continue;
+        OUTPUT("PCR%02d corresponds to: %s\n", i, reason_pcr_hints[i]);
+    }
+    }
 }
 
 
index fddd9bd..a0f7071 100644 (file)
--- a/src/rm.c
+++ b/src/rm.c
@@ -48,6 +48,7 @@
 #include <libxml/parser.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 
 /**
@@ -56,9 +57,8 @@
 OPENPTS_RM_CONTEXT *newRmContext() {
     OPENPTS_RM_CONTEXT *ctx;
 
-    ctx = (OPENPTS_RM_CONTEXT *) malloc(sizeof(OPENPTS_RM_CONTEXT));
+    ctx = (OPENPTS_RM_CONTEXT *) xmalloc(sizeof(OPENPTS_RM_CONTEXT));
     if (ctx == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
 
@@ -73,9 +73,132 @@ void freeRmContext(OPENPTS_RM_CONTEXT *ctx) {
         return;
     }
 
-    free(ctx);
+    xfree(ctx);
 }
 
+/**
+ * write core:ComponentID
+ *
+ * <core:ComponentID id="CompID_<UUID>"
+ *                   [SimpleName=...]
+ *                   [ModelName=...]
+ *                   [ModelNumber=...]
+ *                   [ModelSerialNumber=...]
+ *                   [ModelSystemClass=...]
+ *                   [VersionMajor=...]
+ *                   [VersionMinor=...]
+ *                   [VersionBuild=...]
+ *                   [VersionString=...]
+ *                   [MfgDate=...]
+ *                   [PatchLevel=...]
+ *                   [DiscretePatches=...] >
+ *     <core:VendorID name="IBM">
+ *         <core:TcgVendorId>4116</core:TcgVendorId>
+ *     </core:VendorID>
+ * </core:ComponentID>
+ * 
+ */
+static int writeCoreComponentID(xmlTextWriterPtr writer,
+        const char *id,
+        OPENPTS_CONTEXT * ctx,
+        int level) {
+    OPENPTS_CONFIG *conf = ctx->conf;
+
+    if (xmlTextWriterStartElement(writer, BAD_CAST "core:ComponentID") < 0)
+        goto error;
+
+    if (xmlTextWriterWriteAttribute(writer, BAD_CAST "Id", BAD_CAST id) < 0)
+            goto error;
+
+    if (conf->compIDs[level].SimpleName != NULL)
+        if (xmlTextWriterWriteAttribute(writer, BAD_CAST "SimpleName", BAD_CAST conf->compIDs[level].SimpleName) < 0)
+            goto error;
+    if (conf->compIDs[level].ModelName != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "ModelName", BAD_CAST conf->compIDs[level].ModelName) < 0)
+            goto error;
+    if (conf->compIDs[level].ModelNumber != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "ModelNumber", BAD_CAST conf->compIDs[level].ModelNumber) < 0)
+            goto error;
+    if (conf->compIDs[level].ModelSerialNumber != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "ModelSerialNumber", BAD_CAST conf->compIDs[level].ModelSerialNumber) < 0)
+            goto error;
+    if (conf->compIDs[level].ModelSystemClass != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "ModelSystemClass", BAD_CAST conf->compIDs[level].ModelSystemClass) < 0)
+            goto error;
+    if (conf->compIDs[level].VersionMajor != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "VersionMajor", BAD_CAST conf->compIDs[level].VersionMajor) < 0)
+            goto error;
+    if (conf->compIDs[level].VersionMinor != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "VersionMinor", BAD_CAST conf->compIDs[level].VersionMinor) < 0)
+            goto error;
+    if (conf->compIDs[level].VersionBuild != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "VersionBuild", BAD_CAST conf->compIDs[level].VersionBuild) < 0)
+            goto error;
+    if (conf->compIDs[level].VersionString != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "VersionString", BAD_CAST conf->compIDs[level].VersionString) < 0)
+            goto error;
+    if (conf->compIDs[level].MfgDate != NULL)
+        if (xmlTextWriterWriteAttribute(writer, BAD_CAST "MfgDate", BAD_CAST conf->compIDs[level].MfgDate) < 0)
+            goto error;
+    if (conf->compIDs[level].PatchLevel != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "PatchLevel", BAD_CAST conf->compIDs[level].PatchLevel) < 0)
+            goto error;
+    if (conf->compIDs[level].DiscretePatches != NULL)
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "DiscretePatches", BAD_CAST conf->compIDs[level].DiscretePatches) < 0)
+            goto error;
+
+    if (conf->compIDs[level].VendorID_Name != NULL) {
+        if (xmlTextWriterStartElement(writer, BAD_CAST "core:VendorID") < 0)
+            goto error;
+
+        if (xmlTextWriterWriteAttribute(
+                writer, BAD_CAST "Name", BAD_CAST conf->compIDs[level].VendorID_Name) < 0)
+            goto error;
+
+        if (conf->compIDs[level].VendorID_Value != NULL) {
+            switch (conf->compIDs[level].VendorID_type) {
+                case VENDORID_TYPE_TCG:
+                    if (xmlTextWriterStartElement(writer, BAD_CAST "core:TcgVendorId") < 0)
+                        goto error;
+                    break;
+                case VENDORID_TYPE_SMI:
+                    if (xmlTextWriterStartElement(writer, BAD_CAST "core:SmiVendorId") < 0)
+                        goto error;
+                    break;
+                case VENDORID_TYPE_GUID:
+                    if (xmlTextWriterStartElement(writer, BAD_CAST "core:VendorGUID") < 0)
+                        goto error;
+                    break;
+            }
+            if (xmlTextWriterWriteString(writer, BAD_CAST conf->compIDs[level].VendorID_Value) < 0)
+                goto error;
+
+            if (xmlTextWriterEndElement(writer) < 0)
+                goto error;
+        }
+
+        if (xmlTextWriterEndElement(writer) < 0)  // VendorID
+            goto error;
+    }
+
+    if (xmlTextWriterEndElement(writer) < 0)  // ComponentID
+        goto error;
+
+    return 0;
+
+  error:
+    return -1;
+}
 
 /**
  * write core:Values
@@ -139,6 +262,7 @@ int writeCoreValues(xmlTextWriterPtr writer,
     if (xmlTextWriterEndElement(writer) < 0)  // core:Values
         goto error;
 
+    return 0;
   error:
     return rc;
 }
@@ -201,13 +325,13 @@ int writeAllCoreValues(xmlTextWriterPtr writer, OPENPTS_SNAPSHOT * ss) {
         bhv_trans = eventWrapper->fsm_trans;  // EW keeps the link to BHV
         if (bhv_trans == NULL) {
             DEBUG("writeAllCoreValues() - BHV Trans is missing\n");
-            if (verbose & DEBUG_FLAG) {
+            if (isDebugFlagSet(DEBUG_FLAG)) {
                 UINT32 i;
-                printf("\tpcrindex=%d, eventype=%d, digest=",
+                DEBUG("\tpcrindex=%d, eventype=%d, digest=",
                     event->ulPcrIndex, event->eventType);
                 for (i = 0;i < event->ulPcrValueLength; i++)
-                    printf("%02x", event->rgbPcrValue[i]);
-                printf("\n");
+                    DEBUG("%02x", event->rgbPcrValue[i]);
+                DEBUG("\n");
             }
             return -1;
         }
@@ -216,11 +340,11 @@ int writeAllCoreValues(xmlTextWriterPtr writer, OPENPTS_SNAPSHOT * ss) {
         if (bin_trans == NULL) {
             UINT32 i;
             ERROR("writeAllCoreValues() - BIN Trans is missing\n");
-            printf("\tat the event: pcrindex=%d, eventype=%d, digest=",
-                event->ulPcrIndex, event->eventType);
+            ERROR("\tat the event: pcrindex=%d, eventype=%d, digest=",
+                  event->ulPcrIndex, event->eventType);
             for (i = 0;i < event->ulPcrValueLength; i++)
-                printf("%02x", event->rgbPcrValue[i]);
-            printf("\n");
+                ERROR("%02x", event->rgbPcrValue[i]);
+            ERROR("\n");
             return -1;
         }
 
@@ -240,15 +364,13 @@ ERROR     rm.c:838 writeRm failed, bad IML or FSM
 
 */
 
-        if (verbose & DEBUG_FSM_FLAG) {
-            UINT32 i;
+        if (isDebugFlagSet(DEBUG_FSM_FLAG)) {
             DEBUG_FSM("writeAllCoreValues\n");
-            printf("\teventype=%d, digest=", event->eventType);
-            for (i = 0;i < event->ulPcrValueLength; i++)
-                printf("%02x", event->rgbPcrValue[i]);
-            printf("\n\tBHV(%s -> %s)\n\tBIN(%s -> %s)\n",
-                bhv_trans->source, bhv_trans->target,
-                bin_trans->source, bin_trans->target);
+            DEBUG("\teventype=%d", event->eventType);
+            debugHex("\tdigest", event->rgbPcrValue, event->ulPcrValueLength, "");
+            DEBUG("\n\tBHV(%s -> %s)\n\tBIN(%s -> %s)\n",
+                  bhv_trans->source, bhv_trans->target,
+                  bin_trans->source, bin_trans->target);
         }
 
         /* digest flag > 0 => RM */
@@ -286,7 +408,7 @@ ERROR     rm.c:838 writeRm failed, bad IML or FSM
 
                         /* copy digest value to FSM */
                         bin_trans->digestSize = event->ulPcrValueLength;
-                        bin_trans->digest = malloc(event->ulPcrValueLength);
+                        bin_trans->digest = xmalloc_assert(event->ulPcrValueLength);
                         // TODO(munetoh) check ptr
                         memcpy(bin_trans->digest,
                                event->rgbPcrValue,
@@ -476,9 +598,11 @@ int writeFsmTransition(xmlTextWriterPtr writer,
 
         if (xmlTextWriterWriteBase64(writer,
             (char*)trans->digest, 0, (int)trans->digestSize) < 0) goto error;
-
     } else if (trans->digestFlag == DIGEST_FLAG_IGNORE) {
-        snprintf(buf, sizeof(buf), "digest == base64");
+        snprintf(buf, sizeof(buf), "digest == base64!");
+        if (xmlTextWriterWriteString(writer, BAD_CAST buf) < 0) goto error;
+    } else if (trans->digestFlag == DIGEST_FLAG_TRANSPARENT) {
+        snprintf(buf, sizeof(buf), "digest == transparent!");
         if (xmlTextWriterWriteString(writer, BAD_CAST buf) < 0) goto error;
     }
     /* last */
@@ -693,6 +817,9 @@ int writeCoreAssertionInfo(xmlTextWriterPtr writer, OPENPTS_CONTEXT * ctx, int l
 
     /* SS Loop */
     for (i = 0; i < MAX_PCRNUM; i++) {
+        if (OPENPTS_PCR_INDEX == i) {
+            continue;
+        }
         ss = getSnapshotFromTable(ctx->ss_table, i, level);
         if ((ss != NULL) && (ss->event_num > 0)) {
             rc = writeValidationModel(writer, ss);
@@ -733,8 +860,8 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
     // int j;
     xmlTextWriterPtr writer;
     xmlBufferPtr buf;
-    PTS_UUID *ir_uuid;
-    char *str_ir_uuid;
+    PTS_UUID *ir_uuid = NULL;
+    char *str_ir_uuid = NULL;
     char id[BUF_SIZE];
     OPENPTS_SNAPSHOT *ss = NULL;
 
@@ -768,7 +895,7 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
     if (rc < 0) {
         ERROR("Error at xmlTextWriterStartDocument\n");
         rc = PTS_INTERNAL_ERROR;
-        goto freexml;
+        goto free;
     }
 
     /* Start an element named "Report", the root element of the document. */
@@ -776,7 +903,7 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
     if (rc < 0) {
         ERROR("Error at xmlTextWriterStartElement\n");
         rc = PTS_INTERNAL_ERROR;
-        goto freexml;
+        goto free;
     }
 
     /* new UUID */
@@ -789,7 +916,7 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
     str_ir_uuid = getStringOfUuid(ir_uuid);
     if (str_ir_uuid == NULL) {
         ERROR("UUID gen\n");
-        free(ir_uuid);
+        xfree(ir_uuid);
         rc = PTS_INTERNAL_ERROR;
         goto freexml;
     }
@@ -873,6 +1000,9 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
 
 
     for (i = 0; i < MAX_PCRNUM; i++) {
+        if (OPENPTS_PCR_INDEX == i) {
+            continue;
+        }
         /* get SS */
         ss = getSnapshotFromTable(ctx->ss_table, i, level);
         if (ss != NULL) {
@@ -892,9 +1022,10 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
                 /* update Binary FSM using IML */
                 rc = writeAllCoreValues(writer, ss);
                 if (rc < 0) {
-                    addReason(ctx,
+                    // WORK NEEDED: Please use NLS for i18n
+                    addReason(ctx, i,
                         "[RM] The manifest generation was failed at pcr=%d, level=%d", i, level);
-                    addReason(ctx,
+                    addReason(ctx, i,
                         "[RM] The validation model may not support this platform. "
                         "Report this to openpts-users@lists.sourceforge.jp.");
                     rc = PTS_INTERNAL_ERROR;
@@ -927,9 +1058,12 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
         goto free;
     }
 
-    rc = xmlTextWriterFlush(writer);
+    /* add compIds */
+    snprintf(id, sizeof(id), "COMPID_%s", str_ir_uuid);
+
+    rc = writeCoreComponentID(writer, id, ctx, level);
     if (rc < 0) {
-        ERROR("writeRm: Error at xmlTextWriterFlush\n");
+        ERROR("writeRm - ERROR file %s\n", file);
         rc = PTS_INTERNAL_ERROR;
         goto free;
     }
@@ -942,6 +1076,12 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
         goto free;
     }
 
+    rc = xmlTextWriterFlush(writer);
+    if (rc < 0) {
+        ERROR("writeRm: Error at xmlTextWriterFlush\n");
+        rc = PTS_INTERNAL_ERROR;
+        goto free;
+    }
 
 
     fp = fopen(file, "w");
@@ -951,15 +1091,20 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
         goto free;
     }
 
-    fprintf(fp, "%s", (const char *) buf->content);
+    if (fprintf(fp, "%s", (const char *) buf->content) <= 0) {
+        ERROR("Failed to write to file %s\n", file);
+        rc = PTS_INTERNAL_ERROR;  // 0
+    } else {
+        rc = PTS_SUCCESS;  // 0
+    }
 
     fclose(fp);
 
     rc = PTS_SUCCESS;  // 0
 
   free:
-    free(ir_uuid);
-    free(str_ir_uuid);
+    xfree(ir_uuid);
+    xfree(str_ir_uuid);
 
   freexml:
     xmlFreeTextWriter(writer);
@@ -977,13 +1122,14 @@ int writeRm(OPENPTS_CONTEXT * ctx, const char *file, int level) {
 // almost same with uml.c
 // but RM contains multiple BIN-FSMs
 ///////////////////////////////////////////////////
-#define RM_SAX_STATE_IDOL 0
+#define RM_SAX_STATE_IDLE 0
 #define RM_SAX_STATE_VALIDATION_MODEL 1
 #define RM_SAX_STATE_SUBVERTEX 2
 #define RM_SAX_STATE_TRANSITION 3
 #define RM_SAX_STATE_BODY 4
+#define RM_SAX_STATE_VENDID 5
 
-#define RM_SAX_STATE_STUFF_HASH 5
+#define RM_SAX_STATE_STUFF_HASH 6
 
 /**
  * SAX parser
@@ -995,7 +1141,7 @@ void  rmStartDocument(void * ctx) {
     DEBUG_SAX("rmStartDocument\n");
 
     rm_ctx->sax_error = 0;
-    rm_ctx->sax_state = RM_SAX_STATE_IDOL;
+    rm_ctx->sax_state = RM_SAX_STATE_IDLE;
 }
 
 /**
@@ -1057,6 +1203,11 @@ void  rmStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
                         if (level != rm_ctx->level) {
                             TODO("RM level is %d not %d\n", level, rm_ctx->level);
                             rm_ctx->level = level;
+                            if (level < 0 || level >= MAX_RM_NUM) {
+                                ERROR("level found in RM (%d) is greater or equal to MAX_RM_NUM (%d)\n",
+                                    level, MAX_RM_NUM);
+                                return;
+                            }
                         }
                     }
                 }
@@ -1172,9 +1323,101 @@ void  rmStartElement(void* ctx, const xmlChar* name, const xmlChar** atts) {
     } else if (!strcmp((char *)name, "body")) { /* <body>eventtype == 0xa, </body> */
         // TODO(munetoh)
         rm_ctx->sax_state = RM_SAX_STATE_BODY;
+    } else if (!strcmp((char *)name, "core:ComponentID")) {
+        int attrIdx;
+        int level = pctx->rm_ctx->level;
+        char *attributeName;
+
+        DEBUG_SAX("ComponentID level %d\n", level);
+
+        attrIdx = 0;
+        while (atts[attrIdx] != NULL) {
+            char **attributeValue;
+
+            attributeName = (char *)atts[attrIdx];
+
+            if (strcmp(attributeName, "Id") == 0) {
+                attrIdx++;
+                attrIdx++;
+                continue;
+            }
+
+            if (strcmp(attributeName, "SimpleName") == 0) {
+                attributeValue = &pctx->compIDs[level].SimpleName;
+            } else if (strcmp(attributeName, "ModelName") == 0) {
+                attributeValue = &pctx->compIDs[level].ModelName;
+            } else if (strcmp(attributeName, "ModelNumber") == 0) {
+                attributeValue = &pctx->compIDs[level].ModelNumber;
+            } else if (strcmp(attributeName, "ModelSerialNumber") == 0) {
+                attributeValue = &pctx->compIDs[level].ModelSerialNumber;
+            } else if (strcmp(attributeName, "ModelSystemClass") == 0) {
+                attributeValue = &pctx->compIDs[level].ModelSystemClass;
+            } else if (strcmp(attributeName, "VersionMajor") == 0) {
+                attributeValue = &pctx->compIDs[level].VersionMajor;
+            } else if (strcmp(attributeName, "VersionMinor") == 0) {
+                attributeValue = &pctx->compIDs[level].VersionMinor;
+            } else if (strcmp(attributeName, "VersionBuild") == 0) {
+                attributeValue = &pctx->compIDs[level].VersionBuild;
+            } else if (strcmp(attributeName, "VersionString") == 0) {
+                attributeValue = &pctx->compIDs[level].VersionString;
+            } else if (strcmp(attributeName, "MfgDate") == 0) {
+                attributeValue = &pctx->compIDs[level].MfgDate;
+            } else if (strcmp(attributeName, "PatchLevel") == 0) {
+                attributeValue = &pctx->compIDs[level].PatchLevel;
+            } else if (strcmp(attributeName, "DiscretePatches") == 0) {
+                attributeValue = &pctx->compIDs[level].DiscretePatches;
+            } else {
+                ERROR("unknown attribute for Component ID: '%s'\n", attributeName);
+                attrIdx++;  // attribute
+                attrIdx++;  // skip
+                continue;
+            }
+
+            if (*attributeValue != NULL) {
+                xfree(*attributeValue);
+            }
+            *attributeValue = smalloc((char *)atts[++attrIdx]);
+
+            if (*attributeValue == NULL) {
+                pctx->rm_ctx->sax_error = PTS_FATAL;
+                return;
+            }
+            attrIdx++;
+        }
+    } else if (!strcmp((char *)name, "core:VendorID")) {
+        int level = pctx->rm_ctx->level;
+
+        if (atts[0] != NULL || strcmp((char *)atts[0], "Name") == 0) {
+            pctx->compIDs[level].VendorID_Name = smalloc((char *)atts[1]);
+            if (pctx->compIDs[level].VendorID_Name == NULL) {
+                pctx->rm_ctx->sax_error = PTS_FATAL;
+                return;
+            }
+        }
+    } else if (!strcmp((char *)name, "core:TcgVendorId")) {
+        rm_ctx->sax_state = RM_SAX_STATE_VENDID;
+        pctx->compIDs[pctx->rm_ctx->level].VendorID_type =
+            VENDORID_TYPE_TCG;
+
+        // VendorID_Value
+
+    } else if (!strcmp((char *)name, "core:SmiVendorId")) {
+        rm_ctx->sax_state = RM_SAX_STATE_VENDID;
+        pctx->compIDs[pctx->rm_ctx->level].VendorID_type =
+            VENDORID_TYPE_SMI;
+
+        // VendorID_Value
+
+    } else if (!strcmp((char *)name, "core:VendorGUID")) {
+        rm_ctx->sax_state = RM_SAX_STATE_VENDID;
+        pctx->compIDs[pctx->rm_ctx->level].VendorID_type =
+            VENDORID_TYPE_GUID;
+
+        // VendorID_Value
+
     } else {
         ERROR("Unknown  ELEMENT [%s] \n", name);
-        rm_ctx->sax_state = RM_SAX_STATE_IDOL;
+        rm_ctx->sax_state = RM_SAX_STATE_IDLE;
     }
 }
 
@@ -1209,11 +1452,19 @@ void rmEndElement(void * ctx, const xmlChar * name) {
             rm_ctx->source_xmiid,
             rm_ctx->target_xmiid,
             rm_ctx->charbuf);
+
+        /* We only want to do this once */
+        if (1 == rm_ctx->fsm->numTransparencies) {
+            char name[64];
+            snprintf(name, sizeof(name), "disable.quote.pcr.%d", rm_ctx->fsm->pcr_index);
+            addProperty(pctx, name, "1");
+            DEBUG("Added property %s=1\n", name);
+        }
     } else {
         // DEBUG_SAX("END ELEMENT [%s] \n", name);
     }
 
-    rm_ctx->sax_state = IR_SAX_STATE_IDOL;
+    rm_ctx->sax_state = RM_SAX_STATE_IDLE;
 }
 
 /**
@@ -1240,11 +1491,14 @@ void rmCharacters(void* ctx, const xmlChar * ch, int len) {
     case RM_SAX_STATE_BODY:
         memcpy(rm_ctx->charbuf, buf, sizeof(rm_ctx->charbuf));
         break;
+    case RM_SAX_STATE_VENDID:
+        pctx->compIDs[pctx->rm_ctx->level].VendorID_Value = smalloc_assert(buf);
+        break;
     default:
         DEBUG_SAX("characters[%d]=[%s]\n", len, buf);
         break;
     }
-    rm_ctx->sax_state = RM_SAX_STATE_IDOL;
+    rm_ctx->sax_state = RM_SAX_STATE_IDLE;
 }
 
 
@@ -1273,13 +1527,16 @@ int readRmFile(OPENPTS_CONTEXT *ctx, const char *filename, int level) {
 
     /* SAX variables */
     if (ctx->rm_ctx == NULL) {
-        ctx->rm_ctx = newRmContext();  // (OPENPTS_RM_CONTEXT *) malloc(sizeof(OPENPTS_RM_CONTEXT));
+        ctx->rm_ctx = newRmContext();  // (OPENPTS_RM_CONTEXT *) xmalloc(sizeof(OPENPTS_RM_CONTEXT));
         if (ctx->rm_ctx == NULL) {
-            ERROR("no memory\n");
             return -1;
         }
     }
 
+    if (level < 0 || level >= MAX_RM_NUM) {
+        ERROR("readRmFile - level (%d) is greater or equal to MAX_RM_NUM (%d)\n", level, MAX_RM_NUM);
+        return -1;
+    }
     ctx->rm_ctx->level = level;
 
     /* setup handlers */
@@ -1332,7 +1589,8 @@ int getRmSetDir(OPENPTS_CONFIG *conf) {
 
         if (lstat(buf, &st) == -1) {
             /* Missing conf dir => Error */
-            ERROR("getRmSetDir() -Conf directory, %s is missing. please initialize the collector first\n", buf);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_RM_CONF_DIR_MISSING,
+                        "The configuration directory '%s' is missing. Please initialize the collector first\n"), buf);
             rc = PTS_INTERNAL_ERROR;
             goto end;
         }
@@ -1345,9 +1603,9 @@ int getRmSetDir(OPENPTS_CONFIG *conf) {
                 conf->rm_uuid->str, i);
             if (conf->rm_filename[i] != NULL) {
                 // DEBUG("getRmSetDir() - free conf->rm_filename[%d] %s\n",i, conf->rm_filename[i]);
-                free(conf->rm_filename[i]);
+                xfree(conf->rm_filename[i]);
             }
-            conf->rm_filename[i] = smalloc(buf);
+            conf->rm_filename[i] = smalloc_assert(buf);
             DEBUG("RM File                      : %s\n", conf->rm_filename[i]);
         }
     } else {
@@ -1403,9 +1661,9 @@ int getNewRmSetDir(OPENPTS_CONFIG *conf) {
                 conf->newrm_uuid->str, i);
             if (conf->newrm_filename[i] != NULL) {
                 // DEBUG("getRmSetDir() - free conf->rm_filename[%d] %s\n",i, conf->rm_filename[i]);
-                free(conf->newrm_filename[i]);
+                xfree(conf->newrm_filename[i]);
             }
-            conf->newrm_filename[i] = smalloc(buf);
+            conf->newrm_filename[i] = smalloc_assert(buf);
             DEBUG("NEWRM File                  : %s\n", conf->newrm_filename[i]);
         }
     } else {
@@ -1446,7 +1704,7 @@ int makeRmSetDir(OPENPTS_CONFIG *conf) {
             snprintf(buf, BUF_SIZE, "%s/%s/rm%d.xml",
                 conf->rm_basedir,
                 conf->rm_uuid->str, i);
-            conf->rm_filename[i] = smalloc(buf);
+            conf->rm_filename[i] = smalloc_assert(buf);
         }
     }
     rc = PTS_SUCCESS;
@@ -1487,7 +1745,7 @@ int makeNewRmSetDir(OPENPTS_CONFIG *conf) {
                 "%s/%s/rm%d.xml",
                 conf->rm_basedir,
                 conf->newrm_uuid->str, i);
-            conf->newrm_filename[i] = smalloc(buf);
+            conf->newrm_filename[i] = smalloc_assert(buf);
         }
     }
     rc = PTS_SUCCESS;
index ce422bd..3ca3708 100644 (file)
 #include <string.h>
 #include <netdb.h>
 #include <errno.h>
-
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <unistd.h>
-
 #include <sys/stat.h>
 #include <fcntl.h>
 
 #include <openpts.h>
 
-int verbose = 0; /**< DEBUG  */
-
 /**
  * usage
  */
 void usage(void) {
-    fprintf(stderr, "usage: rm2dot [options] RMfile \n");
-    fprintf(stderr, "\t-o output\tset output file (default is stdout)\n");
-    fprintf(stderr, "\t-p pcrindex\tset PCR index\n");
-    fprintf(stderr, "\t-l level\tset snapshot level (0 or 1)\n");
-    fprintf(stderr, "\t$ dot -Tpng foo.dot -o foo.png; eog foo.png\n");
-    fprintf(stderr, "\n");
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_RM2DOT_USAGE, "usage: rm2dot [options] RMfile \n"
+                    "\t-o output\tset output file (default is stdout)\n"
+                    "\t-p pcrindex\tset PCR index\n"
+                    "\t-l level\tset snapshot level (0 or 1)\n"
+                    "\t$ dot -Tpng foo.dot -o foo.png; eog foo.png\n"
+                    "\n"));
 }
 
 /**
@@ -90,13 +86,12 @@ int main(int argc, char *argv[]) {
     int pcr_index = 0;
     int level = 0;
 
-    verbose = 0;
+    initCatalog();
 
     while ((c = getopt(argc, argv, "do:p:l:h")) != EOF) {
         switch (c) {
         case 'd':
-            verbose = 1;
-
+            setDebugFlags(DEBUG_FLAG);
             break;
         case 'o':
             output_filename = optarg;
@@ -121,7 +116,7 @@ int main(int argc, char *argv[]) {
     /* Read RM(XML) file */
 
     if (input_filename == NULL) {
-        printf("ERROR missing XMLfile\n");
+        printf(NLS(MS_OPENPTS, OPENPTS_RM2DOT_MISSING_XML_FILE, "ERROR missing XMLfile\n"));
         usage();
         return -1;
     }
@@ -129,20 +124,20 @@ int main(int argc, char *argv[]) {
     /* new pts context */
     conf = newPtsConfig();
     if (conf == NULL) {
-        printf("ERROR\n");
+        ERROR("ERROR\n");
         return -1;
     }
 
     ctx = newPtsContext(conf);
     if (ctx == NULL) {
-        printf("ERROR\n");
+        ERROR("ERROR\n");
         return -1;
     }
 
     /* read RM */
     rc = readRmFile(ctx, input_filename, 0);
     if (rc != PTS_SUCCESS) {
-        printf("ERROR readRmFile\n");
+        ERROR("ERROR readRmFile\n");
         goto error;
     }
 
@@ -151,13 +146,13 @@ int main(int argc, char *argv[]) {
     } else if (level == 1) {
         ss =  getSnapshotFromTable(ctx->ss_table, pcr_index, 1);
     } else {
-        printf("ERROR bad level %d\n", level);
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_RM2DOT_BAD_LEVEL, "ERROR bad level %d\n"), level);
         goto error;
     }
 
     rc = writeDotModel(ss->fsm_binary, output_filename);
     if (rc != PTS_SUCCESS) {
-        printf("ERROR writeDotModel\n");
+        ERROR("ERROR writeDotModel\n");
         goto error;
     }
 
index 016bc7f..6d2396e 100644 (file)
@@ -53,6 +53,7 @@
 #include <dirent.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 #define SMBIOS_MAX_SIZE   4096
 #define SMBIOS_MAX_HANDLE 0x50
@@ -122,9 +123,8 @@ int readSmbiosFile(char * filename, BYTE **data, int *len) {
     BYTE *buf;
     int rc = PTS_SUCCESS;
 
-    buf = malloc(SMBIOS_MAX_SIZE);  // TODO check the filesize
+    buf = xmalloc(SMBIOS_MAX_SIZE);  // TODO check the filesize
     if (buf == NULL) {
-        ERROR("readSmbiosFile - no memory/n");
         return PTS_FATAL;
     }
 
@@ -143,7 +143,7 @@ int readSmbiosFile(char * filename, BYTE **data, int *len) {
     return rc;
 
   error:
-    free(buf);
+    xfree(buf);
     return rc;
 }
 
@@ -171,7 +171,8 @@ int printSmbios(BYTE *data, int length) {
         /* */
         str_length = ptr[0x16] + (ptr[0x17]<<8);
         str_num = ptr[0x1C] + (ptr[0x1D]<<8);
-        printf("%d structures occupying %d bytes.\n", str_num, str_length);
+        printf(NLS(MS_OPENPTS, OPENPTS_SMBIOS_STRUCTURES,
+            "%d structures occupying %d bytes.\n"), str_num, str_length);
         eod = ptr + str_length + 32;
         // SKIP Head
         ptr += 32;
@@ -183,11 +184,12 @@ int printSmbios(BYTE *data, int length) {
         type = ptr[0];
         len = ptr[1];
         handle = ptr[2] + ptr[3]*256;
-        printf("Handle 0x%04x, DMI type %d(0x%x), %d bytes\n", handle, type, type, len);
-        printHex("  head", ptr, len, "\n");
+        printf(NLS(MS_OPENPTS, OPENPTS_SMBIOS_HANDLE,
+            "Handle 0x%04x, DMI type %d(0x%x), %d bytes\n"), handle, type, type, len);
+        printHex(NLS(MS_OPENPTS, OPENPTS_SMBIOS_HEAD, "  head"), ptr, len, "\n");
 
         if (type == 127) {
-            printf("End Of Table\n");
+            printf(NLS(MS_OPENPTS, OPENPTS_SMBIOS_END_OF_TABLE, "End Of Table\n"));
             // printf("%ld\n", ptr - data);
             break;
         }
@@ -200,7 +202,7 @@ int printSmbios(BYTE *data, int length) {
         }
 
         if (ptr >  eod) {
-            printf("End Of Table\n");
+            printf(NLS(MS_OPENPTS, OPENPTS_SMBIOS_END_OF_TABLE, "End Of Table\n"));
             break;
         }
 
@@ -214,7 +216,7 @@ int printSmbios(BYTE *data, int length) {
         ptr++;
         ptr++;
 
-        printHex("  body", strings, ptr - strings, "\n");
+        printHex(NLS(MS_OPENPTS, OPENPTS_SMBIOS_BODY, "  body"), strings, ptr - strings, "\n");
 
 
         if (ptr > eod) {
@@ -343,8 +345,8 @@ int parseSmbios(OPENPTS_CONTEXT *ctx, BYTE *data, int length) {
         /* to config  */
         switch (type) {
             case 0x0: /* BIOS Information */
-                conf->bios_vendor = smalloc((char*)strings[0]);
-                conf->bios_version = smalloc((char*)strings[1]);
+                conf->bios_vendor = smalloc_assert((char*)strings[0]);
+                conf->bios_version = smalloc_assert((char*)strings[1]);
                 break;
             default:
                 break;
index 339cbcd..29b0d2d 100644 (file)
@@ -82,6 +82,7 @@
 #include <openssl/sha.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 /**
  * New Snapshot
@@ -93,9 +94,8 @@
 OPENPTS_SNAPSHOT * newSnapshot() {
     OPENPTS_SNAPSHOT *ss = NULL;
 
-    ss = (OPENPTS_SNAPSHOT*) malloc(sizeof(OPENPTS_SNAPSHOT));  // leaked
+    ss = (OPENPTS_SNAPSHOT*) xmalloc(sizeof(OPENPTS_SNAPSHOT));  // leaked
     if (ss == NULL) {
-        ERROR("newSnapshot - no memory\n");  // TODO(munetoh)
         return NULL;
     }
     memset(ss, 0, sizeof(OPENPTS_SNAPSHOT));
@@ -115,10 +115,7 @@ OPENPTS_SNAPSHOT * newSnapshot() {
  * return 0:success, -1:error
  */
 int freeSnapshot(OPENPTS_SNAPSHOT * ss) {
-    if (ss == NULL) {
-        ERROR(" OPENPTS_SNAPSHOT was NULL\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != ss, "freeSnapshot - ss is NULL\n");
 
     /* Event Wrapper Chain - free */
     if (ss->start != NULL) {
@@ -138,7 +135,7 @@ int freeSnapshot(OPENPTS_SNAPSHOT * ss) {
         ss->fsm_binary = NULL;
     }
 
-    free(ss);
+    xfree(ss);
 
     return PTS_SUCCESS;
 }
@@ -154,9 +151,8 @@ int freeSnapshot(OPENPTS_SNAPSHOT * ss) {
 OPENPTS_SNAPSHOT_TABLE * newSnapshotTable() {
     OPENPTS_SNAPSHOT_TABLE *sst = NULL;
 
-    sst = (OPENPTS_SNAPSHOT_TABLE *) malloc(sizeof(OPENPTS_SNAPSHOT_TABLE));  // leaked
+    sst = (OPENPTS_SNAPSHOT_TABLE *) xmalloc(sizeof(OPENPTS_SNAPSHOT_TABLE));  // leaked
     if (sst == NULL) {
-        ERROR("newSnapshotTable - no memory\n");
         return NULL;
     }
     memset(sst, 0, sizeof(OPENPTS_SNAPSHOT_TABLE));
@@ -187,7 +183,7 @@ int freeSnapshotTable(OPENPTS_SNAPSHOT_TABLE * sst) {
         }
     }
 
-    free(sst);
+    xfree(sst);
     return PTS_SUCCESS;
 }
 
@@ -198,14 +194,9 @@ int freeSnapshotTable(OPENPTS_SNAPSHOT_TABLE * sst) {
  */
 int addSnapshotToTable(OPENPTS_SNAPSHOT_TABLE * sst, OPENPTS_SNAPSHOT * ss, int pcr_index, int level) {
     /* check 1 */
-    if (sst == NULL) {
-        ERROR("OPENPTS_SNAPSHOT_TABLE is null\n");
-        return PTS_INTERNAL_ERROR;
-    }
-    if (ss == NULL) {
-        ERROR("OPENPTS_SNAPSHOT is null\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != sst, "addSnapshotToTable - sst is NULL\n");
+    ASSERT(NULL != ss, "addSnapshotToTable - ss is NULL\n");
+
     if ((pcr_index < 0) || (MAX_PCRNUM <= pcr_index )) {
         ERROR("bad PCR index, %d\n", pcr_index);
         return PTS_INTERNAL_ERROR;
@@ -232,10 +223,8 @@ int addSnapshotToTable(OPENPTS_SNAPSHOT_TABLE * sst, OPENPTS_SNAPSHOT * ss, int
  */
 OPENPTS_SNAPSHOT *getSnapshotFromTable(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_index, int level) {
     /* check 1 */
-    if (sst == NULL) {
-        ERROR("getSnapshotFromTable() - OPENPTS_SNAPSHOT_TABLE is null, pcr=%d,level=%d\n", pcr_index, level);
-        return NULL;
-    }
+    ASSERT(NULL != sst, "getSnapshotFromTable - sst is NULL\n");
+
     if ((pcr_index < 0) || (MAX_PCRNUM <= pcr_index)) {
         ERROR("getSnapshotFromTable() - bad PCR index, %d\n", pcr_index);
         return NULL;
@@ -263,10 +252,8 @@ OPENPTS_SNAPSHOT *getSnapshotFromTable(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_ind
  */
 OPENPTS_SNAPSHOT *getNewSnapshotFromTable(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_index, int level) {
     /* check 1 */
-    if (sst == NULL) {
-        ERROR("getSnapshotFromTable() - OPENPTS_SNAPSHOT_TABLE is null\n");
-        return NULL;
-    }
+    ASSERT(NULL != sst, "getNewSnapshotFromTable - sst is NULL\n");
+
     if ((pcr_index < 0) || (MAX_PCRNUM <= pcr_index)) {
         ERROR("getSnapshotFromTable() - bad PCR index, %d\n", pcr_index);
         return NULL;
@@ -298,10 +285,8 @@ OPENPTS_SNAPSHOT *getNewSnapshotFromTable(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_
 OPENPTS_SNAPSHOT *getActiveSnapshotFromTable(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_index) {
     int level;
     /* check 1 */
-    if (sst == NULL) {
-        ERROR("getSnapshotFromTable() - OPENPTS_SNAPSHOT_TABLE is null\n");
-        return NULL;
-    }
+    ASSERT(NULL != sst, "getActiveSnapshotFromTable - sst is NULL\n");
+
     if ((pcr_index < 0) || (MAX_PCRNUM <= pcr_index)) {
         ERROR("getSnapshotFromTable() - bad PCR index, %d\n", pcr_index);
         return NULL;
@@ -319,11 +304,8 @@ OPENPTS_SNAPSHOT *getActiveSnapshotFromTable(OPENPTS_SNAPSHOT_TABLE * sst, int p
  */
 int setActiveSnapshotLevel(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_index, int level) {
     /* check */
-    if (sst == NULL) {
-        ERROR("setActiveSnapshotLevel() - OPENPTS_SNAPSHOT_TABLE is null, pcr=%d,level=%d\n",
-            pcr_index, level);
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != sst, "setActiveSnapshotLevel - sst is NULL\n");
+
     if ((pcr_index < 0) || (MAX_PCRNUM <= pcr_index)) {
         ERROR("setActiveSnapshotLevel() - bad PCR index, %d\n", pcr_index);
         return PTS_INTERNAL_ERROR;
@@ -343,10 +325,8 @@ int setActiveSnapshotLevel(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_index, int leve
  */
 int incActiveSnapshotLevel(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_index) {
     /* check */
-    if (sst == NULL) {
-        ERROR("OPENPTS_SNAPSHOT_TABLE is null\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != sst, "incActiveSnapshotLevel - sst is NULL\n");
+
     if ((pcr_index < 0) || (MAX_PCRNUM <= pcr_index)) {
         ERROR("bad PCR index, %d\n", pcr_index);
         return PTS_INTERNAL_ERROR;
@@ -362,10 +342,8 @@ int incActiveSnapshotLevel(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_index) {
  */
 int getActiveSnapshotLevel(OPENPTS_SNAPSHOT_TABLE * sst, int pcr_index) {
     /* check */
-    if (sst == NULL) {
-        ERROR("OPENPTS_SNAPSHOT_TABLE is null\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(NULL != sst, "incActiveSnapshotLevel - sst is NULL\n");
+
     if ((pcr_index < 0) || (MAX_PCRNUM <= pcr_index)) {
         ERROR("bad PCR index, %d\n", pcr_index);
         return PTS_INTERNAL_ERROR;
index 57e0aab..b7fc927 100644 (file)
--- a/src/ssh.c
+++ b/src/ssh.c
@@ -40,8 +40,9 @@
 #include <sys/socket.h>
 
 #include <openpts.h>
+// #include <log.h>
 
-/* remote command */
+/* chanegd by unit test */
 char *ptsc_command = "/usr/sbin/ptsc -m";
 
 /** 
@@ -109,8 +110,21 @@ pid_t ssh_connect(char *host, char *ssh_username, char *ssh_port, char *key_file
         }
         arguments[arg_idx++] = host;
         arguments[arg_idx++] = ptsc_command;
+        // arguments[arg_idx++] = "ptsc";
+        // arguments[arg_idx++] = "-m";
+#if 0
+        /* Sync verbose level between verifier and collector? */
+        // {
+           int verboseLevel;
+            for ( verboseLevel = 0; (verboseLevel < getVerbosity()) && (arg_idx < 15); verboseLevel++ ) {
+                arguments[arg_idx++] = "-v";
+            }
+        // }
+#endif
         arguments[arg_idx++] = NULL;
 
+DEBUG("ptsc_command %s\n", ptsc_command);
+
         execvp("ssh", arguments);
         ERROR("execvp(ssh)");
         exit(1);
index f1b7dfb..7bd3de8 100644 (file)
@@ -26,7 +26,7 @@
  * \brief target(collector)
  * @author Seiji Munetoh <munetoh@users.sourceforge.jp>
  * @date 2011-06-22
- * cleanup 2011-07-06 SM
+ * cleanup 2011-10-07 SM
  *
  * branch from uuid.c
  *
@@ -44,7 +44,6 @@
 
 #include <errno.h>
 
-
 // DIR
 #include <unistd.h>
 #include <dirent.h>
@@ -180,9 +179,8 @@ int getRmList(OPENPTS_CONFIG *conf, char * config_dir) {
 
     /* malloc */
     // TODO alloc 1 more RMSET for update
-    conf->rmsets = (OPENPTS_RMSETS *) malloc(sizeof(OPENPTS_RMSETS) + sizeof(OPENPTS_RMSET) * (dir_num + 1) );
+    conf->rmsets = (OPENPTS_RMSETS *) xmalloc(sizeof(OPENPTS_RMSETS) + sizeof(OPENPTS_RMSET) * (dir_num + 1) );
     if (conf->rmsets == NULL) {
-        ERROR("no memory");
         return PTS_INTERNAL_ERROR;
     }
     conf->rmsets->rmset_num = dir_num;
@@ -219,9 +217,9 @@ int getRmList(OPENPTS_CONFIG *conf, char * config_dir) {
             }
         }
 
-        free(dir_list[cnt]);
+        xfree(dir_list[cnt]);
     }
-    free(dir_list);
+    xfree(dir_list);
 
     /* sort (bub) */
     for (i = 0; i< dir_num - 1; i++) {
@@ -328,7 +326,7 @@ int purgeRenewedRm(OPENPTS_CONFIG *conf) {
         state = rmset->state;
 
         if (state == OPENPTS_RM_STATE_TRASH) {
-            printf("  purge %s\n", rmset->str_uuid);
+            INFO(NLS(MS_OPENPTS, OPENPTS_PURGE_RENEWED_RM, "  purge %s\n"), rmset->str_uuid);
             rc = rmRmsetDir(rmset->dir);
             if (rc != PTS_SUCCESS) {
                 rc2 = PTS_OS_ERROR;
@@ -348,20 +346,14 @@ void printRmList(OPENPTS_CONFIG *conf, char *indent) {
     int num = 0;
 
     /* check */
-    if (conf == NULL) {
-        ERROR(" conf is NULL");
-        return;
-    }
-    if (conf->rmsets == NULL) {
-        ERROR(" conf->rmsets is NULL");
-        return;
-    }
-
+    ASSERT(NULL != conf, " conf is NULL");
+    ASSERT(NULL != conf->rmsets, " conf->rmsets is NULL");
 
     num = conf->rmsets->rmset_num;
 
-    printf("%s  ID              UUID                        date(UTC)                status\n", indent);
-    printf("%s%s\n", indent, SEP_LINE);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_RM_LIST_HEADER, "%s  ID  UUID  date(UTC)  status\n"), indent);
+    OUTPUT("%s %s\n", indent, SEP_LINE);
+
 
     /* Print  */
     for (cnt = 0; cnt < num; cnt++) {
@@ -371,7 +363,7 @@ void printRmList(OPENPTS_CONFIG *conf, char *indent) {
         time = rmset->time;
         state = rmset->state;
 
-        printf("%s %3d %s %04d-%02d-%02d-%02d:%02d:%02d",
+        OUTPUT("%s %3d %s %04d-%02d-%02d-%02d:%02d:%02d",
             indent,
             cnt,
             str_uuid,
@@ -383,18 +375,18 @@ void printRmList(OPENPTS_CONFIG *conf, char *indent) {
             time->sec);
 
         if (state == OPENPTS_RM_STATE_OLD) {
-            printf(" OLD\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_RM_LIST_OLD, " OLD\n"));
         } else if (state == OPENPTS_RM_STATE_NOW) {
-            printf(" NOW\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_RM_LIST_NOW, " NOW\n"));
         } else if (state == OPENPTS_RM_STATE_NEW) {  // TODO def name is not clear
-            printf(" NEW (for next boot)\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_RM_LIST_NOW_NEXT, " NEW (for next boot)\n"));
         } else if (state == OPENPTS_RM_STATE_TRASH) {
-            printf(" RENEWED (-R to purge)\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_RM_LIST_RENEWED, " RENEWED (-R to purge)\n"));
         } else {
-            printf(" state=UNKNOWN\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_RM_LIST_UNKNOWN, " state=UNKNOWN\n"));
         }
     }
-    printf("%s%s\n", indent, SEP_LINE);
+    OUTPUT("%s %s\n", indent, SEP_LINE);
 }
 
 
@@ -429,21 +421,20 @@ int getTargetList(OPENPTS_CONFIG *conf, char * config_dir) {
 
     /* move to config dir */
     if ((chdir(conf->config_dir)) != 0) {
-        fprintf(stderr, "Accessing config directory %s\n", conf->config_dir);
+        ERROR("Accessing config directory %s\n", conf->config_dir);
         return PTS_INTERNAL_ERROR;
     }
 
     /* scan dirs */
     dir_num = scandir(".", &dir_list, &selectUuidDir, NULL);
     if ( dir_num == -1 ) {
-        fprintf(stderr, "no target data\n");
+        ERROR("no target data\n");
         return PTS_INTERNAL_ERROR;
     }
 
     /* malloc target_list */
     conf->target_list = newTargetList(dir_num + 1);  // conf.c
     if (conf->target_list == NULL) {
-        ERROR("no memory");
         return PTS_INTERNAL_ERROR;
     }
 
@@ -451,11 +442,10 @@ int getTargetList(OPENPTS_CONFIG *conf, char * config_dir) {
     for (cnt = 0; cnt < dir_num; cnt++) {
         target = &conf->target_list->target[cnt];
         if (target == NULL) {
-            ERROR("no memory cnt=%d\n", cnt);
             return PTS_INTERNAL_ERROR;
         }
         /* init */
-        target->str_uuid = smalloc(dir_list[cnt]->d_name);
+        target->str_uuid = smalloc_assert(dir_list[cnt]->d_name);
         target->uuid = getUuidFromString(dir_list[cnt]->d_name);
         target->time = getDateTimeOfUuid(target->uuid);
         target->dir = getFullpathName(conf->config_dir, target->str_uuid);
@@ -466,7 +456,6 @@ int getTargetList(OPENPTS_CONFIG *conf, char * config_dir) {
         /* read target config */
         target_conf = (void *)newPtsConfig();
         if (target_conf  == NULL) {
-            printf("no memory\n");
             return PTS_INTERNAL_ERROR;  // TODO
         }
         readTargetConf(target_conf, target->target_conf_filename);
@@ -501,9 +490,12 @@ int getTargetList(OPENPTS_CONFIG *conf, char * config_dir) {
 
         target->target_conf = (void *)target_conf;
 
-        free(dir_list[cnt]);
+        xfree(dir_list[cnt]);
+    }
+
+    if ( dir_num > 0 ) {
+        xfree(dir_list);
     }
-    free(dir_list);
 
     return PTS_SUCCESS;
 }
@@ -524,10 +516,8 @@ char *getTargetConfDir(OPENPTS_CONFIG *conf) {
     int num = 0;
 
     /* check */
-    if (conf == NULL) {
-        ERROR("getTargetConfDir() - conf is NULL\n");
-        return NULL;
-    }
+    ASSERT(NULL != conf, "getTargetConfDir() - conf is NULL\n");
+
     if (conf->hostname == NULL) {
         ERROR("getTargetConfDir() - conf->hostname is NULL\n");
         return NULL;
@@ -550,7 +540,7 @@ char *getTargetConfDir(OPENPTS_CONFIG *conf) {
         } else {
             if (!strcmp(conf->hostname, target_conf->hostname)) {
                 /* HIT, return first one, if multiple host was exist conf dir was broken */
-                dir = smalloc(target->dir);
+                dir = smalloc_assert(target->dir);
                 return dir;
             }
         }
@@ -570,6 +560,15 @@ OPENPTS_TARGET *getTargetCollector(OPENPTS_CONFIG *conf) {
     OPENPTS_CONFIG *target_conf;
     int num = 0;
 
+    /* check */
+    if (conf == NULL) {
+        return NULL;
+    }
+    if (conf->target_list == NULL) {
+        return NULL;
+    }
+
+    /* # of target */
     num = conf->target_list->target_num;
 
     /* loop  */
@@ -594,7 +593,85 @@ OPENPTS_TARGET *getTargetCollector(OPENPTS_CONFIG *conf) {
     return NULL;
 }
 
+OPENPTS_TARGET *getTargetCollectorByUUID(OPENPTS_CONFIG *conf, const char *uuid) {
+    int cnt;
+    OPENPTS_TARGET *target;
+    int num = 0;
+
+    num = conf->target_list->target_num;
+
+    /* loop  */
+    for (cnt = 0; cnt < num; cnt++) {
+        target = &conf->target_list->target[cnt];
 
+        if (NULL != target->str_uuid && !strcmp(uuid, target->str_uuid)) {
+            /* HIT */
+            return target;
+        } else {
+            /* miss -> skip */
+        }
+    }
+
+    return NULL;
+}
+
+
+#if 0
+/* Needs more work. If we want this printed out for "openpts -D" invocations we need to
+   read in the RM files first, which we no longer do. */
+static void printTargetInfo_CompID(OPENPTS_CONTEXT *ctx, FILE *fp, int cnt) {
+    int level;
+
+    for (level = 0; level < MAX_RM_NUM; level++) {
+        if (ctx->compIDs[level].SimpleName != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.SimpleName: %s\n", cnt, level, ctx->compIDs[level].SimpleName);
+        if (ctx->compIDs[level].ModelName != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.ModelName: %s\n", cnt, level, ctx->compIDs[level].ModelName);
+        if (ctx->compIDs[level].ModelNumber != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.ModelNumber: %s\n",
+                cnt, level, ctx->compIDs[level].ModelNumber);
+        if (ctx->compIDs[level].ModelSerialNumber != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.ModelSerialNumber: %s\n",
+                cnt, level, ctx->compIDs[level].ModelSerialNumber);
+        if (ctx->compIDs[level].ModelSystemClass != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.ModelSystemClass: %s\n",
+                cnt, level, ctx->compIDs[level].ModelSystemClass);
+        if (ctx->compIDs[level].VersionMajor != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.VersionMajor: %s\n",
+                cnt, level, ctx->compIDs[level].VersionMajor);
+        if (ctx->compIDs[level].VersionMinor != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.VersionMinor: %s\n",
+                cnt, level, ctx->compIDs[level].VersionMinor);
+        if (ctx->compIDs[level].VersionBuild != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.VersionBuild: %s\n",
+                cnt, level, ctx->compIDs[level].VersionBuild);
+        if (ctx->compIDs[level].VersionString != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.VersionString: %s\n",
+                cnt, level, ctx->compIDs[level].VersionString);
+        if (ctx->compIDs[level].MfgDate != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.MfgDate: %s\n",
+                cnt, level, ctx->compIDs[level].MfgDate);
+        if (ctx->compIDs[level].PatchLevel != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.PatchLevel: %s\n",
+                cnt, level, ctx->compIDs[level].PatchLevel);
+        if (ctx->compIDs[level].DiscretePatches != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.DiscretePatches: %s\n",
+                cnt, level, ctx->compIDs[level].DiscretePatches);
+        if (ctx->compIDs[level].VendorID_Name != NULL)
+            fprintf(fp, "target[%d] rm.compid.%d.VendorID_Name: %s\n",
+                cnt, level, ctx->compIDs[level].VendorID_Name);
+        if (ctx->compIDs[level].VendorID_Value != NULL) {
+            fprintf(fp, "target[%d] rm.compid.%d.", cnt, level);
+            switch (ctx->compIDs[level].VendorID_type) {
+                case VENDORID_TYPE_TCG: fprintf(fp, "TcgVendorId: "); break;
+                case VENDORID_TYPE_SMI: fprintf(fp, "SmiVendorId: "); break;
+                case VENDORID_TYPE_GUID: fprintf(fp, "VendorGUID: "); break;
+            }
+            fprintf(fp, "%s\n", ctx->compIDs[level].VendorID_Value);
+        }
+    }
+}
+#endif
 
 
 /**
@@ -610,10 +687,10 @@ void printTargetList(OPENPTS_CONFIG *conf, char *indent) {
 
     num = conf->target_list->target_num;
 
-    printf("%s  ID    UUID                                 "
-           "date(UTC)          username@hostname:port\n",
-        indent);
-    printf("%s%s\n", indent, SEP_LINE);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_PRINT_TARGET_LIST_HEADER,
+           "%s  ID  UUID                                 date(UTC)          port port(ssh)  (username@)hostname\n"),
+           indent);
+    OUTPUT("%s%s\n", indent, SEP_LINE);
 
     /* Print  */
     for (cnt = 0; cnt < num; cnt++) {
@@ -628,7 +705,7 @@ void printTargetList(OPENPTS_CONFIG *conf, char *indent) {
                     str_uuid = target_conf->uuid->str;
                 }
             }
-            printf("%s %4d %s %04d-%02d-%02d-%02d:%02d:%02d %s@%s:%s\n",
+            OUTPUT("%s %4d %s %04d-%02d-%02d-%02d:%02d:%02d %s@%s:%s\n",
                 indent,
                 cnt,
                 str_uuid,
@@ -645,5 +722,5 @@ void printTargetList(OPENPTS_CONFIG *conf, char *indent) {
             // printf("--\n");
         }
     }
-    printf("%s%s\n", indent, SEP_LINE);
+    OUTPUT("%s%s\n", indent, SEP_LINE);
 }
index f5ea0cb..c9a5a61 100644 (file)
@@ -472,9 +472,8 @@ int sinit_acm_hash(char *filename, int size, BYTE *sha1_digest, BYTE *sha256_dig
 
     DEBUG("sinit_acm_hash() file = %s, size = %d\n", filename, size);
 
-    acmbuf = malloc(size);
+    acmbuf = xmalloc(size);
     if (acmbuf == NULL) {
-        ERROR("no memory");
         rc = PTS_FATAL;
         goto error;
     }
@@ -527,7 +526,7 @@ int sinit_acm_hash(char *filename, int size, BYTE *sha1_digest, BYTE *sha256_dig
     debugPrintHex(" SHA256 Digest : ", sha256_digest, 32, "\n");
 
   error:
-    free(acmbuf);
+    xfree(acmbuf);
     return rc;
 }
 
@@ -624,8 +623,8 @@ int parseGrubConfFile(OPENPTS_TBOOT_CONTEXT *ctx, char *filename, char *path) {
                 TBOOT_MODULE *module;
                 OPENPTS_EVENT_TBOOT_MODULE *eventdata;
                 /* module structure */
-                module = malloc(sizeof(TBOOT_MODULE));
-                eventdata = malloc(sizeof(OPENPTS_EVENT_TBOOT_MODULE));
+                module = xmalloc_assert(sizeof(TBOOT_MODULE));
+                eventdata = xmalloc_assert(sizeof(OPENPTS_EVENT_TBOOT_MODULE));
                 module->eventdata = eventdata;
                 module->next = NULL;
                 if (prev_module == NULL) {
@@ -934,17 +933,15 @@ int generateEventlog(OPENPTS_TBOOT_CONTEXT *ctx, char *filename) {
     }
 
     /* event  */
-    event = malloc(sizeof(TSS_PCR_EVENT));
+    event = xmalloc(sizeof(TSS_PCR_EVENT));
     if (event == NULL) {
-        ERROR("no memory");
         goto free;
     }
     memset(event, 0, sizeof(TSS_PCR_EVENT));
 
     /* PCR/digest */
-    event->rgbPcrValue = malloc(20);
+    event->rgbPcrValue = xmalloc(20);
     if (event->rgbPcrValue == NULL) {
-        ERROR("no memory");
         goto free;
     }
 
@@ -1073,9 +1070,8 @@ int generateEventlog(OPENPTS_TBOOT_CONTEXT *ctx, char *filename) {
         }
         eventdata = module->eventdata;
         event->ulEventLength = 20 + 20 + 4 + 4 + eventdata->command_size + eventdata->filename_size;
-        event->rgbEvent = malloc(event->ulEventLength);
+        event->rgbEvent = xmalloc(event->ulEventLength);
         if (event->rgbEvent == NULL) {
-            ERROR("no memory");
             goto free;
         }
         ptr = event->rgbEvent;
@@ -1117,10 +1113,9 @@ int generateEventlog(OPENPTS_TBOOT_CONTEXT *ctx, char *filename) {
         }
         eventdata = module->eventdata;
         event->ulEventLength = 20 + 20 + 4 + 4 + eventdata->command_size + eventdata->filename_size;
-        if (event->rgbEvent != NULL) free(event->rgbEvent);
-        event->rgbEvent = malloc(event->ulEventLength);
+        if (event->rgbEvent != NULL) xfree(event->rgbEvent);
+        event->rgbEvent = xmalloc(event->ulEventLength);
         if (event->rgbEvent == NULL) {
-            ERROR("no memory");
             goto free;
         }
         ptr = event->rgbEvent;
@@ -1148,9 +1143,9 @@ int generateEventlog(OPENPTS_TBOOT_CONTEXT *ctx, char *filename) {
 
   free:
     if (event != NULL) {
-        if (event->rgbPcrValue != NULL) free(event->rgbPcrValue);
-        if (event->rgbEvent != NULL) free(event->rgbEvent);
-        free(event);
+        if (event->rgbPcrValue != NULL) xfree(event->rgbPcrValue);
+        if (event->rgbEvent != NULL) xfree(event->rgbEvent);
+        xfree(event);
     }
 
     /* close */
@@ -1221,7 +1216,7 @@ int main(int argc, char *argv[]) {
     }
 
     /* ctx */
-    ctx = malloc(sizeof(OPENPTS_TBOOT_CONTEXT));
+    ctx = xmalloc_assert(sizeof(OPENPTS_TBOOT_CONTEXT));
     memset(ctx, 0, sizeof(OPENPTS_TBOOT_CONTEXT));
     ctx->lcp_policy_version = 1;
 
@@ -1250,6 +1245,6 @@ int main(int argc, char *argv[]) {
 
 
   close:
-    free(ctx);
+    xfree(ctx);
     return 0;
 }
index f6c170b..c83282e 100644 (file)
--- a/src/tpm.c
+++ b/src/tpm.c
@@ -45,6 +45,7 @@
 #include <openssl/sha.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 
 /* TPM functions */
@@ -58,7 +59,7 @@ int resetTpm(OPENPTS_TPM_CONTEXT *tctx, int drtm) {
     DEBUG_TPM("tpm.c - RESET (POR)\n");
 
     if (tctx == NULL) {
-        printf("ERROR TPM_CONTEXT is NULL");
+        ERROR("ERROR TPM_CONTEXT is NULL");
         return -1;
     }
 
@@ -77,7 +78,7 @@ int resetTpm(OPENPTS_TPM_CONTEXT *tctx, int drtm) {
 
     DEBUG_TPM("tpm.c - RESET (POR)\n");
 
-    // iml = (IML *) malloc(sizeof(IML) * MAX_PCRNUM);
+    // iml = (IML *) xmalloc(sizeof(IML) * MAX_PCRNUM);
     return 0;
 }
 
@@ -90,7 +91,7 @@ int resetTpmPcr(OPENPTS_TPM_CONTEXT *tctx, int index) {
     DEBUG_TPM("resetTpmPcr - RESET just one PCR %d\n", index);
 
     if (tctx == NULL) {
-        printf("ERROR TPM_CONTEXT is NULL");
+        ERROR("ERROR TPM_CONTEXT is NULL");
         return -1;
     }
 
@@ -137,15 +138,13 @@ int extendTpm(OPENPTS_TPM_CONTEXT *tctx, TSS_PCR_EVENT *event) {
     int index;
     BYTE * digest;
 
-    // if (verbose>0) printf("extendTpm - start \n");
-
     if (tctx == NULL) {
-        printf("ERROR TPM_CONTEXT is NULL\n");
+        ERROR("TPM_CONTEXT is NULL\n");
         return -1;
     }
 
     if (event == NULL) {
-        printf("ERROR TSS_PCR_EVENT is NULL\n");
+        ERROR("TSS_PCR_EVENT is NULL\n");
         return -1;
     }
 
@@ -153,17 +152,17 @@ int extendTpm(OPENPTS_TPM_CONTEXT *tctx, TSS_PCR_EVENT *event) {
     digest = event->rgbPcrValue;
 
     if (digest == NULL) {
-        printf("event->rgbPcrValue is NULL\n");
+        ERROR("event->rgbPcrValue is NULL\n");
         return -1;
     }
 
     if (index >= MAX_PCRNUM) {
-        printf("ERROR BAD PCR INDEX %d\n", index);
+        ERROR("BAD PCR INDEX %d\n", index);
         return -1;
     }
 
     if (index < 0) {
-        printf("ERROR BAD PCR INDEX %d\n", index);
+        ERROR("ERROR BAD PCR INDEX %d\n", index);
         return -1;
     }
 
@@ -178,13 +177,13 @@ int extendTpm(OPENPTS_TPM_CONTEXT *tctx, TSS_PCR_EVENT *event) {
     SHA1_Update(&ctx, digest, SHA1_DIGEST_SIZE);
     SHA1_Final(&tctx->pcr[index][0], &ctx);
 
-    if (verbose & DEBUG_TPM_FLAG) {
+    if (isDebugFlagSet(DEBUG_TPM_FLAG)) {
         int i;
         DEBUG_TPM("\ttpm.c - extend pcr=%d digest=", index);
-        for (i = 0; i < SHA1_DIGEST_SIZE; i++) printf("%02x", digest[i]);
-        printf("  -> ");
-        for (i = 0; i < SHA1_DIGEST_SIZE; i++) printf("%02x", tctx->pcr[index][i]);
-        printf("\n");
+        for (i = 0; i < SHA1_DIGEST_SIZE; i++) OUTPUT("%02x", digest[i]);
+        OUTPUT("  -> ");
+        for (i = 0; i < SHA1_DIGEST_SIZE; i++) OUTPUT("%02x", tctx->pcr[index][i]);
+        OUTPUT("\n");
     }
 
     // if (verbose>0) printf("extendTpm - done \n");
@@ -217,11 +216,11 @@ int extendTpm2(OPENPTS_TPM_CONTEXT *tctx, int index, BYTE * digest) {
     SHA1_Update(&ctx, digest, SHA1_DIGEST_SIZE);
     SHA1_Final(&tctx->pcr[index][0], &ctx);
 
-    if (verbose & DEBUG_TPM_FLAG) {
+    if (isDebugFlagSet(DEBUG_TPM_FLAG)) {
         int i;
         DEBUG_TPM("tpm.c - extend pcr=%d digest=", index);
-        for (i = 0; i < SHA1_DIGEST_SIZE; i++) printf("%02x", digest[i]);
-        printf("\n");
+        for (i = 0; i < SHA1_DIGEST_SIZE; i++) OUTPUT("%02x", digest[i]);
+        OUTPUT("\n");
     }
 
     return 0;  // TODO(munetoh)
@@ -251,19 +250,19 @@ int printTpm(OPENPTS_TPM_CONTEXT *tctx) {
     DEBUG_FSM("tpm.c - pprint pcrs\n");
 
     if (tctx == NULL) {
-        printf("ERROR TPM_CONTEXT is NULL");
+        ERROR("TPM_CONTEXT is NULL");
         return -1;
     }
 
     for (i = 0; i < MAX_PCRNUM; i++) {
-        printf("PCR[%2d] = ", i);
+        OUTPUT("PCR[%2d] = ", i);
         for (j = 0; j < SHA1_DIGEST_SIZE; j++) {
-            printf("%02x", tctx->pcr[i][j]);
+            OUTPUT("%02x", tctx->pcr[i][j]);
         }
-        printf("\n");
+        OUTPUT("\n");
     }
 
-    // iml = (IML *) malloc(sizeof(IML) * MAX_PCRNUM);
+    // iml = (IML *) xmalloc(sizeof(IML) * MAX_PCRNUM);
     return 0;
 }
 
@@ -277,7 +276,7 @@ int getTpmPcrValue(OPENPTS_TPM_CONTEXT *tpm, int index, BYTE *digest) {
     DEBUG_CAL("getTpmPcrValue - pcr[%d]\n", index);
 
     if (digest == NULL) {
-        printf("ERROR null \n");
+        ERROR("null \n");
         return -1;
     }
 
index 82e382d..d2bbd29 100644 (file)
@@ -42,6 +42,8 @@
 #include <tss.h>
 #include <trousers.h>
 
+#include <openpts.h>
+
 // Local TCSD
 #define SERVER    NULL
 
@@ -64,25 +66,21 @@ const struct option long_option[] = {
 #endif
 const char short_option[] = "u:flNPt:a:hSUB:vz";
 
-int verbose = 0;
-
 int hex2bin(void *dest, const void *src, size_t n);
-void printhex(char *str, unsigned char *buf, int len);
 
 void usage() {
-    printf("Usage: tpm_createkey [options]\n");
-    printf("\t-h\tDisplay command usage info.\n");
-    printf("\t-u\tSet UUID of key. Default is randum number\n");
-    printf("\t-N\tCreate key without auth secret\n");
-    printf("\t-a PASSWORD\tCreate key with auth secret, PASSWORD\n");
-    printf("\t-P\tUse TSS diaglog to set the authsecret\n");
-    printf("\t-f\tUpdate the key\n");
-    printf("\t-z\tUse the SRK secret of all zeros (20 bytes of zeros).\n");
-
-    /* Key storage */
-    printf("\t-S\tUse SYSTEM_PS\n");
-    printf("\t-U\tUse USER_PS\n");
-    printf("\t-B\tUse blob file\n");
+    printf(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_USAGE,
+           "Usage: tpm_createkey [options]\n"
+           "\t-h           Display command usage info.\n"
+           "\t-u           Set UUID of key. Default is randum number\n"
+           "\t-N           Create key without auth secret\n"
+           "\t-a PASSWORD  Create key with auth secret, PASSWORD\n"
+           "\t-P           Use TSS diaglog to set the authsecret\n"
+           "\t-f           Update the key\n"
+           "\t-z           Use the SRK secret of all zeros (20 bytes of zeros).\n"
+           "\t-S           Use SYSTEM_PS\n"
+           "\t-U           Use USER_PS\n"
+           "\t-B           Use blob file\n"));
 }
 
 int hex2bin(void *dest, const void *src, size_t n) {
@@ -91,7 +89,7 @@ int hex2bin(void *dest, const void *src, size_t n) {
     unsigned char *ussrc = (unsigned char *) src;
 
     if (n & 0x01) {
-        printf("ERROR: hex2bin wrong size %d\n", (int)n);
+        ERROR("ERROR: hex2bin wrong size %d\n", (int)n);
         return -1;
     }
 
@@ -125,14 +123,6 @@ int hex2bin(void *dest, const void *src, size_t n) {
     return i;
 }
 
-void printhex(char *str, unsigned char *buf, int len) {
-    int i;
-    printf("%s", str);
-    for (i = 0; i < len; i++)
-        printf("%02x", buf[i]);
-    printf("\n");
-}
-
 void fprinthex(FILE * fp, char *str, unsigned char *buf, int len) {
     int i;
     fprintf(fp, "%s", str);
@@ -194,6 +184,7 @@ int main(int argc, char *argv[]) {
 
     int srk_password_mode = 0;
 
+    initCatalog();
 
     while (1) {
         // so = getopt_long(argc, argv, short_option, long_option, 0);
@@ -204,7 +195,7 @@ int main(int argc, char *argv[]) {
         switch (so) {
         case 'u':  /* UUID of AIK/SignKey */
             if (strlen(optarg) != 32) {
-                printf("ERROR invalid UUID size, %s\n",
+                printf(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_INVALID_UUID_SIZE, "ERROR invalid UUID size, %s\n"),
                        optarg);
                 usage();
                 return -1;
@@ -250,7 +241,8 @@ int main(int argc, char *argv[]) {
             srk_password_mode = 1;
             break;
         case 'v':  /* Verbose */
-            verbose = 1;
+            setVerbosity(1);
+            setDebugFlags(DEBUG_FLAG);
             return 0;
         case 'h':  /* Help */
             usage();
@@ -269,7 +261,7 @@ int main(int argc, char *argv[]) {
 
     /* SRK well_known = 0x00 x 20 */
     if (srk_password_mode == 1) {
-        srk_auth = malloc(20);
+        srk_auth = xmalloc(20);
         memset(srk_auth, 0, 20);
         srk_auth_len = 20;
         srk_auth_mode = TSS_SECRET_MODE_SHA1;
@@ -286,14 +278,14 @@ int main(int argc, char *argv[]) {
 
     result = Tspi_Context_Create(&hContext);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Context_Create failed rc=0x%x\n",
+        ERROR("ERROR: Tspi_Context_Create failed rc=0x%x\n",
                result);
         goto close;
     }
 
     result = Tspi_Context_Connect(hContext, SERVER);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Context_Connect failed rc=0x%x\n",
+        ERROR("ERROR: Tspi_Context_Connect failed rc=0x%x\n",
                result);
         goto close;
     }
@@ -305,7 +297,7 @@ int main(int argc, char *argv[]) {
         TSS_KM_KEYINFO **ppKeyHierarchy = NULL;
 
         buf = (BYTE *) & SRK_UUID;
-        printhex("SRK uuid: ", buf, 16);
+        printHex("SRK uuid: ", buf, 16, "\n");
 
         result = Tspi_Context_GetRegisteredKeysByUUID(
                     hContext,
@@ -315,21 +307,20 @@ int main(int argc, char *argv[]) {
                     ppKeyHierarchy);
 
         if (result != TSS_SUCCESS) {
-            printf
-            ("ERROR: Tspi_Context_GetRegisteredKeysByUUID failed rc=0x%x\n",
+            ERROR("ERROR: Tspi_Context_GetRegisteredKeysByUUID failed rc=0x%x\n",
              result);
         } else {
             int i;
             TSS_KM_KEYINFO *info = ppKeyHierarchy[0];
-            printf("Key number   : %d\n", ulKeyHierarchySize);
+            printf(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_KEYNUM, "Key number   : %d\n"), ulKeyHierarchySize);
             for (i = 0; i < (int)ulKeyHierarchySize; i++) {
-                printf("Key %d\n", i);
+                printf(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_KEY, "Key %d\n"), i);
                 buf = (BYTE *) & info->versionInfo;
-                printhex(" version     : ", buf, 4);
+                printHex(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_VERSION, " version     : "), buf, 4, "\n");
                 buf = (BYTE *) & info->keyUUID;
-                printhex(" uuid        : ", buf, 16);
+                printHex(" uuid        : ", buf, 16, "\n");
                 buf = (BYTE *) & info->parentKeyUUID;
-                printhex(" parents uuid: ", buf, 16);
+                printHex(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_PARENTS_UUID, " parents uuid: "), buf, 16, "\n");
 
                 info = info + 1;
             }
@@ -341,8 +332,8 @@ int main(int argc, char *argv[]) {
 
     result = Tspi_Context_GetTpmObject(hContext, &hTPM);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Context_GetTpmObject failed rc=0x%x\n",
-               result);
+        ERROR("ERROR: Tspi_Context_GetTpmObject failed rc=0x%x\n",
+              result);
         goto close;
     }
 
@@ -354,12 +345,11 @@ int main(int argc, char *argv[]) {
                                         &hSRK);
 
     if (result != TSS_SUCCESS) {
-        printf
-        ("ERROR: Tspi_Context_LoadKeyByUUID (SRK) failed rc=0x%x\n",
-         result);
+        ERROR("ERROR: Tspi_Context_LoadKeyByUUID (SRK) failed rc=0x%x\n",
+              result);
         if (result == 0x2020) {
-            printf
-            ("Your key storage of tcsd is damaged or missing. \n");
+            printf(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_BAD_STORAGE,
+                "The key storage for tcsd is damaged or missing.\n"));
         }
         goto close;
     }
@@ -368,8 +358,8 @@ int main(int argc, char *argv[]) {
 
     result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE, &hSRKPolicy);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_GetPolicyObject failed rc=0x%x\n",
-               result);
+        ERROR("ERROR: Tspi_GetPolicyObject failed rc=0x%x\n",
+              result);
         goto close;
     }
 
@@ -379,8 +369,8 @@ int main(int argc, char *argv[]) {
                 srk_auth_len,
                 srk_auth);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
-               result);
+        ERROR("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
+              result);
         goto close;
     }
 
@@ -389,9 +379,8 @@ int main(int argc, char *argv[]) {
     if (createUuid == 1) {
         result = Tspi_TPM_GetRandom(hTPM, sizeof(TSS_UUID), &buf);
         if (result != TSS_SUCCESS) {
-            printf
-            ("ERROR: Tspi_TPM_GetRandom failed rc=0x%x\n",
-             result);
+            ERROR("ERROR: Tspi_TPM_GetRandom failed rc=0x%x\n",
+                  result);
             Tspi_Context_FreeMemory(hContext, NULL);
             goto close;
         }
@@ -408,8 +397,8 @@ int main(int argc, char *argv[]) {
                                        TSS_OBJECT_TYPE_RSAKEY,
                                        initFlag, &hKey);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Context_CreateObject failed rc=0x%x\n",
-               result);
+        ERROR("ERROR: Tspi_Context_CreateObject failed rc=0x%x\n",
+              result);
         goto close;
     }
 
@@ -458,9 +447,8 @@ int main(int argc, char *argv[]) {
 #endif
             result = Tspi_GetPolicyObject(hKey, TSS_POLICY_USAGE, &hKeyPolicy);
             if (result != TSS_SUCCESS) {
-                printf
-                ("ERROR: Tspi_GetPolicyObject failed rc=0x%x\n",
-                 result);
+                ERROR("ERROR: Tspi_GetPolicyObject failed rc=0x%x\n",
+                      result);
                 goto close;
             }
 
@@ -484,9 +472,8 @@ int main(int argc, char *argv[]) {
                         (BYTE *) popupMsg);
 
             if (result != TSS_SUCCESS) {
-                printf
-                ("ERROR: Tspi_SetAttribData failed rc=0x%x\n",
-                 result);
+                ERROR("ERROR: Tspi_SetAttribData failed rc=0x%x\n",
+                      result);
                 goto close;
             }
 #endif
@@ -497,9 +484,8 @@ int main(int argc, char *argv[]) {
                                            0, NULL);
 
             if (result != TSS_SUCCESS) {
-                printf
-                ("ERROR: Tspi_Policy_SetSecret failed rc=0x%x @POPUP\n",
-                 result);
+                ERROR("ERROR: Tspi_Policy_SetSecret failed rc=0x%x @POPUP\n",
+                      result);
                 goto close;
             }
             // printf("POPUP\n");
@@ -511,9 +497,8 @@ int main(int argc, char *argv[]) {
                                           &hKeyPolicy);
 
             if (result != TSS_SUCCESS) {
-                printf
-                ("ERROR: Tspi_Context_CreateObject failed rc=0x%x\n",
-                 result);
+                ERROR("ERROR: Tspi_Context_CreateObject failed rc=0x%x\n",
+                      result);
                 goto close;
             }
             // PW
@@ -522,25 +507,23 @@ int main(int argc, char *argv[]) {
                 // ask
                 ps = getpass("Enter Key password: ");
                 size0 = strlen(ps);
-                ps0 = malloc(size0 + 1);
+                ps0 = xmalloc(size0 + 1);
                 ps0[size0] = 0;
                 memcpy(ps0, ps, size0);
                 ps1 = getpass("Confirm password: ");
                 size1 = strlen(ps1);
 
                 if (size0 != size1) {
-                    printf
-                    ("Passwords didn't match %d %d\n",
-                     size0, size1);
-                    free(ps0);
+                    printf(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_PASSWORD_MISMATCH, "Passwords didn't match %d %d\n"),
+                           size0, size1);
+                    xfree(ps0);
                     goto close;
                 }
 
                 if (strncmp(ps0, ps1, size0) != 0) {
-                    printf
-                    ("Passwords didn't match %d\n",
+                    printf(NLS(MS_OPENPTS, OPENPTS_TPM_CREATEKEY_PASSWORD_MISMATCH_2, "Passwords didn't match %d\n"),
                      strncmp(ps0, ps1, size0));
-                    free(ps0);
+                    xfree(ps0);
                     goto close;
                 }
 
@@ -553,7 +536,7 @@ int main(int argc, char *argv[]) {
                 /* flash */
                 memset(ps0, 0, size0);
                 memset(ps1, 0, size1);
-                free(ps0);
+                xfree(ps0);
             } else {
                 // commandine
                 int len2;
@@ -572,18 +555,16 @@ int main(int argc, char *argv[]) {
                                            len,
                                            (BYTE *) str);
             if (result != TSS_SUCCESS) {
-                printf
-                ("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
-                 result);
+                ERROR("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
+                      result);
                 goto close;
             }
 
             result = Tspi_Policy_AssignToObject(hKeyPolicy, hKey);
 
             if (result != TSS_SUCCESS) {
-                printf
-                ("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
-                 result);
+                ERROR("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
+                      result);
                 goto close;
             }
         }
@@ -592,8 +573,8 @@ int main(int argc, char *argv[]) {
     result = Tspi_Key_CreateKey(hKey, hSRK, 0);
 
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Key_CreateKey failed rc=0x%04x\n",
-               result);
+        ERROR("ERROR: Tspi_Key_CreateKey failed rc=0x%04x\n",
+              result);
         goto close;
     }
 
@@ -611,8 +592,8 @@ int main(int argc, char *argv[]) {
                      &keyBlob);
 
         if (result != TSS_SUCCESS) {
-            printf("ERROR: Tspi_GetAttribData failed rc=0x%04x\n",
-                   result);
+            ERROR("ERROR: Tspi_GetAttribData failed rc=0x%04x\n",
+                  result);
             fclose(fp);
             goto close;
         }
@@ -645,26 +626,22 @@ int main(int argc, char *argv[]) {
                                                    uuid,
                                                    &hKey);
                     if (result != TSS_SUCCESS) {
-                        printf
-                        ("ERROR: Tspi_Context_UnregisterKey failed rc=0x%x\n",
-                         result);
+                        ERROR("ERROR: Tspi_Context_UnregisterKey failed rc=0x%x\n",
+                              result);
                     } else {
                         /* try again */
                         goto regkey;
                     }
                 } else {
-                    printf
-                    ("ERROR: Tspi_Context_RegisterKey failed rc=0x%x\n",
-                     result);
-                    printf
-                    ("       TSS_E_KEY_ALREADY_REGISTERED\n");
+                    ERROR("ERROR: Tspi_Context_RegisterKey failed rc=0x%x\n",
+                          result);
+                    ERROR("       TSS_E_KEY_ALREADY_REGISTERED\n");
                     buf = (BYTE *) & uuid;
-                    printhex("       uuid=", buf, 16);
+                    printHex("       uuid=", buf, 16, "\n");
                 }
             } else {
-                printf
-                ("ERROR: Tspi_Context_RegisterKey failed rc=0x%x\n",
-                 result);
+                ERROR("ERROR: Tspi_Context_RegisterKey failed rc=0x%x\n",
+                      result);
             }
             goto close;
         } else {
@@ -672,14 +649,13 @@ int main(int argc, char *argv[]) {
         }
     }  // ps_type
 
-    if (verbose == 1) {
-        printhex("       uuid=", buf, 16);
+    if (getVerbosity() > 0) {
+        printHex("       uuid=", buf, 16, "\n");
     }
 
     /* Close TSS/TPM */
 
   close:
-    if (str != NULL) memset(str, 0, len);
     Tspi_Context_Close(hContext);
     return result;
 }
index 6cb431d..2b15cf2 100644 (file)
@@ -25,7 +25,7 @@
  * @author Seiji Munetoh <munetoh@users.sourceforge.jp>
  * @author Olivier Valentin <olivier.valentin@us.ibm.com>
  * @date 2011-03-15
- * cleanup 2011-07-06 SM
+ * cleanup 2011-10-07 SM
  *
  * Copy from tools v0.1.X
  *
@@ -52,7 +52,7 @@
 
 #include <openssl/sha.h>
 
-int verbose = 0;
+#include <openpts.h>
 
 // Local TCSD
 #define SERVER    NULL
@@ -94,7 +94,7 @@ int hex2bin(void *dest, const void *src, size_t n) {
     unsigned char *ussrc = (unsigned char *) src;
 
     if (n & 0x01) {
-        printf("ERROR: hex2bin wrong size %d\n", (int)n);
+        ERROR("ERROR: hex2bin wrong size %d\n", (int)n);
         return -1;
     }
 
@@ -125,24 +125,16 @@ int hex2bin(void *dest, const void *src, size_t n) {
     return i;
 }
 
-void printhex(char *str, unsigned char *buf, int len) {
-    int i;
-    printf("%s", str);
-    for (i = 0; i < len; i++)
-        printf("%02x", buf[i]);
-    printf("\n");
-}
-
-
 void usage(void) {
-    fprintf(stderr, "OpenPTS command\n\n");
-    fprintf(stderr, "Usage: tpm_extendpcr [options] filename\n\n");
-    fprintf(stderr, "  filename              file to be measured\n");
-    fprintf(stderr, "Options:\n");
-    fprintf(stderr, "  -p pcr_index          Set PCR index to extend\n");
-    fprintf(stderr, "  -t event_type         Set event type\n");
-    fprintf(stderr, "  -h                    Help\n");
-    fprintf(stderr, "\n");
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_USAGE,
+                    "OpenPTS command\n\n"
+                    "Usage: tpm_extendpcr [options] filename\n\n"
+                    "  filename              file to be measured\n"
+                    "Options:\n"
+                    "  -p pcr_index          Set PCR index to extend\n"
+                    "  -t event_type         Set event type\n"
+                    "  -h                    Help\n"
+                    "\n"));
 }
 
 
@@ -163,7 +155,6 @@ int main(int argc, char *argv[]) {
     char c;
     int pcrindex = 15;
     int eventtype = EV_FILE_SCAN_TSS;
-    int verbose = 0;
     SHA_CTX sha_ctx;
     int iml_mode = 0;
     int endian = 0;
@@ -174,6 +165,8 @@ int main(int argc, char *argv[]) {
     struct fileScan *fscan;
     struct stat     stat_buf;
 
+    initCatalog();
+
     /* parse the option args */
     while ((c = getopt(argc, argv, "f:p:d:t:IEAvh")) != EOF) {
         switch (c) {
@@ -193,7 +186,7 @@ int main(int argc, char *argv[]) {
             aligned = 1;
             break;
         case 'v':  /* verbose mode */
-            verbose = 1;
+            setVerbosity(1);
             break;
         case 'h':  /* help */
             usage();
@@ -217,26 +210,23 @@ int main(int argc, char *argv[]) {
     /* TSS open */
     result = Tspi_Context_Create(&hContext);
     if (result != TSS_SUCCESS) {
-        printf
-        ("ERROR: Tspi_Context_Create failed rc=0x%x\n",
-         result);
-        goto end;
+        ERROR("ERROR: Tspi_Context_Create failed rc=0x%x\n",
+              result);
+        goto close;
     }
 
     result = Tspi_Context_Connect(hContext, SERVER);
     if (result != TSS_SUCCESS) {
-        printf
-        ("ERROR: Tspi_Context_Connect failed rc=0x%x\n",
-         result);
+        ERROR("ERROR: Tspi_Context_Connect failed rc=0x%x\n",
+              result);
         goto close;
     }
 
     /* Get TPM handle */
     result = Tspi_Context_GetTpmObject(hContext, &hTPM);
     if (result != TSS_SUCCESS) {
-        printf
-        ("ERROR: Tspi_Context_GetTpmObject failed rc=0x%x\n",
-         result);
+        ERROR("ERROR: Tspi_Context_GetTpmObject failed rc=0x%x\n",
+              result);
         goto close;
     }
 
@@ -252,13 +242,14 @@ int main(int argc, char *argv[]) {
                                     &prgbRespData);
 
     if (result != TSS_SUCCESS) {
-        printf("ERROR: failed rc=0x%x\n", result);
+        ERROR("ERROR: failed rc=0x%x\n", result);
         goto close;
     }
 
-    pcrnum = (UINT32) * prgbRespData;
+    pcrnum = * (UINT32 *) prgbRespData;
     if (pcrindex > (int) pcrnum) {
-        printf("ERROR: pcrindex %d is out of range, this must be 0 to %d\n",
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_BAD_RANGE,
+            "ERROR: pcrindex %d is out of range, this must be 0 to %d\n"),
             pcrindex, pcrnum);
         goto close;
     }
@@ -269,16 +260,20 @@ int main(int argc, char *argv[]) {
         int fd;
         int eventCount = 0;
         TSS_PCR_EVENT pcrEvent;
+        void *fileMap;
+        off_t fileLength;
         void *current, *eof;
 
 
         if ((fd = open(filename, O_RDONLY)) < 0) {
-            fprintf(stderr, "file %s open fail\n", filename);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_EXTENDPCR_OPEN_FAIL,
+                "Failed to open file '%s'\n"), filename);
             goto close;
         }
 
         fileLength = lseek(fd, 0, SEEK_END);
         if (fileLength < 0) {
+            // WORK NEEDED: Please use NLS for i18n
             fprintf(stderr, "file %s seek fail\n", filename);
             goto close;
         }
@@ -321,12 +316,15 @@ int main(int argc, char *argv[]) {
                         &prgbPcrValue);
 
             if (result != TSS_SUCCESS) {
-                fprintf(stderr, "Failed to extend PCR at %d event, rc = 0x%04x\n", eventCount, result);
-                fprintf(stderr, " pcr index : %d\n", pcrEvent.ulPcrIndex);
-                fprintf(stderr, " eventtype : 0x%x\n", pcrEvent.eventType);
+                fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_FAILED,
+                    "Failed to extend PCR at event %d\n"), eventCount);
+                fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_INDEX,
+                    " pcr index: %d\n"), pcrEvent.ulPcrIndex);
+                fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_EVENT_TYPE,
+                    " event type: 0x%x\n"), pcrEvent.eventType);
                 exit(1);
             }
-            free(prgbPcrValue);
+            xfree(prgbPcrValue);
             // Tspi_Context_FreeMemory(hContext, NULL);
 
             if (aligned == 1) {
@@ -340,13 +338,15 @@ int main(int argc, char *argv[]) {
         munmap(fileMap, fileLength);
         close(fd);
 
-        if (verbose == 1) {
-            printf("Fed the TPM/log with %d events\n", eventCount);
+        if (getVerbosity() > 0) {
+            printf(NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_FED_TPM,
+                "Fed the TPM/log with %d events\n"), eventCount);
         }
     } else {
         /* File => mmap */
         if ((fd = open(filename, O_RDONLY)) < 0) {
-            fprintf(stderr, "file %s open fail\n", filename);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_EXTENDPCR_OPEN_FAIL,
+                "Failed to open file '%s'"), filename);
             goto close;
         }
 
@@ -359,13 +359,14 @@ int main(int argc, char *argv[]) {
 
         /* EV_SCAN_FILE */
         filename_len = strlen(filename);
-        fscan = malloc(40 + filename_len);
+        fscan = xmalloc(40 + filename_len);
         memset(fscan, 0, 40 + filename_len);
         fscan->filenameLength = filename_len;
         memcpy(fscan->filename, filename, filename_len);
 
         if (stat(filename, &stat_buf) != 0) {
-            fprintf(stderr, "stat fail\n");
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_EXTENDPCR_STAT_FAILED,
+                "Failed to retrieve file information for '%s'\n"), filename);
             exit(1);
         }
 
@@ -379,9 +380,9 @@ int main(int argc, char *argv[]) {
         SHA1_Update(&sha_ctx, fileMap, fileLength);
         SHA1_Final(fscan->fileDigest, &sha_ctx);
 
-        if (verbose == 1) {
-            printf("Filename : %s\n", filename);
-            printhex("Digest   : ", fscan->fileDigest, 20);
+        if (getVerbosity() > 0) {
+            printf(NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_FILENAME, "Filename: %s\n"), filename);
+            printHex(NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_DIGEST, "Digest: "), fscan->fileDigest, 20, "");
         }
 
         /* TSS_PCR_EVENT */
@@ -407,13 +408,15 @@ int main(int argc, char *argv[]) {
                                     &ulPcrValueLength,
                                     &rgbPcrValue);
         if (result != TSS_SUCCESS) {
-            printf("ERROR: failed rc=0x%x\n", result);
+            ERROR("ERROR: failed rc=0x%x\n", result);
             goto free;
         }
 
-        if (verbose == 1) {
-            printhex("EventData: ", (BYTE*)fscan, event.ulEventLength);
-            printhex("PcrValue : ", rgbPcrValue, ulPcrValueLength);
+        if (getVerbosity() > 0) {
+            printHex(NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_EVENT_DATA,
+                "EventData: "), (BYTE*)fscan, event.ulEventLength, "");
+            printHex(NLS(MS_OPENPTS, OPENPTS_TPM_EXTENDPCR_PCR_VALUE,
+                "PCR Value: "), rgbPcrValue, ulPcrValueLength, "");
         }
 
 
@@ -424,7 +427,7 @@ int main(int argc, char *argv[]) {
 
         /* TSS Free */
         Tspi_Context_FreeMemory(hContext, NULL);
-        // free(digest);
+        // xfree(digest);
     }
 
     /* TSS/TPM Close */
index 413e364..8c47a02 100644 (file)
 #include <tss/tss_error.h>
 #include <tss/tspi.h>
 
+#include <openpts_log.h>
+
 // Local TCSD
 #define SERVER    NULL
 
 #define MAX_PCRNUM 24  // TPM v1.2
 
-int verbose = 0;
-
 /*
 
  TPM PCR Read
@@ -65,7 +65,7 @@ int hex2bin(void *dest, const void *src, size_t n) {
     unsigned char *ussrc = (unsigned char *) src;
 
     if (n & 0x01) {
-        printf("ERROR: hex2bin wrong size %d\n", (int)n);
+        ERROR("ERROR: hex2bin wrong size %d\n", (int)n);
         return -1;
     }
 
@@ -123,15 +123,16 @@ void fprinthex2(FILE * fp, char *str, unsigned char *buf, int len) {
 
 
 void usage(void) {
-    fprintf(stderr, "OpenPTS command\n\n");
-    fprintf(stderr, "Usage: tpm_readpcr [options]\n\n");
-    fprintf(stderr, "Options:\n");
-    fprintf(stderr, "  -p pcr_index          Set PCR index to read\n");
-    fprintf(stderr, "  -a                    Show all PCRs value (default)\n");
-    fprintf(stderr, "  -k                    Display PCR same as kernel format (/sys/class/misc/tpm0/device/pcrs)\n");
-    fprintf(stderr, "  -o filename           Output to file (default is STDOUT)\n");
-    fprintf(stderr, "  -h                    Help\n");
-    fprintf(stderr, "\n");
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TPM_READPCR_USAGE,
+                    "OpenPTS command\n\n"
+                    "Usage: tpm_readpcr [options]\n\n"
+                    "Options:\n"
+                    "  -p pcr_index          Set PCR index to read\n"
+                    "  -a                    Show all PCRs value (default)\n"
+                    "  -k                    Display PCR same as kernel format (/sys/class/misc/tpm0/device/pcrs)\n"
+                    "  -o filename           Output to file (default is STDOUT)\n"
+                    "  -h                    Help\n"
+                    "\n"));
 }
 
 
@@ -156,6 +157,8 @@ int main(int argc, char *argv[]) {
     char *filename = NULL;
     FILE *fp = stdout;
 
+    initCatalog();
+
     memset(pcrSelect, 0, MAX_PCRNUM);
 
     /* we parse the option args */
@@ -194,15 +197,15 @@ int main(int argc, char *argv[]) {
 
     result = Tspi_Context_Create(&hContext);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Context_Create failed rc=0x%x\n",
-               result);
+        ERROR("ERROR: Tspi_Context_Create failed rc=0x%x\n",
+              result);
         goto close;
     }
 
     result = Tspi_Context_Connect(hContext, SERVER);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Context_Connect failed rc=0x%x\n",
-               result);
+        ERROR("ERROR: Tspi_Context_Connect failed rc=0x%x\n",
+              result);
         goto close;
     }
 
@@ -210,8 +213,8 @@ int main(int argc, char *argv[]) {
     /* Get TPM handles */
     result = Tspi_Context_GetTpmObject(hContext, &hTPM);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Context_GetTpmObject failed rc=0x%x\n",
-               result);
+        ERROR("ERROR: Tspi_Context_GetTpmObject failed rc=0x%x\n",
+              result);
         goto close;
     }
 
@@ -228,7 +231,7 @@ int main(int argc, char *argv[]) {
     pcrNum = *(UINT32 *) blob;
 
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_TPM_GetCapability failed rc=0x%x\n", result);
+        ERROR("ERROR: Tspi_TPM_GetCapability failed rc=0x%x\n", result);
         goto free;
     }
 
@@ -240,7 +243,7 @@ int main(int argc, char *argv[]) {
                                  &blob);
 
             if (result != TSS_SUCCESS) {
-                printf("ERROR: Tspi_TPM_PcrRead failed rc=0x%x\n", result);
+                ERROR("ERROR: Tspi_TPM_PcrRead failed rc=0x%x\n", result);
                 goto free;
             }
 
index f4792c9..8459d6b 100644 (file)
--- a/src/tss.c
+++ b/src/tss.c
@@ -27,7 +27,7 @@
  * @author Seiji Munetoh <munetoh@users.sourceforge.jp>
  * @date 2010-08-18
  * refactoring 2011-02-15 SM
- * cleanup 2011-07-20 SM
+ * cleanup 2011-10-07 SM
  *
  * Create Sign Key
  * Create AIK
@@ -46,6 +46,9 @@
 #include <string.h>
 
 #ifndef CONFIG_NO_TSS
+#ifdef AIX
+#include <trousers/tss.h>
+#else
 #include <platform.h>
 #include <tss_defines.h>
 #include <tss_typedef.h>
@@ -53,6 +56,7 @@
 #include <tss_error.h>
 #include <tspi.h>
 #endif
+#endif
 
 #include <openssl/sha.h>
 #include <openssl/rsa.h>
@@ -85,6 +89,11 @@ int deleteTssKey(PTS_UUID *uuid, int ps_type) {
     return TSS_SUCCESS;
 }
 
+int getTpmVersion(TSS_VERSION *version) {
+    /* dummy */
+    return TSS_SUCCESS;
+}
+
 int createAIK() {
     /* dummy */
     TODO("createAIK - TBD\n");
@@ -177,7 +186,7 @@ int getTpmStatus(TSS_FLAG flag, TSS_BOOL *value, int tpm_password_mode) {
         ERROR("Tspi_Context_Create failed rc=0x%x\n",
                result);
         if (result == 0x3011) {
-            printf(" TSS_E_COMM_FAILURE. tcsd is not running?\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE, "TSS communications failure. Is tcsd running?\n"));
         }
         goto close;
     }
@@ -268,7 +277,7 @@ int setTpmStatus(TSS_FLAG flag, TSS_BOOL value, int tpm_password_mode) {
         ERROR("Tspi_Context_Create failed rc=0x%x\n",
                result);
         if (result == 0x3011) {
-            printf(" TSS_E_COMM_FAILURE. tcsd is not running?\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE, "TSS communications failure. Is tcsd running?\n"));
         }
         goto close;
     }
@@ -328,7 +337,7 @@ int setTpmStatus(TSS_FLAG flag, TSS_BOOL value, int tpm_password_mode) {
                 flag,  // TSS_TPMSTATUS_RESETLOCK,
                 value);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Policy_SetSecret failed rc=0x%x, TPM requires ownerauth, use tpm_resetdalock command\n",
+        ERROR("Tspi_Policy_SetSecret failed rc=0x%x\n",
                result);
         goto close;
     }
@@ -368,6 +377,9 @@ int printTssKeyList(int ps_type) {
     }
 
     /* List */
+    // buf = (BYTE *) & SRK_UUID;
+    // printhex("SRK uuid: ", buf, 16);
+
     result = Tspi_Context_GetRegisteredKeysByUUID(
                 hContext,
                 (UINT32) ps_type,  // TSS_PS_TYPE_SYSTEM,
@@ -380,9 +392,9 @@ int printTssKeyList(int ps_type) {
         goto close;
     }
 
-    printf("Key number   : %d\n", ulKeyHierarchySize);
+    OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_KEY_NUM, "Key number: %d\n"), ulKeyHierarchySize);
     for (i = 0; i < (int)ulKeyHierarchySize; i++) {
-        printf("Key %d\n", i);
+        OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_KEY, "Key %d\n"), i);
         info = info + 1;
     }
 
@@ -674,7 +686,7 @@ int getTssPubKey(
     if (resetdalock == 1) {
         // 2011-03-03 SM WEC TPM locks well.
         // TSS_TPMSTATUS_RESETLOCK is read only. no way to get this FLAG before 0x803 Error? :-(
-        // Thus, control by ptscd.conf
+        // Thus, control by ptsc.conf
         DEBUG("TSS_TPMSTATUS_RESETLOCK\n");
         setTpmStatus(TSS_TPMSTATUS_RESETLOCK, TRUE, srk_password_mode);
     }
@@ -710,8 +722,10 @@ int getTssPubKey(
          result);
         if (result == 0x2020) {
             ERROR(" TSS_E_PS_KEY_NOT_FOUND.\n");
-            ERROR("  check system_ps_file setting in /etc/tcsd.conf. (default is /var/lib/tpm/system.data)\n");
-            ERROR(" If system_ps_file size is zero. it does not contains SRK info \n");
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TSS_CHECK_SETTING,
+                "Please check your system_ps_file setting in /etc/security/tss/tcsd.conf. "
+                "(The default is /var/tss/lib/tpm/system.data)\n"
+                "If system_ps_file size is zero then it does not contain the SRK info\n"));
         }
 
         goto close;
@@ -782,12 +796,13 @@ int getTssPubKey(
                     tss_uuid,
                     &hKey);
         if (result == 0x803) {
-            ERROR("TPM is locked. use 'tpm_resetdalock' command to clear the lock\n");
-            ERROR("For the ptsc, set the flag, 'tpm.resetdalock=on' in /etc/ptsc.conf, or use tpm_resetdalock command");
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TSS_TPM_LOCKED,
+                        "The TPM is locked. Please use the 'tpm_resetdalock' command to clear the lock\n"
+                        "For the ptscd daemon please set the flag 'tpm.resetdalock=on' in /etc/ptsc.conf\n"));
             goto close;
         } else if (result != TSS_SUCCESS) {
             ERROR("Tspi_Context_LoadKeyByUUID (Key) failed rc=0x%x\n", result);
-            printHex("\t\tUUID", (BYTE*)&tss_uuid, 16, "\n");
+            debugHex("\t\tUUID", (BYTE*)&tss_uuid, 16, "\n");
 
             goto close;
         }
@@ -809,7 +824,7 @@ int getTssPubKey(
                 0,  // ""
                 key_auth);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
+        ERROR("Tspi_Policy_SetSecret failed rc=0x%x\n",
                result);
         goto close;
     }
@@ -824,16 +839,16 @@ int getTssPubKey(
                                 (UINT32 *) pubkey_length,
                                 &buf);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_GetAttribData failed rc=0x%x\n",
+        ERROR("Tspi_GetAttribData failed rc=0x%x\n",
                result);
         goto free;
     }
     /* copy to local */
     if (*pubkey != NULL) {
         // DEBUG("realloc conf->pubkey\n");  // TODO realloc happen
-        free(*pubkey);
+        xfree(*pubkey);
     }
-    *pubkey = malloc(*pubkey_length);
+    *pubkey = xmalloc_assert(*pubkey_length);
     memcpy(*pubkey, buf, *pubkey_length);
 
 
@@ -866,7 +881,7 @@ int getTpmVersion(TSS_VERSION *version) {
         ERROR("Tspi_Context_Create failed rc=0x%x\n",
                result);
         if (result == 0x3011) {
-            printf(" TSS_E_COMM_FAILURE. tcsd is not running?\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE, "TSS communications failure. Is tcsd running?\n"));
         }
         rc = (int)result;
         goto close;
@@ -976,7 +991,7 @@ int quoteTss(
         ERROR("Tspi_Context_Create failed rc=0x%x\n",
                result);
         if (result == 0x3011) {
-            printf(" TSS_E_COMM_FAILURE. tcsd is not running?\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE, "TSS communications failure. Is tcsd running?\n"));
         }
 
         goto close;
@@ -1037,7 +1052,7 @@ int quoteTss(
                         hPcrComposite,
                         i);
             if (result != TSS_SUCCESS) {
-                    printf("ERROR: failed rc=0x%x\n", result);
+                    ERROR("failed rc=0x%x\n", result);
                     goto close;
             }
             pcrSelectCount++;
@@ -1061,8 +1076,10 @@ int quoteTss(
          result);
         if (result == 0x2020) {
             ERROR(" TSS_E_PS_KEY_NOT_FOUND.\n");
-            ERROR("  check system_ps_file setting in /etc/tcsd.conf. (default is /var/lib/tpm/system.data)\n");
-            ERROR(" If system_ps_file size is zero. it does not contains SRK info \n");
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TSS_CHECK_SETTING,
+                "Please check your system_ps_file setting in /etc/tcsd.conf. "
+                "(The default is /var/lib/tpm/system.data)\n"
+                "If system_ps_file size is zero then it does not contains the SRK info\n"));
         }
 
         goto close;
@@ -1133,7 +1150,7 @@ int quoteTss(
                                             &hKey);
         if (result != TSS_SUCCESS) {
             ERROR("Tspi_Context_LoadKeyByUUID (Key) failed rc=0x%x\n", result);
-            printHex("\t\tUUID", (BYTE*)&tss_uuid, 16, "\n");
+            debugHex("\t\tUUID", (BYTE*)&tss_uuid, 16, "\n");
 
             goto close;
         }
@@ -1143,7 +1160,7 @@ int quoteTss(
     result = Tspi_GetPolicyObject(hKey, TSS_POLICY_USAGE, &hKeyPolicy);
     if (result != TSS_SUCCESS) {
         ERROR("Tspi_GetPolicyObject failed rc=0x%x\n",
-               result);
+              result);
         goto close;
     }
 
@@ -1154,7 +1171,7 @@ int quoteTss(
                 0,  // ""
                 key_auth);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
+        ERROR("Tspi_Policy_SetSecret failed rc=0x%x\n",
                result);
         goto close;
     }
@@ -1195,9 +1212,8 @@ int quoteTss(
     //   NONCE[20]
     // total 48-bytes
     validationData->ulDataLength = validation_data.ulDataLength;
-    validationData->rgbData = malloc(validation_data.ulDataLength);
+    validationData->rgbData = xmalloc(validation_data.ulDataLength);
     if (validationData->rgbData == NULL) {
-        ERROR("no memory");
         result = PTS_FATAL;
         goto free;
     }
@@ -1210,9 +1226,8 @@ int quoteTss(
     // 2011-02-09 SM bad approach
     /* rgbData */
     validationData->ulDataLength = 20;
-    validationData->rgbData = malloc(20);
+    validationData->rgbData = xmalloc(20);
     if (validationData->rgbData == NULL) {
-        ERROR("no memory");
         result = PTS_FATAL;
         goto free;
     }
@@ -1225,9 +1240,8 @@ int quoteTss(
 
     /* rgbValidationData */
     validationData->ulValidationDataLength = validation_data.ulValidationDataLength;
-    validationData->rgbValidationData = malloc(validation_data.ulValidationDataLength);
+    validationData->rgbValidationData = xmalloc(validation_data.ulValidationDataLength);
     if (validationData->rgbValidationData == NULL) {
-        ERROR("no memory");
         result = PTS_FATAL;
         goto free;
     }
@@ -1243,9 +1257,9 @@ int quoteTss(
     validationData->versionInfo.bRevMinor = validationData->rgbData[3];
 
 
-    if (verbose & DEBUG_FLAG) {
+    if (isDebugFlagSet(DEBUG_FLAG)) {
         DEBUG("TPM_Quote\n");
-        printHex("   validationData :",
+        debugHex("   validationData :",
             validationData->rgbData,
             validationData->ulDataLength, "\n");
     }
@@ -1270,9 +1284,9 @@ int quoteTss(
             // fprinthex(fp, "", data, length);
             if (length < MAX_DIGEST_SIZE) {
                 memcpy(&pcrs->pcr[i], data, length);
-                if (verbose & DEBUG_FLAG) {
+                if (isDebugFlagSet(DEBUG_FLAG)) {
                     // DEBUG("PCR[%d]", i);
-                    printHex("             : ", data, length, "\n");
+                    debugHex("             : ", data, length, "\n");
                 }
             } else {
                 ERROR("pcr size is too big %d >  %d\n", length, MAX_DIGEST_SIZE);
@@ -1293,7 +1307,6 @@ int quoteTss(
     Tspi_Context_CloseObject(hContext, hSRKPolicy);
     Tspi_Context_CloseObject(hContext, hSRK);
     Tspi_Context_CloseObject(hContext, hTPM);
-    // free(nonce);
 
     /* Close TSS/TPM */
   close:
@@ -1358,7 +1371,7 @@ int quote2Tss(
         ERROR("Tspi_Context_Create failed rc=0x%x\n",
                result);
         if (result == 0x3011) {
-            printf(" TSS_E_COMM_FAILURE. tcsd is not running?\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE, "TSS communications failure. Is tcsd running?\n"));
         }
 
         goto close;
@@ -1421,7 +1434,7 @@ int quote2Tss(
                         i,
                         TSS_PCRS_DIRECTION_RELEASE);
             if (result != TSS_SUCCESS) {
-                    printf("ERROR: failed rc=0x%x\n", result);
+                    ERROR("failed rc=0x%x\n", result);
                     goto close;
             }
             pcrSelectCount++;
@@ -1445,8 +1458,10 @@ int quote2Tss(
          result);
         if (result == 0x2020) {
             ERROR(" TSS_E_PS_KEY_NOT_FOUND.\n");
-            ERROR("  check system_ps_file setting in /etc/tcsd.conf. (default is /var/lib/tpm/system.data)\n");
-            ERROR(" If system_ps_file size is zero. it does not contains SRK info \n");
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TSS_CHECK_SETTING,
+                "Please check your system_ps_file setting in /etc/tcsd.conf. "
+                "(The default is /var/lib/tpm/system.data)\n"
+                "If system_ps_file size is zero then it does not contains the SRK info\n"));
         }
 
         goto close;
@@ -1516,7 +1531,7 @@ int quote2Tss(
                                             &hKey);
         if (result != TSS_SUCCESS) {
             ERROR("Tspi_Context_LoadKeyByUUID (Key) failed rc=0x%x\n", result);
-            printHex("\t\tUUID", (BYTE*)&tss_uuid, 16, "\n");
+            debugHex("\t\tUUID", (BYTE*)&tss_uuid, 16, "\n");
 
             goto close;
         }
@@ -1537,7 +1552,7 @@ int quote2Tss(
                 0,
                 key_auth);
     if (result != TSS_SUCCESS) {
-        printf("ERROR: Tspi_Policy_SetSecret failed rc=0x%x\n",
+        ERROR("Tspi_Policy_SetSecret failed rc=0x%x\n",
                result);
         goto close;
     }
@@ -1557,30 +1572,30 @@ int quote2Tss(
                 &versionInfo);
     if (result != TSS_SUCCESS) {
         if (result == 0x01) {
-            ERROR("Tspi_TPM_Quote failed rc=0x%04x\n",
-                   result);
-            ERROR("       Authorization faild, needs valid password\n");
+            ERROR("Tspi_TPM_Quote failed rc=0x%04x\n", result);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TSS_AUTH_FAILED, "Authorization failed, needs valid password\n"));
         } else {
-            ERROR("Tspi_TPM_Quote failed rc=0x%04x\n",
-                   result);
+            ERROR("Tspi_TPM_Quote failed rc=0x%04x\n", result);
         }
         goto free;
     }
 
-    if (verbose & DEBUG_FLAG) {
+    if (isDebugFlagSet(DEBUG_FLAG)) {
         DEBUG("TPM_Quote2\n");
-        printHex("   externalData   :",
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_EXT_DATA, "External Data:"),
             validation_data.rgbExternalData,
             validation_data.ulExternalDataLength, "\n");
-        printHex("   Data           :",
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_DATA, "Data:"),
             validation_data.rgbData,
             validation_data.ulDataLength, "\n");
-        printHex("   validationData :",
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_VALIDATION_DATA, "Validation Data:"),
             validation_data.rgbValidationData,
             validation_data.ulValidationDataLength, "\n");
-        printHex("   versionInfo    :",
-            versionInfo,
-            versionInfoSize, "\n");
+        if (versionInfoSize > 0) {
+            debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_VERSION_INFO, "Version Info:"),
+                versionInfo,
+                versionInfoSize, "\n");
+        }
     }
 
     /* Get PCR values used by Quote */
@@ -1603,20 +1618,20 @@ int quote2Tss(
             result = Tspi_TPM_PcrRead(
                 hTPM, i, &length, &data);
             if (result != TSS_SUCCESS) {
-                ERROR("Tspi_TPM_PcrRead failed rc=0x%x\n",
-                        result);
+                ERROR("Tspi_TPM_PcrRead failed rc=0x%x\n", result);
                 goto free;
             }
 #endif
 
             if (length < MAX_DIGEST_SIZE) {
                 memcpy(&pcrs->pcr[i], data, length);
-                if (verbose & DEBUG_FLAG) {
+                if (isDebugFlagSet(DEBUG_FLAG)) {
                     // DEBUG("PCR[%d]", i);
-                    printHex("             : ", data, length, "\n");
+                    debugHex("             : ", data, length, "\n");
                 }
             } else {
-                ERROR("pcr size is too big %d >  %d\n", length, MAX_DIGEST_SIZE);
+                fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_TSS_PCR_SIZE_TOO_BIG,
+                    "PCR size is too big %d > %d\n"), length, MAX_DIGEST_SIZE);
             }
 
             Tspi_Context_FreeMemory(hContext, data);
@@ -1648,9 +1663,8 @@ int quote2Tss(
     // 2+4+20+5+1+20 = 52
     // total 75-bytes???
     validationData->ulDataLength = validation_data.ulDataLength;
-    validationData->rgbData = malloc(validation_data.ulDataLength);
+    validationData->rgbData = xmalloc(validation_data.ulDataLength);
     if (validationData->rgbData == NULL) {
-        ERROR("no memory");
         result = PTS_FATAL;
         goto free;
     }
@@ -1662,9 +1676,8 @@ int quote2Tss(
 
     /* rgbValidationData */
     validationData->ulValidationDataLength = validation_data.ulValidationDataLength;
-    validationData->rgbValidationData = malloc(validation_data.ulValidationDataLength);
+    validationData->rgbValidationData = xmalloc(validation_data.ulValidationDataLength);
     if (validationData->rgbValidationData == NULL) {
-        ERROR("no memory");
         result = PTS_FATAL;
         goto free;
     }
@@ -1687,7 +1700,6 @@ int quote2Tss(
     Tspi_Context_FreeMemory(hContext, NULL);
     Tspi_Context_CloseObject(hContext, hPcrComposite);
     Tspi_Context_CloseObject(hContext, hKey);
-    // free(nonce);
 
     /* Close TSS/TPM */
   close:
@@ -1715,26 +1727,23 @@ int getRandom(BYTE *out, int size) {
     /* Connect to TCSD */
     result = Tspi_Context_Create(&hContext);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_Create failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_Create failed rc=0x%x\n", result);
         if (result == 0x3011) {
-            printf(" TSS_E_COMM_FAILURE. tcsd is not running?\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE, "TSS communications failure. Is tcsd running?\n"));
         }
         goto close;
     }
 
     result = Tspi_Context_Connect(hContext, SERVER);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_Connect failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_Connect failed rc=0x%x\n", result);
         goto close;
     }
 
     /* Get TPM handle */
     result = Tspi_Context_GetTpmObject(hContext, &hTPM);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_GetTpmObject failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_GetTpmObject failed rc=0x%x\n", result);
         goto close;
     }
 
@@ -1742,17 +1751,17 @@ int getRandom(BYTE *out, int size) {
     /* get Random*/
     result = Tspi_TPM_GetRandom(hTPM, size, &buf);
     if (result != TSS_SUCCESS) {
-            printf
-                ("ERROR: Tspi_TPM_GetRandom failed rc=0x%x\n",
+            ERROR
+                ("Tspi_TPM_GetRandom failed rc=0x%x\n",
                  result);
             Tspi_Context_FreeMemory(hContext, NULL);
             goto free;
     }
     memcpy(out, buf, size);
 
-    DEBUG("Get ramdom from TPM");
-    if (verbose & DEBUG_FLAG) {
-        printHex(" - random:", buf, size, "\n");
+    DEBUG("Get ramdom data from TPM");
+    if (isDebugFlagSet(DEBUG_FLAG)) {
+        debugHex(" - random:", buf, size, "\n");
     }
 
   free:
@@ -1780,31 +1789,28 @@ int extendEvent(TSS_PCR_EVENT* event) {
     /* Connect to TCSD */
     result = Tspi_Context_Create(&hContext);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_Create failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_Create failed rc=0x%x\n", result);
         if (result == 0x3011) {
-            printf(" TSS_E_COMM_FAILURE. tcsd is not running?\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE, "TSS communications failure. Is tcsd running?\n"));
         }
         goto close;
     }
 
     result = Tspi_Context_Connect(hContext, SERVER);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_Connect failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_Connect failed rc=0x%x\n", result);
         goto close;
     }
 
     /* Get TPM handle */
     result = Tspi_Context_GetTpmObject(hContext, &hTPM);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_GetTpmObject failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_GetTpmObject failed rc=0x%x\n", result);
         goto close;
     }
 
     // 2011-02-21 SM pcr0=NULL -> 0x3003 BAD_PARAMETOR error
-    pcr0 = malloc(20);
+    pcr0 = xmalloc_assert(20);
     memset(pcr0, 0, 20);
 
     /* Extend */
@@ -1817,15 +1823,15 @@ int extendEvent(TSS_PCR_EVENT* event) {
                 &pcr_len,
                 &pcr);
     if (result != TSS_SUCCESS) {
-            printf
-                ("ERROR: Tspi_TPM_PcrExtend failed rc=0x%x\n",
+            ERROR
+                ("Tspi_TPM_PcrExtend failed rc=0x%x\n",
                  result);
             // Tspi_Context_FreeMemory(hContext, NULL);
             goto close;
     }
 
     // TODO free some?
-    free(pcr0);
+    xfree(pcr0);
 
   close:
     /* Close TSS/TPM */
@@ -1848,34 +1854,30 @@ int readPcr(int pcr_index, BYTE *pcr) {
     /* Connect to TCSD */
     result = Tspi_Context_Create(&hContext);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_Create failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_Create failed rc=0x%x\n", result);
         if (result == 0x3011) {
-            printf(" TSS_E_COMM_FAILURE. tcsd is not running?\n");
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_TPM_TSS_COMMS_FAILURE, "TSS communications failure. Is tcsd running?\n"));
         }
         goto close;
     }
 
     result = Tspi_Context_Connect(hContext, SERVER);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_Connect failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_Connect failed rc=0x%x\n", result);
         goto close;
     }
 
     /* Get TPM handle */
     result = Tspi_Context_GetTpmObject(hContext, &hTPM);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_Context_GetTpmObject failed rc=0x%x\n",
-               result);
+        ERROR("Tspi_Context_GetTpmObject failed rc=0x%x\n", result);
         goto close;
     }
 
     result = Tspi_TPM_PcrRead(
         hTPM, pcr_index, &data_len, &data);
     if (result != TSS_SUCCESS) {
-        ERROR("Tspi_TPM_PcrRead failed rc=0x%x\n",
-                result);
+        ERROR("Tspi_TPM_PcrRead failed rc=0x%x\n", result);
         goto close;
     }
     if (data_len != SHA1_DIGEST_SIZE) {
@@ -1925,8 +1927,6 @@ int validateQuoteData(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData) {
     BIGNUM *rsa_e = NULL;
     BIGNUM *rsa_n = NULL;
     BYTE exp[4] = {0x00, 0x01, 0x00, 0x01};
-    char *rsa_e_hex = NULL;
-    char *rsa_n_hex = NULL;
 
     /* check */
     if (pcrs == NULL) {
@@ -1964,7 +1964,7 @@ int validateQuoteData(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData) {
 
     /* hash */
     hash_length = 20;  // TODO
-    hash = malloc(20);
+    hash = xmalloc_assert(20);
     SHA1_Init(&ctx);
     SHA1_Update(&ctx, message, message_length);
     SHA1_Final(hash, &ctx);
@@ -2019,11 +2019,8 @@ int validateQuoteData(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData) {
     rsa_n = BN_new();
     BN_bin2bn(pubkey, pubkey_length, rsa_n);
 
-    rsa_e_hex = BN_bn2hex(rsa_e);
-    rsa_n_hex = BN_bn2hex(rsa_n);
-
-    BN_hex2bn(&(rsa->n), rsa_n_hex);
-    BN_hex2bn(&(rsa->e), rsa_e_hex);
+    BN_hex2bn(&(rsa->n), BN_bn2hex(rsa_n));
+    BN_hex2bn(&(rsa->e), BN_bn2hex(rsa_e));
 
     // DEBUG("RSA_verify\n");
     /* RSA verify  1: success, 0:otherwise */
@@ -2039,23 +2036,21 @@ int validateQuoteData(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData) {
     RSA_free(rsa);
     BN_free(rsa_e);
     BN_free(rsa_n);
-    OPENSSL_free(rsa_e_hex);
-    OPENSSL_free(rsa_n_hex);
 
     if (hash != NULL) {
-        free(hash);
+        xfree(hash);
     }
 
     /* DEBUG */
-    if (verbose & DEBUG_FLAG) {
+    if (isDebugFlagSet(DEBUG_FLAG)) {
         DEBUG("validateQuoteData - rc = %d (1:success)\n", rc);
-        printHex("pubkey    : ", pubkey, pubkey_length, "\n");
-        printHex("message   : ", message, message_length, "\n");
-        printHex("signature : ", signature, signature_length, "\n");
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_PUBKEY, "pubkey: "), pubkey, pubkey_length, "\n");
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_MSG, "message: "), message, message_length, "\n");
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_SIGNATURE, "signature: "), signature, signature_length, "\n");
     }
 
     /**/
-    // free(message);
+    // xfree(message);
 
     if (rc == 1) {
         /* RSA verify - success */
@@ -2065,7 +2060,7 @@ int validateQuoteData(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData) {
         UINT32 e;  // unsigned long
         ERR_load_crypto_strings();
         e = ERR_get_error();
-        ERROR("RSA_verify fail, %s\n", ERR_error_string(e, NULL));
+        ERROR("RSA_verify failed, %s\n", ERR_error_string(e, NULL));
         ERROR("   %s\n", ERR_lib_error_string(e));
         ERROR("   %s\n", ERR_func_error_string(e));
         ERROR("   %s\n", ERR_reason_error_string(e));
@@ -2131,9 +2126,8 @@ int validatePcrCompositeV11(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData)
     /* set ValueSize */
     value_size = 20 * count;
     buf_len = 2 + 2 + 4 + value_size;
-    buf = malloc(buf_len);
+    buf = xmalloc(buf_len);
     if (buf == NULL) {
-        ERROR("no memory\n");
         return PTS_INTERNAL_ERROR;
     }
     memset(buf, 0, buf_len);
@@ -2166,10 +2160,10 @@ int validatePcrCompositeV11(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData)
     SHA1_Update(&ctx, buf, buf_len);
     SHA1_Final(digest, &ctx);
 
-    if (verbose & DEBUG_FLAG) {
-        DEBUG("pcr composit\n");
-        printHex("   buf    :", buf, buf_len, "\n");
-        printHex("   digest :", digest, 20, "\n");
+    if (isDebugFlagSet(DEBUG_FLAG)) {
+        DEBUG("pcr composite\n");
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_BUF, "   buf:"), buf, buf_len, "\n");
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_DIGEST, "   digest:"), digest, 20, "\n");
         DEBUG("select size : %d\n", 2);
         DEBUG("select      : 0x%X\n", mask);
     }
@@ -2199,7 +2193,7 @@ int validatePcrCompositeV11(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData)
 
 
     /* free */
-    free(buf);
+    xfree(buf);
 
     return rc;
 }
@@ -2286,9 +2280,8 @@ int validatePcrCompositeV12(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData)
     /* set ValueSize */
     value_size = 20 * count;
     buf_len = 2 + pcrsel_size + 4 + value_size;
-    buf = malloc(buf_len);
+    buf = xmalloc(buf_len);
     if (buf == NULL) {
-        ERROR("no memory\n");
         return PTS_INTERNAL_ERROR;
     }
     memset(buf, 0, buf_len);
@@ -2324,10 +2317,10 @@ int validatePcrCompositeV12(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData)
     SHA1_Update(&ctx, buf, buf_len);
     SHA1_Final(digest, &ctx);
 
-    if (verbose & DEBUG_FLAG) {
+    if (isDebugFlagSet(DEBUG_FLAG)) {
         DEBUG("PcrComposit\n");
-        printHex("buf    :", buf, buf_len, "\n");
-        printHex("digest :", digest, 20, "\n");
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_BUF, "   buf:"), buf, buf_len, "\n");
+        debugHex(NLS(MS_OPENPTS, OPENPTS_TSS_DIGEST, "   digest:"), digest, 20, "\n");
         DEBUG("PcrComposit - select size   : %d\n", pcrsel_size);
         DEBUG("PcrComposit - bit mask      : 0x%08X\n", mask);
     }
@@ -2339,9 +2332,9 @@ int validatePcrCompositeV12(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData)
         rc = PTS_SUCCESS;
     } else {
         DEBUG("validatePcrCompositeV12() - bad digest\n");
-        if (verbose & DEBUG_FLAG) {
-            printHex("  calc    :", digest, 20, "\n");
-            printHex("  given   :", composit_hash, 20, "\n");
+        if (isDebugFlagSet(DEBUG_FLAG)) {
+            debugHex("  calc    :", digest, 20, "\n");
+            debugHex("  given   :", composit_hash, 20, "\n");
         }
     }
 
@@ -2352,7 +2345,7 @@ int validatePcrCompositeV12(OPENPTS_PCRS *pcrs, TSS_VALIDATION *validationData)
     }
 
     /* free */
-    free(buf);
+    xfree(buf);
 
     return rc;
 }
index ea2a1b4..b7d952d 100644 (file)
--- a/src/uml.c
+++ b/src/uml.c
@@ -47,6 +47,7 @@
 #include <tss/tspi.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 /*
 
@@ -107,7 +108,7 @@ void    uml2sax_endDocument(void * fctx) {
     // TODO(munetoh) ID must be "Start"
     ctx->curr_state = getSubvertex(ctx, "Start");
     if (ctx->curr_state == NULL) {
-        printf("ERROR Start state is missing\n");
+        ERROR("Start state is missing\n");
     }
 
     DEBUG_CAL("endDocument - done\n");
@@ -328,7 +329,7 @@ int readUmlModel(OPENPTS_FSM_CONTEXT * ctx, char *umlfile) {
     } else {
         /* delete previos one if exist */
         /* copy */
-        ctx->uml_file = smalloc(umlfile);
+        ctx->uml_file = smalloc_assert(umlfile);
         DEBUG_CAL("readUmlModel - done\n");
         return ctx->error;  // Success (0) or ERROR of IR if exist
     }
index 480b140..8d2f956 100644 (file)
 #include <string.h>
 #include <netdb.h>
 #include <errno.h>
-
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <unistd.h>
-
 #include <sys/stat.h>
 #include <fcntl.h>
 
 #include <openpts.h>
-
-int verbose = 0; /**< DEBUG  */
+// #include <log.h>
 
 /**
  * usage
  */
 void usage(void) {
-    fprintf(stderr, "usage: uml2dot [options] UMLfile \n");
-    fprintf(stderr, "\t-o output\tset output file (default is stdout)\n");
-    fprintf(stderr, "\t$ dot -Tpng foo.dot -o foo.png; eog foo.png\n");
-
-    fprintf(stderr, "\n");
+    fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_UML2DOT_USAGE,
+            "usage: uml2dot [options] UMLfile \n"
+            "\t-o output\tset output file (default is stdout)\n"
+            "\t$ dot -Tpng foo.dot -o foo.png; eog foo.png\n"
+            "\n"));
 }
 
 /**
@@ -70,13 +67,12 @@ int main(int argc, char *argv[]) {
     char *input_filename = NULL;
     char *output_filename = NULL;
 
-    verbose = 0;
+    initCatalog();
 
     while ((c = getopt(argc, argv, "do:h")) != EOF) {
         switch (c) {
         case 'd':
-            verbose = 1;
-
+            setVerbosity(1);
             break;
         case 'o':
             output_filename = optarg;
@@ -95,7 +91,7 @@ int main(int argc, char *argv[]) {
     /* Read UML(XML) file */
 
     if (input_filename == NULL) {
-        printf("ERROR missing XMLfile\n");
+        printf(NLS(MS_OPENPTS, OPENPTS_UML2DOT_MISSING_XML_FILE, "ERROR missing XMLfile\n"));
         usage();
         return -1;
     }
@@ -105,7 +101,7 @@ int main(int argc, char *argv[]) {
     rc = readUmlModel(ctx, argv[0]);
 
     if (rc != 0) {
-        printf("ERROR\n");
+        ERROR("ERROR\n");
         goto error;
     }
 
@@ -113,7 +109,7 @@ int main(int argc, char *argv[]) {
     rc = writeDotModel(ctx, output_filename);
 
     if (rc != 0) {
-        printf("ERROR\n");
+        ERROR("ERROR\n");
         goto error;
     }
 
index 8933b8d..6f63322 100644 (file)
@@ -26,7 +26,7 @@
  * \brief UUID wrapper (Generic part, OPENPTS_UUID)
  * @author Seiji Munetoh <munetoh@users.sourceforge.jp>
  * @date 2010-11-29
- * cleanup 2011-07-06 SM
+ * cleanup 2011-10-07 SM
  *
  * Linux uses libuuid
  *
@@ -80,9 +80,8 @@
 OPENPTS_UUID *newOpenptsUuid() {
     OPENPTS_UUID *uuid;
 
-    uuid = malloc(sizeof(OPENPTS_UUID));  // BYTE[16]
+    uuid = xmalloc(sizeof(OPENPTS_UUID));  // BYTE[16]
     if (uuid == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memset(uuid, 0, sizeof(OPENPTS_UUID));
@@ -98,14 +97,13 @@ OPENPTS_UUID *newOpenptsUuid() {
 OPENPTS_UUID *newOpenptsUuid2(PTS_UUID *pts_uuid) {
     OPENPTS_UUID *uuid;
 
-    uuid = malloc(sizeof(OPENPTS_UUID));  // BYTE[16]
+    uuid = xmalloc(sizeof(OPENPTS_UUID));  // BYTE[16]
     if (uuid == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memset(uuid, 0, sizeof(OPENPTS_UUID));
 
-    uuid->uuid = malloc(16);
+    uuid->uuid = xmalloc_assert(16);
     memcpy(uuid->uuid, pts_uuid, 16);
 
     uuid->str    = getStringOfUuid(uuid->uuid);
@@ -126,12 +124,11 @@ OPENPTS_UUID *newOpenptsUuidFromFile(char * filename) {
 
     uuid = newOpenptsUuid();
     if (uuid == NULL) {
-        ERROR("no memory");
         return NULL;
     }
 
     /* set the filename */
-    uuid->filename = smalloc(filename);
+    uuid->filename = smalloc_assert(filename);
 
     /* load the filename */
     rc = readOpenptsUuidFile(uuid);
@@ -155,19 +152,19 @@ void freeOpenptsUuid(OPENPTS_UUID *uuid) {
     }
 
     if (uuid->filename != NULL) {
-        free(uuid->filename);
+        xfree(uuid->filename);
     }
     if (uuid->uuid  != NULL) {
-        free(uuid->uuid);
+        xfree(uuid->uuid);
     }
     if (uuid->str  != NULL) {
-        free(uuid->str);
+        xfree(uuid->str);
     }
     if (uuid->time  != NULL) {
-        free(uuid->time);
+        xfree(uuid->time);
     }
 
-    free(uuid);
+    xfree(uuid);
 }
 
 /**
@@ -178,12 +175,7 @@ void freeOpenptsUuid(OPENPTS_UUID *uuid) {
  */
 int genOpenptsUuid(OPENPTS_UUID *uuid) {
     /* check */
-    if (uuid == NULL) {
-        ERROR("\n");
-        return PTS_INTERNAL_ERROR;
-    }
-
-
+    ASSERT(NULL != uuid, "uuid is NULL\n");
 
     /* check the status */
     if (uuid->status == OPENPTS_UUID_EMPTY) {
@@ -211,9 +203,15 @@ int genOpenptsUuid(OPENPTS_UUID *uuid) {
 
 
     /* free */
-    if (uuid->uuid != NULL) free(uuid->uuid);
-    if (uuid->str != NULL) free(uuid->str);
-    if (uuid->time != NULL) free(uuid->time);
+    if (uuid->uuid != NULL) {
+        xfree(uuid->uuid);
+    }
+    if (uuid->str != NULL) {
+        xfree(uuid->str);
+    }
+    if (uuid->time != NULL) {
+        xfree(uuid->time);
+    }
 
     /* set */
     uuid->uuid = newUuid();
@@ -260,13 +258,25 @@ int readOpenptsUuidFile(OPENPTS_UUID *uuid) {
     }
 
     /* free */
-    if (uuid->uuid != NULL) free(uuid->uuid);
-    if (uuid->str != NULL) free(uuid->str);
-    if (uuid->time != NULL) free(uuid->time);
+    if (uuid->uuid != NULL) {
+        xfree(uuid->uuid);
+    }
+    if (uuid->str != NULL) {
+        xfree(uuid->str);
+    }
+    if (uuid->time != NULL) {
+        xfree(uuid->time);
+    }
 
     /* open */
     if ((fp = fopen(uuid->filename, "r")) == NULL) {
         // DEBUG("readUuidFile - UUID File %s open was failed\n", filename);
+        /* we don't want double free errors - we may have already freed these up
+           above. this was a genuine issue that caused multiple pointers to
+           reference the same area of memory. */
+        uuid->uuid = NULL;
+        uuid->str  = NULL;
+        uuid->time = NULL;
         return PTS_DENIED;  // TODO
     }
 
@@ -304,7 +314,7 @@ int readOpenptsUuidFile(OPENPTS_UUID *uuid) {
         }
         uuid->status = OPENPTS_UUID_FILLED;
     } else {
-        ERROR("readOpenptsUuidFile() - read UUID fail\n");
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_UUID_READ_FAILED, "Failed to read the UUID file\n"));
     }
 
  close:
@@ -345,7 +355,8 @@ int writeOpenptsUuidFile(OPENPTS_UUID *uuid, int overwrite) {
     if (overwrite == 1) {
         /* overwrite */
         if ((fp = fopen(uuid->filename, "w")) == NULL) {
-            ERROR("UUID File %s open was failed\n", uuid->filename);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_UUID_FILE_OPEN_FAILED,
+                "Failed to open UUID file %s\n"), uuid->filename);
             return PTS_INTERNAL_ERROR;
         }
     } else {
@@ -353,14 +364,19 @@ int writeOpenptsUuidFile(OPENPTS_UUID *uuid, int overwrite) {
         if ((fd = open(uuid->filename, O_CREAT | O_EXCL | O_WRONLY, mode)) == -1) {
             if (errno == EEXIST) {
                 /* exist, keep the current UUID file */
-                return PTS_SUCCESS;  // TODO
+                fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_UUID_FILE_EXISTS,
+                    "The UUID file '%s' already exists\n"), uuid->filename);
+                // return PTS_SUCCESS;  // TODO
+                return OPENPTS_FILE_EXISTS;
             } else {
-                ERROR("UUID File %s open was failed\n", uuid->filename);
+                fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_UUID_FILE_OPEN_FAILED,
+                    "Failed to open UUID file %s\n"), uuid->filename);
                 return PTS_INTERNAL_ERROR;
             }
         }
         if ((fp = fdopen(fd, "w")) == NULL) {
-            ERROR("UUID File %s open was failed\n", uuid->filename);
+            fprintf(stderr,  NLS(MS_OPENPTS, OPENPTS_UUID_FILE_OPEN_FAILED,
+                "Failed to open UUID file %s\n"), uuid->filename);
             return PTS_INTERNAL_ERROR;
         }
     }
index 2f31759..5de4ae6 100644 (file)
@@ -32,6 +32,7 @@
 
 #include <memory.h>
 #include <stdint.h>
+#include <time.h>
 
 #if 1
 #include <uuid.h>
@@ -49,6 +50,9 @@ void uuid_from_string(unsigned_char_t *string_uuid, uuid_t *uuid,
 #endif
 
 #include <openpts.h>
+#include <log.h>
+
+
 
 #if UUIDSIZE < 16
 #error Insufficient space in PTS_UUID
@@ -71,9 +75,8 @@ PTS_UUID *newUuid() {
     PTS_UUID *uuid;
     unsigned32 status;
 
-    uuid = malloc(sizeof(PTS_UUID));
+    uuid = xmalloc(sizeof(PTS_UUID));
     if (uuid == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
 
@@ -81,8 +84,9 @@ PTS_UUID *newUuid() {
     uuid_create((uuid_p_t)uuid, &status);
 
     if (uuid_s_ok != status) {
-        ERROR("failed to generate an UUID: %s\n", uuid_s_message[status]);
-        free(uuid);
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_UUID_FAILED_GEN_NEW,
+            "Failed to generate an UUID: %s\n"), uuid_s_message[status]);
+        xfree(uuid);
         return NULL;
     }
 
@@ -93,13 +97,7 @@ PTS_UUID *newUuid() {
  * free UUID
  */
 void freeUuid(PTS_UUID *uuid) {
-    /* check */
-    if (uuid == NULL) {
-        ERROR("null input\n");
-        return;
-    }
-
-    free(uuid);
+    xfree(uuid);
 }
 
 /**
@@ -110,9 +108,8 @@ PTS_UUID *getUuidFromString(char *str) {
     uuid_t uu;
     unsigned32 status;
 
-    uuid = malloc(sizeof(PTS_UUID));
+    uuid = xmalloc(sizeof(PTS_UUID));
     if (uuid == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memset(uuid, 0, UUIDSIZE);
@@ -122,7 +119,7 @@ PTS_UUID *getUuidFromString(char *str) {
     if (uuid_s_ok != status) {
         ERROR("getUuidFromString() - uuid_from_string failed UUID='%s': %s\n",
             str, uuid_s_message[status]);
-        free(uuid);
+        xfree(uuid);
         return NULL;
     }
 
@@ -137,9 +134,8 @@ char * getStringOfUuid(PTS_UUID *uuid) {
     char *str_uuid_backup;
     unsigned32 status;
 
-    str_uuid = malloc(UUID_STRLEN + 1);
+    str_uuid = xmalloc(UUID_STRLEN + 1);
     if (str_uuid == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
 
@@ -152,14 +148,14 @@ char * getStringOfUuid(PTS_UUID *uuid) {
     if (uuid_s_ok != status) {
         ERROR("getStringFromUuid() - uuid_to_string failed: %s\n",
             uuid_s_message[status]);
-        free(str_uuid);
+        xfree(str_uuid);
         return NULL;
     }
 
     /* WA
      * the uuid_to_string implementation shouldn't malloc... */
     if (str_uuid_backup != str_uuid) {
-        free(str_uuid_backup);
+        xfree(str_uuid_backup);
     }
 
     return str_uuid;
@@ -190,11 +186,10 @@ PTS_DateTime * getDateTimeOfUuid(PTS_UUID *uuid) {
     clunks  = ((uint64_t)(uu->time_hi_and_version & 0x0fff)) << 48;
     clunks += ((uint64_t)uu->time_mid) << 32;
     clunks += uu->time_low;
-    t = (clunks - (uint64_t)0x01B21DD213814000) / 10000000;
+    t = (clunks - 0x01B21DD213814000ULL) / 10000000;
 
-    pdt = malloc(sizeof(PTS_DateTime));
+    pdt = xmalloc(sizeof(PTS_DateTime));
     if (pdt == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     // TODO gmtime or local?
index f0434f6..943f73e 100644 (file)
  */
 
 /**
- * \file src/uuid.c
+ * \file src/uuid_libuuid.c
  * \brief UUID wrapper (libuuid part)
  * @author Seiji Munetoh <munetoh@users.sourceforge.jp>
  * @date 2010-11-29
- * cleanup 2011-01-20,21 SM
+ * cleanup 2011-10-07 SM
  *
  * Linux uses libuuid
  *
- * Program  UUID   Description        When            
- * ---------------------------------------------------------------------------------------------------
- * ptscd    CID    Colelctor ID       System install     => /var/lib/openpts/uuid (UUID of sign key)
- *          RM     RM ID              RM Gen xid in RM,  path /var/lib/openpts/$UUID/rm_files
- *          RunID  ID of this daemon  Daemon start       => /var/lib/openpts/run_uuid
- * openpts  VID    Verifier ID        1st run            => uuid=XXX in 'HOME/.openpts/openpts.conf' file
- *          RM                                           => 'HOME/.openpts/hostname/$UUID/rm_files
- *
- * Unit Test: check_uuid.c
- *
  */
 
 #include <stdio.h>
 
 #define SEP_LINE "------------------------------------------------------------------------------------"
 
+#ifdef MACOS
+#include <arpa/inet.h>
+
+typedef struct {
+    uint32_t time_low;
+    uint16_t time_mid;
+    uint16_t time_hi_and_version;
+    uint8_t  clock_seq_hi_and_reserved;
+    uint8_t  clock_seq_low;
+    char     node[6];
+} my_uuid_t;
+
+time_t uuid_time(uuid_t uu, struct timeval *tv) {
+    my_uuid_t myUUID;
+    uint64_t clunks;
+
+    myUUID.time_low = ntohl(*((uint32_t*)&uu[0]));
+    myUUID.time_mid = ntohs(*((uint16_t*)&uu[4]));
+    myUUID.time_hi_and_version = ntohs(*((uint16_t*)&uu[6]));
+    myUUID.clock_seq_hi_and_reserved = uu[8];
+
+    if ((myUUID.clock_seq_hi_and_reserved & 0xc0) != 0x80) {
+        ERROR("uuid_time() - bad UUID variant (0x%02x) found, can't extract timestamp\n",
+            (myUUID.clock_seq_hi_and_reserved & 0xc0) >> 4);
+        return (time_t)-1;
+    }
+
+    clunks  = ((uint64_t)(myUUID.time_hi_and_version & 0x0fff)) << 48;
+    clunks += ((uint64_t)myUUID.time_mid) << 32;
+    clunks += myUUID.time_low;
+    return (clunks - 0x01B21DD213814000ULL) / 10000000;
+}
+#endif
+
 /******************************/
 /* PTS_UUID                   */
 /******************************/
@@ -68,9 +92,8 @@ PTS_UUID *newUuid() {
     uuid_t uu;
     PTS_UUID *uuid;
 
-    uuid = malloc(sizeof(PTS_UUID));  // BYTE[16]
+    uuid = xmalloc(sizeof(PTS_UUID));  // BYTE[16]
     if (uuid == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
 
@@ -84,13 +107,7 @@ PTS_UUID *newUuid() {
  * free UUID
  */
 void freeUuid(PTS_UUID *uuid) {
-    /* check */
-    if (uuid == NULL) {
-        ERROR("null input\n");
-        return;
-    }
-
-    free(uuid);
+    xfree(uuid);
 }
 
 
@@ -109,7 +126,7 @@ PTS_UUID *getUuidFromString(char *str) {
         return NULL;
     }
 
-    uuid = malloc(sizeof(PTS_UUID));
+    uuid = xmalloc(sizeof(PTS_UUID));
     if (uuid == NULL) {
         ERROR("\n");
         return NULL;
@@ -126,9 +143,8 @@ char * getStringOfUuid(PTS_UUID *uuid) {
     char *str_uuid;
     uuid_t uu;
 
-    str_uuid = malloc(37);
+    str_uuid = xmalloc(37);
     if (str_uuid == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
 
@@ -190,9 +206,8 @@ PTS_DateTime * getDateTimeOfUuid(PTS_UUID *uuid) {
     // TODO gmtime or local?
     gmtime_r((const time_t *) &t, &time);
 
-    pdt = malloc(sizeof(PTS_DateTime));
+    pdt = xmalloc(sizeof(PTS_DateTime));
     if (pdt == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memcpy(pdt, &time, (9*4));
@@ -213,9 +228,8 @@ PTS_DateTime * getDateTime() {
     // TODO gmtime or local?
     gmtime_r((const time_t *) &t, &ttm);
 
-    pdt = malloc(sizeof(PTS_DateTime));
+    pdt = xmalloc(sizeof(PTS_DateTime));
     if (pdt == NULL) {
-        ERROR("no memory\n");
         return NULL;
     }
     memcpy(pdt, &ttm, (9*4));
index f7af237..67e8fcd 100644 (file)
@@ -48,6 +48,7 @@
 #include <fcntl.h>
 
 #include <openpts.h>
+// #include <log.h>
 
 /**
  * verifier
@@ -82,9 +83,11 @@ int verifierHandleCapability(
     OPENPTS_CONTEXT *ctx,
     char *conf_dir,
     char *host,
-    OPENPTS_IF_M_Capability *cap) {
+    OPENPTS_IF_M_Capability *cap,
+    int *notifiedOfPendingRm,
+    int *currentRmOutOfDate) {
     OPENPTS_UUID *verifier_uuid = NULL;
-    int rc = 0;
+    int rc = PTS_INTERNAL_ERROR; /* guilty until proven innocent */
     int i;
     OPENPTS_CONFIG *target_conf = NULL;
     OPENPTS_CONFIG *conf = NULL;
@@ -92,24 +95,32 @@ int verifierHandleCapability(
     char * collector_dir = NULL;
     char * rm_dir = NULL;
 
+     *currentRmOutOfDate = 0;
+     *notifiedOfPendingRm = 0;
 
     /**/
     conf = ctx->conf;
     verifier_uuid = ctx->conf->uuid;
 
     /* collector UUID */
-    if (ctx->collector_uuid != NULL) freeOpenptsUuid(ctx->collector_uuid);
+    if (ctx->collector_uuid != NULL) {
+        freeOpenptsUuid(ctx->collector_uuid);
+    }
     ctx->collector_uuid = newOpenptsUuid2(&cap->platform_uuid);
     if (ctx->collector_uuid == NULL) {
-        ERROR("Bad collector uuid\n");
+        // ERROR("Bad collector uuid\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
     /* Manifest UUID */
-    if (ctx->rm_uuid != NULL) freeOpenptsUuid(ctx->rm_uuid);
+    if (ctx->rm_uuid != NULL) {
+        freeOpenptsUuid(ctx->rm_uuid);
+    }
     ctx->rm_uuid = newOpenptsUuid2(&cap->manifest_uuid);
     if (ctx->rm_uuid == NULL) {
-        ERROR("Bad RM uuid\n");
+        // ERROR("Bad RM uuid\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
@@ -122,9 +133,12 @@ int verifierHandleCapability(
         /* DIR is missing, unknwon collector */
         ERROR("verifier() - Unknown collector, UUID= %s dir= %s, rc=%d\n",
             ctx->collector_uuid->str, collector_dir, rc);
-        addReason(ctx, "Missing collector configuration");
-        addReason(ctx, "Collector hostname = %s", host);
-        addReason(ctx, "Collector UUID = %s", ctx->collector_uuid->str);
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_MISSING_CONFIG_2,
+            "Missing collector configuration"));
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_HOSTNAME,
+            "Collector hostname = %s"), host);
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_UUID,
+            "Collector UUID = %s"), target_conf->uuid->str);
         rc = PTS_NOT_INITIALIZED;
         goto close;
     }
@@ -134,6 +148,10 @@ int verifierHandleCapability(
     if (ctx->target_conf == NULL) {
         /* no collector info, create new one for this */
         ctx->target_conf = newPtsConfig();
+        if ( NULL == ctx->target_conf ) {
+            rc = PTS_INTERNAL_ERROR;
+            goto close;
+        }
         /* short cut */
         target_conf = ctx->target_conf;
 
@@ -144,9 +162,12 @@ int verifierHandleCapability(
         rc = readTargetConf(target_conf, target_conf->config_file);
         if (rc != PTS_SUCCESS) {
             ERROR("verifier() - readTargetConf failed, %s\n", target_conf->config_file);
-            addReason(ctx, "Missing collector configuration file");
-            addReason(ctx, "Collector hostname = %s", host);
-            addReason(ctx, "Collector UUID = %s", ctx->collector_uuid->str);
+            // WORK NEEDED: Please use NLS for i18n
+            addReason(ctx, -1, "Missing collector configuration file");
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_HOSTNAME,
+                "Collector hostname = %s"), host);
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_UUID,
+                "Collector UUID = %s"), ctx->collector_uuid->str);
             rc = PTS_NOT_INITIALIZED;
             goto close;
         }
@@ -158,10 +179,12 @@ int verifierHandleCapability(
             /* Miss, hostname or IP address was changed?  */
             ERROR("verifier() - Unexpected collector UUID= %s, must be %s\n",
                 ctx->collector_uuid->str, target_conf->uuid->uuid);
-            addReason(ctx, "Collector configuration was changed");
-            addReason(ctx, "Collector hostname = %s", host);
-            addReason(ctx, "Expected Collector UUID = %s", target_conf->uuid->uuid);
-            addReason(ctx, "Given Collector UUID = %s", ctx->collector_uuid->str);
+            // WORK NEEDED: Please use NLS for i18n
+            addReason(ctx, -1, "Collector configuration was changed");
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_HOSTNAME,
+                "Collector hostname = %s"), host);
+            addReason(ctx, -1, "Expected Collector UUID = %s", target_conf->uuid->uuid);
+            addReason(ctx, -1, "Given Collector UUID = %s", ctx->collector_uuid->str);
             rc = PTS_NOT_INITIALIZED;
             goto close;
         } else {
@@ -178,14 +201,27 @@ int verifierHandleCapability(
     memcpy(&target_conf->tss_version, &cap->tss_version, 4);
     memcpy(&target_conf->pts_version, &cap->pts_version, 4);
 
-
+    DEBUG("OPENPTS CAPS EXCHANGE - flag[0] = 0x%02x\n", target_conf->pts_flag[0]);
     DEBUG("Verifier  UUID         : %s\n", verifier_uuid->str);
     DEBUG("Collector UUID         : %s\n", ctx->collector_uuid->str);
     DEBUG("Collector RM UUID      : %s\n", ctx->rm_uuid->str);
-
-    /* Check RM by UUID */
     DEBUG("RM  UUID               : %s\n", target_conf->rm_uuid->str);
 
+#ifdef CONFIG_AUTO_RM_UPDATE
+    /* Possible New RM Set from Collector */
+    if (isFlagSet(target_conf->pts_flag[0], OPENPTS_FLAG0_NEWRM_EXIST)) {
+        DEBUG("Discovered pending RM on target -> extracting UUID\n");
+        conf->target_newrm_exist = 1;
+        conf->target_newrm_uuid = xmalloc(sizeof(PTS_UUID));
+        if (NULL == conf->target_newrm_uuid) {
+            rc = PTS_INTERNAL_ERROR;
+            goto close;
+        }
+        memcpy(conf->target_newrm_uuid, &cap->new_manifest_uuid, 16);
+        *notifiedOfPendingRm = 1;
+    }
+#endif
+
     /* check RM UUID */
     // if (target_conf->uuid->status == OPENPTS_UUID_CHANGED) {
     if (memcmp(target_conf->rm_uuid->uuid, ctx->rm_uuid->uuid, 16) != 0) {
@@ -205,15 +241,23 @@ int verifierHandleCapability(
             DEBUG("RM changed %s -> %s (good reboot)\n",
                 target_conf->rm_uuid->str, target_conf->newrm_uuid->str);
 
-            printf("Collector's manifest has been changed to new manifest (expected reboot)\n");
-            printf("  current manifest UUID : %s\n", target_conf->newrm_uuid->str);
-            printf("  old manifest UUID     : %s\n", target_conf->rm_uuid->str);
+                OUTPUT(NLS(MS_OPENPTS, OPENPTS_VERIFIER_MANIFEST_CHANGED,
+                       "Collector's manifest has been changed to a new manifest (expect a reboot)\n"
+                       "  old manifest UUID : %s\n"
+                       "  new manifest UUID : %s\n"),
+                       target_conf->rm_uuid->str, target_conf->newrm_uuid->str);
 
             /* Free Old RM */
             if (target_conf->oldrm_uuid != NULL) {
-                if (target_conf->oldrm_uuid->uuid != NULL) free(target_conf->oldrm_uuid->uuid);
-                if (target_conf->oldrm_uuid->str != NULL)  free(target_conf->oldrm_uuid->str);
-                if (target_conf->oldrm_uuid->time != NULL) free(target_conf->oldrm_uuid->time);
+                if (target_conf->oldrm_uuid->uuid != NULL) {
+                    xfree(target_conf->oldrm_uuid->uuid);
+                }
+                if (target_conf->oldrm_uuid->str != NULL) {
+                    xfree(target_conf->oldrm_uuid->str);
+                }
+                if (target_conf->oldrm_uuid->time != NULL) {
+                    xfree(target_conf->oldrm_uuid->time);
+                }
             } else {
                 target_conf->oldrm_uuid = newOpenptsUuid();
                 // TODO create this before?
@@ -271,14 +315,18 @@ int verifierHandleCapability(
             // TODO DEBUG("RM changed %s -> %s\n", target_conf->rm_uuid->str, rm_uuid->str);
 
             // TODO update RM
-            addReason(ctx, "Collector uses another Reference Manifest(RM)");
-            addReason(ctx, "Collector hostname = %s", host);
-            addReason(ctx, "Collector UUID = %s", ctx->collector_uuid->str);
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_USING_OTHER_RM,
+                "Collector is using another Reference Manifest (RM)"));
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_HOSTNAME,
+                "Collector hostname = %s"), host);
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_UUID,
+                "Collector UUID = %s"), ctx->collector_uuid->str);
 
             t0 = getDateTimeOfUuid(target_conf->rm_uuid->uuid);
             t1 = getDateTimeOfUuid(ctx->rm_uuid->uuid);
 
-            addReason(ctx, "Previous RM UUID = %s, timestamp = %04d-%02d-%02d-%02d:%02d:%02d",
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_PREV_RM_UUID,
+                "Previous RM UUID = %s, timestamp = %04d-%02d-%02d-%02d:%02d:%02d"),
                 target_conf->rm_uuid->str,
                 t0->year + 1900,
                 t0->mon + 1,
@@ -287,7 +335,8 @@ int verifierHandleCapability(
                 t0->min,
                 t0->sec);
 
-            addReason(ctx, "Current  RM UUID = %s, timestamp = %04d-%02d-%02d-%02d:%02d:%02d",
+            addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_CUR_RM_UUID,
+                "Current RM UUID = %s, timestamp = %04d-%02d-%02d-%02d:%02d:%02d"),
                 ctx->rm_uuid->str,
                 t1->year + 1900,
                 t1->mon + 1,
@@ -296,8 +345,10 @@ int verifierHandleCapability(
                 t1->min,
                 t1->sec);
 
-            rc = PTS_RULE_NOT_FOUND;  // TODO
-            goto close;
+            *currentRmOutOfDate = 1;
+            /* keep going so we can provide remediation based on the last
+               known RM. quitting now gives no information to the user about
+               what has changed. */
         }
     } else {
         /* HIT */
@@ -309,14 +360,19 @@ int verifierHandleCapability(
     /* check RM */
     rm_dir = getFullpathName(collector_dir, target_conf->rm_uuid->str);
     rc = checkDir(rm_dir);
-    if (rc != PTS_SUCCESS) {
+    if (rc != PTS_SUCCESS && 0 == *currentRmOutOfDate) {
         /* unknwon RM */
         ERROR("verifier() - Unknown RM, (RM dir = %s)\n", rm_dir);
-        addReason(ctx, "Missing Reference Manifest(RM)");
-        addReason(ctx, "Collector hostname = %s", host);
-        addReason(ctx, "Collector UUID = %s", target_conf->uuid->str);
-        addReason(ctx, "Collector RM UUID = %s", target_conf->rm_uuid->str);
-        addReason(ctx, "Missing RM dir = %s", rm_dir);
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_MISSING_RM,
+            "Missing Reference Manifest (RM)"));
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_HOSTNAME,
+            "Collector hostname = %s"), host);
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_UUID,
+            "Collector UUID = %s"), target_conf->uuid->str);
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_COLLECTOR_RM_UUID,
+            "Collector RM UUID = %s"), target_conf->rm_uuid->str);
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_MISSING_RM_DIR,
+            "Missing Reference Manifest directory = %s"), rm_dir);
         rc = PTS_RULE_NOT_FOUND;
         goto close;
     }
@@ -365,8 +421,8 @@ int verifierHandleCapability(
  *  
  */
 int verifierHandleRimmSet(
-        OPENPTS_CONTEXT *ctx,
-        BYTE *value) {
+    OPENPTS_CONTEXT *ctx,
+    BYTE *value) {
     int rc = PTS_SUCCESS;
     OPENPTS_CONFIG *target_conf;
     int i;
@@ -378,25 +434,11 @@ int verifierHandleRimmSet(
     int len;
 
     /* check */
-    if (ctx == NULL) {
-        ERROR("verifierHandleRimmSet() - ctx is NULL\n");
-        rc = PTS_FATAL;
-        goto error;
-    }
-
-    if (ctx->target_conf == NULL) {
-        ERROR("verifierHandleRimmSet() - target_conf is NULL\n");
-        rc = PTS_FATAL;
-        goto error;
-    }
+    ASSERT(NULL != ctx, "verifierHandleRimmSet() - ctx is NULL\n");
+    ASSERT(NULL != ctx->target_conf, "verifierHandleRimmSet() - target_conf is NULL\n");
     target_conf = ctx->target_conf;
 
-    if (value == NULL) {
-        ERROR("verifierHandleRimmSet() - value is NULL\n");
-        rc = PTS_FATAL;
-        goto error;
-    }
-
+    ASSERT(NULL != value, "verifierHandleRimmSet() - value is NULL\n");
 
     /* num */
     num = getUint32(value);
@@ -411,12 +453,14 @@ int verifierHandleRimmSet(
         /* Missing rm_basedir => create */
         rc = mkdir(target_conf->rm_basedir, S_IRUSR | S_IWUSR | S_IXUSR);
         if (rc != 0) {
-            ERROR("create conf directory, %s was failed\n", target_conf->rm_basedir);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_VERIFIER_CONF_DIR_CREATE_FAILED,
+                    "Failed to create the configuration directory '%s'\n"), buf);
             rc = PTS_INTERNAL_ERROR;
             goto error;
         }
     } else if ((st.st_mode & S_IFMT) != S_IFDIR) {
-        ERROR("RM directory, %s is not a directory %x %x\n", buf, (st.st_mode & S_IFMT), S_IFDIR);
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_VERIFIER_RM_DIR_NOT_DIR,
+                "The reference manifest path '%s' is not a directory\n"), buf);
         rc = PTS_INTERNAL_ERROR;
         goto close;
     }
@@ -430,7 +474,7 @@ int verifierHandleRimmSet(
 
         if (target_conf->rm_filename[i] != NULL) {
             DEBUG("enroll() - free conf->rm_filename[%d] %s\n", i, target_conf->rm_filename[i]);
-            free(target_conf->rm_filename[i]);
+            xfree(target_conf->rm_filename[i]);
         }
 
         target_conf->rm_filename[i] = smalloc(buf);
@@ -443,7 +487,7 @@ int verifierHandleRimmSet(
         value += 4;
 
         rc = saveToFile(target_conf->rm_filename[i], len, value);
-        if (rc < 0) {
+        if (rc != PTS_SUCCESS) {
             ERROR("enroll - save RM[%d], %s failed\n", i, target_conf->rm_filename[i]);
             rc = PTS_INTERNAL_ERROR;
             goto close;
@@ -484,7 +528,7 @@ int  writePolicyConf(OPENPTS_CONTEXT *ctx, char *filename) {
     DEBUG("writePolicyConf       : %s\n", filename);
 
     if ((fp = fopen(filename, "w")) == NULL) {
-        ERROR("writePolicyConf() - File %s open was failed\n", filename);
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_VERIFIER_OPEN_FAILED, "Failed to open policy file '%s'\n"), filename);
         return -1;
     }
 
@@ -499,6 +543,8 @@ int  writePolicyConf(OPENPTS_CONTEXT *ctx, char *filename) {
             i++;
         } else if (!strncmp(prop->name, "ima.", 4)) {
             /* IMA measurement - SKIP */
+        } else if (!strncmp(prop->name, "disable.", 8)) {
+            /* Indicates a disabled tpm quote - SKIP */
         } else {
             fprintf(fp, "%s=%s\n", prop->name, prop->value);
             i++;
@@ -545,7 +591,8 @@ int  writeAideIgnoreList(OPENPTS_CONTEXT *ctx, char *filename) {
     DEBUG("writeAideIgnoreList     : %s\n", filename);
 
     if ((fp = fopen(filename, "w")) == NULL) {
-        ERROR("File %s open was failed\n", filename);
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_VERIFIER_OPEN_FAILED_2,
+            "Failed to open AIDE ignore list '%s'\n"), filename);
         return -1;
     }
 
@@ -622,7 +669,7 @@ int  writeAideIgnoreList(OPENPTS_CONTEXT *ctx, char *filename) {
 
 
 /**
- *  
+ *  target_conf->ir_filename
  */
 int verifierHandleIR(
         OPENPTS_CONTEXT *ctx,
@@ -635,36 +682,27 @@ int verifierHandleIR(
     int i;
 
     /* check */
-    if (ctx == NULL) {
-        ERROR("verifierHandleRimmSet() - ctx is NULL\n");
-        rc = PTS_FATAL;
-        goto error;
-    }
-
-    if (ctx->target_conf == NULL) {
-        ERROR("verifierHandleRimmSet() - target_conf is NULL\n");
-        rc = PTS_FATAL;
-        goto error;
-    }
+    ASSERT(NULL != ctx, "verifierHandleRimmSet() - ctx is NULL\n");
+    ASSERT(NULL != ctx->target_conf, "verifierHandleRimmSet() - target_conf is NULL\n");
     target_conf = ctx->target_conf;
 
-    if (value == NULL) {
-        ERROR("verifierHandleRimmSet() - value is NULL\n");
-        rc = PTS_FATAL;
-        goto error;
-    }
-
+    ASSERT(NULL != value, "verifierHandleRimmSet() - value is NULL\n");
 
     /* save IR to file */
     if (length > 0) {
         rc = saveToFile(target_conf->ir_filename, length, value);
-        if (rc < 0) {
-            ERROR("verifier - save IR failed\n");
+        if (rc != PTS_SUCCESS) {
+            DEBUG("target_conf->ir_filename, %s\n", target_conf->ir_filename);
+            addReason(ctx, -1, "[IMV] failed to save IR, %s)", target_conf->ir_filename);
+            fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_VERIFIER_SAVE_IR_FAILED,
+                "[verifier] failed to save IR\n"));
             rc = PTS_INTERNAL_ERROR;
             goto close;
         }
     } else {
-        ERROR("verifier - collector can not send IR\n");
+        addReason(ctx, -1, "[IMV] failed to send IR)");
+        fprintf(stderr, NLS(MS_OPENPTS, OPENPTS_VERIFIER_SEND_IR_FAILED,
+            "[verifier] failed to send IR\n"));
         rc = PTS_INTERNAL_ERROR;
         goto close;
     }
@@ -696,8 +734,11 @@ int verifierHandleIR(
     }
 
     /* Validate IR by FSM */
-    *result = validateIr(ctx, target_conf->ir_filename);  /* ir.c */
-
+    // *result = validateIr(ctx, target_conf->ir_filename);  /* ir.c */
+    // TODO 2011-10-15 validateIr was changed
+    if (ctx->ir_filename != NULL) xfree(ctx->ir_filename);
+    ctx->ir_filename = smalloc(target_conf->ir_filename);
+    *result = validateIr(ctx);  /* ir.c */
 
     if (mode == OPENPTS_VERIFY_MODE) {
         /* save properties */
@@ -721,12 +762,12 @@ int verifierHandleIR(
 #endif
     } else {
         ERROR("unknown mode %d\n", mode);
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
     rc = PTS_SUCCESS;
 
    close:
-   error:
 
     return rc;
 }
@@ -760,6 +801,7 @@ int enroll(
     OPENPTS_UUID *verifier_uuid = NULL;
     OPENPTS_CONFIG *target_conf;
     OPENPTS_IF_M_Capability *cap;
+    OPENPTS_TARGET *target;
 
     /* check */
     // TODO
@@ -771,8 +813,24 @@ int enroll(
         return PTS_INTERNAL_ERROR;
     }
 
-    /* new target_conf */
-    if (ctx->target_conf != NULL) {
+    // We must ensure that target names are unique among the registered targets.
+    // Test whether a target with the same name already exists.
+    ctx->conf->hostname = smalloc(host);
+    target = getTargetCollector(ctx->conf);
+
+    if (target != NULL) {
+        ctx->target_conf = target->target_conf;
+        if (!force) {
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_VERIFIER_OVERRIDE,
+                "%s already exists. If you want to override please use the '-f' option\n"),
+                ctx->target_conf->config_file);
+            rc = PTS_INTERNAL_ERROR;
+            goto out;
+        }
+        // assert(force)
+        // the target UUID may have been reseted, erase the known one
+        unlinkDir(target->dir);
+    } else if (ctx->target_conf != NULL) {
         ERROR("enroll() - target_conf of %s already exist?\n", host);
         goto out;
     }
@@ -792,7 +850,8 @@ int enroll(
                           &sock);
 
     if (ssh_pid == -1) {
-        ERROR("connection to %s failed.\n", host);
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_CONNECT_FAILED,
+            "Connection failed (server = %s)\n"), host);
         rc = PTS_OS_ERROR;
         goto out;
     }
@@ -800,7 +859,7 @@ int enroll(
     /* V->C capability (hello) */
     len = writePtsTlv(ctx, sock, OPENPTS_CAPABILITIES);
     if (len < 0) {
-        ERROR("send OPENPTS_CAPABILITIES was failed\n");
+        ERROR("Failed to send capability message, rc = %d\n", len);
         rc = PTS_INTERNAL_ERROR;
         goto close;
     }
@@ -812,19 +871,22 @@ int enroll(
         rc = PTS_INTERNAL_ERROR;
         goto close;
     }
+
     if (read_tlv->type != OPENPTS_CAPABILITIES) {
-        ERROR("\n");
+        ERROR("Expected OPENPTS_CAPABILITIES reply, instead got type '%d'\n", read_tlv->type);
         rc = PTS_INTERNAL_ERROR;
         goto close;
     }
+
     if (read_tlv->length != sizeof(OPENPTS_IF_M_Capability)) {  // TODO set name
         ERROR("UUID length = %d != 36\n", read_tlv->length);
         rc = PTS_INTERNAL_ERROR;
         goto close;
     }
+
     cap =  (OPENPTS_IF_M_Capability *)read_tlv->value;
 
-    /* Fill versions */
+    /* version */
     memcpy(&target_conf->pts_flag,    &cap->flag, 4);
     memcpy(&target_conf->tpm_version, &cap->tpm_version, 4);
     memcpy(&target_conf->tss_version, &cap->tss_version, 4);
@@ -833,14 +895,14 @@ int enroll(
     /* collector UUID */
     target_conf->uuid = newOpenptsUuid2(&cap->platform_uuid);
     if (target_conf->uuid == NULL) {
-        ERROR("Bad collector uuid\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
     /* Manifest UUID */
     target_conf->rm_uuid = newOpenptsUuid2(&cap->manifest_uuid);
     if (target_conf->rm_uuid == NULL) {
-        ERROR("Bad collector uuid\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
@@ -892,7 +954,9 @@ int enroll(
             DEBUG("%s is missing. Get RM from target\n", target_conf->config_file);
         } else {
             // EXIST -> Update
-            fprintf(stderr, "%s exist. if you want to override, use -f option\n", target_conf->config_file);
+            OUTPUT(NLS(MS_OPENPTS, OPENPTS_VERIFIER_OVERRIDE,
+                "%s already exists. If you want to override please use the '-f' option\n"),
+                target_conf->config_file);
             rc = PTS_INTERNAL_ERROR;
             goto close;
         }
@@ -918,7 +982,11 @@ int enroll(
 
     /* C->V template RIMM (RIMM embedded to CTX) */
     read_tlv = readPtsTlv(sock);
-    if (read_tlv->type == OPENPTS_ERROR) {
+    if (read_tlv == NULL) {
+        ERROR("Problem receiving PTS message\n");
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    } else if (read_tlv->type == OPENPTS_ERROR) {
         ERROR("Request RIMM_SET was failed. collector returns error message");
         rc = PTS_INTERNAL_ERROR;
         goto close;
@@ -939,6 +1007,59 @@ int enroll(
     freePtsTlv(read_tlv);
     read_tlv = NULL;
 
+
+    /* V->C TPM PUBKEY req */
+    len = writePtsTlv(ctx, sock, REQUEST_TPM_PUBKEY);  // ifm.c
+
+    if (len < 0) {
+        ERROR("enroll() - REQUEST_TPM_PUBKEY was failed, len=%d\n", len);
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    }
+
+    /* C->V TPM PUBKEY */
+    read_tlv = readPtsTlv(sock);
+    if (read_tlv == NULL) {
+        ERROR("Problem receiving PTS message\n");
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    } else if (read_tlv->type == OPENPTS_ERROR) {
+        // TODO Ignore now
+        TODO("Target did not have TPM_PUBKEY");
+        // WORK NEEDED - Please use NLS for i18n
+        addReason(ctx, -1, "Target did not have TPM_PUBKEY\n");
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    } else if (read_tlv->type != TPM_PUBKEY) {
+        ERROR("read_tlv->type != TPM_PUBKEY, but %d", read_tlv->type);
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    }
+
+    if (read_tlv->length > 0) {
+        /* TPM_PUBKEY -> CTX */
+        DEBUG("TPM_PUBKEY size        : %d\n", read_tlv->length);
+
+        // TODO used by two
+        if (target_conf->pubkey != NULL) {
+            DEBUG("enroll() - reset the PUBKEY\n");
+            xfree(target_conf->pubkey);
+        }
+
+        target_conf->pubkey_length = read_tlv->length;
+        target_conf->pubkey = xmalloc_assert(target_conf->pubkey_length);
+        // TODO check NULL
+        memcpy(
+            target_conf->pubkey,
+            read_tlv->value,
+            target_conf->pubkey_length);
+        /* save to the target.conf */
+    } else {
+        DEBUG("enroll - TPM_PUBKEY is missing.\n");
+    }
+
+
+
 #ifdef CONFIG_AIDE
     // TODO(munetoh) capability defile validation mode of collector
     /* V->C AIDE_DATABASE req  */
@@ -952,14 +1073,18 @@ int enroll(
 
     /* C->V AIDE DATABASE */
     read_tlv = readPtsTlv(sock);
-    if (read_tlv->type != AIDE_DATABASE) {
+    if (read_tlv == NULL) {
+        ERROR("Problem receiving PTS message\n");
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    } else if (read_tlv->type != AIDE_DATABASE) {
         if (read_tlv->type == OPENPTS_ERROR) {
             // TODO check msg?
             /* AIDE DB is missing */
             target_conf->ima_validation_mode = OPENPTS_VALIDATION_MODE_NONE;
             DEBUG("enroll - AIDE DB is missing. do not validate IMA's IMLs\n");
         } else {
-            ERROR("");
+            ERROR("enroll - RAIDE DB req. returns unknown message type 0x%x", read_tlv->type);
             rc = PTS_INTERNAL_ERROR;
             goto close;
         }
@@ -1003,51 +1128,6 @@ int enroll(
 
 
 
-    /* V->C TPM PUBKEY req */
-    len = writePtsTlv(ctx, sock, REQUEST_TPM_PUBKEY);  // ifm.c
-
-    if (len < 0) {
-        ERROR("enroll() - REQUEST_TPM_PUBKEY was failed, len=%d\n", rc);
-        rc = PTS_INTERNAL_ERROR;
-        goto close;
-    }
-
-    /* C->V TPM PUBKEY */
-    read_tlv = readPtsTlv(sock);
-    if (read_tlv->type == OPENPTS_ERROR) {
-        // TODO Ignore now
-        TODO("Target did not have TPM_PUBKEY");
-        addReason(ctx, "Target did not have TPM_PUBKEY\n");
-        rc = PTS_INTERNAL_ERROR;
-        goto close;
-    } else if (read_tlv->type != TPM_PUBKEY) {
-        ERROR("read_tlv->type != TPM_PUBKEY, but %d", read_tlv->type);
-        rc = PTS_INTERNAL_ERROR;
-        goto close;
-    }
-
-    if (read_tlv->length > 0) {
-        /* TPM_PUBKEY -> CTX */
-        DEBUG("TPM_PUBKEY size        : %d\n", read_tlv->length);
-
-        // TODO used by two
-        if (target_conf->pubkey != NULL) {
-            DEBUG("enroll() - reset the PUBKEY\n");
-            free(target_conf->pubkey);
-        }
-
-        target_conf->pubkey_length = read_tlv->length;
-        target_conf->pubkey = malloc(target_conf->pubkey_length);
-        // TODO check NULL
-        memcpy(
-            target_conf->pubkey,
-            read_tlv->value,
-            target_conf->pubkey_length);
-        /* save to the target.conf */
-    } else {
-        DEBUG("enroll - TPM_PUBKEY is missing.\n");
-    }
-
     /* save target conf */
     writeTargetConf(
         target_conf,
@@ -1064,7 +1144,9 @@ int enroll(
   out:
     /* free */
 
-    if (read_tlv != NULL) freePtsTlv(read_tlv);
+    if (read_tlv != NULL) {
+        freePtsTlv(read_tlv);
+    }
 
     freePtsConfig(ctx->target_conf);
     ctx->target_conf = NULL;
@@ -1085,9 +1167,10 @@ int verifier(
     char *ssh_port,
     char *conf_dir,
     int mode) {
-    int rc = PTS_SUCCESS;
+    const int MINIMUM_NONCE_LENGTH = 16;
+    int rc = PTS_VERIFY_FAILED; /* guilty until proven innocent */
+    int result = OPENPTS_RESULT_INVALID;
     int len;
-    int result = OPENPTS_RESULT_VALID;
     /* sock */
     int sock;
     pid_t ssh_pid;
@@ -1098,20 +1181,18 @@ int verifier(
     // char * collector_dir = NULL;
     // char * rm_dir = NULL;
     OPENPTS_IF_M_Capability *cap;
+    int notifiedOfPendingRm = 0;
+    int currentRmOutOfDate = 0;
 
     DEBUG("verifier() - start\n");
     DEBUG("  conf_dir             : %s\n", conf_dir);
     DEBUG("  mode                 : %d  (0:just verify, 1:update the policy)\n", mode);
+
     /* check */
-    if (ctx == NULL) {
-        ERROR("ctx is null\n");
-        return PTS_INTERNAL_ERROR;
-    }
+    ASSERT(ctx != NULL, "ctx is null\n");
+    ASSERT(ctx->conf != NULL, "conf is null\n");
+
     conf = ctx->conf;
-    if (conf == NULL) {
-        ERROR("conf is null\n");
-        return PTS_INTERNAL_ERROR;
-    }
 
     /* connect to the target collector */
     ssh_pid = ssh_connect(host,
@@ -1122,7 +1203,8 @@ int verifier(
 
     if (ssh_pid == -1) {
         ERROR("connection failed (server = %s)\n", host);
-        addReason(ctx, "connection failed (server = %s)\n", host);
+        addReason(ctx, -1, NLS(MS_OPENPTS, OPENPTS_VERIFIER_CONNECT_FAILED,
+            "Connection failed (server = %s)\n"), host);
         rc = PTS_OS_ERROR;
         goto out;
     }
@@ -1132,7 +1214,8 @@ int verifier(
     /* V->C capability (hello) */
     len = writePtsTlv(ctx, sock, OPENPTS_CAPABILITIES);
     if (len < 0) {
-        ERROR("Send OPENPTS_CAPABILITIES was failed\n");
+        ERROR("Failed to send capability message\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
@@ -1143,6 +1226,8 @@ int verifier(
         rc = PTS_INTERNAL_ERROR;
         goto close;
     } else if (read_tlv->type != OPENPTS_CAPABILITIES) {
+        ERROR("Expected OPENPTS_CAPABILITIES reply, instead got type '%d'\n", read_tlv->type);
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     } else if (read_tlv->length != sizeof(OPENPTS_IF_M_Capability)) {
         // TODO PTS_CAPABILITIES_SIZE
@@ -1152,19 +1237,24 @@ int verifier(
     }
     cap = (OPENPTS_IF_M_Capability *)read_tlv->value;
 
-    rc = verifierHandleCapability(ctx, conf_dir, host, cap);
-    if (rc != PTS_SUCCESS) goto close;
+    rc = verifierHandleCapability(ctx, conf_dir, host, cap,
+                                  &notifiedOfPendingRm, &currentRmOutOfDate);
+    if (rc != PTS_SUCCESS) {
+        ERROR("Failed to exchange capabilities\n");
+        goto close;
+    }
 
     /* V->C  D-H nonce param req ---------------------------------- */
     /*   setup req  */
     ctx->nonce->req->reserved = 0;
-    ctx->nonce->req->min_nonce_len = 16;
+    ctx->nonce->req->min_nonce_len = MINIMUM_NONCE_LENGTH;
     ctx->nonce->req->dh_group_set = DH_GROUP_2;
 
     /*   send req   */
     len = writePtsTlv(ctx, sock, DH_NONCE_PARAMETERS_REQUEST);
     if (len < 0) {
-        ERROR("Send DH_NONCE_PARAMETERS_REQUEST was failed\n");
+        ERROR("Failed to send nonce parameters request\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
@@ -1178,6 +1268,9 @@ int verifier(
         rc = PTS_INTERNAL_ERROR;
         goto close;
     } else if (read_tlv->type != DH_NONCE_PARAMETORS_RESPONSE) {
+        ERROR("Expected DH_NONCE_PARAMETORS_RESPONSE reply, but instead got type '%d'\n",
+            read_tlv->type);
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
     // DEBUG("new read_tlv %p\n",read_tlv);
@@ -1190,18 +1283,29 @@ int verifier(
     ctx->nonce->res->selected_dh_group   = (read_tlv->value[4]<<8) | read_tlv->value[5];
     ctx->nonce->res->hash_alg_set        = (read_tlv->value[6]<<8) | read_tlv->value[7];
 
+    if (ctx->nonce->res->nonce_length < MINIMUM_NONCE_LENGTH) {
+        ERROR("Expected minimum nonce length of '%d', instead got '%d'\n",
+            MINIMUM_NONCE_LENGTH, ctx->nonce->res->nonce_length);
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    }
+
     /* set pubkey length */
-    setDhPubkeylength(ctx->nonce);
+    if ( 0 != setDhPubkeylength(ctx->nonce) ) {
+        ERROR("setDhPubkeylength failed\n");
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    }
 
     /* nonce */
-    ctx->nonce->res->dh_respondor_nonce = malloc(ctx->nonce->res->nonce_length);
+    ctx->nonce->res->dh_respondor_nonce = xmalloc_assert(ctx->nonce->res->nonce_length);
     memcpy(
         ctx->nonce->res->dh_respondor_nonce,
         &read_tlv->value[8],
         ctx->nonce->res->nonce_length);
 
     /* pubkey */
-    ctx->nonce->res->dh_respondor_public = malloc(ctx->nonce->pubkey_length);
+    ctx->nonce->res->dh_respondor_public = xmalloc_assert(ctx->nonce->pubkey_length);
     memcpy(
         ctx->nonce->res->dh_respondor_public,
         &read_tlv->value[8 + ctx->nonce->res->nonce_length],
@@ -1211,21 +1315,23 @@ int verifier(
     rc = calcDh(ctx->nonce);
     if (rc != 0) {
         ERROR("calcDh failed\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
     /* V->C D-H nonce finish  --------------------------------------------- */
     len = writePtsTlv(ctx, sock, DH_NONCE_FINISH);
     if (len < 0) {
-        ERROR("Send DH_NONCE_FINISH was failed\n");
+        ERROR("Failed to send nonce finish message\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
-
     /* V->C IR req -------------------------------------------------------- */
     len = writePtsTlv(ctx, sock, REQUEST_INTEGRITY_REPORT);
     if (len < 0) {
-        ERROR("Send REQUEST_INTEGRITY_REPORT was failed\n");
+        ERROR("Failed to send request integrity report message\n");
+        rc = PTS_INTERNAL_ERROR;
         goto close;
     }
 
@@ -1235,7 +1341,7 @@ int verifier(
 
     read_tlv = readPtsTlv(sock);
     if (read_tlv == NULL) {
-        ERROR("REQUEST_INTEGRITY_REPORT was failed, check the collector");
+        ERROR("Failed to get integrity report. Please check the collector.\n");
         rc = PTS_INTERNAL_ERROR;
         goto close;
     } else if (read_tlv->type != INTEGRITY_REPORT) {
@@ -1244,6 +1350,42 @@ int verifier(
     }
 
     rc = verifierHandleIR(ctx, read_tlv->length, read_tlv->value, mode, &result);
+    if (rc != PTS_SUCCESS) {
+        ERROR("verifierHandleIR fail\n");
+        rc = PTS_INTERNAL_ERROR;
+        goto close;
+    }
+
+#ifdef CONFIG_AUTO_RM_UPDATE
+    if ( notifiedOfPendingRm ) {
+        DEBUG("Downloading new RM set\n");
+        /* get the Reference Manifest from target(collector) -
+           we download it here as part of the verify path because
+           it saves us having to open a new connection to ptsc, which
+           is wasteful */
+
+        /* V->C template RIMM req  */
+        rc = writePtsTlv(ctx, sock, REQUEST_NEW_RIMM_SET);
+        if (rc < 0) {
+            rc = PTS_INTERNAL_ERROR;
+            goto close;
+        }
+
+        /* C->V template RIMM (RIMM embedded to CTX) */
+        freePtsTlv(read_tlv);
+        read_tlv = readPtsTlv(sock);
+        if (NULL == read_tlv || NEW_RIMM_SET != read_tlv->type) {
+            rc = PTS_INTERNAL_ERROR;
+            goto close;
+        }
+
+        DEBUG("New RIMM len %d\n", read_tlv->length);
+
+        /* stash a copy of the downloaded pending RM */
+        conf->newRmSet = read_tlv->value;
+        read_tlv->value = 0;
+    }
+#endif
 
     /* V->C VR */
     len = writePtsTlv(ctx, sock, VERIFICATION_RESULT);
@@ -1255,7 +1397,10 @@ int verifier(
     /* return validateIr() result  */
     // TODO
     // OPENPTS_RESULT_INVALID
-    if (result == OPENPTS_RESULT_VALID) {
+    if (currentRmOutOfDate) {
+        DEBUG("verifier() result      : MISSING RM");
+        rc = PTS_RULE_NOT_FOUND;
+    } else if (result == OPENPTS_RESULT_VALID) {
         DEBUG("verifier() result      : VALID");
         rc = PTS_SUCCESS;        // 0 -> 0
     } else if (result == OPENPTS_RESULT_UNVERIFIED) {
@@ -1282,9 +1427,10 @@ int verifier(
 
   out:
     /* free */
-    if (read_tlv != NULL) freePtsTlv(read_tlv);
-    // if (collector_dir != NULL) free(collector_dir);
-    // if (rm_dir != NULL) free(rm_dir);
+    if (read_tlv != NULL) {
+        freePtsTlv(read_tlv);
+    }
+
     if ((rc == PTS_VERIFY_FAILED) && (mode == 1)) {
         DEBUG("verifier() - update the policy");
         rc = PTS_SUCCESS;
@@ -1294,5 +1440,3 @@ int verifier(
 
     return rc;
 }
-
-