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"
42 #include <tilde/tilde.h>
48 extern int expand_aliases
;
49 extern int interrupt_immediately
;
50 extern int interactive_comments
;
51 extern int check_hashed_filenames
;
52 extern int source_uses_path
;
53 extern int source_searches_cwd
;
55 static char *bash_special_tilde_expansions
__P((char *));
56 static int unquoted_tilde_word
__P((const char *));
57 static void initialize_group_array
__P((void));
59 /* A standard error message to use when getcwd() returns NULL. */
60 char *bash_getcwd_errstr
= N_("getcwd: cannot access parent directories");
62 /* Do whatever is necessary to initialize `Posix mode'. */
67 /* Things that should be turned on when posix mode is enabled. */
70 interactive_comments
= source_uses_path
= expand_aliases
= 1;
73 /* Things that should be turned on when posix mode is disabled. */
76 source_searches_cwd
= 1;
77 expand_aliases
= interactive_shell
;
81 /* **************************************************************** */
83 /* Functions to convert to and from and display non-standard types */
85 /* **************************************************************** */
87 #if defined (RLIMTYPE)
89 string_to_rlimtype (s
)
97 while (s
&& *s
&& whitespace (*s
))
99 if (*s
== '-' || *s
== '+')
104 for ( ; s
&& *s
&& DIGIT (*s
); s
++)
105 ret
= (ret
* 10) + TODIGIT (*s
);
106 return (neg
? -ret
: ret
);
110 print_rlimtype (n
, addnl
)
114 char s
[INT_STRLEN_BOUND (RLIMTYPE
) + 1], *p
;
123 while ((n
/= 10) != 0);
131 while ((n
/= 10) != 0);
134 printf ("%s%s", p
, 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
++)
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
162 legal_number (string
, result
)
173 value
= strtoimax (string
, &ep
, 10);
175 return 0; /* errno is set on overflow or underflow */
177 /* Skip any trailing whitespace, since strtoimax does not. */
178 while (whitespace (*ep
))
181 /* If *string is not '\0' but *ep is '\0' on return, the entire string
183 if (string
&& *string
&& *ep
== '\0')
187 /* The SunOS4 implementation of strtol() will happily ignore
188 overflow conditions, so this cannot do overflow correctly
196 /* Return 1 if this token is a legal shell `identifier'; that is, it consists
197 solely of letters, digits, and underscores, and does not begin with a
200 legal_identifier (name
)
206 if (!name
|| !(c
= *name
) || (legal_variable_starter (c
) == 0))
209 for (s
= name
+ 1; (c
= *s
) != 0; s
++)
211 if (legal_variable_char (c
) == 0)
217 /* Make sure that WORD is a valid shell identifier, i.e.
218 does not contain a dollar sign, nor is quoted in any way. Nor
219 does it consist of all digits. If CHECK_WORD is non-zero,
220 the word is checked to ensure that it consists of only letters,
221 digits, and underscores. */
223 check_identifier (word
, check_word
)
227 if ((word
->flags
& (W_HASDOLLAR
|W_QUOTED
)) || all_digits (word
->word
))
229 internal_error (_("`%s': not a valid identifier"), word
->word
);
232 else if (check_word
&& legal_identifier (word
->word
) == 0)
234 internal_error (_("`%s': not a valid identifier"), word
->word
);
241 /* Return 1 if STRING comprises a valid alias name. The shell accepts
242 essentially all characters except those which must be quoted to the
243 parser (which disqualifies them from alias expansion anyway) and `/'. */
245 legal_alias_name (string
, flags
)
251 for (s
= string
; *s
; s
++)
252 if (shellbreak (*s
) || shellxquote (*s
) || shellexp (*s
) || (*s
== '/'))
257 /* Returns non-zero if STRING is an assignment statement. The returned value
258 is the index of the `=' sign. */
260 assignment (string
, flags
)
264 register unsigned char c
;
265 register int newi
, indx
;
267 c
= string
[indx
= 0];
269 #if defined (ARRAY_VARS)
270 if ((legal_variable_starter (c
) == 0) && (flags
&& c
!= '[')) /* ] */
272 if (legal_variable_starter (c
) == 0)
276 while (c
= string
[indx
])
278 /* The following is safe. Note that '=' at the start of a word
279 is not an assignment statement. */
283 #if defined (ARRAY_VARS)
286 newi
= skipsubscript (string
, indx
);
287 if (string
[newi
++] != ']')
289 return ((string
[newi
] == '=') ? newi
: 0);
291 #endif /* ARRAY_VARS */
293 /* Variable names in assignment statements may contain only letters,
295 if (legal_variable_char (c
) == 0)
303 /* **************************************************************** */
305 /* Functions to manage files and file descriptors */
307 /* **************************************************************** */
309 /* A function to unset no-delay mode on a file descriptor. Used in shell.c
310 to unset it on the fd passed as stdin. Should be called on stdin if
311 readline gets an EAGAIN or EWOULDBLOCK when trying to read input. */
313 #if !defined (O_NDELAY)
314 # if defined (FNDELAY)
315 # define O_NDELAY FNDELAY
317 #endif /* O_NDELAY */
319 /* Make sure no-delay mode is not set on file descriptor FD. */
321 sh_unset_nodelay_mode (fd
)
326 if ((flags
= fcntl (fd
, F_GETFL
, 0)) < 0)
331 /* This is defined to O_NDELAY in filecntl.h if O_NONBLOCK is not present
332 and O_NDELAY is defined. */
334 bflags
|= O_NONBLOCK
;
344 return (fcntl (fd
, F_SETFL
, flags
));
350 /* Return 1 if file descriptor FD is valid; 0 otherwise. */
355 return (fcntl (fd
, F_GETFD
, 0) >= 0);
358 /* There is a bug in the NeXT 2.1 rlogind that causes opens
359 of /dev/tty to fail. */
361 #if defined (__BEOS__)
362 /* On BeOS, opening in non-blocking mode exposes a bug in BeOS, so turn it
363 into a no-op. This should probably go away in the future. */
365 # define O_NONBLOCK 0
366 #endif /* __BEOS__ */
374 tty_fd
= open ("/dev/tty", O_RDWR
|O_NONBLOCK
);
378 tty
= (char *)ttyname (fileno (stdin
));
381 tty_fd
= open (tty
, O_RDWR
|O_NONBLOCK
);
386 /* Return 1 if PATH1 and PATH2 are the same file. This is kind of
387 expensive. If non-NULL STP1 and STP2 point to stat structures
388 corresponding to PATH1 and PATH2, respectively. */
390 same_file (path1
, path2
, stp1
, stp2
)
392 struct stat
*stp1
, *stp2
;
394 struct stat st1
, st2
;
398 if (stat (path1
, &st1
) != 0)
405 if (stat (path2
, &st2
) != 0)
410 return ((stp1
->st_dev
== stp2
->st_dev
) && (stp1
->st_ino
== stp2
->st_ino
));
413 /* Move FD to a number close to the maximum number of file descriptors
414 allowed in the shell process, to avoid the user stepping on it with
415 redirection and causing us extra work. If CHECK_NEW is non-zero,
416 we check whether or not the file descriptors are in use before
417 duplicating FD onto them. MAXFD says where to start checking the
418 file descriptors. If it's less than 20, we get the maximum value
419 available from getdtablesize(2). */
421 move_to_high_fd (fd
, check_new
, maxfd
)
422 int fd
, check_new
, maxfd
;
424 int script_fd
, nfds
, ignore
;
428 nfds
= getdtablesize ();
431 if (nfds
> HIGH_FD_MAX
)
432 nfds
= HIGH_FD_MAX
; /* reasonable maximum */
437 for (nfds
--; check_new
&& nfds
> 3; nfds
--)
438 if (fcntl (nfds
, F_GETFD
, &ignore
) == -1)
441 if (nfds
> 3 && fd
!= nfds
&& (script_fd
= dup2 (fd
, nfds
)) != -1)
443 if (check_new
== 0 || fd
!= fileno (stderr
)) /* don't close stderr */
448 /* OK, we didn't find one less than our artificial maximum; return the
449 original file descriptor. */
453 /* Return non-zero if the characters from SAMPLE are not all valid
454 characters to be found in the first line of a shell script. We
455 check up to the first newline, or SAMPLE_LEN, whichever comes first.
456 All of the characters must be printable or whitespace. */
459 check_binary_file (sample
, sample_len
)
466 for (i
= 0; i
< sample_len
; i
++)
472 if (ISSPACE (c
) == 0 && ISPRINT (c
) == 0)
479 /* **************************************************************** */
481 /* Functions to inspect pathnames */
483 /* **************************************************************** */
491 return ((stat (fn
, &sb
) == 0) && S_ISDIR (sb
.st_mode
));
498 return (file_isdir (fn
) && test_eaccess (fn
, W_OK
) == 0);
502 /* **************************************************************** */
504 /* Functions to manipulate pathnames */
506 /* **************************************************************** */
508 /* Turn STRING (a pathname) into an absolute pathname, assuming that
509 DOT_PATH contains the symbolic location of `.'. This always
510 returns a new string, even if STRING was an absolute pathname to
513 make_absolute (string
, dot_path
)
514 char *string
, *dot_path
;
518 if (dot_path
== 0 || ABSPATH(string
))
521 char pathbuf
[PATH_MAX
+ 1];
523 cygwin_conv_to_full_posix_path (string
, pathbuf
);
524 result
= savestring (pathbuf
);
527 result
= savestring (string
);
530 result
= sh_makepath (dot_path
, string
, 0);
535 /* Return 1 if STRING contains an absolute pathname, else 0. Used by `cd'
536 to decide whether or not to look up a directory name in $CDPATH. */
538 absolute_pathname (string
)
541 if (string
== 0 || *string
== '\0')
547 if (string
[0] == '.' && PATHSEP(string
[1])) /* . and ./ */
550 if (string
[0] == '.' && string
[1] == '.' && PATHSEP(string
[2])) /* .. and ../ */
556 /* Return 1 if STRING is an absolute program name; it is absolute if it
557 contains any slashes. This is used to decide whether or not to look
560 absolute_program (string
)
563 return ((char *)xstrchr (string
, '/') != (char *)NULL
);
566 /* Return the `basename' of the pathname in STRING (the stuff after the
567 last '/'). If STRING is not a full pathname, simply return it. */
569 base_pathname (string
)
574 if (absolute_pathname (string
) == 0)
577 p
= (char *)strrchr (string
, '/');
578 return (p
? ++p
: string
);
581 /* Return the full pathname of FILE. Easy. Filenames that begin
582 with a '/' are returned as themselves. Other filenames have
583 the current working directory prepended. A new string is
584 returned in either case. */
591 file
= (*file
== '~') ? bash_tilde_expand (file
, 0) : savestring (file
);
596 ret
= sh_makepath ((char *)NULL
, file
, (MP_DOCWD
|MP_RMDOT
));
602 /* A slightly related function. Get the prettiest name of this
603 directory possible. */
604 static char tdir
[PATH_MAX
];
606 /* Return a pretty pathname. If the first part of the pathname is
607 the same as $HOME, then replace that with `~'. */
609 polite_directory_format (name
)
615 home
= get_string_value ("HOME");
616 l
= home
? strlen (home
) : 0;
617 if (l
> 1 && strncmp (home
, name
, l
) == 0 && (!name
[l
] || name
[l
] == '/'))
619 strncpy (tdir
+ 1, name
+ l
, sizeof(tdir
) - 2);
621 tdir
[sizeof(tdir
) - 1] = '\0';
628 /* Given a string containing units of information separated by colons,
629 return the next one pointed to by (P_INDEX), or NULL if there are no more.
630 Advance (P_INDEX) to the character after the colon. */
632 extract_colon_unit (string
, p_index
)
642 len
= strlen (string
);
644 return ((char *)NULL
);
648 /* Each call to this routine leaves the index pointing at a colon if
649 there is more to the path. If I is > 0, then increment past the
650 `:'. If I is 0, then the path has a leading colon. Trailing colons
651 are handled OK by the `else' part of the if statement; an empty
652 string is returned in that case. */
653 if (i
&& string
[i
] == ':')
656 for (start
= i
; string
[i
] && string
[i
] != ':'; i
++)
665 /* Return "" in the case of a trailing `:'. */
666 value
= (char *)xmalloc (1);
670 value
= substring (string
, start
, i
);
675 /* **************************************************************** */
677 /* Tilde Initialization and Expansion */
679 /* **************************************************************** */
681 #if defined (PUSHD_AND_POPD)
682 extern char *get_dirstack_from_string
__P((char *));
685 static char **bash_tilde_prefixes
;
686 static char **bash_tilde_suffixes
;
688 /* If tilde_expand hasn't been able to expand the text, perhaps it
689 is a special shell expansion. This function is installed as the
690 tilde_expansion_preexpansion_hook. It knows how to expand ~- and ~+.
691 If PUSHD_AND_POPD is defined, ~[+-]N expands to directories from the
694 bash_special_tilde_expansions (text
)
699 result
= (char *)NULL
;
701 if (text
[0] == '+' && text
[1] == '\0')
702 result
= get_string_value ("PWD");
703 else if (text
[0] == '-' && text
[1] == '\0')
704 result
= get_string_value ("OLDPWD");
705 #if defined (PUSHD_AND_POPD)
706 else if (DIGIT (*text
) || ((*text
== '+' || *text
== '-') && DIGIT (text
[1])))
707 result
= get_dirstack_from_string (text
);
710 return (result
? savestring (result
) : (char *)NULL
);
713 /* Initialize the tilde expander. In Bash, we handle `~-' and `~+', as
714 well as handling special tilde prefixes; `:~" and `=~' are indications
715 that we should do tilde expansion. */
719 static int times_called
= 0;
721 /* Tell the tilde expander that we want a crack first. */
722 tilde_expansion_preexpansion_hook
= bash_special_tilde_expansions
;
724 /* Tell the tilde expander about special strings which start a tilde
725 expansion, and the special strings that end one. Only do this once.
726 tilde_initialize () is called from within bashline_reinitialize (). */
727 if (times_called
++ == 0)
729 bash_tilde_prefixes
= strvec_create (3);
730 bash_tilde_prefixes
[0] = "=~";
731 bash_tilde_prefixes
[1] = ":~";
732 bash_tilde_prefixes
[2] = (char *)NULL
;
734 tilde_additional_prefixes
= bash_tilde_prefixes
;
736 bash_tilde_suffixes
= strvec_create (3);
737 bash_tilde_suffixes
[0] = ":";
738 bash_tilde_suffixes
[1] = "=~"; /* XXX - ?? */
739 bash_tilde_suffixes
[2] = (char *)NULL
;
741 tilde_additional_suffixes
= bash_tilde_suffixes
;
745 /* POSIX.2, 3.6.1: A tilde-prefix consists of an unquoted tilde character
746 at the beginning of the word, followed by all of the characters preceding
747 the first unquoted slash in the word, or all the characters in the word
748 if there is no slash...If none of the characters in the tilde-prefix are
749 quoted, the characters in the tilde-prefix following the tilde shell be
750 treated as a possible login name. */
752 #define TILDE_END(c) ((c) == '\0' || (c) == '/' || (c) == ':')
755 unquoted_tilde_word (s
)
760 for (r
= s
; TILDE_END(*r
) == 0; r
++)
773 /* Tilde-expand S by running it through the tilde expansion library.
774 ASSIGN_P is 1 if this is a variable assignment, so the alternate
775 tilde prefixes should be enabled (`=~' and `:~', see above). */
777 bash_tilde_expand (s
, assign_p
)
784 old_immed
= interrupt_immediately
;
785 interrupt_immediately
= 1;
786 tilde_additional_prefixes
= assign_p
? bash_tilde_prefixes
: (char **)0;
787 r
= (*s
== '~') ? unquoted_tilde_word (s
) : 1;
788 ret
= r
? tilde_expand (s
) : savestring (s
);
789 interrupt_immediately
= old_immed
;
793 /* **************************************************************** */
795 /* Functions to manipulate and search the group list */
797 /* **************************************************************** */
799 static int ngroups
, maxgroups
;
801 /* The set of groups that this user is a member of. */
802 static GETGROUPS_T
*group_array
= (GETGROUPS_T
*)NULL
;
804 #if !defined (NOGROUP)
805 # define NOGROUP (gid_t) -1
809 initialize_group_array ()
814 maxgroups
= getmaxgroups ();
817 group_array
= (GETGROUPS_T
*)xrealloc (group_array
, maxgroups
* sizeof (GETGROUPS_T
));
819 #if defined (HAVE_GETGROUPS)
820 ngroups
= getgroups (maxgroups
, group_array
);
823 /* If getgroups returns nothing, or the OS does not support getgroups(),
824 make sure the groups array includes at least the current gid. */
827 group_array
[0] = current_user
.gid
;
831 /* If the primary group is not in the groups array, add it as group_array[0]
832 and shuffle everything else up 1, if there's room. */
833 for (i
= 0; i
< ngroups
; i
++)
834 if (current_user
.gid
== (gid_t
)group_array
[i
])
836 if (i
== ngroups
&& ngroups
< maxgroups
)
838 for (i
= ngroups
; i
> 0; i
--)
839 group_array
[i
] = group_array
[i
- 1];
840 group_array
[0] = current_user
.gid
;
844 /* If the primary group is not group_array[0], swap group_array[0] and
845 whatever the current group is. The vast majority of systems should
846 not need this; a notable exception is Linux. */
847 if (group_array
[0] != current_user
.gid
)
849 for (i
= 0; i
< ngroups
; i
++)
850 if (group_array
[i
] == current_user
.gid
)
854 group_array
[i
] = group_array
[0];
855 group_array
[0] = current_user
.gid
;
860 /* Return non-zero if GID is one that we have in our groups list. */
862 #if defined (__STDC__) || defined ( _MINIX)
863 group_member (gid_t gid
)
867 #endif /* !__STDC__ && !_MINIX */
869 #if defined (HAVE_GETGROUPS)
873 /* Short-circuit if possible, maybe saving a call to getgroups(). */
874 if (gid
== current_user
.gid
|| gid
== current_user
.egid
)
877 #if defined (HAVE_GETGROUPS)
879 initialize_group_array ();
881 /* In case of error, the user loses. */
885 /* Search through the list looking for GID. */
886 for (i
= 0; i
< ngroups
; i
++)
887 if (gid
== (gid_t
)group_array
[i
])
898 static char **group_vector
= (char **)NULL
;
909 initialize_group_array ();
915 return (char **)NULL
;
918 group_vector
= strvec_create (ngroups
);
919 for (i
= 0; i
< ngroups
; i
++)
920 group_vector
[i
] = itos (group_array
[i
]);
928 get_group_array (ngp
)
932 static int *group_iarray
= (int *)NULL
;
938 return (group_iarray
);
942 initialize_group_array ();
951 group_iarray
= (int *)xmalloc (ngroups
* sizeof (int));
952 for (i
= 0; i
< ngroups
; i
++)
953 group_iarray
[i
] = (int)group_array
[i
];