PDO::FETCH_ASSOC, ]); if (php_sapi_name() == 'cli') { if ($argv[$argc - 1] == 'init-db') { $db->query(<<execute(); } return; } $url = parse_url("http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); $method = $_SERVER['REQUEST_METHOD']; if ($method == 'POST') { $inputPost = json_decode(file_get_contents('php://input'), true); if ($inputPost) { $_POST = $inputPost + $_POST; } } $response = []; if ($method == 'POST' && $url['path'] == '/host') { $ip = filter_var( $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP ); if ($ip === false) { $response = [ 'success' => false, 'error' => 'Invalid IP.', ]; } else { $port = intval($_POST['port']); $name = $_POST['name']; $id = md5($name . time()); $secret = md5($id . random_bytes($port)); $success = $db->prepare(<<execute([ 'id' => $id, 'ip' => $ip, 'port' => $port, 'timestamp' => time(), 'name' => $name, 'secret' => $secret, ]); if ($success) { $response = [ 'success' => $success, 'data' => [ 'id' => $id, 'secret' => $secret, ], ]; } else { $response = [ 'success' => $success, 'error' => $db->errorInfo(), ]; } } } else if ($method == 'GET' && $url['path'] == '/get-list') { $statement = $db->prepare(<< :comparison_time SQL); $statement->execute([ 'comparison_time' => time() - $timeoutMax, ]); $results = $statement->fetchAll(); $list = []; foreach ($results as $row) { $list[] = [ 'id' => $row['id'], 'name' => $row['name'], ]; } $response = [ 'success' => true, 'data' => $list, ]; } else if ($method == 'GET' && $url['path'] == '/join') { $id = $_GET['id']; $statement = $db->prepare(<<execute([ 'id' => $id, ]); $result = $statement->fetch(); if ($result === false) { $response = [ 'success' => false, 'error' => 'Game not found.' ]; http_response_code(404); } else { $response = [ 'success' => true, 'data' => [ 'ip' => $result['ip'], 'port' => $result['port'], ], ]; } } else if ($method == 'POST' && $url['path'] == '/close') { $id = $_POST['id']; $secret = $_POST['secret']; $success = $db->prepare(<<execute([ 'id' => $id, 'secret' => $secret, ]); $response = [ 'success' => $success, ]; } else if ($method == 'POST' && $url['path'] == '/keep-alive') { $id = $_POST['id']; $secret = $_POST['secret']; $success = $db->prepare(<<execute([ 'id' => $id, 'secret' => $secret, 'ping_time' => time(), ]); $response = [ 'success' => $success, ]; } else { $response = [ 'success' => false, 'error' => 'Route not found.' ]; http_response_code(404); } header('Content-Type: application/json'); echo json_encode($response);