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 interactive_comments;
52 extern int check_hashed_filenames;
53 extern int source_uses_path;
54 extern int source_searches_cwd;
56 static char *bash_special_tilde_expansions __P((char *));
57 static int unquoted_tilde_word __P((const char *));
58 static void initialize_group_array __P((void));
60 /* A standard error message to use when getcwd() returns NULL. */
61 char *bash_getcwd_errstr = N_("getcwd: cannot access parent directories");
63 /* Do whatever is necessary to initialize `Posix mode'. */
68 /* Things that should be turned on when posix mode is enabled. */
71 interactive_comments = source_uses_path = expand_aliases = 1;
74 /* Things that should be turned on when posix mode is disabled. */
77 source_searches_cwd = 1;
78 expand_aliases = interactive_shell;
82 /* **************************************************************** */
84 /* Functions to convert to and from and display non-standard types */
86 /* **************************************************************** */
88 #if defined (RLIMTYPE)
90 string_to_rlimtype (s)
98 while (s && *s && whitespace (*s))
100 if (*s == '-' || *s == '+')
105 for ( ; s && *s && DIGIT (*s); s++)
106 ret = (ret * 10) + TODIGIT (*s);
107 return (neg ? -ret : ret);
111 print_rlimtype (n, addnl)
115 char s[INT_STRLEN_BOUND (RLIMTYPE) + 1], *p;
124 while ((n /= 10) != 0);
132 while ((n /= 10) != 0);
135 printf ("%s%s", p, addnl ? "\n" : "");
137 #endif /* RLIMTYPE */
139 /* **************************************************************** */
141 /* Input Validation Functions */
143 /* **************************************************************** */
145 /* Return non-zero if all of the characters in STRING are digits. */
152 for (s = string; *s; s++)
159 /* Return non-zero if the characters pointed to by STRING constitute a
160 valid number. Stuff the converted number into RESULT if RESULT is
163 legal_number (string, result)
174 value = strtoimax (string, &ep, 10);
176 return 0; /* errno is set on overflow or underflow */
178 /* Skip any trailing whitespace, since strtoimax does not. */
179 while (whitespace (*ep))
182 /* If *string is not '\0' but *ep is '\0' on return, the entire string
184 if (string && *string && *ep == '\0')
188 /* The SunOS4 implementation of strtol() will happily ignore
189 overflow conditions, so this cannot do overflow correctly
197 /* Return 1 if this token is a legal shell `identifier'; that is, it consists
198 solely of letters, digits, and underscores, and does not begin with a
201 legal_identifier (name)
207 if (!name || !(c = *name) || (legal_variable_starter (c) == 0))
210 for (s = name + 1; (c = *s) != 0; s++)
212 if (legal_variable_char (c) == 0)
218 /* Make sure that WORD is a valid shell identifier, i.e.
219 does not contain a dollar sign, nor is quoted in any way. Nor
220 does it consist of all digits. If CHECK_WORD is non-zero,
221 the word is checked to ensure that it consists of only letters,
222 digits, and underscores. */
224 check_identifier (word, check_word)
228 if ((word->flags & (W_HASDOLLAR|W_QUOTED)) || all_digits (word->word))
230 internal_error (_("`%s': not a valid identifier"), word->word);
233 else if (check_word && legal_identifier (word->word) == 0)
235 internal_error (_("`%s': not a valid identifier"), word->word);
242 /* Return 1 if STRING comprises a valid alias name. The shell accepts
243 essentially all characters except those which must be quoted to the
244 parser (which disqualifies them from alias expansion anyway) and `/'. */
246 legal_alias_name (string, flags)
252 for (s = string; *s; s++)
253 if (shellbreak (*s) || shellxquote (*s) || shellexp (*s) || (*s == '/'))
258 /* Returns non-zero if STRING is an assignment statement. The returned value
259 is the index of the `=' sign. */
261 assignment (string, flags)
265 register unsigned char c;
266 register int newi, indx;
268 c = string[indx = 0];
270 #if defined (ARRAY_VARS)
271 if ((legal_variable_starter (c) == 0) && (flags == 0 || c != '[')) /* ] */
273 if (legal_variable_starter (c) == 0)
277 while (c = string[indx])
279 /* The following is safe. Note that '=' at the start of a word
280 is not an assignment statement. */
284 #if defined (ARRAY_VARS)
287 newi = skipsubscript (string, indx);
288 if (string[newi++] != ']')
290 if (string[newi] == '+' && string[newi+1] == '=')
292 return ((string[newi] == '=') ? newi : 0);
294 #endif /* ARRAY_VARS */
297 if (c == '+' && string[indx+1] == '=')
300 /* Variable names in assignment statements may contain only letters,
302 if (legal_variable_char (c) == 0)
310 /* **************************************************************** */
312 /* Functions to manage files and file descriptors */
314 /* **************************************************************** */
316 /* A function to unset no-delay mode on a file descriptor. Used in shell.c
317 to unset it on the fd passed as stdin. Should be called on stdin if
318 readline gets an EAGAIN or EWOULDBLOCK when trying to read input. */
320 #if !defined (O_NDELAY)
321 # if defined (FNDELAY)
322 # define O_NDELAY FNDELAY
324 #endif /* O_NDELAY */
326 /* Make sure no-delay mode is not set on file descriptor FD. */
328 sh_unset_nodelay_mode (fd)
333 if ((flags = fcntl (fd, F_GETFL, 0)) < 0)
338 /* This is defined to O_NDELAY in filecntl.h if O_NONBLOCK is not present
339 and O_NDELAY is defined. */
341 bflags |= O_NONBLOCK;
351 return (fcntl (fd, F_SETFL, flags));
357 /* Return 1 if file descriptor FD is valid; 0 otherwise. */
362 return (fcntl (fd, F_GETFD, 0) >= 0);
365 /* There is a bug in the NeXT 2.1 rlogind that causes opens
366 of /dev/tty to fail. */
368 #if defined (__BEOS__)
369 /* On BeOS, opening in non-blocking mode exposes a bug in BeOS, so turn it
370 into a no-op. This should probably go away in the future. */
372 # define O_NONBLOCK 0
373 #endif /* __BEOS__ */
381 tty_fd = open ("/dev/tty", O_RDWR|O_NONBLOCK);
385 tty = (char *)ttyname (fileno (stdin));
388 tty_fd = open (tty, O_RDWR|O_NONBLOCK);
393 /* Return 1 if PATH1 and PATH2 are the same file. This is kind of
394 expensive. If non-NULL STP1 and STP2 point to stat structures
395 corresponding to PATH1 and PATH2, respectively. */
397 same_file (path1, path2, stp1, stp2)
399 struct stat *stp1, *stp2;
401 struct stat st1, st2;
405 if (stat (path1, &st1) != 0)
412 if (stat (path2, &st2) != 0)
417 return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
420 /* Move FD to a number close to the maximum number of file descriptors
421 allowed in the shell process, to avoid the user stepping on it with
422 redirection and causing us extra work. If CHECK_NEW is non-zero,
423 we check whether or not the file descriptors are in use before
424 duplicating FD onto them. MAXFD says where to start checking the
425 file descriptors. If it's less than 20, we get the maximum value
426 available from getdtablesize(2). */
428 move_to_high_fd (fd, check_new, maxfd)
429 int fd, check_new, maxfd;
431 int script_fd, nfds, ignore;
435 nfds = getdtablesize ();
438 if (nfds > HIGH_FD_MAX)
439 nfds = HIGH_FD_MAX; /* reasonable maximum */
444 for (nfds--; check_new && nfds > 3; nfds--)
445 if (fcntl (nfds, F_GETFD, &ignore) == -1)
448 if (nfds > 3 && fd != nfds && (script_fd = dup2 (fd, nfds)) != -1)
450 if (check_new == 0 || fd != fileno (stderr)) /* don't close stderr */
455 /* OK, we didn't find one less than our artificial maximum; return the
456 original file descriptor. */
460 /* Return non-zero if the characters from SAMPLE are not all valid
461 characters to be found in the first line of a shell script. We
462 check up to the first newline, or SAMPLE_LEN, whichever comes first.
463 All of the characters must be printable or whitespace. */
466 check_binary_file (sample, sample_len)
473 for (i = 0; i < sample_len; i++)
480 if (ISSPACE (c) == 0 && ISPRINT (c) == 0)
491 /* **************************************************************** */
493 /* Functions to inspect pathnames */
495 /* **************************************************************** */
503 return ((stat (fn, &sb) == 0) && S_ISDIR (sb.st_mode));
510 return (file_isdir (fn) && sh_eaccess (fn, W_OK) == 0);
513 /* Return 1 if STRING contains an absolute pathname, else 0. Used by `cd'
514 to decide whether or not to look up a directory name in $CDPATH. */
516 absolute_pathname (string)
519 if (string == 0 || *string == '\0')
525 if (string[0] == '.' && PATHSEP(string[1])) /* . and ./ */
528 if (string[0] == '.' && string[1] == '.' && PATHSEP(string[2])) /* .. and ../ */
534 /* Return 1 if STRING is an absolute program name; it is absolute if it
535 contains any slashes. This is used to decide whether or not to look
538 absolute_program (string)
541 return ((char *)xstrchr (string, '/') != (char *)NULL);
544 /* **************************************************************** */
546 /* Functions to manipulate pathnames */
548 /* **************************************************************** */
550 /* Turn STRING (a pathname) into an absolute pathname, assuming that
551 DOT_PATH contains the symbolic location of `.'. This always
552 returns a new string, even if STRING was an absolute pathname to
555 make_absolute (string, dot_path)
556 char *string, *dot_path;
560 if (dot_path == 0 || ABSPATH(string))
563 char pathbuf[PATH_MAX + 1];
565 cygwin_conv_to_full_posix_path (string, pathbuf);
566 result = savestring (pathbuf);
569 result = savestring (string);
572 result = sh_makepath (dot_path, string, 0);
577 /* Return the `basename' of the pathname in STRING (the stuff after the
578 last '/'). If STRING is `/', just return it. */
580 base_pathname (string)
586 if (absolute_pathname (string) == 0)
590 if (string[0] == '/' && string[1] == 0)
593 p = (char *)strrchr (string, '/');
594 return (p ? ++p : string);
597 /* Return the full pathname of FILE. Easy. Filenames that begin
598 with a '/' are returned as themselves. Other filenames have
599 the current working directory prepended. A new string is
600 returned in either case. */
607 file = (*file == '~') ? bash_tilde_expand (file, 0) : savestring (file);
612 ret = sh_makepath ((char *)NULL, file, (MP_DOCWD|MP_RMDOT));
618 /* A slightly related function. Get the prettiest name of this
619 directory possible. */
620 static char tdir[PATH_MAX];
622 /* Return a pretty pathname. If the first part of the pathname is
623 the same as $HOME, then replace that with `~'. */
625 polite_directory_format (name)
631 home = get_string_value ("HOME");
632 l = home ? strlen (home) : 0;
633 if (l > 1 && strncmp (home, name, l) == 0 && (!name[l] || name[l] == '/'))
635 strncpy (tdir + 1, name + l, sizeof(tdir) - 2);
637 tdir[sizeof(tdir) - 1] = '\0';
644 /* Given a string containing units of information separated by colons,
645 return the next one pointed to by (P_INDEX), or NULL if there are no more.
646 Advance (P_INDEX) to the character after the colon. */
648 extract_colon_unit (string, p_index)
658 len = strlen (string);
660 return ((char *)NULL);
664 /* Each call to this routine leaves the index pointing at a colon if
665 there is more to the path. If I is > 0, then increment past the
666 `:'. If I is 0, then the path has a leading colon. Trailing colons
667 are handled OK by the `else' part of the if statement; an empty
668 string is returned in that case. */
669 if (i && string[i] == ':')
672 for (start = i; string[i] && string[i] != ':'; i++)
681 /* Return "" in the case of a trailing `:'. */
682 value = (char *)xmalloc (1);
686 value = substring (string, start, i);
691 /* **************************************************************** */
693 /* Tilde Initialization and Expansion */
695 /* **************************************************************** */
697 #if defined (PUSHD_AND_POPD)
698 extern char *get_dirstack_from_string __P((char *));
701 static char **bash_tilde_prefixes;
702 static char **bash_tilde_prefixes2;
703 static char **bash_tilde_suffixes;
704 static char **bash_tilde_suffixes2;
706 /* If tilde_expand hasn't been able to expand the text, perhaps it
707 is a special shell expansion. This function is installed as the
708 tilde_expansion_preexpansion_hook. It knows how to expand ~- and ~+.
709 If PUSHD_AND_POPD is defined, ~[+-]N expands to directories from the
712 bash_special_tilde_expansions (text)
717 result = (char *)NULL;
719 if (text[0] == '+' && text[1] == '\0')
720 result = get_string_value ("PWD");
721 else if (text[0] == '-' && text[1] == '\0')
722 result = get_string_value ("OLDPWD");
723 #if defined (PUSHD_AND_POPD)
724 else if (DIGIT (*text) || ((*text == '+' || *text == '-') && DIGIT (text[1])))
725 result = get_dirstack_from_string (text);
728 return (result ? savestring (result) : (char *)NULL);
731 /* Initialize the tilde expander. In Bash, we handle `~-' and `~+', as
732 well as handling special tilde prefixes; `:~" and `=~' are indications
733 that we should do tilde expansion. */
737 static int times_called = 0;
739 /* Tell the tilde expander that we want a crack first. */
740 tilde_expansion_preexpansion_hook = bash_special_tilde_expansions;
742 /* Tell the tilde expander about special strings which start a tilde
743 expansion, and the special strings that end one. Only do this once.
744 tilde_initialize () is called from within bashline_reinitialize (). */
745 if (times_called++ == 0)
747 bash_tilde_prefixes = strvec_create (3);
748 bash_tilde_prefixes[0] = "=~";
749 bash_tilde_prefixes[1] = ":~";
750 bash_tilde_prefixes[2] = (char *)NULL;
752 bash_tilde_prefixes2 = strvec_create (2);
753 bash_tilde_prefixes2[0] = ":~";
754 bash_tilde_prefixes2[1] = (char *)NULL;
756 tilde_additional_prefixes = bash_tilde_prefixes;
758 bash_tilde_suffixes = strvec_create (3);
759 bash_tilde_suffixes[0] = ":";
760 bash_tilde_suffixes[1] = "=~"; /* XXX - ?? */
761 bash_tilde_suffixes[2] = (char *)NULL;
763 tilde_additional_suffixes = bash_tilde_suffixes;
765 bash_tilde_suffixes2 = strvec_create (2);
766 bash_tilde_suffixes2[0] = ":";
767 bash_tilde_suffixes2[1] = (char *)NULL;
771 /* POSIX.2, 3.6.1: A tilde-prefix consists of an unquoted tilde character
772 at the beginning of the word, followed by all of the characters preceding
773 the first unquoted slash in the word, or all the characters in the word
774 if there is no slash...If none of the characters in the tilde-prefix are
775 quoted, the characters in the tilde-prefix following the tilde shell be
776 treated as a possible login name. */
778 #define TILDE_END(c) ((c) == '\0' || (c) == '/' || (c) == ':')
781 unquoted_tilde_word (s)
786 for (r = s; TILDE_END(*r) == 0; r++)
799 /* Find the end of the tilde-prefix starting at S, and return the tilde
800 prefix in newly-allocated memory. Return the length of the string in
801 *LENP. FLAGS tells whether or not we're in an assignment context --
802 if so, `:' delimits the end of the tilde prefix as well. */
804 bash_tilde_find_word (s, flags, lenp)
812 for (r = s; *r && *r != '/'; r++)
814 /* Short-circuit immediately if we see a quote character. Even though
815 POSIX says that `the first unquoted slash' (or `:') terminates the
816 tilde-prefix, in practice, any quoted portion of the tilde prefix
817 will cause it to not be expanded. */
818 if (*r == '\\' || *r == '\'' || *r == '"')
820 ret = savestring (s);
825 else if (flags && *r == ':')
829 ret = xmalloc (l + 1);
837 /* Tilde-expand S by running it through the tilde expansion library.
838 ASSIGN_P is 1 if this is a variable assignment, so the alternate
839 tilde prefixes should be enabled (`=~' and `:~', see above). If
840 ASSIGN_P is 2, we are expanding the rhs of an assignment statement,
841 so `=~' is not valid. */
843 bash_tilde_expand (s, assign_p)
850 old_immed = interrupt_immediately;
851 interrupt_immediately = 1;
853 tilde_additional_prefixes = assign_p == 0 ? (char **)0
854 : (assign_p == 2 ? bash_tilde_prefixes2 : bash_tilde_prefixes);
856 tilde_additional_suffixes = bash_tilde_suffixes2;
858 r = (*s == '~') ? unquoted_tilde_word (s) : 1;
859 ret = r ? tilde_expand (s) : savestring (s);
860 interrupt_immediately = old_immed;
864 /* **************************************************************** */
866 /* Functions to manipulate and search the group list */
868 /* **************************************************************** */
870 static int ngroups, maxgroups;
872 /* The set of groups that this user is a member of. */
873 static GETGROUPS_T *group_array = (GETGROUPS_T *)NULL;
875 #if !defined (NOGROUP)
876 # define NOGROUP (gid_t) -1
880 initialize_group_array ()
885 maxgroups = getmaxgroups ();
888 group_array = (GETGROUPS_T *)xrealloc (group_array, maxgroups * sizeof (GETGROUPS_T));
890 #if defined (HAVE_GETGROUPS)
891 ngroups = getgroups (maxgroups, group_array);
894 /* If getgroups returns nothing, or the OS does not support getgroups(),
895 make sure the groups array includes at least the current gid. */
898 group_array[0] = current_user.gid;
902 /* If the primary group is not in the groups array, add it as group_array[0]
903 and shuffle everything else up 1, if there's room. */
904 for (i = 0; i < ngroups; i++)
905 if (current_user.gid == (gid_t)group_array[i])
907 if (i == ngroups && ngroups < maxgroups)
909 for (i = ngroups; i > 0; i--)
910 group_array[i] = group_array[i - 1];
911 group_array[0] = current_user.gid;
915 /* If the primary group is not group_array[0], swap group_array[0] and
916 whatever the current group is. The vast majority of systems should
917 not need this; a notable exception is Linux. */
918 if (group_array[0] != current_user.gid)
920 for (i = 0; i < ngroups; i++)
921 if (group_array[i] == current_user.gid)
925 group_array[i] = group_array[0];
926 group_array[0] = current_user.gid;
931 /* Return non-zero if GID is one that we have in our groups list. */
933 #if defined (__STDC__) || defined ( _MINIX)
934 group_member (gid_t gid)
938 #endif /* !__STDC__ && !_MINIX */
940 #if defined (HAVE_GETGROUPS)
944 /* Short-circuit if possible, maybe saving a call to getgroups(). */
945 if (gid == current_user.gid || gid == current_user.egid)
948 #if defined (HAVE_GETGROUPS)
950 initialize_group_array ();
952 /* In case of error, the user loses. */
956 /* Search through the list looking for GID. */
957 for (i = 0; i < ngroups; i++)
958 if (gid == (gid_t)group_array[i])
969 static char **group_vector = (char **)NULL;
980 initialize_group_array ();
986 return (char **)NULL;
989 group_vector = strvec_create (ngroups);
990 for (i = 0; i < ngroups; i++)
991 group_vector[i] = itos (group_array[i]);
999 get_group_array (ngp)
1003 static int *group_iarray = (int *)NULL;
1009 return (group_iarray);
1013 initialize_group_array ();
1022 group_iarray = (int *)xmalloc (ngroups * sizeof (int));
1023 for (i = 0; i < ngroups; i++)
1024 group_iarray[i] = (int)group_array[i];
1028 return group_iarray;