\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#143: An Interpreter Resource Limiting Framework}
\date{July 25, 2003}
\author{Donal K. Fellows}
\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 \#143}&\textbf{An Interpreter Resource Limiting Framework}\\\hline
Author&

Donal K. Fellows \tipmail{donal.k.fellows}{man.ac.uk}
\\
Created&Friday, \(\text{25}^{\text{th}}\) July 2003\\
Type&Project\\
Tcl Version&\(8.5\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.13 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP introduces a mechanism for creating and manipulating per-interpreter resource limits. This stops several significant classes of denial-of-service attack, and can also be used to do things like guaranteeing an answer within a particular amount of time.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

Currently it is trivial for scripts running in even safe Tcl interpreters to conduct a denial-of-service attack on the thread in which they are running. All they have to do is write a simple infinite loop with the \textbf{for} or \textbf{while} commands. Of course, it is possible to put a stop to this by hiding those commands from the interpreter, but even then it is possible to simulate the DoS effect with the help of a procedure like this (which even under ideal conditions will take over three days to run):
\begingroup\small\begin{verbatim}
proc x s {eval $s; eval $s; eval $s; eval $s}
x {x {x {x {x {x {x {x {x {x {x {x {x {x {sleep 1}}}}}}}}}}}}}}
\end{verbatim}
\endgroup

The easiest way around this, of course, is the resource quota as used by heavyweight operating systems, perhaps combined with the \textit{alarm(2)} system call. Or at least that would be the way to do it if it wasn't for the fact that those are ridiculously heavy sledgehammers to take to this particular nut. Luckily we control the execution environment --- it is a Tcl interpreter after all --- so we can implement our own checks. It is this that is the aim of this TIP.

\subsection{Efficiency}

Efficiency of any resource monitoring system is naturally a major concern; it is relatively simple to create a resource monitoring system but quite a lot harder to arrange for that monitoring to be cheap enough that its use does not greatly impact on the general speed of the program (in this case, Tcl.) The costs of checking time limits in particular can be somewhat excessive because of the necessity of performing a system call to carry out the check, but if you're performing any action a lot, it can get costly.

My strategy for limiting the impact upon performance is to provide a programmer-tunable per-limit parameter called the granularity. This specifies how often (out of all the locations in the processing of the Tcl interpreter and bytecode engine) the limits should be checked; the granularity is per-limit because there is this distinct difference in the cost of checking different kinds of limits, and the limits are tunable because the ideal frequency depends very largely on the code being limited. This can be combined with the fact that the test to see if \textit{any} limits have been turned on can be made extremely cheap (i.e. just a comparison of a memory location to zero) and it allows unlimited interpreters to perform at almost the same speed as before.

\section{A Tcl API for Limit Control}

I propose to add a subcommand \textbf{limit} to the \textbf{interp} command and to the object-like interpreter access commands. It will be an error for any safe interpreter to call the \textbf{limit} subcommand; master interpreters may enable it for their safe slaves via the mechanism interpreter aliases, as is normal for security policies.

The first argument to the \textbf{interp limit} command will be the name of the interpreter whose limit is to be inspected. The second argument will be the name of the limit being modified; this TIP defines two kinds of limits:
\begin{description}
\item[time]
Specifies when the interpreter will be prohibited from performing further executions. The limit is not guaranteed to be hit at exactly the time given, but will not be hit before then.
\item[command]
Specifies a maximum number of commands (see \textbf{info cmdcount}) to be executed.
\end{description}

The third and subsequent arguments specify a series of properties (each of which has a name that begins with a hyphen) which may be set (if there are pairs of arguments, being the property name and the value to set it to) or read (if there is just the property name on its own). If no properties are listed at all, all dictionary (see \cite{tip111}) of all properties for the particular limit is returned. The set of properties is limit-specific, but always includes the following:
\begin{description}
\item[-command]
A Tcl script to be executed in the global namespace of the interpreter reading/writing the property when the limit is found to be exceeded in the limited interpreter. If no command callback is defined \textit{for this interpreter}, the \textbf{-command} option will be the empty string. Note that multiple interpreters may set command callbacks that are distinct from each other; an interpreter may not see what other interpreters have installed (except by running a script in those foreign interpreters, of course.) The order of calling of the callbacks is not defined by this TIP.

Where a callback returns any kind of exceptional condition (i.e. the result isn't TCL\_OK) a background error is flagged up.
\item[-granularity]
Limits will always be checked in locations where the \textit{Tcl\_Async*()} API is called, as this is called regularly by the Tcl interpreter (with a few exceptions relating to event loop handling.) However, the cost of just checking a limit can be quite appreciable (it might involve system calls, say) so this property allows the control of how frequently, out of the opportunities to check a limit, are such limits actually checked. If the granularity is \textit{1}, the limit will be checked every time. It is an error to try to set the granularity to less than \textit{1}.
\end{description}

When an interpreter hits a limit, it first runs all command callbacks in their respective interpreters. Once that is done, the interpreter rechecks the limit (since the command callbacks might have decided to raise or remove it) and if it is still exceeded it bails out the interpreter in the following way:
\begin{itemize}
\item{}
A flag is set in the interpreter to mark the interpreter as having exceeded its limits.
\item{}
The currently executing command/script in the interpreter is made to return with code TCL\_ERROR. (This is superior to using a novel return code, as third-party extensions are usually far better at handling error cases!)
\item{}
The \textbf{catch} command will only catch errors if the interpreter containing it does not have the flag mentioned just above set. Similarly, further trips round the internal loops of the \textbf{vwait}, \textbf{update} and \textbf{tkwait} commands will not proceed with that flag set. (Extensions can find this information out by using \textit{Tcl\_LimitExceeded()}; see below.) No calls to \textbf{bgerror} should be made.
\item{}
Once the execution unwinds out of the interpreter so that no further invocations of the interpreter are left on the call-stack, the flag is reset. The same is true if the limits are adjusted in any way. Note that attempting to execute things within the interpreter without raising the limits will result in the limit being hit immediately.
\end{itemize}

When resource limits are being used, unlimited master interpreters should take care to use the \textbf{catch} command when calling their limited slaves. Otherwise hitting the limit in the slave might well smash the master as well, just because of general error propagation. But that is good practise anyway.

\subsection{Time Limits}

Time limits are specified in terms of the time when the limit will be hit. Setting the limit to the current time ensures that the limit will be immediately activated. Time limits have two options for specifying the limit.
\begin{description}
\item[-seconds]
This sets the absolute time (in seconds from the epoch, as returned by \textbf{clock seconds}) that the time limit is hit. If set to the empty string, the limit is removed. If no time limit is set, this option is empty when inspected.
\item[-milliseconds]
This sets the number of milliseconds after the start of the second specified in the \textbf{-seconds} option that the time limit is hit. May only be set to the empty string if the \textbf{-seconds} option is empty and present, and may only be set to a numeric value if the \textbf{-seconds} option is unspecified or present and non-empty (it is always safe to leave this option unspecified.) If no time limit is set, this option is empty when inspected.
\end{description}

Where a time-limited interpreter creates a slave interpreter, the slave will get the same time-limit as the creating master interpreter.

\subsection{Command Limits}

Command limits are specified in terms of the number of commands (see \textbf{info cmdcount} for a definition of the metric) that may be executed before the limit is hit. Command limits have the following extra option for specifying and inspecting the limit.
\begin{description}
\item[-value]
The number of commands (integer of course) that may actually be executed. If set to the empty string, the limit is removed, and when introspecting, unlimited interpreters return empty strings for this value.
\end{description}

Where a command-limited interpreter creates a slave interpreter, the slave will get the command-limit \textit{0} after initialisation (i.e. after the return from the call to \textit{Tcl\_CreateSlave()}) and will be unable to execute and commands until the limit for the slave is raised. Master interpreters implementing security policies for safe interpreters might want to set such limits semi-automatically to something more useful by deducting command-executions from the creating interpreter to its new slave.

\section{A C-level API for Limit Control}

It is also desirable for there to be a general C API for controlling resource limits. Not only does this provide control to extension authors that can't be easily smashed by Tcl scripts by accident, but it also makes implementation of the Tcl API to the limit subsystem easier to create as well.
\begin{itemize}
\item{}
int \textbf{Tcl\_LimitReady}(Tcl\_Interp *\textit{interp})

Test whether a limit is ready to be checked according to its granularity rules. Result is boolean. Note that this is a cheap call.
\item{}
int \textbf{Tcl\_LimitCheck}(Tcl\_Interp *\textit{interp})

Test whether a limit has been exceeded. Result is boolean. Note that this call is potentially expensive (checking a time limit requires a minimum of one system call.)
\item{}
int \textbf{Tcl\_LimitExceeded}(Tcl\_Interp *\textit{interp})

Test whether the interpreter is in a state where a limit has been previously exceeded (i.e. whether a previous call to \textbf{Tcl\_LimitCheck} had indicated that a limit had been hit) and not yet reset (by extending or removing the relevant limit.) Result is boolean. Note that this is a cheap call.
\item{}
int \textbf{Tcl\_LimitTypeEnabled}(Tcl\_Interp *\textit{interp}, int \textit{type})

Test whether the given type of limit is turned on. Result is boolean. Note that this is a cheap call.
\item{}
int \textbf{Tcl\_LimitTypeExceeded}(Tcl\_Interp *\textit{interp}, int \textit{type})

Test whether the given type of limit has been hit (in the notion of \textbf{Tcl\_LimitExceeded}) and not yet reset. Result is boolean. Note that this is a cheap call.
\item{}
void \textbf{Tcl\_LimitTypeSet}(Tcl\_Interp *\textit{interp}, int \textit{type})

Turn on the given type of limit.
\item{}
void \textbf{Tcl\_LimitTypeReset}(Tcl\_Interp *\textit{interp}, int \textit{type})

Turn off the given type of limit.
\item{}
void \textbf{Tcl\_LimitAddHandler}(Tcl\_Interp *\textit{interp}, int \textit{type}, Tcl\_LimitHandlerProc *\textit{handlerProc}, ClientData \textit{clientData}, Tcl\_LimitHandlerDeleteProc *\textit{deleteProc})

Add a limit handler for the given type of limit and specify some caller context and a scheme for deleting that context.
\item{}
void \textbf{Tcl\_LimitRemoveHandler}(Tcl\_Interp *\textit{interp}, int \textit{type}, Tcl\_LimitHandlerProc *\textit{handlerProc}, ClientData \textit{clientData})

Remove a limit handler for the given type of limit. It is not an error to delete a limit that was not set; in that case, nothing is changed.
\item{}
void \textbf{Tcl\_LimitSetCommands}(Tcl\_Interp *\textit{interp}, int \textit{commandLimit})

Set a limiting value on the number of commands, and reset whether the limit has been triggered. Does not enable the limit.
\item{}
int \textbf{Tcl\_LimitGetCommands}(Tcl\_Interp *\textit{interp})

Get the current limit on the number of commands.
\item{}
void \textbf{Tcl\_LimitSetTime}(Tcl\_Interp *\textit{interp}, Tcl\_Time *\textit{timeLimitPtr})

Set a limiting value (copying it from the buffer pointed to by \textit{timeLimitPtr}) on the latest time that the code may execute, and reset whether the limit has been triggered. Does not enable the limit. The \textit{usec} field of the buffer should be in the range 0 to 999999.
\item{}
void \textbf{Tcl\_LimitGetTime}(Tcl\_Interp *\textit{interp}, Tcl\_Time *\textit{timeLimitPtr})

Get the current limit on the execution time, writing it into the buffer pointed to by \textit{timeLimitPtr}.
\item{}
void \textbf{Tcl\_LimitSetGranularity}(Tcl\_Interp *\textit{interp}, int \textit{type}, int \textit{granularity})

Set the checking granularity for the given type of limit.
\item{}
int \textbf{Tcl\_LimitGetGranularity}(Tcl\_Interp *\textit{interp}, int \textit{type})

Get the checking granularity for the given type of limit.
\end{itemize}

Above, \textit{type} is either TCL\_LIMIT\_COMMANDS or TCL\_LIMIT\_TIME, \textit{handlerProc} is a pointer to a function that takes two parameters (a ClientData and a Tcl\_Interp*) and returns void, and \textit{deleteProc} is a pointer to a function that takes a single parameter (a ClientData) and returns void. The key is that \textit{handlerProc}s are called when a limit is hit (they are used to implement the guts of the \textbf{-command} option), and when the callback is deleted for any reason (including a call to \textbf{Tcl\_LimitRemoveHandler} and deleting the limited interpreter) the \textit{deleteProc} is called to release the resources consumed by the \textit{clientData} context.

\section{Use Cases}

\subsection{WebServices}

One use for this sort of code might be in a web-services context where it is important to return a message to some client code within some interval. Using an in-process limiting mechanism allows this to be implemented in a far more light-weight fashion, as the alternative would be to fork off a new small application server for each incoming request and it would be considerably more complex to have a scripted executive that decides (possibly by examining the stack) whether a failure to deliver an answer within bounds is serious, or whether some extra resources should be granted to allow execution to run to completion. Other high-performance server applications would also be likely to gain from this sort of thing.

\subsection{Profiling}

It is possible to use the limiting code (and especially the script callbacks) to write a Tcl profiler. Every time the limit runs out, the callback can examine the Tcl stack in the limited interpreter and then assign some more resources to last up until the next profile trap.

\subsection{Untrusted Code Execution}

As indicated earlier, these limits can be used to increase control over untrusted code running in safe interpreters. While it would be necessary to extend this to memory consumption for every aspect that could be impacted by some malicious code to be controllable, having control over the number of commands that may be executed and how long those commands may take gives a much higher degree of control than currently exists, and is thus a monotonic improvement.

\section{Possible Future Directions}

There are some obvious other things that could be brought within this framework, but which I've left out for various reasons:
\begin{description}
\item[call stack]
We already do limiting of this, so bring that within this framework would be a nice regularisation. On the other hand, such a change would not be backward-compatible, and it might not be safe to perform the callbacks either (especially as overflowing the stack is fatal in a way that overrunning on time is not.)
\item[memory]
Limiting the amount of memory that an interpreter may allocate for its own use would be very nice. But conceptually difficult to do (what about memory shared between interpreters?), expensive to keep track of (memory debugging is known to add a lot of overhead, and memory limiting would be more intrusive) and a really big change technically too (i.e. you'd be rewriting a significant fraction of the Tcl C API to make sure that every memory allocation knows which interpreter owns it.)
\item[open channels, file sizes, etc.]
Most other things can be limited in Tcl right now without special support.
\end{description}

\section{Implementation}

An example implementation of this TIP is available as a patch [\url{http://sf.net/tracker/?func=detail&aid=926771&group_id=10894&atid=310894}].

\section{Copyright}

This document is placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#1}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#111]{tip111}
Donal K. Fellows,
David S. Cargo,
\emph{Dictionary Values and Manipulators},
on-line at \url{http://purl.org/tcl/tip/111.html}
\end{thebibliography}
\end{document}
