Completed
Pull Request — master (#64)
by
unknown
01:52
created

Client::close()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
/**
4
 * This file is part of the php-epp2 library.
5
 *
6
 * (c) Gunter Grodotzki <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE file
9
 * that was distributed with this source code.
10
 */
11
12
namespace AfriCC\EPP;
13
14
use AfriCC\EPP\Frame\Command\Logout as LogoutCommand;
15
use AfriCC\EPP\Frame\ResponseFactory;
16
use Exception;
17
18
/**
19
 * A high level TCP (SSL) based client for the Extensible Provisioning Protocol (EPP)
20
 *
21
 * @see http://tools.ietf.org/html/rfc5734
22
 *
23
 * As this class deals directly with sockets it's untestable
24
 * @codeCoverageIgnore
25
 */
26
class Client extends AbstractClient implements ClientInterface
27
{
28
    protected $socket;
29
    protected $chunk_size;
30
    protected $verify_peer_name;
31
32
    public function __construct(array $config)
33
    {
34
        parent::__construct($config);
35
36
        if (!empty($config['chunk_size'])) {
37
            $this->chunk_size = (int) $config['chunk_size'];
38
        } else {
39
            $this->chunk_size = 1024;
40
        }
41
42
        if (!empty($config['verify_peer_name'])) {
43
            $this->verify_peer_name = (bool) $config['verify_peer_name'];
44
        } else {
45
            $this->verify_peer_name = true;
46
        }
47
48
        if ($this->port === false) {
49
            // if not set, default port is 700
50
            $this->port = 700;
51
        }
52
    }
53
54
    public function __destruct()
55
    {
56
        $this->close();
57
    }
58
59
    /**
60
     * Setup context in case of ssl connection
61
     *
62
     * @return resource|null
63
     */
64
    private function setupContext()
65
    {
66
        if (!$this->ssl) {
67
            return null;
68
        }
69
70
        $context = stream_context_create();
71
72
        $options_array = [
73
            'verify_peer' => false,
74
            'verify_peer_name' => $this->verify_peer_name,
75
            'allow_self_signed' => true,
76
            'local_cert' => $this->local_cert,
77
            'passphrase' => $this->passphrase,
78
            'cafile' => $this->ca_cert,
79
            'local_pk' => $this->pk_cert
80
        ];
81
82
        // filter out empty user provided values
83
        $options_array = array_filter($options_array, function($var){return !is_null($var);});
84
85
        $options = ['ssl' => $options_array];
86
87
        // stream_context_set_option accepts array of options in form of $arr['wrapper']['option'] = value
88
        stream_context_set_option($context, $options);
89
90
        return $context;
91
    }
92
93
    /**
94
     * Setup connection socket
95
     *
96
     * @param resource|null $context SSL context or null in case of tcp connection
97
     *
98
     * @throws Exception
99
     */
100
    private function setupSocket($context = null)
101
    {
102
        $proto = $this->ssl ? 'ssl' : 'tcp';
103
        $target = sprintf('%s://%s:%d', $proto, $this->host, $this->port);
104
105
        $errno = 0;
106
        $errstr = '';
107
108
        $this->socket = @stream_socket_client($target, $errno, $errstr, $this->connect_timeout, STREAM_CLIENT_CONNECT, $context);
109
110
        if ($this->socket === false) {
111
            throw new Exception($errstr, $errno);
112
        }
113
114
        // set stream time out
115
        if (!stream_set_timeout($this->socket, $this->timeout)) {
116
            throw new Exception('unable to set stream timeout');
117
        }
118
119
        // set to non-blocking
120
        if (!stream_set_blocking($this->socket, 0)) {
121
            throw new Exception('unable to set blocking');
122
        }
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     *
128
     * @see \AfriCC\EPP\ClientInterface::connect()
129
     */
130
    public function connect($newPassword = false)
131
    {
132
        $context = $this->setupContext();
133
        $this->setupSocket($context);
134
135
        // get greeting
136
        $greeting = $this->getFrame();
137
138
        // login
139
        $this->login($newPassword);
140
141
        // return greeting
142
        return $greeting;
143
    }
144
145
    /**
146
     * Closes a previously opened EPP connection
147
     */
148
    public function close()
149
    {
150
        if ($this->active()) {
151
            // send logout frame
152
            $this->request(new LogoutCommand());
153
154
            return fclose($this->socket);
155
        }
156
157
        return false;
158
    }
159
160
    /**
161
     * Get an EPP frame from the server.
162
     */
163
    public function getFrame()
164
    {
165
        $header = $this->recv(4);
166
167
        // Unpack first 4 bytes which is our length
168
        $unpacked = unpack('N', $header);
169
        $length = $unpacked[1];
170
171
        if ($length < 5) {
172
            throw new Exception(sprintf('Got a bad frame header length of %d bytes from peer', $length));
173
        } else {
174
            $length -= 4;
175
176
            return ResponseFactory::build($this->recv($length));
177
        }
178
    }
179
180
    /**
181
     * sends a XML-based frame to the server
182
     *
183
     * @param FrameInterface $frame the frame to send to the server
184
     */
185
    public function sendFrame(FrameInterface $frame)
186
    {
187
        // some frames might require a client transaction identifier, so let us
188
        // inject it before sending the frame
189
        if ($frame instanceof TransactionAwareInterface) {
190
            $frame->setClientTransactionId($this->generateClientTransactionId());
191
        }
192
193
        $buffer = (string) $frame;
194
        $header = pack('N', mb_strlen($buffer, 'ASCII') + 4);
195
196
        return $this->send($header . $buffer);
197
    }
198
199
    /**
200
     * a wrapper around sendFrame() and getFrame()
201
     */
202
    public function request(FrameInterface $frame)
203
    {
204
        $this->sendFrame($frame);
205
206
        return $this->getFrame();
207
    }
208
209
    protected function log($message, $color = '0;32')
210
    {
211
        if ($message === '' || !$this->debug) {
212
            return;
213
        }
214
        echo sprintf("\033[%sm%s\033[0m", $color, $message);
215
    }
216
217
    /**
218
     * check if socket is still active
219
     *
220
     * @return bool
221
     */
222
    private function active()
223
    {
224
        return !is_resource($this->socket) || feof($this->socket) ? false : true;
225
    }
226
227
    /**
228
     * receive socket data
229
     *
230
     * @param int $length
231
     *
232
     * @throws Exception
233
     *
234
     * @return string
235
     */
236
    private function recv($length)
237
    {
238
        $result = '';
239
240
        $info = stream_get_meta_data($this->socket);
241
        $hard_time_limit = time() + $this->timeout + 2;
242
243
        while (!$info['timed_out'] && !feof($this->socket)) {
244
            // Try read remaining data from socket
245
            $buffer = @fread($this->socket, $length - mb_strlen($result, 'ASCII'));
246
247
            // If the buffer actually contains something then add it to the result
248
            if ($buffer !== false) {
249
                $this->log($buffer);
250
                $result .= $buffer;
251
252
                // break if all data received
253
                if (mb_strlen($result, 'ASCII') === $length) {
254
                    break;
255
                }
256
            } else {
257
                // sleep 0.25s
258
                usleep(250000);
259
            }
260
261
            // update metadata
262
            $info = stream_get_meta_data($this->socket);
263
            if (time() >= $hard_time_limit) {
264
                throw new Exception('Timeout while reading from EPP Server');
265
            }
266
        }
267
268
        // check for timeout
269
        if ($info['timed_out']) {
270
            throw new Exception('Timeout while reading data from socket');
271
        }
272
273
        return $result;
274
    }
275
276
    /**
277
     * send data to socket
278
     *
279
     * @param string $buffer
280
     */
281
    private function send($buffer)
282
    {
283
        $info = stream_get_meta_data($this->socket);
284
        $hard_time_limit = time() + $this->timeout + 2;
285
        $length = mb_strlen($buffer, 'ASCII');
286
287
        $pos = 0;
288
        while (!$info['timed_out'] && !feof($this->socket)) {
289
            // Some servers don't like a lot of data, so keep it small per chunk
290
            $wlen = $length - $pos;
291
292
            if ($wlen > $this->chunk_size) {
293
                $wlen = $this->chunk_size;
294
            }
295
296
            // try write remaining data from socket
297
            $written = @fwrite($this->socket, mb_substr($buffer, $pos, $wlen, 'ASCII'), $wlen);
298
299
            // If we read something, bump up the position
300
            if ($written) {
301
                if ($this->debug) {
302
                    $this->log(mb_substr($buffer, $pos, $wlen, 'ASCII'), '1;31');
303
                }
304
                $pos += $written;
305
306
                // break if all written
307
                if ($pos === $length) {
308
                    break;
309
                }
310
            } else {
311
                // sleep 0.25s
312
                usleep(250000);
313
            }
314
315
            // update metadata
316
            $info = stream_get_meta_data($this->socket);
317
            if (time() >= $hard_time_limit) {
318
                throw new Exception('Timeout while writing to EPP Server');
319
            }
320
        }
321
322
        // check for timeout
323
        if ($info['timed_out']) {
324
            throw new Exception('Timeout while writing data to socket');
325
        }
326
327
        if ($pos !== $length) {
328
            throw new Exception('Writing short %d bytes', $length - $pos);
329
        }
330
331
        return $pos;
332
    }
333
}
334