* extfs/trpm: Fix quoting issues.
[midnight-commander.git] / src / user.c
blob0220ee255faeb0c56b77572152aeb544a612bc7a
1 /* User Menu implementation
2 Copyright (C) 1994 Miguel de Icaza, Janne Kukonlehto
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 #include <config.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <ctype.h>
22 #include <errno.h>
24 #include "global.h"
25 #include "tty.h"
26 #include "color.h"
27 #include "dir.h"
28 #include "panel.h"
29 #include "main.h"
30 #include "subshell.h" /* for subshell_pty */
31 #include "user.h"
32 #include "layout.h"
33 #include "execute.h"
34 #include "setup.h"
36 #include "../edit/edit.h" /* BLOCK_FILE */
37 #include "../edit/edit-widget.h" /* WEdit */
39 /* For the simple listbox manager */
40 #include "dialog.h"
41 #include "widget.h"
42 #include "wtools.h"
44 #include "view.h" /* for default_* externs */
46 #define MAX_ENTRIES 16
47 #define MAX_ENTRY_LEN 60
49 static int debug_flag = 0;
50 static int debug_error = 0;
51 static char *menu = NULL;
53 /* Formats defined:
54 %% The % character
55 %f The current file (if non-local vfs, file will be copied locally and
56 %f will be full path to it).
57 %p The current file
58 %d The current working directory
59 %s "Selected files"; the tagged files if any, otherwise the current file
60 %t Tagged files
61 %u Tagged files (and they are untagged on return from expand_format)
62 %view Runs the commands and pipes standard output to the view command.
63 If %view is immediately followed by '{', recognize keywords
64 ascii, hex, nroff and unform
66 If the format letter is in uppercase, it refers to the other panel.
68 With a number followed the % character you can turn quoting on (default)
69 and off. For example:
70 %f quote expanded macro
71 %1f ditto
72 %0f don't quote expanded macro
74 expand_format returns a memory block that must be free()d.
77 /* Returns how many characters we should advance if %view was found */
78 int check_format_view (const char *p)
80 const char *q = p;
81 if (!strncmp (p, "view", 4)) {
82 q += 4;
83 if (*q == '{'){
84 for (q++;*q && *q != '}';q++) {
85 if (!strncmp (q, "ascii", 5)) {
86 default_hex_mode = 0;
87 q += 4;
88 } else if (!strncmp (q, "hex", 3)) {
89 default_hex_mode = 1;
90 q += 2;
91 } else if (!strncmp (q, "nroff", 5)) {
92 default_nroff_flag = 1;
93 q += 4;
94 } else if (!strncmp (q, "unform", 6)) {
95 default_nroff_flag = 0;
96 q += 5;
99 if (*q == '}')
100 q++;
102 return q - p;
104 return 0;
107 int check_format_cd (const char *p)
109 return (strncmp (p, "cd", 2)) ? 0 : 3;
112 /* Check if p has a "^var\{var-name\}" */
113 /* Returns the number of skipped characters (zero on not found) */
114 /* V will be set to the expanded variable name */
115 int check_format_var (const char *p, char **v)
117 const char *q = p;
118 char *var_name;
119 const char *value;
120 const char *dots = 0;
122 *v = 0;
123 if (!strncmp (p, "var{", 4)){
124 for (q += 4; *q && *q != '}'; q++){
125 if (*q == ':')
126 dots = q+1;
128 if (!*q)
129 return 0;
131 if (!dots || dots == q+5){
132 message (1,
133 _(" Format error on file Extensions File "),
134 !dots ? _(" The %%var macro has no default ")
135 : _(" The %%var macro has no variable "));
136 return 0;
139 /* Copy the variable name */
140 var_name = g_strndup (p + 4, dots-2 - (p+3));
142 value = getenv (var_name);
143 g_free (var_name);
144 if (value){
145 *v = g_strdup (value);
146 return q-p;
148 var_name = g_strndup (dots, q - dots);
149 *v = var_name;
150 return q-p;
152 return 0;
155 /* strip file's extension */
156 static char *
157 strip_ext(char *ss)
159 register char *s = ss;
160 char *e = NULL;
161 while(*s) {
162 if(*s == '.') e = s;
163 if(*s == PATH_SEP && e) e=NULL; /* '.' in *directory* name */
164 s++;
166 if(e) *e = 0;
167 return ss;
170 char *
171 expand_format (struct WEdit *edit_widget, char c, int quote)
173 WPanel *panel;
174 char *(*quote_func) (const char *, int);
175 char *fname;
177 if (c == '%')
178 return g_strdup ("%");
180 if (islower ((unsigned) c))
181 panel = current_panel;
182 else {
183 if (get_other_type () != view_listing)
184 return g_strdup ("");
185 panel = other_panel;
187 if (!panel)
188 panel = current_panel;
190 if (quote)
191 quote_func = name_quote;
192 else
193 quote_func = fake_name_quote;
195 c = tolower (c);
196 fname = panel->dir.list[panel->selected].fname;
198 switch (c) {
199 case 'f':
200 case 'p':
201 return (*quote_func) (fname, 0);
202 case 'x':
203 return (*quote_func) (extension (fname), 0);
204 case 'd':
205 return (*quote_func) (panel->cwd, 0);
206 case 'i': /* indent equal number cursor position in line */
207 if (edit_widget)
208 return g_strnfill (edit_widget->curs_col, ' ');
209 break;
210 case 'y': /* syntax type */
211 if (edit_widget && edit_widget->syntax_type)
212 return g_strdup (edit_widget->syntax_type);
213 break;
214 case 'k': /* block file name */
215 case 'b': /* block file name / strip extension */ {
216 if (edit_widget) {
217 char *file = g_strconcat (home_dir, BLOCK_FILE, (char *) NULL);
218 fname = (*quote_func) (file, 0);
219 g_free (file);
220 return fname;
221 } else if (c == 'b') {
222 return strip_ext ((*quote_func) (fname, 0));
224 break;
226 case 'n': /* strip extension in editor */
227 if (edit_widget)
228 return strip_ext ((*quote_func) (fname, 0));
229 break;
230 case 'm': /* menu file name */
231 if (menu)
232 return (*quote_func) (menu, 0);
233 break;
234 case 's':
235 if (!panel->marked)
236 return (*quote_func) (fname, 0);
238 /* Fall through */
240 case 't':
241 case 'u':
243 int length = 2, i;
244 char *block, *tmp;
246 for (i = 0; i < panel->count; i++)
247 if (panel->dir.list[i].f.marked)
248 length += strlen (panel->dir.list[i].fname) + 1; /* for space */
250 block = g_malloc (length * 2 + 1);
251 *block = 0;
252 for (i = 0; i < panel->count; i++)
253 if (panel->dir.list[i].f.marked) {
254 strcat (block, tmp =
255 (*quote_func) (panel->dir.list[i].fname, 0));
256 g_free (tmp);
257 strcat (block, " ");
258 if (c == 'u')
259 do_file_mark (panel, i, 0);
261 return block;
262 } /* sub case block */
263 } /* switch */
264 return g_strdup ("%");
268 * Check for the "shell_patterns" directive. If it's found and valid,
269 * interpret it and move the pointer past the directive. Return the
270 * current pointer.
272 static char *
273 check_patterns (char *p)
275 static const char def_name[] = "shell_patterns=";
276 char *p0 = p;
278 if (strncmp (p, def_name, sizeof (def_name) - 1) != 0)
279 return p0;
281 p += sizeof (def_name) - 1;
282 if (*p == '1')
283 easy_patterns = 1;
284 else if (*p == '0')
285 easy_patterns = 0;
286 else
287 return p0;
289 /* Skip spaces */
290 p++;
291 while (*p == '\n' || *p == '\t' || *p == ' ')
292 p++;
293 return p;
296 /* Copies a whitespace separated argument from p to arg. Returns the
297 point after argument. */
298 static char *extract_arg (char *p, char *arg, int size)
300 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
301 p++;
302 /* support quote space .mnu */
303 while (size > 1 && *p && (*p != ' ' || *(p-1) == '\\') && *p != '\t' && *p != '\n') {
304 *arg++ = *p++;
305 size--;
307 *arg = 0;
308 if (!*p || *p == '\n')
309 p --;
310 return p;
313 /* Tests whether the selected file in the panel is of any of the types
314 specified in argument. */
315 static int test_type (WPanel *panel, char *arg)
317 int result = 0; /* False by default */
318 int st_mode = panel->dir.list [panel->selected].st.st_mode;
320 for (;*arg != 0; arg++){
321 switch (*arg){
322 case 'n': /* Not a directory */
323 result |= !S_ISDIR (st_mode);
324 break;
325 case 'r': /* Regular file */
326 result |= S_ISREG (st_mode);
327 break;
328 case 'd': /* Directory */
329 result |= S_ISDIR (st_mode);
330 break;
331 case 'l': /* Link */
332 result |= S_ISLNK (st_mode);
333 break;
334 case 'c': /* Character special */
335 result |= S_ISCHR (st_mode);
336 break;
337 case 'b': /* Block special */
338 result |= S_ISBLK (st_mode);
339 break;
340 case 'f': /* Fifo (named pipe) */
341 result |= S_ISFIFO (st_mode);
342 break;
343 case 's': /* Socket */
344 result |= S_ISSOCK (st_mode);
345 break;
346 case 'x': /* Executable */
347 result |= (st_mode & 0111) ? 1 : 0;
348 break;
349 case 't':
350 result |= panel->marked ? 1 : 0;
351 break;
352 default:
353 debug_error = 1;
354 break;
357 return result;
360 /* Calculates the truth value of the next condition starting from
361 p. Returns the point after condition. */
362 static char *test_condition (WEdit *edit_widget, char *p, int *condition)
364 WPanel *panel;
365 char arg [256];
367 /* Handle one condition */
368 for (;*p != '\n' && *p != '&' && *p != '|'; p++){
369 /* support quote space .mnu */
370 if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
371 continue;
372 if (*p >= 'a')
373 panel = current_panel;
374 else {
375 if (get_other_type () == view_listing)
376 panel = other_panel;
377 else
378 panel = NULL;
380 *p |= 0x20;
382 switch (*p++){
383 case '!':
384 p = test_condition (edit_widget, p, condition);
385 *condition = ! *condition;
386 p--;
387 break;
388 case 'f': /* file name pattern */
389 p = extract_arg (p, arg, sizeof (arg));
390 *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
391 break;
392 case 'y': /* syntax pattern */
393 if (edit_widget && edit_widget->syntax_type) {
394 p = extract_arg (p, arg, sizeof (arg));
395 *condition = panel &&
396 regexp_match (arg, edit_widget->syntax_type, match_normal);
398 break;
399 case 'd':
400 p = extract_arg (p, arg, sizeof (arg));
401 *condition = panel && regexp_match (arg, panel->cwd, match_file);
402 break;
403 case 't':
404 p = extract_arg (p, arg, sizeof (arg));
405 *condition = panel && test_type (panel, arg);
406 break;
407 case 'x': /* executable */
409 struct stat status;
411 p = extract_arg (p, arg, sizeof (arg));
412 if (stat (arg, &status) == 0)
413 *condition = is_exe (status.st_mode);
414 else
415 *condition = 0;
416 break;
418 default:
419 debug_error = 1;
420 break;
421 } /* switch */
423 } /* while */
424 return p;
427 /* General purpose condition debug output handler */
428 static void
429 debug_out (char *start, char *end, int cond)
431 static char *msg;
432 int len;
434 if (start == NULL && end == NULL){
435 /* Show output */
436 if (debug_flag && msg) {
437 len = strlen (msg);
438 if (len)
439 msg [len - 1] = 0;
440 message (0, _(" Debug "), "%s", msg);
443 debug_flag = 0;
444 g_free (msg);
445 msg = NULL;
446 } else {
447 const char *type;
448 char *p;
450 /* Save debug info for later output */
451 if (!debug_flag)
452 return;
453 /* Save the result of the condition */
454 if (debug_error){
455 type = _(" ERROR: ");
456 debug_error = 0;
458 else if (cond)
459 type = _(" True: ");
460 else
461 type = _(" False: ");
462 /* This is for debugging, don't need to be super efficient. */
463 if (end == NULL)
464 p = g_strdup_printf ("%s%s%c \n", msg ? msg : "", type, *start);
465 else
466 p = g_strdup_printf ("%s%s%.*s \n", msg ? msg : "", type,
467 (int) (end - start), start);
468 g_free (msg);
469 msg = p;
473 /* Calculates the truth value of one lineful of conditions. Returns
474 the point just before the end of line. */
475 static char *test_line (WEdit *edit_widget, char *p, int *result)
477 int condition;
478 char operator;
479 char *debug_start, *debug_end;
481 /* Repeat till end of line */
482 while (*p && *p != '\n') {
483 /* support quote space .mnu */
484 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
485 p++;
486 if (!*p || *p == '\n')
487 break;
488 operator = *p++;
489 if (*p == '?'){
490 debug_flag = 1;
491 p++;
493 /* support quote space .mnu */
494 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
495 p++;
496 if (!*p || *p == '\n')
497 break;
498 condition = 1; /* True by default */
500 debug_start = p;
501 p = test_condition (edit_widget, p, &condition);
502 debug_end = p;
503 /* Add one debug statement */
504 debug_out (debug_start, debug_end, condition);
506 switch (operator){
507 case '+':
508 case '=':
509 /* Assignment */
510 *result = condition;
511 break;
512 case '&': /* Logical and */
513 *result &= condition;
514 break;
515 case '|': /* Logical or */
516 *result |= condition;
517 break;
518 default:
519 debug_error = 1;
520 break;
521 } /* switch */
522 /* Add one debug statement */
523 debug_out (&operator, NULL, *result);
525 } /* while (*p != '\n') */
526 /* Report debug message */
527 debug_out (NULL, NULL, 1);
529 if (!*p || *p == '\n')
530 p --;
531 return p;
534 /* FIXME: recode this routine on version 3.0, it could be cleaner */
535 static void
536 execute_menu_command (WEdit *edit_widget, const char *commands)
538 FILE *cmd_file;
539 int cmd_file_fd;
540 int expand_prefix_found = 0;
541 char *parameter = 0;
542 int do_quote = 0;
543 char prompt [80];
544 int col;
545 char *file_name;
546 int run_view = 0;
548 /* Skip menu entry title line */
549 commands = strchr (commands, '\n');
550 if (!commands){
551 return;
554 cmd_file_fd = mc_mkstemps (&file_name, "mcusr", SCRIPT_SUFFIX);
556 if (cmd_file_fd == -1){
557 message (1, MSG_ERROR, _(" Cannot create temporary command file \n %s "),
558 unix_error_string (errno));
559 return;
561 cmd_file = fdopen (cmd_file_fd, "w");
562 fputs ("#! /bin/sh\n", cmd_file);
563 commands++;
565 for (col = 0; *commands; commands++){
566 if (col == 0) {
567 if (*commands != ' ' && *commands != '\t')
568 break;
569 while (*commands == ' ' || *commands == '\t')
570 commands++;
571 if (*commands == 0)
572 break;
574 col++;
575 if (*commands == '\n')
576 col = 0;
577 if (parameter){
578 if (*commands == '}'){
579 char *tmp;
580 *parameter = 0;
581 parameter = input_dialog (_(" Parameter "), prompt, "");
582 if (!parameter || !*parameter){
583 /* User canceled */
584 fclose (cmd_file);
585 unlink (file_name);
586 g_free (file_name);
587 return;
589 if (do_quote) {
590 fputs (tmp = name_quote (parameter, 0), cmd_file);
591 g_free (tmp);
592 } else
593 fputs (parameter, cmd_file);
594 g_free (parameter);
595 parameter = 0;
596 } else {
597 if (parameter < &prompt [sizeof (prompt) - 1]) {
598 *parameter++ = *commands;
601 } else if (expand_prefix_found){
602 expand_prefix_found = 0;
603 if (isdigit ((unsigned)*commands)) {
604 do_quote = atoi (commands);
605 while (isdigit ((unsigned)*commands))
606 commands++;
608 if (*commands == '{')
609 parameter = prompt;
610 else{
611 char *text = expand_format (edit_widget, *commands, do_quote);
612 fputs (text, cmd_file);
613 g_free (text);
615 } else {
616 if (*commands == '%') {
617 int i = check_format_view (commands + 1);
618 if (i) {
619 commands += i;
620 run_view = 1;
621 } else {
622 do_quote = 1; /* Default: Quote expanded macro */
623 expand_prefix_found = 1;
625 } else
626 fputc (*commands, cmd_file);
629 fclose (cmd_file);
630 chmod (file_name, S_IRWXU);
631 if (run_view) {
632 run_view = 0;
633 view (file_name, 0, &run_view, 0);
634 } else {
635 shell_execute (file_name, 0);
637 unlink (file_name);
638 g_free (file_name);
642 ** Check owner of the menu file. Using menu file is allowed, if
643 ** owner of the menu is root or the actual user. In either case
644 ** file should not be group and word-writable.
646 ** Q. Should we apply this routine to system and home menu (and .ext files)?
648 static int
649 menu_file_own(char* path)
651 struct stat st;
653 if (stat (path, &st) == 0
654 && (!st.st_uid || (st.st_uid == geteuid ()))
655 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0)
657 return 1;
659 if (verbose)
661 message (0, _(" Warning -- ignoring file "),
662 _("File %s is not owned by root or you or is world writable.\n"
663 "Using it may compromise your security"),
664 path
667 return 0;
671 * If edit_widget is NULL then we are called from the mc menu,
672 * otherwise we are called from the mcedit menu.
674 void
675 user_menu_cmd (struct WEdit *edit_widget)
677 char *p;
678 char *data, **entries;
679 int max_cols, menu_lines, menu_limit;
680 int col, i, accept_entry = 1;
681 int selected, old_patterns;
682 Listbox *listbox;
684 if (!vfs_current_is_local ()){
685 message (1, MSG_ERROR,
686 _(" Cannot execute commands on non-local filesystems"));
687 return;
690 menu = g_strdup (edit_widget ? CEDIT_LOCAL_MENU : MC_LOCAL_MENU);
691 if (!exist_file (menu) || !menu_file_own (menu)){
692 g_free (menu);
693 menu = concat_dir_and_file \
694 (home_dir, edit_widget ? CEDIT_HOME_MENU : MC_HOME_MENU);
695 if (!exist_file (menu)){
696 g_free (menu);
697 menu = concat_dir_and_file \
698 (mc_home, edit_widget ? CEDIT_GLOBAL_MENU : MC_GLOBAL_MENU);
702 if ((data = load_file (menu)) == NULL){
703 message (1, MSG_ERROR, _(" Cannot open file %s \n %s "),
704 menu, unix_error_string (errno));
705 g_free (menu);
706 menu = NULL;
707 return;
710 max_cols = 0;
711 selected = 0;
712 menu_limit = 0;
713 entries = 0;
715 /* Parse the menu file */
716 old_patterns = easy_patterns;
717 p = check_patterns (data);
718 for (menu_lines = col = 0; *p; p++){
719 if (menu_lines >= menu_limit){
720 char ** new_entries;
722 menu_limit += MAX_ENTRIES;
723 new_entries = g_realloc (entries, sizeof (new_entries[0]) * menu_limit);
725 if (new_entries == 0)
726 break;
728 entries = new_entries;
729 new_entries += menu_limit;
730 while (--new_entries >= &entries[menu_lines])
731 *new_entries = 0;
733 if (col == 0 && !entries [menu_lines]){
734 if (*p == '#'){
735 /* A commented menu entry */
736 accept_entry = 1;
737 } else if (*p == '+'){
738 if (*(p+1) == '='){
739 /* Combined adding and default */
740 p = test_line (edit_widget, p + 1, &accept_entry);
741 if (selected == 0 && accept_entry)
742 selected = menu_lines;
743 } else {
744 /* A condition for adding the entry */
745 p = test_line (edit_widget, p, &accept_entry);
747 } else if (*p == '='){
748 if (*(p+1) == '+'){
749 /* Combined adding and default */
750 p = test_line (edit_widget, p + 1, &accept_entry);
751 if (selected == 0 && accept_entry)
752 selected = menu_lines;
753 } else {
754 /* A condition for making the entry default */
755 i = 1;
756 p = test_line (edit_widget, p, &i);
757 if (selected == 0 && i)
758 selected = menu_lines;
761 else if (*p != ' ' && *p != '\t' && is_printable (*p)) {
762 /* A menu entry title line */
763 if (accept_entry)
764 entries [menu_lines] = p;
765 else
766 accept_entry = 1;
769 if (*p == '\n'){
770 if (entries [menu_lines]){
771 menu_lines++;
772 accept_entry = 1;
774 max_cols = max (max_cols, col);
775 col = 0;
776 } else {
777 if (*p == '\t')
778 *p = ' ';
779 col++;
783 if (menu_lines == 0) {
784 message (1, MSG_ERROR, _(" No suitable entries found in %s "), menu);
785 } else {
787 max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);
789 /* Create listbox */
790 listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
791 "[Menu File Edit]");
792 /* insert all the items found */
793 for (i = 0; i < menu_lines; i++) {
794 p = entries [i];
795 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
796 extract_line (p, p + MAX_ENTRY_LEN), p
799 /* Select the default entry */
800 listbox_select_by_number (listbox->list, selected);
802 selected = run_listbox (listbox);
803 if (selected >= 0)
804 execute_menu_command (edit_widget, entries [selected]);
806 do_refresh ();
809 easy_patterns = old_patterns;
810 g_free (menu);
811 menu = NULL;
812 g_free (entries);
813 g_free (data);