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