\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#409: UDP in Tcl}
\date{August 17, 2012}
\author{Alexandre Ferrieux, Colin McCormack}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#409}&\textbf{UDP in Tcl}\\\hline
Author&

Alexandre Ferrieux \tipmail{alexandre.ferrieux}{gmail.com}
\par
Colin McCormack \tipmail{colin}{chinix.com}
\\
Created&Friday, \(\text{17}^{\text{th}}\) August 2012\\
Type&Project\\
Tcl Version&\(8.7\)\\
State&Draft\\
Vote&Pending\\
Version&\tipversion$Revision: 1.19 $\\
Keywords&udp, datagram, message\\
Obsoletes&391\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP adds support for UDP in Tcl, with a pure event approach to packet reception (as opposed to hijacking the existing channel infrastructure).
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

UDP support is a long-awaited feature in Tcl. Some extensions have traditionally supported it through the channel abstraction. This is of course doable, but there is a non-negligible cost in both complexity and performance due to the impedance mismatch between the ``fluid'' model behind channels and the ``granular'' world of datagrams (where boundaries are significant). Another discrepancy is the existence of (per-packet) metadata, like the source address and port of an incoming UDP packet, which do not fit nicely in the (per-connection) options of the channel API (via \textbf{fconfigure}).

Once this mismatch is acknowledged, it is easy to identify a better home for UDP in Tcl: let it be a direct event source (for the receive side), just like Tk or Snack.

Indeed, hooking a callback for packet reception is a natural fit with Tcl's event-driven tradition, while preserving packet boundaries and easily exposing per-packet metadata.

Sending is trivially handled by a direct per-packet call (but not disguised as a \textbf{puts}). Again, this naturally allows for boundary preservation and metadata specification.

This TIP asks for UDP-in-the core for two strong reasons:

 --- it enables another important core feature: asynchronous (event-driven) DNS lookups

 --- the C runtime supports it without extra libraries (unlike USB or Bluetooth)

We then believe that the ubiquity of the need and the lack of external dependencies justify for UDP the first-class status that TCP enjoys (regardless of the channel vs event models). Note that an acceptable compromise would be a bundled extension, ie distributed-with-the-core (in ``pkgs/'').

\section{Specification}

The new \textbf{udp} ensemble hosts three subcommands: \textbf{new}, \textbf{create}, and \textbf{names}

\begin{quote}
\textbf{udp new} ?\textit{options}?
\end{quote}

\begin{quote}
\textbf{udp create} \textit{name} ?\textit{options}?
\end{quote}

both create an UDP endpoint ;

\begin{quote}
\textbf{udp names}
\end{quote}

returns the list of existing such endpoints.

\subsection{Lifecycle}

Following the traditions of Tk and Snack, \textbf{udp new} and \textbf{udp create} return a Tcl command, which takes subcommands implementing the needed verbs. By analogy with the corresponding TclOO constructors,
\begin{itemize}
\item{}
\textbf{new} generates the command name internally, in the \textbf{::tcl::udp} namespace
\item{}
\textbf{create} takes an extra \textit{name} argument providing the target command name, either fully qualified, or relative to the current namespace.
\end{itemize}

 An UDP endpoint is thus created by:
\begingroup\small\begin{verbatim}
   set u [udp new ...]
\end{verbatim}
\endgroup

or
\begingroup\small\begin{verbatim}
   udp create foo ...
\end{verbatim}
\endgroup

 Once created, its configuration can be tweaked by:

\begin{quote}
\$u \textbf{configure} \textit{-option} \textit{value}
\end{quote}

and retrieved with

\begin{quote}
set value [\$u \textbf{configure} -\textit{option}]
\end{quote}

or 

\begin{quote}
set fullconf [\$u \textbf{configure}]
\end{quote}

To destroy the endpoint, use:

\begin{quote}
\$u \textbf{destroy}
\end{quote}

or, as in Tk, destroy the command:

\begin{quote}
\textbf{rename} \$u \{\}
\end{quote}

or the whole namespace.

\subsection{Status of options}

Among options, a few may only be specified on creation:

\begin{quote}
- local interface+port
\end{quote}

\begin{quote}
- (optional) connect() target's address+port
\end{quote}

\begin{quote}
- reuse flag (described in Advanced Features)
\end{quote}

while all the other options may be specified \textit{both} on creation or through [\$u configure].

\subsection{Addresses and Ports}

The first two creation-only options have the following syntax:

\begin{quote}
set u [\textbf{udp new} ?\textbf{-local} \textit{address\_port}? ]
\end{quote}

\begin{quote}
set u [\textbf{udp new} ?\textbf{-remote} \textit{address\_port}? ]
\end{quote}

where \textit{address\_port} pairs are represented as 2-element Tcl lists.

\begin{quote}
set address\_port [list \$address \$port]
\end{quote}

Addresses can be given either as numeric IP (v4 or v6) addresses, or as hostnames; in the latter case, a synchronous DNS resolution is performed before actual use, just like for \textbf{socket}.

In the case of \textbf{-local}, \$address can be specified as ``*'', meaning INADDR\_ANY, and \$port can be 0, asking for the OS to select a free port. Thus a dynamic port on all interfaces can be requested with
\begingroup\small\begin{verbatim}
   set u [udp new -local [list * 0]]
\end{verbatim}
\endgroup

In case of port 0, after creation of the endpoint, the actual port chosen by the OS can be retrieved with [\$u configure]:
\begingroup\small\begin{verbatim}
   puts "Local port is: [lindex [$u configure -local] 1]"
\end{verbatim}
\endgroup

In the case of \textbf{-remote}, both address and port must be fully specified. The semantics, as is well known, is to tell the kernel (a) to forbid sending to any other destination, and (b) to discard all incoming packets sent by another source.

\subsection{Sending a Message}

Sending is done, unsurprisingly, with the \textbf{send} verb:

\begin{quote}
\$u \textbf{send} \textit{payload} ?\textit{dest\_addr\_port}?
\end{quote}

where \textit{dest\_addr\_port} is a pair as above.

Its blocking semantics is that of the underlying send()/sendto() system calls: it typically returns immediately, though the hardware may buffer the data for some time, and delivery is not guaranteed. The \textit{payload} is interpreted as a byte array that holds the entire content of the UDP message to send.

The destination parameter can be omitted if the endpoint has been created with the \textbf{-remote} option (connected mode).

\subsection{Receiving a message asynchronously}

Asynchronous (i.e. event-driven) message reception is done by specifying a listener callback to \textbf{new/create} or \textbf{configure}:

\begin{quote}
\$u \textbf{configure -listener} \textit{command\_prefix}
\end{quote}

Subsequently, when an incoming packet hits Tcl in the event loop, the \textit{command\_prefix} is called with the endpoint identifier, payload and metadata:

\begin{quote}
\{*\}\textit{command\_prefix} \$u \textit{payload} \textit{metadata\_dict}
\end{quote}

where \textit{payload} is the byte array of the UDP payload and \textit{metadata\_dict} is a dict containing at least two options:

\begin{quote}
\textbf{-remote} \textit{address\_port}
\end{quote}

\begin{quote}
\textbf{-local} \textit{address\_port}
\end{quote}

When read from options or metadata, all address components apart from ``*'' are returned in numeric form; no reverse DNS is ever performed.

Note that \textit{-local} may carry more information than a configured \textit{-local} where the address part is ``*'', by identifying which of the system's several interfaces was targeted.

Also note that \textit{command\_prefix} is a single command, possibly with arguments, that will be expanded on invocation (hence it must be a proper list); it is *not* an arbitrary script as in Tk's \textit{'bind} tradition.

When \textit{command\_prefix} is the empty list (which is the default), the notifier gives up interest in the underlying UDP socket; this allows to keep the port bound while letting the OS buffer any incoming packets (up to a configurable limit) without any script-level handling, while leaving the event loop active. This is similar to setting a \textbf{fileevent} on a channel to the empty string.

\subsection{Receiving a message synchronously}

Synchronous message reception is done with the \textbf{recv} verb:

\begin{quote}
set payload [\$u \textbf{recv} \textit{metadata\_dict\_var}]
\end{quote}

The payload is returned as a byte array, and the variable passed as argument receives the metadata dict just described.

\subsection{Advanced features}

The following few verbs and options control extra IP features that are typically useful in popular UDP applications like media streaming:

\begin{quote}
\$u \textbf{configure -sendbuffer} \textit{buffersize}
\end{quote}

\begin{quote}
\$u \textbf{configure -receivebuffer} \textit{buffersize}
\end{quote}

Set the OS's send (resp. receive) buffer sizes to the given values (in bytes).

\begin{quote}
\$u \textbf{join} \textit{multiaddr} ?\textbf{-source} \textit{sourceaddr}?
\end{quote}

Joins the multicast group \textit{multiaddr}, optionally using IGMPv3's source membership target \textit{sourceaddr}.

\begin{quote}
\$u \textbf{leave} \textit{multiaddr} ?\textbf{-source} \textit{sourceaddr}?
\end{quote}

Leaves the same multicast group with or without source membership.

\begin{quote}
set u [\textbf{udp new -reuse 1}]
\end{quote}

Sets the SO\_REUSEADDR socket option, so that multiple processes may bind to the same local port and interface, and receive the same packets. Creation-time only.

\begin{quote}
\$u \textbf{configure -ttl} \textit{ttl}
\end{quote}

Sets the TTL of subsequent outgoing packets. Some operating systems typically reduce the default TTL to one for multicast packets; this override may thus come in handy.

\section{Rejected Alternatives}
\begin{itemize}
\item{}
Token-based API (like for channels) instead of commands: would need extra machinery (a new Tcl\_ObjType). Moreover, the command style gives reflection for free: a simple proc can emulate an UDP endpoint, and is compatible with all OO schemes.
\item{}
Address+Port pairs as dicts or urls: would hamper performance for no added value
\item{}
Listener as specific subcommand instead of option: R/W semantics is actually that of an option; a subcommand would preclude the direct specification of the listener on creation ; analogy with the -command of \textbf{fcopy}, \textbf{http}, or Tk widgets. 
\end{itemize}

\section{Sources of Inspiration}

This TIP builds on experience with previous attempts at UDP extensions: TclUDP, ceptcl, Duft, along with intensive practice with unpublished work, and borrows ideas from all of them.

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\end{document}
