Resource/config system used by the gateway.
[egate.git] / www / wcgi.c
1 /*
2  * Copyright (c) 1995, the EUROPAGATE consortium (see below).
3  *
4  * The EUROPAGATE consortium members are:
5  *
6  *    University College Dublin
7  *    Danmarks Teknologiske Videnscenter
8  *    An Chomhairle Leabharlanna
9  *    Consejo Superior de Investigaciones Cientificas
10  *
11  * Permission to use, copy, modify, distribute, and sell this software and
12  * its documentation, in whole or in part, for any purpose, is hereby granted,
13  * provided that:
14  *
15  * 1. This copyright and permission notice appear in all copies of the
16  * software and its documentation. Notices of copyright or attribution
17  * which appear at the beginning of any file must remain unchanged.
18  *
19  * 2. The names of EUROPAGATE or the project partners may not be used to
20  * endorse or promote products derived from this software without specific
21  * prior written permission.
22  *
23  * 3. Users of this software (implementors and gateway operators) agree to
24  * inform the EUROPAGATE consortium of their use of the software. This
25  * information will be used to evaluate the EUROPAGATE project and the
26  * software, and to plan further developments. The consortium may use
27  * the information in later publications.
28  * 
29  * 4. Users of this software agree to make their best efforts, when
30  * documenting their use of the software, to acknowledge the EUROPAGATE
31  * consortium, and the role played by the software in their work.
32  *
33  * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND,
34  * EXPRESS, IMPLIED, OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
35  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
36  * IN NO EVENT SHALL THE EUROPAGATE CONSORTIUM OR ITS MEMBERS BE LIABLE
37  * FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF
38  * ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
39  * OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND
40  * ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
41  * USE OR PERFORMANCE OF THIS SOFTWARE.
42  *
43  * $Log: wcgi.c,v $
44  * Revision 1.16  1996/02/12 10:10:29  adam
45  * Resource/config system used by the gateway.
46  *
47  * Revision 1.15  1996/01/26  09:02:20  adam
48  * Open of client FIFO called with O_NDELAY when reconnecting to shell
49  * in order to prevent serious lock if previous shell died without
50  * unlinking client FIFO.
51  *
52  * Revision 1.14  1996/01/12  13:08:06  adam
53  * CGI script passes name of lock file to the shell. The server will not close
54  * the response FIFO until this file becomes unlocked. This method handles
55  * cancel operations much better.
56  *
57  * Revision 1.13  1996/01/12  10:05:17  adam
58  * If script name ends with ';' HTTP/GET/Expires will be defined.
59  * The cgi interface only reads final handshake if response from
60  * server (shell) was zero-terminated [If it isn't it probably died].
61  *
62  * Revision 1.12  1996/01/09  10:46:49  adam
63  * New defines: LOGDIR/EGWDIR/CGIDIR set in Makefile.
64  *
65  * Revision 1.11  1996/01/08  08:42:19  adam
66  * Handles method GET.
67  *
68  * Revision 1.10  1996/01/05  16:21:20  adam
69  * Bug fix: shell (wproto) sometimes closed server FIFO before cgi
70  * program opened it - solution: cgi sends OK when response has been read.
71  *
72  * Revision 1.9  1995/12/20  16:31:33  adam
73  * Bug fix: shell might terminate even though new request was initiated
74  * by the cgi interface program.
75  * Work on more simple user interface and Europagate buttons.
76  *
77  * Revision 1.8  1995/11/08  16:14:35  adam
78  * Many improvements and bug fixes.
79  * First version that ran on dtbsun.
80  *
81  * Revision 1.7  1995/11/08  12:42:18  adam
82  * Added descriptive text field in target info.
83  * Added authentication field in target info.
84  *
85  * Revision 1.6  1995/11/06  17:44:22  adam
86  * State reestablised when shell restarts. History of previous
87  * result sets.
88  *
89  * Revision 1.5  1995/11/06  10:51:15  adam
90  * End of response marker in response from wsh/wproto to wcgi.
91  * Shells are respawned when necessary.
92  *
93  * Revision 1.4  1995/11/02  16:35:37  adam
94  * Bug fixes and select on FIFOs in wcgi - doesn't really work!
95  *
96  * Revision 1.3  1995/10/31  16:56:24  adam
97  * Record presentation.
98  *
99  * Revision 1.2  1995/10/23  16:55:36  adam
100  * A lot of changes - really.
101  *
102  * Revision 1.1  1995/10/20  11:49:25  adam
103  * First version of www gateway.
104  *
105  */
106
107 #include <stdio.h>
108 #include <stdlib.h>
109 #include <unistd.h>
110 #include <fcntl.h>
111 #include <sys/stat.h>
112 #include <sys/time.h>
113 #include <sys/types.h>
114 #ifdef AIX
115 #include <sys/select.h>
116 #endif
117
118 #define DEADSTRING "Your database server has terminated. To reactivate \
119 the server, please reload the server's 'front page'."
120
121 #include <gw-db.h>
122 #include <gw-res.h>
123 #include "wproto.h"
124
125 static char *prog = "cgi";
126
127 static char serverp[256] = {'\0'};
128 static char serverf[256] = {'\0'};
129 static GW_DB gw_db = NULL;
130
131 static void fatal(char *p)
132 {
133     printf("Content-type: text/html\n\n<HTML><HEAD><TITLE>Server Failure</TITLE></HEAD>\n");
134     printf("<BODY>%s</BODY>\n", p);
135     if (gw_db)
136         gw_db_close (gw_db);
137     if (*serverp)
138         unlink (serverp);
139     if (*serverf)
140         unlink (serverf);
141     exit(0);
142 }
143
144 static int spawn (char *sprog, int id)
145 {
146     int r;
147     char path[256];
148     char envstr[80];
149
150     sprintf (envstr, "GWID=%d", id);
151     putenv (envstr);
152     sprintf(path, "%s/%s", EGWDIR, sprog);
153     switch(r = fork())
154     {
155         case -1: 
156             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "fork"); 
157             exit(1);
158         case 0: 
159             close (0);
160             close (1);
161             close (2);
162             gw_log (GW_LOG_DEBUG, prog, "execl %s", path);
163             execl (path, sprog, 0); 
164             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "execl %s", path);
165             exit(0);
166         default: 
167             return r;
168     }
169 }
170
171 #if 0
172 static void print_environ (void)
173 {
174     extern char **environ;
175     int i;
176
177     for (i = 0; environ[i]; i++)
178         gw_log (GW_LOG_DEBUG, prog, "e: %s", environ[i]);
179 }
180 #endif
181
182 /*
183  * NOTE: In the (perhaps odd) terminology used within this software,
184  * the 'server' is the present program, which is executed by the httpd
185  * server. The 'client' is the process running outside.
186  * Protocol is long(len)<serverfifo>\0<extrapath>\0<envvars>\0<INFO>\0
187  */
188 int main()
189 {
190     char clientp[256], *path_info, *p, *operation, *t;
191     char combuf[COMBUF];
192     const char *fifoDir;
193     GwRes cgiRes;
194     int serverf_fd = -1;
195     int linein = -1, lineout, data, gw_id;
196
197     if (chdir (EGWDIR))
198         fatal ("Couldn't change directory to " EGWDIR);
199     gw_log_init ("egw");
200     gw_log_file (GW_LOG_ALL, "egwcgi_log");
201 #if 0
202     gw_log_level (GW_LOG_ALL);
203 #endif
204     gw_log_session (getpid());
205     gw_log (GW_LOG_STAT, prog, "Europagate www cgi server");
206     cgiRes = gw_res_init ();
207     gw_res_merge (cgiRes, "egw.res");
208
209 #if 1
210     gw_log_level (gw_log_mask_str (
211                   gw_res_get (cgiRes, "log.level", "default")));
212 #endif
213     fifoDir = gw_res_get (cgiRes, "fifo.dir", "/tmp/egw");
214     
215     /* Create fifo directory if it doesn't exist already */
216     if (access(fifoDir, R_OK|W_OK) < 0 && mkdir(fifoDir, 0777) < 0)
217     {
218         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "Failed to create %s",
219                 fifoDir);
220         fatal("Internal error in server.");
221     }
222     /* Delete server FIFO if it does exist */
223     sprintf(serverp, "%s/srv%d", fifoDir, getpid());
224     if (access(serverp, R_OK|W_OK) == 0)
225     {
226         if (unlink(serverp) < 0)
227         {
228             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog,
229                     "Failed to delete stale fifo.");
230             fatal("Internal error in server.");
231         }
232         else
233             gw_log (GW_LOG_WARN, prog, "Removed stale server fifo.");
234     }
235     /* Make server FIFO */
236     if (mkfifo(serverp, 0666 | S_IFIFO) < 0)
237     {
238         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "mkfifo(%s)", serverp);
239         fatal("Internal error in server.");
240     }
241     /* The httpd server must pass PATH_INFO */
242     if (!(path_info = getenv("PATH_INFO")))
243     {
244         gw_log (GW_LOG_FATAL, prog, "Must set PATH_INFO.");
245         fatal("Internal error in server.");
246     }
247     /* Create lock file that ensures the server (shell) doesn't */
248     /* terminate before we have read the whole response */
249     sprintf (serverf, "%s/srf%d", fifoDir, getpid ());
250     gw_log (GW_LOG_DEBUG, prog, "open w %s", serverf);
251     serverf_fd = open (serverf, O_WRONLY|O_CREAT|O_TRUNC, 0666);
252     if (serverf_fd == -1)
253     {
254         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "open (%s)", serverf);
255         fatal("Internal error in server.");
256     }
257     else
258     {
259         struct flock area;
260         area.l_type = F_WRLCK;
261         area.l_whence = SEEK_SET;
262         area.l_start = 0L;
263         area.l_len = 0L;
264         fcntl (serverf_fd, F_SETLK, &area);
265     }
266     /* Read first part of path_info. Either it is a numeric session id */
267     /* or it is the name of a backend shell. */
268     operation = ++path_info;
269     while (*path_info && *path_info != '/')
270         path_info++;
271     if (*path_info)
272         *(path_info++) = '\0';
273     gw_log (GW_LOG_DEBUG, prog, "www.db open");
274     if (!(gw_db = gw_db_open (EGWDIR "/www.db", 1, 1)))
275     {
276         gw_log (GW_LOG_FATAL, prog, "gw_db_open");
277         exit (1);
278     }
279     gw_log (GW_LOG_DEBUG, prog, "www.db ok");
280     /* Is operation a backend shell (new session) ? */
281     if ((gw_id = atoi(operation)) <= 0)
282     {
283         int r;
284         char gw_id_str[16];
285
286         /* Get new unique id */
287         gw_id = gw_db_seq_no (gw_db);
288         sprintf (gw_id_str, "%d", gw_id);
289        
290         /* Spawn backend shell (server) */ 
291         spawn(operation, gw_id);
292         r = gw_db_insert (gw_db, gw_id_str, strlen(gw_id_str)+1,
293                           operation, strlen(operation)+1);
294         if (r)
295         {
296             gw_log (GW_LOG_FATAL, prog, "gw_db_insert: %d", r);
297             gw_db_close (gw_db);
298             exit (1);
299         }
300         gw_log (GW_LOG_DEBUG, prog, "Synchronizing with client");
301         if ((linein = open(serverp, O_RDONLY)) < 0)
302         {
303             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "open r %s", serverp);
304             fatal("Internal error in server.");
305         }
306         if (read(linein, combuf, 2) < 2 || strcmp(combuf, "OK"))
307         {
308             gw_log (GW_LOG_FATAL, prog, "Failed to synchronize with client");
309             fatal("Internal error in server");
310         }
311         gw_log (GW_LOG_DEBUG, prog, "Synchronized");
312         sprintf(clientp, "%s/clt%d", fifoDir, gw_id);
313         gw_log (GW_LOG_DEBUG, prog, "open w %s", clientp);
314         lineout = open (clientp, O_WRONLY);
315     }
316     else /* A session is continued */
317     {
318         sprintf(clientp, "%s/clt%d", fifoDir, gw_id);
319         gw_log (GW_LOG_DEBUG, prog, "open w|n %s", clientp);
320         /* Open the FIFO in O_NDELAY-mode: This prevents blocking */
321         /* even though the shell died without unlinking the FIFO */
322         /* On the other hand, if the shell is running, it will never */
323         /* close this FIFO */
324         lineout = open (clientp, O_WRONLY|O_NDELAY);
325     }
326     /* If open of clientp failed, the shell is not running, so we */
327     /* invoke it again */
328     if (lineout < 0)
329     {
330         char gw_id_str[16];
331         void *sprog;
332         size_t sprog_size;
333         int r;
334
335         sprintf (gw_id_str, "%d", gw_id);
336         r = gw_db_lookup (gw_db, gw_id_str, strlen(gw_id_str)+1,  
337                           &sprog, &sprog_size);
338         if (r != 1)
339         {
340             gw_log (GW_LOG_FATAL, prog, "gw_db_lookup %s", gw_id_str);
341             fatal("Internal error in server");
342         }
343         gw_log (GW_LOG_DEBUG|GW_LOG_ERRNO, prog, "open r %s restart", clientp);
344         spawn (sprog, gw_id);
345         gw_log (GW_LOG_DEBUG, prog, "Synchronizing with client");
346         if ((linein = open(serverp, O_RDONLY)) < 0)
347         {
348             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "open %s", serverp);
349             fatal("Internal error in server");
350         }
351         if (read(linein, combuf, 2) < 2 || strcmp(combuf, "OK"))
352         {
353             gw_log (GW_LOG_FATAL, prog, "Failed to synchronize with client.");
354             fatal("Internal error in server");
355         }
356         gw_log (GW_LOG_DEBUG, prog, "Synchronized.");
357         if ((lineout = open(clientp, O_WRONLY)) < 0)
358         {
359             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "%s", clientp);
360             fatal("Internal error in server");
361         }
362     }
363     gw_db_close (gw_db);
364     gw_log (GW_LOG_DEBUG, prog, "Decoding user data");
365     p = combuf + sizeof(data);
366     strcpy (p, serverp);
367     p += strlen (p) + 1;
368     strcpy (p, serverf);
369     p += strlen (p) + 1;
370     strcpy (p, path_info);
371     gw_log (GW_LOG_STAT, prog, "P:%s", p);
372     p += strlen(p) + 1;
373     *(p++) = '\0';               /* no envvars tranferred at present */
374     if ((t = getenv("CONTENT_LENGTH")) && (data = atoi(t)) > 0)
375     {
376         int j, i = 0;
377         while (i < data)
378         {
379             j = read(0, p + i, data - i);
380             if (j == -1)
381             {
382                 gw_log (GW_LOG_ERRNO|GW_LOG_FATAL, prog,
383                         "Failed to read input");
384                 fatal("Internal error in server");
385             }
386             else if (j == 0)
387             {
388                 gw_log (GW_LOG_ERRNO, prog, "Failed to read input");
389                 fatal("Internal error in server");
390             }
391             i += j;
392         }
393     }
394     else if ((t = getenv("QUERY_STRING")))
395     {
396         strcpy (p, t);
397         data = strlen(p);
398     }
399     p[data] = '\0';
400     gw_log (GW_LOG_DEBUG, prog, "C:%s", p);
401     p += data+1;
402     data = (p - combuf);
403     memcpy(combuf, &data, sizeof(data));
404     gw_log (GW_LOG_DEBUG, prog, "Writing data");
405     if (write(lineout, combuf, data) < data)
406     {
407         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "write");
408         fatal("Internal server error");
409     }
410     if (linein < 0)
411     {
412         gw_log (GW_LOG_DEBUG, prog, "open r %s", serverp);
413         if ((linein = open(serverp, O_RDONLY)) < 0)
414         {
415             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "open %s", serverp);
416             fatal("Internal error in server");
417         }
418     }
419     gw_log (GW_LOG_DEBUG, prog, "Reading response");
420
421     while ((data = read(linein, combuf, COMBUF)) > 0)
422     {
423         gw_log (GW_LOG_DEBUG, prog, "Got %d bytes", data);
424         if (combuf[data-1] == '\0')
425             break;
426         if (write(1, combuf, data) < data)
427         {
428             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "write");
429             exit (1);
430         }
431     }
432     if (data < 0)
433     {
434         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "read");
435         exit (1);
436     }
437     if (data > 0)
438     {
439         if (close (serverf_fd))
440         {
441             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "close %s", serverf);
442         }
443         if (--data > 0)
444         {
445             if (write(1, combuf, data) < data)
446             {
447                 gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, prog, "write");
448                 exit (1);
449             }
450         }
451     }
452     gw_log (GW_LOG_DEBUG, prog, "Cleaning up.");
453     unlink (serverf);
454     close(linein);
455     unlink(serverp);
456     close(lineout);
457     return 0;
458 }