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