MediaWiki master
UDPTransport.php
Go to the documentation of this file.
1<?php
21use Wikimedia\IPUtils;
22
34 // Limit to 64 KiB
35 public const MAX_PAYLOAD_SIZE = 65507;
36 private string $host;
37 private int $port;
39 private $prefix;
40 private int $domain;
41
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
60 public static function newFromString( $info ) {
61 if ( preg_match( '!^udp:(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $info, $m ) ) {
62 // IPv6 bracketed host
63 $host = $m[1];
64 $port = intval( $m[2] );
65 $prefix = $m[3] ?? false;
66 $domain = AF_INET6;
67 } elseif ( preg_match( '!^udp:(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $info, $m ) ) {
68 $host = $m[1];
69 if ( !IPUtils::isIPv4( $host ) ) {
70 $host = gethostbyname( $host );
71 }
72 $port = intval( $m[2] );
73 $prefix = $m[3] ?? false;
74 $domain = AF_INET;
75 } else {
76 throw new InvalidArgumentException( __METHOD__ . ': Invalid UDP specification' );
77 }
78
79 return new self( $host, $port, $domain, $prefix );
80 }
81
85 public function emit( $text ): void {
86 // Clean it up for the multiplexer
87 if ( $this->prefix !== false ) {
88 $text = preg_replace( '/^/m', $this->prefix . ' ', $text );
89
90 if ( strlen( $text ) > self::MAX_PAYLOAD_SIZE - 1 ) {
91 $text = substr( $text, 0, self::MAX_PAYLOAD_SIZE - 1 );
92 }
93
94 if ( substr( $text, -1 ) != "\n" ) {
95 $text .= "\n";
96 }
97 } elseif ( strlen( $text ) > self::MAX_PAYLOAD_SIZE ) {
98 $text = substr( $text, 0, self::MAX_PAYLOAD_SIZE );
99 }
100
101 $sock = socket_create( $this->domain, SOCK_DGRAM, SOL_UDP );
102 if ( !$sock ) { // @todo should this throw an exception?
103 return;
104 }
105
106 socket_sendto( $sock, $text, strlen( $text ), 0, $this->host, $this->port );
107 socket_close( $sock );
108 }
109}
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:81
A generic class to send a message over UDP.
const MAX_PAYLOAD_SIZE
static newFromString( $info)
__construct( $host, $port, $domain, $prefix=false)