mirror of
https://github.com/GNS3/gns3-server.git
synced 2026-11-03 14:01:15 +02:00
Drop Windows support
This commit is contained in:
1 parent
4fb0cd9321
commit
74c675d5b0
47 files changed
+223
-1004
No files matched your search
@@ -89,14 +89,3 @@ def parse_version(version):
|
||||
version.append("000000")
|
||||
version.append("final")
|
||||
return tuple(version)
|
||||
|
||||
|
||||
def shlex_quote(s):
|
||||
"""
|
||||
Compatible shlex_quote to handle case where Windows needs double quotes around file names, not single quotes.
|
||||
"""
|
||||
|
||||
if sys.platform.startswith("win"):
|
||||
return s if re.match(r"^[-_\w./]+$", s) else '"%s"' % s.replace('"', '\\"')
|
||||
else:
|
||||
return shlex.quote(s)
|
||||
@@ -136,22 +136,6 @@ async def wait_for_file_creation(path, timeout=60):
|
||||
raise asyncio.TimeoutError()
|
||||
|
||||
|
||||
async def wait_for_named_pipe_creation(pipe_path, timeout=60):
|
||||
|
||||
import win32pipe
|
||||
import pywintypes
|
||||
|
||||
while timeout > 0:
|
||||
try:
|
||||
win32pipe.WaitNamedPipe(pipe_path, 1)
|
||||
except pywintypes.error:
|
||||
await asyncio.sleep(0.5)
|
||||
timeout -= 0.5
|
||||
else:
|
||||
return
|
||||
raise asyncio.TimeoutError()
|
||||
|
||||
|
||||
def locking(f):
|
||||
@functools.wraps(f)
|
||||
async def wrapper(oself, *args, **kwargs):
|
||||
|
||||
@@ -15,19 +15,14 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import sys
|
||||
import asyncio
|
||||
|
||||
from gns3server.utils.asyncio import wait_for_file_creation, wait_for_named_pipe_creation
|
||||
from gns3server.utils.asyncio import wait_for_file_creation
|
||||
from gns3server.compute.error import NodeError
|
||||
|
||||
"""
|
||||
This module handle connection to unix socket or Windows named pipe
|
||||
This module handle connection to unix socket
|
||||
"""
|
||||
if sys.platform.startswith("win"):
|
||||
import win32file
|
||||
import win32pipe
|
||||
import msvcrt
|
||||
|
||||
|
||||
class SerialReaderWriterProtocol(asyncio.Protocol):
|
||||
@@ -61,50 +56,6 @@ class SerialReaderWriterProtocol(asyncio.Protocol):
|
||||
self._output.feed_eof()
|
||||
|
||||
|
||||
class WindowsPipe:
|
||||
"""
|
||||
Write input and output stream to the same object
|
||||
"""
|
||||
|
||||
def __init__(self, path):
|
||||
self._handle = open(path, "a+b")
|
||||
self._pipe = msvcrt.get_osfhandle(self._handle.fileno())
|
||||
|
||||
async def read(self, n=-1):
|
||||
(read, num_avail, num_message) = win32pipe.PeekNamedPipe(self._pipe, 0)
|
||||
if num_avail > 0:
|
||||
(error_code, output) = win32file.ReadFile(self._pipe, num_avail, None)
|
||||
return output
|
||||
await asyncio.sleep(0.01)
|
||||
return b""
|
||||
|
||||
def at_eof(self):
|
||||
return False
|
||||
|
||||
def write(self, data):
|
||||
win32file.WriteFile(self._pipe, data)
|
||||
|
||||
async def drain(self):
|
||||
return
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
async def _asyncio_open_serial_windows(path):
|
||||
"""
|
||||
Open a windows named pipe
|
||||
|
||||
:returns: An IO like object
|
||||
"""
|
||||
|
||||
try:
|
||||
await wait_for_named_pipe_creation(path)
|
||||
except asyncio.TimeoutError:
|
||||
raise NodeError(f'Pipe file "{path}" is missing')
|
||||
return WindowsPipe(path)
|
||||
|
||||
|
||||
async def _asyncio_open_serial_unix(path):
|
||||
"""
|
||||
Open a unix socket or a windows named pipe
|
||||
@@ -128,12 +79,9 @@ async def _asyncio_open_serial_unix(path):
|
||||
|
||||
async def asyncio_open_serial(path):
|
||||
"""
|
||||
Open a unix socket or a windows named pipe
|
||||
Open an unix socket
|
||||
|
||||
:returns: An IO like object
|
||||
"""
|
||||
|
||||
if sys.platform.startswith("win"):
|
||||
return await _asyncio_open_serial_windows(path)
|
||||
else:
|
||||
return await _asyncio_open_serial_unix(path)
|
||||
return await _asyncio_open_serial_unix(path)
|
||||
@@ -21,7 +21,6 @@ import socket
|
||||
import struct
|
||||
import psutil
|
||||
|
||||
from .windows_service import check_windows_service_is_running
|
||||
from gns3server.compute.compute_error import ComputeError
|
||||
from gns3server.config import Config
|
||||
|
||||
@@ -197,55 +196,36 @@ def interfaces():
|
||||
"""
|
||||
|
||||
results = []
|
||||
if not sys.platform.startswith("win"):
|
||||
allowed_interfaces = Config.instance().settings.Server.allowed_interfaces
|
||||
net_if_addrs = psutil.net_if_addrs()
|
||||
for interface in sorted(net_if_addrs.keys()):
|
||||
if allowed_interfaces and interface not in allowed_interfaces and not interface.startswith("gns3tap"):
|
||||
log.warning(f"Interface '{interface}' is not allowed to be used on this server")
|
||||
continue
|
||||
ip_address = ""
|
||||
mac_address = ""
|
||||
netmask = ""
|
||||
interface_type = "ethernet"
|
||||
for addr in net_if_addrs[interface]:
|
||||
# get the first available IPv4 address only
|
||||
if addr.family == socket.AF_INET:
|
||||
ip_address = addr.address
|
||||
netmask = addr.netmask
|
||||
if addr.family == psutil.AF_LINK:
|
||||
mac_address = addr.address
|
||||
if interface.startswith("tap"):
|
||||
# found no way to reliably detect a TAP interface
|
||||
interface_type = "tap"
|
||||
results.append(
|
||||
{
|
||||
"id": interface,
|
||||
"name": interface,
|
||||
"ip_address": ip_address,
|
||||
"netmask": netmask,
|
||||
"mac_address": mac_address,
|
||||
"type": interface_type,
|
||||
}
|
||||
)
|
||||
else:
|
||||
try:
|
||||
service_installed = True
|
||||
if not check_windows_service_is_running("npf") and not check_windows_service_is_running("npcap"):
|
||||
service_installed = False
|
||||
else:
|
||||
results = get_windows_interfaces()
|
||||
except ImportError:
|
||||
message = (
|
||||
"pywin32 module is not installed, please install it on the server to get the available interface names"
|
||||
)
|
||||
raise ComputeError(message)
|
||||
except Exception as e:
|
||||
log.error(f"uncaught exception {type(e)}", exc_info=1)
|
||||
raise ComputeError(f"uncaught exception: {e}")
|
||||
|
||||
if service_installed is False:
|
||||
raise ComputeError("The Winpcap or Npcap is not installed or running")
|
||||
allowed_interfaces = Config.instance().settings.Server.allowed_interfaces
|
||||
net_if_addrs = psutil.net_if_addrs()
|
||||
for interface in sorted(net_if_addrs.keys()):
|
||||
if allowed_interfaces and interface not in allowed_interfaces and not interface.startswith("gns3tap"):
|
||||
log.warning(f"Interface '{interface}' is not allowed to be used on this server")
|
||||
continue
|
||||
ip_address = ""
|
||||
mac_address = ""
|
||||
netmask = ""
|
||||
interface_type = "ethernet"
|
||||
for addr in net_if_addrs[interface]:
|
||||
# get the first available IPv4 address only
|
||||
if addr.family == socket.AF_INET:
|
||||
ip_address = addr.address
|
||||
netmask = addr.netmask
|
||||
if addr.family == psutil.AF_LINK:
|
||||
mac_address = addr.address
|
||||
if interface.startswith("tap"):
|
||||
# found no way to reliably detect a TAP interface
|
||||
interface_type = "tap"
|
||||
results.append(
|
||||
{
|
||||
"id": interface,
|
||||
"name": interface,
|
||||
"ip_address": ip_address,
|
||||
"netmask": netmask,
|
||||
"mac_address": mac_address,
|
||||
"type": interface_type,
|
||||
}
|
||||
)
|
||||
|
||||
# This interface have special behavior
|
||||
for result in results:
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright (C) 2016 GNS3 Technologies Inc.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
import shutil
|
||||
import ipaddress
|
||||
|
||||
if sys.platform.startswith("win"):
|
||||
import wmi
|
||||
else:
|
||||
raise SystemExit("This script must run on Windows!")
|
||||
|
||||
|
||||
def parse_add_loopback():
|
||||
"""
|
||||
Validate params when adding a loopback adapter
|
||||
"""
|
||||
|
||||
class Add(argparse.Action):
|
||||
def __call__(self, parser, args, values, option_string=None):
|
||||
try:
|
||||
ipaddress.IPv4Interface(f"{values[1]}/{values[2]}")
|
||||
except ipaddress.AddressValueError as e:
|
||||
raise argparse.ArgumentTypeError(f"Invalid IP address: {e}")
|
||||
except ipaddress.NetmaskValueError as e:
|
||||
raise argparse.ArgumentTypeError(f"Invalid subnet mask: {e}")
|
||||
setattr(args, self.dest, values)
|
||||
|
||||
return Add
|
||||
|
||||
|
||||
def add_loopback(devcon_path, name, ip_address, netmask):
|
||||
|
||||
# save the list of network adapter in order to find the one we are about to add
|
||||
previous_adapters = wmi.WMI().Win32_NetworkAdapter()
|
||||
for adapter in previous_adapters:
|
||||
if "Loopback" in adapter.Description and adapter.NetConnectionID == name:
|
||||
raise SystemExit(f'Windows loopback adapter named "{name}" already exists')
|
||||
|
||||
# install a new Windows loopback adapter
|
||||
os.system('"{}" install {}\\inf\\netloop.inf *MSLOOP'.format(devcon_path, os.path.expandvars("%WINDIR%")))
|
||||
|
||||
# configure the new Windows loopback adapter
|
||||
for adapter in wmi.WMI().Win32_NetworkAdapter():
|
||||
if "Loopback" in adapter.Description and adapter not in previous_adapters:
|
||||
print(f'Renaming loopback adapter "{adapter.NetConnectionID}" to "{name}"')
|
||||
adapter.NetConnectionID = name
|
||||
for network_config in wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True):
|
||||
if network_config.InterfaceIndex == adapter.InterfaceIndex:
|
||||
print(f'Configuring loopback adapter "{name}" with {ip_address} {netmask}')
|
||||
retcode = network_config.EnableStatic(IPAddress=[ip_address], SubnetMask=[netmask])[0]
|
||||
if retcode == 1:
|
||||
print("A reboot is required")
|
||||
elif retcode != 0:
|
||||
print('Error while configuring IP/Subnet mask on "{}"')
|
||||
|
||||
# FIXME: support gateway?
|
||||
# network_config.SetGateways(DefaultIPGateway=[""])
|
||||
break
|
||||
|
||||
# restart winpcap/npcap services to take the new adapter into account
|
||||
os.system("net stop npf")
|
||||
os.system("net start npf")
|
||||
os.system("net stop npcap")
|
||||
os.system("net start npcap")
|
||||
|
||||
|
||||
def remove_loopback(devcon_path, name):
|
||||
|
||||
deleted = False
|
||||
for adapter in wmi.WMI().Win32_NetworkAdapter():
|
||||
if "Loopback" in adapter.Description and adapter.NetConnectionID == name:
|
||||
# remove a Windows loopback adapter
|
||||
print(f'Removing loopback adapter "{name}"')
|
||||
os.system(f'"{devcon_path}" remove @{adapter.PNPDeviceID}')
|
||||
deleted = True
|
||||
|
||||
if not deleted:
|
||||
raise SystemExit(f'Could not find adapter "{name}"')
|
||||
|
||||
# update winpcap/npcap services
|
||||
os.system("net stop npf")
|
||||
os.system("net start npf")
|
||||
os.system("net stop npcap")
|
||||
os.system("net start npcap")
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
Entry point for the Windows loopback tool.
|
||||
"""
|
||||
|
||||
parser = argparse.ArgumentParser(description="%(prog)s add/remove Windows loopback adapters")
|
||||
parser.add_argument("-a", "--add", nargs=3, action=parse_add_loopback(), help="add a Windows loopback adapter")
|
||||
parser.add_argument("-r", "--remove", action="store", help="remove a Windows loopback adapter")
|
||||
try:
|
||||
args = parser.parse_args()
|
||||
except argparse.ArgumentTypeError as e:
|
||||
raise SystemExit(e)
|
||||
|
||||
# devcon is required to install/remove Windows loopback adapters
|
||||
devcon_path = shutil.which("devcon")
|
||||
if not devcon_path:
|
||||
raise SystemExit("Could not find devcon.exe")
|
||||
|
||||
from win32com.shell import shell
|
||||
|
||||
if not shell.IsUserAnAdmin():
|
||||
raise SystemExit("You must run this script as an administrator")
|
||||
|
||||
try:
|
||||
if args.add:
|
||||
add_loopback(devcon_path, args.add[0], args.add[1], args.add[2])
|
||||
if args.remove:
|
||||
remove_loopback(devcon_path, args.remove)
|
||||
except SystemExit as e:
|
||||
print(e)
|
||||
os.system("pause")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,39 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright (C) 2016 GNS3 Technologies Inc.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
"""
|
||||
Check for Windows service.
|
||||
"""
|
||||
|
||||
from gns3server.compute.compute_error import ComputeError
|
||||
|
||||
|
||||
def check_windows_service_is_running(service_name):
|
||||
|
||||
import pywintypes
|
||||
import win32service
|
||||
import win32serviceutil
|
||||
|
||||
try:
|
||||
if win32serviceutil.QueryServiceStatus(service_name, None)[1] != win32service.SERVICE_RUNNING:
|
||||
return False
|
||||
except pywintypes.error as e:
|
||||
if e.winerror == 1060:
|
||||
return False
|
||||
else:
|
||||
raise ComputeError(f"Could not check if the {service_name} service is running: {e.strerror}")
|
||||
return True
|
||||
Reference in new issue
Block a user