summaryrefslogtreecommitdiff
path: root/vendor/JsonRPC/Server.php
blob: 72d4e27e512d17a547a5e818c934f3584d6ce7ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
158
159
160
161
162
163
164
165
166
167
168
169
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
<?php

namespace JsonRPC;

use ReflectionFunction;
use Closure;

/**
 * JsonRPC server class
 *
 * @package JsonRPC
 * @author Frederic Guillot
 * @license Unlicense http://unlicense.org/
 */
class Server
{
    /**
     * Data received from the client
     *
     * @access private
     * @var string
     */
    private $payload;

    /**
     * List of procedures
     *
     * @static
     * @access private
     * @var array
     */
    static private $procedures = array();

    /**
     * Constructor
     *
     * @access public
     * @param  string   $payload   Client data
     */
    public function __construct($payload = '')
    {
        $this->payload = $payload;
    }

    /**
     * IP based client restrictions
     *
     * Return an HTTP error 403 if the client is not allowed
     *
     * @access public
     * @param  array   $hosts   List of hosts
     */
    public function allowHosts(array $hosts) {

        if (! in_array($_SERVER['REMOTE_ADDR'], $hosts)) {

            header('Content-Type: application/json');
            header('HTTP/1.0 403 Forbidden');
            echo '["Access Forbidden"]';
            exit;
        }
    }

    /**
     * HTTP Basic authentication
     *
     * Return an HTTP error 401 if the client is not allowed
     *
     * @access public
     * @param  array   $users   Map of username/password
     */
    public function authentication(array $users)
    {
        // OVH workaround
        if (isset($_SERVER['REMOTE_USER'])) {
            list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REMOTE_USER'], 6)));
        }

        if (! isset($_SERVER['PHP_AUTH_USER']) ||
            ! isset($users[$_SERVER['PHP_AUTH_USER']]) ||
            $users[$_SERVER['PHP_AUTH_USER']] !== $_SERVER['PHP_AUTH_PW']) {

            header('WWW-Authenticate: Basic realm="JsonRPC"');
            header('Content-Type: application/json');
            header('HTTP/1.0 401 Unauthorized');
            echo '["Authentication failed"]';
            exit;
        }
    }

    /**
     * Register a new procedure
     *
     * @access public
     * @param  string   $name       Procedure name
     * @param  closure  $callback   Callback
     */
    public function register($name, Closure $callback)
    {
        self::$procedures[$name] = $callback;
    }

    /**
     * Unregister a procedure
     *
     * @access public
     * @param  string   $name       Procedure name
     */
    public function unregister($name)
    {
        if (isset(self::$procedures[$name])) {
            unset(self::$procedures[$name]);
        }
    }

    /**
     * Unregister all procedures
     *
     * @access public
     */
    public function unregisterAll()
    {
        self::$procedures = array();
    }

    /**
     * Return the response to the client
     *
     * @access public
     * @param  array    $data      Data to send to the client
     * @param  array    $payload   Incoming data
     * @return string
     */
    public function getResponse(array $data, array $payload = array())
    {
        if (! array_key_exists('id', $payload)) {
            return '';
        }

        $response = array(
            'jsonrpc' => '2.0',
            'id' => $payload['id']
        );

        $response = array_merge($response, $data);

        @header('Content-Type: application/json');
        return json_encode($response);
    }

    /**
     * Map arguments to the procedure
     *
     * @access public
     * @param  array    $request_params      Incoming arguments
     * @param  array    $method_params       Procedure arguments
     * @param  array    $params              Arguments to pass to the callback
     * @param  integer  $nb_required_params  Number of required parameters
     * @return bool
     */
    public function mapParameters(array $request_params, array $method_params, array &$params, $nb_required_params)
    {
        if (count($request_params) < $nb_required_params) {
            return false;
        }

        // Positional parameters
        if (array_keys($request_params) === range(0, count($request_params) - 1)) {
            $params = $request_params;
            return true;
        }

        // Named parameters
        foreach ($method_params as $p) {

            $name = $p->getName();

            if (isset($request_params[$name])) {
                $params[$name] = $request_params[$name];
            }
            else if ($p->isDefaultValueAvailable()) {
                $params[$name] = $p->getDefaultValue();
            }
            else {
                return false;
            }
        }

        return true;
    }

    /**
     * Parse the payload and test if the parsed JSON is ok
     *
     * @access public
     * @return boolean
     */
    public function isValidJsonFormat()
    {
        if (empty($this->payload)) {
            $this->payload = file_get_contents('php://input');
        }

        if (is_string($this->payload)) {
            $this->payload = json_decode($this->payload, true);
        }

        return is_array($this->payload);
    }

    /**
     * Test if all required JSON-RPC parameters are here
     *
     * @access public
     * @return boolean
     */
    public function isValidJsonRpcFormat()
    {
        if (! isset($this->payload['jsonrpc']) ||
            ! isset($this->payload['method']) ||
            ! is_string($this->payload['method']) ||
            $this->payload['jsonrpc'] !== '2.0' ||
            (isset($this->payload['params']) && ! is_array($this->payload['params']))) {

            return false;
        }

        return true;
    }

    /**
     * Return true if we have a batch request
     *
     * @access public
     * @return boolean
     */
    private function isBatchRequest()
    {
        return array_keys($this->payload) === range(0, count($this->payload) - 1);
    }

    /**
     * Handle batch request
     *
     * @access private
     * @return string
     */
    private function handleBatchRequest()
    {
        $responses = array();

        foreach ($this->payload as $payload) {

            if (! is_array($payload)) {

                $responses[] = $this->getResponse(array(
                    'error' => array(
                        'code' => -32600,
                        'message' => 'Invalid Request'
                    )),
                    array('id' => null)
                );
            }
            else {

                $server = new Server($payload);
                $response = $server->execute();

                if ($response) {
                    $responses[] = $response;
                }
            }
        }

        return empty($responses) ? '' : '['.implode(',', $responses).']';
    }

    /**
     * Parse incoming requests
     *
     * @access public
     * @return string
     */
    public function execute()
    {
        // Invalid Json
        if (! $this->isValidJsonFormat()) {
            return $this->getResponse(array(
                'error' => array(
                    'code' => -32700,
                    'message' => 'Parse error'
                )),
                array('id' => null)
            );
        }

        // Handle batch request
        if ($this->isBatchRequest()){
            return $this->handleBatchRequest();
        }

        // Invalid JSON-RPC format
        if (! $this->isValidJsonRpcFormat()) {

            return $this->getResponse(array(
                'error' => array(
                    'code' => -32600,
                    'message' => 'Invalid Request'
                )),
                array('id' => null)
            );
        }

        // Procedure not found
        if (! isset(self::$procedures[$this->payload['method']])) {

            return $this->getResponse(array(
                'error' => array(
                    'code' => -32601,
                    'message' => 'Method not found'
                )),
                $this->payload
            );
        }

        // Execute the procedure
        $callback = self::$procedures[$this->payload['method']];
        $params = array();

        $reflection = new ReflectionFunction($callback);

        if (isset($this->payload['params'])) {

            $parameters = $reflection->getParameters();

            if (! $this->mapParameters($this->payload['params'], $parameters, $params, $reflection->getNumberOfRequiredParameters())) {

                return $this->getResponse(array(
                    'error' => array(
                        'code' => -32602,
                        'message' => 'Invalid params'
                    )),
                    $this->payload
                );
            }
        }

        $result = $reflection->invokeArgs($params);

        return $this->getResponse(array('result' => $result), $this->payload);
    }
}