xref: /freebsd/contrib/less/main.c (revision 4523eebc6c1828d4fd41d7f1ab943cf079043bc8)
1 /*
2  * Copyright (C) 1984-2026  Mark Nudelman
3  *
4  * You may distribute under the terms of either the GNU General Public
5  * License or the Less License, as specified in the README file.
6  *
7  * For more information, see the README file.
8  */
9 
10 
11 /*
12  * Entry point, initialization, miscellaneous routines.
13  */
14 
15 #include "less.h"
16 #if MSDOS_COMPILER==WIN32C
17 #define WIN32_LEAN_AND_MEAN
18 #include <windows.h>
19 
20 #if defined(__MINGW32__) || defined(_MSC_VER)
21 #include <locale.h>
22 #include <shellapi.h>
23 #endif
24 
25 public unsigned less_acp = CP_ACP;
26 #endif
27 
28 #include "option.h"
29 
30 public char *   every_first_cmd = NULL;
31 public lbool    new_file;
32 public lbool    is_tty;
33 public IFILE    curr_ifile = NULL_IFILE;
34 public IFILE    old_ifile = NULL_IFILE;
35 public struct scrpos initial_scrpos;
36 public POSITION start_attnpos = NULL_POSITION;
37 public POSITION end_attnpos = NULL_POSITION;
38 public int      wscroll;
39 static constant char *progname;
40 public lbool    quitting = FALSE;
41 public lbool    dohelp = FALSE;
42 public char *   init_header = NULL;
43 public constant char * no_config = NULL;
44 static unsigned int secure_allow_features;
45 
46 #if LOGFILE
47 public int      logfile = -1;
48 public lbool    force_logfile = FALSE;
49 public char *   namelogfile = NULL;
50 #endif
51 
52 #if EDITOR
53 public constant char *   editor;
54 public constant char *   editproto;
55 #endif
56 
57 #if TAGS
58 extern char *   tags;
59 extern char *   tagoption;
60 extern int      jump_sline;
61 #endif
62 
63 #if HAVE_TIME
64 public time_type less_start_time;
65 #endif
66 
67 #ifdef WIN32
68 static wchar_t consoleTitle[256];
69 #endif
70 
71 public lbool    one_screen;
72 extern lbool    less_is_more;
73 extern lbool    missing_cap;
74 extern int      know_dumb;
75 extern int      quit_if_one_screen;
76 extern int      no_init;
77 extern int      errmsgs;
78 extern int      redraw_on_quit;
79 extern int      term_addrs;
80 extern lbool    first_time;
81 extern lbool    term_init_ever;
82 
83 #if MSDOS_COMPILER==WIN32C && (defined(__MINGW32__) || defined(_MSC_VER))
84 /* malloc'ed 0-terminated utf8 of 0-terminated wide ws, or null on errors */
utf8_from_wide(constant wchar_t * ws)85 static char *utf8_from_wide(constant wchar_t *ws)
86 {
87 	char *u8 = NULL;
88 	int n = WideCharToMultiByte(CP_UTF8, 0, ws, -1, NULL, 0, NULL, NULL);
89 	if (n > 0)
90 	{
91 		u8 = ecalloc(n, sizeof(char));
92 		WideCharToMultiByte(CP_UTF8, 0, ws, -1, u8, n, NULL, NULL);
93 	}
94 	return u8;
95 }
96 
97 /*
98  * similar to using UTF8 manifest to make the ANSI APIs UTF8, but dynamically
99  * with setlocale. unlike the manifest, argv and environ are already ACP, so
100  * make them UTF8. Additionally, this affects only the libc/crt API, and so
101  * e.g. fopen filename becomes UTF-8, but CreateFileA filename remains CP_ACP.
102  * CP_ACP remains the original codepage - use the dynamic less_acp instead.
103  * effective on win 10 1803 or later when compiled with ucrt, else no-op.
104  */
try_utf8_locale(int * pargc,constant char *** pargv)105 static void try_utf8_locale(int *pargc, constant char ***pargv)
106 {
107 	char *locale_orig = strdup(setlocale(LC_ALL, NULL));
108 	wchar_t **wargv = NULL, *wenv, *wp;
109 	constant char **u8argv;
110 	char *u8e;
111 	int i, n;
112 
113 	if (!setlocale(LC_ALL, ".UTF8"))
114 		goto cleanup;  /* not win10 1803+ or not ucrt */
115 
116 	/*
117 	 * wargv is before glob expansion. some ucrt builds may expand globs
118 	 * before main is entered, so n may be smaller than the original argc.
119 	 * that's ok, because later code at main expands globs anyway.
120 	 */
121 	wargv = CommandLineToArgvW(GetCommandLineW(), &n);
122 	if (!wargv)
123 		goto bad_args;
124 
125 	u8argv = (constant char **) ecalloc(n + 1, sizeof(char *));
126 	for (i = 0; i < n; ++i)
127 	{
128 		if (!(u8argv[i] = utf8_from_wide(wargv[i])))
129 			goto bad_args;
130 	}
131 	u8argv[n] = 0;
132 
133 	less_acp = CP_UTF8;
134 	*pargc = n;
135 	*pargv = u8argv;  /* leaked on exit */
136 
137 	/* convert wide env to utf8 where we can, but don't abort on errors */
138 	if ((wenv = GetEnvironmentStringsW()))
139 	{
140 		for (wp = wenv; *wp; wp += wcslen(wp) + 1)
141 		{
142 			if ((u8e = utf8_from_wide(wp)))
143 				_putenv(u8e);
144 			free(u8e);  /* windows putenv makes a copy */
145 		}
146 		FreeEnvironmentStringsW(wenv);
147 	}
148 
149 	goto cleanup;
150 
151 bad_args:
152 	error(LM(cannot_use_unicode_arguments), NULL_PARG);
153 	setlocale(LC_ALL, locale_orig);
154 
155 cleanup:
156 	free(locale_orig);
157 	LocalFree(wargv);
158 }
159 #endif
160 
161 /*
162  * Set the secure_allow_features bitmask, which controls
163  * whether certain secure features are allowed.
164  */
init_secure(void)165 static void init_secure(void)
166 {
167 #if SECURE
168 	secure_allow_features = 0;
169 #else
170 	static struct csl_bitmap_def security_features[] = {
171 		{ "edit",     SF_EDIT },
172 		{ "examine",  SF_EXAMINE },
173 		{ "glob",     SF_GLOB },
174 		{ "history",  SF_HISTORY },
175 		{ "lesskey",  SF_LESSKEY },
176 		{ "lessopen", SF_LESSOPEN },
177 		{ "logfile",  SF_LOGFILE },
178 		{ "osc8",     SF_OSC8_OPEN },
179 		{ "pipe",     SF_PIPE },
180 		{ "shell",    SF_SHELL },
181 		{ "stop",     SF_STOP },
182 		{ "tags",     SF_TAGS },
183 	};
184 	constant char *str = lgetenv("LESSSECURE");
185 	if (isnullenv(str))
186 		secure_allow_features = ~0; /* allow everything */
187 	else
188 		secure_allow_features = 0; /* allow nothing */
189 
190 	str = lgetenv("LESSSECURE_ALLOW");
191 	if (!isnullenv(str))
192 		secure_allow_features = parse_csl_bitmap(str,
193 		    security_features, countof(security_features), "LESSSECURE_ALLOW");
194 
195 	str = lgetenv("LESSSECURE_DISALLOW");
196 	if (!isnullenv(str))
197 		secure_allow_features &=~ parse_csl_bitmap(str,
198 		    security_features, countof(security_features), "LESSSECURE_DISALLOW");
199 #endif
200 }
201 
202 /*
203  * Entry point.
204  */
main(int argc,constant char * argv[])205 int main(int argc, constant char *argv[])
206 {
207 	IFILE ifile;
208 	constant char *s;
209 	int i;
210 	struct xbuffer xfiles;
211 	constant int *files;
212 	size_t num_files;
213 	size_t f;
214 	lbool end_opts = FALSE;
215 	lbool posixly_correct;
216 
217 	no_config = lgetenv("LESSNOCONFIG");
218 	lmsg_init(lgetenv("LESSMSG"));
219 
220 #if MSDOS_COMPILER==WIN32C && (defined(__MINGW32__) || defined(_MSC_VER))
221 	if (GetACP() != CP_UTF8)  /* not using a UTF-8 manifest */
222 		try_utf8_locale(&argc, &argv);
223 #endif
224 
225 #ifdef __EMX__
226 	_response(&argc, &argv);
227 	_wildcard(&argc, &argv);
228 #endif
229 
230 	progname = *argv++;
231 	argc--;
232 	init_secure();
233 
234 #ifdef WIN32
235 	if (lgetenv("HOME") == NULL)
236 	{
237 		/*
238 		 * If there is no HOME environment variable,
239 		 * try the concatenation of HOMEDRIVE + HOMEPATH.
240 		 */
241 		constant char *drive = lgetenv("HOMEDRIVE");
242 		constant char *path  = lgetenv("HOMEPATH");
243 		if (drive != NULL && path != NULL)
244 		{
245 			char *env = (char *) ecalloc(strlen(drive) +
246 					strlen(path) + 6, sizeof(char));
247 			strcpy(env, "HOME=");
248 			strcat(env, drive);
249 			strcat(env, path);
250 			putenv(env);
251 		}
252 	}
253 	/* on failure, consoleTitle is already a valid empty string */
254 	GetConsoleTitleW(consoleTitle, countof(consoleTitle));
255 #endif /* WIN32 */
256 
257 	/*
258 	 * Process command line arguments and LESS environment arguments.
259 	 * Command line arguments override environment arguments.
260 	 */
261 	is_tty = (isatty(1) != 0);
262 	init_mark();
263 	init_cmds();
264 	init_poll();
265 	init_charset();
266 	init_line();
267 	init_cmdhist();
268 	init_option();
269 	init_search();
270 
271 	/*
272 	 * If the name of the executable program is "more",
273 	 * act like LESS_IS_MORE is set.
274 	 */
275 	if (strcmp(last_component(progname), "more") == 0 &&
276 			isnullenv(lgetenv("LESS_IS_MORE"))) {
277 		less_is_more = TRUE;
278 		scan_option("-fG", FALSE);
279 	}
280 
281 	init_prompt();
282 
283 	init_unsupport();
284 	s = lgetenv(less_is_more ? "MORE" : "LESS");
285 	if (s != NULL)
286 		scan_option(s, TRUE);
287 
288 #define isoptstring(s)  less_is_more ? (((s)[0] == '-') && (s)[1] != '\0') : \
289 			(((s)[0] == '-' || (s)[0] == '+') && (s)[1] != '\0')
290 	xbuf_init(&xfiles);
291 	/* Don't use lgetenv because POSIXLY_CORRECT is considered to be true
292 	 * if it is set to an empty string. */
293 	posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
294 	for (i = 0;  i < argc;  i++)
295 	{
296 		if (strcmp(argv[i], "--") == 0)
297 			end_opts = TRUE;
298 		else if (!end_opts && (isoptstring(argv[i]) || isoptpending()))
299 			scan_option(argv[i], FALSE);
300 		else
301 		{
302 			if (posixly_correct)
303 				end_opts = TRUE;
304 			xbuf_add_data(&xfiles, &i, sizeof(i));
305 		}
306 	}
307 #undef isoptstring
308 
309 	if (isoptpending())
310 	{
311 		/*
312 		 * Last command line option was a flag requiring a
313 		 * following string, but there was no following string.
314 		 */
315 		nopendopt();
316 		quit(QUIT_ERROR);
317 	}
318 
319 	if (less_is_more)
320 		no_init = TRUE;
321 
322 	if (is_tty)
323 		get_term();
324 	expand_cmd_tables();
325 
326 #if EDITOR
327 	editor = lgetenv("VISUAL");
328 	if (isnullenv(editor))
329 	{
330 		editor = lgetenv("EDITOR");
331 		if (isnullenv(editor))
332 			editor = EDIT_PGM;
333 	}
334 	editproto = lgetenv("LESSEDIT");
335 	if (isnullenv(editproto))
336 		editproto = "%E ?lm+%lm. %g";
337 #endif
338 
339 	/*
340 	 * Call get_ifile with all the command line filenames
341 	 * to "register" them with the ifile system.
342 	 */
343 	ifile = NULL_IFILE;
344 	if (dohelp)
345 		ifile = get_ifile(FAKE_HELPFILE, ifile);
346 	files = (constant int *) xfiles.data;
347 	num_files = xfiles.end / sizeof(int);
348 	for (f = 0;  f < num_files;  f++)
349 	{
350 #if (MSDOS_COMPILER && MSDOS_COMPILER != DJGPPC)
351 		/*
352 		 * Because the "shell" doesn't expand filename patterns,
353 		 * treat each argument as a filename pattern rather than
354 		 * a single filename.
355 		 * Expand the pattern and iterate over the expanded list.
356 		 */
357 		struct textlist tlist;
358 		constant char *filename;
359 		char *gfilename;
360 		char *qfilename;
361 
362 		gfilename = lglob(argv[files[f]]);
363 		init_textlist(&tlist, gfilename);
364 		filename = NULL;
365 		while ((filename = forw_textlist(&tlist, filename)) != NULL)
366 		{
367 			qfilename = shell_unquote(filename);
368 			(void) get_ifile(qfilename, ifile);
369 			free(qfilename);
370 			ifile = prev_ifile(NULL_IFILE);
371 		}
372 		free(gfilename);
373 #else
374 		(void) get_ifile(argv[files[f]], ifile);
375 		ifile = prev_ifile(NULL_IFILE);
376 #endif
377 	}
378 	xbuf_deinit(&xfiles);
379 
380 	/*
381 	 * Set up terminal, etc.
382 	 */
383 	if (!is_tty)
384 	{
385 		/*
386 		 * Output is not a tty.
387 		 * Just copy the input file(s) to output.
388 		 */
389 		SET_BINARY(1);
390 
391 		if (edit_first())
392 			quit(QUIT_ERROR);
393 
394 		set_output(1, TRUE); /* write to stdout */
395 		do {
396 			cat_file();
397 		} while (edit_next(1) == 0);
398 
399 		quit(QUIT_OK);
400 	}
401 
402 	if (missing_cap && !know_dumb && !less_is_more)
403 		error(LM(terminal_is_not_fully_functional), NULL_PARG);
404 	open_getchr();
405 	init_signals(TRUE);
406 #if HAVE_TIME
407 	less_start_time = get_time();
408 #endif
409 
410 	/*
411 	 * Select the first file to examine.
412 	 */
413 #if TAGS
414 	if (tagoption != NULL || strcmp(tags, "-") == 0)
415 	{
416 		/*
417 		 * A -t option was given.
418 		 * Verify that no filenames were also given.
419 		 * Edit the file selected by the "tags" search,
420 		 * and search for the proper line in the file.
421 		 */
422 		if (nifile() > 0)
423 		{
424 			error(LM(No_filenames_allowed_with_t_option), NULL_PARG);
425 			quit(QUIT_ERROR);
426 		}
427 		findtag(tagoption);
428 		if (edit_tagfile())  /* Edit file which contains the tag */
429 			quit(QUIT_ERROR);
430 		/*
431 		 * Search for the line which contains the tag.
432 		 * Set up initial_scrpos so we display that line.
433 		 */
434 		initial_scrpos.pos = tagsearch();
435 		if (initial_scrpos.pos == NULL_POSITION)
436 			quit(QUIT_ERROR);
437 		initial_scrpos.ln = jump_sline;
438 	} else
439 #endif
440 	{
441 		if (edit_first())
442 			quit(QUIT_ERROR);
443 		/*
444 		 * See if file fits on one screen to decide whether
445 		 * to send terminal init. But don't need this
446 		 * if -X (no_init) overrides this (see term_init()).
447 		 */
448 		if (quit_if_one_screen)
449 		{
450 			if (nifile() > 1) /* If more than one file, -F cannot be used */
451 				quit_if_one_screen = FALSE;
452 			else if (!no_init)
453 				one_screen = get_one_screen();
454 		}
455 	}
456 	if (init_header != NULL)
457 	{
458 		opt_header(TOGGLE, init_header);
459 		free(init_header);
460 		init_header = NULL;
461 	}
462 
463 	if (errmsgs > 0)
464 	{
465 		/*
466 		 * We displayed some messages on error output
467 		 * (file descriptor 2; see flush()).
468 		 * Before erasing the screen contents, wait for a keystroke.
469 		 */
470 		PARG parg;
471 		parg.p_string = LM(Press_RETURN_to_continue);
472 		less_printf("%s", &parg);
473 		get_return();
474 		putchr('\n');
475 	}
476 	set_output(1, FALSE);
477 #if MSDOS_COMPILER
478 	raw_mode(TRUE);
479 	term_init();
480 #endif
481 	commands();
482 	quit(QUIT_OK);
483 	/*NOTREACHED*/
484 	return (0);
485 }
486 
487 /*
488  * Copy a string to a "safe" place
489  * (that is, to a buffer allocated by calloc).
490  */
saven(constant char * s,size_t n)491 public char * saven(constant char *s, size_t n)
492 {
493 	char *p = (char *) ecalloc(n+1, sizeof(char));
494 	strncpy(p, s, n);
495 	p[n] = '\0';
496 	return (p);
497 }
498 
save(constant char * s)499 public char * save(constant char *s)
500 {
501 	return saven(s, strlen(s));
502 }
503 
out_of_memory(void)504 public void out_of_memory(void)
505 {
506 	error(LM(Cannot_allocate_memory), NULL_PARG);
507 	quit(QUIT_ERROR);
508 }
509 
510 /*
511  * Allocate memory.
512  * Like calloc(), but never returns an error (NULL).
513  */
ecalloc(size_t count,size_t size)514 public void * ecalloc(size_t count, size_t size)
515 {
516 	void * p;
517 
518 	p = (void *) calloc(count, size);
519 	if (p == NULL)
520 		out_of_memory();
521 	return p;
522 }
523 
524 /*
525  * Skip leading spaces in a string.
526  */
skipsp(char * s)527 public char * skipsp(char *s)
528 {
529 	while (*s == ' ' || *s == '\t')
530 		s++;
531 	return (s);
532 }
533 
534 /* {{ There must be a better way. }} */
skipspc(constant char * s)535 public constant char * skipspc(constant char *s)
536 {
537 	while (*s == ' ' || *s == '\t')
538 		s++;
539 	return (s);
540 }
541 
542 /*
543  * See how many characters of two strings are identical.
544  * If uppercase is true, the first string must begin with an uppercase
545  * character; the remainder of the first string may be either case.
546  */
sprefix(constant char * ps,constant char * s,int uppercase)547 public size_t sprefix(constant char *ps, constant char *s, int uppercase)
548 {
549 	char c;
550 	char sc;
551 	size_t len = 0;
552 
553 	for ( ;  *s != '\0';  s++, ps++)
554 	{
555 		c = *ps;
556 		if (uppercase)
557 		{
558 			if (len == 0 && ASCII_IS_LOWER(c))
559 				return (0);
560 			if (ASCII_IS_UPPER(c))
561 				c = ASCII_TO_LOWER(c);
562 		}
563 		sc = *s;
564 		if (len > 0 && ASCII_IS_UPPER(sc))
565 			sc = ASCII_TO_LOWER(sc);
566 		if (c != sc)
567 			break;
568 		len++;
569 	}
570 	return (len);
571 }
572 
573 /*
574  * Exit the program.
575  */
quit(int status)576 public void quit(int status)
577 {
578 	static int save_status;
579 
580 	/*
581 	 * Put cursor at bottom left corner, clear the line,
582 	 * reset the terminal modes, and exit.
583 	 */
584 	if (status < 0)
585 		status = save_status;
586 	else
587 		save_status = status;
588 	quitting = TRUE;
589 	check_altpipe_error();
590 	if (interactive())
591 		clear_bot();
592 	term_deinit();
593 	flush();
594 	if (redraw_on_quit && term_addrs)
595 	{
596 		/*
597 		 * The last file text displayed might have been on an
598 		 * alternate screen, which now (since deinit) cannot be seen.
599 		 * redraw_on_quit tells us to redraw it on the main screen.
600 		 */
601 		first_time = TRUE; /* Don't print "skipping" or tildes */
602 		repaint();
603 		flush();
604 	}
605 	edit((char*)NULL);
606 	save_cmdhist();
607 	raw_mode(FALSE);
608 #if MSDOS_COMPILER && MSDOS_COMPILER != DJGPPC
609 	/*
610 	 * If we don't close 2, we get some garbage from
611 	 * 2's buffer when it flushes automatically.
612 	 * I cannot track this one down  RB
613 	 * The same bug shows up if we use ^C^C to abort.
614 	 */
615 	close(2);
616 #endif
617 #ifdef WIN32
618 	SetConsoleTitleW(consoleTitle);
619 #endif
620 	close_getchr();
621 	exit(status);
622 }
623 
624 /*
625  * Are all the features in the features mask allowed by security?
626  */
secure_allow(unsigned int features)627 public lbool secure_allow(unsigned int features)
628 {
629 	return ((secure_allow_features & features) == features);
630 }
631