-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.c
3607 lines (3408 loc) · 122 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 1994 Sun Wu, Udi Manber, Burra Gopal. All Rights Reserved. */
/* bgopal: (1993-4) redesigned/rewritten using agrep's library interface */
#include <autoconf.h>
#include <sys/param.h>
#include <errno.h>
#include "glimpse.h"
#include "defs.h"
#include <fcntl.h>
#include "checkfile.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/file.h> /* for flock definition */
#if ISO_CHAR_SET
#include <locale.h> /* support for 8bit character set */
#endif
#define CLIENTSERVER 1
#define USE_MSGHDR 0
#define USE_UNIXDOMAIN 0
#define DEBUG 0
#define DEF_SERV_PORT 2001
#define MIN_SERV_PORT 1024
#define MAX_SERV_PORT 30000
#define SERVER_QUEUE_SIZE 10 /* number of requests to buffer up while processing one request = 5 */
/* Borrowed from C-Lib */
extern char **environ;
extern int errno;
#if CLIENTSERVER
#include "communicate.c"
#endif /*CLIENTSERVER*/
/* For client-server protocol */
CHAR *SERV_HOST = NULL;
int SERV_PORT;
char glimpse_reqbuf[MAX_ARGS*MAX_NAME_LEN];
extern int glimpse_clientdied; /* set if signal received about dead socket: need agrep variable so that exec() can return quickly */
int glimpse_reinitialize = 0;
/* Borrowed from agrep.c */
extern int D_length; /* global variable in agrep */
extern int D; /* global variable in agrep */
extern int pattern_index;
/* These are used for byte level index search */
extern CHAR CurrentFileName[MAX_LINE_LEN];
extern int SetCurrentFileName;
extern int CurrentByteOffset;
extern int SetCurrentByteOffset;
extern long CurrentFileTime;
extern int SetCurrentFileTime;
extern int execfd;
extern int agrep_initialfd;
extern CHAR *agrep_inbuffer;
extern int agrep_inlen;
extern int agrep_inpointer;
extern FILE *agrep_finalfp;
extern CHAR *agrep_outbuffer;
extern int agrep_outlen;
extern int agrep_outpointer;
extern int glimpse_call; /* prevent agrep from printing out its usage */
extern int glimpse_isserver; /* prevent agrep from asking for user input */
int first_search = 1; /* intra/interaction in process_query() and glimpse_search() */
#if ISSERVER
int RemoteFiles = 0; /* Are the files present locally or remotely? If on, then -NQ is automatically added to all search options for each query */
#endif
/* Borrowed from index/io.c */
extern int InfoAfterFilename;
extern int OneFilePerBlock;
extern int StructuredIndex;
extern unsigned int *dest_index_set;
extern unsigned char *dest_index_buf;
extern unsigned int *src_index_set;
extern unsigned char *src_index_buf;
extern unsigned char *merge_index_buf;
extern int mask_int[32];
extern int indexable_char[256];
int test_indexable_char[256];
extern int p_table[MAX_PARTITION];
extern int GMAX_WORD_SIZE;
extern int IndexNumber; /* used in getword() */
extern int InterpretSpecial; /* used to "not-split" agrep-regexps */
extern int UseFilters; /* defined in build_in.c, used for filtering routines in io.c */
extern int ByteLevelIndex;
extern int RecordLevelIndex;
extern int rdelim_len;
extern char rdelim[MAX_LINE_LEN];
extern char old_rdelim[MAX_LINE_LEN];
extern int file_num;
extern int REAL_PARTITION, REAL_INDEX_BUF, MAX_ALL_INDEX, FILEMASK_SIZE;
/* Borrowed from get_filename.c */
extern int bigbuffer_size;
extern char *bigbuffer;
extern char *outputbuffer;
/* OPTIONS/FLAGS */
int veryfast = 0;
int CONTACT_SERVER = 0; /* Should client try to call server at all or just process query on its own? */
int NOBYTELEVEL = 0; /* Some cases where we cannot do byte level fast-search: ALWAYS 0 if !ByteLevelIndex */
int OPTIMIZEBYTELEVEL = 0; /* Some cases where we don't want to do byte level search since number of files is small */
int GCONSTANT = 0; /* should pattern be taken as-is or parsed? */
int GLIMITOUTPUT = 0; /* max no. of output lines: 0=>infinity=default=nolimit */
int GLIMITTOTALFILE = 0; /* max no. of files to match: 0=>infinity=default=nolimit */
int GLIMITPERFILE = 0; /* not used in glimpse */
int GBESTMATCH = 0; /* Should I change -B to -# where # = no. of errors? */
int GRECURSIVE = 0;
int GNOPROMPT = 0;
int GBYTECOUNT = 0;
int GPRINTFILENUMBER = 0;
int GPRINTFILETIME = 0;
int GOUTTAIL = 0;
int GFILENAMEONLY = 0; /* how to do it if it is an and expression in structured queries */
int GNOFILENAME=0;
int GPRINTNONEXISTENTFILE = 0; /* if filename is not there in index, then at least let user know its name */
int MATCHFILE = 0;
int PRINTATTR = 0;
int PRINTINDEXLINE = 0;
int Pat_as_is=0;
int Only_first=0; /* Do index search only */
int PRINTAPPXFILEMATCH=0; /* Print places in file where match occurs: useful with -b only to analyse the index */
int GCOUNT=0; /* print number of matches rather than actual matches: used only when PRINTAPPX = 1 */
int HINTSFROMUSER=0; /* The user gives the hints about where we should search (result of adding -EQNgy) */
int WHOLEFILESCOPE=0; /* used only when foundattr is NOT set: otherwise, scope is whole file anyway */
int foundattr=0; /* set in split.c -- != 0 only when StructuredIndex AND query is structured */
int foundnot=0; /* set in split.c -- != 0 only when the not operator (~) is present in the pattern */
int FILENAMESINFILE=0; /* whether the user is providing an explicit list of filenames to be searched for pattern (if absent, then means all files) */
int BITFIELDFILE=0; /* Based on contribution From [email protected] Fri Jul 12 01:56 MST 1996; Christer Holgersson, Sen. SysNet Mgr, Umea University/SUNET, Sweden */
int BITFIELDOFFSET=0;
int BITFIELDLENGTH=0;
int BITFIELDENDIAN=0;
int GNumDays = 0; /* whether the user wants files modified within these many days before creating the index: only >0 makes sense */
/* structured queries */
CHAR ***attr_vals; /* matrix of char pointers: row=max #of attributes, col=max possible values */
CHAR **attr_found; /* did the expression corr. to each value in attr_vals match? */
ParseTree *GParse; /* what kind of expression corr. to attr are we looking for */
/* arbitrary booleans */
ParseTree terminals[MAXNUM_PAT]; /* parse tree's terminal node pointers pt. to elements of this array; also used outside */
char matched_terminals[MAXNUM_PAT]; /* ...[i] is 1 if i'th terminal matched: used in filter_output and eval_tree */
int num_terminals; /* number of terminal patterns */
int ComplexBoolean=0; /* 1 if we need to use parse trees and the eval function */
/* index search */
CHAR *pat_list[MAXNUM_PAT]; /* complete words within global pattern */
int pat_lens[MAXNUM_PAT]; /* their lengths */
int pat_attr[MAXNUM_PAT]; /* set of attributes */
int is_mgrep_pat[MAXNUM_PAT];
int mgrep_pat_index[MAXNUM_PAT];
int num_mgrep_pat;
CHAR pat_buf[(MAXNUM_PAT + 2)*MAXPAT];
int pat_ptr = 0;
extern char INDEX_DIR[MAX_LINE_LEN];
char *TEMP_DIR = NULL; /* directory to store glimpse temporary files, usually /tmp unless -T is specified */
char indexnumberbuf[256]; /* to read in first few lines of the index */
char *index_argv[MAX_ARGS];
int index_argc = 0;
int bestmatcherrors=0; /* set during index search, used later on */
int patindex;
int patbufpos = -1;
char tempfile[MAX_NAME_LEN];
char *filenames_file = NULL;
char *bitfield_file = NULL;
/* agrep search */
char *agrep_argv[MAX_ARGS];
int agrep_argc = 0;
CHAR *FileOpt; /* the option list after -F */
int fileopt_length;
CHAR GPattern[MAXPAT];
int GM;
CHAR APattern[MAXPAT];
int AM;
CHAR GD_pattern[MAXPAT];
int GD_length;
CHAR **GTextfiles;
CHAR **GTextfilenames;
int *GFileIndex;
int GNumfiles;
int GNumpartitions;
CHAR GProgname[MAXNAME];
/* persistent file descriptors */
#if BG_DEBUG
FILE *debug; /* file descriptor for debugging output */
#endif /*BG_DEBUG*/
FILE *timesfp = NULL;
FILE *timesindexfp = NULL;
FILE *indexfp = NULL; /* glimpse index */
FILE *partfp = NULL; /* glimpse partitions */
FILE *minifp = NULL; /* glimpse turbo */
FILE *nullfp = NULL; /* to discard output: agrep -s doesn't work properly */
int svstdin = 0, svstdout = 1, svstderr = 2;
static int one = 1; /* to set socket option so that glimpseserver releases socket after death */
/* Index manipulation */
struct offsets **src_offset_table;
struct offsets **multi_dest_offset_table[MAXNUM_PAT];
unsigned int *multi_dest_index_set[MAXNUM_PAT];
extern free_list();
struct stat index_stat_buf, file_stat_buf;
int timesindexsize = 0;
int last_Y_filenumber = 0;
/* Direct agrep access for bytelevel-indices */
extern int COUNT, INVERSE, TCOMPRESSED, NOFILENAME, POST_FILTER, OUTTAIL, BYTECOUNT, SILENT, NEW_FILE,
LIMITOUTPUT, LIMITPERFILE, LIMITTOTALFILE, PRINTRECORD, DELIMITER, SILENT, FILENAMEONLY, num_of_matched, prev_num_of_matched, FILEOUT;
CHAR matched_region[MAX_REGION_LIMIT*2 + MAXPATT*2];
int RegionLimit=DEFAULT_REGION_LIMIT;
/* Returns number of matched records/lines. Uses agrep's options to output stuff nicely; never called with RecordLevelIndex set */
int
glimpse_search(AM, APattern, GD_length, GD_pattern, realfilename, filename, fileindex, src_offset_table, outfp)
int AM;
unsigned char APattern[];
int GD_length;
unsigned char GD_pattern[];
char *realfilename;
char *filename;
int fileindex;
struct offsets *src_offset_table[];
FILE *outfp;
{
FILE *infp;
char sig[SIGNATURE_LEN];
struct offsets **p1, *tp1;
CHAR *text, *curtextend, *curtextbegin, c;
int times;
int num, ret=0, totalret = 0;
int prevoffset = 0, begininterval = 0, endinterval = -1;
CHAR *beginregionptr = 0, *endregionptr = 0;
int beginpage = 0, endpage = -1;
static int MAXTIMES, MAXPGTIMES, pagesize;
static int first_time = 1;
/*
* If can't open file for read, quit
* For each offset for that file:
* seek to that point
* go back until delimiter, go forward until delimiter, output it: MAX_REGION_LIMIT is 16K on either side.
* read in units of RegionLimit
* before outputting matched record, use options to put prefixes (or use memagrep which does everything?)
* Algorithm changed: don't read same page in twice.
*/
if (first_time) {
pagesize = DISKBLOCKSIZE;
MAXTIMES = ((MAX_REGION_LIMIT / RegionLimit) > 1) ? (MAX_REGION_LIMIT / RegionLimit) : 1;
MAXPGTIMES = ((MAX_REGION_LIMIT / pagesize) > 1) ? (MAX_REGION_LIMIT / pagesize) : 1;
first_time = 0;
}
/* Safety: must end/begin with delim */
memcpy(matched_region, GD_pattern, GD_length);
memcpy(matched_region+MAXPATT+2*MAX_REGION_LIMIT, GD_pattern, GD_length);
text = &matched_region[MAX_REGION_LIMIT+MAXPATT];
if ((infp = my_fopen(filename, "r")) == NULL) return 0;
NEW_FILE = ON;
#if 0
/* Cannot search in .CZ files since offset computations will be incorrect */
TCOMPRESSED = ON;
if (!tuncompressible_filename(file_list[i], strlen(file_list[i]))) TCOMPRESSED = OFF;
num_read = fread(sig, 1, SIGNATURE_LEN, infp);
if ((TCOMPRESSED == ON) && tuncompressible(sig, num_read)) {
EASYSEARCH = sig[SIGNATURE_LEN-1];
if (!EASYSEARCH) {
fprintf(stderr, "not compressed for easy-search: can miss some matches in: %s\n", CurrentFileName); /* not filename!!! */
}
}
else TCOMPRESSED = OFF;
#endif /*0*/
p1 = &src_offset_table[fileindex];
while (*p1 != NULL) {
if ( (begininterval <= (*p1)->offset) && (endinterval > (*p1)->offset) ) { /* already covered this area */
#if DEBUG
printf("ignoring %d in [%d,%d]\n", (*p1)->offset, begininterval, endinterval);
#endif /*DEBUG*/
tp1 = *p1;
*p1 = (*p1)->next;
my_free(tp1, sizeof(struct offsets));
continue;
}
TCOMPRESSED = OFF;
#if 1
if ( (beginpage <= (*p1)->offset) && (endpage >= (*p1)->offset) && (text + ((*p1)->offset - prevoffset) + GD_length < endregionptr)) {
/* beginregionptr = curtextend - GD_length; /* prevent next curtextbegin to go behind previous curtextend (!) */
text += ((*p1)->offset - prevoffset);
prevoffset = (*p1)->offset;
if (!((curtextend = forward_delimiter(text, endregionptr, GD_pattern, GD_length, 1)) < endregionptr))
goto fresh_read;
if (!((curtextbegin = backward_delimiter(text, beginregionptr, GD_pattern, GD_length, 0)) > beginregionptr))
goto fresh_read;
}
else { /* NOT within an area already read: must read another page: if record overlapps page, might read page twice: no time to fix */
fresh_read:
prevoffset = (*p1)->offset;
text = &matched_region[MAX_REGION_LIMIT+MAXPATT]; /* middle: points to occurrence of pattern */
endpage = beginpage = ((*p1)->offset / pagesize) * pagesize;
/* endpage = (((*p1)->offset + pagesize) / pagesize) * pagesize */
endregionptr = beginregionptr = text - ((*p1)->offset - beginpage); /* overlay physical place starting from this logical point */
/* endregionptr = text + (endpage - (*p1)->offset); */
curtextbegin = curtextend = text;
times = 0;
while (times < MAXPGTIMES) {
fseek(infp, endpage, 0);
num = (&matched_region[MAX_REGION_LIMIT*2+MAXPATT] - endregionptr < pagesize) ? (&matched_region[MAX_REGION_LIMIT*2+MAXPATT] - endregionptr) : pagesize;
if ((num = fread(endregionptr, 1, num, infp)) <= 0) break;
endpage += num;
endregionptr += num;
if (endregionptr <= text) {
curtextend = text; /* error in value of offset: file was modified and offsets no longer true: your RISK! */
break;
}
if (((curtextend = forward_delimiter(text, endregionptr, GD_pattern, GD_length, 1)) < endregionptr) ||
(endregionptr >= &matched_region[MAX_REGION_LIMIT*2 + MAXPATT])) break;
times ++;
}
times = 0;
while (times < MAXPGTIMES) { /* I have already read the initial page since endpage is beginpage initially */
if ((curtextbegin = backward_delimiter(text, beginregionptr, GD_pattern, GD_length, 0)) > beginregionptr) break;
if (beginpage > 0) {
if (beginregionptr - pagesize < &matched_region[MAXPATT]) {
if ((num = beginregionptr - &matched_region[MAXPATT]) <= 0) break;
}
else num = pagesize;
beginpage -= num;
beginregionptr -= num;
}
else break;
times ++;
fseek(infp, beginpage, 0);
fread(beginregionptr, 1, num, infp);
}
}
#else /*1*/
/* Find forward delimiter (including delimiter) */
times = 0;
fseek(infp, (*p1)->offset, 0);
while (times < MAXTIMES) {
if ((num = fread(text+RegionLimit*times, 1, RegionLimit, infp)) > 0)
curtextend = forward_delimiter(text, text+RegionLimit*times+num, GD_pattern, GD_length, 1);
if ((curtextend < text+RegionLimit*times+num) || (num < RegionLimit)) break;
times ++;
}
/* Find backward delimiter (including delimiter) */
times = 0;
while (times < MAXTIMES) {
num = ((*p1)->offset - RegionLimit*(times+1)) > 0 ? ((*p1)->offset - RegionLimit*(times+1)) : 0;
fseek(infp, num, 0);
if (num > 0) {
fread(text-RegionLimit*(times+1), 1, RegionLimit, infp);
curtextbegin = backward_delimiter(text, text-RegionLimit*(times+1), GD_pattern, GD_length, 0);
}
else {
fread(text-RegionLimit*times-(*p1)->offset, 1, (*p1)->offset, infp);
curtextbegin = backward_delimiter(text, text-RegionLimit*times-(*p1)->offset, GD_pattern, GD_length, 0);
}
if ((num <= 0) || (curtextbegin > text-RegionLimit*(times+1))) break;
times ++;
}
#endif /*1*/
/* set interval and delete the entry */
begininterval = (*p1)->offset - (text - curtextbegin);
endinterval = (*p1)->offset + (curtextend - text);
if (strncmp(curtextbegin, GD_pattern, GD_length)) {
/* always pass enclosing delimiters to agrep; since we have seen text before curtextbegin + we have space, we can overwrite */
memcpy(curtextbegin - GD_length, GD_pattern, GD_length);
curtextbegin -= GD_length;
}
#if DEBUG
c = *curtextend;
*curtextend = '\0';
printf("%s [%d < %d < %d], text = %d: %s\n", CurrentFileName, begininterval, (*p1)->offset, endinterval, text, curtextbegin);
*curtextend = c;
#endif /*DEBUG*/
tp1 = *p1;
*p1 = (*p1)->next;
my_free(tp1, sizeof(struct offsets));
if (curtextend <= curtextbegin) continue; /* error in offsets/delims */
/*
* Don't call memagrep since that is heavy weight. Call exec
* directly after doing agrep_search()'s preprocessing here.
* PS: can add agrep variable not to do delim search if called from here
* since that prevents unnecessarily scanning the buffer for the 2nd time.
*/
CurrentByteOffset = begininterval+1;
SetCurrentByteOffset = 1;
first_search = 1;
if (first_search) {
if ((ret = memagrep_search(AM, APattern, curtextend-curtextbegin, curtextbegin, 0, outfp)) > 0)
totalret ++; /* += ret */
else if ((ret < 0) && (errno == AGREP_ERROR)) {
fclose(infp);
return -1;
}
first_search = 0;
}
else { /* All agrep globals are properly set: has a bug because agrep's globals aren't properly reinitialized without agrep_search :-( */
agrep_finalfp = (FILE *)outfp;
agrep_outlen = 0;
agrep_outbuffer = NULL;
agrep_outpointer = 0;
execfd = agrep_initialfd = -1;
agrep_inbuffer = curtextbegin;
agrep_inlen = curtextend - curtextbegin;
agrep_inpointer = 0;
if ((ret = exec(-1, NULL)) > 0)
totalret ++; /* += ret; */
else if ((ret < 0) && (errno == AGREP_ERROR)) {
fclose(infp);
return -1;
}
}
if (((LIMITOUTPUT > 0) && (LIMITOUTPUT <= num_of_matched)) ||
((LIMITPERFILE > 0) && (LIMITPERFILE <= num_of_matched - prev_num_of_matched))) break; /* done */
if ((totalret > 0) && FILENAMEONLY) break;
} /* while *p1 != NULL */
SetCurrentByteOffset = 0;
fclose(infp);
if (totalret > 0) { /* dirty solution: must handle part of agrep here */
if (COUNT && !FILEOUT && !SILENT) {
if(!NOFILENAME) fprintf(outfp, "%s: %d\n", CurrentFileName, totalret);
else fprintf(outfp, "%d\n", totalret);
}
else if (FILEOUT) {
file_out(realfilename);
}
}
return totalret;
}
/* Sets lastfilenumber that needs to be searched: rest must be discarded */
int
process_Y_option(num_files, num_days, fp)
int num_files, num_days;
FILE *fp;
{
CHAR arrayend[4];
last_Y_filenumber = 0;
if ((num_days <= 0) || (fp == NULL) || (timesindexsize <= 0)) return 0;
last_Y_filenumber = num_files;
if (num_days * sizeof(int) >= timesindexsize) return 0; /* everything will be within so many days */
if (fseek(fp, num_days*sizeof(int), 0) == -1) return -1;
fread(arrayend, 1, 4, fp);
if ((last_Y_filenumber = (arrayend[0] << 24) | (arrayend[1] << 16) | (arrayend[2] << 8) | arrayend[3]) > num_files) last_Y_filenumber = num_files;
if (last_Y_filenumber == 0) {
last_Y_filenumber = 1;
printf("Warning: no files modified in the last %d days were found in the index.\nSearching only the most recently modified file...\n", num_days);
}
return 0;
}
read_index(indexdir)
char indexdir[MAXNAME];
{
char *home;
char s[MAXNAME];
int ret;
if (indexdir[0] == '\0') {
if ((home = (char *)getenv("HOME")) == NULL) {
getcwd(indexdir, MAXNAME-1);
fprintf(stderr, "using working-directory '%s' to locate index\n", indexdir);
}
else strncpy(indexdir, home, MAXNAME);
}
ret = chdir(indexdir);
if (getcwd(INDEX_DIR, MAXNAME-1) == NULL) strcpy(INDEX_DIR, indexdir);
if (ret < 0) {
fprintf(stderr, "using working-directory '%s' to locate index\n", INDEX_DIR);
}
sprintf(s, "%s", INDEX_FILE);
indexfp = fopen(s, "r");
if(indexfp == NULL) {
fprintf(stderr, "can't open glimpse index-file %s/%s\n", INDEX_DIR, INDEX_FILE);
fprintf(stderr, "(use -H to give an index-directory or run 'glimpseindex' to make an index)\n");
return -1;
}
if (stat(s, &index_stat_buf) == -1) {
fprintf(stderr, "can't stat %s/%s\n", INDEX_DIR, s);
fclose(indexfp);
return -1;
}
sprintf(s, "%s", P_TABLE);
partfp = fopen(s, "r");
if(partfp == NULL) {
fprintf(stderr, "can't open glimpse partition-table %s/%s\n", INDEX_DIR, P_TABLE);
fprintf(stderr, "(use -H to specify an index-directory or run glimpseindex to make an index)\n");
fclose(indexfp);
return -1;
}
sprintf(s, "%s", DEF_TIME_FILE);
timesfp = fopen(s, "r");
sprintf(s, "%s.index", DEF_TIME_FILE);
timesindexfp = fopen(s, "r");
if (timesindexfp != NULL) {
struct stat st;
fstat(fileno(timesindexfp), &st);
timesindexsize = st.st_size;
}
/* Get options */
#if BG_DEBUG
debug = fopen(DEBUG_FILE, "w+");
if(debug == NULL) {
fprintf(stderr, "can't open file %s/%s, errno=%d\n", INDEX_DIR, DEBUG_FILE, errno);
return(-1);
}
#endif /*BG_DEBUG*/
fgets(indexnumberbuf, 256, indexfp);
if(strstr(indexnumberbuf, "1234567890")) IndexNumber = ON;
else IndexNumber = OFF;
fscanf(indexfp, "%%%d\n", &OneFilePerBlock);
if (OneFilePerBlock < 0) {
ByteLevelIndex = ON;
OneFilePerBlock = -OneFilePerBlock;
}
else if (OneFilePerBlock == 0) {
GNumpartitions = get_table(P_TABLE, p_table, MAX_PARTITION, 0);
}
fscanf(indexfp, "%%%d%s\n", &StructuredIndex, old_rdelim);
/* Set WHOLEFILESCOPE for do-it-yourself request processing at client */
WHOLEFILESCOPE = 1;
if (StructuredIndex <= 0) {
if (StructuredIndex == -2) {
RecordLevelIndex = 1;
strcpy(rdelim, old_rdelim);
rdelim_len = strlen(rdelim);
preprocess_delimiter(rdelim, rdelim_len, rdelim, &rdelim_len);
}
WHOLEFILESCOPE = 0;
StructuredIndex = 0;
PRINTATTR = 0; /* doesn't make sense: must not go into filter_output */
}
else if (-1 == (StructuredIndex = attr_load_names(ATTRIBUTE_FILE))) {
fprintf(stderr, "error in reading attribute file %s/%s\n", INDEX_DIR, ATTRIBUTE_FILE);
return(-1);
}
#if BG_DEBUG
fprintf(debug, "buf = %s OneFilePerBlock=%d StructuredIndex=%d\n", indexnumberbuf, OneFilePerBlock, StructuredIndex);
#endif /*BG_DEBUG*/
sprintf(s, "%s", MINI_FILE);
minifp = fopen(s, "r");
/* if (minifp==NULL && OneFilePerBlock) fprintf(stderr, "Can't open for reading: %s/%s --- cannot do very fast search\n", INDEX_DIR, MINI_FILE); */
if (OneFilePerBlock && glimpse_isserver && (minifp != NULL)) read_mini(indexfp, minifp);
read_filenames();
/* Once IndexNumber info is available */
set_indexable_char(indexable_char);
set_indexable_char(test_indexable_char);
set_special_char(indexable_char);
return 0;
}
#define CLEANUP \
{\
int q, k;\
if (timesfp != NULL) fclose(timesfp);\
if (timesindexfp != NULL) fclose(timesindexfp);\
if (indexfp != NULL) fclose(indexfp);\
if (partfp != NULL) fclose(partfp);\
if (minifp != NULL) fclose(minifp);\
if (nullfp != NULL) fclose(nullfp);\
indexfp = partfp = minifp = nullfp = NULL;\
if (ByteLevelIndex) {\
if (src_offset_table != NULL) for (k=0; k<OneFilePerBlock; k++) {\
free_list(&src_offset_table[k]);\
}\
for (q=0; q<MAXNUM_PAT; q++) {\
if (multi_dest_offset_table[q] != NULL) for (k=0; k<OneFilePerBlock; k++) {\
free_list(&multi_dest_offset_table[q][k]);\
}\
}\
}\
if (StructuredIndex) {\
attr_free_table();\
}\
destroy_filename_hashtable();\
my_free(SERV_HOST, MAXNAME);\
}
/* Called whenever we get SIGUSR2/SIGHUP (at the end of process_query()) */
reinitialize_server(argc, argv)
int argc;
char **argv;
{
int i, fd;
CLEANUP;
#if 0
init_filename_hashtable();
region_initialize();
indexfp = partfp = minifp = nullfp = NULL;
if ((nullfp = fopen("/dev/null", "w")) == NULL) {
return(-1);
}
src_offset_table = NULL;
for (i=0; i<MAXNUM_PAT; i++) multi_dest_offset_table[i] = NULL;
if (-1 == read_index(INDEX_DIR)) return(-1);
#if 0
#ifndef LOCK_UN
#define LOCK_UN 8
#endif
if ((fd = open(INDEX_DIR, O_RDONLY)) == -1) return -1;
flock(fd, LOCK_UN);
close(fd);
#endif
return 0;
#else
return execve(argv[0], argv, environ);
#endif
}
/* MUST CARE IF PIPE/SOCKET IS BROKEN! ALSO SIGUSR1 ([email protected]) => QUIT CURRENT REQUEST. */
int ignore_signal[32] = { 0,
0, 0, 1, 1, 1, 1, 1, 1, /* all the tracing stuff: since default action is to dump core */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0 }; /* resource lost: since default action is to dump core */
/* S.t. sockets don't persist: they sometimes have a bad habit of doing so */
void
cleanup()
{
int i;
/* ^C in the middle of a client call */
if (svstderr != 2) {
close(2);
dup(svstderr);
}
fprintf(stderr, "server cleaning up...\n");
CLEANUP;
for (i=0; i<64; i++) close(i);
exit(3);
}
void reinitialize(s)
int s;
{
/* To force main-while loop call reinitialize_server() after do_select() */
glimpse_reinitialize = 1;
#ifdef __svr4__
/* Solaris 2.3 insists that you reset the signal handler */
(void)signal(s, reinitialize);
#endif
}
#define QUITREQUESTMSG "glimpseserver: aborting request...\n"
/* S.t. one request doesn't keep server occupied too long, when client already quits */
void quitrequest(s)
int s;
{
/*
* Don't write onto stderr, since 2 is duped to sockfd => can cause recursive signal!
* Also, don't print error message more than once for quitting one request. The
* server receives signals for EVERY write it attempts when it finds a match: I could
* not find a way to prevent it, but agrep/bitap.c/fill_buf() was fixed to limit it.
* -- bg on 16th Feb 1995
*/
if (!glimpse_clientdied && (s != SIGUSR1)) /* USR1 is a "friendly" cleanup message */
write(svstderr, QUITREQUESTMSG, strlen(QUITREQUESTMSG));
glimpse_clientdied = 1;
#ifdef __svr4__
/* Solaris 2.3 insists that you reset the signal handler */
(void)signal(s, quitrequest);
#endif
}
/* The client receives this signal when an output/input pipe is broken, etc. It simply exits from the current request */
void exitrequest()
{
glimpse_clientdied = 1;
}
main(argc, argv)
int argc;
char *argv[];
{
int ret = 0, tried = 0;
char indexdir[MAXNAME];
char **oldargv = argv;
int oldargc = argc;
#if CLIENTSERVER
int sockfd, newsockfd, clilen, len, clpid;
int clout;
#if USE_UNIXDOMAIN
struct sockaddr_un cli_addr, serv_addr;
#else /*USE_UNIXDOMAIN*/
struct sockaddr_in cli_addr, serv_addr;
struct hostent *hp;
#endif /*USE_UNIXDOMAIN*/
int cli_len;
int clargc;
char **clargv;
int clstdin, clstdout, clstderr;
int i;
char array[4];
char *p, c;
#endif /*CLIENTSERVER*/
int quitwhile;
#if ISO_CHAR_SET
setlocale(LC_ALL,""); /* support for 8bit character set: [email protected], [email protected] */
#endif
#if CLIENTSERVER && ISSERVER
glimpse_isserver = 1; /* I am the server */
#else /*CLIENTSERVER && ISSERVER*/
if (argc <= 1) {
usage(); /* Client nees at least 1 argument */
exit(1);
}
#endif /*CLIENTSERVER && ISSERVER*/
#define RETURNMAIN(val)\
{\
CLEANUP;\
if (val < 0) exit (2);\
else if (val == 0) exit (1);\
else exit (0);\
}
SERV_HOST = (CHAR *)my_malloc(MAXNAME);
#if !SYSCALLTESTING
/* once-only initialization */
init_filename_hashtable();
src_offset_table = NULL;
for (i=0; i<MAXNUM_PAT; i++) multi_dest_offset_table[i] = NULL;
#endif
gethostname(SERV_HOST, MAXNAME - 2);
SERV_PORT = DEF_SERV_PORT;
srand(getpid());
umask(077);
strcpy(&GProgname[0], argv[0]);
#if !SYSCALLTESTING
region_initialize();
#endif
indexfp = partfp = minifp = nullfp = NULL;
if ((nullfp = fopen("/dev/null", "w")) == NULL) {
fprintf(stderr, "%s: cannot open for writing: /dev/null, errno=%d\n", argv[0], errno);
RETURNMAIN(-1);
}
InterpretSpecial = ON;
GMAX_WORD_SIZE = MAXPAT;
#if CLIENTSERVER
#if !ISSERVER
/* Install signal handlers so that glimpse doesn't continue to run when pipes get broken, etc. */
if (((void (*)())-1 == signal(SIGPIPE, exitrequest))
#ifndef SCO
|| ((void (*)())-1 == signal(SIGURG, exitrequest))
#endif
)
{
/* Check for return values here since they ensure reliability */
fprintf(stderr, "glimpse: Unable to install signal-handlers.\n");
RETURNMAIN(-1);
}
/* Check if client has too many arguments: then it is surely running as agrep since I have < half those options! */
if (argc > MAX_ARGS) goto doityourself;
#endif /*!ISSERVER*/
#if !SYSCALLTESTING
while((--argc > 0) && (*++argv)[0] == '-' ) {
p = argv[0] + 1; /* ptr to first character after '-' */
c = *(argv[0]+1);
if (*p == '-') { /* cheesy hack to support --version and --help options */
if (*(p+1) == 'v') {
c = 'V';
} else if (*(p+1) == 'h') {
c = '?';
}
}
quitwhile = OFF;
while (!quitwhile && (*p != '\0')) {
switch(c) {
/* Look for -H option at server (only one that makes sense); if client has a -H, then it goes to doityourself */
case 'H' :
if (*(p + 1) == '\0') {/* space after - option */
if (argc <= 1) {
fprintf(stderr, "%s: a directory name must follow the -H option\n", GProgname);
RETURNMAIN(usageS());
}
argv ++;
strcpy(indexdir, argv[0]);
argc --;
}
else {
strcpy(indexdir, p+1);
}
quitwhile = ON;
break;
/* Recognized by both client and server */
case 'J' :
if (*(p + 1) == '\0') {/* space after - option */
if (argc <= 1) {
fprintf(stderr, "%s: the server host name must follow the -J option\n", GProgname);
#if ISSERVER
RETURNMAIN(usageS());
#else /*ISSERVER*/
RETURNMAIN(usage());
#endif /*ISSERVER*/
}
argv ++;
strcpy(SERV_HOST, argv[0]);
argc --;
}
else {
strcpy(SERV_HOST, p+1);
}
quitwhile = ON;
break;
/* Recognized by both client and server */
case 'K' :
if (*(p + 1) == '\0') {/* space after - option */
if (argc <= 1) {
fprintf(stderr, "%s: the server port must follow the -C option\n", GProgname);
#if ISSERVER
RETURNMAIN(usageS());
#else /*ISSERVER*/
RETURNMAIN(usage());
#endif /*ISSERVER*/
}
argv ++;
SERV_PORT = atoi(argv[0]);
argc --;
}
else {
SERV_PORT = atoi(p+1);
}
if ((SERV_PORT < MIN_SERV_PORT) || (SERV_PORT > MAX_SERV_PORT)) {
fprintf(stderr, "Bad server port %d: must be in [%d, %d]: using default %d\n",
SERV_PORT, MIN_SERV_PORT, MAX_SERV_PORT, DEF_SERV_PORT);
SERV_PORT = DEF_SERV_PORT;
}
quitwhile = ON;
break;
#if ISSERVER
#if SFS_COMPAT
case 'R' :
RemoteFiles = ON;
break;
case 'Z' :
/* No op */
break;
#endif
case 'V' :
printf("\nThis is glimpseindex version %s, %s.\n\n", GLIMPSE_VERSION, GLIMPSE_DATE);
RETURNMAIN(1);
case '?' :
RETURNMAIN(usageS());
/* server cannot recognize any other option */
default :
fprintf(stderr, "%s: server cannot recognize option: '%s'\n", GProgname, p);
RETURNMAIN(usageS());
#else /*ISSERVER*/
/* These have 1 argument each, so must do quitwhile */
case 'd' :
case 'e' :
case 'f' :
case 'k' :
case 'D' :
case 'F' :
case 'I' :
case 'L' :
case 'R' :
case 'S' :
case 'T' :
case 'Y' :
case 'p' :
if (argv[0][2] == '\0') {/* space after - option */
if(argc <= 1) {
fprintf(stderr, "%s: the '-%c' option must have an argument\n", GProgname, c);
RETURNMAIN(usage());
}
argv++;
argc--;
}
quitwhile = ON;
break;
/* These are illegal */
case 'm' :
case 'v' :
fprintf(stderr, "%s: illegal option: '-%c'\n", GProgname, c);
RETURNMAIN(usage());
/* They can't be patterns and filenames since they start with a -, these don't have arguments */
case '!' :
case 'a' :
case 'b' :
case 'c' :
case 'h' :
case 'i' :
case 'j' :
case 'l' :
case 'n' :
case 'o' :
case 'q' :
case 'r' :
case 's' :
case 't' :
case 'u' :
case 'g' :
case 'w' :
case 'x' :
case 'y' :
case 'z' :
case 'A' :
case 'B' :
case 'E' :
case 'G' :
case 'M' :
case 'N' :
case 'O' :
case 'P' :
case 'Q' :
case 'U' :
case 'W' :
case 'X' :
case 'Z' :
break;
case 'C':
CONTACT_SERVER = 1;
break;
case 'V' :
printf("\nThis is glimpse version %s, %s.\n\n", GLIMPSE_VERSION, GLIMPSE_DATE);
RETURNMAIN(1);
case '?':
RETURNMAIN(usage());
default :
if (isdigit(c)) quitwhile = ON;
else {
fprintf(stderr, "%s: illegal option: '-%c'\n", GProgname, c);
RETURNMAIN(usage());
}
break;
#endif /*ISSERVER*/
} /* switch(c) */
p ++;
c = *p;
}
}
#else
CONTACT_SERVER = 1;
argc=0;
#endif
#if !ISSERVER
/* Next arg must be the pattern: Check if the user wants to run the client as agrep, or doesn't want to contact the server */
if ((argc > 1) || (!CONTACT_SERVER)) goto doityourself;
#endif /*!ISSERVER*/
argv = oldargv;
argc = oldargc;
#endif /*CLIENTSERVER*/
#if ISSERVER && CLIENTSERVER
if (-1 == read_index(indexdir)) RETURNMAIN(ret);
/* Install signal handlers so that glimpseserver doesn't continue to run when sockets get broken, etc. */
for (i=0; i<32; i++)
if (ignore_signal[i]) signal(i, SIG_IGN);
signal(SIGHUP, cleanup);
signal(SIGINT, cleanup);
if (((void (*)())-1 == signal(SIGPIPE, quitrequest)) ||
((void (*)())-1 == signal(SIGUSR1, quitrequest)) ||
#ifndef SCO
((void (*)())-1 == signal(SIGURG, quitrequest)) ||
#endif
((void (*)())-1 == signal(SIGUSR2, reinitialize)) ||
((void (*)())-1 == signal(SIGHUP, reinitialize))) {