Added logging of all user commands.
[egate.git] / kernel / urp.c
1 /* Gateway kernel
2  * Europagate, 1995
3  *
4  * $Log: urp.c,v $
5  * Revision 1.16  1995/02/23 10:08:20  adam
6  * Added logging of all user commands.
7  *
8  * Revision 1.15  1995/02/23  08:32:17  adam
9  * Changed header.
10  *
11  * Revision 1.13  1995/02/22  16:54:42  adam
12  * Qualifiers of LOC target updated. More logging messages.
13  *
14  * Revision 1.12  1995/02/22  15:51:51  adam
15  * Bug fix: swap of parameter number and offset in function present.
16  *
17  * Revision 1.11  1995/02/22  15:22:33  adam
18  * Much more checking of run-time state. Show command never retrieves
19  * more records than indicated by the previous search request. Help
20  * command available. The maximum number of records retrieved can be
21  * controlled now.
22  *
23  * Revision 1.10  1995/02/22  08:51:35  adam
24  * Output function can be customized in fml, which is used to print
25  * the reply to reply_fd.
26  *
27  * Revision 1.9  1995/02/21  17:46:21  adam
28  * Minor changes.
29  *
30  * Revision 1.8  1995/02/21  12:12:00  adam
31  * Diagnostic record with error info. observed.
32  *
33  * Revision 1.7  1995/02/20  21:16:20  adam
34  * FML support. Bug fixes. Profile for drewdb.
35  *
36  * Revision 1.6  1995/02/17  14:41:14  quinn
37  * Added simple display of records.
38  *
39  * Revision 1.5  1995/02/17  14:22:13  adam
40  * First steps of CCL show command. Not finished yet.
41  *
42  * Revision 1.4  1995/02/17  09:08:36  adam
43  * Reply with subject. CCL base command implemented.
44  *
45  * Revision 1.3  1995/02/16  18:35:09  adam
46  * First use of Zdist library. Search requests are supported.
47  * Present requests are not supported yet.
48  *
49  * Revision 1.2  1995/02/16  13:21:00  adam
50  * Organization of resource files for targets and conversion
51  * language implemented.
52  *
53  * Revision 1.1  1995/02/15  17:45:30  adam
54  * First version of email gateway kernel. Email requests are read
55  * from stdin. The output is transferred to an MTA if 'From' is
56  * found in the header - or stdout if absent. No Z39.50 client is used.
57  *
58  */
59
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <assert.h>
63 #include <ctype.h>
64 #include <string.h>
65 #include <unistd.h>
66
67 #include "kernel.h"
68
69 #define LINE_MAX 256
70
71 static void put_esc_str (const char *s)
72 {
73     int escape_flag = 0;
74     while (*s)
75     {
76         if (*s == '\\' && s[1])
77         {
78             switch (*++s)
79             {
80             case 'n':
81                 fputc ('\n', reply_fd);
82                 break;
83             case 't':
84                 fputc ('\t', reply_fd);
85                 break;
86             default:
87                 fputc (*s, reply_fd);
88                 break;
89             }
90             escape_flag = 1;
91         }
92         else
93         {
94             if (*s != ' ' || !escape_flag)
95                 fputc (*s, reply_fd);
96             escape_flag = 0;
97         }
98         s++;
99     }
100 }
101
102 static int reopen_target (void)
103 {
104     const char *v;
105     if (info.zass)
106         gw_log (GW_LOG_WARN, "urp", "Zass free...");
107     info.zass = zass_open (info.hostname, info.port);
108     if (!info.zass)
109     {
110         fprintf (reply_fd, "%s %s:%d\n", 
111                  gw_res_get (info.kernel_res, "gw.err.connect",
112                              "Cannot connect to target"),
113                  info.hostname, info.port);
114         return -1;
115     }
116     v = gw_res_get (info.kernel_res, "gw.description", NULL);
117     if (v)
118         fprintf (reply_fd, "%s\n", v);
119     fprintf (reply_fd, "%s %s:%d\n",
120              gw_res_get (info.kernel_res, "gw.msg.connect",
121                          "Connection established to"),
122              info.hostname, info.port);
123     if (*info.databases)
124         fprintf (reply_fd, "%s:\n%s\n",
125                  gw_res_get (info.kernel_res, "gw.msg.databases",
126                              "Available databases"),
127                  info.databases);
128     return 0;
129 }
130
131 static char line_buf[LINE_MAX+1];
132
133 static struct command_word {
134     char *default_value;
135     char *resource_suffix;
136 } command_tab [] = 
137 {
138 {   "find", "find"},
139 {   "show", "show"},
140 {   "base", "base" },
141 {   "help", "help" },
142 {   "info", "info" },
143 {   "continue", "continue" },
144 {   "status", "status" },
145 {   "cancel", "cancel" },
146 {   "target", "target" },
147 {   NULL, NULL }
148 };
149
150 static int command_search (struct command_word *tab, struct ccl_token *cmd,
151 const char *resource_prefix)
152 {
153     int no = 1;
154
155     assert (resource_prefix);
156     assert (tab);
157     assert (cmd);
158     while (tab->default_value)
159     {
160         char *cp, command_names[60];
161         char resource_name[60];
162         const char *v;
163
164         sprintf (resource_name, "%s%s", resource_prefix,
165                  tab->resource_suffix);
166         v = gw_res_get (info.kernel_res, resource_name, tab->default_value);
167         assert (v);
168         strcpy (command_names, v);
169         cp = command_names;
170         while (1)
171         {
172             char *split;
173
174             if ((split = strchr (cp, ' ')))
175                 *split = '\0';
176             if (cmd->len == strlen(cp) &&
177                 !memcmp (cmd->name, cp, cmd->len))
178                 return no;
179             if (!split)
180                 break;
181             cp = split+1;
182         }        
183         no++;
184         tab++;
185     }
186     return 0;
187 }
188
189 static struct error_no_struct {
190     int no;
191     char *resource_name;
192 } error_ccl_tab[] = {
193 {  CCL_ERR_OK, "ok"},
194 {  CCL_ERR_TERM_EXPECTED, "term.expected" },
195 {  CCL_ERR_RP_EXPECTED, "rp.expected" },
196 {  CCL_ERR_SETNAME_EXPECTED, "setname.expected" },
197 {  CCL_ERR_OP_EXPECTED, "op.expected" },
198 {  CCL_ERR_BAD_RP, "bad.rp" },
199 {  CCL_ERR_UNKNOWN_QUAL, "unknown.qual" },
200 {  CCL_ERR_DOUBLE_QUAL, "double.qual" },
201 {  CCL_ERR_EQ_EXPECTED, "eq.expected" },
202 {  CCL_ERR_BAD_RELATION, "bad.relation" },
203 {  CCL_ERR_TRUNC_NOT_LEFT, "trunc.not.left" },
204 {  CCL_ERR_TRUNC_NOT_BOTH, "trunc.not.both" },
205 {  CCL_ERR_TRUNC_NOT_RIGHT, "trunc.not.right" },
206 {  0, NULL }
207 };
208
209 static char *error_no_search (struct error_no_struct *tab, int no)
210 {
211     struct error_no_struct *p = tab;
212     while (p->resource_name)
213     {
214         if (no == p->no)
215             return p->resource_name;
216         p++;
217     }
218     return NULL;
219 }
220
221 static int email_header (FILE *inf, char *from_str, char *subject_str)
222 {
223     *from_str = '\0';
224     *subject_str = '\0';
225     while (fgets (line_buf, LINE_MAX, inf))
226     {
227         if (line_buf[0] == '\n')
228             return 0;
229         if (strncmp (line_buf, "From ", 5) == 0)
230             sscanf (line_buf+4, "%s", from_str);
231         if (strncmp (line_buf, "Subject: ", 9) == 0 &&
232             sscanf (line_buf+9, "%s", subject_str+1) == 1)
233             strcpy (subject_str, line_buf+9);
234     }
235     return 1;
236 }
237
238 static void help_general (void)
239 {
240     put_esc_str (gw_res_get (info.kernel_res, "gw.help.general",
241                              "Commands available in this service:\n"));
242 }
243
244 static int exec_help (struct ccl_token *list)
245 {
246     help_general ();
247
248 #if 0
249     put_esc_str (gw_res_get (info.kernel_res, "gw.help.target",
250                              "target <name> - selects a given target\n"));
251
252     put_esc_str (gw_res_get (info.kernel_res, "gw.help.base",
253                              "base <base>..  - selects databases\n"));
254
255     put_esc_str (gw_res_get (info.kernel_res, "gw.help.find",
256                              "find <query>   - performs a search request\n"));
257
258     put_esc_str (gw_res_get (info.kernel_res, "gw.help.show",
259                              "show <spec>    - retrieves and displays "
260                              "records\n"));
261     put_esc_str (gw_res_get (info.kernel_res, "gw.help.help",
262                              "help           - displays help\n"));
263 #endif
264     return 0;
265 }
266
267 static int exec_find (struct ccl_token *list)
268 {
269     const struct zass_searchent *p;
270     struct gw_user_set *us;
271
272     struct ccl_rpn_node *rpn;
273     int error;
274     const char *pos;
275
276     us = user_set_add ("Default", -1);
277     rpn = ccl_find (info.bibset, list, &error, &pos);
278     if (!rpn)
279     {
280         const char *v = NULL, *n;
281         char name[128];
282
283         fprintf (reply_fd, "  %*s^ - ", pos - line_buf, " ");
284
285         n = error_no_search (error_ccl_tab, error);
286         if (n)
287         {
288             sprintf (name, "gw.err.%s", n);
289             v = gw_res_get (info.kernel_res, name, NULL);
290         }
291         if (!v)
292             v = ccl_err_msg (error);
293         fprintf (reply_fd, "%s\n", v);
294         return -1;
295     }
296     ccl_pr_tree (rpn, reply_fd);
297     fprintf (reply_fd, "\n");
298
299     if (!*info.databases)
300     {
301         fprintf (reply_fd, "%s\n",
302                  gw_res_get (info.kernel_res, "gw.err.no.database",
303                              "You must select database"));
304         return -3;
305     }
306     gw_log (GW_LOG_DEBUG, "urp", "Searching in database %s",
307             info.databases);
308     assert (info.zass);
309     p = zass_search (info.zass, rpn, "Default", info.databases);
310     if (!p)
311         return -1;
312     if (p->errcode != -1)
313     {
314         fprintf (reply_fd, "%s %d: %s\n",
315                  gw_res_get (info.kernel_res, "gw.msg.z39errcode",
316                              "Z39.50 error code"),
317                  p->errcode, p->errstring);
318         return -2;
319     }
320     fprintf (reply_fd, "%d %s\n", p->num,
321              gw_res_get (info.kernel_res, "gw.msg.hits", "hit(s)"));
322     us->hits = p->num;
323     return 0;
324 }
325
326 static int exec_target (struct ccl_token *list)
327 {
328     int len;
329     if (list->kind == CCL_TOK_EOL)
330         return -1;
331     len = list->len;
332     memcpy (info.target, list->name, len);
333     info.target [len] = '\0';
334
335     read_kernel_res ();
336     return reopen_target ();
337 }
338
339 static int exec_base (struct ccl_token *list)
340 {
341     struct ccl_token *li = list;
342     int len = 0;
343
344     assert (info.zass);
345     if (list->kind == CCL_TOK_EOL)
346         return -1;
347     free (info.databases);
348     while (li->kind != CCL_TOK_EOL)
349     {
350         len += li->len + 1;
351         li = li->next;
352         if (li->kind == CCL_TOK_COMMA)
353             li = li->next;
354     }
355     info.databases = malloc (len);
356     assert (info.databases);
357     len = 0;
358     li = list;
359     while (li->kind != CCL_TOK_EOL)
360     {
361         memcpy (info.databases+len, li->name, li->len);
362         len += li->len;
363         info.databases[len++] = ',';
364         li = li->next;
365         if (li->kind == CCL_TOK_COMMA)
366             li = li->next;
367     }
368     info.databases[len-1] = '\0';
369     return 0;
370 }
371
372 struct command_word show_tab [] = 
373 {
374 {   "f", "format"},
375 {   "p", "position"},
376 {   NULL, NULL }
377 };
378
379 static void present (const char *set, int offset, int number,
380                      struct ccl_token *format_token)
381 {
382     const struct zass_presentent *zp;
383     int len;
384     int max_number;
385     char format_str[40];
386     
387     max_number = atoi (gw_res_get (info.kernel_res, "gw.max.show", 
388                                    "200"));
389     if (number > max_number)
390         number = max_number;
391     gw_log (GW_LOG_DEBUG, "urp", "present in set %s", set);
392     gw_log (GW_LOG_DEBUG, "urp", "present of %d records from offset %d",
393             number, offset);
394     zp = zass_present(info.zass, (char *) set, offset, number);
395     if (zp)
396     {
397         int i;
398         zass_record *pp;
399         
400         fprintf (reply_fd, gw_res_get (info.kernel_res,
401                                        "gw.msg.records",
402                                        "Got %d records"),
403                  zp->num);
404         fprintf (reply_fd, "\n");
405         for (i = 0, pp = zp->records; pp; pp = pp->next, i++)
406         {
407             Iso2709Rec rec;
408 #if USE_FML
409             const char *arg_ar[5];
410 #endif
411             fprintf (reply_fd, "--- %d/%d ---\n",
412                      i+offset, offset+zp->num-1);
413             if (!gw_res_get (info.kernel_res, "gw.ignore.which", NULL))
414             {
415                 if (pp->which == ZASS_REC_DIAG)
416                 {
417                     fprintf (reply_fd, "Record error %d: %s\n",
418                              pp->errcode, pp->errstring);
419                     continue;
420                 }
421                 else if (pp->which != ZASS_REC_USMARC)
422                 {
423                     fprintf (reply_fd, "Unknown record kind %d\n",
424                              pp->which);
425                     continue;
426                 }
427             }
428             rec = iso2709_cvt (pp->record);
429             if (rec)
430             {
431 #if USE_FML
432                 if (format_token)
433                 {
434                     len = format_token->len;
435                     memcpy (format_str, format_token->name, len);
436                     format_str[len] = '\0';
437                 }
438                 if (info.fml && format_token && 
439                     (!strcmp (format_str, "0") || !strcmp (format_str, "1")))
440                 {
441                     arg_ar[0] = "\\f";
442                     arg_ar[1] = format_str;
443                     arg_ar[2] = " \\list";
444                     arg_ar[3] = marc_to_str (info.fml, rec);
445                     arg_ar[4] = NULL;
446                     fml_exec_call_argv (info.fml, arg_ar);
447                 }
448                 else
449                     iso2709_display (rec, reply_fd);
450 #else
451                 iso2709_display (rec, reply_fd);
452 #endif
453                 iso2709_rm (rec);
454             }
455             else
456                 fprintf (reply_fd, "Not a MARC record\n");
457         }
458     }
459 }
460
461 static int exec_show (struct ccl_token *list)
462 {
463     char tmp_str[20];
464     struct ccl_token *set_token = NULL;
465     struct ccl_token *format_token = NULL;
466     struct ccl_token *li = list;
467     int no_of_present = 0;
468
469     assert (info.zass);
470     while (li->kind != CCL_TOK_EOL)
471     {
472         int modifier_no = 0;
473         if (li->next->kind == CCL_TOK_EQ)
474         {
475             if (li->kind == CCL_TOK_SET)    /* set = <name> ? */
476             {
477                 li = li->next->next;
478                 set_token = li;
479             }
480             else 
481             {
482                 modifier_no = command_search (show_tab, li, "ccl.token.");
483                 if (!modifier_no)
484                 {
485                     fprintf (reply_fd, "Unknown modifier in show\n");
486                     return -1;
487                 }
488                 li = li->next->next;
489                 if (modifier_no == 1)       /* f = <name> ? */
490                     format_token = li;
491                 else if (modifier_no == 2)  /* p = <name> ? */
492                 {
493                     if (li->kind != CCL_TOK_EOL   /* p = <name> - <name> ? */
494                         && li->next->kind == CCL_TOK_MINUS
495                         && li->next->next != CCL_TOK_EOL)
496                         li = li->next->next;
497                 }
498             }
499             if (!li->next)
500             {
501                 fprintf (reply_fd, "%s\n", "Missing token after '='");
502                 return -2;
503             }
504             li = li->next;
505         }
506         else
507             li = li->next;
508     }
509     if (set_token)
510         gw_log (GW_LOG_DEBUG, "urp", "Got set=%.*s", set_token->len,
511                 set_token->name);
512     if (format_token)
513         gw_log (GW_LOG_DEBUG, "urp", "Got format=%.*s", format_token->len,
514                 format_token->name);
515
516     li = list;
517     while (li->kind != CCL_TOK_EOL)
518     {
519         int modifier_no = 0;
520         int offset = 0;
521         int number = 0;
522         int len;
523         if (li->next->kind == CCL_TOK_EQ && li->kind != CCL_TOK_SET)
524         {
525             modifier_no = command_search (show_tab, li, "ccl.token.");
526             li = li->next->next;
527             if (modifier_no == 2)  /* p = <name> ? */
528             {
529                 if (li->kind != CCL_TOK_EOL   /* p = <name> - <name> ? */
530                     && li->next->kind == CCL_TOK_MINUS
531                     && li->next->next != CCL_TOK_EOL)
532                 {
533                     len = li->len;
534                     memcpy (tmp_str, li->name, len);
535                     tmp_str [len] = '\0';
536                     offset = atoi (tmp_str);
537                     li = li->next->next;
538
539                     len = li->len;
540                     memcpy (tmp_str, li->name, len);
541                     tmp_str [len] = '\0';
542                     number = atoi (tmp_str) - offset + 1;
543                 }
544                 else
545                 {
546                     len = li->len;
547                     memcpy (tmp_str, li->name, len);
548                     tmp_str [len] = '\0';
549                     offset = atoi (tmp_str);
550                     number = 1;
551                 }
552             }
553             li = li->next;
554         }
555         else
556         {
557             len = li->len;
558             memcpy (tmp_str, li->name, len);
559             tmp_str[len] = '\0';
560             number = atoi (tmp_str);
561             offset = 1;
562             li = li->next;
563         }
564         if (offset > 0 && number > 0)
565         {
566             struct gw_user_set *us;
567
568             if (set_token)
569             {
570                 len = set_token->len;
571                 memcpy (tmp_str, set_token->name, len);
572                 tmp_str[len] = '\0';
573                 us = user_set_search (tmp_str);
574             }
575             else
576                 us = user_set_search (NULL);
577             if (us && us->hits != -1) /* proper result-set? */
578             {
579                 if (offset <= us->hits)
580                 {
581                     if (offset+number-1 > us->hits)
582                         number = us->hits - offset+1;
583                     present (us->name, offset, number, format_token);
584                 }
585             }
586             else if (!no_of_present) /* display error message once! */
587             {
588                 fprintf (reply_fd, "%s\n",
589                          gw_res_get (info.kernel_res, "gw.err.no.set",
590                                      "No result-set generated"));
591             }
592             no_of_present++;
593         }
594     }
595     if (!no_of_present) /* no records shown so far? */
596     {
597         struct gw_user_set *us;
598         int default_show;
599         
600         us = user_set_search (NULL);
601         if (us && us->hits != -1)    /* proper result-set? */
602         {
603             default_show = atoi (gw_res_get (info.kernel_res,
604                                              "gw.default.show", "20"));
605             if (us->hits > default_show)
606                 present (us->name, 1, default_show, format_token);
607             else if (us->hits > 0)
608                 present (us->name, 1, us->hits, format_token);
609         }
610         else                         /* display error message */
611         {
612             fprintf (reply_fd, "%s\n",
613                      gw_res_get (info.kernel_res, "gw.err.no.set",
614                                  "No result-set generated"));
615             return -3;
616         }        
617     }
618     return 0;
619 }
620
621 static int exec_command (const char *str)
622 {
623     struct ccl_token *cmd = ccl_tokenize (str);
624     int no;
625
626     if (cmd->kind != CCL_TOK_EOL &&
627         (no = command_search (command_tab, cmd, "ccl.command.")))
628     {
629         if (!info.zass && no != 9 && no != 4)
630             reopen_target ();
631         fprintf (reply_fd, "\n> %s\n", str);
632         if (!info.zass && (no == 1 || no == 2 || no == 3))
633         {
634             fprintf (reply_fd, "%s\n",
635                      gw_res_get (info.kernel_res, "gw.err.no.target",
636                                  "No connection established - "
637                                  "command ignored"));
638             return 0;
639         }
640         switch (no)
641         {
642         case 1:
643             return exec_find (cmd->next);
644         case 2:
645             return exec_show (cmd->next);
646         case 3:
647             return exec_base (cmd->next);
648         case 4:
649             return exec_help (cmd->next);
650         case 9:
651             return exec_target (cmd->next);
652         default:
653             fprintf (reply_fd, "%s\n",
654                      gw_res_get (info.kernel_res, "gw.err.unimplemented",
655                                  "Not implemented yet"));
656         }
657     }
658     else
659     {
660         fprintf (reply_fd, "\n> %s", str);
661         fprintf (reply_fd, "  ^ %s\n", 
662                  gw_res_get (info.kernel_res, "gw.err.unknown.command",
663                              "unknown command. "
664                              "Use help to see list of commands"));
665     }
666     return 0;
667 }
668
669 int urp (FILE *inf)
670 {
671     char from_str[128];
672     char subject_str[128];
673     int command_no = 0;
674     char *reply_fname = NULL;
675
676     if (email_header (inf, from_str, subject_str))
677     {
678         gw_log (GW_LOG_WARN, "urp", "No message body");
679         return -1;
680     }
681     if (*from_str)
682     {
683         reply_fname = tempnam (gw_res_get (info.kernel_res,
684                                            "gw.reply.tmp.dir", NULL),
685                                gw_res_get (info.kernel_res,
686                                            "gw.reply.tmp.prefix", "gwr"));
687                                                  
688         reply_fd = fopen (reply_fname, "w");
689         if (!reply_fd)
690         {
691             gw_log (GW_LOG_FATAL, "urp", "Cannot create %s",
692                     reply_fname);
693             return -1;
694         }
695         fprintf (reply_fd, "Subject: ");
696         if (*subject_str)
697             fprintf (reply_fd, "Z39.50 Re: %s", subject_str);
698         else
699             fprintf (reply_fd, "%s\n", gw_res_get (info.kernel_res,
700                                                    "gw.msg.subject",
701                                                    "Your Query"));
702         fprintf (reply_fd, "\n");
703         gw_log (GW_LOG_DEBUG, "urp", "Mail from %s", from_str);
704     }
705     else
706         gw_log (GW_LOG_WARN, "urp", "No From in email header");
707     fprintf (reply_fd, "%s\n", gw_res_get (info.kernel_res, "gw.msg.greeting",
708                                            "Email->Z39.50 gateway"));
709     while (fgets (line_buf, LINE_MAX, inf))
710     {
711         char *cp;
712
713         if (line_buf[0] == '\n')
714             break;
715         if ((cp = strchr (line_buf, '\n')))
716             *cp = '\0';
717         gw_log (GW_LOG_ACCT, "urp", "cmd: %s", line_buf);
718         ccl_token_and = gw_res_get (info.kernel_res, "ccl.token.and", "and");
719         ccl_token_or = gw_res_get (info.kernel_res, "ccl.token.or", "or");
720         ccl_token_not = gw_res_get (info.kernel_res, "ccl.token.not", "not");
721         ccl_token_set = gw_res_get (info.kernel_res, "ccl.token.set", "set");
722         if (isalpha (line_buf[0]))
723             exec_command (line_buf);
724         command_no++;
725     }
726     if (!command_no)
727     {
728         fprintf (reply_fd, "%s\n", gw_res_get (info.kernel_res,
729                                                "gw.err.nullbody",
730                                                "No body"));
731         help_general ();
732     }
733     if (*from_str)
734     {
735         const char *mta;
736         char cmd[256];
737         int mta_code;
738
739         assert (reply_fname);
740         fclose (reply_fd);
741         reply_fd = stdout;
742
743         mta = gw_res_get (info.kernel_res, "gw.reply.mta",
744                           "/usr/lib/sendmail");
745         sprintf (cmd, "%s %s < %s", mta, from_str, reply_fname);
746         
747         mta_code = system (cmd);
748         if (mta_code)
749             gw_log (GW_LOG_FATAL, "urp", "Reply '%s' got exit code %d",
750                     cmd, mta_code);
751         unlink (reply_fname);        
752         gw_log (GW_LOG_DEBUG, "urp", "Normal session for user %s", from_str);
753     }
754     return 0;
755 }