r1118 + initial gateway handling source
[racktables] / inc / gateways.php
CommitLineData
d33645ff
DO
1<?
2/*
3*
4* This file contains gateway functions for RackTables.
5* A gateway is an external executable, which provides
6* read-only or read-write access to some external entities.
7* Each gateway accepts its own list of command-line args
8* and then reads its stdin for requests. Each request consists
9* of one line and results in exactly one line of reply.
10* The replies must have the following syntax:
11* OK<space>any text up to the end of the line
12* ERR<space>any text up to the end of the line
13*
14*/
15
16
17// This function launches specified gateway with specified
18// command-line arguments and feeds it with the commands stored
19// in the second arg as array.
20// The answers are stored in another array, which is returned
21// by this function. In the case when a gateway cannot be found,
22// finishes prematurely or exits with non-zero return code,
23// a single-item array is returned with the only "ERR" record,
24// which explains the reason.
25function queryGateway ($gwname, $arguments, $questions)
26{
27 $execpath = "./gateways/{$gwname}/main";
28 $argline = implode (' ', $arguments);
29 $dspec = array
30 (
31 0 => array ("pipe", "r"),
32 1 => array ("pipe", "w"),
33 2 => array ("file", "/dev/null", "a")
34 );
35 $pipes = array();
36 $gateway = proc_open ("${execpath} ${argline}", $dspec, $pipes);
37 if (!is_resource ($gateway))
38 return array ('ERR proc_open() failed in queryGateway()');
39
40// Dialogue starts. Send all questions.
41 foreach ($questions as $q)
42 fwrite ($pipes[0], "$q\n");
43 fclose ($pipes[0]);
44
45// Fetch replies.
46 $answers = array();
47 while (!feof($pipes[1]))
48 {
49 $a = fgets ($pipes[1]);
50 if (empty ($a))
51 continue;
52 array_push ($answers, $a);
53 }
54 fclose($pipes[1]);
55
56 $retval = proc_close ($gateway);
57 if ($retval != 0)
58 return array ("ERR gateway '${gwname}' returned ${retval}");
59 return $answers;
60}
61
62?>