Bug fix: egw_enc failed on 8-bit chars.
[egate.git] / www / wproto.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: wproto.c,v $
44  * Revision 1.21  1996/05/23 15:53:11  adam
45  * Bug fix: egw_enc failed on 8-bit chars.
46  * New command: egw_parms.
47  *
48  * Revision 1.20  1996/05/21  14:53:04  adam
49  * Tcl command wform extented; options -raw and -exists added.
50  *
51  * Revision 1.19  1996/03/14  11:48:39  adam
52  * New function egw_prog that returns name of shell.
53  *
54  * Revision 1.18  1996/02/12  10:09:23  adam
55  * New parameter to wproto_init: directory root for the FIFOs (instead
56  * of using preprocessor defines FIFODIR/FIFOROOT).
57  *
58  * Revision 1.17  1996/01/26  09:02:22  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.16  1996/01/24  10:13:56  adam
64  * Bug fix: in function wo_write realloc is used only when memory is already
65  * allocated with malloc.
66  *
67  * Revision 1.15  1996/01/24  08:25:32  adam
68  * Buf fix: Uninitialized outbuffer_offset member.
69  *
70  * Revision 1.14  1996/01/12  13:08:07  adam
71  * CGI script passes name of lock file to the shell. The server will not close
72  * the response FIFO until this file becomes unlocked. This method handles
73  * cancel operations much better.
74  *
75  * Revision 1.13  1996/01/12  10:05:20  adam
76  * If script name ends with ';' HTTP/GET/Expires will be defined.
77  * The cgi interface only reads final handshake if response from
78  * server (shell) was zero-terminated [If it isn't it probably died].
79  *
80  * Revision 1.12  1996/01/05  16:35:02  adam
81  * Minor changes.
82  *
83  * Revision 1.11  1996/01/05  16:21:21  adam
84  * Bug fix: shell (wproto) sometimes closed server FIFO before cgi
85  * program opened it - solution: cgi sends OK when response has been read.
86  *
87  * Revision 1.10  1995/12/22  14:21:16  adam
88  * More work on scan. The search.egw script takes care of cached
89  * query page (doesn't always increment nextSetNo). To make new search set
90  * either 'New query' must be selected or the query page must be reloaded.
91  * The msearch script doesn't do this yet, however.
92  *
93  * Revision 1.9  1995/11/14  16:31:36  adam
94  * Temporary remove of ccl entry.
95  *
96  * Revision 1.8  1995/11/13  15:41:45  adam
97  * Arrow gifs.
98  * Gateway uses record element set names B(rief) and F(ull).
99  * Bug fix. Didn't save idAuthentication correctly.
100  *
101  * Revision 1.7  1995/11/10  14:47:32  adam
102  * Plus (+) characters automatically converted to space in forms.
103  * Work on search in multiple targets. Doesn't work well - yet.
104  * Presentation formats enhanced.
105  *
106  * Revision 1.6  1995/11/06  10:51:17  adam
107  * End of response marker in response from wsh/wproto to wcgi.
108  * Shells are respawned when necessary.
109  *
110  * Revision 1.5  1995/11/02  16:35:37  adam
111  * Bug fixes and select on FIFOs in wcgi - doesn't really work!
112  *
113  * Revision 1.4  1995/10/31  16:56:25  adam
114  * Record presentation.
115  *
116  * Revision 1.3  1995/10/27  15:12:10  adam
117  * IrTcl incorporated in the gateway.
118  * Better separation of script types.
119  * Z39.50 gateway scripts entered.
120  *
121  * Revision 1.2  1995/10/23  16:55:39  adam
122  * A lot of changes - really.
123  *
124  * Revision 1.1  1995/10/20  11:49:26  adam
125  * First version of www gateway.
126  *
127  */
128
129 #include <stdio.h>
130 #include <string.h>
131 #include <stdlib.h>
132 #include <sys/time.h>
133 #include <sys/types.h>
134 #include <sys/stat.h>
135 #include <fcntl.h>
136 #include <unistd.h>
137 #include <stdarg.h>
138 #include <ctype.h>
139 #include <errno.h>
140
141 #include "wproto.h"
142
143 static int wproto_dumpcache(WCLIENT wc, int level);
144 static int wproto_findcache(WCLIENT wc, char *name);
145 static void wproto_uncache(WCLIENT wc, int level);
146
147 static char *mod = "wproto";
148
149 void wo_write (WCLIENT wc, const char *s, size_t len)
150 {
151     if (wc->outbuffer_offset + len >= wc->outbuffer_size)
152     {
153         if (!wc->outbuffer)
154             wc->outbuffer = malloc (wc->outbuffer_size += 
155                ((len >= OUTBUFFER_CHUNK) ? len*2 : OUTBUFFER_CHUNK));
156         else
157             wc->outbuffer = realloc(wc->outbuffer, wc->outbuffer_size +=
158                ((len >= OUTBUFFER_CHUNK) ? len*2 : OUTBUFFER_CHUNK));
159     }
160     memcpy(wc->outbuffer + wc->outbuffer_offset, s, len);
161     wc->outbuffer_offset += len;
162 }
163
164 void wo_puts (WCLIENT wc, const char *s)
165 {
166     wo_write (wc, s, strlen(s));
167 }
168
169 void wo_printf (WCLIENT wc, const char *fmt, ...)
170 {
171     va_list ap;
172     char tmpbuf[4048];
173
174     va_start(ap, fmt);
175     vsprintf(tmpbuf, fmt, ap);
176     wo_puts(wc, tmpbuf);
177     va_end(ap);
178 }
179
180 void wo_clear (WCLIENT wc, const char *type)
181 {
182     wc->outbuffer_offset = 0;
183     if (type)
184         wo_printf(wc, "Content-type: %s\n\n", type);
185 }
186
187 int wo_puthtml (WCLIENT wc, char *name)
188 {
189     FILE *f; 
190     char ch;
191
192     wo_clear(wc, "text/html");
193     if (!(f = fopen(name, "r")))
194     {
195         wo_printf(wc, "<BR>Failed to open file: %s<BR>", name);
196         return 0;
197     }
198     while (ch = getc(f), !feof(f))
199     {
200         if (wo_putc(wc, ch) < 0)
201         {
202             fclose(f);
203             return -1;
204         }
205     }
206     fclose(f);
207     return 0;
208 }
209
210 int wo_flush(WCLIENT wc)
211 {
212     int wrote, towrite;
213
214     if (!(wc->outbuffer_offset))
215         return 0;
216     towrite = wc->outbuffer_offset;
217     wc->outbuffer_offset = 0;
218     for (;;)
219     {
220         int w_chunk;
221
222         w_chunk = towrite;
223         wrote = write(wc->lineout, wc->outbuffer + wc->outbuffer_offset,
224             w_chunk);
225         if (wrote <= 0)
226         {
227             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "write response");
228             return -1;
229         }
230         gw_log (GW_LOG_DEBUG, mod, "wrote %d bytes", wrote);
231         if (wc->cache_fd >= 0)
232             if (write(wc->cache_fd, wc->outbuffer + wc->outbuffer_offset,
233                 towrite) < 0)
234             {   
235                 gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "write cache");
236                 return -1;
237             }
238         towrite -= wrote;
239         if (!towrite)
240             break;
241         wc->outbuffer_offset += wrote;
242     }
243     wc->outbuffer_offset = 0;
244     return 0;
245 }
246
247 int wo_overflow(WCLIENT wc, char ch)
248 {
249     gw_log (GW_LOG_DEBUG, mod, "wo_overflow");
250     if (wo_flush(wc) < 0)
251         return -1;
252     return wo_putc(wc, ch);
253 }
254
255 int wo_finish(WCLIENT wc)
256 {
257     int fd;
258     gw_log (GW_LOG_DEBUG, mod, "wo_finish");
259
260     wo_putc (wc, 0);
261     if (wo_flush(wc) < 0)
262         return -1;
263
264     fd = open (wc->wf_serverf, O_RDONLY);
265     if (fd != -1)
266     {
267         struct flock area;
268         area.l_type = F_RDLCK;
269         area.l_whence = SEEK_SET;
270         area.l_start = 0L;
271         area.l_len = 0L;
272         fcntl (fd, F_SETLKW, &area);
273         close (fd);
274     }
275     close(wc->lineout);
276     wc->lineout = -1;
277     if (wc->cache_fd >= 0)
278     {
279         close(wc->cache_fd);
280         wc->cache_fd = -1;
281     }
282     return 0;
283 }
284
285 static void descramble(char *t, const char *o)
286 {
287     unsigned int v;
288
289     while (*o)
290     {
291         if (*o == '%' && isxdigit(*(o + 1)) && isxdigit(*(o + 2)))
292         {
293             sscanf(o + 1, "%2x", &v);
294             o += 3;
295             if (v == '+')
296                 *t = ' ';
297             else
298                 *t = (char) v;
299             t++;
300         }
301         else
302         {
303             if (*o == '+')
304                 *t = ' ';
305             else
306                 *t = *o;
307             t++;
308             o++;
309         }
310     }
311     *t = '\0';
312 }
313
314 static void decode_form(wform_data *form, char *buf)
315 {
316     int i = 0;
317     char *p;
318     char tmp[512];
319
320     while (*buf)
321     {
322         for (p = form[i].name; *buf && *buf != '='; buf++)
323             *(p++) = *buf;
324         *p = '\0';
325         if (*buf)
326             buf++;
327         for (p = tmp; *buf && *buf != '&'; buf++)
328             *(p++) = *buf;
329         *p = '\0';
330         descramble(form[i].value, tmp);
331         if (*buf)
332             buf++;
333         i++;
334     }
335     *form[i].name = '\0';
336 }
337
338 char *wgetval(WCLIENT wc, char *name)
339 {
340     int i;
341
342     for (i = 0; *wc->wf_data[i].name; i++)
343         if (!strcmp(name, wc->wf_data[i].name))
344             return wc->wf_data[i].value;
345     return 0;
346 }
347
348 int wproto_process(WCLIENT wc, int timeout)
349 {
350     int toread, rs, level;
351     char combuf[COMBUF], *p,*t;
352     fd_set input;
353     struct timeval to, *top;
354
355     for (;;)
356     {
357         gw_log (GW_LOG_DEBUG, mod, "process waiting for input.");
358         if (timeout > 0)
359         {
360             to.tv_usec = 0;
361             to.tv_sec = timeout;
362             top = &to;
363         }
364         else
365             top = 0;
366         FD_ZERO(&input);
367         FD_SET(wc->linein, &input);
368         /* go through select handle list */
369         while ((rs = select(wc->linein + 1, &input, 0, 0, top)) < 0 &&
370             errno == EINTR)
371             ;
372         if (rs < 0)
373         {
374             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "select");
375             return -1;
376         }
377         if (rs == 0)
378         {
379             gw_log (GW_LOG_STAT, mod, 
380                     "select %d second timeout.",
381                     timeout);
382             unlink (wc->wf_serverp);
383             return 0;
384         }
385         if (read(wc->linein, &toread, sizeof(toread)) < sizeof(toread))
386         {
387             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "wp_proc:len read failed");
388             exit(1);
389         }
390         toread -= sizeof(toread);
391         if (read(wc->linein, combuf, toread) < toread)
392         {
393             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "wp_proc: data read failed");
394             exit(1);
395         }
396         p = combuf;
397         for (t = wc->wf_serverp; (*t = *p); t++, p++);
398         p++;
399         for (t = wc->wf_serverf; (*t = *p); t++, p++);
400         p++;
401         for (t = wc->wf_script; *p && *p != '/'; t++, p++)
402             *t = *p;
403         *t = '\0';
404         if (*p)
405             p++;
406         decode_form (wc->wf_parms_var, p);
407         for (t = wc->wf_parms; (*t = *p); t++, p++);
408         p++;
409         p++;         /* we don't deal with envvars yet */
410         wc->raw_data = p;
411         decode_form(wc->wf_data, p);
412         if (wc->lineout < 0)
413         {
414             gw_log (GW_LOG_DEBUG, mod, "open %s", wc->wf_serverp);
415             if ((wc->lineout = open(wc->wf_serverp, O_WRONLY)) < 0)
416             {
417                 gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "open %s", 
418                         wc->wf_serverp);
419                 exit(1);
420             }
421         }
422         /* look in cache only if request carries no forms data. */
423         if (!*wc->wf_data[0].name && (level = wproto_findcache(wc,
424             wc->wf_parms)) >= 0)
425         {
426             gw_log (GW_LOG_DEBUG, mod, "wproto_dumpcache");
427             wproto_dumpcache(wc, level);
428             wo_finish(wc);
429             
430         }
431         else
432         {
433             return 1;
434         }
435     }
436 }
437
438 WCLIENT wproto_init (const char *fifoDir, const char *prog)
439 {
440     char *val, path2[256];
441     wclient_data *new;
442
443     gw_log (GW_LOG_DEBUG, mod, "wproto_init");
444     close(1);    /* release us from the wserver */
445     if (!(new = malloc(sizeof(*new))))
446     {
447         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "malloc");
448         exit (1);
449     }
450     if (!(val = getenv ("GWID")))
451     {
452         gw_log (GW_LOG_FATAL, mod, "GWID not set");
453         exit (1);
454     }
455     if (!(new->prog = malloc (strlen(prog)+1)))
456     {
457         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "malloc");
458         exit (1);
459     }
460     strcpy (new->prog, prog);
461     new->fifoDir = fifoDir;
462     new->id = atoi (val);
463     sprintf(new->path, "%s/clt%d", new->fifoDir, new->id);
464     if (mkfifo(new->path, 0666 | S_IFIFO) < 0)
465         gw_log (GW_LOG_WARN|GW_LOG_ERRNO, mod, "mkfifo(%s)", new->path);
466     gw_log (GW_LOG_DEBUG, mod, "Synchronizing with server.");
467     sprintf(path2, "%s/srv%d", new->fifoDir, getppid());
468     if ((new->lineout = open(path2, O_WRONLY)) < 0)
469     {
470         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "open out %s", path2);
471         exit(1);
472     }
473     if (write(new->lineout, "OK", 2) < 2)
474     {
475         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "write");
476         exit(1);
477     }
478     gw_log (GW_LOG_DEBUG, mod, "Synchronized.");
479     if ((new->linein = open(new->path, O_RDONLY)) < 0)
480     {
481         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "open input %s", new->path);
482         exit(1);
483     }
484     gw_log (GW_LOG_DEBUG, mod, "init. linein=%d lineout=%d",
485             new->linein, new->lineout);
486     /* we put a handle on this so we get a blocking read when no peer */
487     if (open(new->path, O_WRONLY | O_NDELAY) < 0)
488     {
489         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "open dummy %s", new->path);
490         exit(1);
491     }
492     new->outbuffer = 0;
493     new->outbuffer_size = 0;
494     new->outbuffer_offset = 0;
495     new->cache_level = -1;
496     new->cache_fd = -1;
497     return new;
498 }
499
500 static void wproto_uncache(WCLIENT wc, int level)
501 {
502     for (;wc->cache_level >= level; wc->cache_level--)
503         unlink(wc->cache[wc->cache_level].path);
504 }
505
506 void wproto_terminate(WCLIENT wc)
507 {
508     free (wc->prog);
509     close(wc->linein);
510     unlink(wc->path);
511     wproto_uncache(wc, 0);
512     free(wc);
513 }
514
515 int wproto_cache(WCLIENT wc, int level)
516 {
517     cache_data *p;
518
519     if (level > wc->cache_level + 1)
520     {
521         gw_log (GW_LOG_FATAL, mod, "Illegal cache level increment.");
522         exit(1);
523     }
524     wproto_uncache(wc, level);
525     p = &wc->cache[++wc->cache_level];
526     sprintf(p->path, "%s/csh%d.%d", wc->fifoDir, wc->id, level);
527     if ((wc->cache_fd = open(p->path, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0)
528     {
529         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "open %s", p->path);
530         return -1;
531     }
532     strcpy(p->name, wc->wf_parms);
533     return 0;
534 }
535
536 static int wproto_findcache(WCLIENT wc, char *name)
537 {
538     int i;
539
540     for (i = 0; i <= wc->cache_level; i++)
541         if (!strcmp(wc->cache[i].name, name))
542             return i;
543     return -1;
544 }
545
546 static int wproto_dumpcache(WCLIENT wc, int level)
547 {
548     int fd, rd;
549
550     gw_log (GW_LOG_STAT, mod, "Using Cache: %s", wc->cache[level].name);
551     if ((fd = open(wc->cache[level].path, O_RDONLY)) < 0)
552     {
553         gw_log (GW_LOG_FATAL, mod, "open (R) %s", wc->cache[level].path);
554         return -1;
555     }
556     while ((rd = read(fd, wc->outbuffer, OUTBUFFER_CHUNK)) > 0)
557         if (write(wc->lineout, wc->outbuffer, rd) < rd)
558         {
559             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "write toline");
560             return -1;
561         }
562     if (rd < 0)
563     {
564         gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, mod, "read");
565         return -1;
566     }
567     wproto_uncache(wc, level + 1);
568     return 0;
569 }