summaryrefslogtreecommitdiffstats
path: root/library/Director/Core/RestApiClient.php
blob: b0854ff4e4ad90742d3a76af60bb25a214ce5cbb (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
<?php

namespace Icinga\Module\Director\Core;

use Icinga\Application\Benchmark;
use RuntimeException;

class RestApiClient
{
    protected $version = 'v1';

    protected $peer;

    protected $port;

    protected $user;

    protected $pass;

    protected $curl;

    protected $readBuffer = '';

    protected $onEvent;

    protected $onEventWantsRaw;

    protected $keepAlive = true;

    public function __construct($peer, $port = 5665, $cn = null)
    {
        $this->peer = $peer;
        $this->port = $port;
    }

    // TODO: replace with Web2 CA trust resource plus cert and get rid
    //       of user/pass or at least strongly advise against using it
    public function setCredentials($user, $pass)
    {
        $this->user = $user;
        $this->pass = $pass;

        return $this;
    }

    public function onEvent($callback, $raw = false)
    {
        $this->onEventWantsRaw = $raw;
        $this->onEvent = $callback;

        return $this;
    }

    public function getPeerIdentity()
    {
        return $this->peer;
    }

    public function setKeepAlive($keepAlive = true)
    {
        $this->keepAlive = (bool) $keepAlive;

        return $this;
    }

    protected function url($url)
    {
        return sprintf('https://%s:%d/%s/%s', $this->peer, $this->port, $this->version, $url);
    }

    /**
     * @param $method
     * @param $url
     * @param null $body
     * @param bool $raw
     * @param bool $stream
     * @return RestApiResponse
     */
    public function request($method, $url, $body = null, $raw = false, $stream = false)
    {
        if (function_exists('curl_version')) {
            return $this->curlRequest($method, $url, $body, $raw, $stream);
        } else {
            throw new RuntimeException(
                'No CURL extension detected, it must be installed and enabled'
            );
        }
    }

    protected function curlRequest($method, $url, $body = null, $raw = false, $stream = false)
    {
        $auth = sprintf('%s:%s', $this->user, $this->pass);
        $headers = [
            'Host: ' . $this->getPeerIdentity(),
        ];

        if (! $this->keepAlive) {
            // This fails on Icinga 2.9:
            // $headers[] = 'Connection: close';
        }

        if (! $raw) {
            $headers[] = 'Accept: application/json';
        }

        if ($body !== null) {
            $body = Json::encode($body);
            $headers[] = 'Content-Type: application/json';
        }

        $curl = $this->curl();
        $opts = [
            CURLOPT_URL            => $this->url($url),
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_USERPWD        => $auth,
            CURLOPT_CUSTOMREQUEST  => strtoupper($method),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 3,

            // TODO: Fix this!
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
        ];

        if ($body !== null) {
            $opts[CURLOPT_POSTFIELDS] = $body;
        }

        if ($stream) {
            $opts[CURLOPT_WRITEFUNCTION] = [$this, 'readPart'];
            $opts[CURLOPT_TCP_NODELAY] = 1;
        }

        curl_setopt_array($curl, $opts);
        // TODO: request headers, validate status code

        Benchmark::measure('Rest Api, sending ' . $url);
        $res = curl_exec($curl);
        if ($res === false) {
            $error = curl_error($curl);
            $this->disconnect();

            throw new RuntimeException("CURL ERROR: $error");
        }

        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($statusCode === 401) {
            $this->disconnect();
            throw new RuntimeException(
                'Unable to authenticate, please check your API credentials'
            );
        }

        Benchmark::measure('Rest Api, got response');
        if (! $this->keepAlive) {
            $this->disconnect();
        }

        if ($stream) {
            return $this;
        }

        if ($raw) {
            return $res;
        } else {
            return RestApiResponse::fromJsonResult($res);
        }
    }

    /**
     * @param  resource $curl
     * @param  $data
     * @return int
     */
    protected function readPart($curl, &$data)
    {
        $length = strlen($data);
        $this->readBuffer .= $data;
        $this->processEvents();
        return $length;
    }

    public function get($url, $body = null)
    {
        return $this->request('get', $url, $body);
    }

    public function getRaw($url, $body = null)
    {
        return $this->request('get', $url, $body, true);
    }

    public function post($url, $body = null)
    {
        return $this->request('post', $url, $body);
    }

    public function put($url, $body = null)
    {
        return $this->request('put', $url, $body);
    }

    public function delete($url, $body = null)
    {
        return $this->request('delete', $url, $body);
    }

    /**
     * @return resource
     */
    protected function curl()
    {
        if ($this->curl === null) {
            $this->curl = curl_init(sprintf('https://%s:%d', $this->peer, $this->port));
            if (! $this->curl) {
                throw new RuntimeException('CURL INIT ERROR: ' . curl_error($this->curl));
            }
        }

        return $this->curl;
    }

    protected function processEvents()
    {
        $offset = 0;
        while (false !== ($pos = strpos($this->readBuffer, "\n", $offset))) {
            if ($pos === $offset) {
                // echo "Got empty line $offset / $pos\n";
                $offset = $pos + 1;
                continue;
            }
            $this->processReadBuffer($offset, $pos);

            $offset = $pos + 1;
        }

        if ($offset > 0) {
            $this->readBuffer = substr($this->readBuffer, $offset + 1);
        }

        // echo "REMAINING: " . strlen($this->readBuffer) . "\n";
    }

    protected function processReadBuffer($offset, $pos)
    {
        if ($this->onEvent === null) {
            return;
        }

        $func = $this->onEvent;
        $str = substr($this->readBuffer, $offset, $pos);
        // printf("Processing %s bytes\n", strlen($str));

        if ($this->onEventWantsRaw) {
            $func($str);
        } else {
            $func(Json::decode($str));
        }
    }

    public function disconnect()
    {
        if ($this->curl !== null) {
            if (is_resource($this->curl)) {
                @curl_close($this->curl);
            }

            $this->curl = null;
        }
    }

    public function __destruct()
    {
        $this->disconnect();
    }
}