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