about summary refs log tree commit diff stats
path: root/tests_integration/dict_mock_server.php
diff options
context:
space:
mode:
Diffstat (limited to 'tests_integration/dict_mock_server.php')
-rw-r--r--tests_integration/dict_mock_server.php185
1 files changed, 185 insertions, 0 deletions
diff --git a/tests_integration/dict_mock_server.php b/tests_integration/dict_mock_server.php
new file mode 100644
index 0000000..d061266
--- /dev/null
+++ b/tests_integration/dict_mock_server.php
@@ -0,0 +1,185 @@
+<?php
+/**
+ * Minimal dictd server mock for integration tests.
+ *
+ * Implements a subset of the dictd protocol (RFC 2229):
+ *   - Banner on connect
+ *   - DEFINE <db> <word> → returns mock definitions
+ *   - Handles curl's "DEFINE ! db/word" format
+ *
+ * Uses pcntl_fork() to handle multiple concurrent clients.
+ *
+ * Usage: php dict_mock_server.php <port>
+ */
+
+$port = $argv[1] ?? 0;
+if (!$port || !is_numeric($port)) {
+	fwrite(STDERR, "Usage: php dict_mock_server.php <port>\n");
+	exit(1);
+}
+
+$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
+socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
+socket_set_option($socket, SOL_SOCKET, SO_REUSEPORT, 1);
+socket_bind($socket, '127.0.0.1', (int)$port);
+socket_listen($socket, 16);
+
+// Mock definitions
+$definitions = [
+	'cat' => [
+		'wn:WordNet (r) 3.0 (2006):' => 'A domesticated carnivorous mammal with soft fur.',
+		'db:Dictd dictionary:' => 'A small animal that catches mice.',
+	],
+	'cats' => [
+		'wn:WordNet (r) 3.0 (2006):' => 'Plural of cat.',
+	],
+	'dog' => [
+		'wn:WordNet (r) 3.0 (2006):' => 'A domesticated carnivorous mammal that barks.',
+	],
+	'hello' => [
+		'db:Dictd dictionary:' => 'A greeting or salutation.',
+	],
+	'world' => [
+		'db:Dictd dictionary:' => 'The earth; the globe.',
+	],
+];
+
+/**
+ * Process a DEFINE command and return the response lines.
+ */
+function handleDefine(string $command, array $definitions): array
+{
+	// Handle curl's "DEFINE ! db/word" format
+	// Also handle standard "DEFINE db word" format
+	$word = null;
+
+	// Try curl format: DEFINE ! db/word
+	if (preg_match('/DEFINE\s+\!\s+(\S+\/\S+)/i', $command, $matches)) {
+		[$_, $dbWord] = $matches;
+		$parts = explode('/', $dbWord, 2);
+		if (count($parts) === 2) {
+			$word = $parts[1];
+		}
+	}
+
+	// Try standard format: DEFINE db word
+	if ($word === null && preg_match('/DEFINE\s+(\S+)\s+(\S+)/i', $command, $matches)) {
+		$word = $matches[2];
+	}
+
+	if ($word === null) {
+		return ["110 0 definitions found\n", "250 OK completed\n"];
+	}
+
+	// Try exact match first, then strip last char (like the handler does)
+	$def = null;
+	$tryWord = $word;
+	while (strlen($tryWord) > 1 && $def === null) {
+		if (isset($definitions[$tryWord])) {
+			$def = $definitions[$tryWord];
+		}
+		$tryWord = mb_substr($tryWord, 0, -1);
+	}
+
+	if ($def !== null) {
+		$response = ["110 " . count($def) . " definitions found\n"];
+		foreach ($def as $key => $value) {
+			/* this fakes specific format DefineHandler() expects which may not be completely correct re: dict protocol, i.e. definition (value) starts with space:
+
+			150 1 definitions retrieved
+			151 "cat" mueller7 "Mueller English-Russian Dictionary"
+			cat
+				_I  [kæt]
+					1. _n.
+						1) кот; кошка; tom cat кот; pussy cat кошка, кошечка
+						2) _зоол. животное семейства кошачьих
+			*/
+
+			$response[] = "151 $key: $key\n $value\n";
+		}
+		$response[] = "250 Ok\n";
+		return $response;
+	} else {
+		return ["110 0 definitions found\n", "250 OK completed\n"];
+	}
+}
+
+/**
+ * Process a single client connection.
+ */
+function handleClient($clientSocket, array $definitions): void
+{
+	// Send banner
+	socket_write($clientSocket, "120 mock dictd server ready\n");
+
+	$buffer = '';
+	while (true) {
+		$data = socket_read($clientSocket, 4096);
+		if ($data === false || $data === '') {
+			socket_shutdown($clientSocket, 2);
+			socket_close($clientSocket);
+			break;
+		}
+
+		$buffer .= $data;
+
+		// Process complete commands
+		while (strpos($buffer, "\n") !== false) {
+			$newlinePos = strpos($buffer, "\n");
+			$line = trim(substr($buffer, 0, $newlinePos));
+			$buffer = substr($buffer, $newlinePos + 1);
+
+			if ($line === '') {
+				continue;
+			}
+
+			# print("<<< $line\n");
+
+			// Handle DEFINE command (both curl and standard formats)
+			if (stripos($line, 'DEFINE') === 0) {
+				$response = handleDefine($line, $definitions);
+				foreach ($response as $line_out) {
+					# print(">>> $line_out");
+					socket_write($clientSocket, $line_out);
+				}
+			} elseif (stripos($line, 'QUIT') === 0) {
+				socket_shutdown($clientSocket, 2); // Shutdown send side
+				socket_close($clientSocket);
+				return;
+			} else if (stripos($line, 'CLIENT') === 0) {
+				socket_write($clientSocket, "250 Ok\n");
+			} else {
+				socket_write($clientSocket, "500 Unknown command\n");
+			}
+		}
+	}
+}
+
+fwrite(STDERR, "Dict mock server listening on port $port\n");
+
+while (true) {
+	$client = socket_accept($socket);
+	if ($client === false) {
+		continue;
+	}
+
+	// Fork to handle each client concurrently
+	$pid = pcntl_fork();
+	if ($pid === -1) {
+		// Fork failed, handle in main process
+		handleClient($client, $definitions);
+	} elseif ($pid === 0) {
+		// Child process
+		socket_close($socket); // Close listener in child
+		handleClient($client, $definitions);
+		exit(0);
+	} else {
+		// Parent process - reap any finished children periodically
+		while (($childPid = pcntl_waitpid(-1, $status, WNOHANG)) > 0) {
+			// Child reaped
+		}
+		// Parent continues to accept new connections
+	}
+}
+
+socket_close($socket);