File: cqueues.tex

package info (click to toggle)
lua-cqueues 20200726-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 1,848 kB
  • sloc: ansic: 23,623; sh: 2,984; makefile: 24
file content (1491 lines) | stat: -rw-r--r-- 82,564 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
\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}


\begin{Module}{cqueues.dns.config}

The traditional BSD /etc/resolv.conf file is the prototype for this module, although it's also capable of parsing /etc/nsswitch.conf. \module{cqueues.dns.config} objects are used when instantiating new resolver objects, and provide the general options controlling a resolver.

The \fn{\_\_tostring} metamethod composes a string adhering to /etc/resolv.conf syntax, with /etc/nsswitch.conf alternatives as comments.

\subsubsection[\fn{config[]}]{\fn{config[]}}

A table mapping flag identifiers to number values.

\begin{tabular}{ c | l }
field & description\\\hline
TCP\_ENABLE & fall back to TCP when truncation detected (default)\\
TCP\_ONLY & only use TCP when querying\\
TCP\_DISABLE & do not fall back to TCP\\
RESOLV\_CONF & specifies BSD /etc/resolv.conf input syntax\\
NSSWITCH\_CONF & specifies Solaris /etc/nsswitch.conf input syntax
\end{tabular}

\subsubsection[\routine{config.type}]{\routine{config.type(obj)}}
Return the string ``dns config'' if $obj$ is a config object, or $nil$ otherwise.

\subsubsection[\fn{config.interpose}]{\fn{config.interpose(name, function)}}

Add or interpose a config class method. Returns the previous method, if any.

\subsubsection[\fn{config.new}]{\fn{config.new\{ $\ldots$ \}}}

Returns a new config object, optionally initialized according to the specified table values.

\begin{ctabular}{ c | c | p{5in} }
field & type & description\\\hline
.nameserver & table & list of IP address strings to use for stub resolvers\\
.search & table & list of domain suffixes to append to query names\\
.lookup & table & order of lookup methods---``file'' and ``bind''\\
.options & table & canonical location for .edns0, .ndots, .timeout, .attempts, .rotate, .recurse, .smart, and .tcp options\\
..edns0 & boolean & enable EDNS0 support\\
..ndots & number & if query name has fewer labels than this, reverse suffix search order\\
..timeout & number & timeout between query retries\\
..attempts & number & maximum number of attempts per nameserver\\
..rotate & boolean & randomize nameserver selection\\
..recurse & boolean & query recursively instead of as a simple stub resolver\\
..smart & boolean & for NS, MX, SRV and similar record queries, resolve the A record if not included as glue in the initial answer\\
..tcp & number & see TCP\_ENABLE, TCP\_ONLY, TCP\_DISABLE in \fn{config[]}\\
.interface & string & IP address to bind to when querying (e.g. [192.168.1.1]:1234)
\end{ctabular}
\subsubsection[\fn{config.stub}]{\fn{config.stub\{ $\ldots$ \}}}

Returns a config object initialized for a stub resolver by loading the relevant system files; e.g. /etc/resolv.conf and /etc/nsswitch.conf. Takes optional initialization values like \fn{config.new}.

\subsubsection[\fn{config.root}]{\fn{config.root\{ $\ldots$ \}}}

Returns a config object initialized for a recursive resolver. Takes optional initialization values like \fn{config.new}.

\subsubsection[\fn{config:loadfile}]{\fn{config:loadfile(file[, syntax])}}

Parse the Lua file object `file'. `syntax' describes the format, which should be RESOLV\_CONF (default), or NSSWITCH\_CONF.

\subsubsection[\fn{config:loadpath}]{\fn{config:loadpath(path[, syntax])}}

Like :loadfile, but takes a file path.

\subsubsection[\fn{config:get}]{\fn{config:get()}}

Returns the configuration as a Lua table structure. See \fn{config.new} for a description of the values.

\subsubsection[\fn{config:set}]{\fn{config:set\{ $\ldots$ \}}}

Apply the defined configuration values. The table should have the same structure as described for \fn{config.new}.

\end{Module}


\begin{Module}{cqueues.dns.hosts}

The traditional BSD /etc/hosts file is the prototype for this module, and provides resolvers the data source for the ``file'' lookup method.

The \fn{\_\_tostring} metamethod composes a string adhering to /etc/hosts syntax.

\subsubsection[\routine{hosts.type}]{\routine{hosts.type(obj)}}
Return the string ``dns hosts'' if $obj$ is a hosts object, or $nil$ otherwise.

\subsubsection[\fn{hosts.interpose}]{\fn{hosts.interpose(name, function)}}

Add or interpose a hosts class method. Returns the previous method, if any.

\subsubsection[\fn{hosts.new}]{\fn{hosts.new()}}

Returns a new hosts object.

\subsubsection[\fn{hosts.stub}]{\fn{hosts.stub()}}

Returns a host object initialized for a stub resolver by loading the relevant system files; e.g. /etc/hosts.

\subsubsection[\fn{hosts.root}]{\fn{hosts.root()}}

Returns a hosts object initialized for a recursive resolver.

\subsubsection[\fn{hosts:loadfile}]{\fn{hosts:loadfile(file)}}

Parse the Lua file object `file' for host entries.

\subsubsection[\fn{hosts:loadpath}]{\fn{hosts:loadpath(path)}}

Like :loadfile, but takes a file path.

\subsubsection[\fn{hosts:insert}]{\fn{hosts:insert(address, name[, alias])}}

Inserts a new hosts entry. `address' should be an IPv4 or IPv6 address string, `name' the domain name, and `alias' a boolean---true if `name' is canonical and a valid response for a reverse address lookup.

\end{Module}


\begin{Module}{cqueues.dns.hints}

The internal DNS library is implemented as a recursive resolver. No matter whether configured as a stub or recursive resolver, when a query is submitted it consults a ``hints'' database for the initial name servers to contact. In stub mode these would usually be the local recursive, caching name servers, derived from the \module{cqueues.dns.config} object; in recursive mode, the root IANA name servers.

The \fn{\_\_tostring} metamethod composes a multi-line string indexing SOA zone names and addresses.

\subsubsection[\routine{hints.type}]{\routine{hints.type(obj)}}
Return the string ``dns hints'' if $obj$ is a hints object, or $nil$ otherwise.

\subsubsection[\fn{hints.interpose}]{\fn{hints.interpose(name, function)}}

Add or interpose a hints class method. Returns the previous method, if any.

\subsubsection[\fn{hints.new}]{\fn{hints.new([resconf])}}

Returns a new hints object. `resconf' is an optional \module{cqueues.dns.config} object which in the future may be used to initialize database behavior. Currently it's unused, and \emph{does not} pre-load the name server list.

\subsubsection[\fn{hints.stub}]{\fn{hints.stub([resconf])}}

Returns a hints object initialized for a stub resolver. If provided, the initial hints are taken from the \module{cqueues.dns.config} object,  `resconf'. Otherwise, the hints are derived from a temporary ``stub'' config object internally.

\subsubsection[\fn{hints.root}]{\fn{hints.root([resconf])}}

Returns a hints object initialized for a recursive resolver. The root name servers are initialized from an internal database compiled into the module. See \fn{hints.new} for the function of the optional `resconf'.

\subsubsection[\fn{hints:insert}]{\fn{hints:insert(zone, address|resconf[, priority])}}

Inserts a new hints entry. `zone' is the domain name which anchors the SOA (e.g. ``.'', or ``com.''), and `address' the IPv4 or IPv6 of the nameserver. Alternatively, in lieu of a string address a \module{cqueues.dns.config} object can be specified, and the addresses taken from the nameserver list property. `priority' is used for ordering  nameservers in each zone.

IPv4 and IPv6 addresses can optionally contain a port component, e.g. ``[2001:503:ba3e::2:30]:123'' or ``[198.41.0.4]:53''.

\end{Module}


\begin{Module}{cqueues.dns.resolver}

This module implements a comprehensive DNS resolution algorithm, capable of working in both stub and recursive modes, and automatically querying for missing glue records.

The resolver implementation only supports one outstanding query per resolver, with a 1:1 mapping between resolvers and sockets. This is intended to promote both simplicity and security---it maximizes port number and QID entropy to mitigate spoofing. An additional module, \module{cqueues.dns.resolvers}, implements a resolver pool to assist with bulk querying.

\subsubsection[\routine{resolver.type}]{\routine{resolver.type(obj)}}
Return the string ``dns resolver'' if $obj$ is a resolver object, or $nil$ otherwise.

\subsubsection[\fn{resolver.interpose}]{\fn{resolver.interpose(name, function)}}

Add or interpose a resolver class method. Returns the previous method, if any.

\subsubsection[\fn{resolver.new}]{\fn{resolver.new([resconf][,hosts][,hints])}}

Returns a new resolver object, configured according to the specified config, hosts, and hints objects. `resconf' can be either an object, or a table suitable for passing to \fn{config.new}. `hosts' and `hints', if nil, are instantiated according to the mode---recursive or stub---of the config object.

\subsubsection[\fn{resolver.stub}]{\fn{resolver.stub\{ $\ldots$ \}}}

Returns a stub resolver, optionally initialized to the defined config parameters, which should have a structure suitable for passing to \fn{cqueues.dns.config.new}.

\subsubsection[\fn{resolver.root}]{\fn{resolver.root\{ $\ldots$ \}}}

Returns a recursive resolver, optionally initialized to the defined config parameters, which should have a structure suitable for passing to \fn{cqueues.dns.config.new}.

\subsubsection[\fn{resolver:query}]{\fn{resolver:query(name[, type][, class][, timeout])}}

Query for the DNS resource record with the specified type and class. $name$ is the fully-qualified or prefix domain name string. $type$ and $class$ corresponding to the IANA-assigned numeric or string identifier for the type of answer desired, and default to A (0x01) and IN (0x01), respectively. $timeout$ is the total elapsed time for resolution, irrespective of the $.attempts$ and $.timeout$ configuration values.\footnote{The \texttt{resolv.conf} $.timeout$ controls the time to wait on each query to a nameserver, while $.attempts$ controls how many times to query each nameserver in the nameserver list. Thus in the absence of an overall timeout, the effective timeout is $.timeout$ x $.attempts$ x number of nameservers.}

Returns a \module{cqueues.dns.packet} answer packet on success, or nil and a numeric error code on failure. The answer may not actually have anything in the ANSWERS section; e.g. if the RCODE is NXDOMAIN.

This routine is a simple wrapper around \fn{resolver:submit} and \fn{resolver:fetch}.

\subsubsection[\fn{resolver:submit}]{\fn{resolver:submit(name[, type][, class])}}

Resets the query state and submits a new query. Returns true on success, or false and an error number on failure. This routine does not poll.

\subsubsection[\fn{resolver:fetch}]{\fn{resolver:fetch()}}

Process a previously submitted query. Returns a \module{dns.packet} object on success, or nil and an error number on failure---usually \texttt{EAGAIN}. This routine does not poll.

\subsubsection[\fn{resolver:stat}]{\fn{resolver:stat()}}

Returns a table of statistics for the resolver instance.

\begin{ctabular}{ c | p{5in}}
field & description\\\hline
.queries & number of queries submitted \\
.udp.sent.count & number of UDP packets sent \\
.udp.sent.bytes & number of UDP bytes sent \\
.udp.rcvd.count & number of UDP packets received \\
.udp.rcvd.bytes & number of UDP bytes received \\
.tcp.sent.count & number of TCP packets sent \\
.tcp.sent.bytes & number of TCP bytes sent \\
.tcp.rcvd.count & number of TCP packets received \\
.tcp.rcvd.bytes & number of TCP bytes received \\

\end{ctabular}
\subsubsection[\fn{resolver:close}]{\fn{resolver:close()}}

Explicitly destroy the resolver object, immediately closing all internal descriptors. This routine ensures all descriptors are properly cancelled.

\end{Module}


\begin{Module}{cqueues.dns.resolvers}

A resolver pool is both a factory and container for resolver objects. When a resolver is requested it attempts to pull one from the internal queue. If none is available and the $.hiwat$ mark has not been reached, a new resolver is created, otherwise the calling coroutine waits on a conditional variable until a resolver becomes available, or the request times-out. When a resolver is placed back into the queue it is cached if the number of cached resolvers is below $.lowat$, otherwise it is closed and discarded.

\subsubsection[\routine{resolvers.type}]{\routine{resolvers.type(obj)}}
Return the string ``dns resolver pool'' if $obj$ is a resolver pool object, or $nil$ otherwise.

\subsubsection[\fn{resolvers.new}]{\fn{resolvers.new([resconf][,hosts][,hints])}}

Behaves similar to \fn{resolver:new}. Returns a new resolver pool object.

\subsubsection[\fn{resolvers.stub}]{\fn{resolvers.stub\{ $\ldots$ \}}}

Returns a stub resolver pool, with each resolver optionally initialized to the defined config parameters, which should have a structure suitable for passing to \fn{cqueues.dns.config.new}.

\subsubsection[\fn{resolvers.root}]{\fn{resolvers.root\{ $\ldots$ \}}}

Returns a recursive resolver pool, with each resolver optionally initialized to the defined config parameters, which should have a structure suitable for passing to \fn{cqueues.dns.config.new}.

\subsubsection[\fn{resolvers:query}]{\fn{resolvers:query(name[, type][, class][, timeout])}}

Behaves similar to \fn{resolver:query}, except that $timeout$ is inclusive of the time spent waiting for a resolver to become available in the pool.

\subsubsection[\fn{resolvers:get}]{\fn{resolvers:get([timeout])}}

Return a resolver from the pool. If $timeout$ is expires, returns nil and ETIMEDOUT.

\subsubsection[\fn{resolvers:put}]{\fn{resolvers:put(resolver)}}

Returns $resolver$ back to the pool. Any waiting coroutines are woken.

\end{Module}


\begin{Module}{cqueues.condition}

This module implements a condition variable. A condition variable can be used to queue multiple Lua threads to await a user-defined event. Unlike some condition variable implementations, this one does not implement the monitor pattern directly. A monitor uses both a mutex and a condition variable. However, a full monitor will usually be unnecessary as coroutines do not run in parallel. Monitors are more a necessity in pre-emptive threading environments.

The condition variable primitive can be used to implement mutexes, semaphores, and monitors.

\subsubsection[\fn{condition.type}]{\fn{condition.type(obj)}}

Returns the string ``condition'' if $obj$ is a condition variable, or $nil$ otherwise.

\subsubsection[\fn{condition.interpose}]{\fn{condition.interpose(name, function)}}

Add or interpose a condition class method. Returns the previous method, if any.

\subsubsection[\fn{condition.new}]{\fn{condition.new([lifo])}}

Returns a new condition variable object. If `lifo' is \texttt{true}, waiting threads are woken
in LIFO order, otherwise in FIFO order.

Note that the \cqueues scheduler might schedule execution of multiple woken threads in a different order. The LIFO/FIFO behavior is most useful when implementing a mutex and for whatever reason you wish to select the thread which has waited either the longest or shortest amount of time.

\subsubsection[\fn{condition:wait}]{\fn{condition:wait([$\ldots$])}}

Wait on the condition variable. Additional arguments are yielded to the \cqueues controller for polling. Passing an integer, for example, allows you to effect a timeout. Passing a socket allows you to wait on both the condition variable and the socket.

Returns true if the thread was woken by the condition variable, and false otherwise. Additional values are returned if they polled as ready. It's possible that both the condition variable and, e.g., a socket object poll ready simultaneously, in which case two values are returned---true and the socket object.

You can also directly yield a condition variable, along with other condition variables, timeouts, or pollable objects, to the \cqueues controller with \fn{cqueues.poll}.

\subsubsection[\fn{condition:signal}]{\fn{condition:signal([n])}}

Signal a condition, wakening one or more waiting threads. If specified, a maximum of `n' threads are woken, otherwise all threads are woken.

\end{Module}


\begin{Module}{cqueues.promise}

This module implements the promise/future pattern. It most closely resembles the C++11 std::promise and std::future APIs rather than the JavaScript Promise API. JavaScript lacks coroutines, so JavaScript Promises are overloaded with complex functionality intended to mitigate the problems with lacking such a primitive. The typical usage of promises/futures with C++11's threading model mirrors how they would be typically used in \cqueues' thread--like model.

The promise object uses a condition variable to wakeup any coroutines waiting inside \fn{promise:wait} or \fn{promise:get}.

\subsubsection[\fn{promise.type}]{\fn{promise.type(obj)}}

Returns the string ``promise'' if $obj$ is a promise, or $nil$ otherwise.

\subsubsection[\fn{promise.new}]{\fn{promise.new([$f$[, $\ldots$]])}}

Returns a new promise object. $f$ is an optional function to run asynchronously, to which any subsequent arguments are passed. $f$ is called using \fn{pcall}, and the return values of \fn{pcall} are passed directly to \fn{promise:set}.

\subsubsection[\fn{promise:status}]{\fn{promise:status()}}

Returns ``pending'' if the promise is yet unresolved, ``fulfilled'' if the promise has been resolved (\fn{promise:get} will return the values), or ``rejected'' if the promise failed (\fn{promise:get} will throw an error).

\subsubsection[\fn{promise:set}]{\fn{promise:set($ok$[, $\ldots$])}}

Resolves the state of the promise object. If $ok$ is \true then any subsequent arguments will be returned to \fn{promise:get} callers. If $ok$ is \false then an error will be thrown to \fn{promise:get} callers, with the error value taken from the first subsequent argument, if any.

\fn{promise:set} can only be called once. Subsequent invocations will throw an error.

\subsubsection[\fn{promise:get}]{\fn{promise:get([$timeout$])}}

Wait for resolution of the promise object (if unresolved) and either return the resolved values directly or, if the promise was ``rejected'', throw an error. If $timeout$ is specified, returns nothing if the promise is not resolved within the timeout.

\subsubsection[\fn{promise:wait}]{\fn{promise:wait([$timeout$])}}

Wait for resolution of the promise object or until $timeout$ expires. Returns promise object if the status is no longer pending (i.e. ``fulfilled'' or ``rejected''), otherwise \nil.

\subsubsection[\fn{promise:pollfd}]{\fn{promise:pollfd()}}

Returns a condition variable suitable for polling which is used to signal resolution of the promise to any waiting threads.\footnote{To improve performance of the scheduler the pollfd member is itself the condition variable, but it can be called as a function because condition variables support the \_\_call metamethod.}

\end{Module}


\begin{Module}{cqueues.auxlib}

The auxiliary module exposes some convenience interfaces, including some interfaces to help with application integration or for dealing with quirky behavior that hasn't yet been changed because of API stability concerns.

\subsubsection[\fn{auxlib.assert}]{\fn{auxlib.assert($v$ [$\ldots$])}}

Similar to Lua's built-in \fn{assert}, except that when $v$ is false searches the argument list for the first non-nil, non-false value to use as the message. If the message is an integer, applies \fn{errno.strerror} to derive a human readable string.

This routine can be explicitly monkey patched to be the global \fn{assert}.

Most \cqueues interfaces return a single integer error rather than the Lua-idiomatic string followed by an integer error. The original concern was that most ``errors'' would be EAGAIN, ETIMEDOUT, or EPIPE, which occur very often and would be costly to continually copy onto the stack as strings, especially given that they'd normally be discarded. In the future the plan is to revert to the idiomatic return protocol used by Lua's \fn{file} API, but memoize the more common errno string representations using upvalues so they can be efficiently returned.


\subsubsection[\fn{auxlib.fileresult}]{\fn{auxlib.fileresult($v$ [$\ldots$])}}

Serves a similar purpose as \fn{auxlib.assert}, except on error returns $v$ (\nil or \false) followed by the string message and any integer error. For example, in

\begin{example}{lua}
	local v, why, syserr = fileresult(false, nil, EPERM)
\end{example}

$v$ is \false, $why$ is ``Operation not permitted'', and $syserr$ is EPERM. Whereas with

\begin{example}{lua}
	local v, why, syserr = fileresult(nil, ``No such file or directory'')
\end{example}

$v$ is \nil, $why$ is ``No such file or directory'', and $syserr$ is \nil.

\subsubsection[\fn{auxlib.resume}]{\fn{auxlib.resume($co$ [$\ldots$])}}

Similar to Lua's built-in \fn{coroutine.resume}, except that when coroutines yield using \fn{cqueues.poll} recursively yields up the stack until the controller is reached, and then silently restart the coroutine when the poll operation completes. This permits creating iterators which can transparently yield. The application must be careful to ensure that this wrapper is used at every point in a yield/resume chain to get the automatic behavior.

This routine can be explicitly monkey patched to be \fn{coroutine.resume}.

\subsubsection[\fn{auxlib.tostring}]{\fn{auxlib.tostring($v$)}}

Similar to Lua's built-in \fn{tostring}, except supports yielding of \_\_tostring metamethods.

This routine can be explicitly monkey patched to be the global \fn{tostring}.

\subsubsection[\fn{auxlib.wrap}]{\fn{auxlib.wrap($f$)}}

Similar to Lua's built-in \fn{coroutine.wrap}, except uses \fn{auxlib.resume} when resuming coroutines.

This routine can be explicitly monkey patched to be \fn{coroutine.wrap}.

Note that unlike \fn{cqueues:wrap}, the created coroutine is not attached to a controller.

\end{Module}


\chapter{Examples}

\section{HTTP SSL Request}

\begin{example}{lua}
local cqueues = require"cqueues"
local socket = require"cqueues.socket"

local http = socket.connect("google.com", 443)

local cq = cqueues.new()

cq:wrap(function()
	http:starttls()

	http:write("GET / HTTP/1.0\n")
	http:write("Host: google.com:443\n\n")

	local status = http:read()
	print("!", status)

	for ln in http:lines"*h" do
		print("|", ln)
	end

	local empty = http:read"*L"
	print"~"

	for ln in http:lines"*L" do
		io.stdout:write(ln)
	end

	http:close()
end)

assert(cq:loop())
\end{example}


\clearpage
\section{Multiplexing Echo Server}

\begin{example}{lua}
local cqueues = require"cqueues"
local socket = require"cqueues.socket"
local bind, port, wait = ...

local srv = socket.listen(bind or "127.0.0.1", tonumber(port or 8000))

local cq = cqueues.new()

cq:wrap(function()
	for con in srv:clients(wait) do
		cq:wrap(function()
			for ln in con:lines("*L") do
				con:write(ln)
			end

			con:shutdown("w")
		end)
	end
end)

assert(cq:loop())
\end{example}

\clearpage
\section{Thread Messaging}

\begin{example}{lua}
local cqueues = require"cqueues"
local thread = require"cqueues.thread"

-- we start a thread and pass two parameters--`0' and '9'
local thr, con = thread.start(function(con, i, j)
	-- the `cqueues' upvalue defined above is gone
	local cqueues = require"cqueues"
	local cq = cqueues.new()

	cq:wrap(function()
		for n = tonumber(i), tonumber(j) do
			io.stdout:write("sent ", n, "\n")
			con:write(n, "\n")
			 -- sleep so our stdout writes don't mix
			cqueues.sleep(0.1)
		end
	end)

	assert(cq:loop())
end, 0, 9)


local cq = cqueues.new()

cq:wrap(function()
	for ln in con:lines() do
		io.stdout:write(ln, " rcvd", "\n")
	end

	local ok, why = thr:join()

	if ok then
		print(why or "OK")
	else
		error(require"cqueues.errno".strerror(why))
	end
end)

assert(cq:loop())
\end{example}



\appendix
\printindex

\end{document}