forked from OpusVL/perl-ccfe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathccfe.pl
More file actions
6606 lines (6145 loc) · 252 KB
/
Copy pathccfe.pl
File metadata and controls
6606 lines (6145 loc) · 252 KB
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
#!/usr/bin/env perl
#
# CCFE - The Curses Command Front-end
# Copyright (C) 2009, 2016 Massimo Loschi
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
#
# Author: Massimo Loschi <ccfedevel@gmail.com>
#
use v5.36; # strict + warnings + modern features (M7 Phase 6 capstone)
# getch() returns an integer keycode for function/arrow keys but a one-character
# string for ordinary keys, and the event loops compare it numerically against
# KEY_* constants ($ch == KEY_UP). That is the program's idiom throughout, so
# the "argument isn't numeric" notice it would raise for a character key is just
# noise; silence that one category while keeping every other warning.
no warnings 'numeric';
use Curses;
use Sys::Hostname;
use File::Basename;
use POSIX qw(:sys_wait_h);
use Getopt::Std;
use IPC::Open3;
use Text::ParseWords qw(shellwords); # shell-free argv split under RESTRICTED
use Symbol qw(gensym);
use IO::File;
use Term::ANSIColor;
use Text::Balanced qw(extract_bracketed);
use IO::Select;
use File::Temp qw(tempfile);
use Digest::MD5 qw(md5_hex);
use Cwd qw(getcwd)
; # robust CWD; avoids fork()ing `pwd`, which fails on small/odd terminals
# Locate CCFE's own Perl modules relative to this file, so they are found both
# from the source tree (src/lib) and when installed (bin/../lib/perl5). Using
# __FILE__ (not $0/FindBin) keeps this correct even when the program is
# require()d headlessly from the test suite.
use lib do {
require Cwd; # resolve a symlinked invocation (e.g. /usr/bin/ccfe -> ...)
my $d = dirname( Cwd::abs_path(__FILE__) );
( "$d/lib", "$d/../lib/perl5" );
};
use CCFE::Restrict ();
use CCFE::Theme ();
use CCFE::MenuFile (); # pure .menu/.item parser (see load_menu)
use CCFE::FormFile (); # pure .form parser (see load_form)
use CCFE::Config (); # pure .conf section tokenizer (see load_config)
use CCFE::Action (); # pure action-string parser (see do_menu/do_form)
use CCFE::Layout (); # pure form value-column/page geometry (see do_form)
use CCFE::Context (); # explicit run-state container (M7 de-globalisation)
use FindBin (); # to locate the program at runtime (see the path block below)
# M7 Phase 6 (capstone): this legacy script predates `use strict`. Its package
# globals -- constants, lookup tables, the search-path arrays, message strings
# and the few intentionally-global runtime vars ($cpid/$tmpfh, owned by the
# signal handlers) -- are declared here so the file runs under strict. The
# de-globalisation (Phases 1-5) moved the mutable per-screen/config/run state
# onto lexicals and $ctx; what remains global is genuinely program-wide.
## BEGIN-OUR (formatted; scalars, then arrays, then hashes)
our (
$ALL_FIELDS_IDS_TAG, $ASKS_FIELD_PAD, $ASKS_FIELD_SIZE,
$ASKS_WIN_COLS, $ASKS_WIN_FTR_ROWS, $ASKS_WIN_ROWS,
$BAD_SHELL_MSG, $BAD_SHELL_TITLE, $BFIELD_DEFAULT,
$BFIELD_NO, $BFIELD_NO_DESCR, $BFIELD_NULL,
$BFIELD_NULL_DESCR, $BFIELD_YES, $BFIELD_YES_DESCR,
$BIG_OUTPUT_MSG, $BIG_OUTPUT_TITLE, $BINDIR,
$BOOLEAN, $BOOLEAN_FIELD_SIZE, $CALLNAME,
$CALL_SHELL_MSG, $CALL_SYS_ES_MSG, $CALL_SYS_MSG,
$CONFIRM_DESCR_NO, $CONFIRM_DESCR_YES, $CONFIRM_TITLE,
$CURSES_ACTIVE, $DEBUG, $DESCR,
$DMENU_DEF_FNAME, $EMPTY_LIST_MSG, $EMPTY_LIST_TITLE,
$EXEC_NOTFOUND_MSG, $EXEC_NOTFOUND_TITLE, $ERR_EMPTY_FIELD_MSG,
$ERR_EMPTY_FIELD_TITLE, $ERR_LOAD_INITIAL_OBJ, $ES_CANCEL,
$ES_EXIT, $ES_FOPEN_ERR, $ES_FOPEN_ERR_MSG,
$ES_NOT_FOUND, $ES_NOT_FOUND_MSG, $ES_NO_ERR,
$ES_NO_ERR_MSG, $ES_NO_ITEMS, $ES_NO_ITEMS_MSG,
$ES_SYNTAX_ERR, $ES_SYNTAX_ERR_MSG, $ES_USER_REQ,
$ETCDIR, $FALSE, $FIELD_LMARGIN,
$FIELD_RMARGIN, $FIELD_VALUE_GAP, $FORMEXT,
$FORM_ARGV_ID, $FORM_ERR_TITLE, $FOUND_NONE_MSG,
$FOUND_NONE_TITLE, $FSEP_ID_PRFX, $FS_BOTTOM_ROWS,
$FS_HEADER_ROWS, $FS_TOP_ROWS, $HAS_COLOR,
$HOSTNAME, $HTAB_COLS, $INIT_DISABLE_FIELDS,
$INIT_ENABLE_FIELDS, $INIT_FORM_ERR_MSG, $INIT_REMOVE_FIELDS,
$KEY_ENTER_LABEL, $KEY_F10_LABEL, $KEY_F1_LABEL,
$KEY_F2_LABEL, $KEY_F3_LABEL, $KEY_F4_LABEL,
$KEY_F5_LABEL, $KEY_F6_LABEL, $KEY_F7_LABEL,
$KEY_F8_LABEL, $KEY_F9_LABEL, $KEY_FIND_LABEL,
$KEY_FNEXT_LABEL, $KEY_INTR_LABEL, $KEY_RELOAD_LABEL,
$KEY_SELALL_LABEL, $KEY_UNSELALL_LABEL, $LANG_ID,
$LEGACY_DIR, $LIBDIR, $LIST_CMD_ERR_MSG,
$LIST_CMD_ERR_TITLE, $LOAD_FORM_ERR_MSG, $LOAD_MENU_ERR_MSG,
$LOGDIR, $LOG_ACTION_CMD, $LOG_ACTION_OUT,
$LOG_DATE, $LOG_DEFAULT_CMD, $LOG_FIELDS_VAL,
$LOG_INITFORM_OUT, $LOG_LIST_CMD, $LOG_MENU_CHOICE,
$LOG_NORMAL, $LOG_REQUESTED, $LOG_SCAN_PATHS,
$LOG_SYSCALL_ENV, $LOG_WRITE_ERROR_MSG, $LOG_WRITE_ERROR_TITLE,
$LW_COLS, $LW_FOOTER_ROWS, $LW_PAD_COLS,
$LW_ROW0, $MAIN_PATH, $MARK_PRIV_SHCUTS,
$MENUEXT, $MENU_ERR_TITLE, $MIN_ITEMS_FOR_FIND,
$MOUSE_ON, $MSGDIR, $MSG_WIN_BMSG,
$MSG_WIN_ROWS, $MSG_WIN_TITLE, $MS_BOTTOM_ROWS,
$MS_HEADER_ROWS, $MS_TOP_ROWS, $NO,
$NORMAL, $NULLBOOLEAN, $NULL_FACTION_MSG,
$NULL_FACTION_TITLE, $NULL_LIST_MSG, $NULL_LIST_TITLE,
$NUMERIC, $OBJDIR, $OFF,
$ON, $PERS_DIR, $PERS_WRITE_ERROR_MSG,
$PERS_WRITE_ERROR_TITLE, $PREFIX, $PRIV_DIR,
$RB_FAILED_MSG, $RB_LINES_MSG, $RB_OK_MSG,
$RB_RUNNING_MSG, $RB_TIME_MSG, $RB_TITLE,
$REALNAME, $RELOAD_MSG, $RELOAD_TITLE,
$THEME_PICK_TITLE, $THEME_SET_MSG, $THEME_TITLE,
$NO_THEMES_MSG, $KEYMAP_PICK_TITLE, $KEYMAP_SET_MSG,
$KEYMAP_TITLE, $NO_KEYMAPS_MSG, $KEY_SEARCH_LABEL,
$SEARCH_OBJ_TITLE, $SEARCH_OBJ_PROMPT, $SEARCH_RESULTS_TITLE,
$NOTIFY_TITLE, $RESTRICTED_MSG, $RESTRICTED_TITLE,
$RS_BOTTOM_ROWS, $RS_HEADER_ROWS, $RS_INFO_ID,
$RS_STDERR_ID, $RS_STDOUT_ID, $RS_TOP_ROWS,
$SAVE_DETAILED, $SAVE_DETAILED_DESCR, $SAVE_ERROR_MSG,
$SAVE_ERROR_TITLE, $SAVE_FIELDVAL_MSG, $SAVE_FIELDVAL_TITLE,
$SAVE_FNAME_PROMPT, $SAVE_FNAME_TITLE, $SAVE_SCRIPT,
$SAVE_SCRIPT_DESCR, $SAVE_SIMPLE, $SAVE_SIMPLE_DESCR,
$SAVE_TYPE_TITLE, $SEARCH_PTRN_PROMPT, $SEARCH_PTRN_TITLE,
$SEPARATOR, $SEP_LINE, $SEP_LINE_DOUBLE,
$SEP_TEXT, $SEP_TEXT_CENTER, $SHOW_ACTION_TITLE,
$SIMPLE, $SR_BUFF_SIZE, $SYNTH_KEY_BASE,
$STRING, $THEMEDIR, $KEYMAPDIR,
$TRUE, $UCSTRING, $USERNAME,
$USR_CFG, $USR_OBJ, $VERSION,
$VERSION_DATE, $VERSION_YEAR, $WAIT_MSG_MSG,
$WRKDIR, $YES, $attrk,
$attrv, $called_form, $ch,
$choice, $cpid, $descr,
$es, $exec_hh, $exec_mm,
$exec_ss, $i, $id,
$lflags_size, $mlmargin, $mwin,
$mwinr, $opt, $out,
$ovl_mode, $p, $pad_lines,
$path, $pid, $prev_wdir,
$res, $rflags_size, $s,
$scan, $search_string, $shcut_type,
$text, $tmpfh, $twin,
@CONFIRM_ITEMS, @ERR_LITTLE_SCREEN, @ERR_WRONG_FPATH,
@FORM_TOP_MSG, @FSKeys, @LW_DISPLAY_TOP_MSG,
@LW_MULTIVAL_TOP_MSG, @LW_SINGLEVAL_TOP_MSG, @MENU_TOP_MSG,
@MSKeys, @RSKeys, @cnf_path,
@cnf_path_base, @es_str, @flist,
@fn_key_functions, @lines, @mf_path,
@mf_path_base, %FN_LABEL, %bool_vals,
%layout_vals, %options, %sep_type_vals,
%type_vals,
);
## END-OUR
# Optional display-width support. In a UTF-8 locale a label/title can occupy
# fewer screen columns than it has bytes (e.g. "caf\xc3\xa9" is 5 bytes, 4
# columns) and a CJK glyph occupies two columns; ncursesw already lays the
# screen out by columns, so CCFE's own layout maths must measure columns too,
# not bytes. Text::CharWidth::mbswidth() (Debian libtext-charwidth-perl)
# reports the column width per the locale, matching ncursesw exactly; if it is
# absent disp_width() falls back to length(), which is column-identical in a
# single-byte locale. See disp_width() below.
our $HAVE_CHARWIDTH = eval { require Text::CharWidth; 1 };
# The explicit run-state container (M7 de-globalisation, REFACTOR.md §3.2).
# Built first so the config defaults and load_config below fill $ctx->{cfg}
# rather than scattered package globals; see M7-CTX-PLAN.md (Phase 4).
our $ctx = CCFE::Context::new();
$VERSION = '2.4';
$VERSION_DATE = '12/06/2026';
$VERSION_YEAR = '2009, 2026';
# Install paths are resolved at runtime from this program's own location, so
# the same unmodified file works at any prefix -- no install-time templating.
# $PREFIX is the directory above bin/ (FindBin::RealBin resolves a PATH lookup
# or a symlinked instance name to the real bin dir). Each directory may be
# overridden by an environment variable, which is how an FHS package points at
# a split tree (e.g. CCFE_ETC_DIR=/etc/ccfe).
$PREFIX = $ENV{CCFE_PREFIX} || dirname($FindBin::RealBin);
$ETCDIR = $ENV{CCFE_ETC_DIR} || "$PREFIX/etc";
$BINDIR = $ENV{CCFE_BIN_DIR} || "$PREFIX/bin";
$LIBDIR = "$PREFIX/lib";
$LOGDIR = $ENV{CCFE_LOG_DIR} || "$PREFIX/log";
$MSGDIR = $ENV{CCFE_MSG_DIR} || "$PREFIX/msg";
$OBJDIR = $ENV{CCFE_OBJ_DIR} || "$PREFIX/share/ccfe/objects";
$THEMEDIR = $ENV{CCFE_THEME_DIR} || "$PREFIX/share/ccfe/themes";
$KEYMAPDIR = $ENV{CCFE_KEYMAP_DIR} || "$PREFIX/share/ccfe/keymaps";
$REALNAME = 'ccfe';
$DESCR = 'The Curses Command Front-end';
$CALLNAME = basename($0);
$USERNAME = ( getpwuid($>) )[0];
$HOSTNAME = ( split /\./, hostname )[0];
$MENUEXT = '.menu';
$FORMEXT = '.form';
$DMENU_DEF_FNAME = 'definition';
# Per-user locations follow the XDG base-directory spec, with the legacy
# ~/.ccfe kept as a fallback so existing setups keep working.
$USR_CFG = ( $ENV{XDG_CONFIG_HOME} || "$ENV{HOME}/.config" ) . "/$REALNAME";
$USR_OBJ = ( $ENV{XDG_DATA_HOME} || "$ENV{HOME}/.local/share" ) . "/$REALNAME";
$LEGACY_DIR = "$ENV{HOME}/.$REALNAME";
$PRIV_DIR = $USR_OBJ;
$PERS_DIR = "$PRIV_DIR/persistent";
$NO = $OFF = $FALSE = 0;
$YES = $ON = $TRUE = 1;
$DEBUG = $NO;
$ctx->{cfg}{PERMIT_DEBUG} = $YES;
$MARK_PRIV_SHCUTS = $YES;
$MAIN_PATH = '/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin';
$ctx->{cfg}{PATH} = "$ENV{HOME}/bin";
$ctx->{cfg}{LOG_FNAME} = "$LOGDIR/$USERNAME.log";
$LOG_DATE = $NO;
$LOG_NORMAL = 1;
$LOG_LIST_CMD = 2;
$LOG_DEFAULT_CMD = 4;
$LOG_ACTION_CMD = 8;
$LOG_FIELDS_VAL = 16;
$LOG_MENU_CHOICE = 32;
$LOG_ACTION_OUT = 64;
$LOG_SYSCALL_ENV = 128;
$LOG_SCAN_PATHS = 256;
$LOG_INITFORM_OUT = 512;
$ctx->{cfg}{LOG_LEVEL} = $LOG_NORMAL;
$LOG_REQUESTED = $NO;
$LW_COLS = 76;
$LW_ROW0 = 2;
$LW_PAD_COLS = 160;
$LW_FOOTER_ROWS = 3;
$MSG_WIN_ROWS = 5;
$MS_HEADER_ROWS = 2;
$MS_TOP_ROWS = 2;
$MS_BOTTOM_ROWS = 0;
$ctx->{cfg}{MS_FOOTER_ROWS} = 2;
$FS_HEADER_ROWS = 2;
$FS_TOP_ROWS = 3;
$FS_BOTTOM_ROWS = 0;
$ctx->{cfg}{FS_FOOTER_ROWS} = 2;
$RS_HEADER_ROWS = 2;
$RS_TOP_ROWS = 1;
$RS_BOTTOM_ROWS = 0;
$ctx->{cfg}{RS_FOOTER_ROWS} = 2;
$ES_NO_ERR = 0;
$ES_SYNTAX_ERR = 1;
$ES_FOPEN_ERR = 2;
$ES_NOT_FOUND = 3;
$ES_NO_ITEMS = 4;
$ES_USER_REQ = 253;
$ES_CANCEL = 254;
$ES_EXIT = 255;
$NUMERIC = 1;
$BOOLEAN = 2;
$NULLBOOLEAN = 6;
$STRING = 8;
$UCSTRING = 24;
$SEPARATOR = 256;
$SEP_TEXT = 1;
$SEP_TEXT_CENTER = 2;
$SEP_LINE = 3;
$SEP_LINE_DOUBLE = 4;
$BOOLEAN_FIELD_SIZE = 3;
$BFIELD_YES = 'YES';
$BFIELD_NO = 'NO';
$BFIELD_NULL = '';
$BFIELD_DEFAULT = $BFIELD_NO;
# Defaults so a headless load_form (e.g. --dump/-k, before load_msgs) does not
# read these undef; load_msgs overrides them with the localised descriptions.
$BFIELD_YES_DESCR = 'Yes';
$BFIELD_NO_DESCR = 'No';
$BFIELD_NULL_DESCR = 'Not set';
$MIN_ITEMS_FOR_FIND = 5;
$INIT_REMOVE_FIELDS = 'CCFE_REMOVE_FIELDS';
$INIT_ENABLE_FIELDS = 'CCFE_ENABLE_FIELDS';
$INIT_DISABLE_FIELDS = 'CCFE_DISABLE_FIELDS';
$FORM_ARGV_ID = 'ARGV';
$ALL_FIELDS_IDS_TAG = '\*';
$FSEP_ID_PRFX = 'CCFEFSEP';
$NORMAL = 0;
$SIMPLE = 1;
%layout_vals = (
normal => $NORMAL,
simple => $SIMPLE
);
$ASKS_WIN_ROWS = 5;
$ASKS_WIN_COLS = 78;
$ASKS_WIN_FTR_ROWS = 2;
$ASKS_FIELD_SIZE = 40;
$SAVE_SIMPLE = 'Simple';
$SAVE_DETAILED = 'Detailed';
$SAVE_SCRIPT = 'Script';
$RS_INFO_ID = 'C';
$RS_STDOUT_ID = 'O';
$RS_STDERR_ID = 'E';
$SR_BUFF_SIZE = 512;
# Base for synthetic key codes assigned to functions bound only to Meta/Ctrl/
# plain keys (no F-key), so the `$ch == {code}` dispatch still matches once
# read_key() has translated the chord (FEATURE-REQUESTS A3). Well above every
# real ncurses keycode (KEY_MAX is ~0777) so it can never collide.
$SYNTH_KEY_BASE = 0x10000000;
# Menus/forms: system objects dir, then the user's XDG data dir, then the
# legacy ~/.ccfe. Config: system etc, then XDG config, then legacy.
@mf_path =
( "$OBJDIR/$CALLNAME", "$USR_OBJ/$CALLNAME", "$LEGACY_DIR/$CALLNAME", );
@cnf_path = (
"$ETCDIR/$REALNAME.conf", "$USR_CFG/$REALNAME.conf",
"$LEGACY_DIR/$REALNAME.conf",
);
if ( $CALLNAME ne $REALNAME ) {
push @cnf_path, "$ETCDIR/$CALLNAME.conf", "$USR_CFG/$CALLNAME.conf",
"$LEGACY_DIR/$CALLNAME.conf";
}
%bool_vals = (
yes => $YES,
no => $NO
);
%type_vals = (
numeric => $NUMERIC,
boolean => $BOOLEAN,
nullboolean => $NULLBOOLEAN,
string => $STRING,
ucstring => $UCSTRING
);
%sep_type_vals = (
text => $SEP_TEXT,
text_center => $SEP_TEXT_CENTER,
line => $SEP_LINE,
line_double => $SEP_LINE_DOUBLE
);
@fn_key_functions =
qw( back exit help list redraw reload reset_field save search sel_items shell_escape show_action );
$ctx->{state}{SCREEN_DIR} = '';
$HTAB_COLS = 2;
$FIELD_LMARGIN = 2;
$FIELD_RMARGIN = 2;
$ctx->{state}{child_es} = 0;
$ctx->{state}{last_item_id} = '';
$ctx->{state}{pad_lines} = 0;
undef $ctx->{state}{exec_args};
undef $cpid;
undef $tmpfh;
$SIG{INT} = sub {
trace("SIGINT handler start - child PID $cpid");
if ( defined($cpid) ) {
trace(
"PID $$ received SIGINT: waiting child (PID $cpid) to terminate..."
);
kill 15, $cpid;
waitpid( $cpid, 0 );
trace("PID $cpid terminated");
my $msg = "PID $cpid execution interrupted by SIGINT!";
undef $cpid;
print $tmpfh "$RS_INFO_ID:\n";
print $tmpfh "$RS_INFO_ID:$msg\n";
$ctx->{state}{pad_lines} += 2;
}
trace("SIGINT handler end");
};
sub REAPER {
my $child;
while ( ( $child = waitpid( -1, WNOHANG ) ) > 0 ) {
$ctx->{state}{child_es} = $? >> 8;
}
$SIG{CHLD} = \&REAPER;
}
$SIG{CHLD} = \&REAPER;
# Screen-column width of a (possibly UTF-8) string -- the unit ncursesw lays
# the screen out in. Pure-ASCII strings (the overwhelming majority of labels)
# take the fast length() path; otherwise use mbswidth() when available.
sub disp_width {
my ($s) = @_;
return 0 unless defined $s;
return length($s) if $s !~ /[^\x00-\x7f]/; # ASCII: bytes == columns
if ($HAVE_CHARWIDTH) {
my $w = Text::CharWidth::mbswidth($s);
return $w if defined $w && $w >= 0; # -1 == has non-printables
}
return length($s);
}
# Theme helper, callable from a config *_attr value: the attribute bits for a
# foreground-over-background colour pair, e.g. `screen_attr = color_pair('white',
# 'blue')`. $bg defaults to the terminal's own background (so color_pair('cyan')
# == a plain cyan foreground). The pair is created after start_color(); see the
# colour-enable block below and CCFE::Theme::pair_for().
sub color_pair {
my ( $fg, $bg ) = @_;
return COLOR_PAIR( CCFE::Theme::pair_for( $fg, $bg ) );
}
# Resolve a config attribute expression to its numeric value WITHOUT eval
# (M8/TD-1d: a config *_attr value is data, never code). Accepts the documented
# grammar -- the A_* video attributes, COLOR_PAIR(n), color_pair('fg','bg'), a
# bare integer, and `|`-combinations of those -- and returns undef on anything
# else, so a malformed config value is ignored (the caller keeps the default)
# instead of being able to inject Perl.
my %ATTR_CONST;
sub attr_value {
my ($str) = @_;
return undef unless defined $str;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
return undef if $str eq '';
%ATTR_CONST = (
A_NORMAL => A_NORMAL,
A_BOLD => A_BOLD,
A_REVERSE => A_REVERSE,
A_UNDERLINE => A_UNDERLINE,
A_BLINK => A_BLINK,
A_DIM => A_DIM,
A_STANDOUT => A_STANDOUT,
) unless %ATTR_CONST;
my $val = 0;
for my $tok ( split /\s*\|\s*/, $str ) {
if ( exists $ATTR_CONST{$tok} ) {
$val |= $ATTR_CONST{$tok};
}
elsif ( $tok =~ /^COLOR_PAIR\(\s*(\d+)\s*\)$/ ) {
$val |= COLOR_PAIR($1);
}
elsif ( $tok =~ /^color_pair\(\s*'([a-z]+)'\s*,\s*'([a-z]+)'\s*\)$/ ) {
$val |= color_pair( $1, $2 );
}
elsif ( $tok =~ /^-?\d+$/ ) {
$val |= $tok;
}
else {
return undef; # outside the grammar -> ignore (no eval, no inject)
}
}
return $val;
}
sub fatal {
trace("FATAL: @_");
clrtobot( 0, 0 );
addstr( 0, 0, "@_\n" );
refresh();
sleep 2;
endwin();
exit 1;
}
sub usage {
my $layouts = lc join( '|', keys(%layout_vals) );
print <<"EOF";
$DESCR.
Usage: $CALLNAME [OPTION]... [SHORTCUT]
Options:
-c : print some Configuration parameters and exit
-d : set verbose log for Debugging purposes
-D NAME : Dump menu/form NAME as JSON, then exit (no terminal needed)
--dump N : long form of -D
-h : print this (Help) message and exit
-k NAME : checK that menu/form NAME parses, then exit (no terminal needed)
-l PATH : set forms and menus Library directory to PATH
-P : list installed Plugins (--plugins) and exit
-R : force Restricted (kiosk) mode for this run (--restricted)
-s : print available Shortcuts and exit
-v : print Version informations and exit
SHORTCUT: initial form or menu name (without extension)
EOF
exit;
}
sub print_config {
print <<"EOF";
ETC_DIR=$ETCDIR
LIB_DIR=$LIBDIR
OBJ_DIR=$OBJDIR
THEME_DIR=$THEMEDIR
MSG_DIR=$MSGDIR
EOF
exit;
}
sub trim {
my ($string) = @_;
for ($$string) {
s/^\s+//;
s/\s+$//;
}
}
sub ralign {
my ( $str, $size ) = @_;
# Plain sprintf, not an eval-string: $str is data, never interpolated into
# code (M8 audit -- removes a latent injection smell).
return sprintf "% ${size}s", $str;
}
# True only when we are *confident* an exec: action's command cannot be run:
# its first word is a bare name found nowhere on PATH, or an explicit path that
# is not an executable file. Returns false (let it proceed) for anything we
# cannot judge cleanly -- an env-assignment prefix (VAR=x cmd), a shell
# metacharacter, or an empty command -- so the check never blocks a valid
# action; a genuine failure of those is still caught by the exec() fallback.
# Used to show a clear "command not found" pop-up while the TUI is still up,
# before exec: tears curses down (FEATURE-REQUESTS item 6).
sub exec_prog_missing {
my ($cmd) = @_;
my @words = shellwords( $cmd // '' );
return $NO unless @words;
my $prog = $words[0];
return $NO if $prog =~ /=/; # env-assignment prefix -> via shell
return $NO
if $cmd =~ m{[|&;<>(){}\$`*?\[\]~]}; # shell metachars -> via shell
if ( $prog =~ m{/} ) { # explicit path: check it directly
return ( -x $prog and !-d _ ) ? $NO : $YES;
}
for my $dir ( split /:/, ( $ENV{PATH} // '' ), -1 ) {
$dir = '.' if $dir eq '';
return $NO if -x "$dir/$prog" and !-d _;
}
return $YES; # bare name, found nowhere
}
sub valid_shell {
my ($shell) = @_;
my $shells = '/etc/shells';
my $found = $NO;
open( SHELLS, $shells ) || die("Error opening $shells:\n$!");
while (<SHELLS>) {
chop;
$found = $YES if /^$shell$/;
}
close(SHELLS);
return $found;
}
# ---- restricted-mode policy (security: prevent escape from the menu) -----
#
# When RESTRICTED is enabled (via the GLOBAL config) CCFE is a constrained
# front-end: the menu user must only be able to do what the menus allow.
# These helpers are consulted at every escape-capable site so the policy
# lives in one place. See REFACTOR.md section 2.
# Thin tracing wrappers over the pure CCFE::Restrict policy: the decisions
# live in the module (unit-tested headlessly), the program just supplies its
# configuration and logs a denial.
sub restricted_denies_verb {
my ( $verb, $args ) = @_;
my $deny = CCFE::Restrict::denies_verb(
$ctx->{cfg}{RESTRICTED},
$ctx->{cfg}{RESTRICTED_ALLOW},
$verb, $args
);
trace("RESTRICTED: denied $verb:\"$args\" (not in RESTRICTED_ALLOW)")
if $deny;
return $deny;
}
sub restricted_denies_shell {
my $deny = CCFE::Restrict::denies_shell( $ctx->{cfg}{RESTRICTED} );
trace('RESTRICTED: interactive shell escape denied') if $deny;
return $deny;
}
# Called once at startup -- CCFE itself does not rely on these variables after
# the dynamic libraries are already loaded.
sub harden_child_env {
return CCFE::Restrict::harden_env( \%ENV );
}
{
my $log_fh; # persistent log handle, opened lazily and reused
my $log_fh_name; # the LOG_FNAME it was opened for
# Append a pre-formatted string to the log, holding the handle open across
# calls (TD-5). Autoflush keeps every line on disk immediately, exactly as
# the old open/append/close-per-line did, but without the per-line syscalls
# in a streaming command's output capture. 3-arg open with an explicit
# append mode so a crafted LOG_FNAME cannot smuggle a pipe or redirect.
# Shared by trace() and the $SIG{__WARN__} handler.
sub _log_write {
my ($str) = @_;
my $fname = $ctx->{cfg}{LOG_FNAME};
return unless $fname;
if ( !$log_fh or ( $log_fh_name // '' ) ne $fname ) {
close($log_fh) if $log_fh;
my $prev_umask = umask 0177;
unless ( open( $log_fh, '>>', $fname ) ) {
umask $prev_umask;
$log_fh = undef;
return;
}
umask $prev_umask;
select( ( select($log_fh), $| = 1 )[0] ); # autoflush this handle
$log_fh_name = $fname;
}
print {$log_fh} $str;
return;
}
}
sub trace {
my ( $msg, $log_level ) = @_;
$log_level //= 0; # no level given -> 0 (logged only under DEBUG, as before)
# TD-5: gate on LOG_FNAME and the log level *before* doing any timestamp or
# caller work -- there is nothing to format if the line will not be logged.
return unless $ctx->{cfg}{LOG_FNAME};
my $log_it = $NO;
if ( $ctx->{cfg}{LOG_LEVEL} & $log_level ) {
$log_it = $YES;
if ( $LOG_NORMAL & $log_level ) {
$log_it = $NO if !$LOG_REQUESTED;
}
}
$log_it = $YES if $DEBUG;
return unless $log_it;
my $caller = '';
if ($DEBUG) {
$caller = ( caller(1) )[3];
$caller =~ s/^.*:://;
$caller .= "[$$]: " if $caller;
}
my $now = '';
if ($LOG_DATE) {
my @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my @buff = localtime(time);
$now = sprintf "%s %02d %d %02d:%02d:%02d%s",
$months[ $buff[4] ],
$buff[3], $buff[5] + 1900, $buff[2], $buff[1], $buff[0],
$DEBUG ? ' ' : "\n";
}
_log_write( sprintf "%s%s%s\n", $now, $caller, $msg );
return;
}
sub get_lang_id {
my $lang_id = 'C';
return $lang_id;
}
sub load_msgs {
my $id;
my $fname = "$MSGDIR/$LANG_ID/$CALLNAME";
my @msg_id = qw(NULL_LIST_MSG
NULL_LIST_TITLE
EMPTY_LIST_MSG
EMPTY_LIST_TITLE
LIST_CMD_ERR_MSG
LIST_CMD_ERR_TITLE
RESTRICTED_MSG
RESTRICTED_TITLE
RELOAD_MSG
RELOAD_TITLE
THEME_PICK_TITLE
THEME_SET_MSG
THEME_TITLE
NO_THEMES_MSG
KEYMAP_PICK_TITLE
KEYMAP_SET_MSG
KEYMAP_TITLE
NO_KEYMAPS_MSG
KEY_SEARCH_LABEL
SEARCH_OBJ_TITLE
SEARCH_OBJ_PROMPT
SEARCH_RESULTS_TITLE
NOTIFY_TITLE
NULL_FACTION_MSG
NULL_FACTION_TITLE
EXEC_NOTFOUND_MSG
EXEC_NOTFOUND_TITLE
SAVE_FIELDVAL_MSG
SAVE_FIELDVAL_TITLE
BIG_OUTPUT_MSG
BIG_OUTPUT_TITLE
FOUND_NONE_MSG
FOUND_NONE_TITLE
SEARCH_PTRN_PROMPT
SEARCH_PTRN_TITLE
CALL_SYS_ES_MSG
CALL_SYS_MSG
MSG_WIN_BMSG
MSG_WIN_TITLE
BFIELD_YES_DESCR
BFIELD_NO_DESCR
BFIELD_NULL_DESCR
CONFIRM_TITLE
CONFIRM_DESCR_NO
CONFIRM_DESCR_YES
SHOW_ACTION_TITLE
KEY_F1_LABEL
KEY_F2_LABEL
KEY_F3_LABEL
KEY_F4_LABEL
KEY_F5_LABEL
KEY_F6_LABEL
KEY_F7_LABEL
KEY_F8_LABEL
KEY_F9_LABEL
KEY_F10_LABEL
KEY_F11_LABEL
KEY_F12_LABEL
KEY_ENTER_LABEL
KEY_INTR_LABEL
KEY_FIND_LABEL
KEY_FNEXT_LABEL
KEY_RELOAD_LABEL
KEY_SELALL_LABEL
KEY_UNSELALL_LABEL
CALL_SHELL_MSG
WAIT_MSG_MSG
FORM_ERR_TITLE
LOAD_FORM_ERR_MSG
INIT_FORM_ERR_MSG
MENU_ERR_TITLE
LOAD_MENU_ERR_MSG
RB_TITLE
RB_RUNNING_MSG
RB_OK_MSG
RB_FAILED_MSG
RB_LINES_MSG
RB_TIME_MSG
SAVE_TYPE_TITLE
SAVE_SIMPLE_DESCR
SAVE_DETAILED_DESCR
SAVE_SCRIPT_DESCR
SAVE_FNAME_PROMPT
SAVE_FNAME_TITLE
SAVE_ERROR_MSG
SAVE_ERROR_TITLE
LOG_WRITE_ERROR_MSG
LOG_WRITE_ERROR_TITLE
PERS_WRITE_ERROR_TITLE
PERS_WRITE_ERROR_MSG
ERR_LITTLE_SCREEN[0]
ERR_LITTLE_SCREEN[1]
ERR_WRONG_FPATH[0]
ERR_WRONG_FPATH[1]
ERR_LOAD_INITIAL_OBJ
ES_NO_ERR_MSG
ES_SYNTAX_ERR_MSG
ES_FOPEN_ERR_MSG
ES_NOT_FOUND_MSG
ES_NO_ITEMS_MSG
LW_MULTIVAL_TOP_MSG[0]
LW_MULTIVAL_TOP_MSG[1]
LW_MULTIVAL_TOP_MSG[2]
LW_SINGLEVAL_TOP_MSG[0]
LW_SINGLEVAL_TOP_MSG[1]
LW_SINGLEVAL_TOP_MSG[2]
LW_DISPLAY_TOP_MSG[0]
LW_DISPLAY_TOP_MSG[1]
LW_DISPLAY_TOP_MSG[2]
FORM_TOP_MSG[0]
FORM_TOP_MSG[1]
MENU_TOP_MSG[0]
MENU_TOP_MSG[1]
ERR_EMPTY_FIELD_MSG
ERR_EMPTY_FIELD_TITLE
BAD_SHELL_MSG
BAD_SHELL_TITLE);
foreach $id (@msg_id) {
eval "\$$id = \"ERROR_OR_UNDEFINED_MSG:$id\"";
}
open( INF, $fname ) or die("$CALLNAME: Error opening file $fname\n");
while (<INF>) {
chop;
next if /^\s*#/;
next if /^$/;
s/\s*#.*$//;
s/^\s*([\w\[\]]+)\s*=\s*(.+)?/\$\U$1\E=$2/;
$id = uc($1);
($id) = (/^\s*(\S+)\s*=/) if !$id;
if ( in( $id, @msg_id ) ) {
eval;
}
else {
trace("unknown message ID '$id'");
}
while ( !$LW_MULTIVAL_TOP_MSG[$#LW_MULTIVAL_TOP_MSG] ) {
pop(@LW_MULTIVAL_TOP_MSG);
}
while ( !$LW_SINGLEVAL_TOP_MSG[$#LW_SINGLEVAL_TOP_MSG] ) {
pop(@LW_SINGLEVAL_TOP_MSG);
}
while ( !$LW_DISPLAY_TOP_MSG[$#LW_DISPLAY_TOP_MSG] ) {
pop(@LW_DISPLAY_TOP_MSG);
}
$CONFIRM_ITEMS[0] = "$BFIELD_NO $CONFIRM_DESCR_NO";
$CONFIRM_ITEMS[1] = "$BFIELD_YES $CONFIRM_DESCR_YES";
}
close(INF);
}
# Substitute $NAME / ${NAME} references to config `variables {}` in a command or
# action string with their resolved values. Only names defined in the section
# are replaced; any other $... is left untouched for the shell. The variables
# are system-config-owned (and config-locked under RESTRICTED), so this is a DRY
# convenience for menu/form authors, not an untrusted-input path. Applied at
# the command choke points (exec_command / call_system / run_browse / the final
# exec). (FEATURE-REQUESTS item 3.)
sub expand_vars {
my ($str) = @_;
return $str unless defined $str;
my $vars = $ctx->{cfg}{vars} or return $str;
$str =~ s/\$\{(\w+)\}/ exists $vars->{$1} ? $vars->{$1} : "\${$1}" /ge;
$str =~ s/\$(\w+)/ exists $vars->{$1} ? $vars->{$1} : "\$$1" /ge;
return $str;
}
sub exec_command {
my ( $cmd, $extra_path, $stdout_ref, $stderr_ref ) = @_;
$cmd = expand_vars($cmd);
my ( $prev_path, $prev_wdir );
$prev_wdir = getcwd();
chdir "$ctx->{state}{SCREEN_DIR}";
trace( "Changed CWD from $prev_wdir to " . getcwd() );
$prev_path = $ENV{PATH};
$ENV{PATH} = sprintf "%s%s:%s", $MAIN_PATH,
$MAIN_PATH ? ":$ctx->{cfg}{PATH}" : '',
$ctx->{state}{SCREEN_DIR};
if ($extra_path) {
my @dirs = split /:/, $extra_path;
foreach $i ( 0 .. $#dirs ) {
$dirs[$i] = "$ctx->{state}{SCREEN_DIR}/$dirs[$i]"
unless $dirs[$i] =~ /^\//;
}
$extra_path = join( ':', @dirs );
}
$ENV{PATH} .= ":$extra_path" if $extra_path;
trace( "PATH=\"$ENV{PATH}\"", $LOG_SYSCALL_ENV );
trace("executing \"$cmd\"");
@$stdout_ref = ();
@$stderr_ref = ();
local *CATCHERR = IO::File->new_tmpfile;
my $pid = open3( gensym, \*CATCHOUT, ">&CATCHERR", $ctx->{cfg}{OPEN3_SHELL},
'-c', $cmd );
while (<CATCHOUT>) {
push @$stdout_ref, $_;
}
waitpid( $pid, 0 );
seek CATCHERR, 0, 0;
while (<CATCHERR>) {
push @$stderr_ref, $_;
}
$ENV{PATH} = $prev_path;
chdir "$prev_wdir";
trace( "Restored CWD to " . getcwd() );
@$stdout_ref = map { s/\n//; $_ } @$stdout_ref;
@$stderr_ref = map { s/\n//; $_ } @$stderr_ref;
@$stdout_ref = map { s/\r//; $_ } @$stdout_ref;
@$stderr_ref = map { s/\r//; $_ } @$stderr_ref;
close(CATCHOUT);
close(CATCHERR);
return (@$stderr_ref) ? $FALSE : $TRUE;
}
sub init_title {
my ( $win, $winRows, $title ) = @_;
$title =~ s/^\s+//;
$title =~ s/\s+$//;
addstr( $win, 0, 0, $USERNAME . '@' . $HOSTNAME )
if ( $ctx->{cfg}{LAYOUT} == $NORMAL );
attron( $win, $ctx->{cfg}{TITLE_ATTR} )
if ( $ctx->{cfg}{LAYOUT} == $NORMAL );
addstr( $win, 0, int( ( $COLS - disp_width($title) ) / 2 ), $title );
attroff( $win, $ctx->{cfg}{TITLE_ATTR} )
if ( $ctx->{cfg}{LAYOUT} == $NORMAL );
hline( $win, $winRows - 1, 0, ACS_HLINE, $COLS )
if ( $ctx->{cfg}{LAYOUT} == $NORMAL );
}
# Normalise a menu/form top{} message into a flat list of display lines that fit
# $width columns: flatten any embedded newlines, then word-wrap lines longer than
# $width. Used to size the top area dynamically so a long description forces
# vertical space (the menu is placed below the full message) instead of being
# overdrawn by it.
sub wrap_top_lines {
my ( $lines, $width ) = @_;
$width = 1 if !$width || $width < 1;
my @out;
for my $line ( @{ $lines || [] } ) {
next unless defined $line;
for my $seg ( split /\n/, $line ) {
$seg =~ s/\s+$//;
if ( length($seg) <= $width ) { push @out, $seg; next; }
my $cur = '';
for my $word ( split /\s+/, $seg ) {
if ( $cur eq '' ) { $cur = $word }
elsif ( length("$cur $word") <= $width ) { $cur .= " $word" }
else { push @out, $cur; $cur = $word }
}
push @out, $cur if $cur ne '';
}
}
return @out;
}
sub init_top {
my ( $win, $has_border, $winY0, $winRows, @tlines ) = @_;
my ( $maxLen, $i, $tlmargin, $maxY, $maxX );
getmaxyx( $win, $maxY, $maxX );
$maxLen = 0;
foreach $i ( 0 .. $#tlines ) {
$maxLen = length( $tlines[$i] ) if length( $tlines[$i] ) > $maxLen;
}
if ( $ctx->{cfg}{LAYOUT} == $SIMPLE ) {
$tlmargin = $has_border ? 2 : 0;
}
else {
$tlmargin = int( ( $maxX - $maxLen ) / 2 ) + ( $has_border ? 1 : 0 );
}
foreach $i ( 0 .. $winRows - 1 ) {
last if $i > $#tlines;
addstr( $win, $winY0 + $i, $tlmargin, $tlines[$i] );
}
}
sub init_footer {
my ( $win, $has_border, $nRows, @keysList ) = @_;
my ( $nOptPerRow, $labelSize, $y, $x, $y0, $x0, $i, $maxY, $maxX );
sub sort_fnkeys {
my ($klist_ref) = @_;
my @sorted = sort {
if ( $ctx->{cfg}{keys}{$a}{key} !~ /F[0-9]+/ ) {
return 0;
}
elsif ( $ctx->{cfg}{keys}{$b}{key} !~ /F[0-9]+/ ) {
return 0;
}
else {
return