% This LaTeX document was generated using the LaTeX backend of PlDoc,
% The SWI-Prolog documentation system



\section{library(udp_broadcast): A UDP broadcast proxy}

\label{sec:udpbroadcast}

\begin{tags}
    \tag{author}
Jeffrey Rosenwald (JeffRose@acm.org), Jan Wielemaker
    \tag{See also}
\file{tipc.pl}
    \tag{license}
BSD-2
\end{tags}

SWI-Prolog's broadcast library provides a means that may be used to
facilitate publish and subscribe communication regimes between anonymous
members of a community of interest. The members of the community are
however, necessarily limited to a single instance of Prolog. The UDP
broadcast library removes that restriction. With this library loaded,
any member on your local IP subnetwork that also has this library loaded
may hear and respond to your broadcasts.

This library support three styles of networking as described below. Each
of these networks have their own advantages and disadvantages. Please
study the literature to understand the consequences.

\begin{description}
    \item[broadcast] 
Broadcast messages are sent to the LAN subnet. The broadcast
implementation uses two UDP ports: a public to address the whole
group and a private one to address a specific node. Broadcasting
is generally a good choice if the subnet is small and traffic is
low.
    \item[unicast] 
Unicast sends copies of packages to known peers. Unicast networks
can easily be routed. The unicast version uses a single UDP port
per node. Unicast is generally a good choice for a small party,
in particular if the peers are in different networks.
    \item[multicast] 
Multicast is like broadcast, but it can be configured to
work accross networks and may work more efficiently on VLAN networks.
Like the broadcast setup, two UDP ports are used. Multicasting can
in general deliver the most efficient LAN and WAN networks, but
requires properly configured routing between the peers.
\end{description}

After initialization and, in the case of a \textit{unicast} network managing
the set of peers, communication happens through \predref{broadcast}{1},
\predref{broadcast_request}{1} and \predref{listen}{1},2,3.

A \predref{broadcast}{1} or \predref{broadcast_request}{1} of the shape \verb$udp(Scope, Term)$ or
\verb$udp(Scope, Term, TimeOut)$ is forwarded over the UDP network to all peers
that joined the same \arg{Scope}. To prevent the potential for feedback
loops, only the plain \arg{Term} is broadcasted locally. The timeout is
optional. It specifies the amount to time to wait for replies to arrive
in response to a \predref{broadcast_request}{1}. The default period is 0.250
seconds. The timeout is ignored for broadcasts.

An example of three separate processes cooperating in the same \textit{scope}
called \const{peers}:

\begin{code}
Process A:

   ?- listen(number(X), between(1, 5, X)).
   true.

   ?-

Process B:

   ?- listen(number(X), between(7, 9, X)).
   true.

   ?-

Process C:

   ?- findall(X, broadcast_request(udp(peers, number(X))), Xs).
   Xs = [1, 2, 3, 4, 5, 7, 8, 9].

   ?-
\end{code}

It is also possible to carry on a private dialog with a single
responder. To do this, you supply a compound of the form, Term:PortId,
to a UDP scoped \predref{broadcast}{1} or \predref{broadcast_request}{1}, where PortId is the
ip-address and port-id of the intended listener. If you supply an
unbound variable, PortId, to broadcast_request, it will be unified with
the address of the listener that responds to Term. You may send a
directed broadcast to a specific member by simply providing this address
in a similarly structured compound to a UDP scoped \predref{broadcast}{1}. The
message is sent via unicast to that member only by way of the member's
broadcast listener. It is received by the listener just as any other
broadcast would be. The listener does not know the difference.

For example, in order to discover who responded with a particular value:

\begin{code}
Host B Process 1:

   ?- listen(number(X), between(1, 5, X)).
   true.

   ?-

Host A Process 1:


   ?- listen(number(X), between(7, 9, X)).
   true.

   ?-

Host A Process 2:

   ?- listen(number(X), between(1, 5, X)).
   true.

   ?- bagof(X, broadcast_request(udp(peers,number(X):From,1)), Xs).
   From = ip(192, 168, 1, 103):34855,
   Xs = [7, 8, 9] ;
   From = ip(192, 168, 1, 103):56331,
   Xs = [1, 2, 3, 4, 5] ;
   From = ip(192, 168, 1, 104):3217,
   Xs = [1, 2, 3, 4, 5].
\end{code}

All incomming trafic is handled by a single thread with the alias
\verb$udp_inbound_proxy$. This thread also performs the internal dispatching
using \predref{broadcast}{1} and \predref{broadcast_request}{1}. Future versions may provide
for handling these requests in seperate threads.

\subsection{Caveats}

\label{sec:udp-broadcase-caveats}

While the implementation is mostly transparent, there are some important
and subtle differences that must be taken into consideration:

\begin{itemize}
    \item UDP broadcast requires an initialization step in order to
launch the broadcast listener proxy. See
\predref{udp_broadcast_initialize}{2}.
    \item Prolog's \predref{broadcast_request}{1} is nondet. It sends the request,
then evaluates the replies synchronously, backtracking as needed
until a satisfactory reply is received. The remaining potential
replies are not evaluated. With UDP, all peers will send all
answers to the query. The receiver may however stop listening.
    \item A UDP \predref{broadcast}{1} is completely asynchronous.
    \item A UDP \predref{broadcast_request}{1} is partially synchronous. A
\predref{broadcast_request}{1} is sent, then the sender balks for a period of
time (default: 250 ms) while the replies are collected. Any reply
that is received after this period is silently discarded. A
optional second argument is provided so that a sender may specify
more (or less) time for replies.
    \item Replies are presented to the user as a choice point on arrival,
until the broadcast request timer finally expires. This
allows traffic to propagate through the system faster and provides
the requestor with the opportunity to terminate a broadcast request
early if desired, by simply cutting choice points.
    \item Please beware that broadcast request transactions remain active
and resources consumed until broadcast_request finally fails on
backtracking, an uncaught exception occurs, or until choice points
are cut. Failure to properly manage this will likely result in
chronic exhaustion of UDP sockets.
    \item If a listener is connected to a generator that always succeeds
(e.g. a random number generator), then the broadcast request will
never terminate and trouble is bound to ensue.
    \item \predref{broadcast_request}{1} with \verb$udp_subnet$ scope is \textit{not} reentrant.
If a listener performs a \predref{broadcast_request}{1} with UDP scope
recursively, then disaster looms certain. This caveat does not apply
to a UDP scoped \predref{broadcast}{1}, which can safely be performed from a
listener context.
    \item UDP broadcast's capacity is not infinite. While it can tolerate
substantial bursts of activity, it is designed for short bursts of
small messages. Unlike TIPC, UDP is unreliable and has no QOS
protections. Congestion is likely to cause trouble in the form of
non-Byzantine failure. That is, late, lost (e.g. infinitely late),
or duplicate datagrams. Caveat emptor.
    \item A UDP \predref{broadcast_request}{1} term that is grounded is considered to
be a broadcast only. No replies are collected unless the there is at
least one unbound variable to unify.
    \item A UDP \predref{broadcast}{1} always succeeds, even if there are no
listeners.
    \item A UDP \predref{broadcast_request}{1} that receives no replies will fail.
    \item Replies may be coming from many different places in the network
(or none at all). No ordering of replies is implied.
    \item Prolog terms are sent to others after first converting them to
atoms using \predref{term_string}{3}. Serialization does not deal with cycles,
attributes or sharing. The hook \predref{udp_term_string_hook}{3} may be
defined to change the message serialization and support different
message formats and/or encryption.
    \item The broadcast model is based on anonymity and a presumption of
trust--a perfect recipe for compromise. UDP is an Internet protocol.
A UDP broadcast listener exposes a public port, which is
static and shared by all listeners, and a private port, which is
semi-static and unique to the listener instance. Both can be seen
from off-cluster nodes and networks. Usage of this module exposes
the node and consequently, the cluster to significant security
risks. So have a care when designing your application. You must talk
only to those who share and contribute to your concerns using a
carefully prescribed protocol.
    \item UDP broadcast categorically and silently ignores all message
traffic originating from or terminating on nodes that are not
members of the local subnet. This security measure only keeps honest
people honest!
\end{itemize}

\vspace{0.7cm}

\begin{description}
    \predicate{udp_broadcast_close}{1}{+Scope}
Close a UDP broadcast scope.

    \predicate[semidet]{udp_broadcast_initialize}{2}{+IPAddress, +Options}
Initialized UDP broadcast bridge. \arg{IPAddress} is the IP address on the
network we want to broadcast on. IP addresses are terms \verb$ip(A,B,C,D)$
or an atom or string of the format \verb$A.B.C.D$. \arg{Options} processed:

\begin{description}
    \termitem{scope}{+ScopeName}
Name of the scope. Default is \const{subnet}.
    \termitem{subnet_mask}{+SubNet}
Subnet to broadcast on. This uses the same syntax as \arg{IPAddress}.
Default classifies the network as class A, B or C depending on
the the first octet and applies the default mask.
    \termitem{port}{+Port}
Public port to use. Default is 20005.
    \termitem{method}{+Method}
\arg{Method} to send a message to multiple peers. One of

\begin{description}
    \termitem{broadcast}{}
Use UDP broadcast messages to the LAN. This is the
default
    \termitem{multicast}{}
Use UDP multicast messages. This can be used on WAN networks,
provided the intermediate routers understand multicast.
    \termitem{unicast}{}
Send the messages individually to all registered peers.
\end{description}
\end{description}

For compatibility reasons \arg{Options} may be the subnet mask.

    \predicate[det]{udp_peer_add}{2}{+Scope, +Address}
\nodescription
    \predicate[det]{udp_peer_del}{2}{+Scope, ?Address}
\nodescription
    \predicate[nondet]{udp_peer}{2}{?Scope, ?Address}
Manage and query the set of known peers for a unicast network.
\arg{Address} is either a term IP:Port or a plain IP address. In the
latter case the default port registered with the scope is used.

\begin{arguments}
\arg{Address} & has canonical form \verb$ip(A,B,C,D)$:Port. \\
\end{arguments}

    \predicate[det,multifile]{udp_term_string_hook}{3}{+Scope, +Term, -String}
\nodescription
    \predicate[semidet,multifile]{udp_term_string_hook}{3}{+Scope, -Term, +String}
Hook for serializing the message \arg{Term}. The default writes
\verb$%prolog\n$, followed by the Prolog term in quoted notation while
ignoring operators. This hook may use alternative serialization such
as \predref{fast_term_serialized}{2}, use \verb$library(ssl)$ to realise encrypted
messages, etc.

\begin{arguments}
\arg{Scope} & is the scope for which the message is broadcasted. This
can be used to use different serialization for different scopes. \\
\arg{Term} & encapsulates the term broadcasted by the application as
follows:

\begin{description}
    \termitem{send}{ApplTerm}
Is sent by \verb$broadcast(udp(Scope, ApplTerm))$
    \termitem{request}{Id, ApplTerm}
Is sent by \predref{broadcast_request}{1}, where \arg{Id} is a unique large
(64 bit) integer.
    \termitem{reply}{Id, ApplTerm}
Is sent to reply on a \predref{broadcast_request}{1} request that has
been received. Arguments are the same as above.
\end{description}

 \\
\end{arguments}

    \predicate[semidet,multifile]{udp_unicast_join_hook}{3}{+Scope, +From, +Data}
This multifile hook is called if an UDP package is received on the
port of the unicast network identified by \arg{Scope}. \arg{From} is the origin
IP and port and \arg{Data} is the message data that is deserialized as
defined for the scope (see \predref{udp_term_string}{3}).

This hook is intended to initiate a new node joining the network of
peers. We could in theory also omit the in-scope test and use a
normal broadcast to join. Using a different channal however provides
a basic level of security. A possibe implementation is below. The
first fragment is a hook added to the server, the second is a
predicate added to a client and the last initiates the request in
the client. The excanged term (\verb$join(X)$) can be used to exchange a
welcome handshake.

\begin{code}
:- multifile udp_broadcast:udp_unicast_join_hook/3.
udp_broadcast:udp_unicast_join_hook(Scope, From, join(welcome)) :-
    udp_peer_add(Scope, From),
\end{code}

\begin{code}
join_request(Scope, Address, Reply) :-
    udp_peer_add(Scope, Address),
    broadcast_request(udp(Scope, join(X))).
\end{code}

\begin{code}
?- join_request(myscope, "1.2.3.4":10001, Reply).
Reply = welcome.
\end{code}

\end{description}

