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