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