-
Notifications
You must be signed in to change notification settings - Fork 37
/
cqueues.tex
1491 lines (920 loc) · 80.6 KB
/
cqueues.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[11pt, oneside]{memoir}
\usepackage{fullpage}
\usepackage{xspace}
\usepackage{makeidx}
\usepackage{listings}
\usepackage{multicol}
\usepackage{graphicx}
\usepackage[colorlinks=true, linkcolor=blue]{hyperref}
\setlength{\parindent}{0pt}
\nonzeroparskip
% add padding to ctabular tables
\renewcommand{\arraystretch}{1.2}
\makeindex
%
% COMMANDS
%
\newcommand*{\cqueues}[0]{\texttt{cqueues}\xspace}
\newcommand*{\key}[1]{#1\index{#1}\xspace}
\newcommand*{\syscall}[1]{\texttt{#1}\xspace}
\newcommand*{\routine}[1]{\texttt{#1}\xspace}
\newcommand*{\fn}[1]{\texttt{#1}\xspace}
\newcommand*{\method}[1]{\texttt{#1}\xspace}
\newcommand*{\module}[1]{\texttt{#1}\xspace}
\newcommand*{\errno}[1]{\texttt{#1}\xspace}
\newcommand*{\crlf}[0]{$\backslash$r$\backslash$n\xspace}
\newcommand*{\lf}[0]{$\backslash$n\xspace}
\newcommand*{\true}[0]{\texttt{true}\xspace}
\newcommand*{\false}[0]{\texttt{false}\xspace}
\newcommand*{\nil}[0]{\texttt{nil}\xspace}
%
% ENVIRONMENTS
%
\lstdefinelanguage{lua}{
morekeywords={break,goto,do,end,while,repeat,until,if,then,elseif,else,for,in,function,local,nil,false,true,and,or,not},
sensitive=true,
morestring=[b]"
}
\lstnewenvironment{code}[1]{
\lstset{language=#1}
}{
}
\lstnewenvironment{example}[1]{
\lstset{language=#1,numbers=left,numberstyle=\tiny,stepnumber=2,tabsize=4}
\ttfamily\small
}{
}
\newcounter{toccols}
\setcounter{toccols}{2}
\newenvironment{Module}[1]{
\subsection{\texttt{#1}}
\addtocontents{toc}{
\protect\begin{multicols}{\value{toccols}}
%\renewcommand*{\cftsubsubsectiondotsep}{\cftnodots}%
}
}{
\addtocontents{toc}{\protect\end{multicols}}
}
\lstdefinelanguage{lua}{morekeywords={break,goto,do,end,while,repeat,until,if,then,elseif,else,for,in,function,local,nil,false,true,and,or,not},sensitive=true,morestring=[b]"}
\begin{document}
%\pagestyle{empty}
\title{
\HUGE\sffamily The \cqueues User Guide \\
%\vspace*{20pt}
%\hrule
\vspace*{10pt}
\LARGE for composing \\
\vspace*{10pt}
\HUGE Socket, Signal, Thread, \& File Change Messaging \\
%\vspace*{20pt}
%\hrule
\vspace*{10pt}
\LARGE on \\
\vspace*{10pt}
\HUGE Linux, OS X, Solaris, \\ FreeBSD, NetBSD, \& OpenBSD
\vspace*{10pt}
\LARGE with \\
\vspace*{10pt}
% ps2pdf -dEPSCrop lua.ps
{\includegraphics[scale=0.10]{art/lua.pdf}}
\vspace*{30pt}
\hrule
}
\date{\today}
\author{William Ahern}
%\setlength{\droptitle}{85pt}
\maketitle
\thispagestyle{empty}
\clearpage
\maxtocdepth{subsubsection}
\setsecnumdepth{subsection}
\setcounter{page}{1}
\pagenumbering{roman}
\tableofcontents
\clearpage
\setcounter{page}{1}
\pagenumbering{arabic}
\chapterstyle{section}
\chapter{Dependencies}
\section{Operating Systems}
\cqueues heavily relies on a modern POSIX environment. But the fundamental premise is to build on the new but non-standard polling facilities provided by contemporary Unix environments. Specifically, BSD \syscall{kqueue}, Linux \syscall{epoll}, and Solaris Event Ports.
\cqueues should work on recent versions of Linux, OS X, Solaris, NetBSD, FreeBSD, OpenBSD, and derivatives. The only other possible candidate is AIX, if and when support for AIX's \syscall{pollset} interface is added to the embedded ``kpoll'' library.
\subsection{$\lnot$ Microsoft Windows}
Microsoft Windows support is basically out of the question\footnote{I have been toying with the idea of using an fd\_set in-place of a pollable descriptor on Windows, and taking the union of all fd\_sets when polling.}, for far too many reasons to put here. Aside from the more technical reasons, Windows I/O and networking programming interfaces have a fundamentally different character than on Unix. Unix historically relies on readiness polling, while Windows uses event completion callbacks. There are strengths and weaknesses to each approach. Trying to paper over the chasm between the two approaches invariably results in a framework with the strengths of neither and the weaknesses of both. The purpose of \cqueues is to leverage the strengths of polling as well as address the weaknesses.
\section{Libraries}
\subsection{LuaJIT, Lua 5.2, Lua 5.3}
\cqueues principally targets Lua 5.2 and above. Some semantics are not fully portable to Lua 5.1 due to 5.1 not supporting yielding from metamethods and iterators. LuaJIT does not have this handicap.
\subsection{OpenSSL}
The \cqueues \module{socket} module provides seamless SSL/TLS support using OpenSSL.
Comprehensive bindings for certificate and key management are provided in the \href{http://25thandClement.com/~william/projects/luaossl.html}{companion \module{openssl} module, \texttt{luaossl}}.
\subsection{pthreads}
\cqueues provides an optional threading module, using POSIX threads.\footnote{Building without threading enabled is not well tested.} Internally it consistently uses thread-safe routines when built with either the \_REENTRANT or \_THREAD\_SAFE feature macros, such as \syscall{pthread\_sigmask} instead of \syscall{sigprocmask}. Thread support is enabled by default.
\paragraph{Linking}
Note that on some systems, such as NetBSD and FreeBSD, the loading application must be linked against pthreads (using -lpthread or -pthread). It is not enough for the \cqueues module to pull in the dependency at load time. In particular, if using the stock Lua interpreter, it must have been linked against pthreads at build time. Add the appropriate linker flag to MYLIBS in lua-5.2.x/src/Makefile.
\paragraph{OpenBSD}
OpenBSD 5.1 threading is completely \emph{fubar}, especially with regard to signals, because of OpenBSD's transition to kernel threading. If using OpenBSD, be sure to compile \emph{without} the thread-safe macros predefined, especially if using \module{cqueues.signal}.
\section{Compilers}
The source code is mostly ISO C99 compliant, and even more so with regards to ISO C11. But regardless of standards conformance, it aims to build cleanly with the native compiler for each targeted platform. It currently builds with recent versions of GCC, clang, and SunPro.
Patches are welcome to silence compiler diagnostics.
\section{GNU Make}
The Makefile requires GNU Make, usually installed as gmake on platforms other than Linux or OS X. The actual \texttt{Makefile} proxies to \texttt{GNUmakefile}. As long as \texttt{gmake} is installed on non-GNU systems you can invoke your system's \texttt{make}.
\chapter{Installation}
Refer to the included \texttt{README.md} for up-to-date build and installation instructions.
\chapter{Usage}
\section{Conventions}
\subsection{Polling}
\cqueues works through a simple protocol. When a coroutine yields to its parent \cqueues controller, it can pass one or more objects. These objects are introspected for three methods: \method{:pollfd}, \method{:events}, and \method{:timeout}. These methods generate the parameters for installing descriptor and timeout events. When one of these events fires, \cqueues will resume the coroutine, passing the relevant objects which were interested in the triggered event. It's analogous to calling Unix \syscall{poll}, and in fact the routine \routine{cqueues.poll} is provided as a wrapper for \routine{coroutine.yield}.\footnote{This wrapper can also detect if the current coroutine was resumed by a controller, and if not chain yield calls---with the cooperation of a \routine{cqueues.resume}---until a controller is reached.}
\subsubsection[\method{object:pollfd}]{\method{:pollfd()}} The \method{:pollfd} method should return a descriptor integer or nil. This descriptor must remain in existence until the owner object is garbage collected, \routine{cqueues.cancel} is used, the coroutine executes one additional yield/resume cycle (so the old descriptor is expired from the descriptor queue), or until after the coroutine exits. If the descriptor is closed prematurely, the kernel will remove it from the internal descriptor queue, bringing it out of sync with the controller, and probably causing \method{cqueues:step} to return EBADF or ENOENT errors.
Alternatively, \method{:pollfd} may return a condition variable object, or the member field may itself
be a condition variable instead of a function. Similarly, the \texttt{.pollfd} member field may be an integer descriptor. This permits user code to create \textit{ad hoc} pollable objects.
\subsubsection[\method{object:events}]{\method{:events()}} The \method{:events} method should return a string or nil. \cqueues searches the string for the flags `r' and `w', which describe the events to associate with the descriptor---respectively, \texttt{POLLIN} and \texttt{POLLOUT}.
The flag `p' may also be specified, describing \texttt{POLLPRI}. However, \texttt{POLLPRI} is not supported for kqueue-based environments.\footnote{OS X's \texttt{EV\_OOBAND} is only useable as an output flag. DragonflyBSD's \texttt{EVFILT\_EXCEPT} maps well and will be supported in a future release.}
Alternatively, the events may be a literal integer value of the logical-OR of the system event values \texttt{POLLIN}, \texttt{POLLOUT}, \texttt{POLLPRI}, etc. However, specifying any events beyond the three discussed is not currently supported and may lead to unexpected behavior.
\subsubsection[\method{object:timeout}]{\method{:timeout()}} The \method{:timeout} should return a number or nil. This schedules an independent timeout event. To effect a simple one second timeout, you can do
\begin{code}{perl}
cqueues.poll({ timeout = function() return 1.0 end })
\end{code}
which is equivalent to the shortcut
\begin{code}{perl}
cqueues.poll(1.0)
\end{code}
Instantiated \cqueues objects implement all three methods.\footnote{\method{:pollfd} returns the internal \syscall{kqueue}, \syscall{epoll}, or Ports descriptor; \method{:events} returns ``r''; and \method{:timeout} returns the time to the next internal timeout event.} In particular, this means that you can stack \cqueues, or poll on a \cqueues object using some other event loop library. Each \cqueues object is entirely self-contained, without any global state.
\subsection{$\lnot$ Globals}
Like the core controller module, other \cqueues modules adhere to a \emph{no global side effects} discipline. In particular, this means
\begin{itemize}
\item no global process variables;
\item no signal handling gimmicks---like the pipe trick---which could conflict with other components of your application\footnote{The \module{cqueues.thread} module ensures threads are started with a filled signal mask.};
\item consistent use of thread-safe function variants; and
\item consistent use of O\_CLOEXEC and similar flags to eliminate or reduce \syscall{fork} $+$ \syscall{exec} races in threaded applications.
\end{itemize}
\subsection{Errors}
The usual behavior is for errors to be returned directly. But see \routine{socket.onerror}. If a routine is specified to return an object or string, nil is returned; if a boolean, false is returned. In both cases, these are usually followed by a numeric error code. Thus, if a routine is specified to return two values on success, then on error three values are returned, the first two nil or false, and the third an error code.
\cqueues is a relatively low-level component library. In almost all cases errors will be system errors, returned as numeric error codes for easy and efficient comparison. For example, attempting to create a UNIX domain socket with \routine{socket.listen} in a directory without sufficient permissions might return `nil, \errno{EACCES}'.
\subsubsection{\texttt{EAGAIN}}
\cqueues modules are implemented in both C and Lua. The C routines never yield, and always return recoverable errors directly. Most C routines are wrapped---and methods interposed---with Lua functions. These Lua functions usually poll when \errno{EAGAIN} is encountered and retry the C routine on resumption. Few methods will return \errno{EAGAIN} directly.
\subsubsection{\texttt{ETIMEDOUT}}
This error value is usually seen when a timeout is specified by the caller of a logically synchronous method. The method will normally yield and poll if the operation cannot be completed immediately, but if the timeout expires then it will return a failure with \errno{ETIMEDOUT}.
\subsubsection{\texttt{EPIPE}}
In Unix \errno{EPIPE} is only encountered when attempting to write to a closed pipe or socket. In \cqueues \errno{EPIPE} is used to signal both EOF and a closed output stream.\footnote{In some situations, such as with SSL/TLS, a read attempt might require a write, anyhow. Expanding the scope of EPIPE simplifies the logic required to handle various I/O failures.} The low-level I/O method \method{socket:recv}, for example, returns \errno{EPIPE} on EOF. In other cases, as with \method{socket:read}, EOF is not an error condition.
\subsubsection{\texttt{EBADF}}
This error commonly occurs in asynchronous applications, which are especially prone to bugs related to their complex state management. With Lua code using the \cqueues APIs, \errno{EBADF} should never be encountered. When it does occur, it's a sure sign of a bug somewhere in the parent application or an extension module and---hopefully---not \cqueues.
\subsubsection{The Future}
The idiomatic protocol for returning errors in Lua is a string representation followed by the integer errno number. This is how Lua's \fn{io} and \fn{file} modules behave. The original concern was that this would be too wasteful for a networking library, where ``errors'' like EAGAIN, ETIMEDOUT, and EPIPE are common and not very exceptional. Copying even small strings into the Lua VM is somewhat costly. However, in the future the API may be configurable to use the Lua-idiomatic protocol by default, using upvalue memoization to minimize the cost of returning string representations.
In the meantime, the auxiliary routines \fn{auxlib.assert} and \fn{auxlib.fileresult} can be used to explicitly achieve the idiomatic behavior.
\section{Modules}
\begin{Module}{\cqueues}
\subsubsection{\routine{cqueues.VENDOR}}
String describing the vendor, e.g.\ william@25thandClement.com. If you fork this project please change this string so I don't receive unwarranted scorn or praise.
\subsubsection{\routine{cqueues.VERSION}}
Number describing the running version, formatted as YYYYMMDD. Official releases are tagged in the git repo as rel-YYYYMMDD.
\subsubsection{\routine{cqueues.COMMIT}}
Git commit hash string of HEAD.
\subsubsection[\routine{cqueues.type}]{\routine{cqueues.type(obj)}}
Return the string ``controller'' if $obj$ is a controller object, or $nil$ otherwise.
\subsubsection[\routine{cqueues.interpose}]{\routine{cqueues.interpose(name, function)}}
Add or interpose a \cqueues controller class method. Returns the previous method, if any.
\subsubsection[\routine{cqueues.monotime}]{\routine{cqueues.monotime()}}
Return the system's monotonic clock time, usually clock\_gettime(CLOCK\_MONOTONIC).
\subsubsection[\routine{cqueues.cancel}]{\routine{cqueues.cancel(fd)}}
Cancels the specified descriptor, $fd$, for all controllers. If $fd$ is an object, the descriptor is obtained by calling the \method{:pollfd} method. Any coroutine polling on the canceled descriptor is placed on its controller's pending queue.
To simplify error and exit paths in application code, canceling a descriptor that isn't installed is a no-op. Similarly, $fd$ may be -1. However, if $fd$ was installed with any controller but the descriptor has already been closed, then this is an error.
Cancellation must be done before closing a descriptor\footnote{Unless the application knows the descriptor isn't currently installed. But note that \cqueues persists descriptor events for at least one yield/resume cycle. When \method{cqueues.poll} returns, for example, the descriptor is still installed. It won't be uninstalled until the coroutine yields again without requesting any events for the descriptor.}, otherwise controller state becomes corrupted. Closing a descriptor automatically removes the descriptor from the kernel's internal polling data structures, but not the user-land data structures. When the process then attempts to modify or remove the descriptor, the operation will fail with \texttt{EBADF}. Some event loops silently suppress such errors because it's very common for applications to close a descriptor before destroying an event handle. But such ordering issues aren't always so benign. If a new socket object was created between the close and cancel operations which happens to have the same descriptor number, then the controller erroneously believes the descriptor is already installed, or if not previously installed than the cancel stalls some other thread. Such bugs can be extremely difficult to track down; they're much easier to discover if the library bubbles up \texttt{EBADF} when canceling an already closed descriptor.
\cqueues objects---controller, notify, resolver, signal, socket, etc---automatically call cancel before closing any descriptor. Normally only extension libraries and modules need to explicitly cancel descriptors.
\subsubsection[\routine{cqueues.poll}]{\routine{cqueues.poll($\ldots$)}}
Takes a series of objects obeying the polling protocol and yields control to the parent \cqueues controller. On an event the coroutine is resumed and \fn{.poll} returns the objects which polled ready. A number value is interpreted as a simple timeout, \emph{not} a file descriptor.
This routine is intended to be behave much like POSIX \texttt{poll(2)}. Think of each object as a \texttt{struct pollfd} object. Then
\begin{example}{lua}
local ready = { assert(cqueues.poll(socket1, socket2, 10)) }
for i=1,#ready do
...
end
\end{example}
looks and behaves like
\begin{example}{c}
struct pollfd pollset[2];
pollset[0].fd = fd1;
pollset[0].events = POLLIN;
pollset[1].fd = fd2;
pollset[1].events = POLLIN;
int n = poll(pollset, 2, 10 * 1000);
assert(n != -1);
for (i = 0; i < n; i++) {
...
}
\end{example}
\subsubsection[\routine{cqueues.sleep}]{\routine{cqueues.sleep(number)}}
Yields to the parent \cqueues controller and schedules a wakeup for `number' seconds in the future.
\subsubsection[\routine{cqueues.running}]{\routine{cqueues.running()}}
Returns two values: the immediate controller currently executing, if any, or nil; and a boolean---true if the caller's coroutine is the same coroutine resumed by the controller.
\subsubsection[\routine{cqueues.resume}]{\routine{cqueues.resume(co)}}
See \fn{auxlib.resume}.
\subsubsection[\routine{cqueues.wrap}]{\routine{cqueues.wrap(f)}}
See \fn{auxlib.wrap}.
\subsubsection[\routine{cqueues.new}]{\routine{cqueues.new()}}
Create a new cqueues object.
\subsubsection[\routine{cqueues:attach}]{\routine{cqueue:attach(coroutine)}}
Attach and manage the specified coroutine. Returns the controller.
\subsubsection[\routine{cqueues:wrap}]{\routine{cqueue:wrap(function)}}
Execute function inside a new coroutine managed by the controller. Returns the controller.
\subsubsection[\routine{cqueues:step}]{\routine{cqueue:step([timeout])}}
Step once through the event queue. Unless the timeout is explicitly specified as \texttt{0}, or unless the current thread of execution is a \cqueues managed coroutine, \emph{it suspends the process indefinitely or for the specified timeout} until a descriptor event or timeout fires.
Returns true on success. Otherwise returns false, an error message, and additional context: a numeric error code (possibly $nil$), a Lua thread object (possibly $nil$), an object that was polled (possibly $nil$), and an integer file descriptor (possibly $nil$). :step can be called again after errors.
If embedding \cqueues within an existing application, the top-level :step invocation should always specify a 0 timeout. A controller is a pollable object, and the descriptor returned by the :pollfd method can be used with third-party event libraries, whether written in Lua, C, or some other language. Don't forget to also schedule a timeout using the value from :timeout.
%[However, at the moment the controller cannot recover from synchronization errors with the kernel queue. In the future, internal, unrecoverable errors should be thrown and only coroutine errors returned directly.]
\subsubsection[\routine{cqueues:loop}]{\routine{cqueue:loop([timeout])}}
Invoke \method{cqueues:step} in a loop, exiting on error, timeout, or if the event queue is empty. Returns same values as \method{cqueues:step}.
\subsubsection[\routine{cqueues:errors}]{\routine{cqueue:errors([timeout])}}
Returns an iterator function over errors returned from \routine{cqueues:loop}. If \routine{cqueues:loop} returns successfully because of an empty event queue, or if the timeout expires, returns nothing, which terminates any for-loop. `timeout' is cumulative over the entire iteration, not simply passed as-is to each invocation of \routine{cqueues:loop}.
\subsubsection[\routine{cqueues:empty}]{\routine{cqueue:empty()}}
Returns true if there are no more descriptor or timeout events queued, false otherwise.
\subsubsection[\routine{cqueues:count}]{\routine{cqueue:count()}}
Returns a count of managed coroutines.
\subsubsection[\routine{cqueues:cancel}]{\routine{cqueue:cancel(fd)}}
Cancel the specified descriptor for that controller. See cqueues.cancel.
\subsubsection[\routine{cqueues:pause}]{\routine{cqueue:pause(signal [, signal $\ldots$ ])}}
A wrapper around \syscall{pselect} which \emph{suspends execution of the process} until the controller polls ready or a signal is delivered. This interface is provided as a very basic least common denominator for simple slave process controller loops and similar scenarios, where immediate response to signal delivery is required on platforms like Solaris without a proper signal polling primitive. (\routine{signal.listen} on Solaris merely periodically queries the pending set.)
Much better alternatives are possible for Solaris, but require global process state or an LWP thread helper.
\end{Module}
\begin{Module}{cqueues.socket}
The socket bindings provide built-in DNS, SSL/TLS, buffering, and line translation. DNS happens transparently, and SSL/TLS can be initiated with the \method{socket:starttls} method.
The default I/O mode is ``tl''---text translation and line buffering. This makes sockets work intuitively with the most common protocols on the Internet, like SMTP and HTTP, which require CRLF and use line delimited framing.
\subsubsection[\fn{socket[]}]{\fn{socket[]}}
A table mapping socket related system identifier names to number codes, including AF\_UNSPEC, AF\_INET, AF\_INET6, AF\_UNIX, SOCK\_STREAM, and SOCK\_DGRAM.
\subsubsection[\routine{socket.type}]{\routine{socket.type(obj)}}
Return the string ``socket'' if $obj$ is a socket object, or $nil$ otherwise.
\subsubsection[\fn{socket.interpose}]{\fn{socket.interpose(name, function)}}
Add or interpose a socket class method. Returns the previous method, if any.
\subsubsection[\fn{socket.connect}]{\fn{socket.connect(host, port [, family] [, type])}}
Return a new socket immediately ready for reading or writing. DNS lookup and TCP connection handling are handled transparently.
\subsubsection[\fn{socket.connect}]{\fn{socket.connect\{ $\ldots$ \}}}
Like \fn{socket.connect} with list arguments, but takes a table of named arguments:
\begin{ctabular}{r | c | p{4.5in}}
field & type:default & description\\\hline
.host & string:nil & IP address or host domain name \\
.port & string:nil & host port \\
.path & string:nil & UNIX domain socket path \\
.family & number & protocol family---AF\_INET (default), AF\_INET6, AF\_UNIX (default if .path specified)\\
.type & number & protocol type---SOCK\_STREAM (default) or SOCK\_DGRAM\\
.mode & string:nil & fchmod or chmod socket after creating UNIX domain socket
%NOTE: There's a race between bind and the following chmod. fchmod is attempted before the bind, however it fails on BSD derivatives. Not all platforms obey UNIX domain socket permissions (e.g. Solaris). Check peer credentials, instead, to be portable.
\\
.mask & string:nil & set and restore umask when binding UNIX domain sockets %NOTE: Not all platforms obey UNIX domain socket permissions. Check peer credentials, instead, to be portable.
\\
.unlink & boolean:false & unlink socket path before binding \\
.reuseaddr & boolean:true & SO\_REUSEADDR socket option \\
.reuseport & boolean:false & SO\_REUSEPORT socket option \\
.nodelay & boolean:false & TCP\_NODELAY IP option \\
.nopush & boolean:false & TCP\_NOPUSH, TCP\_CORK, or equivalent IP option \\
.v6only & boolean:nil & enables or disables IPV6\_V6ONLY IPv6 option, otherwise the system default is left as-is \\
.oobinline & boolean:false & SO\_OOBLINE socket option \\
.nonblock & boolean:true & O\_NONBLOCK descriptor flag \\
.cloexec & boolean:true & O\_CLOEXEC descriptor flag \\
.nosigpipe & boolean:true & O\_NOSIGPIPE, SO\_NOSIGPIPE, MSG\_NOSIGNAL, or equivalent descriptor flag \\
.verify & boolean:false & require SSL certificate verification \\
.sendname & boolean:true & send connect host as TLS SNI host name \\
& string:nil & send specified string as TLS SNI host name \\
.time & boolean:true & track elapsed time for statistics \\
\end{ctabular}
\subsubsection[\fn{socket.listen}]{\fn{socket.listen(host, port)}}
Return a new socket immediately ready for accepting connections.
\subsubsection[\fn{socket.listen}]{\fn{socket.listen\{ $\ldots$ \}}}
Like \fn{socket.listen} with list arguments, but takes a table of named arguments. See also \fn{socket.connect\{\}}.
\subsubsection[\fn{socket.dup}]{\fn{socket.dup(fd)}}
Return a new socket using a duplicate of an existing file-descriptor (integer).
\subsubsection[\fn{socket.fdopen}]{\fn{socket.fdopen(fd)}}
Like \fn{socket.dup(fd)}, but takes ownership of the file-descriptor itself instead of duplicating it.
This is useful e.g. for listening on sockets passed from systemd.
\subsubsection[\fn{socket.pair}]{\fn{socket.pair([type])}}
Returns two bound sockets. Type should be the system type number, e.g. \fn{socket.SOCK\_STREAM} or \fn{socket.SOCK\_DGRAM}.
\subsubsection[\fn{socket.pair}]{\fn{socket.pair\{ $\ldots$ \}}}
Like single argument form of \fn{socket.listen}, but takes a table of named arguments. See also \fn{socket.connect\{\}}.
\subsubsection[\fn{socket.setvbuf}]{\fn{socket.setvbuf(mode [, size])}}
Set the default output buffering mode for all new sockets. See \fn{socket:setvbuf}.
\subsubsection[\fn{socket.setmode}]{\fn{socket.setmode([input] [, output])}}
Set the default I/O modes for all new sockets. See \fn{socket:setmode}.
\subsubsection[\fn{socket.setbufsiz}]{\fn{socket.setbufsiz([input] [, output])}}
Set the default I/O buffer sizes for all new sockets. See \fn{socket:setbufsiz}.
\subsubsection[\fn{socket.setmaxline}]{\fn{socket.setmaxline([input] [, output])}}
Set the default I/O line-buffering limits for all new sockets. See \fn{socket:setmaxline}.
\subsubsection[\fn{socket.settimeout}]{\fn{socket.settimeout([timeout])}}
Set the default timeout for all new sockets. See \fn{socket:settimeout}.
\subsubsection[\fn{socket.setmaxerrs}]{\fn{socket.setmaxerrs([which,][limit])}}
Set the default error limit for all new sockets. See \fn{socket:setmaxerrs}.
\subsubsection[\fn{socket.onerror}]{\fn{socket.onerror([function])}}
Set the default error handler for all new sockets. See \fn{socket:onerror}.
\subsubsection[\fn{socket:connect}]{\fn{socket:connect([timeout])}}
Wait for connection establishment to succeed. You do not need to wait before proceeding to perform
read or write calls, but waiting may ease diagnosing connection problems in your code and allows you to separate connect phase from I/O phase timeouts.
\subsubsection[\fn{socket:listen}]{\fn{socket:listen([timeout])}}
Wait for socket binding to succeed. You do not need to wait before proceeding to call \fn{:accept}, but waiting may ease diagnosing binding problems in your code and allows you to separate listen phase from accept phase timeouts.
Socket binding may not occur immediately if you provided a host address that required DNS resolution over the network. This is uncommon for listening sockets but supported nonetheless; the symmetry simplifies internal code. Also, socket object instantiation with \fn{socket.listen} and \fn{socket.connect} only return errors regarding user data object construction; address lookup and binding errors are detected later, when initiated by subsequent method calls.
\subsubsection[\fn{socket:accept}]{\fn{socket:accept([options] [, timeout])}}
Wait for and return an incoming client socket on a listening object.
Optionally takes a table of named arguments. See also \fn{socket.connect\{\}}.
\subsubsection[\fn{socket:clients}]{\fn{socket:clients([options] [, timeout])}}
Iterator over \method{socket:accept}: \texttt{for con in srv:clients() do ... end}.
%\subsection[\fn{socket:certify}]{\fn{socket:certify(certificate)}}
% Associate a certificate for subsequent :starttls operation.
% [UNFINISHED]
\subsubsection[\fn{socket:starttls}]{\fn{socket:starttls([context][, timeout])}}
Place socket into TLS mode, optionally using the \module{openssl.ssl.context} object as the configuration prototype, and wait for the handshake to complete.\footnote{Prior to 2014-04-30, if no timeout was specified then the routine returned immediately.} Returns true on success, false and an error code on failure.
\subsubsection[\fn{socket:checktls}]{\fn{socket:checktls()}}
If in TLS mode, returns an \module{openssl.ssl} object, otherwise nil. If the openssl module cannot be loaded, returns nil and an error string.
\subsubsection[\fn{socket:setvbuf}]{\fn{socket:setvbuf(mode [, size])}}
Same as Lua \fn{file:setvbuf}. Analogous to ``n'', ``l'', and ``f'' mode flags. Returns the previous output mode and output buffer size.
\subsubsection[\fn{socket:setmode}]{\fn{socket:setmode([input] [, output])}}
Sets the the input and output buffering and translation modes, which mirror C's stdio semantics. Either mode can be nil or none, in which case the mode is left unchanged.
A mode is specified as a string containing one or more of the following flags
\begin{ctabular}{c | c | p{5in}}
flag & default & description \\\hline
t & default & text mode---input or output undergoes LF/CRLF translation \\
b & & binary mode---no LF/CRLF translation \\
n & & no output buffering---output buffer is always flushed completely after every write operation \\
l & default & line buffered output---output buffer is flushed up to and including the last LF after every write operation \\
f & & fully buffered output---all buffer-sized blocks are flushed after every write operation (see \fn{socket:setbufsiz} and \fn{socket:setvbuf}) \\
a & default & enable autoflush---every read operation attempts to flush the output buffer as-if an explicit unbuffered flush were performed with a 0-second timeout; when initiating SSL/TLS, all pending data is fully flushed before proceeding with negotiation \\
A & & disable autoflush \\
p & default & enable pushback---when initiating SSL/TLS, any data in the input buffer is virtually pushed back to the socket so that it will be processed as part of the SSL/TLS handshake \\
P & & disable pushback \\
\end{ctabular}
Returns the previous input and output modes as fixed-sized strings. At present the first character is one of ``t'' or ``b'', and the second character one of ``n'', ``l'', ``f'', or ``-'' (for in the input mode).
\subsubsection[\fn{socket:setbufsiz}]{\fn{socket:setbufsiz([input] [, output])}}
Sets the input and output buffer size. Either size can be nil or none, in which case the size is left unchanged.
These are not hard limits for SOCK\_STREAM sockets. The input buffer argument simply sets a minimum for input buffering, to reduce syscalls. The output buffer argument is the same as provided to \method{:setvbuf}, and effectively changes when flushing occurs for full- or line-buffered output modes.
For SOCK\_DGRAM sockets, the input buffer sets a hard limit on the size of datagram messages. Any message over this size will be truncated, unless a previous block- or line-buffered read operation forced the buffer to be reallocated to a larger size.
Returns the previous input and output buffer sizes, or throws an error if the buffers could not be reallocated.
\subsubsection[\fn{socket:setmaxline}]{\fn{socket:setmaxline([input] [, output])}}
Sets the maximum input and output length for line-buffered operations. Either size can be nil or none, in which case the size is left unchanged.
These are hard limits. For line-buffered input operations, if a \lf character is not found within this limit then the data is processed as-if EOF was reached at this boundary. For line-buffered output, a chunk is always flushed at this boundary.
Returns the previous input and output sizes.
\subsubsection[\fn{socket:settimeout}]{\fn{socket:settimeout([timeout])}}
Sets the default timeout period for I/O. If nil or none, then clears any default timeout. If a timeout is cleared, any operation which polls will wait indefinitely until completion or an error occurs.
Sockets are instantiated without a default timeout.
\subsubsection[\fn{socket:setmaxerrs}]{\fn{socket:setmaxerrs([which,] limit)}}
Set the maximum number of times an error will be returned to a caller before throwing an error, instead. $which$ specifies which I/O channel limit to set---``r'' for the input channel, ``w'' for the output channel, or ``rw'' for both. $which$ defaults to ``rw''. $limit$ is an integer limit. The initial $limit$ is 100.
Returns the previous channel limits in the order specified.
Note that \fn{socket:clearerr} will clear the error counters as well as any errors.
\paragraph{Unchecked error loops} The default error handler will throw on most errors. However, EPIPE and ETIMEDOUT are returned directly as they're common errors that normally need to be handled explicitly in correct applications. Furthermore, errors will be repeated until cleared. If errors were not repeated then unchecked transient errors could lead to difficult to detect loss of data bugs by giving the illusion of successful forward progress.\footnote{This is especially true of Lua's for-loop iterator pattern.} Code which loops and fails to check the success of I/O calls could enter an infinite loop which never yields to the controller and stalls the process. This is a fail-safe mechanism to catch such code.
\subsubsection[\fn{socket:onerror}]{\fn{socket:onerror([function])}}
Set the error handler. The error handler is passed four arguments: socket object, method name, error number, and stack level of caller. The handler is expected to either throw an error or return an error code---to be returned to the caller as part of the documented return interface.
The default error handler returns \errno{EPIPE} and \errno{ETIMEDOUT} directly, and throws everything else. \errno{EAGAIN} is handled internally for logically synchronous calls.
Returns the previous error handler, if any.
\subsubsection[\fn{socket:error}]{\fn{socket:error([which])}}
Returns the saved error conditions for the input and output channels. $which$ is a string containing one or more of the characters `r' and `w', which return the input and output channel errors respectively and in the order specified. $which$ defaults to the string ``rw''.
\subsubsection[\fn{socket:clearerr}]{\fn{socket:clearerr([which])}}
Clears the error conditions and counters for the specified I/O channels and returns any previous errors. $which$ is a string containing one or more of the characters ``r'' and ``w'', which clears the input and output channel errors respectively, and returns the previous error numbers (or nil) in the order specified. $which$ defaults to the string ``rw''.
\subsubsection[\fn{socket:read}]{\fn{socket:read(...)}}
Similar to Lua's \fn{file:read}, with additional formats.
\begin{tabular}{c | l}
format & description\\\hline
{*n} & unsupported \\
{*a} & read until EOF \\
{*l} & read the next line, trimming the EOL marker \\
{*L} & read the next line, keeping the EOL marker \\
{*h} & read and unfold MIME compliant header \\
{*H} & read MIME compliant header, keeping EOL markers \\
{\texttt{--}$marker$} & read multipart MIME entity chunk delineated by MIME boundary $marker$ \\
$number$ & read $number$ bytes or until EOF \\
$-number$ & read 1 to $number$ bytes, immediately returning if possible \\
\end{tabular}
For SOCK\_DGRAM sockets, each message is treated as-if EOF was reached. The slurp operation returns a single datagram, and line-buffered operations will return the remaining text in a message even without a terminating \lf. Datagrams will be truncated if the message is larger than the input buffer size.
The MIME entity reader allows efficient reading of large MIME-encoded bodies, such as with HTTP POST file uploads. The format will return chunks until the boundary is reached. The last chunk will
have any trailing EOL marker removed, regardless of input mode, as this is part of the boundary token. In binary mode chunks are sized according to the current input channel buffer size, except that the last chunk will probably be short. In text mode chunks will not exceed the maximum of the current input channel buffer size or maximum line size; and in addition to EOL translation, chunks are broken along line boundaries with multiple lines aggregated into a single chunk.
Both the MIME header and MIME entity reader require a proper terminating condition. In particular, \emph{EOF is not a terminating condition}. Applications must be careful to handle truncation if the stream was prematurely closed. When looping over one of these input formats, the application should read the next line of input after the loop terminates. If the next next line does not match the terminating condition, then the stream is invalid and the application should abort processing the stream.
For MIME headers the next line should be non-$nil$ and should not appear to be a prefix of a header.
\begin{example}{lua}
local function isbreak(ln) -- requires *L, not *l
return find(ln, "\n", #ln, true) and not match(ln, "[%w%-_]+%s*:")
end
\end{example}
For MIME entities the next line should begin with the boundary text.
\begin{example}{lua}
local function isboundary(marker, ln)
local p, pe = find(ln, marker, 1, true)
if p == 1 then
if find(ln, "^\r?\n?$", pe + 1) then
return "begin"
elseif find(ln, "^--\r?\n?$", pe + 1) then
return "end"
end
end
return false
end
\end{example}
\subsubsection[\fn{socket:xread}]{\fn{socket:xread(format[, mode][, timeout])}}
Like \method{socket:read}, but only takes a single format instead of a list of formats, and permits specifying an input mode and timeout. $mode$ should be in the format described at \method{socket:setmode}. $mode$ and $timeout$ are used only for the current read operation; they do not change the default mode and timeout for the socket.
\subsubsection[\fn{socket:lines}]{\fn{socket:lines(...)}}
Returns an iterator function over \method{socket:read}.
\subsubsection[\fn{socket:xlines}]{\fn{socket:xlines([format][, mode][, timeout])}}
Returns an iterator function over \method{socket:xread}.
\subsubsection[\fn{socket:write}]{\fn{socket:write(...)}}
Same as Lua \fn{file:write}.
\subsubsection[\fn{socket:xwrite}]{\fn{socket:xwrite(string[, mode][, timeout])}}
Like \method{socket:write}, but only takes a single string, and permits specifying an output mode and timeout. $mode$ should be in the format described at \method{socket:setmode}. $mode$ and $timeout$ are used only for the current write operation; they do not change the default mode and timeout for the socket.
\subsubsection[\fn{socket:flush}]{\fn{socket:flush([mode][, timeout])}}
Flushes the output buffer. Mode is one of the ``nlf'' flags described in \method{socket:setmode}. A nil mode implies ``n'', i.e.\ no buffering and effecting a full flush. An empty string mode resolves to the configured output buffering mode.
\subsubsection[\fn{socket:fill}]{\fn{socket:fill(size[, timeout])}}
Fills the input buffer with `size' bytes. Returns true on success, false and an error code on failure.
\subsubsection[{\fn{socket:unget}}]{\fn{socket:unget(string)}}
Writes `string' to the head of the socket input buffer.
\subsubsection[{\fn{socket:pending}}]{\fn{socket:pending()}}
Returns two numbers---the counts of buffered bytes in the input and output streams. This does not include the bytes in the kernel's buffer.
\subsubsection[\fn{socket:uncork}]{\fn{socket:uncork()}}
Disables TCP\_NOPUSH, TCP\_CORK, or equivalent socket option.
\subsubsection[\fn{socket:recv}]{\fn{socket:recv(format [, mode])}}
Similar to \method{socket:read}, except takes only a single format and returns immediately without polling. On success returns the string or number. On failure returns nil and a numeric error code--usually EAGAIN or EPIPE. Does not use error handler.
`mode' is as described in \fn{socket.connect}, and defaults to the configured input mode.
\subsubsection[\fn{socket:send}]{\fn{socket:send(string, i, j [, mode])}}
Write out the slice `string'[i,j]. Similar to passing \fn{string:sub(i, j)}, but without instantiating a new string object. Immediately returns two values: count of bytes written (0 to j-i+1), and numerical error code, if any (usually EAGAIN or EPIPE).
\subsubsection[\fn{socket:recvfd}]{\fn{socket:recvfd([prepbufsiz][, timeout])}}
Receive an ancillary socket message with accompanying descriptor. `prepbufsiz' specifies the maximum message size to expect.
This routine bypasses I/O buffering.
Returns message-string, socket-object on success; nil, nil, error-integer on failure. On success socket-object may still be nil. Message truncation is treated as an error condition.
\subsubsection[\fn{socket:sendfd}]{\fn{socket:sendfd(msg, socket[, timeout])}}
Send an ancillary socket message with accompanying descriptor. `msg' should be a non-zero-length string, which some platforms require. `socket' should be a Lua file handle, \cqueues socket, integer descriptor, or nil.
This routine bypasses I/O buffering.
Returns true on success; false and an error code on failure.
\subsubsection[\fn{socket:shutdown}]{\fn{socket:shutdown(how)}}
Simple binding to \syscall{shutdown(2)}. `how' is a string containing one or both of the flags ``r'' or ``w''.
\begin{tabular}{c | l}
flag & description \\\hline
r & analagous to \syscall{shutdown(SHUT\_RD)} \\
w & analagous to \syscall{shutdown(SHUT\_WR)} \\
\end{tabular}
\subsubsection[\fn{socket:eof}]{\fn{socket:eof([which])}}
Returns boolean values representing whether EOF has been received on the input channel, and whether the output channel has signaled closure (e.g. \errno{EPIPE}). $which$ is a string containing one or more of the characters ``r'' and ``w'', which return the state of the input or output channel, respectively, in the order specified. $which$ defaults to ``rw''.
Note that \fn{socket:shutdown} does not change the state of these values. They are set only upon receiving the condition after I/O is attempted.
\subsubsection[\fn{socket:peername}]{\fn{socket:peername()}}
Returns one, two, or three values.
On success, returns three values for AF\_INET and AF\_INET6 sockets---the address family number, IP address string, and IP port.
For AF\_UNIX sockets, returns the address family and either the file path or nil (e.g. for an unnamed socket).
If the socket is not yet connected, returns the address family AF\_UNSPEC, usually numeric 0.
On failure returns nil and a numeric error code.
\subsubsection[\fn{socket:peereid}]{\fn{socket:peereid()}}
Queries the effective UID and effective GID of an AF\_UNIX, SOCK\_STREAM peer as cached by the kernel when the stream initially connected.
Returns two numbers representing the UID and GID, respectively, on success, otherwise nil and a numeric error code.
\subsubsection[\fn{socket:peerpid}]{\fn{socket:peerpid()}}
Queries the PID of a AF\_UNIX, SOCK\_STREAM peer as cached by the kernel when the stream initially connected. This capability is unsupported on OS X and FreeBSD; they only provide \fn{getpeereid}, which cannot provide the PID.
Returns a number representing the PID on success, otherwise nil and a numeric error code.
\subsubsection[\fn{socket:localname}]{\fn{socket:localname()}}
Identical to \fn{socket:peername}, but returns the local address of the socket.
\subsubsection[\fn{socket:stat}]{\fn{socket:stat()}}
Returns a table containing two subtables, `sent' and `rcvd', which each have three fields---.count for the number of bytes sent or received, a boolean .eof signaling whether input or output has been shutdown, and .time logging the last send or receive operation.
\subsubsection[\fn{socket:close}]{\fn{socket:close()}}
Explicitly and immediately close all internal descriptors. This routine ensures all descriptors are properly cancelled.
\end{Module}
\begin{Module}{cqueues.errno}
\subsubsection[\fn{errno[]}]{\fn{errno[]}}
A table mapping all system error string macros to numerical error codes, and all numerical error codes to system error string macros. Thus, \texttt{errno.EAGAIN} evaluates to a numeric error code, and \texttt{errno[errno.EAGAIN]} evaluates to the string ``EAGAIN''.
\subsubsection[\fn{errno.strerror}]{\fn{errno.strerror(code)}}
Returns string returned by strerror(3).
%[FUTURE: Will also handle embedded socket.c and dns.c library error codes.]
\end{Module}
\begin{Module}{cqueues.signal}
\subsubsection{\fn{signal[]}}
A table mapping signal string macros to numerical signal codes.
In all likelihood, \texttt{signal.SIGKILL} evaluates to the number 9.
\subsubsection[\fn{signal.strsignal}]{\fn{signal.strsignal(code)}}
Returns string returned by strsignal(3).
\subsubsection[\fn{signal.ignore}]{\fn{signal.ignore(signal [, signal $\ldots $ ])}}
Set the signal handler to SIG\_IGN for the specified signals.
\subsubsection[\fn{signal.default}]{\fn{signal.default(signal [, signal $\ldots$ ])}}
Set the signal handler to SIG\_DFL for the specified signals.
\subsubsection[\fn{signal.discard}]{\fn{signal.discard(signal [, signal $\ldots$ ])}}
Set the signal handler to a builtin ``noop'' handler for the specified signals. Use this is you want signals to interrupt syscalls.
\subsubsection[\fn{signal.block}]{\fn{signal.block(signal [, signal $\ldots$ ])}}
Block the specified signals.
\subsubsection[\fn{signal.unblock}]{\fn{signal.unblock(signal [, signal $\ldots$ ])}}
Unblock the specified signals.
\subsubsection[\fn{signal.raise}]{\fn{signal.raise(signal [, signal $\ldots$ ])}}
raise(3) the specified signals.
\subsubsection[\routine{signal.type}]{\routine{signal.type(obj)}}
Return the string ``signal listener'' if $obj$ is a signal listener object, or $nil$ otherwise.
\subsubsection[\fn{signal.interpose}]{\fn{signal.interpose(name, function)}}
Add or interpose a signal listener class method. Returns the previous method, if any.
\subsubsection[\fn{signal.listen}]{\fn{signal.listen(signal [, signal $\ldots$ ])}}
Returns a signal listener object for the specified signals. Semantics differ between platforms:
\paragraph{kqueue}
BSD \syscall{kqueue} provides the most intuitive behavior. All listeners will detect a signal sent to the process irrespective of whether the signal is ignored, blocked, or delivered. However, EVFILT\_SIGNAL is edge-triggered, which means no notification of delivery of a pending signal upon being unblocked.
\paragraph{signalfd}
Linux \syscall{signalfd} will not detect ignored or delivered signals, and only one signalfd object will poll ready per signal.
\paragraph{sigtimedwait}
Solaris provides no signal polling kernel primitive. Instead, the pending set is periodically queried using \syscall{sigtimedwait}. See \method{signal:settimeout}. Like Linux, only one listener can notify per interrupt.
To be portable the application must block the relevant signals. See \fn{signal.block}. Otherwise, neither Linux nor Solaris will be able to detect the interrupt. Any signal should be assigned to one listener only, although any listener may query multiple signals.
Alternatively, applications may start a dedicated thread to field incoming signals, and send notifications over a socket. In the future this may be provided as an optional listener implementation.
See also \routine{cqueue:pause} for another, if crude, alternative.
\subsubsection[\fn{signal:wait}]{\fn{signal:wait([timeout])}}
Polls for the signal set passed to the constructor. Returns the signal number, or nil on timeout.
\subsubsection[\fn{signal:settimeout}]{\fn{signal:settimeout(timeout)}}
Set the polling interval for implementations such as Solaris which lack a signal polling kernel primitive. On such systems signal:wait merely queries the pending set every `timeout' seconds.
\end{Module}
\begin{Module}{cqueues.thread}
\subsubsection[\routine{thread.type}]{\routine{thread.type(obj)}}
Return the string ``thread'' if $obj$ is a thread object, or $nil$ otherwise.
\subsubsection[\fn{thread.self}]{\fn{thread.self()}}
Returns the LWP thread object for the running Lua instances. Threads not started via thread.start return nil.
\subsubsection[\fn{thread.start}]{\fn{thread.start(function [, string [, string $\ldots$ ]])}}
Generates a socket pair, starts a POSIX LWP thread, initializes a new Lua VM instance, preloads the \cqueues library, and loads and executes the specified function from the new LWP thread and Lua instance. The function receives as the first parameter one end of the socket pair---instantiated as a \module{cqueues.socket} object---followed by the string parameters passed to thread.start.
The new LWP thread starts with all signals blocked.
Returns a thread object and a socket object---the other end of the socket pair. The thread object is pollable, and readiness signals that the LWP thread has exited, or is imminently about to exit.
On error returns two nils and an error code.
\subsubsection[\fn{thread:join}]{\fn{thread.join([timeout])}}
Wait for the thread to terminate. Calling the equivalent of thread.self():join() is disallowed.
Returns a boolean and error value. If false, error value is an error code describing a local error, usually \errno{EAGAIN} or \errno{ETIMEDOUT}. If true, error value is 1) an error code describing a system error which the thread encountered, 2) an error message string returned by the new Lua instance, or 3) nil if completed successfully.
\end{Module}
\begin{Module}{cqueues.notify}
\subsubsection[\fn{notify[]}]{\fn{notify[]}}
A table mapping bitwise flags to names, and vice-versa.
\begin{tabular}{c | l}
name & description \\\hline
CREATE & file creation event \\
ATTRIB & metadata change event \\
MODIFY & modification to file contents or directory entries \\
REVOKE & permission revoked \\
DELETE & file deletion event \\
ALL & bitwise-or of CREATE, DELETE, ATTRIB, MODIFY, and REVOKE
%\hline
%INOTIFY & foo \\
%FEN & foo \\
%KQUEUE & foo \\
%KQUEUE1 & foo \\
%OPENAT & foo \\
%FDOPENDIR & foo \\
%O\_CLOEXEC & foo \\
%IN\_CLOEXEC & foo \\
\end{tabular}
\subsubsection[\fn{notify.flags}]{\fn{notify.flags(bitset[, bitset $\ldots$ ])}}
Returns an iterator over the flags in the specified bitwise change sets. Thus, \texttt{notify.flags(bit32.xor(notify.CREATE, notify.DELETE), notify.MODIFY)} returns an iterator returning all three flags.
\subsubsection[\routine{notify.type}]{\routine{notify.type(obj)}}
Return the string ``file notifier'' if $obj$ is a notification object, or $nil$ otherwise.
\subsubsection[\fn{notify.opendir}]{\fn{notify.opendir(path[, changes ])}}
Returns a notification object associated with the specified directory. Directory change events are limited to the set, `changes', or to notify.ALL if nil.
\subsubsection[\fn{notify:add}]{\fn{notify:add(name[, changes ])}}
Track the specified file name within the notification directory. `changes' defaults to notify.ALL if nil.
\subsubsection[\fn{notify:get}]{\fn{notify:get([timeout])}}
Returns a bitwise change set and a filename on success.
\subsubsection[\fn{notify:changes}]{\fn{notify:changes([timeout])}}
Returns an iterator over the \method{notify:get} method.
\end{Module}
\begin{Module}{cqueues.dns}
As the internal DNS implementation has no global state, \module{cqueues.dns} is mostly a convenience wrapper around other facilities.
\subsubsection[\fn{dns.version}]{\fn{dns.version()}}
Returns the release, ABI, and API version numbers of the internal DNS implementation as three numbers.
\subsubsection[\fn{dns.query}]{\fn{dns.query(name[, type][, class][, timeout])}}
Proxies the \fn{resolvers:query} method of the internal resolver pool. If no resolver pool has been set with \fn{dns:setpool}, creates a new stub resolver pool.
\subsubsection[\fn{dns.setpool}]{\fn{dns.setpool(pool)}}
Sets the internal resolver pool for use by subsequent calls to \fn{dns.query} to $pool$.
\subsubsection[\fn{dns.getpool}]{\fn{dns.getpool()}}
Returns the internal resolver pool. This routine should never return nil, as it will automatically
create a new resolver pool if none has been set yet.
\end{Module}
\begin{Module}{cqueues.dns.record}
DNS resource record objects are implemented within \module{cqueues.dns.record}. The global tables and shared methods are documented below. The type-specific accessory methods are quite numerous. Until documented please confer with cqueues/src/dns.c. Also, the accessory method names are usually equivalent to the structure member names in cqueues/src/lib/dns.h, which in return usually reflect the member names in the relevant RFC.
The \fn{\_\_tostring} metamethod returns a representation of the record data only, excluding the name, type, ttl, etc. For an A record, it's equivalent to string.format(``\%s'', \fn{rr:addr()}). For MX---which has multiple members---it's string.format(``\%d \%s'', rr:preference(), rr:host()).
\subsubsection[\fn{record.type[]}]{\fn{record.type[]}}
A table mapping DNS record type string identifiers to number values, and vice-versa. So, \method{record.type.A} evaluates to 1, the IANA numeric record type. String identifiers are only provided for record types which are directly parseable and composable by the library. Currently supported types include A, NS, CNAME, SOA, PTR, MX, TXT, AAAA, SRV, OPT, SSHFP, and SPF. Other record types can be instantiated, but the numeric type must be used and the only methods available operate on the raw rdata.
\subsubsection[\fn{record.class[]}]{\fn{record.class[]}}
A table mapping DNS record class string identifiers to number values, and vice-versa. At present the only class included is IN.
\subsubsection[\fn{record.sshfp[]}]{\fn{record.sshfp[]}}
A table mapping DNS SSHFP record string identifiers to the number values---RSA, DSA, and SHA1.
\subsubsection[\routine{record.type}]{\routine{record.type(obj)}}
Return the string ``dns record'' if $obj$ is a record object, or $nil$ otherwise.
\subsubsection[\fn{record:section}]{\fn{record:section()}}
Returns the section identifier from whence the record came, if derived from a packet. Specifically, QUESTION, ANSWER, AUTHORITY, or ADDITIONAL. See \module{cqueues.dns.packet.section[]}.
\subsubsection[\fn{record:name}]{\fn{record:name()}}
Returns the uncompressed record domain name as a string.
\subsubsection[\fn{record:type}]{\fn{record:type()}}
Returns the numeric record type. If `rr' holds an AAAA record, then the return value of rr:type() will compare equal to \module{record.type.AAAA}.
\subsubsection[\fn{record:class}]{\fn{record:class()}}
Returns the numeric record class. See \module{record.class[]}.
\subsubsection[\fn{record:ttl}]{\fn{record:ttl()}}
Returns the record TTL.
\end{Module}
\begin{Module}{cqueues.dns.packet}
DNS packets are stored in a simple structure encapsulating the raw packet data. One consequence is that packets are append only. Because a packet is composed of four adjacent sections, when building a packet all the information necessary should be at-hand so that records can be appended in order.
The \fn{\_\_tostring} metamethod composes a string similar to the output of the venerable dig utility.
\subsubsection[\fn{packet.section[]}]{\fn{packet.section[]}}
A table mapping packet section string identifiers to number values, and vice-versa. A packet is composed of only four sections: QUESTION, ANSWER, AUTHORITY, and ADDITIONAL.
\subsubsection[\fn{packet.opcode[]}]{\fn{packet.opcode[]}}
A table mapping packet opcode string identifiers to number values, and vice-versa. The currently mapped opcodes are QUERY, IQUERY, STATUS, NOTIFY, and UPDATE.
\subsubsection[\fn{packet.rcode[]}]{\fn{packet.rcode[]}}
A table mapping packet rcode string identifiers to number values, and vice-versa. The currently mapped rcodes are NOERROR, FORMERR, SERVFAIL, NXDOMAIN, NOTIMP, REFUSED, YXDOMAIN, YXRRSET, NXRRSET, NOTAUTH, and NOTZONE.
\subsubsection[\routine{packet.type}]{\routine{packet.type(obj)}}
Return the string ``dns packet'' if $obj$ is a packet object, or $nil$ otherwise.
\subsubsection[\fn{packet.interpose}]{\fn{packet.interpose}}
Add or interpose a packet class method. Returns the previous method, if any.
\subsubsection[\fn{packet.new}]{\fn{packet.new([prepbufsiz])}}
Instantiate a new packet object. `prepbufsiz' is the maximum space available for appending compressed records. For constructing a packet with a single question, the most space possibly necessary is 260---256 bytes for the name, and 2 bytes each for the type and class (a QUESTION record has no TTL or rdata section).
\subsubsection[\fn{packet:qid}]{\fn{packet:qid()}}
Returns the 16-bit QID value.
\subsubsection[\fn{packet:flags}]{\fn{packet:flags()}}
Returns a table of packet header flags.
\begin{tabular}{ c | c | l }
field & type & description\\\hline
.qr & integer & specifies whether the packet is a query (0) or response (1)\\
.opcode & number & specifies the query type\\
.aa & boolean & signals an authoritative answer\\
.tc & boolean & signals packet truncation\\
.rd & boolean & signals ``recursion desired''\\
.ra & boolean & signals ``recursion available''\\
.z & boolean & reserved by RFC 1035 and used by other RFCs\\
.rcode & integer & specifies the response disposition
\end{tabular}
\subsubsection[\fn{packet:count}]{\fn{packet:count([sections])}}
Returns a count of records in the sections specified by the bitwise parameter `sections'. Defaults to \texttt{packet.section.ALL}, which is the XOR of all four sections.
\subsubsection[\fn{packet:grep}]{\fn{packet:grep\{ $\ldots$ \}}}
Returns a record iterator over the packet according to all the criteria specified by the optional table parameter.
\begin{tabular}{ c | l }
field & description\\\hline
.section & select records by bitwise AND with the specified sections\\
.type & select records of this type (not bitwise)\\
.class & selects records of this class (not bitwise)\\
.name & select records with this name
\end{tabular}
\end{Module}