fix a use-after-free in msc_mgcp.c:_handle_error()

Move code which needs to test the mgcp_ctx->free_ctx flag upwards
such that it runs before we're calling functions which will
potentially free mgcp_ctx. The code being moved up takes effect
only in case mgcp_ctx won't be freed, so there should be no
functional difference.

Change-Id: I5df17c19e2a68c019f7eaf582b14585caa54b32a
Related: OS#2885
diff --git a/src/libmsc/msc_mgcp.c b/src/libmsc/msc_mgcp.c
index e58b249..acdb785 100644
--- a/src/libmsc/msc_mgcp.c
+++ b/src/libmsc/msc_mgcp.c
@@ -183,6 +183,16 @@
 	LOGPFSMLSRC(mgcp_ctx->fsm, LOGL_ERROR, file, line, "%s -- graceful shutdown...\n",
 		    get_value_string(msc_mgcp_cause_codes_names, cause));
 
+	/* Request the higher layers (gsm_04_08.c) to release the call. If the
+	 * problem occured after msc_mgcp_call_release() was calls, remain
+	 * silent because we already got informed and the higher layers might
+	 * already freed their context information (trans). */
+	if (!mgcp_ctx->free_ctx) {
+		mncc_set_cause(&mncc, GSM48_CAUSE_LOC_TRANS_NET,
+			       GSM48_CC_CAUSE_RESOURCE_UNAVAIL);
+		mncc_tx_to_cc(mgcp_ctx->trans->net, MNCC_REL_REQ, &mncc);
+	}
+
 	/* For the shutdown we have two options. Whenever it makes sense to
 	 * send a DLCX to the MGW in order to be sure that the connection is
 	 * properly cleaned up, the dlcx flag should be set. In other cases
@@ -205,16 +215,6 @@
 		osmo_fsm_inst_state_chg(fi, ST_HALT, 0, 0);
 		osmo_fsm_inst_dispatch(fi, EV_TEARDOWN_ERROR, mgcp_ctx);
 	}
-
-	/* Request the higher layers (gsm_04_08.c) to release the call. If the
-	 * problem occured after msc_mgcp_call_release() was calls, remain
-	 * silent because we already got informed and the higher layers might
-	 * already freed their context information (trans). */
-	if (!mgcp_ctx->free_ctx) {
-		mncc_set_cause(&mncc, GSM48_CAUSE_LOC_TRANS_NET,
-			       GSM48_CC_CAUSE_RESOURCE_UNAVAIL);
-		mncc_tx_to_cc(mgcp_ctx->trans->net, MNCC_REL_REQ, &mncc);
-	}
 }
 
 /* Timer callback to shut down in case of connectivity problems */