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) {
125 global $CFG, $MNET, $DB;
128 if (!$this->permission_to_call($mnet_peer)) {
132 $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8"));
133 $this->signedrequest = mnet_sign_message($this->requesttext);
134 $this->encryptedrequest = mnet_encrypt_message($this->signedrequest, $mnet_peer->public_key);
136 $httprequest = $this->prepare_http_request($mnet_peer);
137 curl_setopt($httprequest, CURLOPT_POSTFIELDS, $this->encryptedrequest);
139 $timestamp_send = time();
140 $this->rawresponse = curl_exec($httprequest);
141 $timestamp_receive = time();
143 if ($this->rawresponse === false) {
144 $this->error[] = curl_errno($httprequest) .':'. curl_error($httprequest);
147 curl_close($httprequest);
151 $crypt_parser = new mnet_encxml_parser();
152 $crypt_parser->parse($this->rawresponse);
154 // If we couldn't parse the message, or it doesn't seem to have encrypted contents,
155 // give the most specific error msg available & return
156 if (!$crypt_parser->payload_encrypted) {
157 if (! empty($crypt_parser->remoteerror)) {
158 $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror;
159 } else if (! empty($crypt_parser->error)) {
160 $crypt_parser_error = $crypt_parser->error[0];
162 $message = '3:XML Parse error in payload: '.$crypt_parser_error['string']."\n";
163 if (array_key_exists('lineno', $crypt_parser_error)) {
164 $message .= 'At line number: '.$crypt_parser_error['lineno']."\n";
166 if (array_key_exists('line', $crypt_parser_error)) {
167 $message .= 'Which reads: '.$crypt_parser_error['line']."\n";
169 $this->error[] = $message;
171 $this->error[] = '1:Payload not encrypted ';
174 $crypt_parser->free_resource();
178 $key = array_pop($crypt_parser->cipher);
179 $data = array_pop($crypt_parser->cipher);
181 $crypt_parser->free_resource();
183 // Initialize payload var
184 $decryptedenvelope = '';
186 // &$decryptedenvelope
187 $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $MNET->get_private_key());
190 // Decryption failed... let's try our archived keys
191 $openssl_history = get_config('mnet', 'openssl_history');
192 if(empty($openssl_history)) {
193 $openssl_history = array();
194 set_config('openssl_history', serialize($openssl_history), 'mnet');
196 $openssl_history = unserialize($openssl_history);
198 foreach($openssl_history as $keyset) {
199 $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
200 $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $keyresource);
202 // It's an older code, sir, but it checks out
209 trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}.");
210 $this->error[] = '3:No key match';
214 if (strpos(substr($decryptedenvelope, 0, 100), '<signedMessage>')) {
215 $sig_parser = new mnet_encxml_parser();
216 $sig_parser->parse($decryptedenvelope);
218 $this->error[] = '2:Payload not signed: ' . $decryptedenvelope;
222 // Margin of error is the time it took the request to complete.
223 $margin_of_error = $timestamp_receive - $timestamp_send;
225 // Guess the time gap between sending the request and the remote machine
226 // executing the time() function. Marginally better than nothing.
227 $hysteresis = ($margin_of_error) / 2;
229 $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis;
230 $time_offset = $remote_timestamp - $timestamp_send;
231 if ($time_offset > 0) {
232 $threshold = get_config('mnet', 'drift_threshold');
233 if(empty($threshold)) {
234 // We decided 15 seconds was a pretty good arbitrary threshold
235 // for time-drift between servers, but you can customize this in
236 // the config_plugins table. It's not advised though.
237 set_config('drift_threshold', 15, 'mnet');
240 if ($time_offset > $threshold) {
241 $this->error[] = '6:Time gap with '.$mnet_peer->name.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds';
246 $this->xmlrpcresponse = base64_decode($sig_parser->data_object);
247 $this->response = xmlrpc_decode($this->xmlrpcresponse);
249 // xmlrpc errors are pushed onto the $this->error stack
250 if (is_array($this->response) && array_key_exists('faultCode', $this->response)) {
251 // The faultCode 7025 means we tried to connect with an old SSL key
252 // The faultString is the new key - let's save it and try again
253 // The re_key attribute stops us from getting into a loop
254 if($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) {
255 // If the new certificate doesn't come thru clean_param() unmolested, error out
256 if($this->response['faultString'] != clean_param($this->response['faultString'], PARAM_PEM)) {
257 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
259 $record = new stdClass();
260 $record->id = $mnet_peer->id;
261 $record->public_key = $this->response['faultString'];
262 $details = openssl_x509_parse($record->public_key);
263 if(!isset($details['validTo_time_t'])) {
264 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
266 $record->public_key_expires = $details['validTo_time_t'];
267 $DB->update_record('mnet_host', $record);
269 // Create a new peer object populated with the new info & try re-sending the request
270 $rekeyed_mnet_peer = new mnet_peer();
271 $rekeyed_mnet_peer->set_id($record->id);
272 $rekeyed_mnet_peer->re_key = true;
273 return $this->send($rekeyed_mnet_peer);
275 if (!empty($CFG->mnet_rpcdebug)) {
276 $guidance = get_string('error'.$this->response['faultCode'], 'mnet');
280 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'] ."\n".$guidance;
282 return empty($this->error);
286 * Check that we are permitted to call method on specified peer
288 * @param object $mnet_peer A mnet_peer object with details of the remote host we're connecting to
289 * @return bool True if we permit calls to method on specified peer, False otherwise.
292 function permission_to_call($mnet_peer) {
295 // Executing any system method is permitted.
296 $system_methods = array('system/listMethods', 'system/methodSignature', 'system/methodHelp', 'system/listServices');
297 if (in_array($this->method, $system_methods) ) {
301 $id_list = $mnet_peer->id;
302 if (!empty($CFG->mnet_all_hosts_id)) {
303 $id_list .= ', '.$CFG->mnet_all_hosts_id;
305 // At this point, we don't care if the remote host implements the
306 // method we're trying to call. We just want to know that:
307 // 1. The method belongs to some service, as far as OUR host knows
308 // 2. We are allowed to subscribe to that service on this mnet_peer
310 // Find methods that we subscribe to on this host
316 {mnet_service2rpc} s2r,
317 {mnet_host2service} h2s
319 r.xmlrpc_path = ? AND
321 s2r.serviceid = h2s.serviceid AND
322 h2s.subscribe = '1' AND
323 h2s.hostid in ({$id_list})";
325 $permission = $DB->get_record_sql($sql, array($this->method));
326 if ($permission == true) {
330 $this->error[] = '7:User with ID '. $USER->id .
331 ' attempted to call unauthorised method '.
332 $this->method.' on host '.
338 * Generate a curl handle and prepare it for sending to an mnet host
340 * @param object $mnet_peer A mnet_peer object with details of the remote host the request will be sent to
341 * @return cURL handle - the almost-ready-to-send http request
343 function prepare_http_request ($mnet_peer) {
344 $this->uri = $mnet_peer->wwwroot . $mnet_peer->application->xmlrpc_server_url;
346 // Initialize request the target URL
347 $httprequest = curl_init($this->uri);
348 curl_setopt($httprequest, CURLOPT_TIMEOUT, $this->timeout);
349 curl_setopt($httprequest, CURLOPT_RETURNTRANSFER, true);
350 curl_setopt($httprequest, CURLOPT_POST, true);
351 curl_setopt($httprequest, CURLOPT_USERAGENT, 'Moodle');
352 curl_setopt($httprequest, CURLOPT_HTTPHEADER, array("Content-Type: text/xml charset=UTF-8"));
353 curl_setopt($httprequest, CURLOPT_SSL_VERIFYPEER, false);
354 curl_setopt($httprequest, CURLOPT_SSL_VERIFYHOST, 0);