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)
40 #include <tilde/tilde.h>
49 # define to_upper(c) (islower(c) ? toupper(c) : (c))
50 # define to_lower(c) (isupper(c) ? tolower(c) : (c))
53 extern int interactive_shell
, expand_aliases
;
54 extern int interrupt_immediately
;
55 extern int interactive_comments
;
56 extern int check_hashed_filenames
;
57 extern int source_uses_path
;
58 extern int source_searches_cwd
;
60 /* A standard error message to use when getcwd() returns NULL. */
61 char *bash_getcwd_errstr
= "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) + digit_value (*s
);
107 return (neg
? -ret
: ret
);
111 print_rlimtype (n
, addnl
)
115 char s
[sizeof (RLIMTYPE
) * 3 + 1];
120 printf ("0%s", addnl
? "\n" : "");
130 len
= sizeof (RLIMTYPE
) * 3 + 1;
132 for ( ; n
!= 0; n
/= 10)
133 s
[--len
] = n
% 10 + '0';
134 printf ("%s%s", s
+ len
, addnl
? "\n" : "");
136 #endif /* RLIMTYPE */
138 /* **************************************************************** */
140 /* Input Validation Functions */
142 /* **************************************************************** */
144 /* Return non-zero if all of the characters in STRING are digits. */
151 for (s
= string
; *s
; s
++)
152 if (isdigit (*s
) == 0)
158 /* Return non-zero if the characters pointed to by STRING constitute a
159 valid number. Stuff the converted number into RESULT if RESULT is
160 a non-null pointer to a long. */
162 legal_number (string
, result
)
172 value
= strtol (string
, &ep
, 10);
174 /* Skip any trailing whitespace, since strtol does not. */
175 while (whitespace (*ep
))
178 /* If *string is not '\0' but *ep is '\0' on return, the entire string
180 if (string
&& *string
&& *ep
== '\0')
184 /* The SunOS4 implementation of strtol() will happily ignore
185 overflow conditions, so this cannot do overflow correctly
193 /* Return 1 if this token is a legal shell `identifier'; that is, it consists
194 solely of letters, digits, and underscores, and does not begin with a
197 legal_identifier (name
)
202 if (!name
|| !*name
|| (legal_variable_starter (*name
) == 0))
205 for (s
= name
+ 1; *s
; s
++)
207 if (legal_variable_char (*s
) == 0)
213 /* Make sure that WORD is a valid shell identifier, i.e.
214 does not contain a dollar sign, nor is quoted in any way. Nor
215 does it consist of all digits. If CHECK_WORD is non-zero,
216 the word is checked to ensure that it consists of only letters,
217 digits, and underscores. */
219 check_identifier (word
, check_word
)
223 if ((word
->flags
& (W_HASDOLLAR
|W_QUOTED
)) || all_digits (word
->word
))
225 internal_error ("`%s': not a valid identifier", word
->word
);
228 else if (check_word
&& legal_identifier (word
->word
) == 0)
230 internal_error ("`%s': not a valid identifier", word
->word
);
237 /* **************************************************************** */
239 /* Functions to manage files and file descriptors */
241 /* **************************************************************** */
243 /* A function to unset no-delay mode on a file descriptor. Used in shell.c
244 to unset it on the fd passed as stdin. Should be called on stdin if
245 readline gets an EAGAIN or EWOULDBLOCK when trying to read input. */
247 #if !defined (O_NDELAY)
248 # if defined (FNDELAY)
249 # define O_NDELAY FNDELAY
251 #endif /* O_NDELAY */
253 /* Make sure no-delay mode is not set on file descriptor FD. */
255 sh_unset_nodelay_mode (fd
)
260 if ((flags
= fcntl (fd
, F_GETFL
, 0)) < 0)
265 /* This is defined to O_NDELAY in filecntl.h if O_NONBLOCK is not present
266 and O_NDELAY is defined. */
268 bflags
|= O_NONBLOCK
;
278 return (fcntl (fd
, F_SETFL
, flags
));
284 /* There is a bug in the NeXT 2.1 rlogind that causes opens
285 of /dev/tty to fail. */
287 #if defined (__BEOS__)
288 /* On BeOS, opening in non-blocking mode exposes a bug in BeOS, so turn it
289 into a no-op. This should probably go away in the future. */
291 # define O_NONBLOCK 0
292 #endif /* __BEOS__ */
300 tty_fd
= open ("/dev/tty", O_RDWR
|O_NONBLOCK
);
304 tty
= (char *)ttyname (fileno (stdin
));
307 tty_fd
= open (tty
, O_RDWR
|O_NONBLOCK
);
312 /* Return 1 if PATH1 and PATH2 are the same file. This is kind of
313 expensive. If non-NULL STP1 and STP2 point to stat structures
314 corresponding to PATH1 and PATH2, respectively. */
316 same_file (path1
, path2
, stp1
, stp2
)
318 struct stat
*stp1
, *stp2
;
320 struct stat st1
, st2
;
324 if (stat (path1
, &st1
) != 0)
331 if (stat (path2
, &st2
) != 0)
336 return ((stp1
->st_dev
== stp2
->st_dev
) && (stp1
->st_ino
== stp2
->st_ino
));
339 /* Move FD to a number close to the maximum number of file descriptors
340 allowed in the shell process, to avoid the user stepping on it with
341 redirection and causing us extra work. If CHECK_NEW is non-zero,
342 we check whether or not the file descriptors are in use before
343 duplicating FD onto them. MAXFD says where to start checking the
344 file descriptors. If it's less than 20, we get the maximum value
345 available from getdtablesize(2). */
347 move_to_high_fd (fd
, check_new
, maxfd
)
348 int fd
, check_new
, maxfd
;
350 int script_fd
, nfds
, ignore
;
354 nfds
= getdtablesize ();
363 for (nfds
--; check_new
&& nfds
> 3; nfds
--)
364 if (fcntl (nfds
, F_GETFD
, &ignore
) == -1)
367 if (nfds
&& fd
!= nfds
&& (script_fd
= dup2 (fd
, nfds
)) != -1)
369 if (check_new
== 0 || fd
!= fileno (stderr
)) /* don't close stderr */
377 /* Return non-zero if the characters from SAMPLE are not all valid
378 characters to be found in the first line of a shell script. We
379 check up to the first newline, or SAMPLE_LEN, whichever comes first.
380 All of the characters must be printable or whitespace. */
382 #if !defined (isspace)
383 #define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
386 #if !defined (isprint)
387 #define isprint(c) (isletter(c) || digit(c) || ispunct(c))
391 check_binary_file (sample
, sample_len
)
392 unsigned char *sample
;
397 for (i
= 0; i
< sample_len
; i
++)
399 if (sample
[i
] == '\n')
402 if (isspace (sample
[i
]) == 0 && isprint (sample
[i
]) == 0)
409 /* **************************************************************** */
411 /* Functions to manipulate pathnames */
413 /* **************************************************************** */
415 /* Turn STRING (a pathname) into an absolute pathname, assuming that
416 DOT_PATH contains the symbolic location of `.'. This always
417 returns a new string, even if STRING was an absolute pathname to
420 make_absolute (string
, dot_path
)
421 char *string
, *dot_path
;
425 if (dot_path
== 0 || ABSPATH(string
))
426 result
= savestring (string
);
428 result
= sh_makepath (dot_path
, string
, 0);
433 /* Return 1 if STRING contains an absolute pathname, else 0. Used by `cd'
434 to decide whether or not to look up a directory name in $CDPATH. */
436 absolute_pathname (string
)
439 if (string
== 0 || *string
== '\0')
445 if (string
[0] == '.' && PATHSEP(string
[1])) /* . and ./ */
448 if (string
[0] == '.' && string
[1] == '.' && PATHSEP(string
[2])) /* .. and ../ */
454 /* Return 1 if STRING is an absolute program name; it is absolute if it
455 contains any slashes. This is used to decide whether or not to look
458 absolute_program (string
)
461 return ((char *)strchr (string
, '/') != (char *)NULL
);
464 /* Return the `basename' of the pathname in STRING (the stuff after the
465 last '/'). If STRING is not a full pathname, simply return it. */
467 base_pathname (string
)
472 if (absolute_pathname (string
) == 0)
475 p
= (char *)strrchr (string
, '/');
476 return (p
? ++p
: string
);
479 /* Return the full pathname of FILE. Easy. Filenames that begin
480 with a '/' are returned as themselves. Other filenames have
481 the current working directory prepended. A new string is
482 returned in either case. */
489 file
= (*file
== '~') ? bash_tilde_expand (file
) : savestring (file
);
494 ret
= sh_makepath ((char *)NULL
, file
, (MP_DOCWD
|MP_RMDOT
));
500 /* A slightly related function. Get the prettiest name of this
501 directory possible. */
502 static char tdir
[PATH_MAX
];
504 /* Return a pretty pathname. If the first part of the pathname is
505 the same as $HOME, then replace that with `~'. */
507 polite_directory_format (name
)
513 home
= get_string_value ("HOME");
514 l
= home
? strlen (home
) : 0;
515 if (l
> 1 && strncmp (home
, name
, l
) == 0 && (!name
[l
] || name
[l
] == '/'))
517 strncpy (tdir
+ 1, name
+ l
, sizeof(tdir
) - 2);
519 tdir
[sizeof(tdir
) - 1] = '\0';
526 /* Given a string containing units of information separated by colons,
527 return the next one pointed to by (P_INDEX), or NULL if there are no more.
528 Advance (P_INDEX) to the character after the colon. */
530 extract_colon_unit (string
, p_index
)
540 len
= strlen (string
);
542 return ((char *)NULL
);
546 /* Each call to this routine leaves the index pointing at a colon if
547 there is more to the path. If I is > 0, then increment past the
548 `:'. If I is 0, then the path has a leading colon. Trailing colons
549 are handled OK by the `else' part of the if statement; an empty
550 string is returned in that case. */
551 if (i
&& string
[i
] == ':')
554 for (start
= i
; string
[i
] && string
[i
] != ':'; i
++)
563 /* Return "" in the case of a trailing `:'. */
568 value
= substring (string
, start
, i
);
573 /* **************************************************************** */
575 /* Tilde Initialization and Expansion */
577 /* **************************************************************** */
579 #if defined (PUSHD_AND_POPD)
580 extern char *get_dirstack_from_string
__P((char *));
583 /* If tilde_expand hasn't been able to expand the text, perhaps it
584 is a special shell expansion. This function is installed as the
585 tilde_expansion_preexpansion_hook. It knows how to expand ~- and ~+.
586 If PUSHD_AND_POPD is defined, ~[+-]N expands to directories from the
589 bash_special_tilde_expansions (text
)
594 result
= (char *)NULL
;
596 if (text
[0] == '+' && text
[1] == '\0')
597 result
= get_string_value ("PWD");
598 else if (text
[0] == '-' && text
[1] == '\0')
599 result
= get_string_value ("OLDPWD");
600 #if defined (PUSHD_AND_POPD)
601 else if (isdigit (*text
) || ((*text
== '+' || *text
== '-') && isdigit (text
[1])))
602 result
= get_dirstack_from_string (text
);
605 return (result
? savestring (result
) : (char *)NULL
);
608 /* Initialize the tilde expander. In Bash, we handle `~-' and `~+', as
609 well as handling special tilde prefixes; `:~" and `=~' are indications
610 that we should do tilde expansion. */
614 static int times_called
= 0;
616 /* Tell the tilde expander that we want a crack first. */
617 tilde_expansion_preexpansion_hook
= (CPFunction
*)bash_special_tilde_expansions
;
619 /* Tell the tilde expander about special strings which start a tilde
620 expansion, and the special strings that end one. Only do this once.
621 tilde_initialize () is called from within bashline_reinitialize (). */
622 if (times_called
++ == 0)
624 tilde_additional_prefixes
= alloc_array (3);
625 tilde_additional_prefixes
[0] = "=~";
626 tilde_additional_prefixes
[1] = ":~";
627 tilde_additional_prefixes
[2] = (char *)NULL
;
629 tilde_additional_suffixes
= alloc_array (3);
630 tilde_additional_suffixes
[0] = ":";
631 tilde_additional_suffixes
[1] = "=~";
632 tilde_additional_suffixes
[2] = (char *)NULL
;
637 bash_tilde_expand (s
)
643 old_immed
= interrupt_immediately
;
644 interrupt_immediately
= 1;
645 ret
= tilde_expand (s
);
646 interrupt_immediately
= old_immed
;
650 /* **************************************************************** */
652 /* Functions to manipulate and search the group list */
654 /* **************************************************************** */
656 static int ngroups
, maxgroups
;
658 /* The set of groups that this user is a member of. */
659 static GETGROUPS_T
*group_array
= (GETGROUPS_T
*)NULL
;
661 #if !defined (NOGROUP)
662 # define NOGROUP (gid_t) -1
665 #if defined (HAVE_SYSCONF) && defined (_SC_NGROUPS_MAX)
666 # define getmaxgroups() sysconf(_SC_NGROUPS_MAX)
668 # if defined (NGROUPS_MAX)
669 # define getmaxgroups() NGROUPS_MAX
670 # else /* !NGROUPS_MAX */
671 # if defined (NGROUPS)
672 # define getmaxgroups() NGROUPS
673 # else /* !NGROUPS */
674 # define getmaxgroups() 64
675 # endif /* !NGROUPS */
676 # endif /* !NGROUPS_MAX */
677 #endif /* !HAVE_SYSCONF || !SC_NGROUPS_MAX */
680 initialize_group_array ()
685 maxgroups
= getmaxgroups ();
688 group_array
= (GETGROUPS_T
*)xrealloc (group_array
, maxgroups
* sizeof (GETGROUPS_T
));
690 #if defined (HAVE_GETGROUPS)
691 ngroups
= getgroups (maxgroups
, group_array
);
694 /* If getgroups returns nothing, or the OS does not support getgroups(),
695 make sure the groups array includes at least the current gid. */
698 group_array
[0] = current_user
.gid
;
702 /* If the primary group is not in the groups array, add it as group_array[0]
703 and shuffle everything else up 1, if there's room. */
704 for (i
= 0; i
< ngroups
; i
++)
705 if (current_user
.gid
== (gid_t
)group_array
[i
])
707 if (i
== ngroups
&& ngroups
< maxgroups
)
709 for (i
= ngroups
; i
> 0; i
--)
710 group_array
[i
] = group_array
[i
- 1];
711 group_array
[0] = current_user
.gid
;
715 /* If the primary group is not group_array[0], swap group_array[0] and
716 whatever the current group is. The vast majority of systems should
717 not need this; a notable exception is Linux. */
718 if (group_array
[0] != current_user
.gid
)
720 for (i
= 0; i
< ngroups
; i
++)
721 if (group_array
[i
] == current_user
.gid
)
725 group_array
[i
] = group_array
[0];
726 group_array
[0] = current_user
.gid
;
731 /* Return non-zero if GID is one that we have in our groups list. */
733 #if defined (__STDC__) || defined ( _MINIX)
734 group_member (gid_t gid
)
738 #endif /* !__STDC__ && !_MINIX */
740 #if defined (HAVE_GETGROUPS)
744 /* Short-circuit if possible, maybe saving a call to getgroups(). */
745 if (gid
== current_user
.gid
|| gid
== current_user
.egid
)
748 #if defined (HAVE_GETGROUPS)
750 initialize_group_array ();
752 /* In case of error, the user loses. */
756 /* Search through the list looking for GID. */
757 for (i
= 0; i
< ngroups
; i
++)
758 if (gid
== (gid_t
)group_array
[i
])
769 static char **group_vector
= (char **)NULL
;
781 initialize_group_array ();
787 return (char **)NULL
;
790 group_vector
= alloc_array (ngroups
);
791 for (i
= 0; i
< ngroups
; i
++)
793 nbuf
= itos ((int)group_array
[i
]);
794 group_vector
[i
] = nbuf
;
803 get_group_array (ngp
)
807 static int *group_iarray
= (int *)NULL
;
813 return (group_iarray
);
817 initialize_group_array ();
826 group_iarray
= (int *)xmalloc (ngroups
* sizeof (int));
827 for (i
= 0; i
< ngroups
; i
++)
828 group_iarray
[i
] = (int)group_array
[i
];