MediaWiki  1.34.0
UDPTransport.php
Go to the documentation of this file.
1 <?php
31 class UDPTransport {
32  private $host, $port, $prefix, $domain;
33 
40  public function __construct( $host, $port, $domain, $prefix = false ) {
41  $this->host = $host;
42  $this->port = $port;
43  $this->domain = $domain;
44  $this->prefix = $prefix;
45  }
46 
52  public static function newFromString( $info ) {
53  if ( preg_match( '!^udp:(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $info, $m ) ) {
54  // IPv6 bracketed host
55  $host = $m[1];
56  $port = intval( $m[2] );
57  $prefix = $m[3] ?? false;
58  $domain = AF_INET6;
59  } elseif ( preg_match( '!^udp:(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $info, $m ) ) {
60  $host = $m[1];
61  if ( !IP::isIPv4( $host ) ) {
62  $host = gethostbyname( $host );
63  }
64  $port = intval( $m[2] );
65  $prefix = $m[3] ?? false;
66  $domain = AF_INET;
67  } else {
68  throw new InvalidArgumentException( __METHOD__ . ': Invalid UDP specification' );
69  }
70 
71  return new self( $host, $port, $domain, $prefix );
72  }
73 
77  public function emit( $text ) {
78  // Clean it up for the multiplexer
79  if ( $this->prefix !== false ) {
80  $text = preg_replace( '/^/m', $this->prefix . ' ', $text );
81 
82  // Limit to 64KB
83  if ( strlen( $text ) > 65506 ) {
84  $text = substr( $text, 0, 65506 );
85  }
86 
87  if ( substr( $text, -1 ) != "\n" ) {
88  $text .= "\n";
89  }
90  } elseif ( strlen( $text ) > 65507 ) {
91  $text = substr( $text, 0, 65507 );
92  }
93 
94  $sock = socket_create( $this->domain, SOCK_DGRAM, SOL_UDP );
95  if ( !$sock ) { // @todo should this throw an exception?
96  return;
97  }
98 
99  socket_sendto( $sock, $text, strlen( $text ), 0, $this->host, $this->port );
100  socket_close( $sock );
101  }
102 }
UDPTransport\newFromString
static newFromString( $info)
Definition: UDPTransport.php:52
UDPTransport\$port
$port
Definition: UDPTransport.php:32
UDPTransport
A generic class to send a message over UDP.
Definition: UDPTransport.php:31
UDPTransport\__construct
__construct( $host, $port, $domain, $prefix=false)
Definition: UDPTransport.php:40
UDPTransport\$prefix
$prefix
Definition: UDPTransport.php:32
IP\isIPv4
static isIPv4( $ip)
Given a string, determine if it as valid IP in IPv4 only.
Definition: IP.php:99
UDPTransport\$host
$host
Definition: UDPTransport.php:32
UDPTransport\$domain
$domain
Definition: UDPTransport.php:32
UDPTransport\emit
emit( $text)
Definition: UDPTransport.php:77