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