rspro_client_fsm: Fix handling of IPA keepalive

We cannot rely on the implicit IPA keepalive FSM termination, as that
somehow gets the termination order wrong and we end up accessing free'd
memory.

Let's handle the termination explicitly:  We register a callback with
the IPA keepalive FSM, and once that callback gets hit, we ask the
core to *not* terminate the FSM implicitly.  We are anyway terminating
it explicitly in st_reestablish_onenter().

Change-Id: Ia745ccb44c0d0224d1e7ab6b6da3713474111d41
diff --git a/src/rspro_client_fsm.c b/src/rspro_client_fsm.c
index eea8471..758bde7 100644
--- a/src/rspro_client_fsm.c
+++ b/src/rspro_client_fsm.c
@@ -113,6 +113,7 @@
 	OSMO_VALUE_STRING(SRVC_E_TCP_UP),
 	OSMO_VALUE_STRING(SRVC_E_TCP_DOWN),
 	OSMO_VALUE_STRING(SRVC_E_KA_TIMEOUT),
+	OSMO_VALUE_STRING(SRVC_E_KA_TERMINATED),
 	OSMO_VALUE_STRING(SRVC_E_CLIENT_CONN_RES),
 	OSMO_VALUE_STRING(SRVC_E_RSPRO_TX),
 	{ 0, NULL }
@@ -261,6 +262,13 @@
 	}
 }
 
+static int ipa_kaepalive_timeout_cb(struct osmo_fsm_inst *ka_fi, void *conn)
+{
+	struct osmo_fsm_inst *fi = ka_fi->proc.parent;
+	osmo_fsm_inst_dispatch(fi, SRVC_E_KA_TIMEOUT, NULL);
+	return 0; /* we will explicitly terminate it */
+}
+
 static void srvc_st_reestablish_onenter(struct osmo_fsm_inst *fi, uint32_t prev_state)
 {
 	struct rspro_server_conn *srvc = (struct rspro_server_conn *) fi->priv;
@@ -292,8 +300,9 @@
 		LOGPFSM(fi, "Unable to create keepalive FSM\n");
 		exit(1);
 	}
+	ipa_keepalive_fsm_set_timeout_cb(srvc->keepalive_fi, ipa_kaepalive_timeout_cb);
 	/* ensure parent is notified once keepalive FSM instance is dying */
-	osmo_fsm_inst_change_parent(srvc->keepalive_fi, srvc->fi, SRVC_E_KA_TIMEOUT);
+	osmo_fsm_inst_change_parent(srvc->keepalive_fi, srvc->fi, SRVC_E_KA_TERMINATED);
 
 	/* Attempt to connect TCP socket */
 	rc = ipa_client_conn_open(srvc->conn);
diff --git a/src/rspro_client_fsm.h b/src/rspro_client_fsm.h
index b1c14f8..ca59c77 100644
--- a/src/rspro_client_fsm.h
+++ b/src/rspro_client_fsm.h
@@ -9,6 +9,7 @@
 	SRVC_E_TCP_UP,
 	SRVC_E_TCP_DOWN,
 	SRVC_E_KA_TIMEOUT,
+	SRVC_E_KA_TERMINATED,
 	SRVC_E_CLIENT_CONN_RES,
 	SRVC_E_RSPRO_TX		/* transmit a RSPRO PDU to the peer */
 };