d472c264c8a22d8eb05410b7b3f6131dddc25c9f
[egate.git] / kernel / urp.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  */
44 /* Gateway kernel - User Request Processor
45  * Europagate, 1995
46  *
47  * $Log: urp.c,v $
48  * Revision 1.50  1996/03/01 16:09:30  adam
49  * New setting: gw.msg.replyto that sets Reply-To in user response.
50  *
51  * Revision 1.49  1996/03/01  14:25:28  adam
52  * Email gateway obeys 'Reply-To:' in header.
53  *
54  * Revision 1.48  1996/02/12  10:04:57  adam
55  * The gateway doesn't try to reconnect if it is already known that
56  * it will fail (connect_fail flag introduced).
57  *
58  * Revision 1.47  1996/01/18  13:54:48  adam
59  * Help <command> gives help information about individual commands.
60  * Status without arguments gives list of available predefined targets.
61  *
62  * Revision 1.46  1995/07/28  10:51:09  adam
63  * Bug fix: account from previous session had effect when new target command
64  * was executed.
65  *
66  * Revision 1.45  1995/07/20  08:20:24  adam
67  * Minor changes.
68  *
69  * Revision 1.44  1995/07/11  12:28:53  adam
70  * New functions ccl_token_simple and ccl_token_del used.
71  *
72  * Revision 1.43  1995/07/11  11:49:13  adam
73  * LINE_MAX renamed to STR_LINE_MAX.
74  *
75  * Revision 1.42  1995/07/03  12:59:29  adam
76  * New option for eti: -c dir to chdir before start.
77  * Setting change: gw.max.show defaults to 100.
78  *
79  * Revision 1.41  1995/07/03  08:20:18  adam
80  * More help information and better diagnostics.
81  *
82  * Revision 1.40  1995/05/23  08:13:00  adam
83  * Minor changes.
84  *
85  * Revision 1.39  1995/05/22  14:57:30  adam
86  * Next default record position also set by last p=... in show.
87  *
88  * Revision 1.38  1995/05/19  13:26:00  adam
89  * Bug fixes. Better command line options.
90  *
91  * Revision 1.37  1995/05/18  12:03:09  adam
92  * Bug fixes and minor improvements.
93  *
94  * Revision 1.36  1995/05/17  10:51:33  adam
95  * Added a few more error checks to the show command.
96  *
97  * Revision 1.35  1995/05/16  09:40:43  adam
98  * LICENSE. Setting of CCL token names (and/or/not/set) in read_kernel_res.
99  *
100  * Revision 1.34  1995/05/04  10:40:08  adam
101  * More work on Def-settings.
102  *
103  * Revision 1.33  1995/05/03  16:34:19  adam
104  * CCL def command, i.e. user definitions - saved as resource files.
105  *
106  * Revision 1.32  1995/05/03  07:37:46  adam
107  * CCL commands stop/continue implemented. New functions gw_res_{int,bool}
108  * are used when possible.
109  *
110  * Revision 1.31  1995/05/01  12:43:38  adam
111  * First work on resource monitor program.
112  *
113  * Revision 1.30  1995/04/20  16:10:47  adam
114  * Modified to work with non-blocking zass-api. Not using non-blocking
115  * facility yet.
116  *
117  * Revision 1.29  1995/04/19  16:01:58  adam
118  * Some hacks to get the FIFO communication work!! Isn't reliable.
119  * Resource gw.account added - default account info.
120  *
121  * Revision 1.28  1995/04/19  13:19:09  adam
122  * New command: account - for authentication.
123  *
124  * Revision 1.27  1995/04/19  10:46:19  adam
125  * Persistency works much better now. New command: status - history-like
126  *
127  * Revision 1.26  1995/04/19  07:31:12  adam
128  * First work on Z39.50 persistence.
129  *
130  * Revision 1.25  1995/04/17  09:34:33  adam
131  * Timeout (idletime) adjustable. Minor changes in kernel.
132  *
133  * Revision 1.24  1995/03/28  11:42:35  adam
134  * First use of string-queue utility.
135  *
136  * Revision 1.23  1995/03/28  08:01:28  adam
137  * FIFO existence is used to test for a running kernel.
138  *
139  * Revision 1.22  1995/03/27  12:51:05  adam
140  * New log level in use: GW_LOG_ERRNO.
141  *
142  * Revision 1.21  1995/03/27  08:24:04  adam
143  * First use of gip interface and gw-db.
144  * First work on eti program.
145  *
146  * Revision 1.20  1995/03/03  17:19:17  adam
147  * Smarter presentation. Bug fix in email header interpretation.
148  *
149  * Revision 1.19  1995/03/02  09:32:11  adam
150  * New presentation formats. f0=full, f1=brief, f2=mid
151  *
152  * Revision 1.18  1995/03/01  14:32:26  adam
153  * Better diagnostics. Default is, that only one database selected when
154  * several are known.
155  *
156  * Revision 1.17  1995/02/28  13:16:26  adam
157  * Configurable From: added.
158  *
159  * Revision 1.16  1995/02/23  10:08:20  adam
160  * Added logging of all user commands.
161  *
162  * Revision 1.15  1995/02/23  08:32:17  adam
163  * Changed header.
164  *
165  * Revision 1.13  1995/02/22  16:54:42  adam
166  * Qualifiers of LOC target updated. More logging messages.
167  *
168  * Revision 1.12  1995/02/22  15:51:51  adam
169  * Bug fix: swap of parameter number and offset in function present.
170  *
171  * Revision 1.11  1995/02/22  15:22:33  adam
172  * Much more checking of run-time state. Show command never retrieves
173  * more records than indicated by the previous search request. Help
174  * command available. The maximum number of records retrieved can be
175  * controlled now.
176  *
177  * Revision 1.10  1995/02/22  08:51:35  adam
178  * Output function can be customized in fml, which is used to print
179  * the reply to reply_fd.
180  *
181  * Revision 1.9  1995/02/21  17:46:21  adam
182  * Minor changes.
183  *
184  * Revision 1.8  1995/02/21  12:12:00  adam
185  * Diagnostic record with error info. observed.
186  *
187  * Revision 1.7  1995/02/20  21:16:20  adam
188  * FML support. Bug fixes. Profile for drewdb.
189  *
190  * Revision 1.6  1995/02/17  14:41:14  quinn
191  * Added simple display of records.
192  *
193  * Revision 1.5  1995/02/17  14:22:13  adam
194  * First steps of CCL show command. Not finished yet.
195  *
196  * Revision 1.4  1995/02/17  09:08:36  adam
197  * Reply with subject. CCL base command implemented.
198  *
199  * Revision 1.3  1995/02/16  18:35:09  adam
200  * First use of Zdist library. Search requests are supported.
201  * Present requests are not supported yet.
202  *
203  * Revision 1.2  1995/02/16  13:21:00  adam
204  * Organization of resource files for targets and conversion
205  * language implemented.
206  *
207  * Revision 1.1  1995/02/15  17:45:30  adam
208  * First version of email gateway kernel. Email requests are read
209  * from stdin. The output is transferred to an MTA if 'From' is
210  * found in the header - or stdout if absent. No Z39.50 client is used.
211  *
212  */
213
214 /*
215    Todo:
216      info/status (other name?)
217      better persistence diagnostics
218
219    Optional:
220      automatic information about target-aliases: name, query-support, etc.
221  */
222
223 #include <stdio.h>
224 #include <stdlib.h>
225 #include <assert.h>
226 #include <ctype.h>
227 #include <string.h>
228 #include <unistd.h>
229 #include <fcntl.h>
230
231 #include <lgets.h>
232 #include <ttyemit.h>
233 #include <strqueue.h>
234 #include "kernel.h"
235
236 static void present (const char *set, int offset, int number,
237                      struct ccl_token *format_token);
238
239 static char line_buf[STR_LINE_MAX+1];
240
241 static void put_esc_str (const char *s)
242 {
243     while (*s)
244         tty_emit (*s++);
245 }
246
247 int reopen_target (void)
248 {
249     const char *v;
250     if (info.zass)
251         gw_log (GW_LOG_WARN, KERNEL_LOG, "Zass free...");
252     gw_log (GW_LOG_DEBUG, KERNEL_LOG, "reopen_target");
253     info.zass = zass_open (info.hostname, info.port, NULL, /* complete */
254                            *info.account ? info.account : NULL);
255     if (!info.zass)
256     {
257         gw_log (GW_LOG_DEBUG, KERNEL_LOG, "Cannot connect to target %s:%d",
258                 info.hostname, info.port);
259         fprintf (reply_fd, "%s %s:%d\n", 
260                  gw_res_get (info.kernel_res, "gw.err.connect",
261                              "Cannot connect to target"),
262                  info.hostname, info.port);
263         info.connect_failed = 1;
264         return -1;
265     }
266     v = gw_res_get (info.kernel_res, "gw.description", NULL);
267     if (v)
268     {
269         put_esc_str (v);
270         fprintf (reply_fd, "\n");
271     }
272     fprintf (reply_fd, "%s %s:%d\n",
273              gw_res_get (info.kernel_res, "gw.msg.connect",
274                          "Connection established to"),
275              info.hostname, info.port);
276     if (*info.databases)
277         fprintf (reply_fd, "%s: %s\n",
278                  gw_res_get (info.kernel_res, "gw.msg.databases",
279                              "Available databases"),
280                  info.databases);
281     if (*info.database)
282         fprintf (reply_fd, "%s: %s\n",
283                  gw_res_get (info.kernel_res, "gw.msg.database",
284                              "Selected databases"),
285                  info.database);
286     if (info.setno >= 0)
287         fprintf (reply_fd, "set=%d\n", info.setno);
288     else
289         fprintf (reply_fd, "set=Default\n");
290     return 0;
291 }
292
293 struct command_word {
294     char *default_value;
295     char *resource_suffix;
296 };
297
298 static int command_search_str (struct command_word *tab, const char *cmd_name,
299                                int cmd_len, const char *resource_prefix)
300 {
301     int no = 1;
302
303     assert (resource_prefix);
304     assert (tab);
305     while (tab->default_value)
306     {
307         char *cp, command_names[60];
308         char resource_name[60];
309         const char *v;
310
311         sprintf (resource_name, "%s%s", resource_prefix,
312                  tab->resource_suffix);
313         v = gw_res_get (info.kernel_res, resource_name, tab->default_value);
314         assert (v);
315         strcpy (command_names, v);
316         cp = command_names;
317         while (1)
318         {
319             char *split;
320
321             if ((split = strchr (cp, ' ')))
322                 *split = '\0';
323             if (cmd_len == strlen(cp) &&
324                 !memcmp (cmd_name, cp, cmd_len))
325                 return no;
326             if (!split)
327                 break;
328             cp = split+1;
329         }        
330         no++;
331         tab++;
332     }
333     return 0;
334 }
335
336 static int command_search (struct command_word *tab, struct ccl_token *cmd,
337                            const char *resource_prefix)
338 {
339     return command_search_str (tab, cmd->name, cmd->len, resource_prefix);
340 }
341
342 static struct error_no_struct {
343     int no;
344     char *resource_name;
345 } error_ccl_tab[] = {
346 {  CCL_ERR_OK, "ok"},
347 {  CCL_ERR_TERM_EXPECTED, "term.expected" },
348 {  CCL_ERR_RP_EXPECTED, "rp.expected" },
349 {  CCL_ERR_SETNAME_EXPECTED, "setname.expected" },
350 {  CCL_ERR_OP_EXPECTED, "op.expected" },
351 {  CCL_ERR_BAD_RP, "bad.rp" },
352 {  CCL_ERR_UNKNOWN_QUAL, "unknown.qual" },
353 {  CCL_ERR_DOUBLE_QUAL, "double.qual" },
354 {  CCL_ERR_EQ_EXPECTED, "eq.expected" },
355 {  CCL_ERR_BAD_RELATION, "bad.relation" },
356 {  CCL_ERR_TRUNC_NOT_LEFT, "trunc.not.left" },
357 {  CCL_ERR_TRUNC_NOT_BOTH, "trunc.not.both" },
358 {  CCL_ERR_TRUNC_NOT_RIGHT, "trunc.not.right" },
359 {  0, NULL }
360 };
361
362 static char *error_no_search (struct error_no_struct *tab, int no)
363 {
364     struct error_no_struct *p = tab;
365     while (p->resource_name)
366     {
367         if (no == p->no)
368             return p->resource_name;
369         p++;
370     }
371     return NULL;
372 }
373
374 static int email_header (struct str_queue *sq,
375                          char *from_str, char *subject_str)
376 {
377     *from_str = '\0';
378     *subject_str = '\0';    
379     while (str_queue_deq (sq, line_buf, STR_LINE_MAX))
380     {
381         if (line_buf[0] == '\n')
382             return 0;
383         if (memcmp (line_buf, "From ", 5) == 0)
384             sscanf (line_buf+4, "%s", from_str);
385         if (memcmp (line_buf, "Reply-To: ", 10) == 0)
386             sscanf (line_buf+10, "%s", from_str);
387         if (memcmp (line_buf, "Subject: ", 9) == 0 &&
388             sscanf (line_buf+9, "%s", subject_str+1) == 1)
389             strcpy (subject_str, line_buf+9);
390     }
391     return 1;
392 }
393
394 static void help_general (void)
395 {
396     put_esc_str (gw_res_get (info.kernel_res, "gw.help.general",
397                              "Commands available in this service:\n"));
398 }
399
400 static struct command_word command_tab [] = 
401 {
402 {   "find",     "find"},
403 {   "show",     "show"},
404 {   "base",     "base" },
405 {   "help",     "help" },
406 {   "info",     "info" },
407 {   "continue", "continue" },
408 {   "status",   "status" },
409 {   "stop",     "stop" },
410 {   "target",   "target" },
411 {   "def",      "def" },
412 {   "account",  "account" },
413 {   NULL, NULL }
414 };
415
416
417 static int exec_help (struct ccl_token *list)
418 {
419     int no = 0;
420     static char *sep = "-------------------------------\\n";
421     if (list->kind != CCL_TOK_EOL)
422         no = command_search_str (command_tab, list->name, list->len,
423                                  "ccl.command.");
424     if (!no)
425         help_general ();
426
427     if (!no || no == 9)
428     {
429         put_esc_str (sep);
430         put_esc_str (gw_res_get (info.kernel_res, "gw.help.target",
431                                  "target <name> - selects a given target\n"));
432     }
433
434     if (!no || no == 3)
435     {
436         put_esc_str (sep);
437         put_esc_str (gw_res_get (info.kernel_res, "gw.help.base",
438                              "base <base>..  - selects databases\n"));
439     }
440
441     if (!no || no == 1)
442     {
443         put_esc_str (sep);
444         put_esc_str (gw_res_get (info.kernel_res, "gw.help.find",
445                                  "find <query>   - performs a search\n"));
446     }
447
448     if (!no || no == 2)
449     {
450         put_esc_str (sep);
451         put_esc_str (gw_res_get (info.kernel_res, "gw.help.show",
452                                  "show <spec>    - retrieves and displays "
453                                  "records\n"));
454     }
455
456     if (!no || no == 10)
457     {
458         put_esc_str (sep);
459         put_esc_str (gw_res_get (info.kernel_res, "gw.help.def",
460                                  "def <setting> <value> user definitons\n"));
461     }
462
463     if (!no || no == 11)
464     {
465         put_esc_str (sep);
466         put_esc_str (gw_res_get (info.kernel_res, "gw.help.account",
467                                  "account <str>    sets authentication\n"));
468     }
469
470     if (!no || no == 7)
471     {
472         put_esc_str (sep);
473         put_esc_str (gw_res_get (info.kernel_res, "gw.help.status",
474                                  "status           status information\n"));
475     }
476
477     return 0;
478 }
479
480 static void display_diag_error (int code, const char *addinfo)
481 {
482     static char str[20];
483
484     sprintf (str, "gw.bib1.diag.%d", code);
485     fprintf (reply_fd, "%s %d:\n %s: '%s'\n",
486              gw_res_get (info.kernel_res, "gw.msg.z39errcode", 
487                          "Z39.50 Error"),
488              code,
489              gw_res_get (info.kernel_res, str, ""), addinfo);
490 }
491
492 static int exec_find (struct ccl_token *list, const char *search_str)
493 {
494     const struct zass_searchent *p;
495     struct gw_user_set *us;
496     char setname[32];
497     int autoshow;
498
499     struct ccl_rpn_node *rpn;
500     int error;
501     const char *pos;
502
503     if (info.setno == -1)
504         strcpy (setname, "Default");
505     else
506         sprintf (setname, "%d", info.setno);
507     info.next_position = 1;
508     if (info.setno >= 0)
509         info.setno++;
510     rpn = ccl_find (info.bibset, list, &error, &pos);
511     if (!rpn)
512     {
513         const char *v = NULL, *n;
514         char name[128];
515
516         fprintf (reply_fd, "  %*s^ - ", pos - line_buf, " ");
517
518         n = error_no_search (error_ccl_tab, error);
519         if (n)
520         {
521             sprintf (name, "gw.err.%s", n);
522             v = gw_res_get (info.kernel_res, name, NULL);
523         }
524         if (!v)
525             v = ccl_err_msg (error);
526         fprintf (reply_fd, "%s\n", v);
527         return -1;
528     }
529     ccl_pr_tree (rpn, reply_fd);
530     fprintf (reply_fd, "\n");
531
532     if (!*info.database )
533     {
534         fprintf (reply_fd, "%s\n",
535                  gw_res_get (info.kernel_res, "gw.err.no.database",
536                              "You must select database"));
537         return -3;
538     }
539     gw_log (GW_LOG_DEBUG, KERNEL_LOG, "Searching in database %s",
540             info.database );
541     assert (info.zass);
542     p = zass_p_search (info.zass, rpn, setname, info.database, info.sets);
543     if (!p)
544     {
545         fprintf (reply_fd, "%s\n",
546                  gw_res_get (info.kernel_res, "gw.err.search.fail",
547                              "Search fail."));
548         return -1;
549     }
550     if (p->errcode != -1)
551     {
552         display_diag_error (p->errcode, p->errstring);
553         return -2;
554     }
555     fprintf (reply_fd, "%d %s %s\n", p->num,
556              gw_res_get (info.kernel_res, "gw.msg.hits", "hit(s) in set "),
557              setname);
558     us = user_set_add (setname, p->num, info.database, rpn, 1, search_str);
559     autoshow = gw_res_int (info.kernel_res, "gw.auto.show", 0);
560     if (autoshow && p->num > 0)
561     {
562         if (autoshow > p->num)
563         {
564             present (setname, 1, p->num, NULL);
565             info.next_position = 1+p->num;
566         }
567         else
568         {
569             present (setname, 1, autoshow, NULL);
570             info.next_position = 1+autoshow;
571         }
572     }
573     return 0;
574 }
575
576 static int exec_account (struct ccl_token *list)
577 {
578     if (list->kind != CCL_TOK_EOL)
579     {
580         int len = list->len;
581         memcpy (info.account, list->name, len);
582         info.target[len] = '\0';
583     }
584     else
585         *info.account = '\0';
586     info.account_in_session = 1;
587     return 0;
588 }
589
590 void handle_target_list (const char *name, const char *value)
591 {
592     GwRes res;
593     const char *p;
594
595     if (strlen(name) < 10)
596         return;
597     if (memcmp (name, "gw.target.", 10))
598         return;
599     fprintf (reply_fd, "%s\n", name+10);
600     res = gw_res_init ();
601     gw_res_merge (res, value);
602     p = gw_res_get (res, "gw.description", NULL);
603     if (p)
604     {
605         put_esc_str (p);
606         put_esc_str ("\\n");
607     }
608     p = gw_res_get (res, "gw.databases", NULL);
609     if (p)
610         fprintf (reply_fd, "  Databases: %s\n", p);
611     fprintf (reply_fd, "\n");
612     gw_res_close (res);
613 }
614
615 static int exec_target_list (void)
616 {
617     gw_res_trav (info.kernel_res, NULL, handle_target_list);
618     fprintf (reply_fd, "\n");
619     return 0;
620 }
621
622 static int exec_target (struct ccl_token *list)
623 {
624     int len;
625     if (list->kind == CCL_TOK_EOL)
626         return exec_target_list ();
627     len = list->len;
628     memcpy (info.target, list->name, len);
629     info.target [len] = '\0';
630     
631     if (!info.account_in_session)
632         *info.account = '\0';
633     info.account_in_session = 0;
634     read_kernel_res ();
635     info.connect_failed = 0;
636     return reopen_target ();
637 }
638
639 static void exec_status_r (struct gw_user_set *sp)
640 {
641     if (!sp)
642         return;
643     exec_status_r (sp->prev);
644     fprintf (reply_fd, "%6s %7d %12.12s   %.50s\n", sp->name, sp->hits,
645              sp->database, sp->search_str);
646 }
647
648 static int exec_status (struct ccl_token *list)
649 {
650     fprintf (reply_fd, "%s\n",
651              gw_res_get (info.kernel_res,
652                          "gw.msg.statusline",
653                          "  Name    Hits     Database   Find"));
654     exec_status_r (info.sets);
655     return 0;
656 }
657
658 static int exec_base (struct ccl_token *list)
659 {
660     struct ccl_token *li = list;
661     int len = 0;
662
663     assert (info.zass);
664     if (list->kind == CCL_TOK_EOL)
665         return -1;
666     free (info.database);
667     while (li->kind != CCL_TOK_EOL)
668     {
669         len += li->len + 1;
670         li = li->next;
671         if (li->kind == CCL_TOK_COMMA)
672             li = li->next;
673     }
674     info.database  = malloc (len);
675     assert (info.database );
676     len = 0;
677     li = list;
678     while (li->kind != CCL_TOK_EOL)
679     {
680         memcpy (info.database+len, li->name, li->len);
681         len += li->len;
682         info.database[len++] = ',';
683         li = li->next;
684         if (li->kind == CCL_TOK_COMMA)
685             li = li->next;
686     }
687     info.database[len-1] = '\0';
688     return 0;
689 }
690
691 static void present (const char *set, int offset, int number,
692                      struct ccl_token *format_token)
693 {
694     const struct zass_presentent *zp;
695     int len;
696     int max_number;
697     char format_str[16];
698     
699     max_number = gw_res_int (info.kernel_res, "gw.max.show", 100);
700     if (number > max_number)
701         number = max_number;
702     gw_log (GW_LOG_DEBUG, KERNEL_LOG, "present in set %s", set);
703     gw_log (GW_LOG_DEBUG, KERNEL_LOG, "present of %d records from offset %d",
704             number, offset);
705     zp = zass_p_present(info.zass, (char *) set, offset, number);
706     if (zp)
707     {
708         int i;
709         zass_record *pp;
710         int  record_log_fd = -1;
711         const char *record_log_name;
712
713         record_log_name = gw_res_get (info.kernel_res, "gw.marc.log",
714                                       NULL);
715         if (record_log_name)
716         {
717             record_log_fd = open (record_log_name, 
718                                   O_WRONLY|O_CREAT|O_APPEND, 0666);
719             if (record_log_fd == -1)
720                 gw_log (GW_LOG_WARN|GW_LOG_ERRNO, "Cannot open %s", 
721                         record_log_name);
722         }
723         fprintf (reply_fd, gw_res_get (info.kernel_res,
724                                        "gw.msg.records",
725                                        "Got %d records from set %s"),
726                  zp->num, set);
727         fprintf (reply_fd, "\n");
728         for (i = 0, pp = zp->records; pp; pp = pp->next, i++)
729         {
730             Iso2709Rec rec;
731 #if USE_FML
732             const char *arg_ar[5];
733 #endif
734             fprintf (reply_fd, "--- %d/%d ---\n",
735                      i+offset, offset+zp->num-1);
736             if (!gw_res_get (info.kernel_res, "gw.ignore.which", NULL))
737             {
738                 if (pp->which == ZASS_REC_DIAG)
739                 {
740                     display_diag_error (pp->errcode, pp->errstring);
741                     continue;
742                 }
743                 else if (pp->which != ZASS_REC_USMARC)
744                 {
745                     fprintf (reply_fd, "Unknown record kind %d\n",
746                              pp->which);
747                     continue;
748                 }
749             }
750             if (record_log_fd != -1)
751                 write (record_log_fd, pp->record, strlen(pp->record));
752             rec = iso2709_cvt (pp->record);
753             if (rec)
754             {
755 #if USE_FML
756                 strcpy (format_str,
757                         gw_res_get (info.kernel_res,
758                                     "gw.display.format", ""));
759                 if (format_token)
760                 {
761                     len = format_token->len;
762                     if (len >= sizeof(format_str))
763                         len = sizeof(format_str)-1;
764                     memcpy (format_str, format_token->name, len);
765                     format_str[len] = '\0';
766                 }
767                 if (info.fml && *format_str && 
768                     (!strcmp (format_str, "0") || !strcmp (format_str, "1")
769                      || !strcmp(format_str, "2")))
770                 {
771                     arg_ar[0] = "\\f";
772                     arg_ar[1] = format_str;
773                     arg_ar[2] = " \\list";
774                     arg_ar[3] = marc_to_str (info.fml, rec);
775                     arg_ar[4] = NULL;
776                     fml_exec_call_argv (info.fml, arg_ar);
777                 }
778                 else
779                     iso2709_display (rec, reply_fd);
780 #else
781                 iso2709_display (rec, reply_fd);
782 #endif
783                 iso2709_rm (rec);
784             }
785             else
786                 fprintf (reply_fd, "Not a MARC record\n");
787         }
788         if (record_log_fd != -1)
789             close (record_log_fd);
790     }
791 }
792
793 static int exec_show (struct ccl_token *list)
794 {
795     static struct command_word show_tab [] = 
796     {
797     {   "f", "format"},
798     {   "p", "position"},
799     {   NULL, NULL }
800     };
801     char tmp_str[20];
802     struct ccl_token *set_token = NULL;
803     struct ccl_token *format_token = NULL;
804     struct ccl_token *li = list;
805     int no_of_present = 0;
806
807     assert (info.zass);
808     while (li->kind != CCL_TOK_EOL)
809     {
810         int modifier_no = 0;
811         if (li->next->kind == CCL_TOK_EQ)
812         {
813             if (li->kind == CCL_TOK_SET)    /* set = <name> ? */
814             {
815                 li = li->next->next;
816                 set_token = li;
817             }
818             else 
819             {
820                 modifier_no = command_search (show_tab, li, "ccl.token.");
821                 if (!modifier_no)
822                 {
823                     fprintf (reply_fd, "Unknown modifier in show\n");
824                     return -1;
825                 }
826                 li = li->next->next;
827                 if (modifier_no == 1)       /* f = <name> ? */
828                     format_token = li;
829                 else if (modifier_no == 2)  /* p = <name> ? */
830                 {
831                     if (li->kind != CCL_TOK_EOL   /* p = <name> - <name> ? */
832                         && li->next->kind == CCL_TOK_MINUS
833                         && li->next->next != CCL_TOK_EOL)
834                         li = li->next->next;
835                 }
836             }
837             if (!li->next)
838             {
839                 fprintf (reply_fd, "%s\n", "Missing token after '='");
840                 return -2;
841             }
842             li = li->next;
843         }
844         else
845         {
846             int len = li->len;
847             memcpy (tmp_str, li->name, len);
848             tmp_str[len] = '\0';
849             if (atoi(tmp_str) <= 0)
850             {
851                 fprintf (reply_fd, "%s\n",
852                          gw_res_get (info.kernel_res, "gw.err.bad.show",
853                                      "Syntax error"));
854                 return -3;
855             }
856             li = li->next;
857         }
858     }
859     if (set_token)
860         gw_log (GW_LOG_DEBUG, KERNEL_LOG, "Got set=%.*s", set_token->len,
861                 set_token->name);
862     if (format_token)
863         gw_log (GW_LOG_DEBUG, KERNEL_LOG, "Got format=%.*s", format_token->len,
864                 format_token->name);
865
866     li = list;
867     while (li->kind != CCL_TOK_EOL)
868     {
869         int modifier_no = 0;
870         int offset = 0;
871         int number = 0;
872         int len;
873         if (li->next->kind == CCL_TOK_EQ && li->kind != CCL_TOK_SET)
874         {
875             modifier_no = command_search (show_tab, li, "ccl.token.");
876             li = li->next->next;
877             if (modifier_no == 2)  /* p = <name> ? */
878             {
879                 if (li->kind != CCL_TOK_EOL   /* p = <name> - <name> ? */
880                     && li->next->kind == CCL_TOK_MINUS
881                     && li->next->next != CCL_TOK_EOL)
882                 {
883                     len = li->len;
884                     memcpy (tmp_str, li->name, len);
885                     tmp_str [len] = '\0';
886                     offset = atoi (tmp_str);
887                     li = li->next->next;
888
889                     len = li->len;
890                     memcpy (tmp_str, li->name, len);
891                     tmp_str [len] = '\0';
892                     number = atoi (tmp_str) - offset + 1;
893                     if (number <= 0)
894                     {
895                         fprintf (reply_fd, "%s\n",
896                                  gw_res_get (info.kernel_res,
897                                              "gw.err.pos.show",
898                                              "Starting position "
899                                              "greater than ending position"));
900                         return -3;
901                     }
902                 }
903                 else
904                 {
905                     len = li->len;
906                     memcpy (tmp_str, li->name, len);
907                     tmp_str [len] = '\0';
908                     offset = atoi (tmp_str);
909                     number = 1;
910                 }
911             }
912             li = li->next;
913         }
914         else if (li->kind == CCL_TOK_TERM)
915         {
916             len = li->len;
917             memcpy (tmp_str, li->name, len);
918             tmp_str[len] = '\0';
919             number = atoi (tmp_str);
920             offset = 1;
921             li = li->next;
922         }
923         if (offset > 0 && number > 0)
924         {
925             struct gw_user_set *us;
926
927             if (set_token)
928             {
929                 len = set_token->len;
930                 memcpy (tmp_str, set_token->name, len);
931                 tmp_str[len] = '\0';
932                 us = user_set_search (tmp_str);
933             }
934             else
935                 us = user_set_search (NULL);
936             if (us && us->hits != -1) /* proper result-set? */
937             {
938                 if (offset <= us->hits)
939                 {
940                     if (offset+number-1 > us->hits)
941                         number = us->hits - offset+1;
942                     present (us->name, offset, number, format_token);
943                     info.next_position = offset+number;
944                 }
945             }
946             else if (!no_of_present) /* display error message once! */
947             {
948                 fprintf (reply_fd, "%s\n",
949                          gw_res_get (info.kernel_res, "gw.err.no.set",
950                                      "No result-set generated"));
951             }
952             no_of_present++;
953         }
954     }
955     if (!no_of_present) /* no records shown so far? */
956     {
957         struct gw_user_set *us;
958         int default_show;
959         
960         us = user_set_search (NULL);
961         if (us && us->hits != -1)    /* proper result-set? */
962         {
963             default_show = gw_res_int (info.kernel_res, "gw.default.show", 20);
964             if (us->hits >= info.next_position + default_show)
965             {
966                 present (us->name, info.next_position, default_show, 
967                          format_token);
968                 info.next_position += default_show;
969             }
970             else if (us->hits >= info.next_position)
971             {
972                 present (us->name, info.next_position, 
973                          us->hits - info.next_position + 1, 
974                          format_token);
975                 info.next_position = us->hits + 1;
976             }
977         }
978         else                         /* display error message */
979         {
980             fprintf (reply_fd, "%s\n",
981                      gw_res_get (info.kernel_res, "gw.err.no.set",
982                                  "No result-set generated"));
983             return -3;
984         }        
985     }
986     return 0;
987 }
988
989 static void show_def (void)
990 {
991     fprintf (reply_fd, "format       %s\n", gw_res_get
992              (info.kernel_res, "gw.display.format", ""));
993     fprintf (reply_fd, "autoshow     %s\n", gw_res_get
994              (info.kernel_res, "gw.auto.show", ""));
995     fprintf (reply_fd, "defaultshow  %s\n", gw_res_get
996              (info.kernel_res, "gw.default.show", ""));
997     fprintf (reply_fd, "language     %s\n", gw_res_get
998              (info.kernel_res, "gw.language", ""));
999 }
1000
1001 static int exec_def (struct ccl_token *list)
1002 {
1003     const char *name = NULL;
1004     char value[128];
1005     char fname[256];
1006     static struct command_word def_tab [] =
1007     {
1008     {   "reset",       "reset" },
1009     {   "show",        "show" },
1010     {   "f",           "format"},
1011     {   "autoshow",    "autoshow" },
1012     {   "defaultshow", "defaultshow" },
1013     {   "lang",        "language" },
1014     {   NULL, NULL }
1015     };
1016
1017     if (info.userid < 0)
1018         return -1;
1019     sprintf (fname, "user.%d.r", info.userid);
1020
1021     if (list->kind == CCL_TOK_EOL) 
1022         show_def ();
1023     else
1024     {
1025         int setting_no = command_search (def_tab, list, "ccl.token.");
1026
1027         if (!setting_no)
1028         {
1029             fprintf (reply_fd, "Unknown setting in def\n");
1030             return -1;
1031         }
1032         if (setting_no == 1)
1033         {
1034             unlink (fname);
1035             read_kernel_res ();
1036             return 0;
1037         }
1038         else if (setting_no == 2)
1039         {
1040             show_def ();
1041             return 0;
1042         }
1043         list = list->next;
1044         if (list->kind == CCL_TOK_EOL)
1045             return 0;
1046         strncpy (value, list->name, 127);
1047         value[(size_t) list->len] = '\0';
1048         switch (setting_no)
1049         {
1050         case 3:
1051             name = "gw.display.format";
1052             break;
1053         case 4:
1054             name = "gw.auto.show";
1055             break;
1056         case 5:
1057             name = "gw.default.show";
1058             break;
1059         case 6:
1060             name = "gw.language";
1061             break;
1062         default:
1063             return 0;
1064         }
1065         gw_log (GW_LOG_DEBUG, KERNEL_LOG, "update file %s with %s=%s",
1066                 fname, name, value);
1067         gw_res_put (info.kernel_res, "gw.username", info.from_str, fname);
1068         gw_res_put (info.kernel_res, name, value, fname);
1069         gw_res_commit (info.kernel_res, fname);
1070         if (setting_no == 6)
1071             read_kernel_res ();
1072     }
1073     return 0;
1074 }
1075
1076
1077 /*
1078  * exec_command: parse and execute ccl command in str.
1079  * str:      ccl command string
1080  * stop_flag pointer to integer. On completion the integer
1081  *           is 1 (stop) or 2 (continue); 0 (other command)
1082  * return: 0 success; non-zero otherwise
1083  */
1084 static int exec_command (const char *str, int *stop_flag)
1085 {
1086     struct ccl_token *cmd;
1087     const char *cp = str;
1088     int no;
1089
1090     while (*cp && *cp != ' ' && *cp != '\n' && *cp != '\t' && *cp != '\r')
1091         cp++;
1092
1093     *stop_flag = 0;
1094     no = command_search_str (command_tab, str, cp-str, "ccl.command.");
1095     if (no)
1096     {
1097         if (no == 1 || no == 2 || no == 3) /* find/show/base? */
1098         {
1099             if (!info.connect_failed && !info.zass) 
1100                             /* open if not already opened */
1101                 reopen_target ();
1102             fprintf (reply_fd, "\n> %s\n", str);
1103             if (!info.zass)      /* fail? */
1104             {
1105                 fprintf (reply_fd, "\n%s\n",
1106                          gw_res_get (info.kernel_res, "gw.err.no.target",
1107                                      "No connection established - "
1108                                      "command ignored"));
1109                 return 0;
1110             }
1111         }
1112         else
1113             fprintf (reply_fd, "\n> %s\n", str);
1114         switch (no)
1115         {
1116         case 1: /* find */
1117             cmd = ccl_tokenize (cp);
1118             exec_find (cmd, str);
1119             break;
1120         case 2: /* show */
1121             cmd = ccl_tokenize (cp);
1122             exec_show (cmd);
1123             break;
1124         case 3: /* base */
1125             cmd = ccl_token_simple (cp);
1126             exec_base (cmd);
1127             break;
1128         case 4: /* help */
1129             cmd = ccl_token_simple (cp);
1130             exec_help (cmd);
1131             break;
1132         case 6:  /* continue */
1133             *stop_flag = 2;
1134             return 0;
1135         case 7:  /* status */
1136             exec_status (cmd);
1137             return 0;
1138         case 8:  /* stop */
1139             *stop_flag = 1;
1140             return 0;
1141         case 9:  /* target */
1142             cmd = ccl_token_simple (cp);
1143             exec_target (cmd);
1144             break;
1145         case 10: /* def */
1146             cmd = ccl_token_simple (cp);
1147             exec_def (cmd);
1148             break;
1149         case 11: /* account */
1150             cmd = ccl_token_simple (cp);
1151             exec_account (cmd);
1152             break;
1153         default:
1154             cmd = NULL;
1155             fprintf (reply_fd, "%s\n",
1156                      gw_res_get (info.kernel_res, "gw.err.unimplemented",
1157                                  "Not implemented yet"));
1158         }
1159         ccl_token_del (cmd);
1160     }
1161     else
1162     {
1163         fprintf (reply_fd, "\n> %s\n", str);
1164         fprintf (reply_fd, "  ^ %s\n", 
1165                  gw_res_get (info.kernel_res, "gw.err.unknown.command",
1166                              "unknown command. "
1167                              "Use help to see list of commands"));
1168     }
1169     return 0;
1170 }
1171
1172 int urp_start (int continuation, struct str_queue *queue)
1173 {
1174     char subject_str[128];
1175     const char *cp;
1176
1177     info.command_no = 0;
1178     info.reply_fname = NULL;
1179
1180     if (email_header (queue, info.from_str, subject_str))
1181     {
1182         gw_log (GW_LOG_WARN, KERNEL_LOG, "No message body");
1183         return -1;
1184     }
1185     tty_init (stdout, 40, 70);
1186     if (*info.from_str)
1187     {
1188         info.reply_fname = (char *)
1189             tempnam (gw_res_get (info.kernel_res, "gw.reply.tmp.dir", NULL),
1190                      gw_res_get (info.kernel_res,
1191                                  "gw.reply.tmp.prefix", "gwr"));
1192
1193         reply_fd = fopen (info.reply_fname, "w");
1194         if (!reply_fd)
1195         {
1196             gw_log (GW_LOG_FATAL|GW_LOG_ERRNO, KERNEL_LOG, "Cannot create %s",
1197                     info.reply_fname);
1198             return -1;
1199         }
1200         tty_init (reply_fd, 0, 0);
1201         fprintf (reply_fd, "From: %s\n",
1202                  gw_res_get (info.kernel_res, "gw.msg.from",
1203                              "Email-Z39.50 gateway"));
1204         cp = gw_res_get (info.kernel_res, "gw.msg.replyto", NULL);
1205         if (cp)
1206             fprintf (reply_fd, "Reply-To: %s\n", cp);
1207         fprintf (reply_fd, "Subject: ");
1208         if (*subject_str)
1209             fprintf (reply_fd, "Z39.50 Re: %s", subject_str);
1210         else
1211             fprintf (reply_fd, "%s\n", gw_res_get (info.kernel_res,
1212                                                    "gw.msg.subject",
1213                                                    "Your Query"));
1214         fprintf (reply_fd, "\n");
1215         gw_log (GW_LOG_ACCT, KERNEL_LOG, "User start %s", info.from_str);
1216     }
1217     else
1218         gw_log (GW_LOG_WARN, KERNEL_LOG, "No From in email header");
1219     fprintf (reply_fd, "%s\n", gw_res_get (info.kernel_res, "gw.msg.greeting",
1220                                            "Email->Z39.50 gateway"));
1221     if (continuation)
1222         fprintf (reply_fd, "%s\n", gw_res_get (info.kernel_res,
1223                                                "gw.msg.cont",
1224                                                "Continued..."));
1225     return 0;
1226 }
1227
1228 int urp_command (struct str_queue *queue)
1229 {
1230     char *cp;
1231     int stop_flag;
1232
1233     while (str_queue_deq (queue, line_buf, STR_LINE_MAX))
1234     {
1235         if (line_buf[0] == '\n')
1236             if (info.command_no)
1237             {
1238                 while (str_queue_deq (queue, 0, 0))
1239                     ;
1240                 break;
1241             }
1242             else 
1243                 continue;
1244         if ((cp = strchr (line_buf, '\n')))
1245             *cp = '\0';
1246         gw_log (GW_LOG_ACCT, KERNEL_LOG, "cmd: %s", line_buf);
1247         if (isalpha (line_buf[0]))
1248         {
1249             exec_command (line_buf, &stop_flag);
1250             if (stop_flag)
1251             {
1252                 info.command_no++;     /* prevent help! */
1253                 while (str_queue_deq (queue, line_buf, STR_LINE_MAX))
1254                      ;
1255                 return stop_flag;
1256             }
1257         }
1258         info.command_no++;
1259     }
1260     return 0;
1261 }
1262
1263 void urp_end (void)
1264 {
1265     if (!info.command_no)
1266     {
1267         fprintf (reply_fd, "%s\n", 
1268                  gw_res_get (info.kernel_res, "gw.err.nullbody", "No body"));
1269         help_general ();
1270     }
1271     if (*info.from_str)
1272     {
1273         const char *mta;
1274         char cmd[256];
1275         int mta_code;
1276
1277         assert (info.reply_fname);
1278         fclose (reply_fd);
1279         reply_fd = stdout;
1280
1281         mta = gw_res_get (info.kernel_res, "gw.reply.mta",
1282                           "/usr/lib/sendmail");
1283         sprintf (cmd, "%s %s < %s", mta, info.from_str, info.reply_fname);
1284         mta_code = system (cmd);
1285         if (mta_code)
1286             gw_log (GW_LOG_FATAL, KERNEL_LOG,
1287                     "Reply '%s' got exit code %d", cmd, mta_code);
1288         else
1289             unlink (info.reply_fname);        
1290         gw_log (GW_LOG_ACCT, KERNEL_LOG, "User end %s", info.from_str);
1291     }
1292 }
1293