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