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