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