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