osmux: Allocate rate counters during initialization of osmux conn

Let's not delay allocation of rate counters until the osmux conn is
fully enabled, since we may want to count stuff before that point in
time.

Fixes crash accessing null conn->osmux.ctrg in
MGCP_Test.TC_two_crcx_and_rtp_osmux_bidir.

Change-Id: Ic31d3567f4d24e628f8983d8362e5c7c2f66ec02
diff --git a/include/osmocom/mgcp/osmux.h b/include/osmocom/mgcp/osmux.h
index 58d9095..1da7c8b 100644
--- a/include/osmocom/mgcp/osmux.h
+++ b/include/osmocom/mgcp/osmux.h
@@ -14,6 +14,7 @@
 struct mgcp_conn_rtp;
 
 int osmux_init(int role, struct mgcp_trunk *trunk);
+int osmux_init_conn(struct mgcp_conn_rtp *conn);
 int osmux_enable_conn(struct mgcp_endpoint *endp, struct mgcp_conn_rtp *conn,
 		      const struct osmo_sockaddr *addr);
 void conn_osmux_disable(struct mgcp_conn_rtp *conn);
diff --git a/src/libosmo-mgcp/mgcp_osmux.c b/src/libosmo-mgcp/mgcp_osmux.c
index 1f21888..ab49cd5 100644
--- a/src/libosmo-mgcp/mgcp_osmux.c
+++ b/src/libosmo-mgcp/mgcp_osmux.c
@@ -500,6 +500,19 @@
 	return 0;
 }
 
+/*! Initialize Osmux bits of a conn.
+ *  \param[in] conn Osmux connection to initialize
+ *  \returns 0 on success, negative on ERROR */
+int osmux_init_conn(struct mgcp_conn_rtp *conn)
+{
+	if (conn_osmux_allocate_local_cid(conn) == -1)
+		return -1;
+	conn->osmux.ctrg = rate_ctr_group_alloc(conn->conn, &rate_ctr_group_osmux_desc, conn->ctrg->idx);
+
+	conn->osmux.state = OSMUX_STATE_ACTIVATING;
+	return 0;
+}
+
 /*! enable OSXMUX circuit for a specified connection.
  *  \param[in] endp mgcp endpoint (configuration)
  *  \param[in] conn connection to disable
@@ -561,8 +574,6 @@
 	osmux_xfrm_output_set_tx_cb(conn->osmux.out,
 				    scheduled_from_osmux_tx_rtp_cb, conn);
 
-	conn->osmux.ctrg = rate_ctr_group_alloc(conn->conn, &rate_ctr_group_osmux_desc, conn->ctrg->idx);
-
 	conn->osmux.state = OSMUX_STATE_ENABLED;
 
 	return 0;
@@ -591,11 +602,12 @@
 		osmux_handle_put(conn->osmux.in);
 		conn->osmux.remote_cid = 0;
 		conn->osmux.remote_cid_present = false;
-
-		rate_ctr_group_free(conn->osmux.ctrg);
-		conn->osmux.ctrg = NULL;
 	}
+
 	conn_osmux_release_local_cid(conn);
+
+	rate_ctr_group_free(conn->osmux.ctrg);
+	conn->osmux.ctrg = NULL;
 }
 
 /*! relase OSXMUX cid, that had been allocated to this connection.
diff --git a/src/libosmo-mgcp/mgcp_protocol.c b/src/libosmo-mgcp/mgcp_protocol.c
index e748c5b..711ca31 100644
--- a/src/libosmo-mgcp/mgcp_protocol.c
+++ b/src/libosmo-mgcp/mgcp_protocol.c
@@ -1003,8 +1003,7 @@
 	conn->osmux.state = OSMUX_STATE_DISABLED;
 	/* If X-Osmux (remote CID) was received (-1 is wilcard), alloc next avail CID as local CID */
 	if (remote_osmux_cid >= -1) {
-		conn->osmux.state = OSMUX_STATE_ACTIVATING;
-		if (conn_osmux_allocate_local_cid(conn) == -1) {
+		if (osmux_init_conn(conn) < 0) {
 			rate_ctr_inc(rate_ctr_group_get_ctr(rate_ctrs, MGCP_CRCX_FAIL_NO_OSMUX));
 			goto error2;
 		}