-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipecut.c
2458 lines (2231 loc) · 67.3 KB
/
pipecut.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
// # vim: shiftwidth=4 tabstop=4 softtabstop=4 expandtab
// # indent: -bap -br -ce -ci4 -cli0 -d0 -di0 -i4 -ip -l79 -nbc -ncdb -ndj -ei -nfc1 -nlp -npcs -psl -sc -sob
// # Gnu indent: -bap -nbad -br -ce -ci4 -cli0 -d0 -di0 -i4 -ip4 -l79 -nbc -ncdb -ndj -nfc1 -nlp -npcs -psl -sc -sob
/*
* Copyright (c) 2014, David William Maxwell david_at_NetBSD_dot_org
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* This is the main source file for the pipecut front-end, interactive pipeline editor.
* It uses libpipecut backend functions (which are still currently intermingled in this file,
* but which will be split out)
*/
/* Naming conventions
* Throughout the pipecut source code, the following naming conventions apply.
* lpc_ Function designated to part of libpipecut. Must not refer to uigbl. Must not use
* curses functions
* or write tty output, except for major warnings / fatal errors to stderr.
*
* pc_ Data structures that are part of the pipecut frontend. Note that functions
* in the frontend don't have to be labelled with any prefix.
*
* other Anything that asks for user input, prints output, or uses curses.
*
* The actual separation of libpipecut has not happened yet. UI elements from the proof of
* concept are still being teased out of the code and split from the lpc_ functions.
*/
/* Development notes
* The primary author of this code has not developed using the curses library before.
* As a result, I'm sure I've made incorrect assumptions and non-portable implementation
* choices.
*
* Review and patches from knowledgable curses programmers are welcome.
*/
#ifdef HAVE_BSD_STRING_H // If we're on a BSD platform, strl* functions will be in string.h (in pipecut.h below)
#include <bsd/string.h> // Required on Linux platforms - from bsd-dev package
#endif
// Macro for curses debugging. Should be off in production builds.
#define Q "";
//#define Q curs_set(1); refresh();
#include "pipecut.h" // libpipecut backend include file
#include "ipe.h" // Interactive pipeline editor - front-end include file
#include "pcDB.h" // Database routines that will move to the back
struct termios oldt, newt;
char lpc_toolcmds[22][20] = { // XXX Move this to the lpc library sourcee when it splits.
"NULL '", "' NULL",
"cat ", "",
" | ", "",
"BLACKBOX '", "",
"egrep -v '", "'",
"awk '{print \"", "\\n\"}'",
"egrep '", "'",
"wc ", "",
"sort ", "",
"uniq ", "",
"tr ", "",
};
// UI Functions
void newBBox(); // Input a Blackbox literal from user
void editBlade();
void removeMid();
void updateStatus();
void terminalraw();
void terminalnormal(); // XXX Unused
void print_in_middle(WINDOW * win, int starty, int startx, int width, char *string); // XXX Unused
void displayfilepage(int redraw, char *exp);
void start_background_thread(char *av1);
void dumprulefile();
void listExclude();
void toggleCurs();
void usage(char *av0) __attribute__ ((noreturn));
void version() __attribute__ ((noreturn));
void helpscreen();
void menu();
// Globals
// pthread_mutex_t linecount_mutex = PTHREAD_MUTEX_INITIALIZER;
char inputpipe[16384];
// Flags:
int parse_from_pipe = 0;
// libpipecut Functions
void pc_init(struct pipecut_ctx *ctx); // Initialize Context
// Execution of functions
int pc_wc_w(char *str); // WC - wordcount words
// Front-end instantiator functions for various blade types
void newExclude();
void newInclude();
void newAwk();
void pc_newSTDIN();
void pc_newTranslate();
// History parser
void pc_text2ts(char *);
/* Database usage model: toolsets sit in DB. Load command asks for a toolset name,
* Should also be able to bring up list of toolsets in DB.
* (Save / discard existing toolset? Keep modification state? )
* (Toolset name on status line? Modified state on status line?
* Save command asks for name.
* Ask for save on exit? Different quit methods?
* Initialize DB at startup if not found.
*/
// XXX Consider a TOOLINIT macro - not sure whether it would be used often enough.
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id; /* ID returned by pthread_create() */
int thread_num; /* Application-defined thread # */
char *argv_string; /* From command-line argument */
};
void bladeAction(struct toolelement *blade, char tmpbuf[BLADECACHE]);
/*
* NAME:
* pipecut is an alternative way to build up a UNIX shell command pipeline.
* Instead of alternatinv between adding commands and testing output, pipecut allows you
* to do this interactively, and provides functionality that can't be done on a
* command line.
*
* ORIGINS:
* pipecut was written to provide a framework to implement one concept originally -
* a line-oriented common pattern extractor. The pattern extractor's purpose is
* to analyze sample text, and identify common elements that share the same 'skeleton'
* but have different expressions as malleable fields within the line are changed.
* For example given these two lines:
* -rwxrwxr-x 1 david david 35063 May 23 15:30 pipecut
* -rw-rw-r-- 1 david david 15808 May 23 15:30 pipecut.c
*
* The two lines have the same number of fields (though this wouldn't be true for all 'ls'
* sample output) and have whitespace in the same column locations on each line. Some of the
* fields are the same in both lines, some are different, and (given a sufficient sample set)
* some fields have a limited character set. Many interesting actions can be performed on
* this data (or on larger sample sets).
*
* We can extract a regular expression that matches all input lines with the same skeleton:
* -rw[-x]rw[-x]r-[-x] 1 david david [13][35][08][60][38] May 23 15:30 pipecut(.c)?
*
* With some generalization rules, provided either by recognition of the skeleton type, or
* through analyzing sufficient sample input, or by the user providing guidance, this
* could become:
*
* [-lsp][-rwx][-rwxs][-rwxs] [0-9]+ [a-zA-Z0-9]+ [a-zA-Z0-9]+ [0-9]+ [A-Z][a-z][a-z] [0-9]+ 15:30 pipecut(.c)?
* XXX
*
* OVERVIEW:
* This full-screen curses utility reads a file and displays a sample of lines from it.
* The user can then create a list of rules that modify the file data in ways that
* correspond to common manipulations needed in typical information formatting challenges.
*
* The file is not modified in-place. As additional pipecut modifiers are added, the
* resulting output is displyed interactively. Since each of the pipecut modifiers
* corresponds to common UNIX command line utilities, a set of pipecut modifiers can be
* output in a variety of programming lanaguages for the purpose of rapid-prototyping,
* comparative performance analysis, or maintaining the modifiers in a language-abstract
* way so that the implementation can migrate between languages as needed.
*
* Implemented output formats: shell script
* Planned output formats: perl, python, C
*
* Pipecut can also be run with command line arguments (-t) to execute a pipecut
* toolset and process
* the provided input through a set of modifiers and output the result. This allows you
* to save a particular transformation and reuse it, or share it with others.
*
* pipecut can also be run with a toolname, and the user can interactively single-step
* through applying additional layers of modifiers. You can think of this like a
* pipeline debugger, or the application of a photo-editing layer visibility functionality
* to a text processing environment.
*
* XXX update text below for exclusion -> generic tool change
* Implementation: exclusion rules are maintained as elements of a TAILQ.
* A second thread calculates statistics about the target file, and the impact of the
* various exclusion rules. The statistics are updated in the background while the
* user interacts with the main event loop. Since the interface between the threads
* is not performance critical, and the statistics thread calculates into temporary
* variables and does the update in a small crtitical section, simple mutexes are used
* to protect the shared variables.
*/
int
main(int argc, char *argv[])
{
int c;
int dorefresh = 0;
char l1[16384]; // XXX Don't need such large blocks on the stack - move to the heap.
char l2[16384];
char l3[16384];
char *cp;
FILE *fp;
int ch;
char lesspipe[BLADECACHE]; // XXX fixed size bad
int k;
lpc_ctx.debug = 0;
/* Handle the case of piped input */
struct stat stats;
//sleep(10); // Give gdb a chance to attach
// Check command line arguments
while ((ch = getopt(argc, argv, "ht:v")) != -1) {
switch (ch) {
case 'h':
usage(NULL);
break;
case 't':
lpc_ctx.filtermode = 1;
lpc_ctx.filter = optarg;
break;
case 'v':
version();
break;
case '?':
usage(NULL);
break;
default:
break;
}
}
argc -= optind;
argv += optind;
/* Would like to check for DB early - but we can't interact with the user until we know
the mode we're running in. So get past those checks first. */
/* Figure out whether we've started running with piped input, or a terminal */
int r = fstat(fileno(stdin), &stats);
if (r) {
printf("fstat of STDIN returned an error. Exiting.\n");
exit(-1);
}
// Initialize libpipecut context structure
pc_init(&lpc_ctx);
// This stanza is only for debugging printfs, and a reminder of the other way to
// identify our input type. We use the stats structure below to decide operational mode.
if (isatty(fileno(stdin))) {
if (lpc_ctx.debug)
fprintf(stderr, "stdin is a terminal\n");
} else {
if (lpc_ctx.debug)
fprintf(stderr, "stdin is a file or a pipe\n");
}
// Initialize the tool list
TAILQ_INIT(&head);
if (lpc_ctx.filtermode != 1) {
uigbl.mainwin = initscr(); // Start curses mode
}
initDB(0); // Setup Database (debugging off)
if (S_ISFIFO(stats.st_mode)) {
if (lpc_ctx.debug)
fprintf(stderr, "stdin is a pipeline\n");
// Input is a pipeline. Either we're to consume command history, or run as a filter.
// -t (lpc_ctx.filtermode) will tell us which.
if (lpc_ctx.filtermode) { // -t, load the toolset, process, and exit.
pc_loadToolset(2); // 2 for filter mode
updateTextPipeline(lpc_ctx.tstext, 0); // Prep the pipeline from the toolset
lpc_ctx.tstext[0] = ' '; // XXX Cheesy hack to avoid rewriting the way a blade's text representation is generated
filterrun(lpc_ctx.tstext);
// Doit
exit(0);
}
//Test that it looks like a command history and consume the last
// pipeline
while (1) {
strcpy(l3, l2);
strcpy(l2, l1);
if (!fgets(l1, 16384, stdin)) {
printf("fgets returned NULL\n");
}
//fscanf(stdin,"%s",l1);
if (feof(stdin)) {
printf("End of stdin\n");
break;
}
}
// Get our stdin pointed back to the user.
fclose(stdin);
freopen("/dev/tty", "r", stdin);
printf("L1: %s\n", l1);
printf("L2: %s\n", l2);
printf("L3: %s\n", l3);
// In some shells (tcsh, csh) the history format is:
// # hh:mm cmd
// And the last line in the history will be the executed command that ran pipecut - so we want the
// command before that (l3)
// In other shells (bash, zsh), the time is omitted. bash includes the history command, zsh omits it.
// XXX Ignore the zsh case, and handle l3 for now.
strcpy(inputpipe, l3);
// Flag that we came from a pipe - we'll later need to open the input on the pipeline, instead of ARGV[1]
parse_from_pipe = 1;
} else {
// Input is not a pipeline, so assume we're in interactive mode.
/* We didn't get a pipe on input - so make sure we got a filename argument. */
if (argc < 1) {
// XXX End curses, print error.
usage(argv[0]);
exit(-1);
}
}
// setup Color
start_color(); /* Start color */
use_default_colors();
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, -1, -1);
attron(COLOR_PAIR(2));
cbreak();
noecho();
erase();
// find out the screen size
uigbl.maxx = getmaxx(uigbl.mainwin);
uigbl.maxy = getmaxy(uigbl.mainwin);
uigbl.numbering = 0;
uigbl.statsthread = 0;
if (!parse_from_pipe) {
// In the history|pipecut case, we already have the source filename.
strlcpy(lpc_ctx.sourcefile, argv[0], PATH_MAX);
} else {
printf("Calling pc_text2ts %s\n", inputpipe);
pc_text2ts(inputpipe);
}
// Must happen after we get maxy and maxx - lpc_newCat used to use them to size the buffer
// That won't be an issue any more with the use of an sz object.
fp = fopen(lpc_ctx.sourcefile, "r");
if (!fp) {
endwin();
printf("Could not open file %s\n", lpc_ctx.sourcefile);
exit(-1);
}
// Must know the filename before the lpc_newCat
if (!parse_from_pipe) {
lpc_newCat(lpc_ctx.sourcefile);
}
terminalraw();
// XXX This is disabled for now. needs more portability and build testing on a variety of platforms
// Spin off a thread to build some statistics (libmoremagic, etc)
//start_background_thread(lpc_ctx.sourcefile);
displayfilepage(1, NULL);
/*
* Items prefixed with X are not yet implemented
* In the main event loop, the user can perform the following actions:
* Add/modify/delete pipecut modifiers (grep, s///, awk, tr, sort)
* X: Edit the pattern of an existing blade
* X: Export the current pipecut set into a single-tool box, for emailing to another user
* X: Import a pipecut single-tool, or toolbox into the user's toolbox
*/
// Process Commands - main UI event loop starts here
keypad(uigbl.mainwin, 1); // Handle Esc sequences for us, thank you.
timeout(-1);
while ((c = getch()) != 'q') {
// mvprintw(uigbl.maxy-3,0,"GETCH:%d:",c); // For debugging.
if (c == '\x12') { /* Control-R */
//erase();
move(uigbl.maxy, 0);
for (k = 0; k < uigbl.maxy; k++) {
printf("\n\n");
}
move(0, 0);
clrtotop();
refresh();
displayfilepage(1, NULL);
continue;
}
if (c == '\x08' || /* c == '\x7f' || */ c == KEY_BACKSPACE) { /* Backspace or delete */
if (TAILQ_PREV(lpc_ctx.curBlade, tailhead, entries) != NULL) {
lpc_removeTail();
displayfilepage(1, NULL);
}
continue;
}
if (c == 'd') {
dumprulefile();
displayfilepage(1, NULL);
continue;
}
if (c == 'P') {
toggleCurs();
continue;
}
if (c == 'R') {
toggleRe();
displayfilepage(1, NULL);
continue;
}
if (c == '-') { // Modify the existing blade (iff Blackbox)
if (lpc_ctx.curBlade->ttype != BLACKBOX) {
beep();
continue;
}
c = getch();
if (lpc_ctx.curBlade->pattern)
cp = strchr(lpc_ctx.curBlade->pattern, ' ');
if (!cp) {
realloc(lpc_ctx.curBlade->pattern,
strlen(lpc_ctx.curBlade->pattern) + 4);
snprintf(l3, strlen(lpc_ctx.curBlade->pattern) + 4, "%s -%c",
lpc_ctx.curBlade->pattern, c);
strcpy(lpc_ctx.curBlade->pattern, l3);
regenCaches();
displayfilepage(1, NULL);
} else {
realloc(lpc_ctx.curBlade->pattern,
strlen(lpc_ctx.curBlade->pattern) + 2);
snprintf(l3, strlen(lpc_ctx.curBlade->pattern) + 2, "%s%c",
lpc_ctx.curBlade->pattern, c);
strcpy(lpc_ctx.curBlade->pattern, l3);
regenCaches();
displayfilepage(1, NULL);
}
continue;
}
if (c == '|') {
strcpy(lesspipe, lpc_ctx.tspart);
strcat(lesspipe, " | less");
fullrun(lesspipe);
continue;
}
if (c == 'L') {
toggleLA();
displayfilepage(1, NULL);
continue;
}
if (c == 'C') {
pc_togglecaches();
displayfilepage(1, NULL);
continue;
}
if (c == '!') {
FILE *so;
char scriptout[BLADECACHE];
updateTextPipeline(scriptout, 1);
so = fopen("script.sh", "w");
fprintf(so, "%s", scriptout);
fclose(so);
}
if (c == 'c') {
lpc_newBB("cat -n");
displayfilepage(1, NULL);
continue;
}
// XXX TODO if (c == 'e') { editBlade(); displayfilepage(1,NULL); continue; }
if (c == 'h') {
lpc_newBB("hexdump -C");
displayfilepage(1, NULL);
continue;
}
if (c == 's') {
lpc_newBB("sort");
displayfilepage(1, NULL);
continue;
}
// XXX TODO if (c == 't') { pc_newTranslate(); displayfilepage(1,NULL); continue; }
if (c == 'u') {
lpc_condprepend("sort");
lpc_newBB("uniq");
displayfilepage(1, NULL);
continue;
}
if (c == 'U') {
lpc_condprepend("sort");
lpc_newBB("uniq -c");
displayfilepage(1, NULL);
continue;
}
if (c == 'H') {
lpc_newBB("sort -nr");
displayfilepage(1, NULL);
continue;
}
if (c == 'A') {
lpc_newBB("awk '{print $8, $9}'");
displayfilepage(1, NULL);
continue;
}
if (c == '?') {
helpscreen();
displayfilepage(1, NULL);
continue;
}
if (c == '[') {
pc_loadToolset(0); // 0 to replace
updateTextPipeline(lpc_ctx.tstext, 0); // Rewrite the pipeline text from the toolset
displayfilepage(1, NULL);
continue;
}
if (c == '"') {
pc_loadToolset(1); // 1 to append
updateTextPipeline(lpc_ctx.tstext, 0); // Rewrite the pipeline text from the toolset
displayfilepage(1, NULL);
continue;
}
if (c == ']') {
pc_saveToolset();
displayfilepage(1, NULL);
continue;
}
if (c == 'l') {
listExclude();
displayfilepage(1, NULL);
continue;
}
if (c == 'm') {
menu();
displayfilepage(1, NULL);
continue;
}
if (c == 'n') { // Currently deprecated. use 'c' (cat -n)
togglenumbering();
displayfilepage(1, NULL);
continue;
}
if (c == 'g') {
newInclude();
displayfilepage(1, NULL);
continue;
}
if (c == 'w') {
newSummarize();
displayfilepage(1, NULL);
continue;
}
if (c == 'x') {
newExclude();
displayfilepage(1, NULL);
continue;
}
if (c == '\'') {
newBBox();
displayfilepage(1, NULL);
continue;
}
if (c == 'a') {
newAwk();
displayfilepage(1, NULL);
continue;
}
if (c == 'r') {
regenCaches();
displayfilepage(1, NULL);
continue;
}
if (c == KEY_DC) { // DC -> Delete Character -> DELETE
removeMid();
displayfilepage(1, NULL);
continue;
}
if (c == KEY_LEFT) {
mvwchgat(uigbl.mainwin, uigbl.maxy - 2,
lpc_ctx.curBlade->bladeoffset + 2,
lpc_ctx.curBlade->bladelen - 2, A_NORMAL, 0, NULL);
dorefresh = lpc_ctx.curBlade->haseffect;
lpc_ctx.n1 = TAILQ_PREV(lpc_ctx.curBlade, tailhead, entries);
if (lpc_ctx.n1) {
lpc_ctx.curBlade = lpc_ctx.n1;
} // Can't go left of the first blade
// XXX Optimization to add here - if secondblade !haseffect, no need to redraw when moving right
if (dorefresh)
displayfilepage(1, NULL);
else
displayfilepage(1, NULL); // second was 0
}
if (c == KEY_RIGHT) {
mvwchgat(uigbl.mainwin, uigbl.maxy - 2,
lpc_ctx.curBlade->bladeoffset + 2,
lpc_ctx.curBlade->bladelen - 2, A_NORMAL, (short)0, NULL);
lpc_ctx.n1 = TAILQ_NEXT(lpc_ctx.curBlade, entries);
if (lpc_ctx.n1) {
lpc_ctx.curBlade = lpc_ctx.n1;
} // Can't go right of the last blade
dorefresh = lpc_ctx.curBlade->haseffect;
// XXX Optimization to add here - if secondblade !haseffect, no need to redraw when moving left
if (dorefresh)
displayfilepage(1, NULL);
else
displayfilepage(1, NULL);
}
if (c == KEY_PPAGE) {
lpc_ctx.fileoffset = 0;
regenCaches();
displayfilepage(1, NULL);
}
if (c == KEY_NPAGE) {
lpc_ctx.fileoffset = lpc_ctx.filepageend; // Move the seek point to just past where we've been displaying
regenCaches();
displayfilepage(1, NULL);
}
// We shouldn't have to decode escape sequences manually, but
// I'm leaving this here until I know I don't need to abuse keyok()
if (c == 27) { // Escape character may begin an escape sequence.
c = getch();
if (c == '[') {
c = getch();
if (c == '3') {
c = getch();
if (c == '~') { // Delete
removeMid();
displayfilepage(1, NULL);
continue;
}
}
if (c == 'A') { // up arrow
//dothing();
}
if (c == 'B') { // down arrow
//dothing();
}
if (c == 'C') { // right arrow
mvwchgat(uigbl.mainwin, uigbl.maxy - 2,
lpc_ctx.curBlade->bladeoffset + 2,
lpc_ctx.curBlade->bladelen - 2, A_NORMAL, (short)0,
NULL);
dorefresh = lpc_ctx.curBlade->haseffect;
lpc_ctx.n1 = TAILQ_NEXT(lpc_ctx.curBlade, entries);
if (lpc_ctx.n1) {
lpc_ctx.curBlade = lpc_ctx.n1;
} // Can't go right of the last blade
// XXX Optimization to add here - if secondblade !haseffect, no need to redraw when moving right
if (dorefresh)
displayfilepage(1, NULL);
else
displayfilepage(1, NULL);
}
if (c == 'D') { // left arrow
mvwchgat(uigbl.mainwin, uigbl.maxy - 2,
lpc_ctx.curBlade->bladeoffset + 2,
lpc_ctx.curBlade->bladelen - 2, A_NORMAL, (short)0,
NULL);
lpc_ctx.n1 =
TAILQ_PREV(lpc_ctx.curBlade, tailhead, entries);
if (lpc_ctx.n1) {
lpc_ctx.curBlade = lpc_ctx.n1;
} // Can't go left of the first blade
dorefresh = lpc_ctx.curBlade->haseffect;
// XXX Optimization to add here - if secondblade !haseffect, no need to redraw when moving left
if (dorefresh)
displayfilepage(1, NULL);
else
displayfilepage(1, NULL);
}
if (c == '5') {
c = getch();
if (c == '~') { // PageUP
lpc_ctx.fileoffset = 0;
regenCaches();
displayfilepage(1, NULL);
}
}
if (c == '6') {
c = getch();
if (c == '~') { // PageDn
lpc_ctx.fileoffset = lpc_ctx.filepageend; // Move the seek point to just past where we've been displaying
regenCaches();
displayfilepage(1, NULL);
}
}
}
// Since not all escape sequences are explicitly handled, throw away any
// unconsumed input at this point.
flushinp();
}
//if (c > 'a' && c < 'z' && c!= 'x') putchar(c);
//if (c > '0' && c < '9') putchar(c);
}
printf("\n");
endwin(); /* End curses mode */
return 0;
}
void
togglenumbering()
{ // Currently deprecated.
uigbl.numbering++;
if (uigbl.numbering > 2) { // valid values are 0 (no numbering) 1 (current numbering), 2 (source numbering)
uigbl.numbering = 0;
}
return;
}
void
toggleCurs()
{
lpc_ctx.curs++;
if (lpc_ctx.curs > 2) { // valid values are 0 (hide) 1 (low vis ), 2 (high vis )
lpc_ctx.curs = 0;
}
curs_set(lpc_ctx.curs);
return;
}
void
toggleRe()
{
lpc_ctx.reon ^= 1;
return;
}
void
toggleLA()
{
lpc_ctx.laon ^= 1;
return;
}
void
pc_togglecaches()
{
lpc_ctx.cacheon ^= 1;
return;
}
void
dumprulefile()
{
FILE *fp;
fp = fopen("rulefile.out", "w");
TAILQ_FOREACH(lpc_ctx.np, &head, entries) {
fprintf(fp, "action NAMEXXX severity:XXX __%s_ type:%d store:XXX:$1 alert:template/foo.template\n", lpc_ctx.np->pattern, lpc_ctx.np->ttype); // XXX need to humanize ttype
}
fclose(fp);
}
void
newSummarize()
{
char *ma;
printw("| wc ");
refresh();
/* Insert the new entry into the toolset list */
lpc_ctx.n1 = malloc(sizeof(struct toolelement)); /* Insert at the head. */
memset(lpc_ctx.n1->cache, 0, BLADECACHE);
ma = malloc(1); // Although Summarize has no 'pattern' - initialize a null string so that code everywhere else doesn't need special cases.
strcpy(ma, "");
lpc_ctx.n1->enabled = 1;
lpc_ctx.n1->pattern = ma;
lpc_ctx.n1->ttype = SUMMARIZE;
lpc_ctx.n1->menuptr = NULL; // We don't use this until the menu is called. NULL it to a known state now.
TAILQ_INSERT_TAIL(&head, lpc_ctx.n1, entries);
lpc_ctx.curBlade = lpc_ctx.n1; // Current Blade follows the newly created Blade.
return;
}
void
newInclude()
{
char incl[1024]; // XXX Not okay to use fixed length field
char blade[200]; // XXX Not okay to use fixed length field
char *cp;
char *ma;
int rc, nlen;
int c;
int y, x;
cp = incl;
sprintf(blade, "| egrep '");
mvprintw(uigbl.maxy - 2, strlen(lpc_ctx.tstext), blade); // on NetBSD, this could just be printw'd. Curses inconsistency between platforms
refresh();
// We have two modes of input. In the noRe case, getstr does all the work for us. In the Re case, we have to do it.
if (!lpc_ctx.reon) {
echo();
curs_set(1);
//getstr(cp);
getnstr(cp, 1024);
} else {
while (1) { // XXX Need to rework the pointer handling here.
c = getch();
if (c == '\n') {
break;
}
*(cp++) = (char)c; // Accumulate characters.
if (c == KEY_BACKSPACE || c == '\x08' || c == '\x7f') {
if (cp > incl + 1) { // No backspacing past the start of the string
printw(" ");
move(getcury(uigbl.mainwin), getcurx(uigbl.mainwin) - 1);
*cp = '\0'; // Always leave a clean tail on the string.
cp--;
*cp = '\0';
cp--;
*cp = '\0';
curs_set(0);
getyx(uigbl.mainwin, y, x);
displayfilepage(0, incl);
move(y, x);
curs_set(1);
} else {
*cp = '\0';
cp--;
*cp = '\0';
}
} else {
printw("%c", *(cp - 1)); // print, since echo is off.
*cp = '\0';
curs_set(0);
// This is where we update the display for interactive behavior
// like Regular Expression mode.
// Record where the cursor is, and restore it afterwards,
// since displayfilepage doesn't do so for us.
getyx(uigbl.mainwin, y, x);
displayfilepage(0, incl); // No redraw, so we don't overwrite incl
move(y, x);
curs_set(1);
}
}
*cp = '\0';
cp--;
}
curs_set(0);
noecho();
//printw("\nNew Inclusion is:%s\n", incl);
refresh();
/* XXX This check applies in the single-tool case, within a range of toolelements. e.g. don't grep-v the same
string out twice, with no other changes in betwen.
XXX The code needs to be updated to reflect that. */
/* Check that the new entry is not a duplicate of an existing entry */
TAILQ_FOREACH(lpc_ctx.np, &head, entries) {
if (!strcmp(incl, lpc_ctx.np->pattern)) {
printw
("WARNING: The supplied value is a duplicate of an existing inclusion (not added).\n");
printw("\nHit any key to continue.\n");
getch();
return;
}
}
if (!strncmp(incl, "", 1024)) {
// Empty string? Just return without adding.
return;
}
lpc_newIN(incl);
return;
}
void
newExclude()
{
char excl[200]; // XXX Not okay to use fixed length field
char blade[200]; // XXX Not okay to use fixed length field
char *cp;
char *ma;
int rc, nlen;
int y, x;
int c;
cp = excl;
echo();
getyx(uigbl.mainwin, y, x);
sprintf(blade, "| egrep -v '");
mvprintw(uigbl.maxy - 2, strlen(lpc_ctx.tstext), blade); // on NetBSD, this could just be printw'd. Curses inconsistency between platforms
refresh();
// We have two modes of input. In the noRe case, getstr does all the work for us. In the Re case, we have to do it.
if (!lpc_ctx.reon) {
echo();
curs_set(1);
getstr(cp);
} else {
noecho();
curs_set(1);
while (1) { // XXX Need to rework the pointer handling here.
c = getch();
if (c == '\n') {
break;
}
*(cp++) = (char)c; // Accumulate characters.
if (c == KEY_BACKSPACE || c == '\x08' || c == '\x7f') {
if (cp > excl + 1) { // No backspacing past the start of the string
printw(" ");
move(getcury(uigbl.mainwin), getcurx(uigbl.mainwin) - 1);
*cp = '\0'; // Always leave a clean tail on the string.
cp--;
*cp = '\0';
cp--;
*cp = '\0';
curs_set(0);
getyx(uigbl.mainwin, y, x);
displayfilepage(0, excl);
move(y, x);
curs_set(1);
} else {
*cp = '\0';
cp--;
*cp = '\0';
}
} else {
printw("%c", *(cp - 1)); // print, since echo is off.
*cp = '\0';
curs_set(0);
// This is where we update the display for interactive behavior
// like Regular Expression mode.
// Record where the cursor is, and restore it afterwards,
// since displayfilepage doesn't do so for us.
getyx(uigbl.mainwin, y, x);
displayfilepage(0, excl); // No redraw, so we don't overwrite excl
move(y, x);
curs_set(1);
}
}
*cp = '\0';
cp--;
}
curs_set(1);
noecho();
//printw("\nNew Exclusion is:%s\n", excl);
refresh();
/* XXX This check applies in the single-tool case, within a range of toolelements. e.g. don't grep-v the same
string out twice, with no other changes in betwen.
XXX The code needs to be updated to reflect that. */
/* Check that the new entry is not a duplicate of an existing entry */
TAILQ_FOREACH(lpc_ctx.np, &head, entries) {
if (!strcmp(excl, lpc_ctx.np->pattern)) {
printw
("WARNING: The supplied value is a duplicate of an existing exclusion (not added).\n");
printw("\nHit any key to continue.\n");
getch();
return;
}
}
if (!strncmp(excl, "", 1024)) {
// Empty string? Just return without adding.
return;
}
lpc_newEX(excl);
return;
}
void
lpc_newEX(char *excl)
{
int rc, nlen;
char *ma;