[Opendnssec-commits] [svn.opendnssec.org/svn/dnssec] r6026 - branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate

rene at xpt.nl rene at xpt.nl
Thu Jan 5 11:04:41 CET 2012


Author: rene
Date: 2012-01-05 11:04:41 +0100 (Thu, 05 Jan 2012)
New Revision: 6026

Modified:
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate.proto
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_cmd.h
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_cmd.h
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_cmd.h
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_cmd.h
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_cmd.h
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_cmd.h
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_rollover_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_rollover_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_cmd.h
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_cmd.h
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_task.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_list_cmd.cpp
   branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_list_task.cpp
Log:
Change key state handling code so it now uses the database instead of serializing protocol buffers to file.

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate.proto
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate.proto	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate.proto	2012-01-05 10:04:41 UTC (rev 6026)
@@ -4,16 +4,16 @@
 package ods.keystate;
 
 import "xmlext.proto";
+import "orm.proto";
 
-message KeyStateDocument {
-    repeated EnforcerZone zones = 1;
-}
-
 message KeyStateExport {
     optional EnforcerZone zone = 1 [(xml).path="Zone"];
 }
 
 message EnforcerZone {
+	option(orm.index).name = "EnforcerZone_name_index";
+	option(orm.index).spec = "name";
+	
     required string name = 1 [(xml).path="@name"];
     required string policy = 2 [(xml).path="@policy"];
     repeated KeyData keys = 3 [(xml).path="Key"];
@@ -39,7 +39,7 @@
 //    optional bool ds_seen = 8 [default = false, (xml).path="DSSeen"]; // parent says DS has been seen
 //    optional bool submit_to_parent = 9 [default = false, (xml).path="DSSubmit"]; // submit DS to parent
     optional bool introducing = 10 [default=true, (xml).path="Introducing"];
-    optional bool revoke = 11 [default = false, (xml).path="Revoke"];
+    optional bool revoke = 11 [default = false, (xml).path="Revoke", (orm.column).name="shouldrevoke"];
     optional bool standby = 12 [default = false, (xml).path="Standby"];
     optional bool active_zsk = 13 [default = false, (xml).path="ActiveZSK"];
     optional bool publish = 14 [default = false, (xml).path="Publish"];

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -18,19 +18,17 @@
  */
 void help_keystate_ds_gone_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
-        "key ds-gone     list KSK keys that were retracted from the parent.\n"
+	ods_printf(sockfd,
+		"key ds-gone     list KSK keys that were retracted from the parent.\n"
         "  --zone <zone> (aka -z) set KSK key to unsubmitted for zone <zone>\n"
         "  --id <id>     (aka -k) with id <id>.\n"
         "  --keytag <keytag>\n"
         "                (aka -x) with keytag <keytag>.\n"
         );
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
 int handled_keystate_ds_gone_cmd(int sockfd, engine_type* engine,
-                                   const char *cmd, ssize_t n)
+								 const char *cmd, ssize_t n)
 {
     char buf[ODS_SE_MAXLINE];
     const char *argv[8];
@@ -53,8 +51,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
 
@@ -69,8 +66,7 @@
     if (argc) {
         ods_log_warning("[%s] unknown arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"unknown arguments\n");
         return 1; // errors, but handled
     }
 
@@ -78,8 +74,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
 
@@ -90,27 +85,24 @@
         if (!zone) {
             ods_log_warning("[%s] expected option --zone <zone> for %s command",
                             module_str,scmd);
-            (void)snprintf(buf, ODS_SE_MAXLINE,"expected --zone <zone> option\n");
-            ods_writen(sockfd, buf, strlen(buf));
+            ods_printf(sockfd,"expected --zone <zone> option\n");
             return 1; // errors, but handled
         }
         if (!id && !keytag) {
             ods_log_warning("[%s] expected option --id <id> or "
                             "--keytag <keytag> for %s command",
                             module_str,scmd);
-            (void)snprintf(buf, ODS_SE_MAXLINE,"expected --id <id> or "
+            ods_printf(sockfd,"expected --id <id> or "
                            "--keytag <keytag> option\n");
-            ods_writen(sockfd, buf, strlen(buf));
             return 1; // errors, but handled
         } else {
             if (id && keytag) {
                 ods_log_warning("[%s] both --id <id> and --keytag <keytag> given, "
                                 "please only specify one for %s command",
                                 module_str,scmd);
-                (void)snprintf(buf, ODS_SE_MAXLINE,
+                ods_printf(sockfd,
                                "both --id <id> and --keytag <keytag> given, "
                                "please only specify one\n");
-                ods_writen(sockfd, buf, strlen(buf));
                 return 1; // errors, but handled
             }
         }
@@ -119,24 +111,21 @@
             if (kt<=0 || kt>=65536) {
                 ods_log_warning("[%s] value \"%s\" for --keytag is invalid",
                                 module_str,keytag);
-                (void)snprintf(buf, ODS_SE_MAXLINE,
+                ods_printf(sockfd,
                                "value \"%s\" for --keytag is invalid\n",
                                keytag);
-                ods_writen(sockfd, buf, strlen(buf));
                 return 1; // errors, but handled
             }
             nkeytag = (uint16_t )kt;
         }
     }
     
-    /* perform task immediately */
     time_t tstart = time(NULL);
+
     perform_keystate_ds_gone(sockfd,engine->config,zone,id,nkeytag);
-    (void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
-                   scmd,time(NULL)-tstart);
-    ods_writen(sockfd, buf, strlen(buf));
+    
+	ods_printf(sockfd,"%s completed in %ld seconds.\n",scmd,time(NULL)-tstart);
 
     flush_enforce_task(engine);
-    
     return 1;
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_cmd.h
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_cmd.h	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_cmd.h	2012-01-05 10:04:41 UTC (rev 6026)
@@ -10,7 +10,7 @@
 void help_keystate_ds_gone_cmd(int sockfd);
 
 int handled_keystate_ds_gone_cmd(int sockfd, engine_type* engine,
-                                 const char *cmd, ssize_t n);
+								 const char *cmd, ssize_t n);
 
 #ifdef __cplusplus
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_gone_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -8,175 +8,187 @@
 #include "keystate/keystate.pb.h"
 #include "xmlext-pb/xmlext-rd.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
+
 #include <memory>
 #include <fcntl.h>
 
 static const char *module_str = "keystate_ds_gone_task";
 
+static void
+list_keys_retracted(OrmConn conn, int sockfd, const char *datastore)
+{
+	#define LOG_AND_RETURN(errmsg)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg);return;}while(0)
+	
+	// list all keys that have submitted flag set.
+	ods_printf(sockfd,
+			   "Database set to: %s\n"
+			   "Retracted Keys:\n"
+			   "Zone:                           "
+			   "Key role:     "
+			   "Keytag:       "
+			   "Id:                                      "
+			   "\n"
+			   ,datastore
+			   );
+	
+	OrmTransaction transaction(conn);
+	if (!transaction.started())
+		LOG_AND_RETURN("transaction not started");
+	
+	{	OrmResultRef rows;
+		::ods::keystate::EnforcerZone enfzone;
+		if (!OrmMessageEnum(conn,enfzone.descriptor(),rows))
+			LOG_AND_RETURN("zone enumeration failed");
+		
+		for (bool next=OrmFirst(rows); next; next=OrmNext(rows)) {
+			
+			if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true))
+				LOG_AND_RETURN("retrieving zone from database failed");
+			
+			for (int k=0; k<enfzone.keys_size(); ++k) {
+				const ::ods::keystate::KeyData &key = enfzone.keys(k);
+				
+				// ZSKs are never trust anchors so skip them.
+				if (key.role() == ::ods::keystate::ZSK)
+					continue;
+				
+				// Skip KSKs with a zero length id, they are placeholder keys.
+				if (key.locator().size()==0)
+					continue;
+				
+				if (key.ds_at_parent()!=::ods::keystate::retracted)
+					continue;
+				
+				std::string keyrole = keyrole_Name(key.role());
+				ods_printf(sockfd,
+						   "%-31s %-13s %-13u %-40s\n",
+						   enfzone.name().c_str(),
+						   keyrole.c_str(),
+						   key.keytag(),
+						   key.locator().c_str()
+						   );
+			}
+			
+		}		
+	}
+	
+	#undef LOG_AND_RETURN
+}
+
+static void
+change_keys_retracted_to_unsubmitted(OrmConn conn, int sockfd,
+									 const char *zone, const char *id, uint16_t keytag)
+{
+	#define LOG_AND_RETURN(errmsg)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg);return;}while(0)
+	#define LOG_AND_RETURN_1(errmsg,p)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg,p);return;}while(0)
+	
+	OrmTransactionRW transaction(conn);
+	if (!transaction.started())
+		LOG_AND_RETURN("transaction not started");
+	
+	std::string qzone;
+	if (!OrmQuoteStringValue(conn, std::string(zone), qzone))
+		LOG_AND_RETURN("quoting string value failed");
+	
+	{	OrmResultRef rows;
+		::ods::keystate::EnforcerZone enfzone;
+		if (!OrmMessageEnumWhere(conn,enfzone.descriptor(),
+								 rows,"name = %s",qzone.c_str()))
+			LOG_AND_RETURN("zone enumeration failed");
+		
+		if (!OrmFirst(rows))
+			LOG_AND_RETURN_1("zone %s not found",zone);
+		
+		OrmContextRef context;
+		if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true, context))
+			LOG_AND_RETURN("retrieving zone from database failed");
+		
+		// we no longer need the query result, so release it.
+		rows.release();
+		
+		// Try to change the state of a specific 'retracted' key to 'unsubmitted'.
+		bool bKeyStateMatched = false;
+		bool bZoneModified = false;
+		for (int k=0; k<enfzone.keys_size(); ++k) {
+			const ::ods::keystate::KeyData &key = enfzone.keys(k);
+			
+			// ZSKs are never trust anchors so skip them.
+			if (key.role() == ::ods::keystate::ZSK)
+				continue;
+			
+			// Skip KSKs with a zero length id, they are placeholder keys.
+			if (key.locator().size()==0)
+				continue;
+			
+			if ((id && key.locator()==id) || (keytag && key.keytag()==keytag)) {
+				bKeyStateMatched = true;
+				
+				if (key.ds_at_parent()!=::ods::keystate::retracted) {
+					ods_printf(sockfd,
+							   "Key that matches id \"%s\" in zone "
+							   "\"%s\" is not retracted but %s\n",
+							   key.locator().c_str(), zone,
+							   dsatparent_Name(key.ds_at_parent()).c_str());
+					break;
+				}
+				
+				enfzone.mutable_keys(k)->set_ds_at_parent(::ods::keystate::unsubmitted);
+				enfzone.set_next_change(0); // reschedule immediately
+				bZoneModified = true;
+			}
+		}
+		
+		// Report back the status of the operation.
+		if (!bKeyStateMatched) {
+			if (id)
+				ods_printf(sockfd,
+						   "No KSK key matches id \"%s\" in zone \"%s\"\n",
+						   id,
+						   zone);
+			else
+				ods_printf(sockfd,
+						   "No KSK key matches keytag \"%u\" in zone \"%s\"\n",
+						   keytag,
+						   zone);
+		} else {
+			if (bZoneModified) {
+				// Update key states for the zone in the database.
+				if (!OrmMessageUpdate(context))
+					LOG_AND_RETURN_1("unable to update zone %s in the database",zone);
+				
+				// Commit updated records to the database.
+				if (!transaction.commit())
+					LOG_AND_RETURN_1("unable to commit updated zone %s to the database",zone);
+				
+				ods_log_debug("[%s] key states have been updated",module_str);
+				ods_printf(sockfd,"update of key states completed.\n");
+			} else {
+				ods_log_debug("[%s] key states are unchanged",module_str);
+				ods_printf(sockfd,"key states are unchanged\n");
+			}
+		}
+	}
+	
+	#undef LOG_AND_RETURN
+	#undef LOG_AND_RETURN_1
+}
+
 void 
 perform_keystate_ds_gone(int sockfd, engineconfig_type *config,
                          const char *zone, const char *id, uint16_t keytag)
 {
-    char buf[ODS_SE_MAXLINE];
-    const char *datastore = config->datastore;
-
 	GOOGLE_PROTOBUF_VERIFY_VERSION;
-    
-    std::auto_ptr< ::ods::keystate::KeyStateDocument >
-        keystateDoc(new ::ods::keystate::KeyStateDocument);
-   {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (fd != -1) {
-            if (keystateDoc->ParseFromFileDescriptor(fd)) {
-                ods_log_debug("[%s] keys have been loaded",
-                              module_str);
-                close(fd);
-            } else {
-                ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                              module_str,datapath.c_str());
-                close(fd);
-                return;
-            }
-        } else {
-            ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                          module_str,datapath.c_str());
-            return;
-        }
-    }
-    
-    if (!(zone && (id || keytag))) {
-    
-        // list all keys that have retracted flag set.
-        
-        (void)snprintf(buf, ODS_SE_MAXLINE,
-                       "Database set to: %s\n"
-                       "Retracted Keys:\n"
-                       "Zone:                           "
-                       "Key role:     "
-                       "Keytag:       "
-                       "Id:                                      "
-                       "\n"
-                       ,datastore
-                       );
-        ods_writen(sockfd, buf, strlen(buf));
-        
-        for (int z=0; z<keystateDoc->zones_size(); ++z) {
-            
-            const ::ods::keystate::EnforcerZone &enfzone = keystateDoc->zones(z);
-            for (int k=0; k<enfzone.keys_size(); ++k) {
-                const ::ods::keystate::KeyData &key = enfzone.keys(k);
-                
-                // ZSKs are never trust anchors so skip them.
-                if (key.role() == ::ods::keystate::ZSK)
-                    continue;
-                
-                // Skip KSKs with a zero length id, they are placeholder keys.
-                if (key.locator().size()==0)
-                    continue;
-                
-                if (key.ds_at_parent()!=::ods::keystate::retracted)
-                    continue;
-
-                std::string keyrole = keyrole_Name(key.role());
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "%-31s %-13s %13u %-40s\n",
-                               enfzone.name().c_str(),
-                               keyrole.c_str(),
-                               key.keytag(),
-                               key.locator().c_str()
-                               );
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-        }
-        return;
-    }
-
-    // Try to change the state of a specific retracted key back to unsubmitted.
-    bool id_match = false;
-    bool bKeyStateModified = false;
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
-
-        ::ods::keystate::EnforcerZone *enfzone = keystateDoc->mutable_zones(z);
-        for (int k=0; k<enfzone->keys_size(); ++k) {
-            const ::ods::keystate::KeyData &key = enfzone->keys(k);
-
-            // ZSKs are never trust anchors so skip them.
-            if (key.role() == ::ods::keystate::ZSK)
-                continue;
-            
-            // Skip KSKs with a zero length id, they are placeholder keys.
-            if (key.locator().size()==0)
-                continue;
-            
-            // Skip when zone doesn't match
-            if (enfzone->name()!=zone)
-                continue;
-            
-            if (id && key.locator()==id || keytag && key.keytag()==keytag ) {
-                id_match = true;
-                
-                if (key.ds_at_parent()!=::ods::keystate::retracted) {
-                    
-                    std::string dsatparentname = dsatparent_Name(key.ds_at_parent());
-                    (void)snprintf(buf, ODS_SE_MAXLINE, 
-                                   "Key that matches id \"%s\" in zone "
-                                   "\"%s\" is not retracted but %s\n",
-                                   key.locator().c_str(), zone,
-                                   dsatparentname.c_str());
-                    ods_writen(sockfd, buf, strlen(buf));
-                    break;
-                }
-
-                bKeyStateModified = true;
-                
-                ::ods::keystate::KeyData *kd =
-                    keystateDoc->mutable_zones(z)->mutable_keys(k);
-                kd->set_ds_at_parent(::ods::keystate::unsubmitted);
-                enfzone->set_next_change(0); // reschedule immediately
-            }
-
-        }
-    }
-
-    if (!id_match) {
-        if (id)
-            (void)snprintf(buf, ODS_SE_MAXLINE, 
-                           "No KSK key matches id \"%s\" in zone \"%s\"\n",
-                           id, zone);
-        else
-            (void)snprintf(buf, ODS_SE_MAXLINE, 
-                           "No KSK key matches keytag \"%u\" in zone \"%s\"\n",
-                           keytag, zone);
-        ods_writen(sockfd, buf, strlen(buf));
-    }
-    
-    // Persist the keystate zones back to disk as they may have
-    // been changed by the enforcer update
-    if (bKeyStateModified) {
-        if (keystateDoc->IsInitialized()) {
-            std::string datapath(datastore);
-            datapath += ".keystate.pb";
-            int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
-            if (keystateDoc->SerializeToFileDescriptor(fd)) {
-                ods_log_debug("[%s] key states have been updated",
-                              module_str);
-                
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "update of key states completed.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            } else {
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "error: key states file could not be written.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-            close(fd);
-        } else {
-            (void)snprintf(buf, ODS_SE_MAXLINE,
-                           "error: a message in the key states is missing "
-                           "mandatory information.\n");
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-    }
+	OrmConnRef conn;
+	if (ods_orm_connect(sockfd, config, conn)) {
+		// list key states with ds-seen state
+		if (!(zone && (id || keytag)))
+			list_keys_retracted(conn, sockfd, config->datastore);
+		else
+			change_keys_retracted_to_unsubmitted(conn, sockfd, zone, id, keytag);
+	}
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -14,20 +14,18 @@
 void
 help_keystate_ds_retract_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
+    ods_printf(sockfd,
         "key ds-retract  list KSK keys that should be retracted from the parent.\n"
         "  --zone <zone> (aka -z) force retract of KSK key for zone <zone>.\n"
         "  --id <id>     (aka -k) force retract of KSK key with id <id>.\n"
         "  --auto        (aka -a) perform retract for all keys that have "
                         "the retract flag set.\n"
         );
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
 int
 handled_keystate_ds_retract_cmd(int sockfd, engine_type* engine,
-                               const char *cmd, ssize_t n)
+								const char *cmd, ssize_t n)
 {
     char buf[ODS_SE_MAXLINE];
     const char *argv[8];
@@ -52,8 +50,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
     
@@ -65,8 +62,7 @@
     if (argc) {
         ods_log_warning("[%s] unknown arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"unknown arguments\n");
         return 1; // errors, but handled
     }
     
@@ -74,9 +70,8 @@
     time_t tstart = time(NULL);
     perform_keystate_ds_retract(sockfd,engine->config,zone,id,bAutomatic?1:0);
     if (!zone && !id) {
-        (void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
-                       scmd,time(NULL)-tstart);
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"%s completed in %ld seconds.\n",
+				   scmd,time(NULL)-tstart);
     }
 
     return 1;

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_cmd.h
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_cmd.h	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_cmd.h	2012-01-05 10:04:41 UTC (rev 6026)
@@ -10,7 +10,7 @@
 void help_keystate_ds_retract_cmd(int sockfd);
 
 int handled_keystate_ds_retract_cmd(int sockfd, engine_type* engine,
-                                    const char *cmd, ssize_t n);
+									const char *cmd, ssize_t n);
 
 #ifdef __cplusplus
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_retract_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -10,42 +10,44 @@
 #include "keystate/keystate.pb.h"
 #include "xmlext-pb/xmlext-rd.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
 
+#include <memory>
 #include <fcntl.h>
 
 static const char *module_str = "keystate_ds_retract_task";
 
-static bool retract_dnskey_by_id(int sockfd,
-                                const char *ds_retract_command,
-                                const char *id,
-                                ::ods::keystate::keyrole role,
-                                const char *zone,
-                                int algorithm)
+static bool 
+retract_dnskey_by_id(int sockfd,
+					const char *ds_retract_command,
+					const char *id,
+					::ods::keystate::keyrole role,
+					const char *zone,
+					int algorithm)
 {
-    char buf[ODS_SE_MAXLINE];
-
     /* Code to output the DNSKEY record  (stolen from hsmutil) */
     hsm_ctx_t *hsm_ctx = hsm_create_context();
     if (!hsm_ctx) {
-        ods_log_error("[%s] Could not connect to HSM", module_str);
-        (void)snprintf(buf,ODS_SE_MAXLINE, "Could not connect to HSM\n");
-        ods_writen(sockfd, buf, strlen(buf));
+		ods_log_error_and_printf(sockfd,
+								 module_str,
+								 "could not connect to HSM");
         return false;
     }
     hsm_key_t *key = hsm_find_key_by_id(hsm_ctx, id);
     
     if (!key) {
-        ods_log_error("[%s] key %s not found in any HSM",
-                      module_str,id);
-        (void)snprintf(buf,ODS_SE_MAXLINE, "key %s not found in any HSM\n", id);
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_log_error_and_printf(sockfd,
+								 module_str,
+								 "key %s not found in any HSM",
+								 id);
         hsm_destroy_context(hsm_ctx);
         return false;
     }
     
     bool bOK = false;
     char *dnskey_rr_str;
-
+	
     hsm_sign_params_t *sign_params = hsm_sign_params_new();
     sign_params->owner = ldns_rdf_new_frm_str(LDNS_RDF_TYPE_DNAME, zone);
     sign_params->algorithm = (ldns_algorithm)algorithm;
@@ -61,7 +63,7 @@
     hsm_sign_params_free(sign_params);
     ldns_rr_free(dnskey_rr);
     hsm_key_free(key);
-
+	
     /* Replace tab with white-space */
     for (int i = 0; dnskey_rr_str[i]; ++i) {
         if (dnskey_rr_str[i] == '\t') {
@@ -79,221 +81,277 @@
         }
     }
 
-    // retract the dnskey rr string to a configured
+    // pass the dnskey rr string to a configured
     // delegation signer retract program.
     if (ds_retract_command && ds_retract_command[0] != '\0') {
         /* send records to the configured command */
         FILE *fp = popen(ds_retract_command, "w");
         if (fp == NULL) {
-            ods_log_error("[%s] Failed to run command: %s: %s",
-                          module_str,ds_retract_command,strerror(errno));
-            (void)snprintf(buf,ODS_SE_MAXLINE,"failed to run command: %s: %s\n",
-                           ds_retract_command,strerror(errno));
-            ods_writen(sockfd, buf, strlen(buf));
-            
+            ods_log_error_and_printf(sockfd,
+									 module_str,
+									 "failed to run command: %s: %s",
+									 ds_retract_command,
+									 strerror(errno));
         } else {
             int bytes_written = fprintf(fp, "%s", dnskey_rr_str);
             if (bytes_written < 0) {
-                ods_log_error("[%s] Failed to write to %s: %s",
-                              module_str,ds_retract_command,strerror(errno));
-                (void)snprintf(buf,ODS_SE_MAXLINE,"failed to write to %s: %s\n",
-                               ds_retract_command,strerror(errno));
-                               ods_writen(sockfd, buf, strlen(buf));
-                
+                ods_log_error_and_printf(sockfd,
+										 module_str,
+										 "[%s] Failed to write to %s: %s",
+										 ds_retract_command,
+										 strerror(errno));
             } else {
-            
+				
                 if (pclose(fp) == -1) {
-                    
-                    ods_log_error("[%s] Failed to close %s: %s",
-                                  module_str,ds_retract_command,strerror(errno));
-                    (void)snprintf(buf,ODS_SE_MAXLINE,"failed to close %s: %s\n",
-                                   ds_retract_command,strerror(errno));
-                    ods_writen(sockfd, buf, strlen(buf));
-                    
+                    ods_log_error_and_printf(sockfd,
+											 module_str,
+											 "failed to close %s: %s",
+											 ds_retract_command,
+											 strerror(errno));
                 } else {
                     bOK = true;
-                    (void)snprintf(buf,ODS_SE_MAXLINE, 
-                                   "key %s retracted to %s\n", 
-                                   id, ds_retract_command);
-                    ods_writen(sockfd, buf, strlen(buf));
+                    ods_printf(sockfd,
+							   "key %s retracted by %s\n",
+							   id,
+							   ds_retract_command);
                 }
             }
         }
     } else {
-        ods_log_error("[%s] No Delegation Signer retract Command configured "
-                      "in conf.xml.",module_str);
-        (void)snprintf(buf,ODS_SE_MAXLINE,
-                       "no ds retract command configured in conf.xml.\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_log_error_and_printf(sockfd,
+								 module_str,
+								 "no \"DelegationSignerRetractCommand\" binary "
+								 "configured in conf.xml.");
     }
-        
+	
     LDNS_FREE(dnskey_rr_str);
     hsm_destroy_context(hsm_ctx);
-
-    // Once the new DS records are seen in DNS please issue the ds-seen 
-    // command for zone %s with the following cka_ids %s
     return bOK;
 }
 
-void 
-perform_keystate_ds_retract(int sockfd, engineconfig_type *config,
-                           const char *zone, const char *id, int bauto)
+static void
+retract_keys(OrmConn conn,
+			int sockfd,
+			const char *zone,
+			const char *id,
+			const char *datastore,
+			const char *ds_retract_command)
 {
-    char buf[ODS_SE_MAXLINE];
-    const char *datastore = config->datastore;
-    const char *ds_retract_command = config->delegation_signer_retract_command;
+	#define LOG_AND_RETURN(errmsg)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg);return;}while(0)
+	#define LOG_AND_RETURN_1(errmsg,p)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg,p);return;}while(0)
+	
+	OrmTransactionRW transaction(conn);
+	if (!transaction.started())
+		LOG_AND_RETURN("transaction not started");
+	
+	{	OrmResultRef rows;
+		::ods::keystate::EnforcerZone enfzone;
+		if (zone) {
+			std::string qzone;
+			if (!OrmQuoteStringValue(conn, std::string(zone), qzone))
+				LOG_AND_RETURN("quoting string value failed");
+			
+			if (!OrmMessageEnumWhere(conn,enfzone.descriptor(),
+									 rows,"name = %s",qzone.c_str()))
+				LOG_AND_RETURN("zone enumeration failed");
+		} else {
+			if (!OrmMessageEnum(conn,enfzone.descriptor(),rows))
+				LOG_AND_RETURN("zone enumeration failed");
+		}
+		
+		bool bZonesModified = false;
+		
+		if (!OrmFirst(rows)) {
+			if (zone)
+				LOG_AND_RETURN_1("zone %s not found",zone);
+		} else {
+			
+			for (bool next=true; next; next=OrmNext(rows)) {
+				
+				OrmContextRef context;
+				if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true, context))
+					LOG_AND_RETURN("retrieving zone from database failed");
+				
+				// Try to change the state of a specific 'retract' key to 'retracted'.
+				bool bKeyModified = false;
+				for (int k=0; k<enfzone.keys_size(); ++k) {
+					const ::ods::keystate::KeyData &key = enfzone.keys(k);
+					
+					// Don't retract ZSKs from the parent.
+					if (key.role()==::ods::keystate::ZSK)
+						continue;
+					
+					// Only retract KSKs that have the retract flag set.
+					if (key.ds_at_parent()!=::ods::keystate::retract)
+						continue;
 
-	GOOGLE_PROTOBUF_VERIFY_VERSION;
-    
-    ::ods::keystate::KeyStateDocument *keystateDoc =
-    new ::ods::keystate::KeyStateDocument;
-    {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (keystateDoc->ParseFromFileDescriptor(fd)) {
-            ods_log_debug("[%s] keys have been loaded",
-                          module_str);
-        } else {
-            ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                          module_str,datapath.c_str());
-        }
-        close(fd);
-    }
+					if (id) {
+						// --id <id>
+						//     Force retract key to the parent for specific key id.
+						if (key.locator()==id) {
+							// retract key with this id from the parent
+							if (retract_dnskey_by_id(sockfd,ds_retract_command,
+													 key.locator().c_str(),
+													 key.role(),
+													 enfzone.name().c_str(),
+													 key.algorithm()))
+							{
+								::ods::keystate::KeyData *kd =
+									enfzone.mutable_keys(k);
+								kd->set_ds_at_parent(::ods::keystate::retracted);
+								bKeyModified = true;
+							}
+						}
+					} else {
+						if (zone) {
+							// --zone <zone>
+							//     Force retract key from the parent for specific zone.
+							if (enfzone.name()==zone) {
+								// retract key for this zone from the parent
+								if (retract_dnskey_by_id(sockfd,ds_retract_command,
+														 key.locator().c_str(),
+														 key.role(),
+														 enfzone.name().c_str(),
+														 key.algorithm()))
+								{
+									::ods::keystate::KeyData *kd = 
+									enfzone.mutable_keys(k);
+									kd->set_ds_at_parent(::ods::keystate::retracted);
+									bKeyModified = true;
+								}
+							}
+						} else {
+							// --auto
+							//     Retract all keys from the parent that have
+							//     the retract flag set.
+							if (retract_dnskey_by_id(sockfd,ds_retract_command,
+													 key.locator().c_str(),
+													 key.role(),
+													 enfzone.name().c_str(),
+													 key.algorithm()))
+							{
+								::ods::keystate::KeyData *kd = 
+									enfzone.mutable_keys(k);
+								kd->set_ds_at_parent(::ods::keystate::retracted);
+								bKeyModified = true;
+							}
+						}
+					}
+				}
+				
+				if (bKeyModified) {
+					if (!OrmMessageUpdate(context))
+						LOG_AND_RETURN_1("failed to update zone %s in the database", enfzone.name().c_str());
+					
+					bZonesModified = true;
+				}
+			}
+			
+			// we no longer need the query result, so release it.
+			rows.release();
+			
+		}
+		
+		// Report back the status of the operation.
+		if (bZonesModified) {
+			// Commit updated records to the database.
+			if (!transaction.commit())
+				LOG_AND_RETURN_1("unable to commit updated zone %s to the database",zone);
+			
+			ods_log_debug("[%s] key states have been updated",module_str);
+			ods_printf(sockfd,"update of key states completed.\n");
+		} else {
+			ods_log_debug("[%s] key states are unchanged",module_str);
+			if (id)
+				ods_printf(sockfd,
+						   "No key state changes for id \"%s\"\n",
+						   id);
+			else
+				if (zone)
+					ods_printf(sockfd,
+							   "No key state changes for zone \"%s\"\n",
+							   zone);
+				else
+					ods_printf(sockfd,"key states are unchanged\n");
+		}
+	}
+	
+	#undef LOG_AND_RETURN
+	#undef LOG_AND_RETURN_1
+}
 
-    // Evalutate parameters and retract keys to the parent when instructed
-    // to do so.
-    if (id || zone || bauto) {
-        bool bFlagsChanged = false;
-        for (int z=0; z<keystateDoc->zones_size(); ++z) {
-            const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
-            for (int k=0; k<enfzone.keys_size(); ++k) {
-                const ::ods::keystate::KeyData &key = enfzone.keys(k);
+static void
+list_keys_retract(OrmConn conn, int sockfd, const char *datastore)
+{
+	#define LOG_AND_RETURN(errmsg)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg);return;}while(0)
+	
+	// List the keys with retract flags.
+    ods_printf(sockfd,
+			   "Database set to: %s\n"
+			   "Retract Keys:\n"
+			   "Zone:                           "
+			   "Key role:     "
+			   "Id:                                      "
+			   "\n"
+			   ,datastore
+			   );
+	
+	OrmTransaction transaction(conn);
+	if (!transaction.started())
+		LOG_AND_RETURN("transaction not started");
+	
+	{	OrmResultRef rows;
+		::ods::keystate::EnforcerZone enfzone;
+		if (!OrmMessageEnum(conn,enfzone.descriptor(),rows))
+			LOG_AND_RETURN("zone enumeration failed");
 
-                // Don't ever retract ZSKs to the parent.
-                if (key.role()==::ods::keystate::ZSK)
-                    continue;
-
-                // Onlyt retract KSKs that have the retract flag set.
-                if (key.ds_at_parent()!=::ods::keystate::retract)
-                    continue;
-                    
-                if (id) {
-                    // --id <id>
-                    //     Force retract key to the parent for specific key id.
-                    if (key.locator()==id) {
-                        // retract key with this id to the parent
-                        if (retract_dnskey_by_id(sockfd,ds_retract_command,
-                                            key.locator().c_str(),
-                                            key.role(),
-                                            enfzone.name().c_str(),
-                                            key.algorithm()))
-                        {
-                            bFlagsChanged = true;
-                            keystateDoc->mutable_zones(z)->mutable_keys(k)
-                             ->set_ds_at_parent(::ods::keystate::retracted);
-                        }
-                    }
-                } else {
-                    if (zone) {
-                        // --zone <zone>
-                        //     Force retract key to the parent for specific zone.
-                        if (enfzone.name()==zone) {
-                            // retract key for this zone to the parent
-                            if (retract_dnskey_by_id(sockfd,ds_retract_command,
-                                                key.locator().c_str(),
-                                                key.role(),
-                                                enfzone.name().c_str(),
-                                                key.algorithm()))
-                            {
-                                bFlagsChanged = true;
-                                keystateDoc->mutable_zones(z)->mutable_keys(k)
-                                 ->set_ds_at_parent(::ods::keystate::retracted);
-                            }
-                        }
-                    } else {
-                        // --auto
-                        //     retract all keys to the parent that have
-                        //     the retract flag set.
-                        if (retract_dnskey_by_id(sockfd,ds_retract_command,
-                                            key.locator().c_str(),
-                                            key.role(),
-                                            enfzone.name().c_str(),
-                                            key.algorithm()))
-                        {
-                            bFlagsChanged = true;
-                            keystateDoc->mutable_zones(z)->mutable_keys(k)
-                             ->set_ds_at_parent(::ods::keystate::retracted);
-                        }
-                    }
-                }
-            }
-        }
-        
-        if (bFlagsChanged) {
-            // Persist the keystate zones back to disk as they may have
-            // been changed by the enforcer update
-            if (keystateDoc->IsInitialized()) {
-                std::string datapath(datastore);
-                datapath += ".keystate.pb";
-                int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
-                if (keystateDoc->SerializeToFileDescriptor(fd)) {
-                    ods_log_debug("[%s] key states have been updated",
-                                  module_str);
-                    
-                    (void)snprintf(buf, ODS_SE_MAXLINE,
-                                   "update of key states completed.\n");
-                    ods_writen(sockfd, buf, strlen(buf));
-                } else {
-                    (void)snprintf(buf, ODS_SE_MAXLINE,
-                                   "error: key states file could not be written.\n");
-                    ods_writen(sockfd, buf, strlen(buf));
-                }
-                close(fd);
-            } else {
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "error: a message in the key states is missing "
-                               "mandatory information.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-        }
-        
-        return;
+		for (bool next=OrmFirst(rows); next; next=OrmNext(rows)) {
+			
+			if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true))
+				LOG_AND_RETURN("retrieving zone from database failed");
+			
+			for (int k=0; k<enfzone.keys_size(); ++k) {
+				const ::ods::keystate::KeyData &key = enfzone.keys(k);
+				
+				// Don't suggest ZSKs can be retracted, don't show them
+				if (key.role() == ::ods::keystate::ZSK)
+					continue;
+				
+				// Only show keys that have the retract flag set.
+				if (key.ds_at_parent()!=::ods::keystate::retract)
+					continue;
+				
+				std::string keyrole = keyrole_Name(key.role());
+				ods_printf(sockfd,
+						   "%-31s %-13s %-40s\n",
+						   enfzone.name().c_str(),
+						   keyrole.c_str(),
+						   key.locator().c_str()
+						   );
+			}
+		}
     }
+	
+	#undef LOG_AND_RETURN
+}
 
-    // List the keys with retract flags.
-    (void)snprintf(buf, ODS_SE_MAXLINE,
-                   "Database set to: %s\n"
-                   "Retract Keys:\n"
-                   "Zone:                           "
-                   "Key role:     "
-                   "Id:                                      "
-                   "\n"
-                   ,datastore
-                   );
-    ods_writen(sockfd, buf, strlen(buf));
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
-        const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
-        for (int k=0; k<enfzone.keys_size(); ++k) {
-            const ::ods::keystate::KeyData &key = enfzone.keys(k);
-            // Don't suggest ZSKs can be retracted, leave them out of the list.
-            if (key.role() == ::ods::keystate::ZSK)
-                continue;
-
-            // Only show keys that have the retract flag set.
-            if (key.ds_at_parent()!=::ods::keystate::retract)
-                continue;
-            
-            std::string keyrole = keyrole_Name(key.role());
-            (void)snprintf(buf, ODS_SE_MAXLINE,
-                           "%-31s %-13s %-40s\n",
-                           enfzone.name().c_str(),
-                           keyrole.c_str(),
-                           key.locator().c_str()
-                           );
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-    }
+void 
+perform_keystate_ds_retract(int sockfd, engineconfig_type *config,
+							const char *zone, const char *id, int bauto)
+{
+	GOOGLE_PROTOBUF_VERIFY_VERSION;
+	OrmConnRef conn;
+	if (ods_orm_connect(sockfd, config, conn)) {
+		// Evaluate parameters and retract keys from the parent when instructed to.
+		if (zone || id || bauto)
+			retract_keys(conn,sockfd,zone,id,config->datastore,
+						 config->delegation_signer_retract_command);
+		else
+			list_keys_retract(conn,sockfd,config->datastore);
+	}
 }
 
 static task_type * 

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -14,19 +14,17 @@
 
 void help_keystate_ds_seen_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
+    ods_printf(sockfd,
         "key ds-seen     list KSK keys that were submitted to the parent.\n"
         "  --zone <zone> (aka -z) set KSK key to seen for zone <zone>\n"
         "  --id <id>     (aka -k) with id <id>.\n"
         "  --keytag <keytag>\n"
         "                (aka -x) with keytag <keytag>.\n"
         );
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
 int handled_keystate_ds_seen_cmd(int sockfd, engine_type* engine,
-                                   const char *cmd, ssize_t n)
+                                 const char *cmd, ssize_t n)
 {
     char buf[ODS_SE_MAXLINE];
     const char *argv[8];
@@ -49,8 +47,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
     
@@ -65,8 +62,7 @@
     if (argc) {
         ods_log_warning("[%s] unknown arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"unknown arguments\n");
         return 1; // errors, but handled
     }
     
@@ -74,8 +70,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+		ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
     
@@ -86,27 +81,24 @@
         if (!zone) {
             ods_log_warning("[%s] expected option --zone <zone> for %s command",
                             module_str,scmd);
-            (void)snprintf(buf, ODS_SE_MAXLINE,"expected --zone <zone> option\n");
-            ods_writen(sockfd, buf, strlen(buf));
+			ods_printf(sockfd,"expected --zone <zone> option\n");
             return 1; // errors, but handled
         }
         if (!id && !keytag) {
             ods_log_warning("[%s] expected option --id <id> or "
                             "--keytag <keytag> for %s command",
                             module_str,scmd);
-            (void)snprintf(buf, ODS_SE_MAXLINE,"expected --id <id> or "
+            ods_printf(sockfd,"expected --id <id> or "
                            "--keytag <keytag> option\n");
-            ods_writen(sockfd, buf, strlen(buf));
             return 1; // errors, but handled
         } else {
             if (id && keytag) {
                 ods_log_warning("[%s] both --id <id> and --keytag <keytag> given, "
                                 "please only specify one for %s command",
                                 module_str,scmd);
-                (void)snprintf(buf, ODS_SE_MAXLINE,
+                ods_printf(sockfd,
                                "both --id <id> and --keytag <keytag> given, "
                                "please only specify one\n");
-                ods_writen(sockfd, buf, strlen(buf));
                 return 1; // errors, but handled
             }
         }
@@ -115,24 +107,21 @@
             if (kt<=0 || kt>=65536) {
                 ods_log_warning("[%s] value \"%s\" for --keytag is invalid",
                                 module_str,keytag);
-                (void)snprintf(buf, ODS_SE_MAXLINE,
+                ods_printf(sockfd,
                                "value \"%s\" for --keytag is invalid\n",
                                keytag);
-                ods_writen(sockfd, buf, strlen(buf));
                 return 1; // errors, but handled
             }
             nkeytag = (uint16_t )kt;
         }
     }
 
-    /* perform task immediately */
     time_t tstart = time(NULL);
+	
     perform_keystate_ds_seen(sockfd,engine->config,zone,id,nkeytag);
-    (void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
-                   scmd,time(NULL)-tstart);
-    ods_writen(sockfd, buf, strlen(buf));
 
+    ods_printf(sockfd,"%s completed in %ld seconds.\n",scmd,time(NULL)-tstart);
+
     flush_enforce_task(engine);
-    
     return 1;
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_cmd.h
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_cmd.h	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_cmd.h	2012-01-05 10:04:41 UTC (rev 6026)
@@ -10,7 +10,7 @@
 void help_keystate_ds_seen_cmd(int sockfd);
 
 int handled_keystate_ds_seen_cmd(int sockfd, engine_type* engine,
-                                 const char *cmd, ssize_t n);
+								 const char *cmd, ssize_t n);
 
 #ifdef __cplusplus
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_seen_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -8,176 +8,188 @@
 #include "keystate/keystate.pb.h"
 #include "xmlext-pb/xmlext-rd.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
 
 #include <memory>
 #include <fcntl.h>
 
 static const char *module_str = "keystate_ds_seen_task";
 
+static void
+list_keys_submitted(OrmConn conn, int sockfd, const char *datastore)
+{
+	#define LOG_AND_RETURN(errmsg)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg);return;}while(0)
+
+	// list all keys that have submitted flag set.
+	ods_printf(sockfd,
+			   "Database set to: %s\n"
+			   "Submitted Keys:\n"
+			   "Zone:                           "
+			   "Key role:     "
+			   "Keytag:       "
+			   "Id:                                      "
+			   "\n"
+			   ,datastore
+			   );
+	
+	OrmTransaction transaction(conn);
+	if (!transaction.started())
+		LOG_AND_RETURN("transaction not started");
+
+	{	OrmResultRef rows;
+		::ods::keystate::EnforcerZone enfzone;
+		if (!OrmMessageEnum(conn,enfzone.descriptor(),rows))
+			LOG_AND_RETURN("zone enumeration failed");
+
+		for (bool next=OrmFirst(rows); next; next=OrmNext(rows)) {
+			
+			if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true))
+				LOG_AND_RETURN("retrieving zone from database failed");
+
+			for (int k=0; k<enfzone.keys_size(); ++k) {
+				const ::ods::keystate::KeyData &key = enfzone.keys(k);
+				
+				// ZSKs are never trust anchors so skip them.
+				if (key.role() == ::ods::keystate::ZSK)
+					continue;
+				
+				// Skip KSKs with a zero length id, they are placeholder keys.
+				if (key.locator().size()==0)
+					continue;
+				
+				if (key.ds_at_parent()!=::ods::keystate::submitted)
+					continue;
+				
+				std::string keyrole = keyrole_Name(key.role());
+				ods_printf(sockfd,
+						   "%-31s %-13s %-13u %-40s\n",
+						   enfzone.name().c_str(),
+						   keyrole.c_str(),
+						   key.keytag(),
+						   key.locator().c_str()
+						   );
+			}
+				
+		}		
+	}
+	
+	#undef LOG_AND_RETURN
+}
+
+static void
+change_keys_submitted_to_seen(OrmConn conn, int sockfd,
+							  const char *zone, const char *id, uint16_t keytag)
+{
+	#define LOG_AND_RETURN(errmsg)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg);return;}while(0)
+	#define LOG_AND_RETURN_1(errmsg,p)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg,p);return;}while(0)
+		
+	OrmTransactionRW transaction(conn);
+	if (!transaction.started())
+		LOG_AND_RETURN("transaction not started");
+	
+	std::string qzone;
+	if (!OrmQuoteStringValue(conn, std::string(zone), qzone))
+		LOG_AND_RETURN("quoting string value failed");
+	
+	{	OrmResultRef rows;
+		::ods::keystate::EnforcerZone enfzone;
+		if (!OrmMessageEnumWhere(conn,enfzone.descriptor(),
+								 rows,"name = %s",qzone.c_str()))
+			LOG_AND_RETURN("zone enumeration failed");
+		
+		if (!OrmFirst(rows))
+			LOG_AND_RETURN_1("zone %s not found",zone);
+		
+		OrmContextRef context;
+		if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true, context))
+			LOG_AND_RETURN("retrieving zone from database failed");
+		
+		// we no longer need the query result, so release it.
+		rows.release();
+		
+		// Try to change the state of a specific 'submitted' key to 'seen'.
+		bool bKeyStateMatched = false;
+		bool bZoneModified = false;
+		for (int k=0; k<enfzone.keys_size(); ++k) {
+			const ::ods::keystate::KeyData &key = enfzone.keys(k);
+			
+			// ZSKs are never trust anchors so skip them.
+			if (key.role() == ::ods::keystate::ZSK)
+				continue;
+			
+			// Skip KSKs with a zero length id, they are placeholder keys.
+			if (key.locator().size()==0)
+				continue;
+			
+			if ((id && key.locator()==id) || (keytag && key.keytag()==keytag)) {
+				bKeyStateMatched = true;
+				
+				if (key.ds_at_parent()!=::ods::keystate::submitted) {
+					ods_printf(sockfd,
+							   "Key that matches id \"%s\" in zone "
+							   "\"%s\" is not submitted but %s\n",
+							   key.locator().c_str(), zone,
+							   dsatparent_Name(key.ds_at_parent()).c_str());
+					break;
+				}
+				
+				enfzone.mutable_keys(k)->set_ds_at_parent(::ods::keystate::seen);
+				enfzone.set_next_change(0); // reschedule immediately
+				bZoneModified = true;
+			}
+		}
+		
+		
+		// Report back the status of the operation.
+		if (!bKeyStateMatched) {
+			if (id)
+				ods_printf(sockfd,
+						   "No KSK key matches id \"%s\" in zone \"%s\"\n",
+						   id,
+						   zone);
+			else
+				ods_printf(sockfd,
+						   "No KSK key matches keytag \"%u\" in zone \"%s\"\n",
+						   keytag,
+						   zone);
+		} else {
+			if (bZoneModified) {
+				// Update key states for the zone in the database.
+				if (!OrmMessageUpdate(context))
+					LOG_AND_RETURN_1("unable to update zone %s in the database",zone);
+
+				// Commit updated records to the database.
+				if (!transaction.commit())
+					LOG_AND_RETURN_1("unable to commit updated zone %s to the database",zone);
+				
+				ods_log_debug("[%s] key states have been updated",module_str);
+				ods_printf(sockfd,"update of key states completed.\n");
+			} else {
+				ods_log_debug("[%s] key states are unchanged",module_str);
+				ods_printf(sockfd,"key states are unchanged\n");
+			}
+		}
+	}
+	
+	#undef LOG_AND_RETURN
+	#undef LOG_AND_RETURN_1
+}
+
 void 
 perform_keystate_ds_seen(int sockfd, engineconfig_type *config,
                          const char *zone, const char *id, uint16_t keytag)
 {
-    char buf[ODS_SE_MAXLINE];
-    const char *datastore = config->datastore;
-    
 	GOOGLE_PROTOBUF_VERIFY_VERSION;
-    
-    std::auto_ptr< ::ods::keystate::KeyStateDocument >
-    keystateDoc(new ::ods::keystate::KeyStateDocument);
-    {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (fd != -1) {
-            if (keystateDoc->ParseFromFileDescriptor(fd)) {
-                ods_log_debug("[%s] keys have been loaded",
-                              module_str);
-                close(fd);
-            } else {
-                ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                              module_str,datapath.c_str());
-                close(fd);
-                return;
-            }
-        } else {
-            ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                          module_str,datapath.c_str());
-            return;
-        }
-    }
-    
-    if (!(zone && (id || keytag))) {
-        
-        // list all keys that have submitted flag set.
-        
-        (void)snprintf(buf, ODS_SE_MAXLINE,
-                       "Database set to: %s\n"
-                       "Submitted Keys:\n"
-                       "Zone:                           "
-                       "Key role:     "
-                       "Keytag:       "
-                       "Id:                                      "
-                       "\n"
-                       ,datastore
-                       );
-        ods_writen(sockfd, buf, strlen(buf));
-        
-        for (int z=0; z<keystateDoc->zones_size(); ++z) {
-            
-            const ::ods::keystate::EnforcerZone &enfzone = keystateDoc->zones(z);
-            for (int k=0; k<enfzone.keys_size(); ++k) {
-                const ::ods::keystate::KeyData &key = enfzone.keys(k);
-                
-                // ZSKs are never trust anchors so skip them.
-                if (key.role() == ::ods::keystate::ZSK)
-                    continue;
-                
-                // Skip KSKs with a zero length id, they are placeholder keys.
-                if (key.locator().size()==0)
-                    continue;
-                
-                if (key.ds_at_parent()!=::ods::keystate::submitted)
-                    continue;
-                
-                std::string keyrole = keyrole_Name(key.role());
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "%-31s %-13s %-13u %-40s\n",
-                               enfzone.name().c_str(),
-                               keyrole.c_str(),
-                               key.keytag(),
-                               key.locator().c_str()
-                               );
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-        }
-        return;
-    }
-    
-    // Try to change the state of a specific submitted key back to unsubmitted.
-    bool id_match = false;
-    bool bKeyStateModified = false;
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
-        
-        ::ods::keystate::EnforcerZone *enfzone = keystateDoc->mutable_zones(z);
-        for (int k=0; k<enfzone->keys_size(); ++k) {
-            const ::ods::keystate::KeyData &key = enfzone->keys(k);
-            
-            // ZSKs are never trust anchors so skip them.
-            if (key.role() == ::ods::keystate::ZSK)
-                continue;
-            
-            // Skip KSKs with a zero length id, they are placeholder keys.
-            if (key.locator().size()==0)
-                continue;
-            
-            // Skip when zone doesn't match
-            if (enfzone->name()!=zone)
-                continue;
-            
-            if (id && key.locator()==id || keytag && key.keytag()==keytag ) {
-                id_match = true;
-                
-                if (key.ds_at_parent()!=::ods::keystate::submitted) {
-                    
-                    std::string dsatparentname =
-                        dsatparent_Name(key.ds_at_parent());
-                    (void)snprintf(buf, ODS_SE_MAXLINE, 
-                                   "Key that matches id \"%s\" in zone "
-                                   "\"%s\" is not submitted but %s\n",
-                                   key.locator().c_str(), zone,
-                                   dsatparentname.c_str());
-                    ods_writen(sockfd, buf, strlen(buf));
-                    break;
-                }
-                
-                bKeyStateModified = true;
-                
-                ::ods::keystate::KeyData *kd =
-                    keystateDoc->mutable_zones(z)->mutable_keys(k);
-                kd->set_ds_at_parent(::ods::keystate::seen);
-                enfzone->set_next_change(0); // reschedule immediately
-            }
-        }
-    }
-    
-    if (!id_match) {
-        if (id)
-            (void)snprintf(buf, ODS_SE_MAXLINE, 
-                           "No KSK key matches id \"%s\" in zone \"%s\"\n",
-                           id, zone);
-        else
-            (void)snprintf(buf, ODS_SE_MAXLINE, 
-                           "No KSK key matches keytag \"%u\" in zone \"%s\"\n",
-                           keytag, zone);
-        ods_writen(sockfd, buf, strlen(buf));
-    }
-    
-    // Persist the keystate zones back to disk as they may have
-    // been changed by the enforcer update
-    if (bKeyStateModified) {
-        if (keystateDoc->IsInitialized()) {
-            std::string datapath(datastore);
-            datapath += ".keystate.pb";
-            int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
-            if (keystateDoc->SerializeToFileDescriptor(fd)) {
-                ods_log_debug("[%s] key states have been updated",
-                              module_str);
-                
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "update of key states completed.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            } else {
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "error: key states file could not be written.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-            close(fd);
-        } else {
-            (void)snprintf(buf, ODS_SE_MAXLINE,
-                           "error: a message in the key states is missing "
-                           "mandatory information.\n");
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-    }
+	OrmConnRef conn;
+	if (ods_orm_connect(sockfd, config, conn)) {
+		// list key states with ds-seen state
+		if (!(zone && (id || keytag)))
+			list_keys_submitted(conn, sockfd, config->datastore);
+		else
+			change_keys_submitted_to_seen(conn, sockfd, zone, id, keytag);
+	}
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -14,15 +14,13 @@
 void
 help_keystate_ds_submit_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
+    ods_printf(sockfd,
         "key ds-submit   list KSK keys that should be submitted to the parent.\n"
         "  --zone <zone> (aka -z) force submit of KSK key for zone <zone>.\n"
         "  --id <id>     (aka -k) force submit of KSK key with id <id>.\n"
         "  --auto        (aka -a) perform submit for all keys that have "
                         "the submit flag set.\n"
         );
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
 int
@@ -52,8 +50,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
     
@@ -65,8 +62,7 @@
     if (argc) {
         ods_log_warning("[%s] unknown arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"unknown arguments\n");
         return 1; // errors, but handled
     }
     
@@ -74,9 +70,8 @@
     time_t tstart = time(NULL);
     perform_keystate_ds_submit(sockfd,engine->config,zone,id,bAutomatic?1:0);
     if (!zone && !id) {
-        (void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
-                       scmd,time(NULL)-tstart);
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"%s completed in %ld seconds.\n",
+				   scmd,time(NULL)-tstart);
     }
 
     return 1;

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_cmd.h
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_cmd.h	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_cmd.h	2012-01-05 10:04:41 UTC (rev 6026)
@@ -10,7 +10,7 @@
 void help_keystate_ds_submit_cmd(int sockfd);
 
 int handled_keystate_ds_submit_cmd(int sockfd, engine_type* engine,
-                                   const char *cmd, ssize_t n);
+								   const char *cmd, ssize_t n);
 
 #ifdef __cplusplus
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_ds_submit_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -11,38 +11,40 @@
 #include "policy/kasp.pb.h"
 #include "xmlext-pb/xmlext-rd.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
+
 #include <memory>
 #include <fcntl.h>
 
 static const char *module_str = "keystate_ds_submit_task";
 
-static uint16_t submit_dnskey_by_id(int sockfd,
-                                    const char *ds_submit_command,
-                                    const char *id,
-                                    ::ods::keystate::keyrole role,
-                                    const char *zone,
-                                    int algorithm,
-                                    uint32_t ttl)
+static uint16_t
+submit_dnskey_by_id(int sockfd,
+					const char *ds_submit_command,
+					const char *id,
+					::ods::keystate::keyrole role,
+					const char *zone,
+					int algorithm,
+					uint32_t ttl)
 {
-    char buf[ODS_SE_MAXLINE];
-
     /* Code to output the DNSKEY record  (stolen from hsmutil) */
     hsm_ctx_t *hsm_ctx = hsm_create_context();
     if (!hsm_ctx) {
-        ods_log_error("[%s] Could not connect to HSM", module_str);
-        (void)snprintf(buf,ODS_SE_MAXLINE, "Could not connect to HSM\n");
-        ods_writen(sockfd, buf, strlen(buf));
-        return false;
+		ods_log_error_and_printf(sockfd,
+								 module_str,
+								 "could not connect to HSM");
+        return 0;
     }
     hsm_key_t *key = hsm_find_key_by_id(hsm_ctx, id);
     
     if (!key) {
-        ods_log_error("[%s] key %s not found in any HSM",
-                      module_str,id);
-        (void)snprintf(buf,ODS_SE_MAXLINE, "key %s not found in any HSM\n", id);
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_log_error_and_printf(sockfd,
+								 module_str,
+								 "key %s not found in any HSM",
+								 id);
         hsm_destroy_context(hsm_ctx);
-        return false;
+        return 0;
     }
     
     char *dnskey_rr_str;
@@ -93,47 +95,43 @@
         FILE *fp = popen(ds_submit_command, "w");
         if (fp == NULL) {
             keytag = 0;
-            ods_log_error("[%s] Failed to run command: %s: %s",
-                          module_str,ds_submit_command,strerror(errno));
-            (void)snprintf(buf,ODS_SE_MAXLINE,"failed to run command: %s: %s\n",
-                           ds_submit_command,strerror(errno));
-            ods_writen(sockfd, buf, strlen(buf));
-            
+            ods_log_error_and_printf(sockfd,
+									 module_str,
+									 "failed to run command: %s: %s",
+									 ds_submit_command,
+									 strerror(errno));
         } else {
             int bytes_written = fprintf(fp, "%s", dnskey_rr_str);
             if (bytes_written < 0) {
                 keytag = 0;
-                ods_log_error("[%s] Failed to write to %s: %s",
-                              module_str,ds_submit_command,strerror(errno));
-                (void)snprintf(buf,ODS_SE_MAXLINE,"failed to write to %s: %s\n",
-                               ds_submit_command,strerror(errno));
-                               ods_writen(sockfd, buf, strlen(buf));
-                
+                ods_log_error_and_printf(sockfd,
+										 module_str,
+										 "[%s] Failed to write to %s: %s",
+										 ds_submit_command,
+										 strerror(errno));
             } else {
             
                 if (pclose(fp) == -1) {
                     keytag = 0;
-                    ods_log_error("[%s] Failed to close %s: %s",
-                                  module_str,ds_submit_command,strerror(errno));
-                    (void)snprintf(buf,ODS_SE_MAXLINE,"failed to close %s: %s\n",
-                                   ds_submit_command,strerror(errno));
-                    ods_writen(sockfd, buf, strlen(buf));
-                    
+                    ods_log_error_and_printf(sockfd,
+											 module_str,
+											 "failed to close %s: %s",
+											 ds_submit_command,
+											 strerror(errno));
                 } else {
-                    (void)snprintf(buf,ODS_SE_MAXLINE, 
-                                   "key %s submitted to %s\n", 
-                                   id, ds_submit_command);
-                    ods_writen(sockfd, buf, strlen(buf));
+                    ods_printf(sockfd,
+							   "key %s submitted to %s\n",
+							   id,
+							   ds_submit_command);
                 }
             }
         }
     } else {
         keytag = 0;
-        ods_log_error("[%s] No Delegation Signer Submit Command configured "
-                      "in conf.xml.",module_str);
-        (void)snprintf(buf,ODS_SE_MAXLINE,
-                       "no ds submit command configured in conf.xml.\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_log_error_and_printf(sockfd,
+								 module_str,
+								 "no \"DelegationSignerSubmitCommand\" binary "
+								 "configured in conf.xml.");
     }
         
     LDNS_FREE(dnskey_rr_str);
@@ -143,253 +141,272 @@
     return keytag;
 }
 
-static const ::ods::kasp::Policy *
-find_kasp_policy_for_zone(const ::ods::kasp::KASP &kasp,
-                          const ::ods::keystate::EnforcerZone &ks_zone)
+static bool
+load_kasp_policy(OrmConn conn,const std::string &name,
+				 ::ods::kasp::Policy &policy)
 {
-    // Find the policy associated with the zone.
-    for (int p=0; p<kasp.policies_size(); ++p) {
-        if (kasp.policies(p).name() == ks_zone.policy()) {
-            ods_log_debug("[%s] policy %s found for zone %s",
-                          module_str,ks_zone.policy().c_str(),
-                          ks_zone.name().c_str());
-            return &kasp.policies(p);
-        }
-    }
-    ods_log_error("[%s] policy %s could not be found for zone %s",
-                  module_str,ks_zone.policy().c_str(),
-                  ks_zone.name().c_str());
-    return NULL;
+	std::string qname;
+	if (!OrmQuoteStringValue(conn, name, qname))
+		return false;
+	
+	OrmResultRef rows;
+	if (!OrmMessageEnumWhere(conn,policy.descriptor(),rows,
+							 "name=%s",qname.c_str()))
+		return false;
+	
+	if (!OrmFirst(rows))
+		return false;
+	
+	return OrmGetMessage(rows, policy, true);
 }
 
-void 
-perform_keystate_ds_submit(int sockfd, engineconfig_type *config,
-                           const char *zone, const char *id, int bauto)
+static void
+submit_keys(OrmConn conn,
+			int sockfd,
+			const char *zone,
+			const char *id,
+			const char *datastore,
+			const char *ds_submit_command)
 {
-    char buf[ODS_SE_MAXLINE];
-    const char *datastore = config->datastore;
-    const char *ds_submit_command = config->delegation_signer_submit_command;
+	#define LOG_AND_RETURN(errmsg)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg);return;}while(0)
+	#define LOG_AND_RETURN_1(errmsg,p)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg,p);return;}while(0)
 
-	GOOGLE_PROTOBUF_VERIFY_VERSION;
-    
-    std::auto_ptr< ::ods::kasp::KaspDocument >
-    kaspDoc(new ::ods::kasp::KaspDocument);
-    {
-        std::string datapath(datastore);
-        datapath += ".policy.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (fd != -1) {
-            if (kaspDoc->ParseFromFileDescriptor(fd)) {
-                ods_log_debug("[%s] policies have been loaded",
-                              module_str);
-            } else {
-                ods_log_error("[%s] policies could not be loaded from \"%s\"",
-                              module_str,datapath.c_str());
-                (void)snprintf(buf,ODS_SE_MAXLINE, "policies could not be loaded "
-                               "from \"%s\"\n", 
-                               datapath.c_str());
-                ods_writen(sockfd, buf, strlen(buf));
-                return;
-            }
-            close(fd);
-        } else {
-            ods_log_error("[%s] file \"%s\" could not be opened",
-                          module_str,datapath.c_str());
-            (void)snprintf(buf,ODS_SE_MAXLINE,
-                           "file \"%s\" could not be opened\n", 
-                           datapath.c_str());
-            ods_writen(sockfd, buf, strlen(buf));
-            return;
-        }
-    }
+	OrmTransactionRW transaction(conn);
+	if (!transaction.started())
+		LOG_AND_RETURN("transaction not started");
 
-    std::auto_ptr< ::ods::keystate::KeyStateDocument >
-        keystateDoc(new ::ods::keystate::KeyStateDocument);
-    {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (fd != -1) {
-            if (keystateDoc->ParseFromFileDescriptor(fd)) {
-                ods_log_debug("[%s] keys have been loaded",
-                              module_str);
-            } else {
-                ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                              module_str,datapath.c_str());
-                (void)snprintf(buf,ODS_SE_MAXLINE, "keys could not be loaded "
-                               "from \"%s\"\n", 
-                               datapath.c_str());
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-            close(fd);
-        } else {
-            ods_log_error("[%s] file \"%s\" could not be opened",
-                          module_str,datapath.c_str());
-            (void)snprintf(buf,ODS_SE_MAXLINE,
-                           "file \"%s\" could not be opened\n", 
-                           datapath.c_str());
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-    }
+	{	OrmResultRef rows;
+		::ods::keystate::EnforcerZone enfzone;
+		if (zone) {
+			std::string qzone;
+			if (!OrmQuoteStringValue(conn, std::string(zone), qzone))
+				LOG_AND_RETURN("quoting string value failed");
+			
+			if (!OrmMessageEnumWhere(conn,enfzone.descriptor(),rows,"name = %s",qzone.c_str()))
+				LOG_AND_RETURN("zone enumeration failed");
+		} else {
+			if (!OrmMessageEnum(conn,enfzone.descriptor(),rows))
+				LOG_AND_RETURN("zone enumeration failed");
+		}
 
-    // Evalutate parameters and submit keys to the parent when instructed
-    // to do so.
-    if (id || zone || bauto) {
-        bool bFlagsChanged = false;
-        for (int z=0; z<keystateDoc->zones_size(); ++z) {
-            const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
-            for (int k=0; k<enfzone.keys_size(); ++k) {
-                const ::ods::keystate::KeyData &key = enfzone.keys(k);
+		bool bZonesModified = false;
 
-                // Don't ever submit ZSKs to the parent.
-                if (key.role()==::ods::keystate::ZSK)
-                    continue;
+		if (!OrmFirst(rows)) {
+			if (zone)
+				LOG_AND_RETURN_1("zone %s not found",zone);
+		} else {
+			
+			for (bool next=true; next; next=OrmNext(rows)) {
+				
+				OrmContextRef context;
+				if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true, context))
+					LOG_AND_RETURN("retrieving zone from database failed");
+				
+				// Try to change the state of a specific 'submitted' key to 'seen'.
+				bool bKeyModified = false;
+				for (int k=0; k<enfzone.keys_size(); ++k) {
+					const ::ods::keystate::KeyData &key = enfzone.keys(k);
+						
+					// Don't ever submit ZSKs to the parent.
+					if (key.role()==::ods::keystate::ZSK)
+						continue;
+					
+					// Onlyt submit KSKs that have the submit flag set.
+					if (key.ds_at_parent()!=::ods::keystate::submit)
+						continue;
+				
+					// Find the policy for the zone and get the ttl for the dnskey
+					uint32_t dnskey_ttl = 0;
+					::ods::kasp::Policy policy;
+					if (!load_kasp_policy(conn, enfzone.policy(), policy)) {
+						ods_log_error_and_printf(sockfd,module_str,
+												 "unable to load policy %s",
+												 enfzone.policy().c_str());
+						continue;
+					}
+					dnskey_ttl = policy.keys().ttl();
 
-                // Onlyt submit KSKs that have the submit flag set.
-                if (key.ds_at_parent()!=::ods::keystate::submit)
-                    continue;
-                
-                // Find the policy for the zone and get the ttl for the dnskey
-                uint32_t dnskey_ttl = 0;
-                const ::ods::kasp::Policy *policy = 
-                find_kasp_policy_for_zone(kaspDoc->kasp(), enfzone);
-                if (policy) {
-                    dnskey_ttl = policy->keys().ttl();
-                }
+					if (id) {
+						// --id <id>
+						//     Force submit key to the parent for specific key id.
+						if (key.locator()==id) {
+							// submit key with this id to the parent
+							uint16_t keytag = 
+							submit_dnskey_by_id(sockfd,ds_submit_command,
+												key.locator().c_str(),
+												key.role(),
+												enfzone.name().c_str(),
+												key.algorithm(),
+												dnskey_ttl);
+							if (keytag)
+							{
+								::ods::keystate::KeyData *kd =
+									enfzone.mutable_keys(k);
+								kd->set_ds_at_parent(::ods::keystate::submitted);
+								kd->set_keytag(keytag);
+								bKeyModified = true;
+							}
+						}
+					} else {
+						if (zone) {
+							// --zone <zone>
+							//     Force submit key to the parent for specific zone.
+							if (enfzone.name()==zone) {
+								// submit key for this zone to the parent
+								uint16_t keytag = 
+								submit_dnskey_by_id(sockfd,ds_submit_command,
+													key.locator().c_str(),
+													key.role(),
+													enfzone.name().c_str(),
+													key.algorithm(),
+													dnskey_ttl);
+								if (keytag)
+								{
+									::ods::keystate::KeyData *kd = 
+										enfzone.mutable_keys(k);
+									kd->set_ds_at_parent(::ods::keystate::submitted);
+									kd->set_keytag(keytag);
+									bKeyModified = true;
+								}
+							}
+						} else {
+							// --auto
+							//     Submit all keys to the parent that have
+							//     the submit flag set.
+							uint16_t keytag = 
+							submit_dnskey_by_id(sockfd,ds_submit_command,
+												key.locator().c_str(),
+												key.role(),
+												enfzone.name().c_str(),
+												key.algorithm(),
+												dnskey_ttl);
+							if (keytag)
+							{
+								::ods::keystate::KeyData *kd = 
+									enfzone.mutable_keys(k);
+								kd->set_ds_at_parent(::ods::keystate::submitted);
+								kd->set_keytag(keytag);
+								bKeyModified = true;
+							}
+						}
+					}
+				}
+				
+				if (bKeyModified) {
+					if (!OrmMessageUpdate(context))
+						LOG_AND_RETURN_1("failed to update zone %s in the database", enfzone.name().c_str());
 
-                if (id) {
-                    // --id <id>
-                    //     Force submit key to the parent for specific key id.
-                    if (key.locator()==id) {
-                        // submit key with this id to the parent
-                        uint16_t keytag = 
-                            submit_dnskey_by_id(sockfd,ds_submit_command,
-                                                key.locator().c_str(),
-                                                key.role(),
-                                                enfzone.name().c_str(),
-                                                key.algorithm(),
-                                                dnskey_ttl);
-                        if (keytag)
-                        {
-                            bFlagsChanged = true;
-                            ::ods::keystate::KeyData *kd = 
-                            keystateDoc->mutable_zones(z)->mutable_keys(k);
-                            kd->set_ds_at_parent(::ods::keystate::submitted);
-                            kd->set_keytag(keytag);
-                        }
-                    }
-                } else {
-                    if (zone) {
-                        // --zone <zone>
-                        //     Force submit key to the parent for specific zone.
-                        if (enfzone.name()==zone) {
-                            // submit key for this zone to the parent
-                            uint16_t keytag = 
-                                submit_dnskey_by_id(sockfd,ds_submit_command,
-                                                    key.locator().c_str(),
-                                                    key.role(),
-                                                    enfzone.name().c_str(),
-                                                    key.algorithm(),
-                                                    dnskey_ttl);
-                            if (keytag)
-                            {
-                                bFlagsChanged = true;
-                                ::ods::keystate::KeyData *kd = 
-                                keystateDoc->mutable_zones(z)->mutable_keys(k);
-                                kd->set_ds_at_parent(::ods::keystate::submitted);
-                                kd->set_keytag(keytag);
-                            }
-                        }
-                    } else {
-                        // --auto
-                        //     Submit all keys to the parent that have
-                        //     the submit flag set.
-                        uint16_t keytag = 
-                            submit_dnskey_by_id(sockfd,ds_submit_command,
-                                                key.locator().c_str(),
-                                                key.role(),
-                                                enfzone.name().c_str(),
-                                                key.algorithm(),
-                                                dnskey_ttl);
-                        if (keytag)
-                        {
-                            bFlagsChanged = true;
-                            ::ods::keystate::KeyData *kd = 
-                            keystateDoc->mutable_zones(z)->mutable_keys(k);
-                            kd->set_ds_at_parent(::ods::keystate::submitted);
-                            kd->set_keytag(keytag);
-                        }
-                    }
-                }
-            }
-        }
-        
-        if (bFlagsChanged) {
-            // Persist the keystate zones back to disk as they may have
-            // been changed by the enforcer update
-            if (keystateDoc->IsInitialized()) {
-                std::string datapath(datastore);
-                datapath += ".keystate.pb";
-                int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
-                if (keystateDoc->SerializeToFileDescriptor(fd)) {
-                    ods_log_debug("[%s] key states have been updated",
-                                  module_str);
-                    
-                    (void)snprintf(buf, ODS_SE_MAXLINE,
-                                   "update of key states completed.\n");
-                    ods_writen(sockfd, buf, strlen(buf));
-                } else {
-                    (void)snprintf(buf, ODS_SE_MAXLINE,
-                                   "error: key states file could not be written.\n");
-                    ods_writen(sockfd, buf, strlen(buf));
-                }
-                close(fd);
-            } else {
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "error: a message in the key states is missing "
-                               "mandatory information.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-        }
-        
-        return;
-    }
+					bZonesModified = true;
+				}
+			}
+			
+			// we no longer need the query result, so release it.
+			rows.release();
+			
+		}
 
-    // List the keys with submit flags.
-    (void)snprintf(buf, ODS_SE_MAXLINE,
-                   "Database set to: %s\n"
-                   "Submit Keys:\n"
-                   "Zone:                           "
-                   "Key role:     "
-                   "Id:                                      "
-                   "\n"
-                   ,datastore
-                   );
-    ods_writen(sockfd, buf, strlen(buf));
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
-        const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
-        for (int k=0; k<enfzone.keys_size(); ++k) {
-            const ::ods::keystate::KeyData &key = enfzone.keys(k);
-            // Don't suggest ZSKs can be submitted, leave them out of the list.
-            if (key.role() == ::ods::keystate::ZSK)
-                continue;
+		// Report back the status of the operation.
+		if (bZonesModified) {
+			// Commit updated records to the database.
+			if (!transaction.commit())
+				LOG_AND_RETURN_1("unable to commit updated zone %s to the database",zone);
+			
+			ods_log_debug("[%s] key states have been updated",module_str);
+			ods_printf(sockfd,"update of key states completed.\n");
+		} else {
+			ods_log_debug("[%s] key states are unchanged",module_str);
+			if (id)
+				ods_printf(sockfd,
+						   "No key state changes for id \"%s\"\n",
+						   id);
+			else
+				if (zone)
+					ods_printf(sockfd,
+							   "No key state changes for zone \"%s\"\n",
+							   zone);
+				else
+					ods_printf(sockfd,"key states are unchanged\n");
+		}
+	}
+	
+	#undef LOG_AND_RETURN
+	#undef LOG_AND_RETURN_1
+}
 
-            // Only show keys that have the submit flag set.
-            if (key.ds_at_parent()!=::ods::keystate::submit)
-                continue;
-            
-            std::string keyrole = keyrole_Name(key.role());
-            (void)snprintf(buf, ODS_SE_MAXLINE,
-                           "%-31s %-13s %-40s\n",
-                           enfzone.name().c_str(),
-                           keyrole.c_str(),
-                           key.locator().c_str()
-                           );
-            ods_writen(sockfd, buf, strlen(buf));
-        }
+static void
+list_keys_submit(OrmConn conn, int sockfd, const char *datastore)
+{
+	#define LOG_AND_RETURN(errmsg)\
+		do{ods_log_error_and_printf(sockfd,module_str,errmsg);return;}while(0)
+	
+	// List the keys with submit flags.
+    ods_printf(sockfd,
+			   "Database set to: %s\n"
+			   "Submit Keys:\n"
+			   "Zone:                           "
+			   "Key role:     "
+			   "Id:                                      "
+			   "\n"
+			   ,datastore
+			   );
+
+	OrmTransaction transaction(conn);
+	if (!transaction.started())
+		LOG_AND_RETURN("transaction not started");
+	
+	{	OrmResultRef rows;
+		::ods::keystate::EnforcerZone enfzone;
+		if (!OrmMessageEnum(conn,enfzone.descriptor(),rows))
+			LOG_AND_RETURN("zone enumeration failed");
+
+		for (bool next=OrmFirst(rows); next; next=OrmNext(rows)) {
+			
+			if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true))
+				LOG_AND_RETURN("retrieving zone from database failed");
+			
+			for (int k=0; k<enfzone.keys_size(); ++k) {
+				const ::ods::keystate::KeyData &key = enfzone.keys(k);
+
+				// Don't suggest ZSKs can be submitted, don't list them.
+				if (key.role() == ::ods::keystate::ZSK)
+					continue;
+				
+				// Only show keys that have the submit flag set.
+				if (key.ds_at_parent()!=::ods::keystate::submit)
+					continue;
+				
+				std::string keyrole = keyrole_Name(key.role());
+				ods_printf(sockfd,
+						   "%-31s %-13s %-40s\n",
+						   enfzone.name().c_str(),
+						   keyrole.c_str(),
+						   key.locator().c_str()
+						   );
+			}
+		}
     }
+	
+	#undef LOG_AND_RETURN
 }
 
+void 
+perform_keystate_ds_submit(int sockfd, engineconfig_type *config,
+                           const char *zone, const char *id, int bauto)
+{
+	GOOGLE_PROTOBUF_VERIFY_VERSION;
+	OrmConnRef conn;
+	if (ods_orm_connect(sockfd, config, conn)) {
+		// Evaluate parameters and submit keys to the parent when instructed to.
+		if (zone || id || bauto)
+			submit_keys(conn,sockfd,zone,id,config->datastore,
+						config->delegation_signer_submit_command);
+		else
+			list_keys_submit(conn,sockfd,config->datastore);
+	}
+}
+
 static task_type * 
 keystate_ds_submit_task_perform(task_type *task)
 {

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -13,17 +13,15 @@
 
 void help_keystate_export_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
+	ods_printf(sockfd,
         "key export      export trust anchors of a given zone\n"
         "  --zone <zone> (aka -z) export for the given zone.\n"
         "  [--dnskey]    export DNSKEY in BIND format (default).\n"
         "  [--ds]        export DS in BIND format.\n");
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
-int handled_keystate_export_cmd(int sockfd, engine_type* engine, const char *cmd,
-                              ssize_t n)
+int handled_keystate_export_cmd(int sockfd, engine_type* engine,
+								const char *cmd, ssize_t n)
 {
     char buf[ODS_SE_MAXLINE];
     const char *argv[8];
@@ -46,8 +44,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
     
@@ -58,15 +55,13 @@
     if (argc) {
         ods_log_warning("[%s] unknown arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"unknown arguments\n");
         return 1; // errors, but handled
     }
     if (!zone) {
         ods_log_warning("[%s] expected option --zone <zone> for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"expected --zone <zone> option\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"expected --zone <zone> option\n");
         return 1; // errors, but handled
     }
     

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_cmd.h
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_cmd.h	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_cmd.h	2012-01-05 10:04:41 UTC (rev 6026)
@@ -9,8 +9,8 @@
 
 void help_keystate_export_cmd(int sockfd);
 
-int handled_keystate_export_cmd(int sockfd, engine_type* engine,
-                                const char *cmd, ssize_t n);
+int handled_keystate_export_cmd(int sockfd, engine_type* engine, 
+								const char *cmd, ssize_t n);
 
 #ifdef __cplusplus
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_export_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -11,6 +11,9 @@
 #include "policy/kasp.pb.h"
 #include "xmlext-pb/xmlext-rd.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
+
 #include <memory>
 #include <fcntl.h>
 
@@ -114,184 +117,127 @@
     return keytag;
 }
 
-static const ::ods::kasp::Policy *
-find_kasp_policy_for_zone(const ::ods::kasp::KASP &kasp,
-                          const ::ods::keystate::EnforcerZone &ks_zone)
+static bool
+load_kasp_policy(OrmConn conn,const std::string &name,
+				 ::ods::kasp::Policy &policy)
 {
-    // Find the policy associated with the zone.
-    for (int p=0; p<kasp.policies_size(); ++p) {
-        if (kasp.policies(p).name() == ks_zone.policy()) {
-            ods_log_debug("[%s] policy %s found for zone %s",
-                          module_str,ks_zone.policy().c_str(),
-                          ks_zone.name().c_str());
-            return &kasp.policies(p);
-        }
-    }
-    ods_log_error("[%s] policy %s could not be found for zone %s",
-                  module_str,ks_zone.policy().c_str(),
-                  ks_zone.name().c_str());
-    return NULL;
+	std::string qname;
+	if (!OrmQuoteStringValue(conn, name, qname))
+		return false;
+	
+	OrmResultRef rows;
+	if (!OrmMessageEnumWhere(conn,policy.descriptor(),rows,
+							 "name=%s",qname.c_str()))
+		return false;
+	
+	if (!OrmFirst(rows))
+		return false;
+	
+	return OrmGetMessage(rows, policy, true);
 }
 
 void 
 perform_keystate_export(int sockfd, engineconfig_type *config, const char *zone,
                         int bds)
 {
-    char buf[ODS_SE_MAXLINE];
-    const char *datastore = config->datastore;
+	#define LOG_AND_RETURN(errmsg) do { ods_log_error_and_printf(\
+		sockfd,module_str,errmsg); return; } while (0)
+	#define LOG_AND_RETURN_1(errmsg,param) do { ods_log_error_and_printf(\
+		sockfd,module_str,errmsg,param); return; } while (0)
 
 	GOOGLE_PROTOBUF_VERIFY_VERSION;
     
-    std::auto_ptr< ::ods::kasp::KaspDocument >
-        kaspDoc(new ::ods::kasp::KaspDocument);
-    {
-        std::string datapath(datastore);
-        datapath += ".policy.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (fd != -1) {
-            if (kaspDoc->ParseFromFileDescriptor(fd)) {
-                ods_log_debug("[%s] policies have been loaded",
-                              module_str);
-            } else {
-                ods_log_error("[%s] policies could not be loaded from \"%s\"",
-                              module_str,datapath.c_str());
-                (void)snprintf(buf,ODS_SE_MAXLINE, "policies could not be loaded "
-                               "from \"%s\"\n", 
-                               datapath.c_str());
-                ods_writen(sockfd, buf, strlen(buf));
-                return;
-            }
-            close(fd);
-        } else {
-            ods_log_error("[%s] file \"%s\" could not be opened",
-                          module_str,datapath.c_str());
-            (void)snprintf(buf,ODS_SE_MAXLINE,
-                           "file \"%s\" could not be opened\n", 
-                           datapath.c_str());
-            ods_writen(sockfd, buf, strlen(buf));
-            return;
-        }
-    }
+	OrmConnRef conn;
+	if (!ods_orm_connect(sockfd, config, conn))
+		return; // error already reported.
+	
+	{	OrmTransactionRW transaction(conn);
+		if (!transaction.started())
+			LOG_AND_RETURN("transaction not started");
 
-    std::auto_ptr< ::ods::keystate::KeyStateDocument >
-        keystateDoc(new ::ods::keystate::KeyStateDocument);
-    {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (fd!=-1) {
-            if (keystateDoc->ParseFromFileDescriptor(fd)) {
-                ods_log_debug("[%s] keys have been loaded",
-                              module_str);
-            } else {
-                ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                              module_str,datapath.c_str());
-                (void)snprintf(buf,ODS_SE_MAXLINE, "keys could not be loaded "
-                               "from \"%s\"\n", 
-                               datapath.c_str());
-                ods_writen(sockfd, buf, strlen(buf));
-                return;
-            }
-            close(fd);
-        } else {
-            ods_log_error("[%s] file \"%s\" could not be opened",
-                          module_str,datapath.c_str());
-            (void)snprintf(buf,ODS_SE_MAXLINE,
-                           "file \"%s\" could not be opened\n", 
-                           datapath.c_str());
-            ods_writen(sockfd, buf, strlen(buf));
-            return;
-        }
-    }
-    
-    bool bSubmitChanged = false;
-    bool bRetractChanged = false;
-    bool bKeytagChanged = false;
-    std::string zname(zone);
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
+		std::string qzone;
+		if (!OrmQuoteStringValue(conn, std::string(zone), qzone))
+			LOG_AND_RETURN("quoting string value failed");
+		
+		{	OrmResultRef rows;
+			::ods::keystate::EnforcerZone enfzone;
+			if (!OrmMessageEnumWhere(conn,enfzone.descriptor(),
+									 rows,"name = %s",qzone.c_str()))
+				LOG_AND_RETURN("zone enumeration failed");
+			
+			if (!OrmFirst(rows)) {
+				ods_printf(sockfd,"zone %s not found\n",zone);
+				return;
+			}
+			
+			OrmContextRef context;
+			if (!OrmGetMessage(rows, enfzone, /*zones + keys*/true, context))
+				LOG_AND_RETURN("retrieving zone from database failed");
+			
+			// we no longer need the query result, so release it.
+			rows.release();
 
-        const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
-        if (enfzone.name() != zname) 
-            continue;
-        
-        uint32_t dnskey_ttl = 0;
-        const ::ods::kasp::Policy *policy = 
-            find_kasp_policy_for_zone(kaspDoc->kasp(), enfzone);
-        if (policy) {
-            dnskey_ttl = policy->keys().ttl();
-        }
+			// Retrieve the dnskey ttl from the policy associated with the zone.
+			::ods::kasp::Policy policy;
+			if (!load_kasp_policy(conn, enfzone.policy(), policy))
+				LOG_AND_RETURN_1("policy %s not found",enfzone.policy().c_str());
+			uint32_t dnskey_ttl = policy.keys().ttl();
 
-        for (int k=0; k<enfzone.keys_size(); ++k) {
-            const ::ods::keystate::KeyData &key = enfzone.keys(k);
-            if (key.role()==::ods::keystate::ZSK)
-                continue;
-            
-            if (key.ds_at_parent()!=::ods::keystate::submit
-                && key.ds_at_parent()!=::ods::keystate::submitted
-                && key.ds_at_parent()!=::ods::keystate::retract
-                && key.ds_at_parent()!=::ods::keystate::retracted
-                )
-                continue;
-            
-            std::string dnskey;
-            uint16_t keytag = dnskey_from_id(dnskey,key.locator().c_str(),
-                                             key.role(),
-                                             enfzone.name().c_str(),
-                                             key.algorithm(),bds,
-                                             dnskey_ttl);
-            if (keytag) {
-                ods_writen(sockfd, dnskey.c_str(), dnskey.size());
-                bSubmitChanged = key.ds_at_parent()==::ods::keystate::submit;
-                bRetractChanged = key.ds_at_parent()==::ods::keystate::retract;
-                bKeytagChanged = key.keytag()!=keytag;
-                if (bSubmitChanged) {
-                    ::ods::keystate::KeyData *kd = 
-                        keystateDoc->mutable_zones(z)->mutable_keys(k);
-                    kd->set_ds_at_parent(::ods::keystate::submitted);
-                }
-                if (bRetractChanged) {
-                    ::ods::keystate::KeyData *kd = 
-                        keystateDoc->mutable_zones(z)->mutable_keys(k);
-                    kd->set_ds_at_parent(::ods::keystate::retracted);
-                }
-                if (bKeytagChanged) {
-                    ::ods::keystate::KeyData *kd = 
-                    keystateDoc->mutable_zones(z)->mutable_keys(k);
-                    kd->set_keytag(keytag);
-                }
-            } else {
-                ods_log_error("[%s] unable to find key with id %s",
-                              module_str,key.locator().c_str());
-                (void)snprintf(buf,ODS_SE_MAXLINE, "key %s not found\n", 
-                               key.locator().c_str());
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-        }
-    }
+			bool bSubmitChanged = false;
+			bool bRetractChanged = false;
+			bool bKeytagChanged = false;
+			
+			for (int k=0; k<enfzone.keys_size(); ++k) {
+				const ::ods::keystate::KeyData &key = enfzone.keys(k);
+				if (key.role()==::ods::keystate::ZSK)
+					continue;
+				
+				if (key.ds_at_parent()!=::ods::keystate::submit
+					&& key.ds_at_parent()!=::ods::keystate::submitted
+					&& key.ds_at_parent()!=::ods::keystate::retract
+					&& key.ds_at_parent()!=::ods::keystate::retracted
+					)
+					continue;
+				
+				std::string dnskey;
+				uint16_t keytag = dnskey_from_id(dnskey,key.locator().c_str(),
+												 key.role(),
+												 enfzone.name().c_str(),
+												 key.algorithm(),bds,
+												 dnskey_ttl);
+				if (keytag) {
+					ods_writen(sockfd, dnskey.c_str(), dnskey.size());
+					bSubmitChanged = key.ds_at_parent()==::ods::keystate::submit;
+					bRetractChanged = key.ds_at_parent()==::ods::keystate::retract;
+					bKeytagChanged = key.keytag()!=keytag;
+					if (bSubmitChanged) {
+						::ods::keystate::KeyData *kd = enfzone.mutable_keys(k);
+						kd->set_ds_at_parent(::ods::keystate::submitted);
+					}
+					if (bRetractChanged) {
+						::ods::keystate::KeyData *kd = enfzone.mutable_keys(k);
+						kd->set_ds_at_parent(::ods::keystate::retracted);
+					}
+					if (bKeytagChanged) {
+						::ods::keystate::KeyData *kd = enfzone.mutable_keys(k);
+						kd->set_keytag(keytag);
+					}
+				} else
+					LOG_AND_RETURN_1("unable to find key with id %s",
+									 key.locator().c_str());
+			}
     
-    if (bSubmitChanged || bRetractChanged || bKeytagChanged) {
-        // Persist the keystate zones back to disk as they may have
-        // been changed by the enforcer update
-        if (keystateDoc->IsInitialized()) {
-            std::string datapath(datastore);
-            datapath += ".keystate.pb";
-            int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
-            if (fd!=-1) {
-                if (keystateDoc->SerializeToFileDescriptor(fd)) {
-                    ods_log_debug("[%s] key states have been updated",
-                                  module_str);
-                } else {
-                    ods_log_error("[%s] key states file could not be written",
-                                  module_str);
-                }
-                close(fd);
-            } else {
-                ods_log_error("[%s] key states file \"%s\"could not be opened "
-                              "for writing", module_str,datastore);
-            }
-        } else {
-            ods_log_error("[%s] a message in the key states is missing "
-                          "mandatory information", module_str);
-        }
-    }
+			if (bSubmitChanged || bRetractChanged || bKeytagChanged) {
+				// Update the zone recursively in the database as keystates
+				// have been changed because of the export
+				
+				if (!OrmMessageUpdate(context))
+					LOG_AND_RETURN("updating zone in the database failed");
+				
+				
+				if (!transaction.commit())
+					LOG_AND_RETURN("committing zone to the database failed");
+			}
+		}
+	}
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -13,12 +13,10 @@
 
 void help_keystate_list_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
+    ods_printf(sockfd,
         "key list        list all the keys used by a zone\n"
 //        "  --verbose     (aka -v) also show the id for every key.\n"
         );
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
 int handled_keystate_list_cmd(int sockfd, engine_type* engine, const char *cmd,
@@ -45,8 +43,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
     
@@ -54,17 +51,15 @@
     if (argc) {
         ods_log_warning("[%s] unknown arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"unknown arguments\n");
         return 1; // errors, but handled
     }
     
-    /* perform task immediately */
     time_t tstart = time(NULL);
+
     perform_keystate_list(sockfd,engine->config,bVerbose?1:0);
-    (void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
-                   scmd,time(NULL)-tstart);
-    ods_writen(sockfd, buf, strlen(buf));
+	
+	ods_printf(sockfd,"%s completed in %ld seconds.\n",scmd,time(NULL)-tstart);
     
     return 1;
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_cmd.h
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_cmd.h	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_cmd.h	2012-01-05 10:04:41 UTC (rev 6026)
@@ -9,8 +9,8 @@
 
 void help_keystate_list_cmd(int sockfd);
 
-int handled_keystate_list_cmd(int sockfd, engine_type* engine,
-                              const char *cmd, ssize_t n);
+int handled_keystate_list_cmd(int sockfd, engine_type* engine, const char *cmd,
+							  ssize_t n);
 
 #ifdef __cplusplus
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_list_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -8,6 +8,9 @@
 #include "keystate/keystate.pb.h"
 #include "xmlext-pb/xmlext-rd.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
+
 #include <fcntl.h>
 
 static const char *module_str = "keystate_list_task";
@@ -15,69 +18,74 @@
 void 
 perform_keystate_list(int sockfd, engineconfig_type *config, int bverbose)
 {
-    char buf[ODS_SE_MAXLINE];
-    const char *datastore = config->datastore;
-
 	GOOGLE_PROTOBUF_VERIFY_VERSION;
-    
-    ::ods::keystate::KeyStateDocument *keystateDoc =
-    new ::ods::keystate::KeyStateDocument;
-    {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (keystateDoc->ParseFromFileDescriptor(fd)) {
-            ods_log_debug("[%s] keys have been loaded",
-                          module_str);
-        } else {
-            ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                          module_str,datapath.c_str());
-        }
-        close(fd);
-    }
-    
-    (void)snprintf(buf, ODS_SE_MAXLINE,
-                   "Database set to: %s\n"
-                   "Keys:\n"
-                   "Zone:                           "
-                   "Key role:     "
-                   "DS:          "
-                   "DNSKEY:      "
-                   "RRSIGDNSKEY: "
-                   "RRSIG:       "
-                   "Pub: "
-                   "Act: "
-                   "Id:"
-                   "\n"
-                   ,datastore
-                   );
-    ods_writen(sockfd, buf, strlen(buf));
 
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
+	OrmConnRef conn;
+	if (!ods_orm_connect(sockfd, config, conn))
+		return; // error already reported.
+	
+	{	OrmTransaction transaction(conn);
+		if (!transaction.started()) {
+			ods_log_error("[%s] Could not start database transaction", module_str);
+			ods_printf(sockfd, "error: Could not start database transaction\n");
+			return;
+		}
+		
+		::ods::keystate::EnforcerZone zone;
+		
+		{	OrmResultRef rows;
+			if (!OrmMessageEnum(conn, zone.descriptor(),rows)) {
+				ods_log_error("[%s] error enumerating zones", module_str);
+				ods_printf(sockfd, "error enumerating zones\n");
+				return;
+			}
+			
+			ods_printf(sockfd,
+					   "Database set to: %s\n"
+					   "Keys:\n"
+					   "Zone:                           "
+					   "Key role:     "
+					   "DS:          "
+					   "DNSKEY:      "
+					   "RRSIGDNSKEY: "
+					   "RRSIG:       "
+					   "Pub: "
+					   "Act: "
+					   "Id:"
+					   "\n"
+					   ,config->datastore
+					   );
 
-        const ::ods::keystate::EnforcerZone &zone  = keystateDoc->zones(z);
-        
-        for (int k=0; k<zone.keys_size(); ++k) {
-            const ::ods::keystate::KeyData &key = zone.keys(k);
-            std::string keyrole = keyrole_Name(key.role());
-            std::string ds_rrstate = rrstate_Name(key.ds().state());
-            std::string dnskey_rrstate = rrstate_Name(key.dnskey().state());
-            std::string rrsigdnskey_rrstate = rrstate_Name(key.rrsigdnskey().state());
-            std::string rrsig_rrstate = rrstate_Name(key.rrsig().state());
-            (void)snprintf(buf, ODS_SE_MAXLINE,
-                       "%-31s %-13s %-12s %-12s %-12s %-12s %d %4d    %s\n",
-                       zone.name().c_str(),
-                       keyrole.c_str(),
-                       ds_rrstate.c_str(),
-                       dnskey_rrstate.c_str(),
-                       rrsigdnskey_rrstate.c_str(),
-                       rrsig_rrstate.c_str(),
-                       key.publish(),
-                       key.active_ksk()||key.active_zsk(),
-                       key.locator().c_str()
-                       );
-            ods_writen(sockfd, buf, strlen(buf));
-        }
+			for (bool next=OrmFirst(rows); next; next=OrmNext(rows)) {
+				
+				if (!OrmGetMessage(rows, zone, true)) {
+					ods_log_error("[%s] error reading zone", module_str);
+					ods_printf(sockfd, "error reading zone\n");
+					return;
+				}
+					
+				for (int k=0; k<zone.keys_size(); ++k) {
+					const ::ods::keystate::KeyData &key = zone.keys(k);
+					std::string keyrole = keyrole_Name(key.role());
+					std::string ds_rrstate = rrstate_Name(key.ds().state());
+					std::string dnskey_rrstate = rrstate_Name(key.dnskey().state());
+					std::string rrsigdnskey_rrstate = rrstate_Name(key.rrsigdnskey().state());
+					std::string rrsig_rrstate = rrstate_Name(key.rrsig().state());
+					ods_printf(sockfd, 
+							   "%-31s %-13s %-12s %-12s %-12s %-12s %d %4d    %s\n",
+							   zone.name().c_str(),
+							   keyrole.c_str(),
+							   ds_rrstate.c_str(),
+							   dnskey_rrstate.c_str(),
+							   rrsigdnskey_rrstate.c_str(),
+							   rrsig_rrstate.c_str(),
+							   key.publish(),
+							   key.active_ksk()||key.active_zsk(),
+							   key.locator().c_str()
+							   );
+				}
+			}
+		}
     }
 }
 

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_rollover_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_rollover_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_rollover_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -18,14 +18,12 @@
 
 void help_keystate_rollover_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
+    ods_printf(sockfd,
         "key rollover    rollover the key\n"
         "  --zone <zone> (aka -z) rollover key with id <id>.\n"
         "  [--keytype <keytype>]\n"
         "                (aka -t) type of the key KSK or ZSK (default all).\n"
         );
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
 int handled_keystate_rollover_cmd(int sockfd, engine_type* engine, const char *cmd,
@@ -52,8 +50,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
     
@@ -64,15 +61,13 @@
     if (argc) {
         ods_log_warning("[%s] unknown arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"unknown arguments\n");
         return 1; // errors, but handled
     }
     if (!zone) {
         ods_log_warning("[%s] expected option --zone <zone> for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"expected --zone <zone> option\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"expected --zone <zone> option\n");
         return 1; // errors, but handled
     }
 
@@ -92,23 +87,19 @@
                 } else {
                     ods_log_warning("[%s] given keytype \"%s\" invalid",
                                     module_str,keytype);
-                    (void)snprintf(buf, ODS_SE_MAXLINE, 
-                                   "given keytype \"%s\" invalid\n",
-                                   keytype);
-                    ods_writen(sockfd, buf, strlen(buf));
+                    ods_printf(sockfd,"given keytype \"%s\" invalid\n",keytype);
                     return 1; // errors, but handled
                 }
             }
         }
     }
     
-    /* perform task immediately */
     time_t tstart = time(NULL);
+
     perform_keystate_rollover(sockfd,engine->config,zone,nkeytype);
-    (void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
-                   scmd,time(NULL)-tstart);
-    ods_writen(sockfd, buf, strlen(buf));
 
+    ods_printf(sockfd,"%s completed in %ld seconds.\n",scmd,time(NULL)-tstart);
+
     flush_enforce_task(engine);
 
     return 1;

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_rollover_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_rollover_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/keystate_rollover_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -10,107 +10,89 @@
 #include "keystate/keystate.pb.h"
 #include "xmlext-pb/xmlext-rd.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
+
 #include <memory>
 #include <fcntl.h>
 
 static const char *module_str = "keystate_rollover_task";
 
+#define ODS_LOG_AND_RETURN(errmsg) do { \
+ods_log_error_and_printf(sockfd,module_str,errmsg); return; } while (0)
+#define ODS_LOG_AND_CONTINUE(errmsg) do { \
+ods_log_error_and_printf(sockfd,module_str,errmsg); continue; } while (0)
+
 void 
 perform_keystate_rollover(int sockfd, engineconfig_type *config,
                           const char *zone, int nkeyrole)
 {
-    char buf[ODS_SE_MAXLINE];
-    const char *datastore = config->datastore;
+	OrmConnRef conn;
+	if (!ods_orm_connect(sockfd, config, conn))
+		return; // error already reported.
+	
+	{	OrmTransactionRW transaction(conn);
+		if (!transaction.started())
+			ODS_LOG_AND_RETURN("transaction not started");
+		
+		{	OrmResultRef rows;
+			::ods::keystate::EnforcerZone enfzone;
+			
+			std::string qzone;
+			if (!OrmQuoteStringValue(conn, std::string(zone), qzone))
+				ODS_LOG_AND_RETURN("quoting string value failed");
+			
+			if (!OrmMessageEnumWhere(conn,enfzone.descriptor(),
+									 rows,"name = %s",qzone.c_str()))
+				ODS_LOG_AND_RETURN("zone enumeration failed");
+			
+			if (!OrmFirst(rows)) {
+				ods_printf(sockfd,"zone %s not found\n",zone);
+				return;
+			}
 
-    std::auto_ptr< ::ods::keystate::KeyStateDocument >
-    keystateDoc(new ::ods::keystate::KeyStateDocument);
-    {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (fd != -1) {
-            if (keystateDoc->ParseFromFileDescriptor(fd)) {
-                ods_log_debug("[%s] keys have been loaded",
-                              module_str);
-            } else {
-                ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                              module_str,datapath.c_str());
-            }
-            close(fd);
-        } else {
-            ods_log_error("[%s] file \"%s\" could not be opened",
-                          module_str,datapath.c_str());
-        }
-    }
+			OrmContextRef context;
+			if (!OrmGetMessage(rows, enfzone, /*just zone*/false, context))
+				ODS_LOG_AND_RETURN("retrieving zone from database failed");
+				
+			// we no longer need the query result, so release it.
+			rows.release();
+			
+			switch (nkeyrole) {
+				case 0:
+					enfzone.set_roll_ksk_now(true);
+					enfzone.set_roll_zsk_now(true);
+					enfzone.set_roll_csk_now(true);
+					enfzone.set_next_change(0); // reschedule immediately
+					ods_printf(sockfd,"rolling all keys for zone %s\n",zone);
+					break;
+				case ::ods::keystate::KSK:
+					enfzone.set_roll_ksk_now(true);
+					enfzone.set_next_change(0); // reschedule immediately
+					ods_printf(sockfd,"rolling KSK for zone %s\n",zone);
+					break;
+				case ::ods::keystate::ZSK:
+					enfzone.set_roll_zsk_now(true);
+					enfzone.set_next_change(0); // reschedule immediately
+					ods_printf(sockfd,"rolling ZSK for zone %s\n",zone);
+					break;
+				case ::ods::keystate::CSK:
+					enfzone.set_roll_csk_now(true);
+					enfzone.set_next_change(0); // reschedule immediately
+					ods_printf(sockfd,"rolling CSK for zone %s\n",zone);
+					break;
+				default:
+					ods_log_assert(false && "nkeyrole out of range");
+					ODS_LOG_AND_RETURN("nkeyrole out of range");
+			}
 
-    bool bFlagsChanged = false;
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
-        ::ods::keystate::EnforcerZone *enfzone  = keystateDoc->mutable_zones(z);
-        if (enfzone->name() != std::string(zone))
-            continue;
+			// Update the changes back into the database.
+			if (!OrmMessageUpdate(context))
+				ODS_LOG_AND_RETURN("updating zone in the database failed");
 
-        if (nkeyrole == 0) {
-            enfzone->set_roll_ksk_now(true);
-            enfzone->set_roll_zsk_now(true);
-            enfzone->set_roll_csk_now(true);
-            enfzone->set_next_change(0); // reschedule immediately
-            bFlagsChanged = true;
-            (void)snprintf(buf, ODS_SE_MAXLINE, "rolling all keys for zone %s\n",
-                           zone);
-            ods_writen(sockfd, buf, strlen(buf));
-        } else
-        if (nkeyrole == (int)::ods::keystate::KSK) {
-            enfzone->set_roll_ksk_now(true);
-            enfzone->set_next_change(0); // reschedule immediately
-            bFlagsChanged = true;
-            (void)snprintf(buf, ODS_SE_MAXLINE, "rolling KSK for zone %s\n",
-                           zone);
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-        if (nkeyrole == (int)::ods::keystate::ZSK) {
-            enfzone->set_roll_zsk_now(true);
-            enfzone->set_next_change(0); // reschedule immediately
-            bFlagsChanged = true;
-            (void)snprintf(buf, ODS_SE_MAXLINE, "rolling ZSK for zone %s\n",
-                           zone);
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-        if (nkeyrole == (int)::ods::keystate::CSK) {
-            enfzone->set_roll_csk_now(true);
-            enfzone->set_next_change(0); // reschedule immediately
-            bFlagsChanged = true;
-            (void)snprintf(buf, ODS_SE_MAXLINE, "rolling CSK for zone %s\n",
-                           zone);
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-        break;
-    }
-
-    if (bFlagsChanged) {
-        // Persist the keystate zones back to disk as they may have
-        // been changed by the enforcer update
-        if (keystateDoc->IsInitialized()) {
-            std::string datapath(datastore);
-            datapath += ".keystate.pb";
-            int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
-            if (keystateDoc->SerializeToFileDescriptor(fd)) {
-                ods_log_debug("[%s] key states have been updated",
-                              module_str);
-                
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "update of key states completed.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            } else {
-                (void)snprintf(buf, ODS_SE_MAXLINE,
-                               "error: key states file could not be written.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-            close(fd);
-        } else {
-            (void)snprintf(buf, ODS_SE_MAXLINE,
-                           "error: a message in the key states is missing "
-                           "mandatory information.\n");
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-    }
+			// The zone has been changed and we need to commit it.
+			if (!transaction.commit())
+				ODS_LOG_AND_RETURN("commiting updated zone to the database failed");
+		}
+	}
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -15,20 +15,15 @@
 void
 help_update_keyzones_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    snprintf(buf, ODS_SE_MAXLINE,
+    ods_printf(sockfd,
              "update zonelist update zonelist by importing zonelist.xml\n"
         );
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
 int
 handled_update_keyzones_cmd(int sockfd, engine_type* engine, const char *cmd,
                             ssize_t n)
 {
-    char buf[ODS_SE_MAXLINE];
-    task_type *task;
-    ods_status status;
     const char *scmd = "update zonelist";
 
     cmd = ods_check_command(cmd,n,scmd);
@@ -37,14 +32,12 @@
 
     ods_log_debug("[%s] %s command", module_str, scmd);
     
-    /* perform task immediately */
     time_t tstart = time(NULL);
+	
     perform_update_keyzones(sockfd,engine->config);
-    (void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
-                   scmd,time(NULL)-tstart);
-    ods_writen(sockfd, buf, strlen(buf));
+	
+    ods_printf(sockfd,"%s completed in %ld seconds.\n",scmd,time(NULL)-tstart);
 
     flush_enforce_task(engine);
-
     return 1;
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_cmd.h
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_cmd.h	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_cmd.h	2012-01-05 10:04:41 UTC (rev 6026)
@@ -9,8 +9,8 @@
 
 void help_update_keyzones_cmd(int sockfd);
 
-int handled_update_keyzones_cmd(int sockfd, engine_type* engine, 
-                                 const char *cmd, ssize_t n);
+int handled_update_keyzones_cmd(int sockfd, engine_type* engine,
+								const char *cmd, ssize_t n);
 
 #ifdef __cplusplus
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/update_keyzones_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -11,129 +11,130 @@
 
 #include <fcntl.h>
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
+
 static const char *module_str = "update_keyzones_task";
 
-static 
-::ods::zonelist::ZoneListDocument *
-load_zonelist_xml(int sockfd, const char *zonelistfile)
+static bool
+load_zonelist_xml(int sockfd, const char * zonelistfile,
+				  std::auto_ptr< ::ods::zonelist::ZoneListDocument >&doc)
 {
-    char buf[ODS_SE_MAXLINE];
 	// Create a zonefile and load it with zones from the xml zonelist.xml
-	::ods::zonelist::ZoneListDocument *doc  = new ::ods::zonelist::ZoneListDocument;
-	if (read_pb_message_from_xml_file(doc, zonelistfile)) {
-		if (doc->has_zonelist()) {
-			const ::ods::zonelist::ZoneList  &zonelist = doc->zonelist();
-			if (zonelist.zones_size() > 0) {
-				if (zonelist.IsInitialized()) {
-                    
-                    return doc;
-                    
-				} else {
-                    (void)snprintf(buf, ODS_SE_MAXLINE, "error: a zone in the zonelist is missing mandatory information.\n");
-                    ods_writen(sockfd, buf, strlen(buf));
-                }
-			} else {
-                (void)snprintf(buf, ODS_SE_MAXLINE, "warning: no zones found in zonelist.\n");
-                ods_writen(sockfd, buf, strlen(buf));
-            }
-		} else {
-            (void)snprintf(buf, ODS_SE_MAXLINE, "warning: no zonelist found in zonelist.xml file.\n");
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-    } else {
-        (void)snprintf(buf, ODS_SE_MAXLINE, "warning: unable to read the zonelist.xml file.\n");
-        ods_writen(sockfd, buf, strlen(buf));
-    }
-    delete doc;
-    return NULL;
+	doc.reset(new ::ods::zonelist::ZoneListDocument);
+	if (doc.get() == NULL) {
+		ods_log_error_and_printf(sockfd,module_str,
+								 "out of memory allocating ZoneListDocument");
+		return false;
+	}
+	
+	if (!read_pb_message_from_xml_file(doc.get(), zonelistfile)) {
+		ods_log_error_and_printf(sockfd,module_str,
+								 "unable to read the zonelist.xml file");
+		return false;
+	}
+		
+	if (!doc->has_zonelist()) {
+		ods_log_error_and_printf(sockfd,module_str,
+								 "no zonelist found in zonelist.xml file");
+		return false;
+	}
+		
+	const ::ods::zonelist::ZoneList  &zonelist = doc->zonelist();
+	if (zonelist.zones_size() <= 0) {
+		ods_log_error_and_printf(sockfd,module_str,
+								 "no zones found in zonelist");
+		return false;
+	}
+	
+	if (!zonelist.IsInitialized()) {
+		ods_log_error_and_printf(sockfd,module_str,
+								 "a zone in the zonelist is missing mandatory "
+								 "information");
+		return false;
+	}
+
+	return true;
 }
 
 
 void 
 perform_update_keyzones(int sockfd, engineconfig_type *config)
 {
-    char buf[ODS_SE_MAXLINE];
-    const char *datastore = config->datastore;
-
 	GOOGLE_PROTOBUF_VERIFY_VERSION;
     
-    ::ods::zonelist::ZoneListDocument *
-        zonelistDoc = load_zonelist_xml(sockfd, config->zonelist_filename);
-    if (zonelistDoc == NULL) {
-        ods_log_error("[%s] zonelist could not be loaded from \"%s\"",
-                      module_str,config->zonelist_filename);
-        return; // failure, exit.
-    }
-    
-    ::ods::keystate::KeyStateDocument *keystateDoc =
-    new ::ods::keystate::KeyStateDocument;
-    {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (keystateDoc->ParseFromFileDescriptor(fd)) {
-            ods_log_debug("[%s] keys have been loaded",
-                          module_str);
-        } else {
-            ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                          module_str,datapath.c_str());
-        }
-        close(fd);
-    }
-    
-    // Add new zones found in the zonelist to the keystates
-    // We don't want nested lookup loops of O(N^2) we create a map to get O(2N)
-    std::map<const std::string,const ::ods::keystate::EnforcerZone*> kszonemap;
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
-        const ::ods::keystate::EnforcerZone &ks_zone = keystateDoc->zones(z);
-        kszonemap[ ks_zone.name() ] = &ks_zone;
-    }
+    std::auto_ptr< ::ods::zonelist::ZoneListDocument > zonelistDoc;
+	if (!load_zonelist_xml(sockfd, config->zonelist_filename, zonelistDoc))
+		return; // errors have already been reported.
+
+	OrmConnRef conn;
+	if (!ods_orm_connect(sockfd, config, conn))
+		return;  // errors have already been reported.
+
+	//TODO: SPEED: We should create an index on the EnforcerZone.name column
+		
     // Go through the list of zones from the zonelist to determine if we need
     // to insert new zones to the keystates.
     for (int i=0; i<zonelistDoc->zonelist().zones_size(); ++i) {
         const ::ods::zonelist::ZoneData &zl_zone = 
             zonelistDoc->zonelist().zones(i);
-        // if we can't find the zone in the kszonemap, it is new and we need
-        // to add it.
-        if (kszonemap.find( zl_zone.name() ) == kszonemap.end()) {
-            ::ods::keystate::EnforcerZone *ks_zone = keystateDoc->add_zones();
-            
-            // setup information the enforcer will need.
-            ks_zone->set_name( zl_zone.name() );
-            ks_zone->set_policy( zl_zone.policy() );
-            ks_zone->set_signconf_path( zl_zone.signer_configuration() );
-                        
-            // enforcer needs to trigger signer configuration writing.
-            ks_zone->set_signconf_needs_writing( false );
-        }
+		
+		{	OrmTransactionRW transaction(conn);
+			if (!transaction.started()) {
+				ods_log_error_and_printf(sockfd, module_str,
+					"error starting a database transaction for updating zones");
+				return;
+			}
+			
+			std::string qzone;
+			if (!OrmQuoteStringValue(conn, zl_zone.name(), qzone)) {
+				ods_log_error_and_printf(sockfd, module_str,
+										 "quoting a string failed");
+				return;
+			}
+
+			::ods::keystate::EnforcerZone ks_zone;
+			{	OrmResultRef rows;
+				
+				if (!OrmMessageEnumWhere(conn, ks_zone.descriptor(), rows,
+										 "name = %s",qzone.c_str()))
+				{
+					ods_log_error_and_printf(sockfd, module_str,
+											 "zone lookup by name failed");
+					return;
+				}
+			
+				// if OrmFirst succeeds, a zone with the queried name is 
+				// already present
+				if (OrmFirst(rows))
+					continue; // skip existing zones
+
+				//TODO: FEATURE: update zone fields with information from zonelist.
+
+				// query no longer needed, so lets drop it.
+				rows.release();
+				
+				// setup information the enforcer will need.
+				ks_zone.set_name( zl_zone.name() );
+				ks_zone.set_policy( zl_zone.policy() );
+				ks_zone.set_signconf_path( zl_zone.signer_configuration() );
+							
+				// enforcer needs to trigger signer configuration writing.
+				ks_zone.set_signconf_needs_writing( false );
+				
+				pb::uint64 zoneid;
+				if (!OrmMessageInsert(conn, ks_zone, zoneid)) {
+					ods_log_error_and_printf(sockfd, module_str,
+									"inserting zone into the database failed");
+					return;
+				}
+				
+				if (!transaction.commit()) {
+					ods_log_error_and_printf(sockfd, module_str,
+									"committing zone to the database failed");
+					return;
+				}
+			}
+		}
     }
-    
-    // Persist the keystate zones back to disk as they may have
-    // been changed by the key state update
-    if (keystateDoc->IsInitialized()) {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
-        if (keystateDoc->SerializeToFileDescriptor(fd)) {
-            ods_log_debug("[%s] key states have been updated",
-                          module_str);
-            
-            (void)snprintf(buf, ODS_SE_MAXLINE,
-                           "update of key states completed.\n");
-            ods_writen(sockfd, buf, strlen(buf));
-        } else {
-            (void)snprintf(buf, ODS_SE_MAXLINE, 
-                           "error: key states file could not be written.\n");
-            ods_writen(sockfd, buf, strlen(buf));
-        }
-        close(fd);
-    } else {
-        (void)snprintf(buf, ODS_SE_MAXLINE, 
-                       "error: a message in the key states is missing "
-                       "mandatory information.\n");
-        ods_writen(sockfd, buf, strlen(buf));
-    }
-    
-    delete keystateDoc;
-    delete zonelistDoc;
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -13,12 +13,10 @@
 
 void help_zone_export_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
+    ods_printf(sockfd,
         "zone export     export all the keys used by a zone\n"
         "  --zone <zone> (aka -z) export for the specified zone.\n"
         );
-    ods_writen(sockfd, buf, strlen(buf));
 }
 
 int handled_zone_export_cmd(int sockfd, engine_type* engine, const char *cmd,
@@ -45,8 +43,7 @@
     if (argc > NARGV) {
         ods_log_warning("[%s] too many arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"too many arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"too many arguments\n");
         return 1; // errors, but handled
     }
     
@@ -55,20 +52,18 @@
     if (!zone) {
         ods_log_warning("[%s] expected option --zone <zone> for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"expected --zone <zone> option\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"expected --zone <zone> option\n");
         return 1; // errors, but handled
     }
 
     if (argc) {
         ods_log_warning("[%s] unknown arguments for %s command",
                         module_str,scmd);
-        (void)snprintf(buf, ODS_SE_MAXLINE,"unknown arguments\n");
-        ods_writen(sockfd, buf, strlen(buf));
+        ods_printf(sockfd,"unknown arguments\n");
         return 1; // errors, but handled
     }
     
-    /* perform task immediately */
     perform_zone_export(sockfd,engine->config,zone);
+	
     return 1;
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_cmd.h
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_cmd.h	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_cmd.h	2012-01-05 10:04:41 UTC (rev 6026)
@@ -9,8 +9,8 @@
 
 void help_zone_export_cmd(int sockfd);
 
-int handled_zone_export_cmd(int sockfd, engine_type* engine,
-                            const char *cmd, ssize_t n);
+int handled_zone_export_cmd(int sockfd, engine_type* engine, const char *cmd,
+							ssize_t n);
 
 #ifdef __cplusplus
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_export_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -9,40 +9,52 @@
 #include "xmlext-pb/xmlext-rd.h"
 #include "xmlext-pb/xmlext-wr.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
+
 #include <memory>
 
 #include <fcntl.h>
 
 static const char *module_str = "zone_export_task";
 
+#define ODS_LOG_AND_RETURN(errmsg) do { \
+	ods_log_error_and_printf(sockfd,module_str,errmsg); return; } while (0)
+#define ODS_LOG_AND_CONTINUE(errmsg) do { \
+	ods_log_error_and_printf(sockfd,module_str,errmsg); continue; } while (0)
+
 void 
 perform_zone_export(int sockfd, engineconfig_type *config, const char *zone)
 {
 	GOOGLE_PROTOBUF_VERIFY_VERSION;
-    
-    std::auto_ptr< ::ods::keystate::KeyStateDocument >
-        keystateDoc( new ::ods::keystate::KeyStateDocument );
-    {
-        std::string datapath(config->datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (keystateDoc->ParseFromFileDescriptor(fd)) {
-            ods_log_debug("[%s] keys have been loaded",
-                          module_str);
-        } else {
-            ods_log_error("[%s] keys could not be loaded from \"%s\"",
-                          module_str,datapath.c_str());
-        }
-        close(fd);
+
+	OrmConnRef conn;
+	if (!ods_orm_connect(sockfd, config, conn))
+		return; // error already reported.
+	
+	{	OrmTransaction transaction(conn);
+		if (!transaction.started())
+			ODS_LOG_AND_RETURN("transaction not started");
+		
+		{	OrmResultRef rows;
+			ods::keystate::KeyStateExport kexport;
+			
+			std::string qzone;
+			if (!OrmQuoteStringValue(conn, std::string(zone), qzone))
+				ODS_LOG_AND_RETURN("quoting string value failed");
+			
+			if (!OrmMessageEnumWhere(conn,kexport.zone().descriptor(),
+									 rows,"name = %s",qzone.c_str()))
+				ODS_LOG_AND_RETURN("message enumeration failed");
+
+			for (bool next=OrmFirst(rows); next; next=OrmNext(rows)) {
+				
+				if (!OrmGetMessage(rows, *kexport.mutable_zone(), true))
+					ODS_LOG_AND_CONTINUE("reading zone from database failed");
+
+				if (!write_pb_message_to_xml_fd(kexport.mutable_zone(),sockfd))
+					ODS_LOG_AND_CONTINUE("writing message to xml file failed");
+			}
+		}
     }
-    
-    for (int z=0; z<keystateDoc->zones_size(); ++z) {
-        const ::ods::keystate::EnforcerZone &efzone  = keystateDoc->zones(z);
-        if (efzone.name() == zone) {
-            ods::keystate::KeyStateExport *kexport = new ods::keystate::KeyStateExport;
-            *kexport->mutable_zone() = efzone;
-            write_pb_message_to_xml_fd(kexport,sockfd);
-            delete kexport;
-        }
-    }
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_list_cmd.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_list_cmd.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_list_cmd.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -13,19 +13,12 @@
 
 void help_zone_list_cmd(int sockfd)
 {
-    char buf[ODS_SE_MAXLINE];
-    (void) snprintf(buf, ODS_SE_MAXLINE,
-                    "zone list       list zones\n"
-                    );
-    ods_writen(sockfd, buf, strlen(buf));
+    ods_printf(sockfd,"zone list       list zones\n");
 }
 
 int handled_zone_list_cmd(int sockfd, engine_type* engine, const char *cmd, 
-                                ssize_t n)
+						  ssize_t n)
 {
-    char buf[ODS_SE_MAXLINE];
-    task_type *task;
-    ods_status status;
     const char *scmd =  "zone list";
     
     cmd = ods_check_command(cmd,n,scmd);
@@ -34,12 +27,10 @@
     
     ods_log_debug("[%s] %s command", module_str, scmd);
 
-    /* perform task immediately */
     time_t tstart = time(NULL);
+
     perform_zone_list(sockfd,engine->config);
-    (void)snprintf(buf, ODS_SE_MAXLINE, "%s completed in %ld seconds.\n",
-                   scmd,time(NULL)-tstart);
-    ods_writen(sockfd, buf, strlen(buf));
 
+    ods_printf(sockfd,"%s completed in %ld seconds.\n",scmd,time(NULL)-tstart);
     return 1;
 }

Modified: branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_list_task.cpp
===================================================================
--- branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_list_task.cpp	2012-01-05 10:04:26 UTC (rev 6025)
+++ branches/OpenDNSSEC-enforcer-ng/enforcer-ng/src/keystate/zone_list_task.cpp	2012-01-05 10:04:41 UTC (rev 6026)
@@ -10,6 +10,9 @@
 
 #include "xmlext-pb/xmlext-rd.h"
 
+#include "protobuf-orm/pb-orm.h"
+#include "daemon/orm.h"
+
 #include <fcntl.h>
 
 static const char *module_str = "zone_list_task";
@@ -17,76 +20,81 @@
 void 
 perform_zone_list(int sockfd, engineconfig_type *config)
 {
-    char buf[ODS_SE_MAXLINE];
 	const char *zonelistfile = config->zonelist_filename;
-    const char *datastore = config->datastore;
-    
+
 	GOOGLE_PROTOBUF_VERIFY_VERSION;
 
-    // Load the keystate from the doc file
-    ::ods::keystate::KeyStateDocument *keystateDoc =
-        new ::ods::keystate::KeyStateDocument;
-    {
-        std::string datapath(datastore);
-        datapath += ".keystate.pb";
-        int fd = open(datapath.c_str(),O_RDONLY);
-        if (keystateDoc->ParseFromFileDescriptor(fd)) {
-            ods_log_debug("[%s] keystate has been loaded",
-                          module_str);
-        } else {
-            ods_log_error("[%s] keystate could not be loaded from \"%s\"",
-                          module_str,datapath.c_str());
-        }
-        close(fd);
-    }
+	OrmConnRef conn;
+	if (!ods_orm_connect(sockfd, config, conn))
+		return; // error already reported.
 
-    int nzones = keystateDoc->zones_size();
-    if (nzones == 0) {
-        (void)snprintf(buf, ODS_SE_MAXLINE,
+	{	OrmTransaction transaction(conn);
+		if (!transaction.started()) {
+			const char *errmsg = "could not start database transaction";
+			ods_log_error_and_printf(sockfd,module_str,errmsg);
+			return;
+		}
+		
+		::ods::keystate::EnforcerZone zone;
+		
+		{	OrmResultRef rows;
+			if (!OrmMessageEnum(conn, zone.descriptor(),rows)) {
+				const char *errmsg = "failure during zone enumeration";
+				ods_log_error_and_printf(sockfd,module_str,errmsg);
+				return;
+			}
+			
+			if (!OrmFirst(rows)) {
+				ods_printf(sockfd,
+						   "Zonelist filename set to: %s\n"
+						   "Database set to: %s\n"
+						   "I have no zones configured\n",
+						   zonelistfile,
+						   config->datastore);
+				return;
+			}
+
+			//TODO: SPEED: what if there are milions of zones ?
+			
+			ods_printf(sockfd,
                        "Zonelist filename set to: %s\n"
                        "Database set to: %s\n"
-                       "I have no zones configured\n"
-                       ,zonelistfile,datastore
-                       );
-        ods_writen(sockfd, buf, strlen(buf));
-    } else {
-        (void)snprintf(buf, ODS_SE_MAXLINE,
-                       "Zonelist filename set to: %s\n"
-                       "Database set to: %s\n"
-                       "I have %i zones configured\n"
+//                       "I have %i zones configured\n"
                        "Zones:\n"
                        "Zone:                           "
                        "Policy:       "
                        "Next change:               "
                        "Signer Configuration:"
-                       "\n"
-                       ,zonelistfile,datastore,nzones
+                       "\n",
+                       zonelistfile,
+					   config->datastore //,nzones
                        );
-        ods_writen(sockfd, buf, strlen(buf));
-        
-        for (int i=0; i<nzones; ++i) {
-            const ::ods::keystate::EnforcerZone &zl_zone = keystateDoc->zones(i);
-            
-            char nctime[32];
-            if (zl_zone.next_change()>0) {
-                if (!ods_ctime_r(nctime,sizeof(nctime),zl_zone.next_change())) {
-                    strncpy(nctime,"invalid date/time",sizeof(nctime));
-                    nctime[sizeof(nctime)-1] = '\0';
-                }
-            } else {
-                strncpy(nctime,"as soon as possible",sizeof(nctime));
-                nctime[sizeof(nctime)-1] = '\0';
-            }
-            (void)snprintf(buf, ODS_SE_MAXLINE,
-                           "%-31s %-13s %-26s %-34s\n",
-                           zl_zone.name().c_str(),
-                           zl_zone.policy().c_str(),
-                           nctime,
-                           zl_zone.signconf_path().c_str()
-                           );
-            ods_writen(sockfd, buf, strlen(buf));
+			
+			for (bool next=true; next; next=OrmNext(rows)) {
+
+				if (!OrmGetMessage(rows, zone, true))
+					return;
+				
+				char nctime[32];
+				if (zone.next_change()>0) {
+					if (!ods_ctime_r(nctime,sizeof(nctime),zone.next_change())) {
+						strncpy(nctime,"invalid date/time",sizeof(nctime));
+						nctime[sizeof(nctime)-1] = '\0';
+					}
+				} else {
+					strncpy(nctime,"as soon as possible",sizeof(nctime));
+					nctime[sizeof(nctime)-1] = '\0';
+				}
+				ods_printf(sockfd,
+						   "%-31s %-13s %-26s %-34s\n",
+						   zone.name().c_str(),
+						   zone.policy().c_str(),
+						   nctime,
+						   zone.signconf_path().c_str()
+						   );
+			}
         }
     }
-    delete keystateDoc;
+
     ods_log_debug("[%s] zone list completed", module_str);
 }




More information about the Opendnssec-commits mailing list