\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#287: Add a Commands for Determining Size of Buffered Data}
\date{October 26, 2006}
\author{Michael A. Cleverly}
\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 \#287}&\textbf{Add a Commands for Determining Size of Buffered Data}\\\hline
Author&

Michael A. Cleverly \tipmail{michael}{cleverly.com}
\\
Created&Thursday, \(\text{26}^{\text{th}}\) October 2006\\
Type&Project\\
Tcl Version&\(8.5\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.12 $\\
Keywords&Tcl, channel, chan, pendinginput, pendingoutput\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

Many network servers programmed in Tcl (including the venerable tclhttpd) are vulnerable to DoS (denial of service) attacks because they lack any way to introspect the amount of buffered data on a non-blocking socket that is in line buffering mode. This TIP proposes a new subcommand to \textbf{chan} to allow the amount of buffered input and buffered output (for symmetry) to be inspected from Tcl.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

Many network protocols are inherently line-oriented (HTTP, SMTP, etc.) and the natural approach to implementing servers for these protocols in Tcl is to configure the incoming client sockets to use non-blocking I/O and to have \textit{line} buffering and then define a readable fileevent callback.
\begingroup\small\begin{verbatim}
    proc accept {sock addr port} {
        fconfigure $sock -buffering line -blocking 0
        fileevent $sock readable [list callback $sock ...]
    }
    socket -server accept $listenPort
\end{verbatim}
\endgroup

Recall that a readable fileevent will be called even when there is an incomplete line buffered. As the \textbf{fileevent} manual page states:

\begin{quote}
A channel is considered to be readable if there is unread data available on the underlying device. A channel is also considered to be readable if there is unread data in an input buffer, except in the special case where the most recent attempt to read from the channel was a gets call that could not find a complete line in the input buffer.
\end{quote}

The \textbf{fblocked} (and in 8.5 \textbf{chan blocked}) command provides the Tcl programmer a means to test whether:

\begin{quote}
the most recent input operation ... returned less information than requested because all available input was exhausted.
\end{quote}

There is currently no way at the Tcl level to see how much data is buffered and could be read safely (via \textbf{read} instead of \textbf{gets}).

There is also no way to specify any kind of upper limit on the length of a line; when in line-buffering mode all input is buffered until an end-of-line sequence is encountered or the EOF on the channel is reached.

The practical result is that all network daemons written in Tcl using line-oriented I/O (\textbf{gets}) can be fed repeated input lacking an end-of-line sequence until all physical memory is exhausted.

This vulnerability has been recognized since at least 2001. See, for example, the discussion between George Peter Staplin and Donald Porter on the \textit{gets} page on the Tcl'ers Wiki [\url{http://wiki.tcl.tk/gets}].

\section{Proposed Change}

At the C level Tcl already has a function, \textit{Tcl\_InputBuffered} which returns the number of unread bytes buffered for a channel and a corresponding \textit{Tcl\_OutputBuffered} which returns the number of bytes buffered for output that have not yet been flushed out.

This TIP proposes to implement a new \textit{chan pending} command which will take two arguments: a \textit{mode} and a \textit{channelId}. The mode argument can be either \textit{input} or \textit{output}.

When the mode is \textit{input} the command returns the value of \textit{Tcl\_InputBuffered()} (if the channel was open for input or -1 otherwise).

When the mode is \textit{output} the command returns the value of \textit{Tcl\_OutputBuffered()} (if the channel was output for output or -1 otherwise).

This allows a programmer developing network daemons at the Tcl level to implement their own policy decisions based on the size of the unread line. Potential DoS situations could be avoided (in an application specific manner) long before all memory was exhausted.
\begingroup\small\begin{verbatim}
 if {[chan blocked $sock] && [chan pending input $sock] > $limit} {
     # Take application specific steps (i.e., [close $sock] or
     # [read $sock] to process a partial line and drain the buffer, etc.)
 }
\end{verbatim}
\endgroup

\section{Rejected Alternatives}
\begin{itemize}
\item{}
Adding a flag to \textbf{fblocked} to return the number of unread bytes instead of just 0 or 1 (since \textbf{fblocked} is now considered deprecated as per \cite{tip208}).
\item{}
Polluting the global namespace with a new \textbf{favailable}, \textbf{fpending} or \textbf{fqueued} command.
\item{}
A \textbf{chan unread} because of potential confusion as to whether it performed \textit{ungetch()} type functionality (\textit{un-reed} vs \textit{un-red}).
\item{}
Any sort of \textbf{-maxchars} or \textbf{-maxbytes} flag to \textbf{gets} in order to not complicate the semantics of \textbf{gets}. Additionally without even further complicating \textbf{gets} semantics one could not distinguish input of exactly \$limit characters from the case where only \$limit characters were returned (with some input remaining unread).
\item{}
The initial version of this TIP called for a \textit{chan available} command. This was changed to \textit{pendinginput} (and \textit{pendingoutput} added for symmetry's sake) following suggestions on \url{news:comp.lang.tcl} from Donald Arseneau and Donal Fellows, and later to \textit{chan pending} that takes a \textit{mode} argument (\textit{input} or \textit{output}) based on suggestions from Donald Porter and Joe English.
\end{itemize}

\section{Reference Implementation}

[RFE 1586860] at SourceForge now contains a patch implementing \textbf{chan pendinginput} and \textbf{chan pendingoutput} (including updated \textbf{chan} man page and corresponding test cases) [\url{http://sourceforge.net/tracker/index.php?func=detail&aid=1586860&group_id=10894&atid=360894}].

\section{Copyright}

This document is in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#1}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#208]{tip208}
Jeff Hobbs,
\emph{Add a 'chan' Command},
on-line at \url{http://purl.org/tcl/tip/208.html}
\end{thebibliography}
\end{document}
