Changing one generic class-name to a glossary specific one.
[pfb-moodle.git] / mnet / xmlrpc / client.php
blobefd494f79839243692d856abdbe81112b7a645a8
1 <?php
2 /**
3 * An XML-RPC client
5 * @author Donal McMullan donal@catalyst.net.nz
6 * @version 0.0.1
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
8 * @package mnet
9 */
11 require_once $CFG->dirroot.'/mnet/lib.php';
13 /**
14 * Class representing an XMLRPC request against a remote machine
16 class mnet_xmlrpc_client {
18 var $method = '';
19 var $params = array();
20 var $timeout = 60;
21 var $error = array();
22 var $response = '';
24 /**
25 * Constructor returns true
27 function mnet_xmlrpc_client() {
28 return true;
31 /**
32 * Allow users to override the default timeout
33 * @param int $timeout Request timeout in seconds
34 * $return bool True if param is an integer or integer string
36 function set_timeout($timeout) {
37 if (!is_integer($timeout)) {
38 if (is_numeric($timeout)) {
39 $this->timeout = (integer($timeout));
40 return true;
42 return false;
44 $this->timeout = $timeout;
45 return true;
48 /**
49 * Set the path to the method or function we want to execute on the remote
50 * machine. Examples:
51 * mod/scorm/functionname
52 * auth/mnet/methodname
53 * In the case of auth and enrolment plugins, an object will be created and
54 * the method on that object will be called
56 function set_method($xmlrpcpath) {
57 if (is_string($xmlrpcpath)) {
58 $this->method = $xmlrpcpath;
59 $this->params = array();
60 return true;
62 $this->method = '';
63 $this->params = array();
64 return false;
67 /**
68 * Add a parameter to the array of parameters.
70 * @param string $argument A transport ID, as defined in lib.php
71 * @param string $type The argument type, can be one of:
72 * none
73 * empty
74 * base64
75 * boolean
76 * datetime
77 * double
78 * int
79 * string
80 * array
81 * struct
82 * In its weakly-typed wisdom, PHP will (currently)
83 * ignore everything except datetime and base64
84 * @return bool True on success
86 function add_param($argument, $type = 'string') {
88 $allowed_types = array('none',
89 'empty',
90 'base64',
91 'boolean',
92 'datetime',
93 'double',
94 'int',
95 'i4',
96 'string',
97 'array',
98 'struct');
99 if (!in_array($type, $allowed_types)) {
100 return false;
103 if ($type != 'datetime' && $type != 'base64') {
104 $this->params[] = $argument;
105 return true;
108 // Note weirdness - The type of $argument gets changed to an object with
109 // value and type properties.
110 // bool xmlrpc_set_type ( string &value, string type )
111 xmlrpc_set_type($argument, $type);
112 $this->params[] = $argument;
113 return true;
117 * Send the request to the server - decode and return the response
119 * @param object $mnet_peer A mnet_peer object with details of the
120 * remote host we're connecting to
121 * @return mixed A PHP variable, as returned by the
122 * remote function
124 function send($mnet_peer) {
125 global $CFG, $MNET;
127 $this->uri = $mnet_peer->wwwroot.
128 '/mnet/xmlrpc/server.php';
130 // Initialize with the target URL
131 $ch = curl_init($this->uri);
133 $system_methods = array('system/listMethods', 'system/methodSignature', 'system/methodHelp', 'system/listServices');
135 if (in_array($this->method, $system_methods) ) {
137 // Executing any system method is permitted.
139 } else {
140 $id_list = $mnet_peer->id;
141 if (!empty($CFG->mnet_all_hosts_id)) {
142 $id_list .= ', '.$CFG->mnet_all_hosts_id;
145 // At this point, we don't care if the remote host implements the
146 // method we're trying to call. We just want to know that:
147 // 1. The method belongs to some service, as far as OUR host knows
148 // 2. We are allowed to subscribe to that service on this mnet_peer
150 // Find methods that we subscribe to on this host
151 $sql = "
152 SELECT
154 FROM
155 {$CFG->prefix}mnet_rpc r,
156 {$CFG->prefix}mnet_service2rpc s2r,
157 {$CFG->prefix}mnet_host2service h2s
158 WHERE
159 r.xmlrpc_path = '{$this->method}' AND
160 s2r.rpcid = r.id AND
161 s2r.serviceid = h2s.serviceid AND
162 h2s.subscribe = '1' AND
163 h2s.hostid in ({$id_list})";
165 $permission = get_record_sql($sql);
166 if ($permission == false) {
167 global $USER;
168 $this->error[] = '7:User with ID '. $USER->id .
169 ' attempted to call unauthorised method '.
170 $this->method.' on host '.
171 $mnet_peer->wwwroot;
172 return false;
176 $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8"));
177 $rq = $this->requesttext;
178 $rq = mnet_sign_message($this->requesttext);
179 $this->signedrequest = $rq;
180 $rq = mnet_encrypt_message($rq, $mnet_peer->public_key);
181 $this->encryptedrequest = $rq;
183 curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
184 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
185 curl_setopt($ch, CURLOPT_POST, true);
186 curl_setopt($ch, CURLOPT_USERAGENT, 'Moodle');
187 curl_setopt($ch, CURLOPT_POSTFIELDS, $rq);
188 curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml charset=UTF-8"));
190 $timestamp_send = time();
191 $this->rawresponse = curl_exec($ch);
192 $timestamp_receive = time();
194 if ($this->rawresponse == false) {
195 $this->error[] = curl_errno($ch) .':'. curl_error($ch);
196 return false;
199 $mnet_peer->touch();
201 $crypt_parser = new mnet_encxml_parser();
202 $crypt_parser->parse($this->rawresponse);
204 if ($crypt_parser->payload_encrypted) {
206 $key = array_pop($crypt_parser->cipher);
207 $data = array_pop($crypt_parser->cipher);
209 $crypt_parser->free_resource();
211 // Initialize payload var
212 $payload = '';
214 // &$payload
215 $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $MNET->get_private_key());
217 if (!$isOpen) {
218 // Decryption failed... let's try our archived keys
219 $openssl_history = get_config('mnet', 'openssl_history');
220 if(empty($openssl_history)) {
221 $openssl_history = array();
222 set_config('openssl_history', serialize($openssl_history), 'mnet');
223 } else {
224 $openssl_history = unserialize($openssl_history);
226 foreach($openssl_history as $keyset) {
227 $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
228 $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $keyresource);
229 if ($isOpen) {
230 // It's an older code, sir, but it checks out
231 break;
236 if (!$isOpen) {
237 trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}.");
238 $this->error[] = '3:No key match';
239 return false;
242 if (strpos(substr($payload, 0, 100), '<signedMessage>')) {
243 $sig_parser = new mnet_encxml_parser();
244 $sig_parser->parse($payload);
245 } else {
246 $this->error[] = '2:Payload not signed: '.$payload;
247 return false;
250 } else {
251 $this->error[] = '1:Payload not encrypted ';
252 $crypt_parser->free_resource();
253 return false;
256 // Margin of error is the time it took the request to complete.
257 $margin_of_error = $timestamp_receive - $timestamp_send;
259 // Guess the time gap between sending the request and the remote machine
260 // executing the time() function. Marginally better than nothing.
261 $hysteresis = ($margin_of_error) / 2;
263 $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis;
264 $time_offset = $remote_timestamp - $timestamp_send;
265 if ($time_offset > 0) {
266 $threshold = get_config('mnet', 'drift_threshold');
267 if(empty($threshold)) {
268 // We decided 15 seconds was a pretty good arbitrary threshold
269 // for time-drift between servers, but you can customize this in
270 // the config_plugins table. It's not advised though.
271 set_config('drift_threshold', 15, 'mnet');
272 $threshold = 15;
274 if ($time_offset > $threshold) {
275 $this->error[] = '6:Time gap with '.$mnet_peer->name.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds';
276 return false;
280 $this->xmlrpcresponse = base64_decode($sig_parser->data_object);
281 $this->response = xmlrpc_decode($this->xmlrpcresponse);
282 curl_close($ch);
284 // xmlrpc errors are pushed onto the $this->error stack
285 if (isset($this->response['faultCode'])) {
286 // The faultCode 7025 means we tried to connect with an old SSL key
287 // The faultString is the new key - let's save it and try again
288 // The re_key attribute stops us from getting into a loop
289 if($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) {
290 $record = new stdClass();
291 $record->id = $mnet_peer->id;
292 if($this->response['faultString'] == clean_param($this->response['faultString'], PARAM_PEM)) {
293 $record->public_key = $this->response['faultString'];
294 $details = openssl_x509_parse($record->public_key);
295 if(is_array($details) && isset($details['validTo_time_t'])) {
296 $record->public_key_expires = $details['validTo_time_t'];
297 update_record('mnet_host', $record);
298 $mnet_peer2 = new mnet_peer();
299 $mnet_peer2->set_id($record->id);
300 $mnet_peer2->re_key = true;
301 $this->send($mnet_peer2);
302 } else {
303 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
305 } else {
306 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
308 } else {
309 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
312 return empty($this->error);