-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfcgi.c
123 lines (92 loc) · 2.4 KB
/
fcgi.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <assert.h>
#include <fcgi_stdio.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#define POST_CONTENT_TYPE "application/x-www-form-urlencoded"
lua_State *L;
// this is needed because libfcgi temporarily sets stdout
// to something else during a request, and lua can't see
// the change
static int fcgiPrint( lua_State *L )
{
const char *str = luaL_checkstring( L, 1 );
printf( "%s", str );
return 0;
}
void cleanup( int signal )
{
// if fcgi_shutdown.lua doesn't exist then
// lua_close is still called
( void ) luaL_dofile( L, "fcgi_shutdown.lua" );
lua_close( L );
}
int main( int argc, char *argv[] )
{
L = lua_open();
luaL_openlibs( L );
// SIGUSR1 is sent when the server is shutting down
signal( SIGUSR1, cleanup );
// register functions
lua_register( L, "print", fcgiPrint );
// put debug.traceback on the stack
lua_getglobal( L, "debug" );
lua_getfield( L, -1, "traceback" );
lua_remove( L, -2 );
// load init script
if( luaL_loadfile( L, "fcgi.lua" ) || lua_pcall( L, 0, 0, -2 ) )
{
printf( "Error loading fcgi.lua: %s\n", lua_tostring( L, -1 ) );
exit( 1 );
}
while( FCGI_Accept() >= 0 )
{
// POST parsing
char *postString = NULL;
char *contentLength = getenv( "CONTENT_LENGTH" );
if( contentLength )
{
size_t postLength = atoi( contentLength );
if( postLength != 0 )
{
char *contentType = getenv( "CONTENT_TYPE" );
if( contentType != NULL && strncmp( contentType, POST_CONTENT_TYPE, sizeof( POST_CONTENT_TYPE ) - 1 ) == 0 )
{
postString = malloc( postLength + 1 );
// if malloc fails then don't die completely
if( postString != NULL )
{
fread( postString, 1, postLength, stdin );
postString[ postLength ] = 0;
}
}
}
}
// call FCGI_Accept( postString ) in fcgi.lua
lua_getglobal( L, "FCGI_Accept" );
lua_pushstring( L, postString );
if( lua_pcall( L, 1, 0, -3 ) )
{
printf( "ERR: %s\n", lua_tostring( L, -1 ) );
}
if( postString != NULL )
{
free( postString );
}
// i don't understand why lua_gettop varies depending on
// whether lua_pcall fails but this damn well fixes it
while( lua_gettop( L ) != 1 )
{
lua_pop( L, 1 );
}
}
// this will get called when this is run as
// a CGI script but not as FCGI
cleanup( SIGUSR1 );
return EXIT_SUCCESS;
}