From 89c0702a4714f872b5ccfad5fd7387509d537ac8 Mon Sep 17 00:00:00 2001 From: Shoghi Cervantes Pueyo Date: Sun, 6 Jan 2013 21:19:39 +0100 Subject: [PATCH] Added optional Windows UPnP port forwading --- src/API/ServerAPI.php | 9 ++++++ src/misc/utils/UPnP.php | 61 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/misc/utils/UPnP.php diff --git a/src/API/ServerAPI.php b/src/API/ServerAPI.php index c6b2c9f37..71f734dfb 100644 --- a/src/API/ServerAPI.php +++ b/src/API/ServerAPI.php @@ -90,6 +90,10 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run define("DEBUG", $this->config["debug"]); $this->server = new PocketMinecraftServer($this->getProperty("server-name"), $this->getProperty("gamemode"), false, $this->getProperty("port"), $this->getProperty("server-id")); $this->server->api = $this; + if($this->getProperty("upnp-forwading") === true ){ + console("[INFO] [UPnP] Trying to port forward..."); + UPnP_PortForward($this->getProperty("port")); + } if($this->getProperty("last-update") === false or ($this->getProperty("last-update") + 3600) < time()){ console("[INFO] Checking for new server version"); console("[INFO] Last check: ".date("Y-m-d H:i:s", $this->getProperty("last-update"))); @@ -236,6 +240,7 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run $config = $this->config; $config["white-list"] = $config["white-list"] === true ? "true":"false"; $config["invisible"] = $config["invisible"] === true ? "true":"false"; + $config["upnp-forwading"] = $config["upnp-forwading"] === true ? "true":"false"; $prop = "#Pocket Minecraft PHP server properties\r\n#".date("D M j H:i:s T Y")."\r\n"; foreach($config as $n => $v){ $prop .= $n."=".$v."\r\n"; @@ -297,6 +302,10 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run unregister_tick_function(array($this->server, "tick")); $this->__destruct(); unset($this->server); + if($this->getProperty("upnp-forwading") === true ){ + console("[INFO] [UPnP] Removing port forward..."); + UPnP_RemovePortForward($this->getProperty("port")); + } return $this->restart; } diff --git a/src/misc/utils/UPnP.php b/src/misc/utils/UPnP.php new file mode 100644 index 000000000..8579bc1ce --- /dev/null +++ b/src/misc/utils/UPnP.php @@ -0,0 +1,61 @@ +StaticPortMappingCollection->Add($port, "UDP", $port, $myLocalIP, true, "PocketMine-MP"); + }catch(Exception $e){ + return false; + } + return true; +} + +function UPnP_RemovePortForward($port){ + if(Utils::getOS() != "win" or !class_exists("COM")){ + return false; + } + $port = (int) $port; + try{ + $com = new COM("HNetCfg.NATUPnP") or false; + if($com === false){ + return false; + } + $com->StaticPortMappingCollection->Remove($port, "UDP"); + }catch(Exception $e){ + return false; + } + return true; +} \ No newline at end of file