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 public constant char *progname;
40 public lbool quitting = FALSE;
41 public lbool dohelp = FALSE;
42 public char * init_header = NULL;
43 public char * no_config = NULL;
44 static 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 int 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("WARNING: 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 #endif
195 }
196
197 /*
198 * Entry point.
199 */
main(int argc,constant char * argv[])200 int main(int argc, constant char *argv[])
201 {
202 IFILE ifile;
203 constant char *s;
204 int i;
205 struct xbuffer xfiles;
206 constant int *files;
207 size_t num_files;
208 size_t f;
209 lbool end_opts = FALSE;
210 lbool posixly_correct;
211
212 no_config = getenv("LESSNOCONFIG");
213
214 #if MSDOS_COMPILER==WIN32C && (defined(__MINGW32__) || defined(_MSC_VER))
215 if (GetACP() != CP_UTF8) /* not using a UTF-8 manifest */
216 try_utf8_locale(&argc, &argv);
217 #endif
218
219 #ifdef __EMX__
220 _response(&argc, &argv);
221 _wildcard(&argc, &argv);
222 #endif
223
224 progname = *argv++;
225 argc--;
226 init_secure();
227
228 #ifdef WIN32
229 if (getenv("HOME") == NULL)
230 {
231 /*
232 * If there is no HOME environment variable,
233 * try the concatenation of HOMEDRIVE + HOMEPATH.
234 */
235 char *drive = getenv("HOMEDRIVE");
236 char *path = getenv("HOMEPATH");
237 if (drive != NULL && path != NULL)
238 {
239 char *env = (char *) ecalloc(strlen(drive) +
240 strlen(path) + 6, sizeof(char));
241 strcpy(env, "HOME=");
242 strcat(env, drive);
243 strcat(env, path);
244 putenv(env);
245 }
246 }
247 /* on failure, consoleTitle is already a valid empty string */
248 GetConsoleTitleW(consoleTitle, countof(consoleTitle));
249 #endif /* WIN32 */
250
251 /*
252 * Process command line arguments and LESS environment arguments.
253 * Command line arguments override environment arguments.
254 */
255 is_tty = (isatty(1) != 0);
256 init_mark();
257 init_cmds();
258 init_poll();
259 init_charset();
260 init_line();
261 init_cmdhist();
262 init_option();
263 init_search();
264
265 /*
266 * If the name of the executable program is "more",
267 * act like LESS_IS_MORE is set.
268 */
269 if (strcmp(last_component(progname), "more") == 0 &&
270 isnullenv(lgetenv("LESS_IS_MORE"))) {
271 less_is_more = 1;
272 scan_option("-fG", FALSE);
273 }
274
275 init_prompt();
276
277 init_unsupport();
278 s = lgetenv(less_is_more ? "MORE" : "LESS");
279 if (s != NULL)
280 scan_option(s, TRUE);
281
282 #define isoptstring(s) less_is_more ? (((s)[0] == '-') && (s)[1] != '\0') : \
283 (((s)[0] == '-' || (s)[0] == '+') && (s)[1] != '\0')
284 xbuf_init(&xfiles);
285 posixly_correct = (lgetenv("POSIXLY_CORRECT") != NULL);
286 for (i = 0; i < argc; i++)
287 {
288 if (strcmp(argv[i], "--") == 0)
289 end_opts = TRUE;
290 else if (!end_opts && (isoptstring(argv[i]) || isoptpending()))
291 scan_option(argv[i], FALSE);
292 else
293 {
294 if (posixly_correct)
295 end_opts = TRUE;
296 xbuf_add_data(&xfiles, &i, sizeof(i));
297 }
298 }
299 #undef isoptstring
300
301 if (isoptpending())
302 {
303 /*
304 * Last command line option was a flag requiring a
305 * following string, but there was no following string.
306 */
307 nopendopt();
308 quit(QUIT_OK);
309 }
310
311 if (less_is_more)
312 no_init = TRUE;
313
314 if (is_tty)
315 get_term();
316 expand_cmd_tables();
317
318 #if EDITOR
319 editor = lgetenv("VISUAL");
320 if (isnullenv(editor))
321 {
322 editor = lgetenv("EDITOR");
323 if (isnullenv(editor))
324 editor = EDIT_PGM;
325 }
326 editproto = lgetenv("LESSEDIT");
327 if (isnullenv(editproto))
328 editproto = "%E ?lm+%lm. %g";
329 #endif
330
331 /*
332 * Call get_ifile with all the command line filenames
333 * to "register" them with the ifile system.
334 */
335 ifile = NULL_IFILE;
336 if (dohelp)
337 ifile = get_ifile(FAKE_HELPFILE, ifile);
338 files = (constant int *) xfiles.data;
339 num_files = xfiles.end / sizeof(int);
340 for (f = 0; f < num_files; f++)
341 {
342 #if (MSDOS_COMPILER && MSDOS_COMPILER != DJGPPC)
343 /*
344 * Because the "shell" doesn't expand filename patterns,
345 * treat each argument as a filename pattern rather than
346 * a single filename.
347 * Expand the pattern and iterate over the expanded list.
348 */
349 struct textlist tlist;
350 constant char *filename;
351 char *gfilename;
352 char *qfilename;
353
354 gfilename = lglob(argv[files[f]]);
355 init_textlist(&tlist, gfilename);
356 filename = NULL;
357 while ((filename = forw_textlist(&tlist, filename)) != NULL)
358 {
359 qfilename = shell_unquote(filename);
360 (void) get_ifile(qfilename, ifile);
361 free(qfilename);
362 ifile = prev_ifile(NULL_IFILE);
363 }
364 free(gfilename);
365 #else
366 (void) get_ifile(argv[files[f]], ifile);
367 ifile = prev_ifile(NULL_IFILE);
368 #endif
369 }
370 xbuf_deinit(&xfiles);
371
372 /*
373 * Set up terminal, etc.
374 */
375 if (!is_tty)
376 {
377 /*
378 * Output is not a tty.
379 * Just copy the input file(s) to output.
380 */
381 SET_BINARY(1);
382 if (edit_first() == 0)
383 {
384 set_output(1, TRUE); /* write to stdout */
385 do {
386 cat_file();
387 } while (edit_next(1) == 0);
388 }
389 quit(QUIT_OK);
390 }
391
392 if (missing_cap && !know_dumb && !less_is_more)
393 error("WARNING: terminal is not fully functional", NULL_PARG);
394 open_getchr();
395 raw_mode(1);
396 init_signals(1);
397 #if HAVE_TIME
398 less_start_time = get_time();
399 #endif
400
401 /*
402 * Select the first file to examine.
403 */
404 #if TAGS
405 if (tagoption != NULL || strcmp(tags, "-") == 0)
406 {
407 /*
408 * A -t option was given.
409 * Verify that no filenames were also given.
410 * Edit the file selected by the "tags" search,
411 * and search for the proper line in the file.
412 */
413 if (nifile() > 0)
414 {
415 error("No filenames allowed with -t option", NULL_PARG);
416 quit(QUIT_ERROR);
417 }
418 findtag(tagoption);
419 if (edit_tagfile()) /* Edit file which contains the tag */
420 quit(QUIT_ERROR);
421 /*
422 * Search for the line which contains the tag.
423 * Set up initial_scrpos so we display that line.
424 */
425 initial_scrpos.pos = tagsearch();
426 if (initial_scrpos.pos == NULL_POSITION)
427 quit(QUIT_ERROR);
428 initial_scrpos.ln = jump_sline;
429 } else
430 #endif
431 {
432 if (edit_first())
433 quit(QUIT_ERROR);
434 /*
435 * See if file fits on one screen to decide whether
436 * to send terminal init. But don't need this
437 * if -X (no_init) overrides this (see term_init()).
438 */
439 if (quit_if_one_screen)
440 {
441 if (nifile() > 1) /* If more than one file, -F cannot be used */
442 quit_if_one_screen = FALSE;
443 else if (!no_init)
444 one_screen = get_one_screen();
445 }
446 }
447 if (init_header != NULL)
448 {
449 opt_header(TOGGLE, init_header);
450 free(init_header);
451 init_header = NULL;
452 }
453
454 if (errmsgs > 0)
455 {
456 /*
457 * We displayed some messages on error output
458 * (file descriptor 2; see flush()).
459 * Before erasing the screen contents, wait for a keystroke.
460 */
461 less_printf("Press RETURN to continue ", NULL_PARG);
462 get_return();
463 putchr('\n');
464 }
465 set_output(1, FALSE);
466 #if MSDOS_COMPILER
467 term_init();
468 #endif
469 commands();
470 quit(QUIT_OK);
471 /*NOTREACHED*/
472 return (0);
473 }
474
475 /*
476 * Copy a string to a "safe" place
477 * (that is, to a buffer allocated by calloc).
478 */
saven(constant char * s,size_t n)479 public char * saven(constant char *s, size_t n)
480 {
481 char *p = (char *) ecalloc(n+1, sizeof(char));
482 strncpy(p, s, n);
483 p[n] = '\0';
484 return (p);
485 }
486
save(constant char * s)487 public char * save(constant char *s)
488 {
489 return saven(s, strlen(s));
490 }
491
out_of_memory(void)492 public void out_of_memory(void)
493 {
494 error("Cannot allocate memory", NULL_PARG);
495 quit(QUIT_ERROR);
496 }
497
498 /*
499 * Allocate memory.
500 * Like calloc(), but never returns an error (NULL).
501 */
ecalloc(size_t count,size_t size)502 public void * ecalloc(size_t count, size_t size)
503 {
504 void * p;
505
506 p = (void *) calloc(count, size);
507 if (p == NULL)
508 out_of_memory();
509 return p;
510 }
511
512 /*
513 * Skip leading spaces in a string.
514 */
skipsp(char * s)515 public char * skipsp(char *s)
516 {
517 while (*s == ' ' || *s == '\t')
518 s++;
519 return (s);
520 }
521
522 /* {{ There must be a better way. }} */
skipspc(constant char * s)523 public constant char * skipspc(constant char *s)
524 {
525 while (*s == ' ' || *s == '\t')
526 s++;
527 return (s);
528 }
529
530 /*
531 * See how many characters of two strings are identical.
532 * If uppercase is true, the first string must begin with an uppercase
533 * character; the remainder of the first string may be either case.
534 */
sprefix(constant char * ps,constant char * s,int uppercase)535 public size_t sprefix(constant char *ps, constant char *s, int uppercase)
536 {
537 char c;
538 char sc;
539 size_t len = 0;
540
541 for ( ; *s != '\0'; s++, ps++)
542 {
543 c = *ps;
544 if (uppercase)
545 {
546 if (len == 0 && ASCII_IS_LOWER(c))
547 return (0);
548 if (ASCII_IS_UPPER(c))
549 c = ASCII_TO_LOWER(c);
550 }
551 sc = *s;
552 if (len > 0 && ASCII_IS_UPPER(sc))
553 sc = ASCII_TO_LOWER(sc);
554 if (c != sc)
555 break;
556 len++;
557 }
558 return (len);
559 }
560
561 /*
562 * Exit the program.
563 */
quit(int status)564 public void quit(int status)
565 {
566 static int save_status;
567
568 /*
569 * Put cursor at bottom left corner, clear the line,
570 * reset the terminal modes, and exit.
571 */
572 if (status < 0)
573 status = save_status;
574 else
575 save_status = status;
576 quitting = TRUE;
577 check_altpipe_error();
578 if (interactive())
579 clear_bot();
580 term_deinit();
581 flush();
582 if (redraw_on_quit && term_addrs)
583 {
584 /*
585 * The last file text displayed might have been on an
586 * alternate screen, which now (since deinit) cannot be seen.
587 * redraw_on_quit tells us to redraw it on the main screen.
588 */
589 first_time = TRUE; /* Don't print "skipping" or tildes */
590 repaint();
591 flush();
592 }
593 edit((char*)NULL);
594 save_cmdhist();
595 raw_mode(0);
596 #if MSDOS_COMPILER && MSDOS_COMPILER != DJGPPC
597 /*
598 * If we don't close 2, we get some garbage from
599 * 2's buffer when it flushes automatically.
600 * I cannot track this one down RB
601 * The same bug shows up if we use ^C^C to abort.
602 */
603 close(2);
604 #endif
605 #ifdef WIN32
606 SetConsoleTitleW(consoleTitle);
607 #endif
608 close_getchr();
609 exit(status);
610 }
611
612 /*
613 * Are all the features in the features mask allowed by security?
614 */
secure_allow(int features)615 public int secure_allow(int features)
616 {
617 return ((secure_allow_features & features) == features);
618 }
619