summaryrefslogtreecommitdiffstats
path: root/inc/rpc.inc.php
blob: 83029e41b3345c4eebb23f121a592f5654cd02b5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php

/**
 * Interface to the external rpc.
 */
class RPC
{

	/**
	 * UDP socket used for communication with the rpc
	 * @var resource
	 */
	private static $sock = false;

	private static function init()
	{
		if (self::$sock !== false)
			return;
		self::$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
		socket_set_option(self::$sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 0, 'usec' => 300000));
		socket_set_option(self::$sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0));
		socket_connect(self::$sock, '127.0.0.1', 1333);
	}

	public static function submit($data)
	{
		self::init();
		if (empty($data)) {
			$data = '{}';
		} else {
			$data = json_encode($data);
		}
		$sent = socket_send(self::$sock, $data, strlen($data), 0);
		if ($sent != strlen($data)) {
			return 'RPC send error';
		}
		$reply = self::readReply();
		if ($reply === false) {
			return 'RPC receive error';
		}
		return $reply;
	}

	/**
	 * Read reply from socket.
	 *
	 * @return mixed read reply as astring, or error message
	 */
	private static function readReply()
	{
		for ($i = 0; $i < 3; ++$i) {
			$bytes = socket_recvfrom(self::$sock, $buf, 90000, 0, $bla1, $bla2);
			if ($bytes !== false)
				return $buf;
		}
		return false;
	}

}