gbproxy_peer: Free all related BVCs if the cell is freed

Previously the SGSN BVCs would still be present after the related Cell
was freed. This caused some inconsistencies if a BVC with the same BVCI
was established again. The symptoms of this were cells that were attached
to no SGSN or the same one multiple times and crashes.

This patch ensures that the SGSN-side BVCs are also freed when the cell
is freed and that this fact is reflected when handling reset
notifications.

Change-Id: Iedeede8917e2870e0b62a2050ccb331109167017
diff --git a/src/gb_proxy.c b/src/gb_proxy.c
index d6d760f..69a58d4 100644
--- a/src/gb_proxy.c
+++ b/src/gb_proxy.c
@@ -682,8 +682,10 @@
 				LOGPBVC(bvc->cell->bss_bvc, LOGL_NOTICE, "Destroying due to conflicting "
 					"BVCI configuration (new NSEI=%05u)!\n", bvc->nse->nsei);
 				gbproxy_bvc_free(bvc->cell->bss_bvc);
+				bvc->cell = NULL;
+			} else {
+				LOGPBVC(bvc, LOGL_ERROR, "Found cell without BSS BVC, this should not happen!");
 			}
-			bvc->cell->bss_bvc = bvc;
 		}
 	}
 
diff --git a/src/gb_proxy_peer.c b/src/gb_proxy_peer.c
index f59cf9e..0070155 100644
--- a/src/gb_proxy_peer.c
+++ b/src/gb_proxy_peer.c
@@ -217,8 +217,16 @@
 {
 	int i;
 
-	if (cell->bss_bvc == bvc)
+	if (cell->bss_bvc == bvc) {
+		/* Remove the whole cell including all BVCs */
+		for (i = 0; i < ARRAY_SIZE(cell->sgsn_bvc); i++) {
+			if (cell->sgsn_bvc[i]) {
+				gbproxy_bvc_free(cell->sgsn_bvc[i]);
+				cell->sgsn_bvc[i] = NULL;
+			}
+		}
 		return gbproxy_cell_free(cell);
+	}
 
 	/* we could also be a SGSN-side BVC */
 	for (i = 0; i < ARRAY_SIZE(cell->sgsn_bvc); i++) {