Index: branches/cname-collision/DNSDB.pm
===================================================================
--- branches/cname-collision/DNSDB.pm	(revision 982)
+++ branches/cname-collision/DNSDB.pm	(revision 983)
@@ -662,16 +662,45 @@
       }
     }
-  }
-
-#  } else {
-#    # Non-CNAME records will only collide with CNAMEs
-#    my @t = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec}, $args{revrec}).
-#	" WHERE "._recparent($args{defrec}, $args{revrec})." = ? AND type = 5 AND $hfield = ?",
-#	undef, $args{id}, $hcheck);
-#    return ('FAIL', "There is already a CNAME present for $hcheck.  Only one CNAME may be present for a given name.")
-#	if $t[0] > 1;
-#  }
+
+    # Check timestamps of pending active-after records.  Coerce expires-at fields to soonest match if found.
+    if ($args{defrec} eq 'n') {
+      $sql = "SELECT extract(epoch from stamp) FROM "._rectable($args{defrec}, $args{revrec}).
+       " WHERE "._recparent($args{defrec}, $args{revrec})." = ? AND type $tcompare 5 AND $hfield = ?".
+       " AND stampactive = 't' AND expires = 'f' AND stamp >= now() ";
+      my @lookupargs = ($args{id}, $hcheck);
+      if ($args{update}) {
+        $sql .= "AND record_id <> ? ";
+        push @lookupargs, $args{update};
+      }
+      $sql .= "ORDER BY stamp LIMIT 1";
+      my @t = $dbh->selectrow_array($sql, undef, @lookupargs);
+      if (@t) {
+        # existing record with valid-after stamp is present
+        if (${$args{stamp}}) {
+          # caller requested an expiry time
+          if (${$args{expires}} eq 'f') {
+            # valid-after can't be used together with expires-at, so we can't coerce
+            # the new record to expire as well as keeping valid-after
+            return ('FAIL', "Cannot add CNAME, another record with a later valid-after time already exists");
+          }
+          my $reqstamp = str2time(${$args{stamp}});
+          if ($reqstamp < $t[0]) {
+            # do nothing, new record will expire before the one we found
+          } else {
+            # coerce the expiry timestamp
+            ${$args{stamp}} = strftime('Y-%m-%d %H:%M:%S', localtime($t[0]));
+            return ('WARN', "CNAME added with modified expiry time;  conflicting valid-after record found");
+          }
+        } else {
+          # no expiry requested, but we found a valid-after, so coerce the new record down to expiring at that time
+          ${$args{stamp}} = strftime('%Y-%m-%d %H:%M:%S', localtime($t[0]));
+          ${$args{expires}} = 't';
+          return ('WARN', "CNAME added with expiry time;  conflicting valid-after record found");
+        }
+      }
+    } # args{defrecs} eq 'n'
+  } # each $tcompare
+
   return ('OK', 'OK');
-
 } # _cname_collision()
 
