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