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