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