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