1 /* general.c -- Stuff that is used by all files. */
3 /* Copyright (C) 1987-1999 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"
40 #include <tilde/tilde.h>
46 extern int expand_aliases;
47 extern int interrupt_immediately;
48 extern int interactive_comments;
49 extern int check_hashed_filenames;
50 extern int source_uses_path;
51 extern int source_searches_cwd;
53 /* A standard error message to use when getcwd() returns NULL. */
54 char *bash_getcwd_errstr = "getcwd: cannot access parent directories";
56 /* Do whatever is necessary to initialize `Posix mode'. */
61 /* Things that should be turned on when posix mode is enabled. */
64 interactive_comments = source_uses_path = expand_aliases = 1;
67 /* Things that should be turned on when posix mode is disabled. */
70 source_searches_cwd = 1;
71 expand_aliases = interactive_shell;
75 /* **************************************************************** */
77 /* Functions to convert to and from and display non-standard types */
79 /* **************************************************************** */
81 #if defined (RLIMTYPE)
83 string_to_rlimtype (s)
91 while (s && *s && whitespace (*s))
93 if (*s == '-' || *s == '+')
98 for ( ; s && *s && DIGIT (*s); s++)
99 ret = (ret * 10) + TODIGIT (*s);
100 return (neg ? -ret : ret);
104 print_rlimtype (n, addnl)
108 char s[INT_STRLEN_BOUND (RLIMTYPE) + 1], *p;
117 while ((n /= 10) != 0);
125 while ((n /= 10) != 0);
128 printf ("%s%s", p, addnl ? "\n" : "");
130 #endif /* RLIMTYPE */
132 /* **************************************************************** */
134 /* Input Validation Functions */
136 /* **************************************************************** */
138 /* Return non-zero if all of the characters in STRING are digits. */
145 for (s = string; *s; s++)
152 /* Return non-zero if the characters pointed to by STRING constitute a
153 valid number. Stuff the converted number into RESULT if RESULT is
156 legal_number (string, result)
167 value = strtol (string, &ep, 10);
169 return 0; /* errno is set on overflow or underflow */
171 /* Skip any trailing whitespace, since strtol does not. */
172 while (whitespace (*ep))
175 /* If *string is not '\0' but *ep is '\0' on return, the entire string
177 if (string && *string && *ep == '\0')
181 /* The SunOS4 implementation of strtol() will happily ignore
182 overflow conditions, so this cannot do overflow correctly
190 /* Return 1 if this token is a legal shell `identifier'; that is, it consists
191 solely of letters, digits, and underscores, and does not begin with a
194 legal_identifier (name)
200 if (!name || !(c = *name) || (legal_variable_starter (c) == 0))
203 for (s = name + 1; (c = *s) != 0; s++)
205 if (legal_variable_char (c) == 0)
211 /* Make sure that WORD is a valid shell identifier, i.e.
212 does not contain a dollar sign, nor is quoted in any way. Nor
213 does it consist of all digits. If CHECK_WORD is non-zero,
214 the word is checked to ensure that it consists of only letters,
215 digits, and underscores. */
217 check_identifier (word, check_word)
221 if ((word->flags & (W_HASDOLLAR|W_QUOTED)) || all_digits (word->word))
223 internal_error ("`%s': not a valid identifier", word->word);
226 else if (check_word && legal_identifier (word->word) == 0)
228 internal_error ("`%s': not a valid identifier", word->word);
235 /* **************************************************************** */
237 /* Functions to manage files and file descriptors */
239 /* **************************************************************** */
241 /* A function to unset no-delay mode on a file descriptor. Used in shell.c
242 to unset it on the fd passed as stdin. Should be called on stdin if
243 readline gets an EAGAIN or EWOULDBLOCK when trying to read input. */
245 #if !defined (O_NDELAY)
246 # if defined (FNDELAY)
247 # define O_NDELAY FNDELAY
249 #endif /* O_NDELAY */
251 /* Make sure no-delay mode is not set on file descriptor FD. */
253 sh_unset_nodelay_mode (fd)
258 if ((flags = fcntl (fd, F_GETFL, 0)) < 0)
263 /* This is defined to O_NDELAY in filecntl.h if O_NONBLOCK is not present
264 and O_NDELAY is defined. */
266 bflags |= O_NONBLOCK;
276 return (fcntl (fd, F_SETFL, flags));
282 /* There is a bug in the NeXT 2.1 rlogind that causes opens
283 of /dev/tty to fail. */
285 #if defined (__BEOS__)
286 /* On BeOS, opening in non-blocking mode exposes a bug in BeOS, so turn it
287 into a no-op. This should probably go away in the future. */
289 # define O_NONBLOCK 0
290 #endif /* __BEOS__ */
298 tty_fd = open ("/dev/tty", O_RDWR|O_NONBLOCK);
302 tty = (char *)ttyname (fileno (stdin));
305 tty_fd = open (tty, O_RDWR|O_NONBLOCK);
310 /* Return 1 if PATH1 and PATH2 are the same file. This is kind of
311 expensive. If non-NULL STP1 and STP2 point to stat structures
312 corresponding to PATH1 and PATH2, respectively. */
314 same_file (path1, path2, stp1, stp2)
316 struct stat *stp1, *stp2;
318 struct stat st1, st2;
322 if (stat (path1, &st1) != 0)
329 if (stat (path2, &st2) != 0)
334 return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
337 /* Move FD to a number close to the maximum number of file descriptors
338 allowed in the shell process, to avoid the user stepping on it with
339 redirection and causing us extra work. If CHECK_NEW is non-zero,
340 we check whether or not the file descriptors are in use before
341 duplicating FD onto them. MAXFD says where to start checking the
342 file descriptors. If it's less than 20, we get the maximum value
343 available from getdtablesize(2). */
345 move_to_high_fd (fd, check_new, maxfd)
346 int fd, check_new, maxfd;
348 int script_fd, nfds, ignore;
352 nfds = getdtablesize ();
361 for (nfds--; check_new && nfds > 3; nfds--)
362 if (fcntl (nfds, F_GETFD, &ignore) == -1)
365 if (nfds && fd != nfds && (script_fd = dup2 (fd, nfds)) != -1)
367 if (check_new == 0 || fd != fileno (stderr)) /* don't close stderr */
375 /* Return non-zero if the characters from SAMPLE are not all valid
376 characters to be found in the first line of a shell script. We
377 check up to the first newline, or SAMPLE_LEN, whichever comes first.
378 All of the characters must be printable or whitespace. */
381 check_binary_file (sample, sample_len)
388 for (i = 0; i < sample_len; i++)
394 if (ISSPACE (c) == 0 && ISPRINT (c) == 0)
401 /* **************************************************************** */
403 /* Functions to manipulate pathnames */
405 /* **************************************************************** */
407 /* Turn STRING (a pathname) into an absolute pathname, assuming that
408 DOT_PATH contains the symbolic location of `.'. This always
409 returns a new string, even if STRING was an absolute pathname to
412 make_absolute (string, dot_path)
413 char *string, *dot_path;
417 if (dot_path == 0 || ABSPATH(string))
418 result = savestring (string);
420 result = sh_makepath (dot_path, string, 0);
425 /* Return 1 if STRING contains an absolute pathname, else 0. Used by `cd'
426 to decide whether or not to look up a directory name in $CDPATH. */
428 absolute_pathname (string)
431 if (string == 0 || *string == '\0')
437 if (string[0] == '.' && PATHSEP(string[1])) /* . and ./ */
440 if (string[0] == '.' && string[1] == '.' && PATHSEP(string[2])) /* .. and ../ */
446 /* Return 1 if STRING is an absolute program name; it is absolute if it
447 contains any slashes. This is used to decide whether or not to look
450 absolute_program (string)
453 return ((char *)strchr (string, '/') != (char *)NULL);
456 /* Return the `basename' of the pathname in STRING (the stuff after the
457 last '/'). If STRING is not a full pathname, simply return it. */
459 base_pathname (string)
464 if (absolute_pathname (string) == 0)
467 p = (char *)strrchr (string, '/');
468 return (p ? ++p : string);
471 /* Return the full pathname of FILE. Easy. Filenames that begin
472 with a '/' are returned as themselves. Other filenames have
473 the current working directory prepended. A new string is
474 returned in either case. */
481 file = (*file == '~') ? bash_tilde_expand (file) : savestring (file);
486 ret = sh_makepath ((char *)NULL, file, (MP_DOCWD|MP_RMDOT));
492 /* A slightly related function. Get the prettiest name of this
493 directory possible. */
494 static char tdir[PATH_MAX];
496 /* Return a pretty pathname. If the first part of the pathname is
497 the same as $HOME, then replace that with `~'. */
499 polite_directory_format (name)
505 home = get_string_value ("HOME");
506 l = home ? strlen (home) : 0;
507 if (l > 1 && strncmp (home, name, l) == 0 && (!name[l] || name[l] == '/'))
509 strncpy (tdir + 1, name + l, sizeof(tdir) - 2);
511 tdir[sizeof(tdir) - 1] = '\0';
518 /* Given a string containing units of information separated by colons,
519 return the next one pointed to by (P_INDEX), or NULL if there are no more.
520 Advance (P_INDEX) to the character after the colon. */
522 extract_colon_unit (string, p_index)
532 len = strlen (string);
534 return ((char *)NULL);
538 /* Each call to this routine leaves the index pointing at a colon if
539 there is more to the path. If I is > 0, then increment past the
540 `:'. If I is 0, then the path has a leading colon. Trailing colons
541 are handled OK by the `else' part of the if statement; an empty
542 string is returned in that case. */
543 if (i && string[i] == ':')
546 for (start = i; string[i] && string[i] != ':'; i++)
555 /* Return "" in the case of a trailing `:'. */
556 value = (char *)xmalloc (1);
560 value = substring (string, start, i);
565 /* **************************************************************** */
567 /* Tilde Initialization and Expansion */
569 /* **************************************************************** */
571 #if defined (PUSHD_AND_POPD)
572 extern char *get_dirstack_from_string __P((char *));
575 /* Reserved for post-bash-2.05a */
576 static char **bash_tilde_prefixes;
577 static char **bash_tilde_suffixes;
579 /* If tilde_expand hasn't been able to expand the text, perhaps it
580 is a special shell expansion. This function is installed as the
581 tilde_expansion_preexpansion_hook. It knows how to expand ~- and ~+.
582 If PUSHD_AND_POPD is defined, ~[+-]N expands to directories from the
585 bash_special_tilde_expansions (text)
590 result = (char *)NULL;
592 if (text[0] == '+' && text[1] == '\0')
593 result = get_string_value ("PWD");
594 else if (text[0] == '-' && text[1] == '\0')
595 result = get_string_value ("OLDPWD");
596 #if defined (PUSHD_AND_POPD)
597 else if (DIGIT (*text) || ((*text == '+' || *text == '-') && DIGIT (text[1])))
598 result = get_dirstack_from_string (text);
601 return (result ? savestring (result) : (char *)NULL);
604 /* Initialize the tilde expander. In Bash, we handle `~-' and `~+', as
605 well as handling special tilde prefixes; `:~" and `=~' are indications
606 that we should do tilde expansion. */
610 static int times_called = 0;
612 /* Tell the tilde expander that we want a crack first. */
613 tilde_expansion_preexpansion_hook = bash_special_tilde_expansions;
615 /* Tell the tilde expander about special strings which start a tilde
616 expansion, and the special strings that end one. Only do this once.
617 tilde_initialize () is called from within bashline_reinitialize (). */
618 if (times_called++ == 0)
620 bash_tilde_prefixes = alloc_array (3);
621 bash_tilde_prefixes[0] = "=~";
622 bash_tilde_prefixes[1] = ":~";
623 bash_tilde_prefixes[2] = (char *)NULL;
625 tilde_additional_prefixes = bash_tilde_prefixes;
627 bash_tilde_suffixes = alloc_array (3);
628 bash_tilde_suffixes[0] = ":";
629 bash_tilde_suffixes[1] = "=~"; /* XXX - ?? */
630 bash_tilde_suffixes[2] = (char *)NULL;
632 tilde_additional_suffixes = bash_tilde_suffixes;
636 /* POSIX.2, 3.6.1: A tilde-prefix consists of an unquoted tilde character
637 at the beginning of the word, followed by all of the characters preceding
638 the first unquoted slash in the word, or all the characters in the word
639 if there is no slash...If none of the characters in the tilde-prefix are
640 quoted, the characters in the tilde-prefix following the tilde shell be
641 treated as a possible login name. */
643 #define TILDE_END(c) ((c) == '\0' || (c) == '/' || (c) == ':')
646 unquoted_tilde_word (s)
651 for (r = s; TILDE_END(*r) == 0; r++)
664 /* Tilde-expand S by running it through the tilde expansion library. */
666 bash_tilde_expand (s)
672 old_immed = interrupt_immediately;
673 interrupt_immediately = 1;
674 r = (*s == '~') ? unquoted_tilde_word (s) : 1;
675 ret = r ? tilde_expand (s) : savestring (s);
676 interrupt_immediately = old_immed;
680 /* **************************************************************** */
682 /* Functions to manipulate and search the group list */
684 /* **************************************************************** */
686 static int ngroups, maxgroups;
688 /* The set of groups that this user is a member of. */
689 static GETGROUPS_T *group_array = (GETGROUPS_T *)NULL;
691 #if !defined (NOGROUP)
692 # define NOGROUP (gid_t) -1
695 #if defined (HAVE_SYSCONF) && defined (_SC_NGROUPS_MAX)
696 # define getmaxgroups() sysconf(_SC_NGROUPS_MAX)
698 # if defined (NGROUPS_MAX)
699 # define getmaxgroups() NGROUPS_MAX
700 # else /* !NGROUPS_MAX */
701 # if defined (NGROUPS)
702 # define getmaxgroups() NGROUPS
703 # else /* !NGROUPS */
704 # define getmaxgroups() 64
705 # endif /* !NGROUPS */
706 # endif /* !NGROUPS_MAX */
707 #endif /* !HAVE_SYSCONF || !SC_NGROUPS_MAX */
710 initialize_group_array ()
715 maxgroups = getmaxgroups ();
718 group_array = (GETGROUPS_T *)xrealloc (group_array, maxgroups * sizeof (GETGROUPS_T));
720 #if defined (HAVE_GETGROUPS)
721 ngroups = getgroups (maxgroups, group_array);
724 /* If getgroups returns nothing, or the OS does not support getgroups(),
725 make sure the groups array includes at least the current gid. */
728 group_array[0] = current_user.gid;
732 /* If the primary group is not in the groups array, add it as group_array[0]
733 and shuffle everything else up 1, if there's room. */
734 for (i = 0; i < ngroups; i++)
735 if (current_user.gid == (gid_t)group_array[i])
737 if (i == ngroups && ngroups < maxgroups)
739 for (i = ngroups; i > 0; i--)
740 group_array[i] = group_array[i - 1];
741 group_array[0] = current_user.gid;
745 /* If the primary group is not group_array[0], swap group_array[0] and
746 whatever the current group is. The vast majority of systems should
747 not need this; a notable exception is Linux. */
748 if (group_array[0] != current_user.gid)
750 for (i = 0; i < ngroups; i++)
751 if (group_array[i] == current_user.gid)
755 group_array[i] = group_array[0];
756 group_array[0] = current_user.gid;
761 /* Return non-zero if GID is one that we have in our groups list. */
763 #if defined (__STDC__) || defined ( _MINIX)
764 group_member (gid_t gid)
768 #endif /* !__STDC__ && !_MINIX */
770 #if defined (HAVE_GETGROUPS)
774 /* Short-circuit if possible, maybe saving a call to getgroups(). */
775 if (gid == current_user.gid || gid == current_user.egid)
778 #if defined (HAVE_GETGROUPS)
780 initialize_group_array ();
782 /* In case of error, the user loses. */
786 /* Search through the list looking for GID. */
787 for (i = 0; i < ngroups; i++)
788 if (gid == (gid_t)group_array[i])
799 static char **group_vector = (char **)NULL;
811 initialize_group_array ();
817 return (char **)NULL;
820 group_vector = alloc_array (ngroups);
821 for (i = 0; i < ngroups; i++)
823 nbuf = itos (group_array[i]);
824 group_vector[i] = nbuf;
833 get_group_array (ngp)
837 static int *group_iarray = (int *)NULL;
843 return (group_iarray);
847 initialize_group_array ();
856 group_iarray = (int *)xmalloc (ngroups * sizeof (int));
857 for (i = 0; i < ngroups; i++)
858 group_iarray[i] = (int)group_array[i];