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