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