client.php 9.48 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
5
 *
Francois Marier's avatar
Francois Marier committed
6
7
8
9
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
10
 *
Francois Marier's avatar
Francois Marier committed
11
12
13
14
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
15
 *
Francois Marier's avatar
Francois Marier committed
16
17
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19
20
 *
 * @package    mahara
 * @subpackage xmlrpc
21
 * @author     Catalyst IT Ltd
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
24
25
26
 *
 */

27
defined('INTERNAL') || die();
28
require_once(get_config('docroot') . 'api/xmlrpc/lib.php');
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Client {

    private $requesttext      = '';
    private $signedrequest    = '';
    private $encryptedrequest = '';
    private $timeout          = 60;
    private $params           = array();
    private $method           = '';

    function __construct() {
        return true;
    }

    function set_method($method) {
44
        if (is_string($method) && preg_match("@^[A-Za-z0-9]+/[A-Za-z0-9/_-]+(\.php/)?[A-Za-z0-9_-]+$@", $method)) {
45
46
47
48
49
            $this->method = $method;
        }
        return $this;
    }

50
51
    function send($wwwroot, $use_cached_peer=true) {
        $this->peer     = get_peer($wwwroot, $use_cached_peer);
52
        $this->response = '';
53
54
55
        $URL = $this->peer->wwwroot . $this->peer->application->xmlrpcserverurl;

        $ch = curl_init( $URL );
56
57
58
59
60
61
62
63

        $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8"));
        $this->signedrequest = xmldsig_envelope($this->requesttext);
        $this->encryptedrequest = xmlenc_envelope($this->signedrequest, $this->peer->certificate);

        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
64
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mahara');
65
66
67
68
69
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encryptedrequest);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml charset=UTF-8"));

        $timestamp_send    = time();
        $this->rawresponse = curl_exec($ch);
70

71
72
73
74
75
76
        $response_code        = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $response_code_prefix = substr($response_code, 0, 1);
    
        if ('2' != $response_code_prefix) {
            if ('4' == $response_code_prefix) {
                throw new XmlrpcClientException('Client error code: ', $response_code);
77
            } elseif ('5' == $response_code_prefix) {
78
79
80
81
                throw new XmlrpcClientException('An error occurred at the remote server. Code: ', $response_code);
            }
        }

82
        $timestamp_receive = time();
83
        $remote_timestamp  = null;
84
85

        if ($this->rawresponse == false) {
86
            throw new XmlrpcClientException('Curl error: '.curl_errno($ch) .':'. curl_error($ch));
87
88
89
90
91
            return false;
        }

        try {
            $xml = new SimpleXMLElement($this->rawresponse);
92
93
94
95
        }
        catch (Exception $e) {
            log_debug($this->rawresponse);
            throw new XmlrpcClientException('Payload is not a valid XML document (payload is above)', 6001);
96
97
        }

98
        if ($xml->getName() == 'encryptedMessage') {
99
100
101
102
103
            $payload_encrypted = true;
            $wwwroot           = (string)$xml->wwwroot;
            $payload           = xmlenc_envelope_strip($xml);
        }

104
        if ($xml->getName() == 'signedMessage') {
105
106
107
            $payload_signed   = true;
            $remote_timestamp = $xml->timestamp;
            $payload          = xmldsig_envelope_strip($xml);
108
109
        }

110
        if ($xml->getName() == 'methodResponse') {
111
112
113
114
115
116
117
118
119
            $this->response = xmlrpc_decode($payload);

            // Margin of error is the time it took the request to complete.
            $margin_of_error  = $timestamp_receive - $timestamp_send;

            // Guess the time gap between sending the request and the remote machine
            // executing the time() function. Marginally better than nothing.
            $hysteresis       = ($margin_of_error) / 2;

120
            if (!empty($remote_timestamp)) {
121
122
                $remote_timestamp = $remote_timestamp - $hysteresis;
                $time_offset      = $remote_timestamp - $timestamp_send;
123
                if ($time_offset > self::get_max_server_time_difference()) {
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
                    throw new XmlrpcClientException('Time drift ('.$margin_of_error.', '.$time_offset.') is too large.');
                }
            }

            if (is_array($this->response) && array_key_exists('faultCode', $this->response)) {
                if ($this->response['faultCode'] == 7025) {
                    log_info('Remote application has sent us a new public key');
                    // The remote application sent back a new public key, the 
                    // old one must have expired
                    if (array_key_exists('faultString', $this->response)) {
                        $details = openssl_x509_parse($this->response['faultString']);
                        if (isset($details['validTo_time_t'])) {
                            $updateobj = (object)array(
                                'publickey' => $this->response['faultString'],
                                'publickeyexpires' => $details['validTo_time_t'],
                            );
                            $whereobj = (object)array(
                                'wwwroot' => $wwwroot,
                            );
                            update_record('host', $updateobj, $whereobj);
                            log_info('New key has been imported. Valid until ' . date('Y/m/d h:i:s', $details['validTo_time_t']));

                            // Send request again. But don't use the cached 
                            // peer, look it up again now we've changed the 
                            // public key
                            $this->send($wwwroot, false);
                        }
                        else {
                            throw new XmlrpcClientException('Could not parse new public key');
                        }
                    }
                    else {
                        throw new XmlrpcClientException('Remote site claims to have sent a public key, but they LIE');
                    }
158
                }
159
160
161
162
163
164
165
166
167
168
            }

            // Clean up so object can be re-used.
            $this->requesttext      = '';
            $this->signedrequest    = '';
            $this->encryptedrequest = '';
            $this->params           = array();
            $this->method           = '';
            return true;
        } else {
169
            throw new XmlrpcClientException('Unrecognized XML document form: ' . $payload);
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        }
    }

    /**
     * Add a parameter to the array of parameters.
     *
     * @param  string  $argument    A transport ID, as defined in lib.php
     * @param  string  $type        The argument type, can be one of:
     *                              none
     *                              empty
     *                              base64
     *                              boolean
     *                              datetime
     *                              double
     *                              int
     *                              string
     *                              array
     *                              struct
     *                              In its weakly-typed wisdom, PHP will (currently)
     *                              ignore everything except datetime and base64
     * @return bool                 True on success
     */
    function add_param($argument, $type = 'string') {

        $allowed_types = array('none',
                               'empty',
                               'base64',
                               'boolean',
                               'datetime',
                               'double',
                               'int',
                               'i4',
                               'string',
                               'array',
                               'struct');
        if (!in_array($type, $allowed_types)) {
            return false;
        }

        if ($type != 'datetime' && $type != 'base64') {
            $this->params[] = $argument;
            return $this;
        }

        // Note weirdness - The type of $argument gets changed to an object with
        // value and type properties.
        // bool xmlrpc_set_type ( string &value, string type )
        xmlrpc_set_type($argument, $type);
        $this->params[] = $argument;
        return $this;
    }
221
222
223
224
225
226
227
228
229
230
231
232
233

    private static function get_max_server_time_difference() {
        $max_time_difference = (int)get_config('xmlrpcmaxservertimedifference');
        if ($max_time_difference < 15) {
            log_warn('Minimum value allowed for "max_server_time_difference" is 15 seconds');
            $max_time_difference = 15;
        }
        if ($max_time_difference > 300) {
            log_warn('Maximum value allowed for "max_server_time_difference" is 300 seconds');
            $max_time_difference = 300;
        }
        return $max_time_difference;
    }
234
235
}
?>