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