5 * @author Donal McMullan donal@catalyst.net.nz
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
11 require_once $CFG->dirroot
.'/mnet/lib.php';
14 * Class representing an XMLRPC request against a remote machine
16 class mnet_xmlrpc_client
{
19 var $params = array();
25 * Constructor returns true
27 function mnet_xmlrpc_client() {
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));
44 $this->timeout
= $timeout;
49 * Set the path to the method or function we want to execute on the remote
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();
63 $this->params
= array();
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:
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',
99 if (!in_array($type, $allowed_types)) {
103 if ($type != 'datetime' && $type != 'base64') {
104 $this->params
[] = $argument;
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;
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
124 function send($mnet_peer) {
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.
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
155 {$CFG->prefix}mnet_rpc r,
156 {$CFG->prefix}mnet_service2rpc s2r,
157 {$CFG->prefix}mnet_host2service h2s
159 r.xmlrpc_path = '{$this->method}' 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) {
168 $this->error
[] = '7:User with ID '. $USER->id
.
169 ' attempted to call unauthorised method '.
170 $this->method
.' on host '.
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);
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
215 $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $MNET->get_private_key());
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');
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);
230 // It's an older code, sir, but it checks out
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';
242 if (strpos(substr($payload, 0, 100), '<signedMessage>')) {
243 $sig_parser = new mnet_encxml_parser();
244 $sig_parser->parse($payload);
246 $this->error
[] = '2:Payload not signed: '.$payload;
251 $this->error
[] = '1:Payload not encrypted ';
252 $crypt_parser->free_resource();
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');
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';
280 $this->xmlrpcresponse
= base64_decode($sig_parser->data_object
);
281 $this->response
= xmlrpc_decode($this->xmlrpcresponse
);
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);
303 $this->error
[] = $this->response
['faultCode'] . " : " . $this->response
['faultString'];
306 $this->error
[] = $this->response
['faultCode'] . " : " . $this->response
['faultString'];
309 $this->error
[] = $this->response
['faultCode'] . " : " . $this->response
['faultString'];
312 return empty($this->error
);