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