c45c1546502e74a06d8b64ff044e1e77beafa9db
[moodle.git] / mnet / xmlrpc / client.php
1 <?php
2 /**
3  * An XML-RPC client
4  *
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
15  */
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
26      */
27     function mnet_xmlrpc_client() {
28         return true;
29     }
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
35      */
36     function set_timeout($timeout) {
37         if (!is_integer($timeout)) {
38             if (is_numeric($timeout)) {
39                 $this->timeout = (integer($timeout));
40                 return true;
41             }
42             return false;
43         }
44         $this->timeout = $timeout;
45         return true;
46     }
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
55      */
56     function set_method($xmlrpcpath) {
57         if (is_string($xmlrpcpath)) {
58             $this->method = $xmlrpcpath;
59             $this->params = array();
60             return true;
61         }
62         $this->method = '';
63         $this->params = array();
64         return false;
65     }
67     /**
68      * Add a parameter to the array of parameters.
69      *
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
85      */
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;
101         }
103         if ($type != 'datetime' && $type != 'base64') {
104             $this->params[] = $argument;
105             return true;
106         }
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;
114     }
116     /**
117      * Send the request to the server - decode and return the response
118      *
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
123      */
124     function send($mnet_peer) {
125         global $CFG, $MNET, $DB;
128         if (!$this->permission_to_call($mnet_peer)) {
129             return false;
130         }
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);
145             return false;
146         }
147         curl_close($httprequest);
149         $mnet_peer->touch();
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";
165                 }
166                 if (array_key_exists('line', $crypt_parser_error)) {
167                     $message .= 'Which reads: '.$crypt_parser_error['line']."\n";
168                 }
169                 $this->error[] = $message;
170             } else {
171                 $this->error[] = '1:Payload not encrypted ';
172             }
174             $crypt_parser->free_resource();
175             return false;
176         }
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());
189         if (!$isOpen) {
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');
195             } else {
196                 $openssl_history = unserialize($openssl_history);
197             }
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);
201                 if ($isOpen) {
202                     // It's an older code, sir, but it checks out
203                     break;
204                 }
205             }
206         }
208         if (!$isOpen) {
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';
211             return false;
212         }
214         if (strpos(substr($decryptedenvelope, 0, 100), '<signedMessage>')) {
215             $sig_parser = new mnet_encxml_parser();
216             $sig_parser->parse($decryptedenvelope);
217         } else {
218             $this->error[] = '2:Payload not signed: ' . $decryptedenvelope;
219             return false;
220         }
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');
238                 $threshold = 15;
239             }
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';
242                 return false;
243             }
244         }
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'];
258                 }
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'];
265                 }
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);
274             }
275             if (!empty($CFG->mnet_rpcdebug)) {
276                 $guidance = get_string('error'.$this->response['faultCode'], 'mnet');
277             } else {
278                 $guidance = '';
279             }
280             $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'] ."\n".$guidance;
281         }
282         return empty($this->error);
283     }
285     /**
286      * Check that we are permitted to call method on specified peer
287      *
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.
290      */
292     function permission_to_call($mnet_peer) {
293         global $DB, $CFG;
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) ) {
298             return true;
299         }
301         $id_list = $mnet_peer->id;
302         if (!empty($CFG->mnet_all_hosts_id)) {
303             $id_list .= ', '.$CFG->mnet_all_hosts_id;
304         }
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
311         $sql = "
312             SELECT
313                 *
314             FROM
315                 {mnet_rpc} r,
316                 {mnet_service2rpc} s2r,
317                 {mnet_host2service} h2s
318             WHERE
319                 r.xmlrpc_path = ? AND
320                 s2r.rpcid = r.id 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) {
327             return true;
328         }
329         global $USER;
330         $this->error[] = '7:User with ID '. $USER->id .
331                          ' attempted to call unauthorised method '.
332                          $this->method.' on host '.
333                          $mnet_peer->wwwroot;
334         return false;
335     }
337     /**
338      * Generate a curl handle and prepare it for sending to an mnet host
339      *
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
342      */
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);
355         return $httprequest;
356     }
358 ?>