Skip to content

Commit

Permalink
refactor: Check for valid port and address in run_server (grapheneX#178)
Browse files Browse the repository at this point in the history
* add helper functions

* refactor run_server

* add missing docstring

* simplify is_valid_port func
  • Loading branch information
jxdv authored Jan 1, 2024
1 parent bbcd7eb commit 80e34bc
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 19 deletions.
17 changes: 17 additions & 0 deletions graphenex/core/utils/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys
import json
import ctypes
import socket
import pathlib
import argparse
from colorama import init, Fore, Style
Expand Down Expand Up @@ -160,3 +161,19 @@ def get_mod_json():
except FileNotFoundError:
logger.error(f"{mod_json_file} not found! Exiting grapheneX.")
sys.exit(1)


def is_valid_port(port):
"""Verify the port number"""

return 1 <= port <= 65535


def is_valid_address(address):
"""Verify the IP address"""

try:
socket.getaddrinfo(address, None)
return True
except socket.gaierror:
return False
51 changes: 32 additions & 19 deletions graphenex/core/web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from flask import Flask
from flask_socketio import SocketIO

from graphenex.core.utils.helpers import is_valid_port, is_valid_address
from graphenex.core.cli.shell import Shell
from graphenex.core.utils.logcl import GraphenexLogger

Expand All @@ -24,30 +25,42 @@
def run_server(args=None, exit_shell=True):
"""Run the web server"""

if args:
server_params = args.get('host_port', '').split(':') or default_addr
else:
server_params = default_addr

try:
server_addr, server_port = server_params
server_port = int(server_port)
except (ValueError, IndexError):
logger.error(f"Invalid server parameters: {server_params}")
return

if not is_valid_port(server_port):
logger.error(f"Invalid port specified: {server_port}")
return

if not is_valid_address(server_addr):
logger.error(f"Invalid address specified: {server_addr}")
return

logger.info(f"Starting server on http://{server_addr}:{server_port}")

try:
if args:
server_params = args['host_port'].split(':') \
if ':' in args['host_port'] \
else (args['host_port'], '8080')
else:
server_params = default_addr
logger.info(f"Starting server: http://{server_params[0]}:{server_params[1]}")
try:
if args and args['open']:
webbrowser.open(f"http://{server_params[0]}:{server_params[1]}")
except Exception:
pass
if args and args.get('open', False):
webbrowser.open(f"http://{server_addr}:{server_port}")

logger.info(f"Your access token: {app.config['ACCESS_TOKEN']}")
socketio.run(app, host=server_params[0], port=int(server_params[1]), debug=False)
except (PermissionError, ValueError):
logger.error('Invalid host & port address. Restarting with default host and port.')
run_server()
socketio.run(app, host=server_addr, port=server_port, debug=False)
except socket.error as e:
if e.errno == 98:
logger.error(f"{server_addr}:{server_port} is already in use!")
return
except KeyboardInterrupt:
socketio.stop()
if exit_shell:
Shell().do_exit(None)
except socket.error as e:
if e.errno == 98:
logger.error(f"{server_params[0]}:{server_params[1]} is already in use!")
except Exception as e:
logger.error(f'An error occurred: {e}')
return

0 comments on commit 80e34bc

Please sign in to comment.