From fbc7169d2175c66b1b9d1884a30ff30100bce122 Mon Sep 17 00:00:00 2001
From: Allanis <allanis@saracraft.net>
Date: Wed, 21 May 2014 16:34:10 +0100
Subject: [PATCH] [Change] Avoid a theoretical infinite loop plus a memleak in
 the map.

---
 dat/outfit.xml |  2 +-
 src/map.c      | 28 +++++++++++++++++++++-------
 2 files changed, 22 insertions(+), 8 deletions(-)

diff --git a/dat/outfit.xml b/dat/outfit.xml
index b1357b8..13924bd 100644
--- a/dat/outfit.xml
+++ b/dat/outfit.xml
@@ -365,7 +365,7 @@
    <energy_regen>125</energy_regen>
   </specific>
  </outfit>
- <outfit name="Shield Capacitator">
+ <outfit name="Shield Capacitor">
   <general>
    <max>12</max>
    <tech>9</tech>
diff --git a/src/map.c b/src/map.c
index d7ce5ed..a1d0bc5 100644
--- a/src/map.c
+++ b/src/map.c
@@ -21,6 +21,9 @@
 #define BUTTON_WIDTH    60  /**< Map button width. */
 #define BUTTON_HEIGHT   30  /**< Map button height. */
 
+#define MAP_LOOP_PROT   250 /**< Number of iterations max in pathfinding before
+                                 aborting. */
+
 static double map_zoom  = 1.;         /**< Zoom of the map. */
 static double map_xpos  = 0.;         /**< Map X position. */
 static double map_ypos  = 0.;         /**< Map Y position. */
@@ -766,7 +769,7 @@ static void A_freeList(SysNode* first) {
 }
 
 StarSystem** map_getJumpPath(int* njumps, char* sysstart, char* sysend, int ignore_known) {
-  int i, cost;
+  int i, j, cost;
 
   StarSystem* sys, *ssys, *esys, **res;
 
@@ -792,7 +795,13 @@ StarSystem** map_getJumpPath(int* njumps, char* sysstart, char* sysend, int igno
   cur = A_newNode(ssys, NULL);
   open = A_add(open, cur); /* Initial open node is the start system. */
 
+  j = 0;
   while((cur = A_lowest(open))->sys != esys) {
+    /* Break if infinite loop. */
+    j++;
+    if(j > MAP_LOOP_PROT)
+      break;
+
     /* Get best from open and toss to closed. */
     open = A_rm(open, cur->sys);
     closed = A_add(closed, cur);
@@ -825,12 +834,17 @@ StarSystem** map_getJumpPath(int* njumps, char* sysstart, char* sysend, int igno
       }
     }
   }
-  /* Build the path backwards. */
-  (*njumps) = A_g(cur);
-  res = malloc(sizeof(StarSystem*) * (*njumps));
-  for(i = 0; i < (*njumps); i++) {
-    res[(*njumps)-i-1] = cur->sys;
-    cur = cur->parent;
+  /* Build the path backwards if not broken from loop. */
+  if(j <= MAP_LOOP_PROT) {
+    (*njumps) = A_g(cur);
+    res = malloc(sizeof(StarSystem*) * (*njumps));
+    for(i = 0; i < (*njumps); i++) {
+      res[(*njumps)-i-1] = cur->sys;
+      cur = cur->parent;
+    }
+  } else {
+    (*njumps) = 0;
+    res = NULL;
   }
 
   /* Free the linked list. */