Changed character map facility so that admin can specify character
[idzebra-moved-to-github.git] / index / zserver.c
1 /*
2  * Copyright (C) 1995-1997, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: zserver.c,v $
7  * Revision 1.52  1997-11-18 10:05:08  adam
8  * Changed character map facility so that admin can specify character
9  * mapping files for each register type, w, p, etc.
10  *
11  * Revision 1.51  1997/10/27 14:33:06  adam
12  * Moved towards generic character mapping depending on "structure"
13  * field in abstract syntax file. Fixed a few memory leaks. Fixed
14  * bug with negative integers when doing searches with relational
15  * operators.
16  *
17  * Revision 1.50  1997/09/29 09:08:36  adam
18  * Revised locking system to be thread safe for the server.
19  *
20  * Revision 1.49  1997/09/25 14:57:23  adam
21  * Windows NT port.
22  *
23  * Revision 1.48  1997/09/17 12:19:19  adam
24  * Zebra version corresponds to YAZ version 1.4.
25  * Changed Zebra server so that it doesn't depend on global common_resource.
26  *
27  * Revision 1.47  1997/09/04 13:58:36  adam
28  * New retrieve/extract method tellf (added).
29  * Added O_BINARY for open calls.
30  *
31  * Revision 1.46  1997/07/28 08:30:47  adam
32  * Server returns diagnostic 14 when record doesn't exist.
33  *
34  * Revision 1.45  1996/12/23 15:30:45  adam
35  * Work on truncation.
36  * Bug fix: result sets weren't deleted after server shut down.
37  *
38  * Revision 1.44  1996/12/11 12:08:01  adam
39  * Added better compression.
40  *
41  * Revision 1.43  1996/11/15 15:03:58  adam
42  * Logging of execution speed by using the times(2) call.
43  *
44  * Revision 1.42  1996/11/08  11:10:36  adam
45  * Buffers used during file match got bigger.
46  * Compressed ISAM support everywhere.
47  * Bug fixes regarding masking characters in queries.
48  * Redesigned Regexp-2 queries.
49  *
50  * Revision 1.41  1996/10/29 14:09:56  adam
51  * Use of cisam system - enabled if setting isamc is 1.
52  *
53  * Revision 1.40  1996/06/04 10:19:02  adam
54  * Minor changes - removed include of ctype.h.
55  *
56  * Revision 1.39  1996/05/31  09:07:05  quinn
57  * Work on character-set handling
58  *
59  * Revision 1.38  1996/05/14  11:34:01  adam
60  * Scan support in multiple registers/databases.
61  *
62  * Revision 1.37  1996/05/14  06:16:48  adam
63  * Compact use/set bytes used in search service.
64  *
65  * Revision 1.36  1996/05/01 13:46:37  adam
66  * First work on multiple records in one file.
67  * New option, -offset, to the "unread" command in the filter module.
68  *
69  * Revision 1.35  1996/03/26  16:01:14  adam
70  * New setting lockPath: directory of various lock files.
71  *
72  * Revision 1.34  1996/03/20  09:36:46  adam
73  * Function dict_lookup_grep got extra parameter, init_pos, which marks
74  * from which position in pattern approximate pattern matching should occur.
75  * Approximate pattern matching is used in relevance=re-2.
76  *
77  * Revision 1.33  1996/01/17  14:57:56  adam
78  * Prototype changed for reader functions in extract/retrieve. File
79  *  is identified by 'void *' instead of 'int.
80  *
81  * Revision 1.32  1995/12/11  09:12:58  adam
82  * The rec_get function returns NULL if record doesn't exist - will
83  * happen in the server if the result set records have been deleted since
84  * the creation of the set (i.e. the search).
85  * The server saves a result temporarily if it is 'volatile', i.e. the
86  * set is register dependent.
87  *
88  * Revision 1.31  1995/12/08  16:22:56  adam
89  * Work on update while servers are running. Three lock files introduced.
90  * The servers reload their registers when necessary, but they don't
91  * reestablish result sets yet.
92  *
93  * Revision 1.30  1995/12/07  17:38:48  adam
94  * Work locking mechanisms for concurrent updates/commit.
95  *
96  * Revision 1.29  1995/12/04  14:22:32  adam
97  * Extra arg to recType_byName.
98  * Started work on new regular expression parsed input to
99  * structured records.
100  *
101  * Revision 1.28  1995/11/28  09:09:48  adam
102  * Zebra config renamed.
103  * Use setting 'recordId' to identify record now.
104  * Bug fix in recindex.c: rec_release_blocks was invokeded even
105  * though the blocks were already released.
106  * File traversal properly deletes records when needed.
107  *
108  * Revision 1.27  1995/11/27  13:58:54  adam
109  * New option -t. storeStore data implemented in server.
110  *
111  * Revision 1.26  1995/11/25  10:24:07  adam
112  * More record fields - they are enumerated now.
113  * New options: flagStoreData flagStoreKey.
114  *
115  * Revision 1.25  1995/11/21  15:29:13  adam
116  * Config file 'base' read by default by both indexer and server.
117  *
118  * Revision 1.24  1995/11/20  16:59:47  adam
119  * New update method: the 'old' keys are saved for each records.
120  *
121  * Revision 1.23  1995/11/16  17:00:56  adam
122  * Better logging of rpn query.
123  *
124  * Revision 1.22  1995/11/16  15:34:55  adam
125  * Uses new record management system in both indexer and server.
126  *
127  * Revision 1.21  1995/11/01  16:25:52  quinn
128  * *** empty log message ***
129  *
130  * Revision 1.20  1995/10/27  14:00:12  adam
131  * Implemented detection of database availability.
132  *
133  * Revision 1.19  1995/10/17  18:02:11  adam
134  * New feature: databases. Implemented as prefix to words in dictionary.
135  *
136  * Revision 1.18  1995/10/16  14:03:09  quinn
137  * Changes to support element set names and espec1
138  *
139  * Revision 1.17  1995/10/16  09:32:40  adam
140  * More work on relational op.
141  *
142  * Revision 1.16  1995/10/13  12:26:44  adam
143  * Optimization of truncation.
144  *
145  * Revision 1.15  1995/10/12  12:40:55  adam
146  * Bug fixes in rpn_prox.
147  *
148  * Revision 1.14  1995/10/09  16:18:37  adam
149  * Function dict_lookup_grep got extra client data parameter.
150  *
151  * Revision 1.13  1995/10/06  14:38:00  adam
152  * New result set method: r_score.
153  * Local no (sysno) and score is transferred to retrieveCtrl.
154  *
155  * Revision 1.12  1995/10/06  13:52:06  adam
156  * Bug fixes. Handler may abort further scanning.
157  *
158  * Revision 1.11  1995/10/06  10:43:57  adam
159  * Scan added. 'occurrences' in scan entries not set yet.
160  *
161  * Revision 1.10  1995/10/02  16:43:32  quinn
162  * Set default resulting record type in fetch.
163  *
164  * Revision 1.9  1995/10/02  15:18:52  adam
165  * New member in recRetrieveCtrl: diagnostic.
166  *
167  * Revision 1.8  1995/09/28  09:19:47  adam
168  * xfree/xmalloc used everywhere.
169  * Extract/retrieve method seems to work for text records.
170  *
171  * Revision 1.7  1995/09/27  16:17:32  adam
172  * More work on retrieve.
173  *
174  * Revision 1.6  1995/09/08  08:53:22  adam
175  * Record buffer maintained in server_info.
176  *
177  * Revision 1.5  1995/09/06  16:11:18  adam
178  * Option: only one word key per file.
179  *
180  * Revision 1.4  1995/09/06  10:33:04  adam
181  * More work on present. Some log messages removed.
182  *
183  * Revision 1.3  1995/09/05  15:28:40  adam
184  * More work on search engine.
185  *
186  * Revision 1.2  1995/09/04  12:33:43  adam
187  * Various cleanup. YAZ util used instead.
188  *
189  * Revision 1.1  1995/09/04  09:10:41  adam
190  * More work on index add/del/update.
191  * Merge sort implemented.
192  * Initial work on z39 server.
193  *
194  */
195 #include <stdio.h>
196 #include <assert.h>
197 #ifdef WINDOWS
198 #include <io.h>
199 #include <process.h>
200 #else
201 #include <unistd.h>
202 #endif
203 #include <fcntl.h>
204
205 #include <data1.h>
206 #include <recctrl.h>
207 #include <dmalloc.h>
208
209 #include "zserver.h"
210
211 static int register_lock (ZServerInfo *zi)
212 {
213     time_t lastChange;
214     int state = zebra_server_lock_get_state(zi, &lastChange);
215
216     switch (state)
217     {
218     case 'c':
219         state = 1;
220         break;
221     default:
222         state = 0;
223     }
224     zebra_server_lock (zi, state);
225 #if USE_TIMES
226     times (&zi->tms1);
227 #endif
228     if (zi->registerState == state)
229     {
230         if (zi->registerChange >= lastChange)
231             return 0;
232         logf (LOG_LOG, "Register completely updated since last access");
233     }
234     else if (zi->registerState == -1)
235         logf (LOG_LOG, "Reading register using state %d pid=%ld", state,
236               (long) getpid());
237     else
238         logf (LOG_LOG, "Register has changed state from %d to %d",
239               zi->registerState, state);
240     zi->registerChange = lastChange;
241     if (zi->records)
242     {
243         zebTargetInfo_close (zi->zti, 0);
244         dict_close (zi->dict);
245         if (zi->isam)
246             is_close (zi->isam);
247         if (zi->isamc)
248             isc_close (zi->isamc);
249         rec_close (&zi->records);
250     }
251     bf_cache (zi->bfs, state ? res_get (zi->res, "shadow") : NULL);
252     zi->registerState = state;
253     zi->records = rec_open (zi->bfs, 0);
254     if (!(zi->dict = dict_open (zi->bfs, FNAME_DICT, 40, 0)))
255         return -1;
256     zi->isam = NULL;
257     zi->isamc = NULL;
258     if (res_get_match (zi->res, "isam", "c", NULL))
259     {
260         if (!(zi->isamc = isc_open (zi->bfs, FNAME_ISAMC,
261                                     0, key_isamc_m(zi->res))))
262             return -1;
263
264     }
265     else
266     {
267         if (!(zi->isam = is_open (zi->bfs, FNAME_ISAM, key_compare, 0,
268                                   sizeof (struct it_key), zi->res)))
269             return -1;
270     }
271     zi->zti = zebTargetInfo_open (zi->records, 0);
272
273     return 0;
274 }
275
276 static void register_unlock (ZServerInfo *zi)
277 {
278     static int waitSec = -1;
279
280 #if USE_TIMES
281     times (&zi->tms2);
282     logf (LOG_LOG, "user/system: %ld/%ld",
283                         (long) (zi->tms2.tms_utime - zi->tms1.tms_utime),
284                         (long) (zi->tms2.tms_stime - zi->tms1.tms_stime));
285 #endif
286     if (waitSec == -1)
287     {
288         char *s = res_get (zi->res, "debugRequestWait");
289         if (s)
290             waitSec = atoi (s);
291         else
292             waitSec = 0;
293     }
294 #ifdef WINDOWS
295 #else
296     if (waitSec > 0)
297         sleep (waitSec);
298 #endif
299     if (zi->registerState != -1)
300         zebra_server_unlock (zi, zi->registerState);
301 }
302
303 bend_initresult *bend_init (bend_initrequest *q)
304 {
305     bend_initresult *r = odr_malloc (q->stream, sizeof(*r));
306     ZServerInfo *zi = xmalloc (sizeof(*zi));
307     struct statserv_options_block *sob;
308
309     r->errcode = 0;
310     r->errstring = 0;
311     r->handle = zi;
312
313     logf (LOG_DEBUG, "bend_init");
314
315     sob = statserv_getcontrol ();
316     logf (LOG_LOG, "Reading resources from %s", sob->configname);
317     if (!(zi->res = res_open (sob->configname)))
318     {
319         logf (LOG_FATAL, "Cannot open resource `%s'", sob->configname);
320         exit (1);
321     }
322     zebra_server_lock_init (zi);
323     zi->dh = data1_create ();
324     zi->bfs = bfs_create (res_get (zi->res, "register"));
325     bf_lockDir (zi->bfs, res_get (zi->res, "lockDir"));
326     data1_set_tabpath (zi->dh, res_get(zi->res, "profilePath"));
327     zi->sets = NULL;
328     zi->registerState = -1;  /* trigger open of registers! */
329     zi->registerChange = 0;
330
331     zi->records = NULL;
332     zi->odr = odr_createmem (ODR_ENCODE);
333     zi->registered_sets = NULL;
334     zi->zebra_maps = zebra_maps_open (res_get(zi->res, "profilePath"),
335                                       zi->res);
336     return r;
337 }
338
339 bend_searchresult *bend_search (void *handle, bend_searchrequest *q, int *fd)
340 {
341     ZServerInfo *zi = handle;
342     bend_searchresult *r = odr_malloc (q->stream, sizeof(*r));
343
344     r->errcode = 0;
345     r->errstring = 0;
346     r->hits = 0;
347
348     register_lock (zi);
349     odr_reset (zi->odr);
350     zi->errCode = 0;
351     zi->errString = NULL;
352
353     logf (LOG_LOG, "ResultSet '%s'", q->setname);
354     switch (q->query->which)
355     {
356     case Z_Query_type_1: case Z_Query_type_101:
357         r->errcode = rpn_search (zi, q->query->u.type_1,
358                                 q->num_bases, q->basenames, q->setname,
359                                 &r->hits);
360         r->errstring = zi->errString;
361         break;
362     default:
363         r->errcode = 107;
364     }
365     register_unlock (zi);
366     return r;
367 }
368
369 struct fetch_control {
370     int record_offset;
371     int record_int_pos;
372     char *record_int_buf;
373     int record_int_len;
374     int fd;
375 };
376
377 static int record_ext_read (void *fh, char *buf, size_t count)
378 {
379     struct fetch_control *fc = fh;
380     return read (fc->fd, buf, count);
381 }
382
383 static off_t record_ext_seek (void *fh, off_t offset)
384 {
385     struct fetch_control *fc = fh;
386     return lseek (fc->fd, offset + fc->record_offset, SEEK_SET);
387 }
388
389 static off_t record_ext_tell (void *fh)
390 {
391     struct fetch_control *fc = fh;
392     return lseek (fc->fd, 0, SEEK_CUR) - fc->record_offset;
393 }
394
395 static off_t record_int_seek (void *fh, off_t offset)
396 {
397     struct fetch_control *fc = fh;
398     return (off_t) (fc->record_int_pos = offset);
399 }
400
401 static off_t record_int_tell (void *fh)
402 {
403     struct fetch_control *fc = fh;
404     return (off_t) fc->record_int_pos;
405 }
406
407 static int record_int_read (void *fh, char *buf, size_t count)
408 {
409     struct fetch_control *fc = fh;
410     int l = fc->record_int_len - fc->record_int_pos;
411     if (l <= 0)
412         return 0;
413     l = (l < count) ? l : count;
414     memcpy (buf, fc->record_int_buf + fc->record_int_pos, l);
415     fc->record_int_pos += l;
416     return l;
417 }
418
419 static int record_fetch (ZServerInfo *zi, int sysno, int score, ODR stream,
420                           oid_value input_format, Z_RecordComposition *comp,
421                           oid_value *output_format, char **rec_bufp,
422                           int *rec_lenp, char **basenamep)
423 {
424     Record rec;
425     char *fname, *file_type, *basename;
426     RecType rt;
427     struct recRetrieveCtrl retrieveCtrl;
428     char subType[128];
429     struct fetch_control fc;
430
431     rec = rec_get (zi->records, sysno);
432     if (!rec)
433     {
434         logf (LOG_DEBUG, "rec_get fail on sysno=%d", sysno);
435         return 14;
436     }
437     file_type = rec->info[recInfo_fileType];
438     fname = rec->info[recInfo_filename];
439     basename = rec->info[recInfo_databaseName];
440     *basenamep = odr_malloc (stream, strlen(basename)+1);
441     strcpy (*basenamep, basename);
442
443     if (!(rt = recType_byName (file_type, subType)))
444     {
445         logf (LOG_FATAL|LOG_ERRNO, "Retrieve: Cannot handle type %s", 
446               file_type);
447         exit (1);
448     }
449     logf (LOG_DEBUG, "retrieve localno=%d score=%d", sysno, score);
450     retrieveCtrl.fh = &fc;
451     fc.fd = -1;
452     if (rec->size[recInfo_storeData] > 0)
453     {
454         retrieveCtrl.readf = record_int_read;
455         retrieveCtrl.seekf = record_int_seek;
456         retrieveCtrl.tellf = record_int_tell;
457         fc.record_int_len = rec->size[recInfo_storeData];
458         fc.record_int_buf = rec->info[recInfo_storeData];
459         fc.record_int_pos = 0;
460         logf (LOG_DEBUG, "Internal retrieve. %d bytes", fc.record_int_len);
461     }
462     else 
463     {
464         if ((fc.fd = open (fname, O_BINARY|O_RDONLY)) == -1)
465         {
466             logf (LOG_WARN|LOG_ERRNO, "Retrieve fail; missing file: %s",
467                   fname);
468             rec_rm (&rec);
469             return 14;
470         }
471         memcpy (&fc.record_offset, rec->info[recInfo_offset],
472                 sizeof(fc.record_offset));
473
474         retrieveCtrl.readf = record_ext_read;
475         retrieveCtrl.seekf = record_ext_seek;
476         retrieveCtrl.tellf = record_ext_tell;
477
478         record_ext_seek (retrieveCtrl.fh, 0);
479     }
480     retrieveCtrl.subType = subType;
481     retrieveCtrl.localno = sysno;
482     retrieveCtrl.score = score;
483     retrieveCtrl.odr = stream;
484     retrieveCtrl.input_format = retrieveCtrl.output_format = input_format;
485     retrieveCtrl.comp = comp;
486     retrieveCtrl.diagnostic = 0;
487     retrieveCtrl.dh = zi->dh;
488     (*rt->retrieve)(&retrieveCtrl);
489     *output_format = retrieveCtrl.output_format;
490     *rec_bufp = retrieveCtrl.rec_buf;
491     *rec_lenp = retrieveCtrl.rec_len;
492     if (fc.fd != -1)
493         close (fc.fd);
494     rec_rm (&rec);
495
496     return retrieveCtrl.diagnostic;
497 }
498
499 bend_fetchresult *bend_fetch (void *handle, bend_fetchrequest *q, int *num)
500 {
501     ZServerInfo *zi = handle;
502     bend_fetchresult *r = odr_malloc (q->stream, sizeof(*r));
503     int positions[2];
504     ZServerSetSysno *records;
505
506     register_lock (zi);
507
508     r->errstring = 0;
509     r->last_in_set = 0;
510     r->basename = "base";
511
512     odr_reset (zi->odr);
513     zi->errCode = 0;
514
515     positions[0] = q->number;
516     records = resultSetSysnoGet (zi, q->setname, 1, positions);
517     if (!records)
518     {
519         logf (LOG_DEBUG, "resultSetRecordGet, error");
520         r->errcode = 13;
521         register_unlock (zi);
522         return r;
523     }
524     if (!records[0].sysno)
525     {
526         r->errcode = 13;
527         logf (LOG_DEBUG, "Out of range. pos=%d", q->number);
528         register_unlock (zi);
529         return r;
530     }
531     r->errcode = record_fetch (zi, records[0].sysno,
532                               records[0].score, q->stream, q->format,
533                               q->comp, &r->format, &r->record, &r->len,
534                               &r->basename);
535     resultSetSysnoDel (zi, records, 1);
536     register_unlock (zi);
537     return r;
538 }
539
540 bend_deleteresult *bend_delete (void *handle, bend_deleterequest *q, int *num)
541 {
542     ZServerInfo *zi = handle;
543     register_lock (zi);
544     register_unlock (zi);
545     return 0;
546 }
547
548 bend_scanresult *bend_scan (void *handle, bend_scanrequest *q, int *num)
549 {
550     ZServerInfo *zi = handle;
551     bend_scanresult *r = odr_malloc (q->stream, sizeof(*r));
552     int status;
553
554     register_lock (zi);
555     odr_reset (zi->odr);
556     zi->errCode = 0;
557     zi->errString = 0;
558
559     r->term_position = q->term_position;
560     r->num_entries = q->num_entries;
561     r->errcode = rpn_scan (zi, q->term,
562                           q->attributeset,
563                           q->num_bases, q->basenames,
564                           &r->term_position,
565                           &r->num_entries, &r->entries, &status);
566     r->errstring = zi->errString;
567     r->status = status;
568     register_unlock (zi);
569     return r;
570 }
571
572 void bend_close (void *handle)
573 {
574     ZServerInfo *zi = handle;
575
576     if (zi->records)
577     {
578         resultSetDestroy (zi);
579         zebTargetInfo_close (zi->zti, 0);
580         dict_close (zi->dict);
581         if (zi->isam)
582             is_close (zi->isam);
583         if (zi->isamc)
584             isc_close (zi->isamc);
585         rec_close (&zi->records);
586         register_unlock (zi);
587     }
588     odr_destroy (zi->odr);
589     zebra_maps_close (zi->zebra_maps);
590     bfs_destroy (zi->bfs);
591     data1_destroy (zi->dh);
592     zebra_server_lock_destroy (zi);
593
594     res_close (zi->res);
595     xfree (zi);
596 }
597
598 #ifndef WINDOWS
599 static void pre_init (struct statserv_options_block *sob)
600 {
601     char *pidfile = "zebrasrv.pid";
602     int fd = creat (pidfile, 0666);
603     
604     if (fd == -1)
605         logf (LOG_WARN|LOG_ERRNO, "creat %s", pidfile);
606     else
607     {
608         char pidstr[30];
609         
610         sprintf (pidstr, "%ld", (long) getpid ());
611         write (fd, pidstr, strlen(pidstr));
612         close (fd);
613     }
614 }
615 #endif
616
617 int main (int argc, char **argv)
618 {
619     struct statserv_options_block *sob;
620
621     sob = statserv_getcontrol ();
622     strcpy (sob->configname, FNAME_CONFIG);
623 #ifndef WINDOWS
624     sob->pre_init = pre_init;
625 #endif
626     statserv_setcontrol (sob);
627
628     return statserv_main (argc, argv);
629 }