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