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