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