1<?php declare(strict_types=1);
2
3/*
4 * This file is part of the Monolog package.
5 *
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Monolog\Handler\SyslogUdp;
13
14use Monolog\Utils;
15use Socket;
16
17class UdpSocket
18{
19    protected const DATAGRAM_MAX_LENGTH = 65023;
20
21    /** @var string */
22    protected $ip;
23    /** @var int */
24    protected $port;
25    /** @var resource|Socket|null */
26    protected $socket;
27
28    public function __construct(string $ip, int $port = 514)
29    {
30        $this->ip = $ip;
31        $this->port = $port;
32        $domain = AF_INET;
33        $protocol = SOL_UDP;
34        // Check if we are using unix sockets.
35        if ($port === 0) {
36            $domain = AF_UNIX;
37            $protocol = IPPROTO_IP;
38        }
39        $this->socket = socket_create($domain, SOCK_DGRAM, $protocol) ?: null;
40    }
41
42    /**
43     * @param  string $line
44     * @param  string $header
45     * @return void
46     */
47    public function write($line, $header = "")
48    {
49        $this->send($this->assembleMessage($line, $header));
50    }
51
52    public function close(): void
53    {
54        if (is_resource($this->socket) || $this->socket instanceof Socket) {
55            socket_close($this->socket);
56            $this->socket = null;
57        }
58    }
59
60    protected function send(string $chunk): void
61    {
62        if (!is_resource($this->socket) && !$this->socket instanceof Socket) {
63            throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
64        }
65        socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
66    }
67
68    protected function assembleMessage(string $line, string $header): string
69    {
70        $chunkSize = static::DATAGRAM_MAX_LENGTH - strlen($header);
71
72        return $header . Utils::substr($line, 0, $chunkSize);
73    }
74}
75