MediaWiki
master
Toggle main menu visibility
UDPTransport.php
Go to the documentation of this file.
1
<?php
6
7
namespace
Wikimedia
;
8
9
use InvalidArgumentException;
10
21
class
UDPTransport
{
22
// Limit to 64 KiB
23
public
const
MAX_PAYLOAD_SIZE
= 65507;
24
private
string
$host;
25
private
int
$port;
27
private
$prefix;
28
private
int
$domain;
29
36
public
function
__construct
( $host, $port, $domain, $prefix =
false
) {
37
$this->host = $host;
38
$this->port = $port;
39
$this->domain = $domain;
40
$this->prefix = $prefix;
41
}
42
47
public
static
function
newFromString
( $info ) {
48
if
( preg_match(
'!^udp:(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!'
, $info, $m ) ) {
49
// IPv6 bracketed host
50
$host = $m[1];
51
$port = intval( $m[2] );
52
$prefix = $m[3] ??
false
;
53
$domain = AF_INET6;
54
} elseif ( preg_match(
'!^udp:(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!'
, $info, $m ) ) {
55
$host = $m[1];
56
if
( !IPUtils::isIPv4( $host ) ) {
57
$host = gethostbyname( $host );
58
}
59
$port = intval( $m[2] );
60
$prefix = $m[3] ??
false
;
61
$domain = AF_INET;
62
}
else
{
63
throw
new
InvalidArgumentException( __METHOD__ .
': Invalid UDP specification'
);
64
}
65
66
return
new
self
( $host, $port, $domain, $prefix );
67
}
68
72
public
function
emit
( $text ): void {
73
// Clean it up for the multiplexer
74
if
( $this->prefix !== false ) {
75
$text = preg_replace(
'/^/m'
, $this->prefix .
' '
, $text );
76
77
if
( strlen( $text ) > self::MAX_PAYLOAD_SIZE - 1 ) {
78
$text = substr( $text, 0, self::MAX_PAYLOAD_SIZE - 1 );
79
}
80
81
if
( !str_ends_with( $text,
"\n"
) ) {
82
$text .=
"\n"
;
83
}
84
} elseif ( strlen( $text ) > self::MAX_PAYLOAD_SIZE ) {
85
$text = substr( $text, 0, self::MAX_PAYLOAD_SIZE );
86
}
87
88
$sock = socket_create( $this->domain, SOCK_DGRAM, SOL_UDP );
89
if
( !$sock ) {
// @todo should this throw an exception?
90
return
;
91
}
92
93
socket_sendto( $sock, $text, strlen( $text ), 0, $this->host, $this->port );
94
socket_close( $sock );
95
}
96
}
97
99
class_alias( UDPTransport::class,
'UDPTransport'
);
if
if(!defined('MW_SETUP_CALLBACK'))
Definition
WebStart.php:72
Wikimedia\UDPTransport
A generic class to send a message over UDP.
Definition
UDPTransport.php:21
Wikimedia\UDPTransport\emit
emit( $text)
Definition
UDPTransport.php:72
Wikimedia\UDPTransport\MAX_PAYLOAD_SIZE
const MAX_PAYLOAD_SIZE
Definition
UDPTransport.php:23
Wikimedia\UDPTransport\__construct
__construct( $host, $port, $domain, $prefix=false)
Definition
UDPTransport.php:36
Wikimedia\UDPTransport\newFromString
static newFromString( $info)
Definition
UDPTransport.php:47
Wikimedia
includes
libs
UDPTransport.php
Generated on
for MediaWiki by
1.18.0