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