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