openrvdas.logger.readers.udp_reader

No module-level documentation available.
  1#!/usr/bin/env python3
  2
  3import logging
  4import socket
  5
  6from logger.readers.reader import Reader  # noqa: E402
  7
  8# The UDP header's `length` field sets a theoretical limit of 65,535 bytes
  9# (8-byte header + 65,527 bytes of data) for a UDP datagram.  Technically, IPV4
 10# or IPv6 headers use up some of that size, so actual maximum data sent per
 11# datagram is slightly less.
 12#
 13# UDP receivers should always request the max, though, because if you request
 14# less than what's on the wire, you get what you asked for and the rest gets
 15# tossed on the floor.  There's no built-in error detection/correction in UDP,
 16# so that would mess things up pretty good.
 17READ_BUFFER_SIZE = 65535
 18
 19# On the send side of things, we can (and do) detect when a write has failed
 20# because the user's `record` was too big.  This is usually because the user is
 21# trying to send huge datagrams after looking up the "theoretical max size of a
 22# datagram" on wikipedia.  Well, it's called "theoretical" for a reason.  It's
 23# really the maximum size of the data portion of a UDP datagram, but that
 24# doesn't take into account extra header for IPv4/IPv6 or seemingly random
 25# system-level caps (e.g., Mac's socket implementation set maximum udp send
 26# size to 9K).
 27#
 28# When UDPWriter detects this condition, it fragments the record into smaller
 29# records and appends each fragment with this FRAGMENT_MARKER.  Inside
 30# UDPReader.read(), we check to see if a received datagram ends with this
 31# marker, and if it does, we read another datagram and combine the results
 32# (over and over until we get a datagram that doesn't end with the marker).
 33FRAGMENT_MARKER = b'\xff\xffTOOBIG\xff\xff'
 34
 35
 36################################################################################
 37class UDPReader(Reader):
 38    """Read UDP packets from network."""
 39    ############################
 40    def __init__(self, interface=None, port=None, mc_group=None,
 41                 reuseaddr=False, reuseport=False, eol=None,
 42                 allow_empty=False, this_is_a_test=False, **kwargs):
 43        """
 44        ```
 45        interface    IP (or resolvable name) of interface to listen on.  None or ''
 46                     will listen on INADDR_ANY (all interfaces). This IP should
 47                     not be on the loopback network (OK for testing, but won't work
 48                     in the real world).
 49
 50        port         Port to listen to for packets.  REQUIRED
 51
 52        mc_group     If specified, IP address of multicast group id to subscribe to.
 53
 54        reuseaddr    Specifies wether we set SO_REUSEADDR on the created socket.  If
 55                     you don't know you need this, don't enable it.
 56
 57        reuseport    Specifies wether we set SO_REUSEPORT on the created socket.  If
 58                     you don't know you need this, don't enable it.
 59
 60        eol          split the record by the eol character if present.
 61
 62        allow_empty - If True, preserve and return empty records
 63
 64        this_is_a_test - If True, recognize that this is being called in a unittest, so
 65                don't output warnings about not using loopback addresses.
 66        ```
 67        """
 68        super().__init__(**kwargs)
 69
 70        # resolve interface once in constructor
 71        if interface:
 72            interface = socket.inet_aton(socket.gethostbyname(interface))
 73        else:
 74            interface = socket.inet_aton('0.0.0.0')
 75        self.interface = interface
 76
 77        # make sure user passed in `port`
 78        #
 79        # NOTE: We want the order of the arguments to consistently be (ip,
 80        #       port, ...) across all the network readers/writers... but we
 81        #       want `interface` to be optional.  All kwargs need to come after
 82        #       all regular args, so we've assigned a default value of None to
 83        #       `port`.  But don't be confused, it is REQUIRED.
 84        #
 85        if not port:
 86            raise TypeError('must specify `port`')
 87        # make sure port gets stored as an int, even if passed in as a string
 88        self.port = int(port)
 89
 90        # resolve mc_group once in constructor
 91        if mc_group:
 92            mc_group = socket.inet_aton(socket.gethostbyname(mc_group))
 93        self.mc_group = mc_group
 94
 95        self.reuseaddr = reuseaddr
 96        self.reuseport = reuseport
 97
 98        self.eol = eol
 99        self.allow_empty = allow_empty
100
101        self.this_is_a_test = this_is_a_test
102
103        # socket gets initialized on-demand in read()
104        self.socket = None
105
106    ############################
107    def __del__(self):
108        try:
109            if self.socket:
110                self.socket.close()
111        except AttributeError:
112            pass
113
114    ############################
115    def _open_socket(self):
116        """Do socket prep so we're ready to read().  Returns socket object or None on
117        failure.
118        """
119        sock = socket.socket(family=socket.AF_INET,
120                             type=socket.SOCK_DGRAM,
121                             proto=socket.IPPROTO_UDP)
122        if self.reuseaddr:
123            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
124        if self.reuseport:
125            try:  # Raspbian doesn't recognize SO_REUSEPORT
126                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
127            except AttributeError:
128                logging.warning('Unable to set socket REUSEPORT; may be unsupported.')
129
130        # If mc_group is specified, subscribe to it as a multicast group
131        if self.mc_group:
132            # set outgoing multicast interface
133            #
134            # NOTE: Can't use loopback device for this, otherwise IGMP packets
135            #       never leave the system, and you never actually join the
136            #       group.
137            #
138            if socket.inet_ntoa(self.interface).startswith('127.') and not self.this_is_a_test:
139                logging.warning("Can't use loopback device for joining multicast groups.  Make "
140                                "sure your system's hostname does NOT resolve to something in "
141                                "the 127.0.0.0/8 address block (e.g., localhost, 127.0.0.1), or "
142                                "specify the interface to use by passing its IP address as the "
143                                "`interface` parameter.  (You can ignore this message if you're "
144                                "actually just doing loopback testing.)")
145
146            # join the group via IGMP
147            #
148            # NOTE: Since these are both already encoded as binary by
149            #       inet_aton(), we can just concatenate them.  Alternatively,
150            #       could use struct.pack("4s4s", ...) to create a struct to
151            #       pass into setsockopt()
152            #
153            sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
154                            self.mc_group + self.interface)
155
156            # multicast, bind to mc_group
157            sock.bind((socket.inet_ntoa(self.mc_group), self.port))
158
159        else:
160            # broadcast or unicast, bind to specificed interface
161            sock.bind((socket.inet_ntoa(self.interface), self.port))
162
163        return sock
164
165    ############################
166    def read(self):
167        """
168        Read the next UDP packet.
169        """
170        # If socket isn't ready, set it up.  If something fails, return w/out reading.
171        if not self.socket:
172            self.socket = self._open_socket()
173        if not self.socket:
174            logging.error('UDPReader.read: unable to open UDP socket')
175            return
176
177        # Read datagrams until we get one that doesn't end with a FRAGMENT_MARKER
178        record_buffer = b''
179        while True:
180            try:
181                record = self.socket.recv(READ_BUFFER_SIZE)
182            except OSError as e:
183                logging.error('UDPReader error: %s', str(e))
184                return None
185            logging.debug('UDPReader.read: received %d bytes', len(record))
186
187            if record.endswith(FRAGMENT_MARKER):
188                # UDPWriter fragmented this record because it was too large to
189                # send as a single datagram
190                logging.info('UDPReader.read: detected fragmented packet')
191                record_buffer += record.rsplit(FRAGMENT_MARKER, maxsplit=1)[0]
192                logging.debug('record_buffer: %s', record_buffer)
193            else:
194                record_buffer += record
195                break
196
197        # we've got a whole record in our record_buffer, decode it
198
199        # if eol == None, return the record as is
200        if not self.eol:
201            return self._decode_bytes(record_buffer, self.allow_empty)
202
203        # otherwise split the record by the eol
204        decoded_records = self._decode_bytes(record_buffer,
205                                             self.allow_empty).rstrip(self.eol).split(self.eol)
206
207        # if there was only one record, return just the first element in the
208        # list, otherwise return the whole list.
209        return decoded_records[0] if len(decoded_records) == 1 else decoded_records
READ_BUFFER_SIZE = 65535
FRAGMENT_MARKER = b'\xff\xffTOOBIG\xff\xff'
class UDPReader(logger.readers.reader.Reader):
 38class UDPReader(Reader):
 39    """Read UDP packets from network."""
 40    ############################
 41    def __init__(self, interface=None, port=None, mc_group=None,
 42                 reuseaddr=False, reuseport=False, eol=None,
 43                 allow_empty=False, this_is_a_test=False, **kwargs):
 44        """
 45        ```
 46        interface    IP (or resolvable name) of interface to listen on.  None or ''
 47                     will listen on INADDR_ANY (all interfaces). This IP should
 48                     not be on the loopback network (OK for testing, but won't work
 49                     in the real world).
 50
 51        port         Port to listen to for packets.  REQUIRED
 52
 53        mc_group     If specified, IP address of multicast group id to subscribe to.
 54
 55        reuseaddr    Specifies wether we set SO_REUSEADDR on the created socket.  If
 56                     you don't know you need this, don't enable it.
 57
 58        reuseport    Specifies wether we set SO_REUSEPORT on the created socket.  If
 59                     you don't know you need this, don't enable it.
 60
 61        eol          split the record by the eol character if present.
 62
 63        allow_empty - If True, preserve and return empty records
 64
 65        this_is_a_test - If True, recognize that this is being called in a unittest, so
 66                don't output warnings about not using loopback addresses.
 67        ```
 68        """
 69        super().__init__(**kwargs)
 70
 71        # resolve interface once in constructor
 72        if interface:
 73            interface = socket.inet_aton(socket.gethostbyname(interface))
 74        else:
 75            interface = socket.inet_aton('0.0.0.0')
 76        self.interface = interface
 77
 78        # make sure user passed in `port`
 79        #
 80        # NOTE: We want the order of the arguments to consistently be (ip,
 81        #       port, ...) across all the network readers/writers... but we
 82        #       want `interface` to be optional.  All kwargs need to come after
 83        #       all regular args, so we've assigned a default value of None to
 84        #       `port`.  But don't be confused, it is REQUIRED.
 85        #
 86        if not port:
 87            raise TypeError('must specify `port`')
 88        # make sure port gets stored as an int, even if passed in as a string
 89        self.port = int(port)
 90
 91        # resolve mc_group once in constructor
 92        if mc_group:
 93            mc_group = socket.inet_aton(socket.gethostbyname(mc_group))
 94        self.mc_group = mc_group
 95
 96        self.reuseaddr = reuseaddr
 97        self.reuseport = reuseport
 98
 99        self.eol = eol
100        self.allow_empty = allow_empty
101
102        self.this_is_a_test = this_is_a_test
103
104        # socket gets initialized on-demand in read()
105        self.socket = None
106
107    ############################
108    def __del__(self):
109        try:
110            if self.socket:
111                self.socket.close()
112        except AttributeError:
113            pass
114
115    ############################
116    def _open_socket(self):
117        """Do socket prep so we're ready to read().  Returns socket object or None on
118        failure.
119        """
120        sock = socket.socket(family=socket.AF_INET,
121                             type=socket.SOCK_DGRAM,
122                             proto=socket.IPPROTO_UDP)
123        if self.reuseaddr:
124            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
125        if self.reuseport:
126            try:  # Raspbian doesn't recognize SO_REUSEPORT
127                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
128            except AttributeError:
129                logging.warning('Unable to set socket REUSEPORT; may be unsupported.')
130
131        # If mc_group is specified, subscribe to it as a multicast group
132        if self.mc_group:
133            # set outgoing multicast interface
134            #
135            # NOTE: Can't use loopback device for this, otherwise IGMP packets
136            #       never leave the system, and you never actually join the
137            #       group.
138            #
139            if socket.inet_ntoa(self.interface).startswith('127.') and not self.this_is_a_test:
140                logging.warning("Can't use loopback device for joining multicast groups.  Make "
141                                "sure your system's hostname does NOT resolve to something in "
142                                "the 127.0.0.0/8 address block (e.g., localhost, 127.0.0.1), or "
143                                "specify the interface to use by passing its IP address as the "
144                                "`interface` parameter.  (You can ignore this message if you're "
145                                "actually just doing loopback testing.)")
146
147            # join the group via IGMP
148            #
149            # NOTE: Since these are both already encoded as binary by
150            #       inet_aton(), we can just concatenate them.  Alternatively,
151            #       could use struct.pack("4s4s", ...) to create a struct to
152            #       pass into setsockopt()
153            #
154            sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
155                            self.mc_group + self.interface)
156
157            # multicast, bind to mc_group
158            sock.bind((socket.inet_ntoa(self.mc_group), self.port))
159
160        else:
161            # broadcast or unicast, bind to specificed interface
162            sock.bind((socket.inet_ntoa(self.interface), self.port))
163
164        return sock
165
166    ############################
167    def read(self):
168        """
169        Read the next UDP packet.
170        """
171        # If socket isn't ready, set it up.  If something fails, return w/out reading.
172        if not self.socket:
173            self.socket = self._open_socket()
174        if not self.socket:
175            logging.error('UDPReader.read: unable to open UDP socket')
176            return
177
178        # Read datagrams until we get one that doesn't end with a FRAGMENT_MARKER
179        record_buffer = b''
180        while True:
181            try:
182                record = self.socket.recv(READ_BUFFER_SIZE)
183            except OSError as e:
184                logging.error('UDPReader error: %s', str(e))
185                return None
186            logging.debug('UDPReader.read: received %d bytes', len(record))
187
188            if record.endswith(FRAGMENT_MARKER):
189                # UDPWriter fragmented this record because it was too large to
190                # send as a single datagram
191                logging.info('UDPReader.read: detected fragmented packet')
192                record_buffer += record.rsplit(FRAGMENT_MARKER, maxsplit=1)[0]
193                logging.debug('record_buffer: %s', record_buffer)
194            else:
195                record_buffer += record
196                break
197
198        # we've got a whole record in our record_buffer, decode it
199
200        # if eol == None, return the record as is
201        if not self.eol:
202            return self._decode_bytes(record_buffer, self.allow_empty)
203
204        # otherwise split the record by the eol
205        decoded_records = self._decode_bytes(record_buffer,
206                                             self.allow_empty).rstrip(self.eol).split(self.eol)
207
208        # if there was only one record, return just the first element in the
209        # list, otherwise return the whole list.
210        return decoded_records[0] if len(decoded_records) == 1 else decoded_records

Read UDP packets from network.

UDPReader( interface=None, port=None, mc_group=None, reuseaddr=False, reuseport=False, eol=None, allow_empty=False, this_is_a_test=False, **kwargs)
 41    def __init__(self, interface=None, port=None, mc_group=None,
 42                 reuseaddr=False, reuseport=False, eol=None,
 43                 allow_empty=False, this_is_a_test=False, **kwargs):
 44        """
 45        ```
 46        interface    IP (or resolvable name) of interface to listen on.  None or ''
 47                     will listen on INADDR_ANY (all interfaces). This IP should
 48                     not be on the loopback network (OK for testing, but won't work
 49                     in the real world).
 50
 51        port         Port to listen to for packets.  REQUIRED
 52
 53        mc_group     If specified, IP address of multicast group id to subscribe to.
 54
 55        reuseaddr    Specifies wether we set SO_REUSEADDR on the created socket.  If
 56                     you don't know you need this, don't enable it.
 57
 58        reuseport    Specifies wether we set SO_REUSEPORT on the created socket.  If
 59                     you don't know you need this, don't enable it.
 60
 61        eol          split the record by the eol character if present.
 62
 63        allow_empty - If True, preserve and return empty records
 64
 65        this_is_a_test - If True, recognize that this is being called in a unittest, so
 66                don't output warnings about not using loopback addresses.
 67        ```
 68        """
 69        super().__init__(**kwargs)
 70
 71        # resolve interface once in constructor
 72        if interface:
 73            interface = socket.inet_aton(socket.gethostbyname(interface))
 74        else:
 75            interface = socket.inet_aton('0.0.0.0')
 76        self.interface = interface
 77
 78        # make sure user passed in `port`
 79        #
 80        # NOTE: We want the order of the arguments to consistently be (ip,
 81        #       port, ...) across all the network readers/writers... but we
 82        #       want `interface` to be optional.  All kwargs need to come after
 83        #       all regular args, so we've assigned a default value of None to
 84        #       `port`.  But don't be confused, it is REQUIRED.
 85        #
 86        if not port:
 87            raise TypeError('must specify `port`')
 88        # make sure port gets stored as an int, even if passed in as a string
 89        self.port = int(port)
 90
 91        # resolve mc_group once in constructor
 92        if mc_group:
 93            mc_group = socket.inet_aton(socket.gethostbyname(mc_group))
 94        self.mc_group = mc_group
 95
 96        self.reuseaddr = reuseaddr
 97        self.reuseport = reuseport
 98
 99        self.eol = eol
100        self.allow_empty = allow_empty
101
102        self.this_is_a_test = this_is_a_test
103
104        # socket gets initialized on-demand in read()
105        self.socket = None
interface    IP (or resolvable name) of interface to listen on.  None or ''
             will listen on INADDR_ANY (all interfaces). This IP should
             not be on the loopback network (OK for testing, but won't work
             in the real world).

port         Port to listen to for packets.  REQUIRED

mc_group     If specified, IP address of multicast group id to subscribe to.

reuseaddr    Specifies wether we set SO_REUSEADDR on the created socket.  If
             you don't know you need this, don't enable it.

reuseport    Specifies wether we set SO_REUSEPORT on the created socket.  If
             you don't know you need this, don't enable it.

eol          split the record by the eol character if present.

allow_empty - If True, preserve and return empty records

this_is_a_test - If True, recognize that this is being called in a unittest, so
        don't output warnings about not using loopback addresses.
interface
port
mc_group
reuseaddr
reuseport
eol
allow_empty
this_is_a_test
socket
def read(self):
167    def read(self):
168        """
169        Read the next UDP packet.
170        """
171        # If socket isn't ready, set it up.  If something fails, return w/out reading.
172        if not self.socket:
173            self.socket = self._open_socket()
174        if not self.socket:
175            logging.error('UDPReader.read: unable to open UDP socket')
176            return
177
178        # Read datagrams until we get one that doesn't end with a FRAGMENT_MARKER
179        record_buffer = b''
180        while True:
181            try:
182                record = self.socket.recv(READ_BUFFER_SIZE)
183            except OSError as e:
184                logging.error('UDPReader error: %s', str(e))
185                return None
186            logging.debug('UDPReader.read: received %d bytes', len(record))
187
188            if record.endswith(FRAGMENT_MARKER):
189                # UDPWriter fragmented this record because it was too large to
190                # send as a single datagram
191                logging.info('UDPReader.read: detected fragmented packet')
192                record_buffer += record.rsplit(FRAGMENT_MARKER, maxsplit=1)[0]
193                logging.debug('record_buffer: %s', record_buffer)
194            else:
195                record_buffer += record
196                break
197
198        # we've got a whole record in our record_buffer, decode it
199
200        # if eol == None, return the record as is
201        if not self.eol:
202            return self._decode_bytes(record_buffer, self.allow_empty)
203
204        # otherwise split the record by the eol
205        decoded_records = self._decode_bytes(record_buffer,
206                                             self.allow_empty).rstrip(self.eol).split(self.eol)
207
208        # if there was only one record, return just the first element in the
209        # list, otherwise return the whole list.
210        return decoded_records[0] if len(decoded_records) == 1 else decoded_records

Read the next UDP packet.