| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
use Wikimedia\IPUtils; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
class UDPTransport { |
| 34 |
|
| 35 |
public const MAX_PAYLOAD_SIZE = 65507; |
| 36 |
private string $host; |
| 37 |
private int $port; |
| 38 |
|
| 39 |
private $prefix; |
| 40 |
private int $domain; |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
public function __construct( $host, $port, $domain, $prefix = false ) { |
| 49 |
$this->host = $host; |
| 50 |
$this->port = $port; |
| 51 |
$this->domain = $domain; |
| 52 |
$this->prefix = $prefix; |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
public static function newFromString( $info ) { |
| 60 |
if ( preg_match( '!^udp:(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $info, $m ) ) { |
| 61 |
|
| 62 |
$host = $m[1]; |
| 63 |
$port = intval( $m[2] ); |
| 64 |
$prefix = $m[3] ?? false; |
| 65 |
$domain = AF_INET6; |
| 66 |
} elseif ( preg_match( '!^udp:(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $info, $m ) ) { |
| 67 |
$host = $m[1]; |
| 68 |
if ( !IPUtils::isIPv4( $host ) ) { |
| 69 |
$host = gethostbyname( $host ); |
| 70 |
} |
| 71 |
$port = intval( $m[2] ); |
| 72 |
$prefix = $m[3] ?? false; |
| 73 |
$domain = AF_INET; |
| 74 |
} else { |
| 75 |
throw new InvalidArgumentException( __METHOD__ . ': Invalid UDP specification' ); |
| 76 |
} |
| 77 |
|
| 78 |
return new self( $host, $port, $domain, $prefix ); |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
public function emit( $text ): void { |
| 85 |
|
| 86 |
if ( $this->prefix !== false ) { |
| 87 |
$text = preg_replace( '/^/m', $this->prefix . ' ', $text ); |
| 88 |
|
| 89 |
if ( strlen( $text ) > self::MAX_PAYLOAD_SIZE - 1 ) { |
| 90 |
$text = substr( $text, 0, self::MAX_PAYLOAD_SIZE - 1 ); |
| 91 |
} |
| 92 |
|
| 93 |
if ( substr( $text, -1 ) != "\n" ) { |
| 94 |
$text .= "\n"; |
| 95 |
} |
| 96 |
} elseif ( strlen( $text ) > self::MAX_PAYLOAD_SIZE ) { |
| 97 |
$text = substr( $text, 0, self::MAX_PAYLOAD_SIZE ); |
| 98 |
} |
| 99 |
|
| 100 |
$sock = socket_create( $this->domain, SOCK_DGRAM, SOL_UDP ); |
| 101 |
if ( !$sock ) { |
| 102 |
return; |
| 103 |
} |
| 104 |
|
| 105 |
socket_sendto( $sock, $text, strlen( $text ), 0, $this->host, $this->port ); |
| 106 |
socket_close( $sock ); |
| 107 |
} |
| 108 |
} |