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
.$mnet_peer->application
->xmlrpc_server_url
;
129 // Initialize with the target URL
130 $ch = curl_init($this->uri
);
132 $system_methods = array('system/listMethods', 'system/methodSignature', 'system/methodHelp', 'system/listServices');
134 if (in_array($this->method
, $system_methods) ) {
136 // Executing any system method is permitted.
139 $id_list = $mnet_peer->id
;
140 if (!empty($CFG->mnet_all_hosts_id
)) {
141 $id_list .= ', '.$CFG->mnet_all_hosts_id
;
144 // At this point, we don't care if the remote host implements the
145 // method we're trying to call. We just want to know that:
146 // 1. The method belongs to some service, as far as OUR host knows
147 // 2. We are allowed to subscribe to that service on this mnet_peer
149 // Find methods that we subscribe to on this host
154 {$CFG->prefix}mnet_rpc r,
155 {$CFG->prefix}mnet_service2rpc s2r,
156 {$CFG->prefix}mnet_host2service h2s
158 r.xmlrpc_path = '{$this->method}' AND
160 s2r.serviceid = h2s.serviceid AND
161 h2s.subscribe = '1' AND
162 h2s.hostid in ({$id_list})";
164 $permission = get_record_sql($sql);
165 if ($permission == false) {
167 $this->error
[] = '7:User with ID '. $USER->id
.
168 ' attempted to call unauthorised method '.
169 $this->method
.' on host '.
175 $this->requesttext
= xmlrpc_encode_request($this->method
, $this->params
, array("encoding" => "utf-8"));
176 $rq = $this->requesttext
;
177 $rq = mnet_sign_message($this->requesttext
);
178 $this->signedrequest
= $rq;
179 $rq = mnet_encrypt_message($rq, $mnet_peer->public_key
);
180 $this->encryptedrequest
= $rq;
182 curl_setopt($ch, CURLOPT_TIMEOUT
, $this->timeout
);
183 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
184 curl_setopt($ch, CURLOPT_POST
, true);
185 curl_setopt($ch, CURLOPT_USERAGENT
, 'Moodle');
186 curl_setopt($ch, CURLOPT_POSTFIELDS
, $rq);
187 curl_setopt($ch, CURLOPT_HTTPHEADER
, array("Content-Type: text/xml charset=UTF-8"));
188 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
189 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, 0);
191 $timestamp_send = time();
192 $this->rawresponse
= curl_exec($ch);
193 $timestamp_receive = time();
195 if ($this->rawresponse
== false) {
196 $this->error
[] = curl_errno($ch) .':'. curl_error($ch);
202 $crypt_parser = new mnet_encxml_parser();
203 $crypt_parser->parse($this->rawresponse
);
205 if ($crypt_parser->payload_encrypted
) {
207 $key = array_pop($crypt_parser->cipher
);
208 $data = array_pop($crypt_parser->cipher
);
210 $crypt_parser->free_resource();
212 // Initialize payload var
216 $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $MNET->get_private_key());
219 // Decryption failed... let's try our archived keys
220 $openssl_history = get_config('mnet', 'openssl_history');
221 if(empty($openssl_history)) {
222 $openssl_history = array();
223 set_config('openssl_history', serialize($openssl_history), 'mnet');
225 $openssl_history = unserialize($openssl_history);
227 foreach($openssl_history as $keyset) {
228 $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
229 $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $keyresource);
231 // It's an older code, sir, but it checks out
238 trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}.");
239 $this->error
[] = '3:No key match';
243 if (strpos(substr($payload, 0, 100), '<signedMessage>')) {
244 $sig_parser = new mnet_encxml_parser();
245 $sig_parser->parse($payload);
247 $this->error
[] = '2:Payload not signed: '.$payload;
252 $this->error
[] = '1:Payload not encrypted ';
253 $crypt_parser->free_resource();
257 // Margin of error is the time it took the request to complete.
258 $margin_of_error = $timestamp_receive - $timestamp_send;
260 // Guess the time gap between sending the request and the remote machine
261 // executing the time() function. Marginally better than nothing.
262 $hysteresis = ($margin_of_error) / 2;
264 $remote_timestamp = $sig_parser->remote_timestamp
- $hysteresis;
265 $time_offset = $remote_timestamp - $timestamp_send;
266 if ($time_offset > 0) {
267 $threshold = get_config('mnet', 'drift_threshold');
268 if(empty($threshold)) {
269 // We decided 15 seconds was a pretty good arbitrary threshold
270 // for time-drift between servers, but you can customize this in
271 // the config_plugins table. It's not advised though.
272 set_config('drift_threshold', 15, 'mnet');
275 if ($time_offset > $threshold) {
276 $this->error
[] = '6:Time gap with '.$mnet_peer->name
.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds';
281 $this->xmlrpcresponse
= base64_decode($sig_parser->data_object
);
282 $this->response
= xmlrpc_decode($this->xmlrpcresponse
);
285 // xmlrpc errors are pushed onto the $this->error stack
286 if (is_array($this->response
) && array_key_exists('faultCode', $this->response
)) {
287 // The faultCode 7025 means we tried to connect with an old SSL key
288 // The faultString is the new key - let's save it and try again
289 // The re_key attribute stops us from getting into a loop
290 if($this->response
['faultCode'] == 7025 && empty($mnet_peer->re_key
)) {
291 $record = new stdClass();
292 $record->id
= $mnet_peer->id
;
293 if($this->response
['faultString'] == clean_param($this->response
['faultString'], PARAM_PEM
)) {
294 $record->public_key
= $this->response
['faultString'];
295 $details = openssl_x509_parse($record->public_key
);
296 if(is_array($details) && isset($details['validTo_time_t'])) {
297 $record->public_key_expires
= $details['validTo_time_t'];
298 update_record('mnet_host', $record);
299 $mnet_peer2 = new mnet_peer();
300 $mnet_peer2->set_id($record->id
);
301 $mnet_peer2->re_key
= true;
302 $this->send($mnet_peer2);
304 $this->error
[] = $this->response
['faultCode'] . " : " . $this->response
['faultString'];
307 $this->error
[] = $this->response
['faultCode'] . " : " . $this->response
['faultString'];
310 $this->error
[] = $this->response
['faultCode'] . " : " . $this->response
['faultString'];
313 return empty($this->error
);