-
Notifications
You must be signed in to change notification settings - Fork 0
/
licenses.c
1347 lines (1252 loc) · 40.9 KB
/
licenses.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) 2006-2013 Hewlett-Packard Development Company, L.P.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
***************************************************************/
/* Equivalent to core nomos v1.48 */
/**
* \file
* \brief utilities to scan, score and save license found data
*
* @version "$Id: licenses.c 4032 2011-04-05 22:16:20Z bobgo $"
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <signal.h>
#include <libgen.h>
#include <limits.h>
#include <stdlib.h>
#include "nomos.h"
#include "licenses.h"
#include "nomos_utils.h"
#include "util.h"
#include "list.h"
#include "nomos_regex.h"
#include "parse.h"
#include "_autodefs.h"
#define HASHES "#####################"
#define DEBCPYRIGHT "debian/copyright"
static void makeLicenseSummary(list_t *, int, char *, int);
static void noLicenseFound();
#ifdef notdef
static void licenseStringChecks();
static void findLines(char *, char *, int, int, list_t *);
#endif /* notdef */
static int searchStrategy(int, char *, int);
static void saveLicenseData(scanres_t *, int, int, int);
static int scoreCompare(const void *, const void *);
static void printHighlightInfo(GArray* keyWords, GArray* theMatches);
static char any[6];
static char some[7];
static char few[6];
static char year[7];
#ifdef MEMSTATS
extern void memStats();
#endif /* MEMSTATS */
#ifdef STOPWATCH
DECL_TIMER;
int timerBytes;
char timerName[64];
#endif /* STOPWATCH */
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? a : b) ///< Max of two
#define MIN(a, b) ((a) < (b) ? a : b) ///< Min of two
#endif
/**
* \brief license initialization
*/
void licenseInit() {
int i;
int len;
int same;
int ssAbove = 0;
int ssBelow = 0;
item_t *p;
char *cp;
char buf[myBUFSIZ];
#ifdef PROC_TRACE
traceFunc("== licenseInit()\n");
#endif /* PROC_TRACE */
strcpy(any, "=ANY=");
strcpy(some, "=SOME=");
strcpy(few, "=FEW=");
strcpy(year, "=YEAR=");
listInit(&gl.sHash, 0, "search-cache"); /* CDB - Added */
/**
* Examine the search strings in licSpec looking for 3 corner-cases
* to optimize all the regex-searches we'll be making:
* -# The seed string is the same as the text-search string
* -# The text-search string has length 1 and contents == "."
* -# The seed string is the 'null-string' indicator
*/
for (i = 0; i < NFOOTPRINTS; i++) {
same = 0;
len = licSpec[i].seed.csLen;
if (licSpec[i].text.csData == NULL_STR) {
licText[i].tseed = "(null)";
}
if ((licSpec[i].text.csLen == 1) && (*(licSpec[i].text.csData) == '.')) {
same++;
/*CDB -- CHanged next line to use ! */
}
else if ((licSpec[i].seed.csLen == licSpec[i].text.csLen) && !memcmp(
licSpec[i].seed.csData, licSpec[i].text.csData, len)) {
same++;
}
/**
* Step 1, copy the tseed "search seed", decrypt it, and munge any wild-
* cards in the string. Note that once we eliminate the compile-time
* string encryption, we could re-use the same exact data. In fact, some
* day (in our copious spare time), we could effectively remove licSpec.
*/
#ifdef FIX_STRINGS
fixSearchString(buf, sizeof(buf), i, YES);
#endif /* FIX_STRINGS */
licText[i].tseed = licSpec[i].seed.csData;
/*---------------------------------------*/
/* CDB - This is the code that I inadvertently removed. */
/**
* Step 2, add the search-seed to the search-cache
*/
if ((p = listGetItem(&gl.sHash, licText[i].tseed)) == NULL_ITEM) {
LOG_FATAL("Cannot enqueue search-cache item \"%s\"", licText[i].tseed)
Bail(-__LINE__);
}
p->refCount++;
/*--------------------------------*/
/**
* Step 3, handle special cases of NULL seeds and (regex == seed)
*/
if (strcmp(licText[i].tseed, "=NULL=") == 0) { /* null */
#ifdef OLD_DECRYPT
memFree(licText[i].tseed, MTAG_SEEDTEXT);
#endif /* OLD_DECRYPT */
licText[i].tseed = NULL_STR;
licText[i].nAbove = licText->nBelow = -1;
}
if (same) { /* seed == phrase */
licText[i].regex = licText[i].tseed;
#if 0
ssBelow = searchStrategy(i, buf, NO);
licText[i].nBelow = MIN(ssBelow, 2);
#endif
licText[i].nAbove = licText[i].nBelow = 0;
}
/**
* Step 4, decrypt and fix the regex (since seed != regex here). Once
* we have all that, searchStrategy() helps determine how many lines
* above and below [the seed] to save -- see findPhrase() for details.
*/
else { /* seed != phrase */
len = licSpec[i].text.csLen;
memcpy(buf, licSpec[i].text.csData, (size_t)(len + 1));
#ifdef OLD_DECRYPT
decrypt(buf, len);
#endif /* OLD_DECRYPT */
ssAbove = searchStrategy(i, buf, YES);
ssBelow = searchStrategy(i, buf, NO);
#if 0
licText[i].nAbove = MIN(ssAbove, 3);
licText[i].nBelow = MIN(ssBelow, 6);
#endif
licText[i].nAbove = licText[i].nBelow = 1; /* for now... */
#ifdef FIX_STRINGS
fixSearchString(buf, sizeof(buf), i, NO);
#endif /* FIX_STRINGS */
licText[i].regex = copyString(buf, MTAG_SRCHTEXT);
}
if (p->ssComp < (ssAbove * 100) + ssBelow) {
p->ssComp = (ssAbove * 100) + ssBelow;
}
licText[i].compiled = 0;
licText[i].plain = 1; /* assume plain-text for now */
}
/**
* Now that we've computed the above- and below-values for license
* searches, set each of the appropriate entries with the MAX values
* determined. Limit 'above' values to 3 and 'below' values to 6.
*****
* QUESTION: the above has worked in the past - is it STILL valid?
*/
for (i = 0; i < NFOOTPRINTS; i++) {
if (licText[i].tseed == NULL_STR) {
#ifdef LICENSE_DEBUG
LOG_NOTICE("License[%d] configured with NULL seed", i)
#endif /* LICENSE_DEBUG */
continue;
}
if (licText[i].tseed == licText[i].regex) {
#ifdef LICENSE_DEBUG
LOG_NOTICE("License[%d] seed == regex", i)
#endif /* LICENSE_DEBUG */
continue;
}
licText[i].nAbove = p->ssComp / 100;
licText[i].nBelow = p->ssComp % 100;
}
/**
* Finally (if enabled), compare each of the search strings to see if
* there are duplicates, and determine if some of the regexes can be
* searched via strstr() (instead of it's slower-but-more-functional
* regex brethern).
*/
for (i = 0; i < NFOOTPRINTS; i++) {
for (cp = _REGEX(i); licText[i].plain && *cp; cp++) {
switch (*cp) {
case '.':
case '*':
case '+':
case '|':
case '[':
case ']':
case '(':
case ')':
case '^':
case '$':
case '?':
case ',':
case '<':
case '>':
case '{':
case '}':
case '\\':
licText[i].plain = 0;
break;
}
}
if (i >= _CR_first && i <= _CR_last) {
continue;
}
}
return;
}
#define LINE_BYTES 50 /**< fudge for punctuation, etc. */
#define LINE_WORDS 8 /**< assume this many words per line */
#define WC_BYTES 30 /**< wild-card counts this many bytes */
#define WC_WORDS 3 /**< wild-card counts this many words */
#define PUNT_LINES 3 /**< if "dunno", guess this line-count */
#define MIN_LINES 1 /**< normal minimum-extra-lines */
/**
* \note This function should be called BEFORE the wild-card specifier =ANY=
* is converted to a REAL regex ".*" (e.g., before fixSearchString())!
*
* ASSUME a "standard line-length" of 50 characters/bytes. That's
* likely too small, but err on the side of being too conservative.
*
* Determining for the number of text-lines ABOVE involves finding out
* how far into the 'license footprint' the seed-word resides. ASSUME
* a standard line-length of 50 (probably too small, but we'll err on
* the side of being too conservative. If the seed isn't IN the regex,
* assume a generally-bad worst-case and search 2-3 lines above.
*
* Determining for the number of text-lines BELOW involves finding out
* how long the 'license footprint' actually is, plus adding some fudge
* based on the number of wild-cards in the footprint.
* \param index License index from Strings.in
* \param regex regex to match for
* \param aboveCalc Set to look above
*/
static int searchStrategy(int index, char *regex, int aboveCalc) {
char *start;
char *cp;
char *s;
char seed[myBUFSIZ];
int words;
int lines;
int bytes;
int minLines;
int matchWild;
int matchSeed;
#ifdef PROC_TRACE
traceFunc("== searchStrategy(%d(%s), \"%s\", %d)\n", index,
_SEED(index), regex, aboveCalc);
#endif /* PROC_TRACE */
s = _SEED(index);
if (s == NULL_STR || strlen(s) == 0) {
#ifdef LICENSE_DEBUG
LOG_NOTICE("Lic[%d] has NULL seed", index)
#endif /* LICENSE_DEBUG */
return (0);
}
if (regex == NULL_STR || strlen(regex) == 0) {
#ifdef LICENSE_DEBUG
Assert(NO, "searchStrategy(%d) called with NULL data", index);
#endif /* LICENSE_DEBUG */
return (0);
}
if (strcmp(s, regex) == 0) {
return (0);
}
bytes = words = lines = 0;
(void) strcpy(seed, s);
while (seed[strlen(seed) - 1] == ' ') {
seed[strlen(seed) - 1] = NULL_CHAR;
}
/* how far ABOVE to look depends on location of the seed in footprint */
if (aboveCalc) {
if (strGrep(seed, regex, REG_ICASE) == 0) {
#ifdef LICENSE_DEBUG
printf("DEBUG: seed(%d) no hit in regex!\n", index);
#endif /* LICENSE_DEBUG */
return (PUNT_LINES); /* guess */
}
start = regex;
cp = start;
for (minLines = 0; cp != NULL; start = cp + 1) {
matchWild = matchSeed = 0;
if ((cp = strchr(start, ' ')) != NULL_STR) {
*cp = NULL_CHAR;
}
matchWild = (strcmp(start, any) == 0 || strcmp(start, some) == 0
|| strcmp(start, few));
matchSeed = strcmp(start, seed) == 0;
if (!matchSeed) {
bytes += (matchWild ? WC_BYTES : strlen(start) + 1);
words += (matchWild ? WC_WORDS : 1);
}
if (cp != NULL_STR) {
*cp = ' ';
}
if (matchSeed) { /* found seed? */
break;
}
}
/* optimization for single-lines: */
minLines += (words >= LINE_WORDS / 2 && words < LINE_WORDS);
lines = MAX(bytes/LINE_BYTES, words/LINE_WORDS) + minLines;
#ifdef LICENSE_DEBUG
printf("ABOVE: .... bytes=%d, words=%d; max(%d,%d)+%d == %d\n",
bytes, words, bytes/LINE_BYTES, words/LINE_WORDS,
minLines, lines);
#endif /* LICENSE_DEBUG */
return (words == 0 ? 0 : lines);
}
/* calculate how far below to look -- depends on length of footprint */
for (minLines = MIN_LINES, cp = start = regex; cp; start = cp + 1) {
matchWild = matchSeed = 0;
if ((cp = strchr(start, ' ')) != NULL_STR) {
*cp = NULL_CHAR;
}
matchWild = (strcmp(start, any) == 0 || strcmp(start, some) == 0
|| strcmp(start, few));
matchSeed = strcmp(start, seed) == 0;
if (matchSeed) {
bytes = words = 0;
/*minLines = MIN_LINES+1;*/
}
else {
bytes += (matchWild ? WC_BYTES : strlen(start) + 1);
words += (matchWild ? WC_WORDS : 1);
}
if (cp != NULL_STR) {
*cp = ' ';
}
}
lines = MAX(bytes/LINE_BYTES, words/LINE_WORDS) + minLines;
#ifdef LICENSE_DEBUG
printf("BELOW: .... bytes=%d, words=%d; max(%d,%d)+%d == %d\n",
bytes, words, bytes/LINE_BYTES, words/LINE_WORDS, minLines, lines);
#endif /* LICENSE_DEBUG */
return (lines);
}
#ifdef FIX_STRINGS
static void fixSearchString(char *s, int size, int i, int wildcardBad)
{
char *cp;
int len;
char wildCard[16];
/* */
#ifdef PROC_TRACE
traceFunc("== fixSearchString(\"%s\", %d, %d, %d)\n", s, size, i,
wildcardBad);
#endif /* PROC_TRACE */
/* */
/**
* Decrypt the text-string and then replace all instances of our wild-
* card string =ANY= to ".*". This may appear stupid on the surface,
* but the string =ANY= is *more* noticable when examining the text
* than an 'embedded' .* wild-card is. Same for =SOME=...
*****
* Make sure the search string does NOT start with a wild-card; it's not
* necessary and will probably double execution time. Once we know the
* first text is 'not wild', walk through an replace our strange =ANY=
* wildcards with regex(7) wild-cards. The only magic is to ensure the
* string doesn't END in a wild-card, either (more performance dumb-ness).
*/
cp = s;
while (isspace(*cp)) {
cp++;
}
if (strncmp(cp, any, sizeof(any)-1) == 0 ||
strncmp(cp, some, sizeof(some)-1) == 0 ||
strncmp(cp, few, sizeof(few)-1) == 0) {
printf("string %d == \"%s\"\n", i, cp);
LOG_FATAL("Text-spec %d begins with a wild-card", i)
Bail(-__LINE__);
}
/*
* We'll replace the string " =ANY=" (6 chars) with ".*" (2 chars).
* The token MUST OCCUR BY ITSELF (e.g., not a substring)!
*/
(void) sprintf(wildCard, " %s", any);
len = strlen(wildCard);
for (cp = s; strGrep(wildCard, cp, 0); ) {
if (wildcardBad) {
LOG_FATAL("OOPS, regex %d, wild-card not allowed here", i)
Bail(-__LINE__);
}
if (*(cp+cur.regm.rm_eo) == NULL_CHAR) {
LOG_FATAL("String %d ends in a wild-card", i)
Bail(-__LINE__);
}
else if (*(cp+cur.regm.rm_eo) == ' ') {
#ifdef DEBUG
printf("BEFORE(any): %s\n", s);
#endif /* DEBUG */
cp += cur.regm.rm_so;
*cp++ = '.';
*cp++ = '*';
memmove(cp, cp+len-1, strlen(cp+len)+2);
#ifdef DEBUG
printf("_AFTER(any): %s\n", s);
#endif /* DEBUG */
}
else {
LOG_NOTICE("Wild-card \"%s\" sub-string, phrase %d", wildCard, i)
cp += cur.regm.rm_eo;
}
}
/*
* Ditto for replacing " =SOME= " (8 chars) with ".{0,60}" (7 chars)
*/
(void) sprintf(wildCard, " %s", some);
len = strlen(wildCard);
for (cp = s; strGrep(wildCard, cp, 0); ) {
if (wildcardBad) {
LOG_FATAL("OOPS, regex %d, wild-card not allowed here", i)
Bail(-__LINE__);
}
if (*(cp+cur.regm.rm_eo) == NULL_CHAR) {
LOG_FATAL("String %d ends in a wild-card", i)
Bail(-__LINE__);
}
else if (*(cp+cur.regm.rm_eo) == ' ') {
#ifdef DEBUG
printf("BEFORE(some): %s\n", s);
#endif /* DEBUG */
cp += cur.regm.rm_so;
*cp++ = '.';
*cp++ = '{';
*cp++ = '0';
*cp++ = ',';
*cp++ = '6';
*cp++ = '0';
*cp++ = '}';
memmove(cp, cp+len-6, strlen(cp+len)+7);
#ifdef DEBUG
printf("_AFTER(some): %s\n", s);
#endif /* DEBUG */
}
else {
LOG_NOTICE("Wild-card \"%s\" sub-string, phrase %d", wildCard, i)
cp += cur.regm.rm_eo;
}
}
/*
* And, same for replacing " =FEW= " (7 chars) with ".{0,15}" (7 chars)
*/
(void) sprintf(wildCard, " %s", few);
len = strlen(wildCard);
for (cp = s; strGrep(wildCard, cp, 0); ) {
if (wildcardBad) {
LOG_FATAL("OOPS, regex %d, wild-card not allowed here", i)
Bail(-__LINE__);
}
if (*(cp+cur.regm.rm_eo) == NULL_CHAR) {
LOG_FATAL("String %d ends in a wild-card", i)
Bail(-__LINE__);
}
else if (*(cp+cur.regm.rm_eo) == ' ') {
#ifdef DEBUG
printf("BEFORE(few): %s\n", s);
#endif /* DEBUG */
cp += cur.regm.rm_so;
*cp++ = '.';
*cp++ = '{';
*cp++ = '0';
*cp++ = ',';
*cp++ = '3';
*cp++ = '0';
*cp++ = '}';
memmove(cp, cp+len-6, strlen(cp+len)+7);
#ifdef DEBUG
printf("_AFTER(few): %s\n", s);
#endif /* DEBUG */
}
else {
LOG_NOTICE("Wild-card \"%s\" sub-string, phrase %d", wildCard, i)
cp += cur.regm.rm_eo;
}
}
/*
* AND, replace the string "=YEAR=" with "[12][0-9][0-9][0-9][,- ]*".
* The former is 6 chars in length, the latter is 24. We must be careful
* not to overflow the buffer we're passed.
*/
len = strlen(year);
while (strGrep(year, s, 0)) {
if (strlen(s)+25 >= size) { /* 24 plus 1(NULL) */
LOG_FATAL("buffer overflow, text-spec %d", i)
Bail(-__LINE__);
}
cp = (char *)(s+cur.regm.rm_so);
#ifdef DEBUG
printf("BEFORE: %s\n", s);
#endif /* DEBUG */
memmove(cp+25, cp+6, strlen(cp+len)+1); /* was 26, 6 */
memset(cp+6, '_', 19);
#ifdef DEBUG
printf("_MOVED: %s\n", s);
#endif /* DEBUG */
*cp = *(cp+4) = *(cp+9) = *(cp+14) = *(cp+19) = '[';
*(cp+1) = '1';
*(cp+2) = '2';
*(cp+5) = *(cp+10) = *(cp+15) = '0';
*(cp+6) = *(cp+11) = *(cp+16) = '-';
*(cp+7) = *(cp+12) = *(cp+17) = '9';
*(cp+3) = *(cp+8) = *(cp+13) = *(cp+18) = *(cp+23) = ']';
*(cp+20) = ' ';
*(cp+21) = ',';
*(cp+22) = '-';
*(cp+24) = '*';
#ifdef DEBUG
printf("_AFTER: %s\n", s);
#endif /* DEBUG */
}
return;
}
#endif /* FIX_STRINGS */
char* createRelativePath(item_t *p, scanres_t *scp)
{
char* cp;
if (*(p->str) == '/')
{
strcpy(scp->fullpath, p->str);
scp->nameOffset = (size_t) (cur.targetLen + 1);
cp = scp->fullpath; /* full pathname */
}
else
{
strncpy(scp->fullpath, cur.cwd, sizeof(scp->fullpath)-1);
strncat(scp->fullpath, "/", sizeof(scp->fullpath)-1);
strncat(scp->fullpath, p->str, sizeof(scp->fullpath)-1);
scp->nameOffset = (size_t) (cur.cwdLen + 1);
cp = p->str; /* relative path == faster open() */
}
return cp;
}
/**
* For EACH file, determine if we want to scan it, and if so, scan
* the candidate files for keywords (to obtain a "score" -- the higher
* the score, the more likely it has a real open source license in it).
*
* There are lots of things that will 'disinterest' us in a file (below).
* \param scores
* \param licenseList
* \note This loop is called 400,000 to 500,000 times when parsing a
* distribution. Little slow-downs ADD UP quickly!
* \note Some other part of FOSSology has already decided we
* want to scan this file, so we need to look into removing this
* file scoring stuff.
* \FIXME We don't currently use _UTIL_FILTER, which is set up to
* exclude some files by filename.
*/
void scanForKeywordsAndSetScore(scanres_t* scores, list_t* licenseList)
{
/*
CDB -- Some other part of FOSSology has already decided we
want to scan this file, so we need to look into removing this
file scoring stuff.
*/
scanres_t* scp;
int c;
item_t* p;
char* textp;
char* cp;
for (scp = scores; (p = listIterate(licenseList)) != NULL_ITEM ; scp++)
{
/*
* Use *relative* pathnames wherever possible -- we'll spend less time in
* the kernel looking up inodes and pathname components that way.
*/
cp = createRelativePath(p, scp);
#ifdef DEBUG
printf("licenseScan: scan %s\n",
(char *)(scp->fullpath+scp->nameOffset));
#endif /* DEBUG */
/*
* Zero-length files are of no interest; there's nothing in them!
* CDB - We need to report this error somehow... and clean up
* /tmp/nomos.tmpdir (or equivalent).
*/
if ((textp = mmapFile(cp)) == NULL_STR) {
/* perror(cp); */
/*printf("Zero length file: %s\n", cp); */
continue;
}
scp->size = cur.stbuf.st_size; /* Where did this get set ? CDB */
/*
* Disinterest #3 (discriminate-by-file-content):
* Files not of a known-good type (as reported by file(1)/magic(3)) should
* also be skipped (some are quite large!). _UTIL_MAGIC (see _autodata.c)
* contains a regex for MOST of the files we're interested in, but there
* ARE some exceptions (logged below).
*
*****
* exception (A): patch/diff files are sometimes identified as "data".
*****
* FIX-ME: we don't currently use _UTIL_FILTER, which is set up to
* exclude some files by filename.
*/
/*
* Scan for keywords (_KW_), and use the number found for the score.
*/
assert(NKEYWORDS >= sizeof(scp->kwbm));
for (scp->kwbm = c = 0; c < NKEYWORDS; c++)
{
if (idxGrep_recordPosition(c + _KW_first, textp, REG_EXTENDED | REG_ICASE))
{
scp->kwbm |= (1 << c); // put a one at c'th position in kwbm (KeywordByteMap)
scp->score++;
#if (DEBUG > 5)
printf("Keyword %d (\"%s\"): YES\n", c, _REGEX(c+_KW_first));
#endif /* DEBUG > 5 */
}
}
munmapFile(textp);
#if (DEBUG > 5)
printf("%s = %d\n", (char *)(scp->fullpath+scp->nameOffset),
scp->score);
#endif /* DEBUG > 5 */
}
return;
}
/**
* \brief Reset scores to 1 if it is 0
*
* If we were invoked with a single-file-only option, just over-ride the
* score calculation -- give the file any greater-than-zero score so it
* appears as a valid candidate. This is important when the file to be
* evaluated has no keywords, yet might contain authorship inferences.
* \param scores
* \note It is always the case that we are doing one file at a time.
*/
void relaxScoreCriterionForSingleFile(scanres_t* scores)
{
/*
* CDB - It is always the case that we are doing one file at a time.
*/
if (scores->score == 0)
{
scores->score = 1;
}
}
/**
* \brief Run through the list once more
*
* This time we record and count the license candidates to process. License
* candidates are determined by either (score >= low) *OR* matching a set of
* filename patterns.
* @param lowWater Lowest score to filter
* @param scores Scores to filter
* @param nFiles Number of files
* @return
*/
int fiterResultsOfKeywordScan(int lowWater, scanres_t* scores, int nFiles)
{
int nCand;
scanres_t* scp;
int i;
for (scp = scores, i = nCand = 0; i < nFiles; i++, scp++)
{
scp->relpath = (char *) (scp->fullpath + scp->nameOffset);
if (idxGrep(_FN_LICENSEPATT, pathBasename(scp->relpath), REG_ICASE
| REG_EXTENDED)) {
scp->flag = 1;
if (idxGrep(_FN_DEBCPYRT, scp->relpath, REG_ICASE)) {
scp->flag = 2;
}
}
else if (scp->score >= lowWater) {
scp->flag |= 1;
}
/*
* So now, save any license candidate EITHER named "debian/copyright*"
* OR having a score > 0
*/
if (scp->flag == 2 || (scp->score && scp->flag)) {
#if (DEBUG > 3)
printf("%s [score: %d], %07o\n", scp->fullpath,
scp->score, scp->kwbm);
#endif /* DEBUG > 3 */
nCand++;
}
}
return nCand;
}
/**
* \brief scan the list for a license(s)
*
* This routine takes a list, but in fossology we always pass in a single file.
*
* Set up defaults for the minimum-scores for which we'll save files.
* Try to ensure a minimum # of license files will be recorded for this
* source/package (try, don't force it too hard); see if lower scores
* yield a better fit, but recognize the of a non-license file increases
* as we lower the bar.
*/
void licenseScan(list_t *licenseList)
{
int lowWater = 1; // constant
int nCand; //relevant output
//fields
int counts[NKEYWORDS + 1];
scanres_t *scores;
//recycled temp variables
scanres_t *scp;
int nFilesInList;
#ifdef PROC_TRACE
traceFunc("== licenseScan(%p, %d)\n", l);
#endif /* PROC_TRACE */
#ifdef MEMSTATS
printf("... allocating %d bytes for scanres_t[] array\n",
sizeof(*scp)*licenseList->used);
#endif /* MEMSTATS */
scores = (scanres_t *) memAlloc(sizeof(*scp) * licenseList->used, MTAG_SCANRES);
memset((void *) counts, 0, (size_t) ((NKEYWORDS + 1) * sizeof(int)));
scanForKeywordsAndSetScore(scores, licenseList);
relaxScoreCriterionForSingleFile(scores);
#ifdef PROC_TRACE
traceFunc("=> invoking qsort(): callback == scoreCompare()\n");
#endif /* PROC_TRACE */
nFilesInList = licenseList->used;
qsort(scores, (size_t) nFilesInList, sizeof(*scp), scoreCompare);
//recycled temp variables
nCand = fiterResultsOfKeywordScan(lowWater, scores, nFilesInList);
/*
* OF SPECIAL INTEREST: saveLicenseData() changes directory (to "..")!!!
*/
/* DBug: printf("licenseScan: gl.initwd is:%s\n",gl.initwd); */
saveLicenseData(scores, nCand, nFilesInList, lowWater);
/*
* At this point, we don't need either the raw-source directory or the
* unpacked results anymore, so get rid of 'em.
*/
if (scores->licenses) free(scores->licenses);
memFree((char *) scores, "scores table");
return;
} /* licenseScan */
/**
* \brief Compare two scores
* \return -1 ; If score1 > score2 \n
* 1 ; If score1 < score2 \n
* -1 ; If fullpath1 != NULL and follpath2 = NULL \n
* 1 ; If fullpath1 = NULL and follpath2 != NULL \n
* ; String comparison of fullpath if conditions above fails
* \note this procedure is a qsort callback that provides a REVERSE
* integer sort (highest to lowest)
*/
static int scoreCompare(const void *arg1, const void *arg2) {
scanres_t *sc1 = (scanres_t *) arg1;
scanres_t *sc2 = (scanres_t *) arg2;
if (sc1->score > sc2->score) {
return (-1);
}
else if (sc1->score < sc2->score) {
return (1);
}
else if ((sc1->fullpath != NULL_STR) && (sc2->fullpath == NULL_STR)) {
return (-1);
}
else if ((sc2->fullpath != NULL_STR) && (sc1->fullpath == NULL_STR)) {
return (1);
}
else {
return (-strcmp(sc1->fullpath, sc2->fullpath));
}
}
/**
* \brief Mark curent scan as LS_NOSUM (No_license_found)
*/
static void noLicenseFound() {
#ifdef PROC_TRACE
traceFunc("== noLicenseFound\n");
#endif /* PROC_TRACE */
(void) strcpy(cur.compLic, LS_NOSUM);
return;
}
/**
* \brief Print highlight info about matches
*
* This functions prtints to STDOUT only if OPTS_HIGHLIGHT_STDOUT is set.
*
* Format:
* ` Keyword at <start>, length <length>, index = 0,
* License #<name># at <start>, length <length>, index = <license_index>,`
* \param keyWords Keywords matches
* \param theMatches License matches
*/
static void printHighlightInfo(GArray* keyWords, GArray* theMatches){
if ( optionIsSet(OPTS_HIGHLIGHT_STDOUT) )
{
printf(" Highlighting Info at");
int currentKeyw;
for (currentKeyw=0; currentKeyw < keyWords->len; ++currentKeyw ) {
MatchPositionAndType* ourMatchv = getMatchfromHighlightInfo(keyWords,currentKeyw );
printf(" Keyword at %i, length %i, index = 0,", ourMatchv->start, ourMatchv->end - ourMatchv->start );
}
int currentLicence;
for (currentLicence = 0; currentLicence < theMatches->len; ++currentLicence)
{
LicenceAndMatchPositions* theLicence = getLicenceAndMatchPositions(theMatches, currentLicence);
int highl;
for (highl = 0; highl < theLicence->matchPositions->len; ++highl)
{
MatchPositionAndType* ourMatchv = getMatchfromHighlightInfo(theLicence->matchPositions, highl);
printf(" License #%s# at %i, length %i, index = %i,", theLicence->licenceName , ourMatchv->start, ourMatchv->end - ourMatchv->start, ourMatchv->index );
}
}
}
printf("\n");
return;
}
/**
* \brief Prints keywords match to STDOUT
*/
static void printKeyWordMatches(scanres_t *scores, int idx)
{
int c;
int base;
char miscbuf[myBUFSIZ];
int offset;
/*
* construct the list of keywords that matched in licenseScan()
*/
(void) strcpy(miscbuf, "Matches: ");
offset = 9; /* e.g., strlen("Matches: ") */
for (base = c = 0; c < NKEYWORDS; c++)
{
if (scores[idx].kwbm & (1 << c))
{
if (base++)
{
miscbuf[offset++] = ',';
miscbuf[offset++] = ' ';
}
offset += sprintf(miscbuf + offset, "%s", _REGEX(c + _KW_first));
}
}
printf("%s\n", miscbuf);
}
/**
* \brief Compare two integers
* \returns negative value if a < b; zero if a = b; positive value if a > b.
*/
static gint compare_integer(gconstpointer a, gconstpointer b)
{
gint out;
if (a < b)
out = -1;
else if (a == b)
out = 0;
else
out = 1;
return out;
}
/**
* \brief Rescan original content for the licenses already found
* \param textp Original text string
* \param isFileMarkupLanguage Is original text a markup text
* \param isPS Is original text a PostScript text
*/
static void rescanOriginalTextForFoundLicences(char* textp, int isFileMarkupLanguage, int isPS){
if (cur.theMatches->len > 0 )
{
if (cur.cliMode == 1 && !optionIsSet(OPTS_HIGHLIGHT_STDOUT) ) return;
// do a fresh doctoring of the buffer
g_array_free(cur.docBufferPositionsAndOffsets, TRUE);
cur.docBufferPositionsAndOffsets = g_array_new(FALSE, FALSE, sizeof(pairPosOff));
doctorBuffer(textp, isFileMarkupLanguage, isPS, NO);
for (cur.currentLicenceIndex = 0; cur.currentLicenceIndex < cur.theMatches->len; ++cur.currentLicenceIndex)
{
LicenceAndMatchPositions* currentLicence = getLicenceAndMatchPositions(cur.theMatches, cur.currentLicenceIndex);
//we want to only look for each found index once
g_array_sort(currentLicence->indexList, compare_integer);
int myIndex;
int lastindex = -1;
for (myIndex = 0; myIndex < currentLicence->indexList->len; ++myIndex)
{
int currentIndex = g_array_index(currentLicence->indexList, int, myIndex);
if (currentIndex == lastindex) continue;
idxGrep_recordPositionDoctored(currentIndex, textp, REG_ICASE | REG_EXTENDED);
lastindex = currentIndex;
}
}
}
}
/**
* \brief Save/creates all the license-data in a specific directory temp
* directory?
*
* \note OF SPECIAL INTEREST: this function changes directory!
*
* \todo CDB - Some initializations happen here for no particular reason
* \FIXME we should filter some names out like the shellscript does.
* For instance, word-spell-dictionary files will score high but will
* likely NOT contain a license. But the shellscript filters these
* names AFTER they're already scanned. Think about it.
* \FIXME BUG: When _FTYP_POSTSCR is "(postscript|utf-8 unicode)", the resulting
* license-parse yields 'NoLicenseFound' but when both "postscript" and
* "utf-8 unicode" are searched independently, parsing definitely finds
* quantifiable licenses. WHY?
* \callgraph
*/
static void saveLicenseData(scanres_t *scores, int nCand, int nElem,
int lowWater) {
int i;
// int c;
// int base;
int size;
int highScore = scores->score;