gbproxy/sgsn: Enforce termination when creating a P-TMSI/TLLI

Currently the number of iterations when creating a P-TMSI/TLLI is not
limited. It is nevertheless very unlikely that the loop will not
terminate. On the other hand, the number of iterations of every loop
should have an upper bound (loop variant) which wouldn't be the case
here if an arbitrary random generator was used.

This patch limits the number of iterations to 23 and logs an error if
the creation of the indentifier was aborted due to this limit.

Sponsored-by: On-Waves ehf
diff --git a/openbsc/src/gprs/gprs_sgsn.c b/openbsc/src/gprs/gprs_sgsn.c
index 0c15619..4e51632 100644
--- a/openbsc/src/gprs/gprs_sgsn.c
+++ b/openbsc/src/gprs/gprs_sgsn.c
@@ -359,15 +359,23 @@
 {
 	struct sgsn_mm_ctx *mm;
 	uint32_t ptmsi;
+	int max_retries = 23;
 
 restart:
 	ptmsi = rand() | 0xC0000000;
 	llist_for_each_entry(mm, &sgsn_mm_ctxts, list) {
-		if (mm->p_tmsi == ptmsi)
+		if (mm->p_tmsi == ptmsi) {
+			if (!max_retries--)
+				goto failed;
 			goto restart;
+		}
 	}
 
 	return ptmsi;
+
+failed:
+	LOGP(DGPRS, LOGL_ERROR, "Failed to allocate a P-TMSI\n");
+	return GSM_RESERVED_TMSI;
 }
 
 static void drop_one_pdp(struct sgsn_pdp_ctx *pdp)