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