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