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