nat: Remember a pending delete on an endpoint and carry it out later
diff --git a/openbsc/include/openbsc/bsc_nat.h b/openbsc/include/openbsc/bsc_nat.h
index e272349..13bdc71 100644
--- a/openbsc/include/openbsc/bsc_nat.h
+++ b/openbsc/include/openbsc/bsc_nat.h
@@ -134,6 +134,8 @@
 	char *transaction_id;
 	/* the bsc we are talking to */
 	struct bsc_connection *bsc;
+	/* pending delete */
+	int pending_delete;
 };
 
 /**
diff --git a/openbsc/src/nat/bsc_mgcp_utils.c b/openbsc/src/nat/bsc_mgcp_utils.c
index 1ccb136..49c4466 100644
--- a/openbsc/src/nat/bsc_mgcp_utils.c
+++ b/openbsc/src/nat/bsc_mgcp_utils.c
@@ -150,6 +150,7 @@
 
 	bsc_endp->transaction_id = talloc_strdup(nat, transaction_id);
 	bsc_endp->bsc = bsc_con;
+	bsc_endp->pending_delete = state == MGCP_ENDP_DLCX;
 
 	/* we need to update some bits */
 	if (state == MGCP_ENDP_CRCX) {
@@ -232,6 +233,13 @@
 	endp->bts_rtcp = htons(port + 1);
 	output = bsc_mgcp_rewrite((char * ) msg->l2h, msgb_l2len(msg),
 				  bsc->nat->mgcp_cfg->source_addr, endp->rtp_port);
+
+	if (bsc_endp->pending_delete) {
+		mgcp_free_endp(endp);
+		bsc_endp->bsc = NULL;
+		bsc_endp->pending_delete = 0;
+	}
+
 	if (!output) {
 		LOGP(DMGCP, LOGL_ERROR, "Failed to rewrite MGCP msg.\n");
 		return;