3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use Wikimedia\IPUtils
;
24 * A generic class to send a message over UDP
26 * If a message prefix is provided to the constructor or via
27 * UDPTransport::newFromString(), the payload of the UDP datagrams emitted
28 * will be formatted with the prefix and a single space at the start of each
29 * line. This is the payload format expected by the udp2log service.
35 public const MAX_PAYLOAD_SIZE
= 65507;
38 /** @var bool|string */
43 * @param string $host IP address to send to
44 * @param int $port port number
45 * @param int $domain AF_INET or AF_INET6 constant
46 * @param string|bool $prefix Prefix to use, false for no prefix
48 public function __construct( $host, $port, $domain, $prefix = false ) {
51 $this->domain
= $domain;
52 $this->prefix
= $prefix;
56 * @param string $info In the format of "udp://host:port/prefix"
57 * @return UDPTransport
59 public static function newFromString( $info ) {
60 if ( preg_match( '!^udp:(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $info, $m ) ) {
61 // IPv6 bracketed host
63 $port = intval( $m[2] );
64 $prefix = $m[3] ??
false;
66 } elseif ( preg_match( '!^udp:(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $info, $m ) ) {
68 if ( !IPUtils
::isIPv4( $host ) ) {
69 $host = gethostbyname( $host );
71 $port = intval( $m[2] );
72 $prefix = $m[3] ??
false;
75 throw new InvalidArgumentException( __METHOD__
. ': Invalid UDP specification' );
78 return new self( $host, $port, $domain, $prefix );
84 public function emit( $text ): void
{
85 // Clean it up for the multiplexer
86 if ( $this->prefix
!== false ) {
87 $text = preg_replace( '/^/m', $this->prefix
. ' ', $text );
89 if ( strlen( $text ) > self
::MAX_PAYLOAD_SIZE
- 1 ) {
90 $text = substr( $text, 0, self
::MAX_PAYLOAD_SIZE
- 1 );
93 if ( substr( $text, -1 ) != "\n" ) {
96 } elseif ( strlen( $text ) > self
::MAX_PAYLOAD_SIZE
) {
97 $text = substr( $text, 0, self
::MAX_PAYLOAD_SIZE
);
100 $sock = socket_create( $this->domain
, SOCK_DGRAM
, SOL_UDP
);
101 if ( !$sock ) { // @todo should this throw an exception?
105 socket_sendto( $sock, $text, strlen( $text ), 0, $this->host
, $this->port
);
106 socket_close( $sock );