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