weekly release 5.0dev
[moodle.git] / mnet / xmlrpc / client.php
blob6e2fb08c42c58996b526ff912fbc31358d1a0363
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 = '';
23 var $mnet = null;
25 /**
26 * Constructor
28 public function __construct() {
29 // make sure we've got this set up before we try and do anything else
30 $this->mnet = get_mnet_environment();
33 /**
34 * Allow users to override the default timeout
35 * @param int $timeout Request timeout in seconds
36 * $return bool True if param is an integer or integer string
38 public function set_timeout($timeout) {
39 if (!is_integer($timeout)) {
40 if (is_numeric($timeout)) {
41 $this->timeout = (integer)$timeout;
42 return true;
44 return false;
46 $this->timeout = $timeout;
47 return true;
50 /**
51 * Set the path to the method or function we want to execute on the remote
52 * machine. Examples:
53 * mod/scorm/functionname
54 * auth/mnet/methodname
55 * In the case of auth and enrolment plugins, an object will be created and
56 * the method on that object will be called
58 public function set_method($xmlrpcpath) {
59 if (is_string($xmlrpcpath)) {
60 $this->method = $xmlrpcpath;
61 $this->params = array();
62 return true;
64 $this->method = '';
65 $this->params = array();
66 return false;
69 /**
70 * Add a parameter to the array of parameters.
72 * @param string $argument A transport ID, as defined in lib.php
73 * @param string $type The argument type, can be one of:
74 * i4
75 * i8
76 * int
77 * double
78 * string
79 * boolean
80 * datetime | dateTime.iso8601
81 * base64
82 * null
83 * array
84 * struct
85 * @return bool True on success
87 public function add_param($argument, $type = 'string') {
89 // Convert any use of the old 'datetime' to the correct 'dateTime.iso8601' one.
90 $type = ($type === 'datetime' ? 'dateTime.iso8601' : $type);
92 // BC fix, if some argument is array and comes as string, change type to array (sequentials)
93 // or struct (associative).
94 // This is the behavior of the encode_request() method from the xmlrpc extension.
95 // Note that uses in core have been fixed, but there may be others using that.
96 if (is_array($argument) && $type === 'string') {
97 if (array_keys($argument) === range(0, count($argument) - 1)) {
98 $type = 'array';
99 } else {
100 $type = 'struct';
102 mnet_debug('Incorrect ' . $type . ' param passed as string in mnet_xmlrpc_client->add_param(): ' .
103 json_encode($argument));
106 if (!isset(\PhpXmlRpc\Value::$xmlrpcTypes[$type])) { // Arrived here, still erong type? Let's stop.
107 return false;
110 // If we are array or struct, we need to ensure that, recursively, all the elements are proper values.
111 // or serialize, used later on send() won't work with them. Encoder::encode() provides us with that.
112 if ($type === 'array' || $type === 'struct') {
113 $encoder = new \PhpXmlRpc\Encoder();
114 $this->params[] = $encoder->encode($argument);
115 } else {
116 // Normal scalar case.
117 $this->params[] = new \PhpXmlRpc\Value($argument, $type);
119 return true;
123 * Send the request to the server - decode and return the response
125 * @param object $mnet_peer A mnet_peer object with details of the
126 * remote host we're connecting to
127 * @param bool $rekey The rekey attribute stops us from
128 * getting into a loop.
129 * @return mixed A PHP variable, as returned by the
131 public function send($mnet_peer, bool $rekey = false) {
132 global $CFG, $DB;
134 if (!$this->permission_to_call($mnet_peer)) {
135 mnet_debug("tried and wasn't allowed to call a method on $mnet_peer->wwwroot");
136 return false;
139 $request = new \PhpXmlRpc\Request($this->method, $this->params);
140 $requesttext = $request->serialize('utf-8');
142 $signedrequest = mnet_sign_message($requesttext);
143 $encryptedrequest = mnet_encrypt_message($signedrequest, $mnet_peer->public_key);
145 $client = $this->prepare_http_request($mnet_peer);
147 $timestamp_send = time();
148 mnet_debug("about to send the xmlrpc request");
149 $response = $client->send($encryptedrequest, $this->timeout);
150 mnet_debug("managed to complete a xmlrpc request");
151 $timestamp_receive = time();
153 if ($response->faultCode()) {
154 $this->error[] = $response->faultCode() .':'. $response->faultString();
155 return false;
158 $rawresponse = trim($response->value()); // Because MNet responses ARE NOT valid xmlrpc, don't try any PhpXmlRpc facility.
160 $mnet_peer->touch();
162 $crypt_parser = new mnet_encxml_parser();
163 $crypt_parser->parse($rawresponse);
165 // If we couldn't parse the message, or it doesn't seem to have encrypted contents,
166 // give the most specific error msg available & return
167 if (!$crypt_parser->payload_encrypted) {
168 if (! empty($crypt_parser->remoteerror)) {
169 $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror;
170 } else if (! empty($crypt_parser->error)) {
171 $crypt_parser_error = $crypt_parser->error[0];
173 $message = '3:XML Parse error in payload: '.$crypt_parser_error['string']."\n";
174 if (array_key_exists('lineno', $crypt_parser_error)) {
175 $message .= 'At line number: '.$crypt_parser_error['lineno']."\n";
177 if (array_key_exists('line', $crypt_parser_error)) {
178 $message .= 'Which reads: '.$crypt_parser_error['line']."\n";
180 $this->error[] = $message;
181 } else {
182 $this->error[] = '1:Payload not encrypted ';
185 $crypt_parser->free_resource();
186 return false;
189 $key = array_pop($crypt_parser->cipher);
190 $data = array_pop($crypt_parser->cipher);
192 $crypt_parser->free_resource();
194 // Initialize payload var
195 $decryptedenvelope = '';
197 // &$decryptedenvelope
198 $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key),
199 $this->mnet->get_private_key(), 'RC4');
201 if (!$isOpen) {
202 // Decryption failed... let's try our archived keys
203 $openssl_history = get_config('mnet', 'openssl_history');
204 if(empty($openssl_history)) {
205 $openssl_history = array();
206 set_config('openssl_history', serialize($openssl_history), 'mnet');
207 } else {
208 $openssl_history = unserialize($openssl_history);
210 foreach($openssl_history as $keyset) {
211 $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
212 $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $keyresource, 'RC4');
213 if ($isOpen) {
214 // It's an older code, sir, but it checks out
215 break;
220 if (!$isOpen) {
221 trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}.");
222 $this->error[] = '3:No key match';
223 return false;
226 if (strpos(substr($decryptedenvelope, 0, 100), '<signedMessage>')) {
227 $sig_parser = new mnet_encxml_parser();
228 $sig_parser->parse($decryptedenvelope);
229 } else {
230 $this->error[] = '2:Payload not signed: ' . $decryptedenvelope;
231 return false;
234 // Margin of error is the time it took the request to complete.
235 $margin_of_error = $timestamp_receive - $timestamp_send;
237 // Guess the time gap between sending the request and the remote machine
238 // executing the time() function. Marginally better than nothing.
239 $hysteresis = ($margin_of_error) / 2;
241 $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis;
242 $time_offset = $remote_timestamp - $timestamp_send;
243 if ($time_offset > 0) {
244 $threshold = get_config('mnet', 'drift_threshold');
245 if(empty($threshold)) {
246 // We decided 15 seconds was a pretty good arbitrary threshold
247 // for time-drift between servers, but you can customize this in
248 // the config_plugins table. It's not advised though.
249 set_config('drift_threshold', 15, 'mnet');
250 $threshold = 15;
252 if ($time_offset > $threshold) {
253 $this->error[] = '6:Time gap with '.$mnet_peer->name.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds';
254 return false;
258 $xmlrpcresponse = base64_decode($sig_parser->data_object);
259 // Let's convert the xmlrpc back to PHP structure.
260 $response = null;
261 $encoder = new \PhpXmlRpc\Encoder();
262 $oresponse = $encoder->decodeXML($xmlrpcresponse); // First, to internal PhpXmlRpc\Response structure.
263 if ($oresponse instanceof \PhpXmlRpc\Response) {
264 // Special handling of fault responses (because value() doesn't handle them properly).
265 if ($oresponse->faultCode()) {
266 $response = ['faultCode' => $oresponse->faultCode(), 'faultString' => $oresponse->faultString()];
267 } else {
268 $response = $encoder->decode($oresponse->value()); // Normal Response conversion to PHP.
270 } else {
271 // Maybe this is just a param, let's convert it too.
272 $response = $encoder->decode($oresponse);
274 $this->response = $response;
276 // xmlrpc errors are pushed onto the $this->error stack
277 if (is_array($this->response) && array_key_exists('faultCode', $this->response)) {
278 // The faultCode 7025 means we tried to connect with an old SSL key
279 // The faultString is the new key - let's save it and try again
280 // The rekey attribute stops us from getting into a loop
281 if($this->response['faultCode'] == 7025 && empty($rekey)) {
282 mnet_debug('recieved an old-key fault, so trying to get the new key and update our records');
283 // If the new certificate doesn't come thru clean_param() unmolested, error out
284 if($this->response['faultString'] != clean_param($this->response['faultString'], PARAM_PEM)) {
285 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
287 $record = new stdClass();
288 $record->id = $mnet_peer->id;
289 $record->public_key = $this->response['faultString'];
290 $details = openssl_x509_parse($record->public_key);
291 if(!isset($details['validTo_time_t'])) {
292 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
294 $record->public_key_expires = $details['validTo_time_t'];
295 $DB->update_record('mnet_host', $record);
297 // Create a new peer object populated with the new info & try re-sending the request
298 $rekeyed_mnet_peer = new mnet_peer();
299 $rekeyed_mnet_peer->set_id($record->id);
300 return $this->send($rekeyed_mnet_peer, true); // Re-send mnet_peer with the new key.
302 if (!empty($CFG->mnet_rpcdebug)) {
303 if (get_string_manager()->string_exists('error'.$this->response['faultCode'], 'mnet')) {
304 $guidance = get_string('error'.$this->response['faultCode'], 'mnet');
305 } else {
306 $guidance = '';
308 } else {
309 $guidance = '';
311 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'] ."\n".$guidance;
314 // ok, it's signed, but is it signed with the right certificate ?
315 // do this *after* we check for an out of date key
316 $verified = openssl_verify($xmlrpcresponse, base64_decode($sig_parser->signature), $mnet_peer->public_key);
317 if ($verified != 1) {
318 $this->error[] = 'Invalid signature';
321 return empty($this->error);
325 * Check that we are permitted to call method on specified peer
327 * @param object $mnet_peer A mnet_peer object with details of the remote host we're connecting to
328 * @return bool True if we permit calls to method on specified peer, False otherwise.
330 public function permission_to_call($mnet_peer) {
331 global $DB, $CFG, $USER;
333 // Executing any system method is permitted.
334 $system_methods = array('system/listMethods', 'system/methodSignature', 'system/methodHelp', 'system/listServices');
335 if (in_array($this->method, $system_methods) ) {
336 return true;
339 $hostids = array($mnet_peer->id);
340 if (!empty($CFG->mnet_all_hosts_id)) {
341 $hostids[] = $CFG->mnet_all_hosts_id;
343 // At this point, we don't care if the remote host implements the
344 // method we're trying to call. We just want to know that:
345 // 1. The method belongs to some service, as far as OUR host knows
346 // 2. We are allowed to subscribe to that service on this mnet_peer
348 list($hostidsql, $hostidparams) = $DB->get_in_or_equal($hostids);
350 $sql = "SELECT r.id
351 FROM {mnet_remote_rpc} r
352 INNER JOIN {mnet_remote_service2rpc} s2r ON s2r.rpcid = r.id
353 INNER JOIN {mnet_host2service} h2s ON h2s.serviceid = s2r.serviceid
354 WHERE r.xmlrpcpath = ?
355 AND h2s.subscribe = ?
356 AND h2s.hostid $hostidsql";
358 $params = array($this->method, 1);
359 $params = array_merge($params, $hostidparams);
361 if ($DB->record_exists_sql($sql, $params)) {
362 return true;
365 $this->error[] = '7:User with ID '. $USER->id .
366 ' attempted to call unauthorised method '.
367 $this->method.' on host '.
368 $mnet_peer->wwwroot;
369 return false;
373 * Generate a \PhpXmlRpc\Client handle and prepare it for sending to an mnet host
375 * @param object $mnet_peer A mnet_peer object with details of the remote host the request will be sent to
376 * @return \PhpXmlRpc\Client handle - the almost-ready-to-send http request
378 public function prepare_http_request($mnet_peer) {
379 $uri = $mnet_peer->wwwroot . $mnet_peer->application->xmlrpc_server_url;
381 // Instantiate the xmlrpc client to be used for the client request
382 // and configure it the way we want.
383 $client = new \PhpXmlRpc\Client($uri);
384 $client->setUseCurl(\PhpXmlRpc\Client::USE_CURL_ALWAYS);
385 $client->setUserAgent('Moodle');
386 $client->return_type = 'xml'; // Because MNet responses ARE NOT valid xmlrpc, don't try any validation.
388 // TODO: Link this to DEBUG DEVELOPER or with MNET debugging...
389 // $client->setdebug(1); // See a good number of complete requests and responses.
391 $verifyhost = 0;
392 $verifypeer = false;
393 if ($mnet_peer->sslverification == mnet_peer::SSL_HOST_AND_PEER) {
394 $verifyhost = 2;
395 $verifypeer = true;
396 } else if ($mnet_peer->sslverification == mnet_peer::SSL_HOST) {
397 $verifyhost = 2;
399 $client->setSSLVerifyHost($verifyhost);
400 $client->setSSLVerifyPeer($verifypeer);
402 return $client;