-
Notifications
You must be signed in to change notification settings - Fork 0
/
cgi-supt.nw
9731 lines (8786 loc) · 303 KB
/
cgi-supt.nw
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
% -*- mode: Noweb; noweb-code-mode: c-mode; -*-
\documentclass[twoside,english]{report}
\usepackage[letterpaper,rmargin=1.5in,bmargin=1in]{geometry}
%%% latex preamble
\RCS $Id$
\RCS $Revision$
% Build with noweb:
% notangle -t8 build.nw > makefile
% make
%
% Copyright 2009-2010 Trustees of Indiana University
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Additional modifications released with no additional restrictions by
% Thomas J. Moore.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% requires cs-glib
\begin{document}
\title{CGI Extensions for the ClearSilver CGI Kit}
\def\putlogo#1{\includegraphics[width=0.5\textwidth]{#1}}
% l2h macro putlogo 1 <img src="#$1" alt="Indiana University" width=400 />
\ifpdf
\else
\def\putlogo#1{\HCode{<img src="#1" alt="Indiana University" width=400 />}}
\fi
\author{Thomas J. Moore}
\date{Version 1.0 Revision \RCSRevision\\2010}
\maketitle
\begin{abstract}
This document describes and implements a few enhancements to the CGI library
provided by ClearSilver, in addition to what is provided by the
\emph{Generic ClearSilver and GLib Module Build Support} document.
\vspace{0.25in}
\copyright{} 2009--2010 Trustees of Indiana University. This document
is licensed under the Apache License, Version 2.0 (the ``License'');
you may not use this document except in compliance with the License.
You may obtain a copy of the License at
\url{http://www.apache.org/licenses/LICENSE-2.0}. Unless required by
applicable law or agreed to in writing, software distributed under the
License is distributed on an ``AS IS'' BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for
the specific language governing permissions and limitations under the
License.
\vspace{0.25in}
This document was generated from the following sources, all of which are
attached to the original electronic forms of this document:
\input{Sources.tex} % txt
\end{abstract}
\tableofcontents{}
\chapter{Introduction}
The CGI kit included with ClearSilver works well enough for most
applications, but some improvements could be made. First, like most CGI
libraries, file upload control is inadequate: all uploads are placed in the
same temporary directory (which bypasses per-user quotas, among other
things), and the only provided callback does not get access to already-known
CGI parameters or file attributes. Second, there is no direct
FastCGI\footnote{\url{http://www.fastcgi.com}} support. FastCGI allows the
sharing of long setup times among multiple connections; for example,
connections can be made to a database before the user ever connects to the
web server. Third, there is no macro library for common form operations.
This is probably for the better, since limitations in such a library tend to
prompt either rewrite or convoluted workarounds. Fourth, there is no
support for WebDAV\footnote{\url{http://www.webdav.org}} request processing.
This is normally done in a web server module, but there is no reason not to
do it in (Fast)CGI.
In addition to the basic parsing enhancements and FastCGI support, a simple
session management infrastructure is implemented, using either files or a
database for session storage. This is then used to help implement
authentication caching for the Central Authentication
Service\footnote{\url{http://www.jasig.org/cas}}.
<<Version Strings>>=
"$Id$\n"
@
\lstset{language=txt}
<<Sources>>=
$Id$
@
\lstset{language=sh}
<<Common NoWeb Warning>>=
# $Id$
@
\chapter{HTML Form Support Macros}
Using macros to display widgets makes the HTML harder to edit with normal
tools, and also makes it more dependent on the macro language. The
conditional HTML is complex enough that the use of macros is worth the
potential problems.
<<CS files>>=
html_macros.cs \
@
<<html_macros.cs>>=
<?cs <<Common NoWeb Warning>> ?><?cs
<<Generic ClearSilver HTML Macros>>
# ?>
@
<<Install other files>>=
<<Install ClearSilver templates>>
@
First, to start out a form, the form header must be printed.
\lstset{language=[ext]HTML}
<<Generic ClearSilver HTML Macros>>=
def:form(fname,hasfiles)
?><form name="<?cs var:fname ?>" action="<?cs
var: CGI.ScriptName + CGI.PathInfo ?>"<?cs
if:hasfiles ?> enctype="multipart/form-data"<?cs /if ?>><?cs
/def ?><?cs
@
For a standard text widget, only the variable name and default value are
required. As with all of these macros, the CGI parameter value is retrieved
from the [[Query]] variable hierarchy.
<<Generic ClearSilver HTML Macros>>=
def:text(varn,default)
?><input type="text" size="32" name="<?cs var:varn ?>" value="<?cs
if: ?Query[varn] ?><?cs
var:Query[varn] ?><?cs
else ?><?cs
var:default ?><?cs
/if ?>" /><?cs
/def ?><?cs
@
Repeated text widgets are the same as regular text widgets, but a sequence
number is attached to the variable name. The hierarchy is expected to go
one level lower, using the sequence number. The first widget (0) is
actually just like a normal text widget.
<<Generic ClearSilver HTML Macros>>=
def:rtext(varn,seq,default)
?><input type="text" size="32" name="<?cs var:varn ?>" value="<?cs
if:?Query[varn][seq] ?><?cs
var:Query[varn][seq] ?><?cs
else ?><?cs
if:seq == "0" && ?Query[varn] ?><?cs
var:Query[varn] ?><?cs
else ?><?cs
var:default ?><?cs
/if ?><?cs
/if ?>" /><?cs
/def ?><?cs
@
Hidden parameters are just printed once for every available value.
<<Generic ClearSilver HTML Macros>>=
def:hidden(varn)
?><?cs
if:len(Query[varn]) ?><?cs
each:v = Query[varn]
?><input type="hidden" name="<?cs var:varn ?>" value="<?cs var:v ?>" />
<?cs /each ?><?cs
elseif:?Query[varn]
?><input type="hidden" name="<?cs var:varn ?>" value="<?cs
var:Query[varn] ?>" />
<?cs
/if ?><?cs
/def ?><?cs
@
File selection widgets do not have defaults. Even if the variable is
provided by the CGI, it does not necessarily match a local file name.
<<Generic ClearSilver HTML Macros>>=
def:file(varn)
?><input type="file" size="32" name="<?cs var:varn ?>" value="<?cs
var:Query[varn] ?>" /><?cs
/def ?><?cs
@
Radio selections are checked if the CGI parameter matches the value, or if
this is the default and the CGI parameter either does not exist or has no
value.
<<Generic ClearSilver HTML Macros>>=
def:radio(varn, val, isdef)
?><input type="radio" value="<?cs var:val ?>" name="<?cs var:varn ?>"<?cs
if:?Query[varn]["0"] ?><?cs
each:i = Query[varn] ?><?cs
if: i == val ?> checked="checked" <?cs /if ?><?cs
/each ?><?cs
else ?><?cs
if: Query[varn] == val ?> checked="checked" <?cs
else ?><?cs
if:isdef && (!?Query[varn] || Query[varn] == "") ?> checked="checked" <?cs /if?><?cs
/if ?><?cs
/if ?> /><?cs
/def ?><?cs
@
Plain checkboxes always default to unchecked, as it is too hard to tell the
difference between unchecked and missing. If a hidden value were added, it
would be a little easier, but possibly inconsistent.
<<Generic ClearSilver HTML Macros>>=
def:checkbox(varn)
?><input type="checkbox" value="Y" name="<?cs var:varn ?>"<?cs
if:Query[varn] ?> checked="checked" <?cs /if ?>/><?cs
/def ?><?cs
@
Date widgets should really have a JavaScript calendar-based date selection
button, but instead they are currently just plain text widgets. However,
they are assigned an easy-to-identify class name to make adding the popup
with dynamic HTML easier.
<<Generic ClearSilver HTML Macros>>=
def:date(varn, def)
?><input type="text" class="datesel" size="12" name="<?cs var:varn ?>" value="<?cs
if: ?Query[varn] ?><?cs
var:Query[varn] ?><?cs
else ?><?cs
var:default ?><?cs
/if ?>" /><?cs
/def ?><?cs
@
Submit buttons display the value as the button text, so the value cannot be
used to determine the action. Instead, the parameter name is used. The
label is the configuration value of \texttt{labels.}\emph{action}, and the
parameter name is \texttt{action.}\emph{action}.
<<Generic ClearSilver HTML Macros>>=
def:submit(action)
?><input type="submit" name="action.<?cs var:action ?>" value="<?cs
var:labels[action] ?>" /><?cs
/def ?><?cs
@
Finally, a facility is provided for showing or hiding various HTML divisions
using a selection widget (aka drop-down menu). If JavaScript is not
supported by the browser, then all divisions will be displayed. The
selection widget itself should not be displayed, either, so it is rendered
using JavaScript. The less-than and greater-than symbols for the HTML tags
are also escaped, so that simplistic HTML parsers don't get confused. Note
that only one division set, and one selection widget are supported per page.
In order to remain independent of web servers, this could be included
entirely in-line. However, as a general rule, it is better to keep anything
more complex than a function call in a separate JavaScript file to avoid
quoting issues, and enable preparsing optimizations by the browser.
<<JavaScript Files>>=
html_prefix.js \
@
\lstset{language=C}
<<html_prefix.js>>=
function showdiv(divno)
{
var mydiv, i;
for(i = 1; (mydiv = document.getElementById('div' + i)); i++)
mydiv.style.display = divno == i ? "block" : "none";
}
@
\lstset{language=[ext]HTML}
<<Generic ClearSilver HTML Macros>>=
def:optdiv_onload()
?>showdiv(document.forms[0]._ignore.selectedIndex);<?cs /def ?><?cs
@
<<Generic ClearSilver HTML Macros>>=
def:optdiv_start() ?><script language="javascript" type="text/javascript">
//<![CDATA[
document.writeln('\x3Cselect name="_ignore" onchange="showdiv(this.value);"\x3E');
document.write('\x3Coption value="0"\x3E<?cs var:labels.optdiv ?>');
document.writeln('\x3C/option\x3E');<?cs /def ?><?cs
@
<<Generic ClearSilver HTML Macros>>=
def:optdiv_opt(n, v)
?>document.write('\x3Coption value="<?cs var:v ?>"\x3E<?cs var:n ?>');
document.writeln('\x3C/option\x3E');<?cs
/def ?><?cs
@
<<Generic ClearSilver HTML Macros>>=
def:optdiv_end()
?>document.writeln('\x3C/select\x3E');
//]]>
</script><?cs /def ?><?cs
@
This does require that yet another location must be chosen for installation.
The HTML can still be kept generic enough for easy run-time override of the
installation location.
\lstset{language=sed}
<<CGI Support Configuration>>=
# Location of JavaScript on the server
#server_script_path = /js
@
\lstset{language=make}
<<makefile.config>>=
# Installation directory for javascript files
JS_DIR:=/var/www/html/js
@
<<makefile.vars>>=
JS_FILES = <<JavaScript Files>>
@
<<Plain Files>>=
$(JS_FILES) \
@
<<Install other files>>=
mkdir -p $(DESTDIR)$(JS_DIR)
cp -p $(JS_FILES) $(DESTDIR)$(JS_DIR)
@
\lstset{language=[ext]HTML}
<<html_prefix.cs>>=
<script language="javascript" type="text/javascript" src="<?cs
alt:server_script_path ?>/js<?cs /alt ?>/html_prefix.js"></script>
@
\chapter{FastCGI Support}
FastCGI support is implemented using the mostly undocumented direct
functions of the [[libfcgi]] API. The standard I/O overrides are better
documented, but intrusively override many standard functions. There is no
standard method provided by [[libfcgi]] to find the libraries and include
files, so standard [[LDFLAGS]] and [[CFLAGS]] overrides must be used if
needed.
<<Library [[cs-supt]] Members>>=
cgi.o
@
\lstset{language=C}
<<Common C Includes>>=
<<CGI Prerequisite Headers>>
#include "cgi.h"
@
<<CGI Prerequisite Headers>>=
#include <fcgiapp.h>
@
<<cgi.h>>=
/*
<<Common NoWeb Warning>>
*/
#ifndef _CGI_H
#define _CGI_H
<<CGI Support Global Definitions>>
#endif /* _CGI_H */
@
<<cgi.c>>=
<<Common C Header>>
<<CGI Support Variables>>
<<CGI Support Functions>>
@
<<makefile.vars>>=
EXTRA_LDFLAGS += -lfcgi
@
Each FastCGI session is like an independent CGI program. This implies that
no global variables should be used; instead, a master state structure is
passed around.
<<CGI Support Global Definitions>>=
typedef struct cgi_state_t cgi_state_t;
<<CGI State Dependencies>>
struct cgi_state_t {
<<CGI State Members>>
};
@
<<Known Data Types>>=
cgi_state_t,%
@
The general program structure supported here is to perform global
initializations before the main loop, and in the main loop spawn a thread
for every incoming connection. The threads get the [[cgi_state_t]]
structure for the current CGI execution. An initialization function is
provided for the global initializations, and a generic main loop with a
callback is provided for spwan loop. The callback is called from within the
thread rather than as the main body of the thread so that cleanup is
automatic. That means that the callback must be stored in the CGI state for
the thread to call. In addition, a generic cleanup callback is provided;
this should be overridden using a statically stored chain for each overrider
to ensure that all cleaners are called. Calling from within the thread also
allows the return code from the callback to be used; if an error is
returned, that error is printed.
<<CGI Support Functions>>=
void init_cgi(void)
{
<<Perform global CGI support initialization>>
}
@
<<CGI State Dependencies>>=
struct cgi_state_t;
typedef NEOERR *(*cgi_callback_t)(struct cgi_state_t *cgi_state);
typedef void (*cgi_cleanup_cb)(struct cgi_state_t *cgi_state);
@
<<Known Data Types>>=
cgi_callback_t,cgi_cleanup_cb,%
@
<<CGI State Members>>=
cgi_callback_t callback;
cgi_cleanup_cb cleanup;
@
<<CGI Support Functions>>=
static void *run_cgi_thread(void *_state)
{
cgi_state_t *cgi_state = _state;
NEOERR *nerr = (*cgi_state->callback)(cgi_state);
if(cgi_state->cleanup)
(*cgi_state->cleanup)(cgi_state);
if(nerr != STATUS_OK) {
<<Display error from CGI callback>>
}
<<Clean up after CGI callback>>
return NULL;
}
@
<<CGI Support Functions>>=
void run_cgi(cgi_callback_t callback)
{
while(1) {
cgi_state_t *cgi_state;
<<Allocate CGI state>>
cgi_state->callback = callback;
<<Prepare for CGI thread>>
<<Spawn CGI thread>>
}
<<Wait for remaining CGI threads>>
}
@
The most obvious global initializations are the memory pool for the CGI
state structures, and the FastCGI subsystem.
<<Perform global CGI support initialization>>=
#if GLIB_MINOR_VERSION < 10 /* GMemChunk is deprecated */
state_pool = g_mem_chunk_create(cgi_state_t, 16, G_ALLOC_AND_FREE);
#endif
FCGX_Init();
@
Rather than spawn a thread every time, which is what FastCGI is meant to
avoid in the first place, a thread pool is used. The pool is generated in
non-exclusive mode to prevent all of them from being created at once. GLib
provides no control over how many idle threads to create initially. Only
the maximum number of threads is configurable.
<<CGI Support Variables>>=
static GThreadPool *cgi_thread_pool = NULL;
@
<<CGI Support Functions>>=
static void run_cgi_thread_pool(gpointer data, gpointer user_data)
{
run_cgi_thread(data);
}
@
\lstset{language=sed}
<<CGI Support Configuration>>=
# Maximum number of FastCGI threads
#max_cgi_threads = 64
@
\lstset{language=C}
<<Perform global CGI support initialization>>=
cgi_thread_pool = g_thread_pool_new(run_cgi_thread_pool, NULL,
getconf_int("max_cgi_threads", 64),
FALSE, NULL);
@
<<Spawn CGI thread>>=
g_thread_pool_push(cgi_thread_pool, cgi_state, NULL);
@
Keeping track of whether or not the threads are finished can be done several
ways. The simplest is to just keep a count; in fact, the count can be
retrieved from the pool. However, there is no signal associated with the
pool's thread count, so waiting for the pool to empty is not possible.
Instead, an integer thread counter is used, along with a lock and signal.
<<CGI Support Variables>>=
static pthread_mutex_t cgi_state_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cgi_state_sig = PTHREAD_COND_INITIALIZER;
static int cgi_thread_count = 0;
@
<<Spawn CGI thread>>=
pthread_mutex_lock(&cgi_state_lock);
++cgi_thread_count;
pthread_mutex_unlock(&cgi_state_lock);
@
<<Clean up after CGI callback>>=
pthread_mutex_lock(&cgi_state_lock);
--cgi_thread_count;
pthread_cond_signal(&cgi_state_sig);
pthread_mutex_unlock(&cgi_state_lock);
@
<<Wait for remaining CGI threads>>=
pthread_mutex_lock(&cgi_state_lock);
while(cgi_thread_count > 0)
pthread_cond_wait(&cgi_state_sig, &cgi_state_lock);
pthread_mutex_unlock(&cgi_state_lock);
@
Allocating a CGI state from a pool requries locking. The thread count lock
can be reused for this purpose.
<<CGI Support Variables>>=
#if GLIB_MINOR_VERSION < 10 /* GMemChunk is deprecated */
static GMemChunk *cgi_state_pool;
#endif
@
<<Allocate CGI state>>=
#if GLIB_MINOR_VERSION < 10 /* GMemChunk is deprecated */
pthread_mutex_lock(&cgi_state_lock);
cgi_state = g_chunk_new0(cgi_state_t, cgi_state_pool);
pthread_mutex_unlock(&cgi_state_lock);
#else
cgi_state = g_slice_new0(cgi_state_t);
#endif
@
<<Clean up after CGI callback>>=
<<Free CGI state members>>
#if GLIB_MINOR_VERSION < 10 /* GMemChunk is deprecated */
pthread_mutex_lock(&cgi_state_lock);
g_chunk_free(cgi_state, cgi_state_pool);
pthread_mutex_unlock(&cgi_state_lock);
#else
g_slice_free(cgi_state_t, cgi_state);
#endif
@
Since FastCGI programs are so similar to regular CGI programs, they should
be expected to fall back to normal CGI behavior if invoked without FastCGI
enabled. To support this, a global flag is used to distinguish the
execution types, as well as macros to select the appropriate input and
output funtions.
<<Common C Includes>>=
#include <stdarg.h>
@
<<CGI Support Global Definitions>>=
extern gboolean is_cgi;
#define cgi_puts(x) (is_cgi ? fputs(x, stdout) : \
FCGX_PutS(x, cgi_state->req.out))
#define cgi_putc(x) (is_cgi ? putchar(x) : \
FCGX_PutChar(x, cgi_state->req.out))
#define cgi_status(x) do { \
if(!is_cgi) \
FCGX_SetExitStatus(x, cgi_state->req.out); \
} while(0)
#define cgi_raw_gets(x, l) (is_cgi ? fgets(x, l, stdin) : \
FCGX_GetLine(x, l, cgi_state->req.in))
#define cgi_raw_read(x, l) (is_cgi ? fread(x, 1, l, stdin) : \
FCGX_GetStr(x, l, cgi_state->req.in))
#define cgi_write(x, l) (is_cgi ? fwrite(x, 1, l, stdout) : \
FCGX_PutStr(x, l, cgi_state->req.out))
#define cgi_getenv(x) (is_cgi ? getenv(x) : \
FCGX_GetParam(x, cgi_state->req.envp))
#define cgi_printf(f, ...) (is_cgi ? printf(f, __VA_ARGS__) : \
FCGX_FPrintF(cgi_state->req.out, f, \
__VA_ARGS__))
#define cgi_vprintf(f, a) (is_cgi ? vprintf(f, a) : \
FCGX_VFPrintF(cgi_state->req.out, f, a))
@
<<C Prototypes>>=
int cgi_puts(const char *str);
int cgi_putc(char c);
int cgi_write(const char *buf, int length);
int cgi_printf(const char *format, ...);
int cgi_vprintf(const char *fmt, va_list parms);
void cgi_status(int stat);
int cgi_raw_gets(char *buf, int length);
int cgi_raw_read(char *buf, int length);
const char *cgi_getenv(const char *name);
@
<<CGI Support Variables>>=
gboolean is_cgi;
@
<<Perform global CGI support initialization>>=
is_cgi = FCGX_IsCGI();
if(debug && is_cgi)
setbuf(stdout, NULL);
@
<<Spawn CGI thread>>=
if(is_cgi)
break;
@
Unfortunately, not all operations are possible in threads. In particular,
if there is a need to change the process identity via [[setuid]](2) or
similar functions, POSIX threads will change the identity for all threads in
the process at the same time. Older Linux versions were buggy in that
respect and in fact provided separate identities per thread, and in fact may
still do so via [[setfsuid]](2), but programs should not depend on buggy
behavior or Linux-specific functions that may not even be exposed in the C
library.
Rather than maintain a separate process pool, it is expected that the
callback will do a fork and wait for the subprocess to finish. A simple
wrapper function is provided to make implementation easier. The wrapper
will return [[TRUE]] if the child code is to be executed. It will not call
[[fork]] for single-run CGI programs.
<<Common C Includes>>=
#include <sys/wait.h>
@
<<CGI Support Functions>>=
gboolean cgi_fork(cgi_state_t *cgi_state)
{
pid_t child_pid = is_cgi ? 0 : fork();
if(child_pid < 0) {
cgi_neo_error(cgi_state->cgi, nerr_raise_msg_errno("fork"));
} else if(child_pid) {
while(waitpid(child_pid, NULL, 0) < 0) {
if(errno != EINTR && errno != EAGAIN) {
cgi_neo_error(cgi_state->cgi, nerr_raise_msg_errno("fork"));
break;
}
}
}
return !child_pid;
}
@
Sometimes it may be useful to print strings escaped. Rather than allocating
a string, escaping into that memory, and then printing and freeing that
memory, these functions print their parameters escaped. These functions are
not in any which way Unicode compatible.
<<CGI Support Functions>>=
NEOERR *cgi_puts_url_escape(cgi_state_t *cgi_state, const char *s)
{
const char *e;
while(*s) {
for(e = s; *e && (isalnum(*e) || *e == '.' || *e == '-' ||
*e == '_' ||*e == '~'); e++);
if(e != s)
if(cgi_write(s, (int)(e - s)) <= 0)
return nerr_raise_errno(NERR_IO, "CGI Write");
if(*e == ' ') {
if(cgi_putc('+') == EOF)
return nerr_raise_errno(NERR_IO, "CGI Write");
} else
if(cgi_printf("%%%02X", (int)*e) <= 0)
return nerr_raise_errno(NERR_IO, "CGI Write");
s = e + 1;
}
return STATUS_OK;
}
@
<<CGI Support Functions>>=
NEOERR *cgi_puts_html_escape(cgi_state_t *cgi_state, const char *s,
gboolean is_js)
{
const char *e;
int ret;
while(*s) {
for(e = s; *e && (isgraph(*e) || *e == ' ' || *e == '\n') &&
*e != '<' && *e != '>' && *e != '&' && *e != '"' && *e != '\'' &&
(*e != '\\' || !is_js);
e++);
if(e != s)
if(cgi_write(s, (int)(e - s)) < 0)
return nerr_raise_errno(NERR_IO, "CGI Write");
if(!*e)
break;
if(*e == '<')
ret = cgi_puts("<");
else if(*e == '>')
ret = cgi_puts(">");
else if(*e == '&')
ret = cgi_puts("&");
#if 0 /* " shorter & more portable than " - same for ' and ' */
else if(*e == '"')
ret = cgi_puts(""");
else if(*e == '\'')
ret = cgi_puts("'");
#endif
else if(*e == '\\')
ret = cgi_puts("\\\\");
else
ret = cgi_printf("&#%02X;", (int)*e) - 1; /* <= 0, not just < 0 -> err */
if(ret < 0)
return nerr_raise_errno(NERR_IO, "CGI Write");
s = e + 1;
}
return STATUS_OK;
}
@
For building strings, GLib provides [[g_string_append_uri_escaped]], but no
equivalent for HTML escaping. Actually, before $2.16$, it does not provide
either. Since for most uses, the default behavior is fine, no support is
provided for [[reserved_chars_allowed]] or [[allow_utf8]] in the
reimplementation of [[g_string_append_uri_escaped]].
<<CGI Support Functions>>=
GString *g_string_append_html_escaped(GString *buf, const char *s,
gboolean is_js)
{
const char *e;
while(*s) {
for(e = s; *e && isgraph(*e) &&
*e != '<' && *e != '>' && *e != '&' && *e != '"' && *e != '\'' &&
(*e != '\\' || !is_js);
e++);
if(e != s)
g_string_append_len(buf, s, (int)(e - s));
if(!*e)
break;
if(*e == '<')
g_string_append(buf, "<");
else if(*e == '>')
g_string_append(buf, ">");
else if(*e == '&')
g_string_append(buf, "&");
#if 0 /* " shorter & more portable than " - same for ' and ' */
else if(*e == '"')
g_string_append(buf, """);
else if(*e == '\'')
g_string_append(buf, "'");
#endif
else if(*e == '\\')
g_string_append(buf, "\\\\");
else
g_string_append_printf(buf, "&#%02X;", (int)*e);
s = e + 1;
}
return buf;
}
@
<<CGI Support Functions>>=
#if !GLIB_CHECK_VERSION(2,16,0)
GString *g_string_append_uri_escaped(GString *buf, const char *s,
const char *reserved,
gboolean utf8)
{
const char *e;
while(*s) {
for(e = s; *e && (isalnum(*e) || *e == '.' || *e == '-' ||
*e == '_' ||*e == '~'); e++);
if(e != s)
g_string_append_len(buf, s, (int)(e - s));
if(*e == ' ')
g_string_append_c(buf, '+');
else
g_string_append_printf(buf, "%%%02X", (int)*e);
s = e + 1;
}
return buf;
}
#endif
@
JSON encoding is provided already for strings, but converting to a string
before writing to CGI output may be inefficient for large objects and
arrays. For this reason, a function is provided to use the string version
for the leaf values, but to output the object and array delimiters directly.
This limits the total size of dynamically allocated string buffers. Since
reading JSON from a CGI stream will never happen (CGI input is always parsed
as CGI parameters), no equivalent input function is provided.
<<CGI Support Functions>>=
NEOERR *cgi_output_json(cgi_state_t *cgi_state, HDF *hdf)
{
GString *buf;
NEOERR *nerr = STATUS_OK;
#define io_nerr_op(op) do { \
if(nerr == STATUS_OK && op < 0) \
nerr = nerr_raise_msg_errno("JSON output"); \
} while(0)
if(hdf_obj_child(hdf)) {
json_var_type vt = hdf_json_var_type(hdf);
if(vt == JSON_ARRAY) {
char c = '[';
hdf_sort_obj(hdf, comp_hdf_name);
for(hdf = hdf_obj_child(hdf); hdf; hdf = hdf_obj_next(hdf)) {
io_nerr_op(cgi_putc(c));
c = ',';
nerr_op(cgi_output_json(cgi_state, hdf));
}
io_nerr_op(cgi_putc(']'));
} else {
buf = g_string_new("");
char c = '{';
for(hdf = hdf_obj_child(hdf); hdf; hdf = hdf_obj_next(hdf)) {
io_nerr_op(cgi_putc(c));
c = ',';
g_string_truncate(buf, 0);
append_unicode_quoted(buf, hdf_obj_name(hdf));
io_nerr_op(cgi_puts(buf->str));
io_nerr_op(cgi_putc(':'));
nerr_op(cgi_output_json(cgi_state, hdf));
}
io_nerr_op(cgi_putc('}'));
g_string_free(buf, TRUE);
}
return nerr;
}
buf = g_string_new("");
g_string_append_json(buf, hdf);
cgi_puts(buf->str);
g_string_free(buf, TRUE);
return nerr;
}
@
Any errors that occur should be printed to the user, but not with the
standard error reporting mechanism. Instead, they should be reported via
the CGI output stream. Unfortunately, that is impossible during initial
setup for FastCGI programs, so a dummy [[NULL]] CGI state indicates that
regular output should be used instead. If the CGI state exists, it is
assumed that the call is from a NEOERR returning function, so the error is
simply returned. This breaks usage in the mainline even though it never
gets invoked, so [[DIE_IF_ERR]] is toggled from the error to a static 1 in
the mainline. Once an error is returned from the primary callback, it is
displayed to the user.
<<CGI Message Overrides>>=
#undef die_if_err
#define die_if_err(err) do { \
NEOERR *_err = err; \
\
if(_err != STATUS_OK) { \
if(cgi_state) \
return DIE_IF_ERR; \
else if(!is_cgi) \
nerr_log_error(_err); \
else \
cgi_log_error_stdout(_err); \
exit(1); \
} \
} while(0)
#define DIE_IF_ERR _err
@
<<CGI Support Functions>>=
<<CGI Message Overrides>>
@
<<CGI Mainline Variables>>=
<<Common Mainline Variables>>
cgi_state_t *cgi_state unused_attr = NULL;
#undef DIE_IF_ERR
#define DIE_IF_ERR 1
@
<<CGI Per-Run Variables>>=
<<Common Mainline Variables>>
@
The error itself is printed as HTML or HTTP text, from a template. The HTTP
header can be suppressed by setting the [[header_printed]] variable to
non-blank in the CGI state's HDF. The default status of 500 can also be
overridden by setting the [[error_status]] variable. The text to print can
also be overridden by a template by setting the [[error_tmpl]] variable,
which may use the error text in [[error_text]]. If the HTML tags have
already been printed, the XML will become invalid, and if they haven't, the
document type will not be printed. In either case, most browsers will print
the message anyway, and don't care. Note that in addition to the ability to
override the header, this differs from the standard kit's [[cgi_neo_error]]
in that it will HTML-escape the message.
<<CGI Support Functions>>=
void cgi_log_error_stdout(NEOERR *nerr)
{
is_cgi = TRUE;
cgi_log_error(nerr, NULL, local_config);
}
void cgi_log_error(NEOERR *nerr, cgi_state_t *cgi_state, HDF *hdf)
{
cgi_state_t _cgi_state;
if(!cgi_state) {
cgi_state = &_cgi_state;
cgi_state->hdf = hdf;
}
if(!*cgi_env_val("header_printed", "")) {
const char *status = cgi_env_val("error_status", NULL);
if(!status || !*status)
status = "500 Internal Server Error";
cgi_status(atoi(status));
cgi_puts("Content-type: text/html\nStatus: ");
cgi_puts(status);
cgi_puts("\n\n");
}
<<Convert [[nerr]] to [[err_str]]>>
const char *tmpl = cgi_env_val("error_tmpl", NULL);
if(tmpl && *tmpl) {
NEOERR *nerr2 = cgi_env_set("error_text", err_str.buf);
if(nerr2 == STATUS_OK)
nerr2 = tmpl_to_cgi(tmpl, cgi_state, FALSE);
if(nerr2 != STATUS_OK) {
tmpl = NULL;
nerr_ignore(&nerr2);
}
}
if(!tmpl || !*tmpl) {
cgi_puts("<html><body>An error occurred:<pre>\n");
cgi_puts_html_escape(cgi_state, err_str.buf, FALSE);
cgi_puts("</pre></body></html>");
}
string_clear(&err_str);
}
@
<<Display error from CGI callback>>=
cgi_log_error(nerr, cgi_state, NULL);
@
\lstset{language=sed}
<<CGI Support Configuration>>=
# Set to non-blank to override message to print on errors
# This is evaluated as a ClearSilver template in the CGI environment; the
# text of the error message is in the error_text variable.
# The default message prints:
# <html><body><h3>An error occurred while processing your request:</h3><pre>
# <?cs var:error_text ?></pre></body></html>
#error_tmpl = <html><body><h3>An error occurred while processing ...
# Set to non-blank to override the status to return on errors
#error_status = 500 Internal Server Error
# Set to non-blank to disable printing the HTTP header for error messages
# This is usually set by any template which prints an HTTP header.