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