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