1 /* general.c -- Stuff that is used by all files. */
3 /* Copyright (C) 1987-2004 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
12 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License along
18 with Bash; see the file COPYING. If not, write to the Free Software
19 Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
23 #include "bashtypes.h"
25 # include <sys/param.h>
27 #include "posixstat.h"
29 #if defined (HAVE_UNISTD_H)
36 #include "chartypes.h"
44 #include <tilde/tilde.h>
50 extern int expand_aliases;
51 extern int interrupt_immediately;
52 extern int interactive_comments;
53 extern int check_hashed_filenames;
54 extern int source_uses_path;
55 extern int source_searches_cwd;
57 static char *bash_special_tilde_expansions __P((char *));
58 static int unquoted_tilde_word __P((const char *));
59 static void initialize_group_array __P((void));
61 /* A standard error message to use when getcwd() returns NULL. */
62 char *bash_getcwd_errstr = N_("getcwd: cannot access parent directories");
64 /* Do whatever is necessary to initialize `Posix mode'. */
69 /* Things that should be turned on when posix mode is enabled. */
72 interactive_comments = source_uses_path = expand_aliases = 1;
75 /* Things that should be turned on when posix mode is disabled. */
78 source_searches_cwd = 1;
79 expand_aliases = interactive_shell;
83 /* **************************************************************** */
85 /* Functions to convert to and from and display non-standard types */
87 /* **************************************************************** */
89 #if defined (RLIMTYPE)
91 string_to_rlimtype (s)
99 while (s && *s && whitespace (*s))
101 if (*s == '-' || *s == '+')
106 for ( ; s && *s && DIGIT (*s); s++)
107 ret = (ret * 10) + TODIGIT (*s);
108 return (neg ? -ret : ret);
112 print_rlimtype (n, addnl)
116 char s[INT_STRLEN_BOUND (RLIMTYPE) + 1], *p;
125 while ((n /= 10) != 0);
133 while ((n /= 10) != 0);
136 printf ("%s%s", p, addnl ? "\n" : "");
138 #endif /* RLIMTYPE */
140 /* **************************************************************** */
142 /* Input Validation Functions */
144 /* **************************************************************** */
146 /* Return non-zero if all of the characters in STRING are digits. */
153 for (s = string; *s; s++)
160 /* Return non-zero if the characters pointed to by STRING constitute a
161 valid number. Stuff the converted number into RESULT if RESULT is
164 legal_number (string, result)
175 value = strtoimax (string, &ep, 10);
177 return 0; /* errno is set on overflow or underflow */
179 /* Skip any trailing whitespace, since strtoimax does not. */
180 while (whitespace (*ep))
183 /* If *string is not '\0' but *ep is '\0' on return, the entire string
185 if (string && *string && *ep == '\0')
189 /* The SunOS4 implementation of strtol() will happily ignore
190 overflow conditions, so this cannot do overflow correctly
198 /* Return 1 if this token is a legal shell `identifier'; that is, it consists
199 solely of letters, digits, and underscores, and does not begin with a
202 legal_identifier (name)
208 if (!name || !(c = *name) || (legal_variable_starter (c) == 0))
211 for (s = name + 1; (c = *s) != 0; s++)
213 if (legal_variable_char (c) == 0)
219 /* Make sure that WORD is a valid shell identifier, i.e.
220 does not contain a dollar sign, nor is quoted in any way. Nor
221 does it consist of all digits. If CHECK_WORD is non-zero,
222 the word is checked to ensure that it consists of only letters,
223 digits, and underscores. */
225 check_identifier (word, check_word)
229 if ((word->flags & (W_HASDOLLAR|W_QUOTED)) || all_digits (word->word))
231 internal_error (_("`%s': not a valid identifier"), word->word);
234 else if (check_word && legal_identifier (word->word) == 0)
236 internal_error (_("`%s': not a valid identifier"), word->word);
243 /* Return 1 if STRING comprises a valid alias name. The shell accepts
244 essentially all characters except those which must be quoted to the
245 parser (which disqualifies them from alias expansion anyway) and `/'. */
247 legal_alias_name (string, flags)
253 for (s = string; *s; s++)
254 if (shellbreak (*s) || shellxquote (*s) || shellexp (*s) || (*s == '/'))
259 /* Returns non-zero if STRING is an assignment statement. The returned value
260 is the index of the `=' sign. */
262 assignment (string, flags)
266 register unsigned char c;
267 register int newi, indx;
269 c = string[indx = 0];
271 #if defined (ARRAY_VARS)
272 if ((legal_variable_starter (c) == 0) && (flags == 0 || c != '[')) /* ] */
274 if (legal_variable_starter (c) == 0)
278 while (c = string[indx])
280 /* The following is safe. Note that '=' at the start of a word
281 is not an assignment statement. */
285 #if defined (ARRAY_VARS)
288 newi = skipsubscript (string, indx);
289 if (string[newi++] != ']')
291 if (string[newi] == '+' && string[newi+1] == '=')
293 return ((string[newi] == '=') ? newi : 0);
295 #endif /* ARRAY_VARS */
298 if (c == '+' && string[indx+1] == '=')
301 /* Variable names in assignment statements may contain only letters,
303 if (legal_variable_char (c) == 0)
311 /* **************************************************************** */
313 /* Functions to manage files and file descriptors */
315 /* **************************************************************** */
317 /* A function to unset no-delay mode on a file descriptor. Used in shell.c
318 to unset it on the fd passed as stdin. Should be called on stdin if
319 readline gets an EAGAIN or EWOULDBLOCK when trying to read input. */
321 #if !defined (O_NDELAY)
322 # if defined (FNDELAY)
323 # define O_NDELAY FNDELAY
325 #endif /* O_NDELAY */
327 /* Make sure no-delay mode is not set on file descriptor FD. */
329 sh_unset_nodelay_mode (fd)
334 if ((flags = fcntl (fd, F_GETFL, 0)) < 0)
339 /* This is defined to O_NDELAY in filecntl.h if O_NONBLOCK is not present
340 and O_NDELAY is defined. */
342 bflags |= O_NONBLOCK;
352 return (fcntl (fd, F_SETFL, flags));
358 /* Return 1 if file descriptor FD is valid; 0 otherwise. */
363 return (fcntl (fd, F_GETFD, 0) >= 0);
366 /* There is a bug in the NeXT 2.1 rlogind that causes opens
367 of /dev/tty to fail. */
369 #if defined (__BEOS__)
370 /* On BeOS, opening in non-blocking mode exposes a bug in BeOS, so turn it
371 into a no-op. This should probably go away in the future. */
373 # define O_NONBLOCK 0
374 #endif /* __BEOS__ */
382 tty_fd = open ("/dev/tty", O_RDWR|O_NONBLOCK);
386 tty = (char *)ttyname (fileno (stdin));
389 tty_fd = open (tty, O_RDWR|O_NONBLOCK);
394 /* Return 1 if PATH1 and PATH2 are the same file. This is kind of
395 expensive. If non-NULL STP1 and STP2 point to stat structures
396 corresponding to PATH1 and PATH2, respectively. */
398 same_file (path1, path2, stp1, stp2)
400 struct stat *stp1, *stp2;
402 struct stat st1, st2;
406 if (stat (path1, &st1) != 0)
413 if (stat (path2, &st2) != 0)
418 return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
421 /* Move FD to a number close to the maximum number of file descriptors
422 allowed in the shell process, to avoid the user stepping on it with
423 redirection and causing us extra work. If CHECK_NEW is non-zero,
424 we check whether or not the file descriptors are in use before
425 duplicating FD onto them. MAXFD says where to start checking the
426 file descriptors. If it's less than 20, we get the maximum value
427 available from getdtablesize(2). */
429 move_to_high_fd (fd, check_new, maxfd)
430 int fd, check_new, maxfd;
432 int script_fd, nfds, ignore;
436 nfds = getdtablesize ();
439 if (nfds > HIGH_FD_MAX)
440 nfds = HIGH_FD_MAX; /* reasonable maximum */
445 for (nfds--; check_new && nfds > 3; nfds--)
446 if (fcntl (nfds, F_GETFD, &ignore) == -1)
449 if (nfds > 3 && fd != nfds && (script_fd = dup2 (fd, nfds)) != -1)
451 if (check_new == 0 || fd != fileno (stderr)) /* don't close stderr */
456 /* OK, we didn't find one less than our artificial maximum; return the
457 original file descriptor. */
461 /* Return non-zero if the characters from SAMPLE are not all valid
462 characters to be found in the first line of a shell script. We
463 check up to the first newline, or SAMPLE_LEN, whichever comes first.
464 All of the characters must be printable or whitespace. */
467 check_binary_file (sample, sample_len)
474 for (i = 0; i < sample_len; i++)
480 if (ISSPACE (c) == 0 && ISPRINT (c) == 0)
487 /* **************************************************************** */
489 /* Functions to inspect pathnames */
491 /* **************************************************************** */
499 return ((stat (fn, &sb) == 0) && S_ISDIR (sb.st_mode));
506 return (file_isdir (fn) && test_eaccess (fn, W_OK) == 0);
510 /* **************************************************************** */
512 /* Functions to manipulate pathnames */
514 /* **************************************************************** */
516 /* Turn STRING (a pathname) into an absolute pathname, assuming that
517 DOT_PATH contains the symbolic location of `.'. This always
518 returns a new string, even if STRING was an absolute pathname to
521 make_absolute (string, dot_path)
522 char *string, *dot_path;
526 if (dot_path == 0 || ABSPATH(string))
529 char pathbuf[PATH_MAX + 1];
531 cygwin_conv_to_full_posix_path (string, pathbuf);
532 result = savestring (pathbuf);
535 result = savestring (string);
538 result = sh_makepath (dot_path, string, 0);
543 /* Return 1 if STRING contains an absolute pathname, else 0. Used by `cd'
544 to decide whether or not to look up a directory name in $CDPATH. */
546 absolute_pathname (string)
549 if (string == 0 || *string == '\0')
555 if (string[0] == '.' && PATHSEP(string[1])) /* . and ./ */
558 if (string[0] == '.' && string[1] == '.' && PATHSEP(string[2])) /* .. and ../ */
564 /* Return 1 if STRING is an absolute program name; it is absolute if it
565 contains any slashes. This is used to decide whether or not to look
568 absolute_program (string)
571 return ((char *)xstrchr (string, '/') != (char *)NULL);
574 /* Return the `basename' of the pathname in STRING (the stuff after the
575 last '/'). If STRING is `/', just return it. */
577 base_pathname (string)
583 if (absolute_pathname (string) == 0)
587 if (string[0] == '/' && string[1] == 0)
590 p = (char *)strrchr (string, '/');
591 return (p ? ++p : string);
594 /* Return the full pathname of FILE. Easy. Filenames that begin
595 with a '/' are returned as themselves. Other filenames have
596 the current working directory prepended. A new string is
597 returned in either case. */
604 file = (*file == '~') ? bash_tilde_expand (file, 0) : savestring (file);
609 ret = sh_makepath ((char *)NULL, file, (MP_DOCWD|MP_RMDOT));
615 /* A slightly related function. Get the prettiest name of this
616 directory possible. */
617 static char tdir[PATH_MAX];
619 /* Return a pretty pathname. If the first part of the pathname is
620 the same as $HOME, then replace that with `~'. */
622 polite_directory_format (name)
628 home = get_string_value ("HOME");
629 l = home ? strlen (home) : 0;
630 if (l > 1 && strncmp (home, name, l) == 0 && (!name[l] || name[l] == '/'))
632 strncpy (tdir + 1, name + l, sizeof(tdir) - 2);
634 tdir[sizeof(tdir) - 1] = '\0';
641 /* Given a string containing units of information separated by colons,
642 return the next one pointed to by (P_INDEX), or NULL if there are no more.
643 Advance (P_INDEX) to the character after the colon. */
645 extract_colon_unit (string, p_index)
655 len = strlen (string);
657 return ((char *)NULL);
661 /* Each call to this routine leaves the index pointing at a colon if
662 there is more to the path. If I is > 0, then increment past the
663 `:'. If I is 0, then the path has a leading colon. Trailing colons
664 are handled OK by the `else' part of the if statement; an empty
665 string is returned in that case. */
666 if (i && string[i] == ':')
669 for (start = i; string[i] && string[i] != ':'; i++)
678 /* Return "" in the case of a trailing `:'. */
679 value = (char *)xmalloc (1);
683 value = substring (string, start, i);
688 /* **************************************************************** */
690 /* Tilde Initialization and Expansion */
692 /* **************************************************************** */
694 #if defined (PUSHD_AND_POPD)
695 extern char *get_dirstack_from_string __P((char *));
698 static char **bash_tilde_prefixes;
699 static char **bash_tilde_prefixes2;
700 static char **bash_tilde_suffixes;
701 static char **bash_tilde_suffixes2;
703 /* If tilde_expand hasn't been able to expand the text, perhaps it
704 is a special shell expansion. This function is installed as the
705 tilde_expansion_preexpansion_hook. It knows how to expand ~- and ~+.
706 If PUSHD_AND_POPD is defined, ~[+-]N expands to directories from the
709 bash_special_tilde_expansions (text)
714 result = (char *)NULL;
716 if (text[0] == '+' && text[1] == '\0')
717 result = get_string_value ("PWD");
718 else if (text[0] == '-' && text[1] == '\0')
719 result = get_string_value ("OLDPWD");
720 #if defined (PUSHD_AND_POPD)
721 else if (DIGIT (*text) || ((*text == '+' || *text == '-') && DIGIT (text[1])))
722 result = get_dirstack_from_string (text);
725 return (result ? savestring (result) : (char *)NULL);
728 /* Initialize the tilde expander. In Bash, we handle `~-' and `~+', as
729 well as handling special tilde prefixes; `:~" and `=~' are indications
730 that we should do tilde expansion. */
734 static int times_called = 0;
736 /* Tell the tilde expander that we want a crack first. */
737 tilde_expansion_preexpansion_hook = bash_special_tilde_expansions;
739 /* Tell the tilde expander about special strings which start a tilde
740 expansion, and the special strings that end one. Only do this once.
741 tilde_initialize () is called from within bashline_reinitialize (). */
742 if (times_called++ == 0)
744 bash_tilde_prefixes = strvec_create (3);
745 bash_tilde_prefixes[0] = "=~";
746 bash_tilde_prefixes[1] = ":~";
747 bash_tilde_prefixes[2] = (char *)NULL;
749 bash_tilde_prefixes2 = strvec_create (2);
750 bash_tilde_prefixes2[0] = ":~";
751 bash_tilde_prefixes2[1] = (char *)NULL;
753 tilde_additional_prefixes = bash_tilde_prefixes;
755 bash_tilde_suffixes = strvec_create (3);
756 bash_tilde_suffixes[0] = ":";
757 bash_tilde_suffixes[1] = "=~"; /* XXX - ?? */
758 bash_tilde_suffixes[2] = (char *)NULL;
760 tilde_additional_suffixes = bash_tilde_suffixes;
762 bash_tilde_suffixes2 = strvec_create (2);
763 bash_tilde_suffixes2[0] = ":";
764 bash_tilde_suffixes2[1] = (char *)NULL;
768 /* POSIX.2, 3.6.1: A tilde-prefix consists of an unquoted tilde character
769 at the beginning of the word, followed by all of the characters preceding
770 the first unquoted slash in the word, or all the characters in the word
771 if there is no slash...If none of the characters in the tilde-prefix are
772 quoted, the characters in the tilde-prefix following the tilde shell be
773 treated as a possible login name. */
775 #define TILDE_END(c) ((c) == '\0' || (c) == '/' || (c) == ':')
778 unquoted_tilde_word (s)
783 for (r = s; TILDE_END(*r) == 0; r++)
796 /* Find the end of the tilde-prefix starting at S, and return the tilde
797 prefix in newly-allocated memory. Return the length of the string in
798 *LENP. FLAGS tells whether or not we're in an assignment context --
799 if so, `:' delimits the end of the tilde prefix as well. */
801 bash_tilde_find_word (s, flags, lenp)
809 for (r = s; *r && *r != '/'; r++)
811 /* Short-circuit immediately if we see a quote character. Even though
812 POSIX says that `the first unquoted slash' (or `:') terminates the
813 tilde-prefix, in practice, any quoted portion of the tilde prefix
814 will cause it to not be expanded. */
815 if (*r == '\\' || *r == '\'' || *r == '"')
817 ret = savestring (s);
822 else if (flags && *r == ':')
826 ret = xmalloc (l + 1);
834 /* Tilde-expand S by running it through the tilde expansion library.
835 ASSIGN_P is 1 if this is a variable assignment, so the alternate
836 tilde prefixes should be enabled (`=~' and `:~', see above). If
837 ASSIGN_P is 2, we are expanding the rhs of an assignment statement,
838 so `=~' is not valid. */
840 bash_tilde_expand (s, assign_p)
847 old_immed = interrupt_immediately;
848 interrupt_immediately = 1;
850 tilde_additional_prefixes = assign_p == 0 ? (char **)0
851 : (assign_p == 2 ? bash_tilde_prefixes2 : bash_tilde_prefixes);
853 tilde_additional_suffixes = bash_tilde_suffixes2;
855 r = (*s == '~') ? unquoted_tilde_word (s) : 1;
856 ret = r ? tilde_expand (s) : savestring (s);
857 interrupt_immediately = old_immed;
861 /* **************************************************************** */
863 /* Functions to manipulate and search the group list */
865 /* **************************************************************** */
867 static int ngroups, maxgroups;
869 /* The set of groups that this user is a member of. */
870 static GETGROUPS_T *group_array = (GETGROUPS_T *)NULL;
872 #if !defined (NOGROUP)
873 # define NOGROUP (gid_t) -1
877 initialize_group_array ()
882 maxgroups = getmaxgroups ();
885 group_array = (GETGROUPS_T *)xrealloc (group_array, maxgroups * sizeof (GETGROUPS_T));
887 #if defined (HAVE_GETGROUPS)
888 ngroups = getgroups (maxgroups, group_array);
891 /* If getgroups returns nothing, or the OS does not support getgroups(),
892 make sure the groups array includes at least the current gid. */
895 group_array[0] = current_user.gid;
899 /* If the primary group is not in the groups array, add it as group_array[0]
900 and shuffle everything else up 1, if there's room. */
901 for (i = 0; i < ngroups; i++)
902 if (current_user.gid == (gid_t)group_array[i])
904 if (i == ngroups && ngroups < maxgroups)
906 for (i = ngroups; i > 0; i--)
907 group_array[i] = group_array[i - 1];
908 group_array[0] = current_user.gid;
912 /* If the primary group is not group_array[0], swap group_array[0] and
913 whatever the current group is. The vast majority of systems should
914 not need this; a notable exception is Linux. */
915 if (group_array[0] != current_user.gid)
917 for (i = 0; i < ngroups; i++)
918 if (group_array[i] == current_user.gid)
922 group_array[i] = group_array[0];
923 group_array[0] = current_user.gid;
928 /* Return non-zero if GID is one that we have in our groups list. */
930 #if defined (__STDC__) || defined ( _MINIX)
931 group_member (gid_t gid)
935 #endif /* !__STDC__ && !_MINIX */
937 #if defined (HAVE_GETGROUPS)
941 /* Short-circuit if possible, maybe saving a call to getgroups(). */
942 if (gid == current_user.gid || gid == current_user.egid)
945 #if defined (HAVE_GETGROUPS)
947 initialize_group_array ();
949 /* In case of error, the user loses. */
953 /* Search through the list looking for GID. */
954 for (i = 0; i < ngroups; i++)
955 if (gid == (gid_t)group_array[i])
966 static char **group_vector = (char **)NULL;
977 initialize_group_array ();
983 return (char **)NULL;
986 group_vector = strvec_create (ngroups);
987 for (i = 0; i < ngroups; i++)
988 group_vector[i] = itos (group_array[i]);
996 get_group_array (ngp)
1000 static int *group_iarray = (int *)NULL;
1006 return (group_iarray);
1010 initialize_group_array ();
1019 group_iarray = (int *)xmalloc (ngroups * sizeof (int));
1020 for (i = 0; i < ngroups; i++)
1021 group_iarray[i] = (int)group_array[i];
1025 return group_iarray;