]> git.ipfire.org Git - thirdparty/bash.git/blob - general.c
Imported from ../bash-2.05.tar.gz.
[thirdparty/bash.git] / general.c
1 /* general.c -- Stuff that is used by all files. */
2
3 /* Copyright (C) 1987-1999 Free Software Foundation, Inc.
4
5 This file is part of GNU Bash, the Bourne Again SHell.
6
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
10 version.
11
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
15 for more details.
16
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. */
20
21 #include "config.h"
22
23 #include "bashtypes.h"
24 #ifndef _MINIX
25 # include <sys/param.h>
26 #endif
27 #include "posixstat.h"
28
29 #if defined (HAVE_UNISTD_H)
30 # include <unistd.h>
31 #endif
32
33 #include "filecntl.h"
34 #include "bashansi.h"
35 #include <stdio.h>
36 #include <ctype.h>
37 #include <errno.h>
38
39 #include "shell.h"
40 #include <tilde/tilde.h>
41
42 #include "maxpath.h"
43
44 #if !defined (errno)
45 extern int errno;
46 #endif /* !errno */
47
48 #ifndef to_upper
49 # define to_upper(c) (islower(c) ? toupper(c) : (c))
50 # define to_lower(c) (isupper(c) ? tolower(c) : (c))
51 #endif
52
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;
59
60 /* A standard error message to use when getcwd() returns NULL. */
61 char *bash_getcwd_errstr = "getcwd: cannot access parent directories";
62
63 /* Do whatever is necessary to initialize `Posix mode'. */
64 void
65 posix_initialize (on)
66 int on;
67 {
68 /* Things that should be turned on when posix mode is enabled. */
69 if (on != 0)
70 {
71 interactive_comments = source_uses_path = expand_aliases = 1;
72 }
73
74 /* Things that should be turned on when posix mode is disabled. */
75 if (on == 0)
76 {
77 source_searches_cwd = 1;
78 expand_aliases = interactive_shell;
79 }
80 }
81
82 /* **************************************************************** */
83 /* */
84 /* Functions to convert to and from and display non-standard types */
85 /* */
86 /* **************************************************************** */
87
88 #if defined (RLIMTYPE)
89 RLIMTYPE
90 string_to_rlimtype (s)
91 char *s;
92 {
93 RLIMTYPE ret;
94 int neg;
95
96 ret = 0;
97 neg = 0;
98 while (s && *s && whitespace (*s))
99 s++;
100 if (*s == '-' || *s == '+')
101 {
102 neg = *s == '-';
103 s++;
104 }
105 for ( ; s && *s && digit (*s); s++)
106 ret = (ret * 10) + digit_value (*s);
107 return (neg ? -ret : ret);
108 }
109
110 void
111 print_rlimtype (n, addnl)
112 RLIMTYPE n;
113 int addnl;
114 {
115 char s[sizeof (RLIMTYPE) * 3 + 1];
116 int len;
117
118 if (n == 0)
119 {
120 printf ("0%s", addnl ? "\n" : "");
121 return;
122 }
123
124 if (n < 0)
125 {
126 putchar ('-');
127 n = -n;
128 }
129
130 len = sizeof (RLIMTYPE) * 3 + 1;
131 s[--len] = '\0';
132 for ( ; n != 0; n /= 10)
133 s[--len] = n % 10 + '0';
134 printf ("%s%s", s + len, addnl ? "\n" : "");
135 }
136 #endif /* RLIMTYPE */
137
138 /* **************************************************************** */
139 /* */
140 /* Input Validation Functions */
141 /* */
142 /* **************************************************************** */
143
144 /* Return non-zero if all of the characters in STRING are digits. */
145 int
146 all_digits (string)
147 char *string;
148 {
149 register char *s;
150
151 for (s = string; *s; s++)
152 if (isdigit (*s) == 0)
153 return (0);
154
155 return (1);
156 }
157
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. */
161 int
162 legal_number (string, result)
163 char *string;
164 long *result;
165 {
166 long value;
167 char *ep;
168
169 if (result)
170 *result = 0;
171
172 value = strtol (string, &ep, 10);
173
174 /* Skip any trailing whitespace, since strtol does not. */
175 while (whitespace (*ep))
176 ep++;
177
178 /* If *string is not '\0' but *ep is '\0' on return, the entire string
179 is valid. */
180 if (string && *string && *ep == '\0')
181 {
182 if (result)
183 *result = value;
184 /* The SunOS4 implementation of strtol() will happily ignore
185 overflow conditions, so this cannot do overflow correctly
186 on those systems. */
187 return 1;
188 }
189
190 return (0);
191 }
192
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
195 digit. */
196 int
197 legal_identifier (name)
198 char *name;
199 {
200 register char *s;
201
202 if (!name || !*name || (legal_variable_starter (*name) == 0))
203 return (0);
204
205 for (s = name + 1; *s; s++)
206 {
207 if (legal_variable_char (*s) == 0)
208 return (0);
209 }
210 return (1);
211 }
212
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. */
218 int
219 check_identifier (word, check_word)
220 WORD_DESC *word;
221 int check_word;
222 {
223 if ((word->flags & (W_HASDOLLAR|W_QUOTED)) || all_digits (word->word))
224 {
225 internal_error ("`%s': not a valid identifier", word->word);
226 return (0);
227 }
228 else if (check_word && legal_identifier (word->word) == 0)
229 {
230 internal_error ("`%s': not a valid identifier", word->word);
231 return (0);
232 }
233 else
234 return (1);
235 }
236
237 /* **************************************************************** */
238 /* */
239 /* Functions to manage files and file descriptors */
240 /* */
241 /* **************************************************************** */
242
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. */
246
247 #if !defined (O_NDELAY)
248 # if defined (FNDELAY)
249 # define O_NDELAY FNDELAY
250 # endif
251 #endif /* O_NDELAY */
252
253 /* Make sure no-delay mode is not set on file descriptor FD. */
254 int
255 sh_unset_nodelay_mode (fd)
256 int fd;
257 {
258 int flags, bflags;
259
260 if ((flags = fcntl (fd, F_GETFL, 0)) < 0)
261 return -1;
262
263 bflags = 0;
264
265 /* This is defined to O_NDELAY in filecntl.h if O_NONBLOCK is not present
266 and O_NDELAY is defined. */
267 #ifdef O_NONBLOCK
268 bflags |= O_NONBLOCK;
269 #endif
270
271 #ifdef O_NDELAY
272 bflags |= O_NDELAY;
273 #endif
274
275 if (flags & bflags)
276 {
277 flags &= ~bflags;
278 return (fcntl (fd, F_SETFL, flags));
279 }
280
281 return 0;
282 }
283
284 /* There is a bug in the NeXT 2.1 rlogind that causes opens
285 of /dev/tty to fail. */
286
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. */
290 # undef O_NONBLOCK
291 # define O_NONBLOCK 0
292 #endif /* __BEOS__ */
293
294 void
295 check_dev_tty ()
296 {
297 int tty_fd;
298 char *tty;
299
300 tty_fd = open ("/dev/tty", O_RDWR|O_NONBLOCK);
301
302 if (tty_fd < 0)
303 {
304 tty = (char *)ttyname (fileno (stdin));
305 if (tty == 0)
306 return;
307 tty_fd = open (tty, O_RDWR|O_NONBLOCK);
308 }
309 close (tty_fd);
310 }
311
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. */
315 int
316 same_file (path1, path2, stp1, stp2)
317 char *path1, *path2;
318 struct stat *stp1, *stp2;
319 {
320 struct stat st1, st2;
321
322 if (stp1 == NULL)
323 {
324 if (stat (path1, &st1) != 0)
325 return (0);
326 stp1 = &st1;
327 }
328
329 if (stp2 == NULL)
330 {
331 if (stat (path2, &st2) != 0)
332 return (0);
333 stp2 = &st2;
334 }
335
336 return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
337 }
338
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). */
346 int
347 move_to_high_fd (fd, check_new, maxfd)
348 int fd, check_new, maxfd;
349 {
350 int script_fd, nfds, ignore;
351
352 if (maxfd < 20)
353 {
354 nfds = getdtablesize ();
355 if (nfds <= 0)
356 nfds = 20;
357 if (nfds > 256)
358 nfds = 256;
359 }
360 else
361 nfds = maxfd;
362
363 for (nfds--; check_new && nfds > 3; nfds--)
364 if (fcntl (nfds, F_GETFD, &ignore) == -1)
365 break;
366
367 if (nfds && fd != nfds && (script_fd = dup2 (fd, nfds)) != -1)
368 {
369 if (check_new == 0 || fd != fileno (stderr)) /* don't close stderr */
370 close (fd);
371 return (script_fd);
372 }
373
374 return (fd);
375 }
376
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. */
381
382 #if !defined (isspace)
383 #define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
384 #endif
385
386 #if !defined (isprint)
387 #define isprint(c) (isletter(c) || digit(c) || ispunct(c))
388 #endif
389
390 int
391 check_binary_file (sample, sample_len)
392 unsigned char *sample;
393 int sample_len;
394 {
395 register int i;
396
397 for (i = 0; i < sample_len; i++)
398 {
399 if (sample[i] == '\n')
400 return (0);
401
402 if (isspace (sample[i]) == 0 && isprint (sample[i]) == 0)
403 return (1);
404 }
405
406 return (0);
407 }
408
409 /* **************************************************************** */
410 /* */
411 /* Functions to manipulate pathnames */
412 /* */
413 /* **************************************************************** */
414
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
418 begin with. */
419 char *
420 make_absolute (string, dot_path)
421 char *string, *dot_path;
422 {
423 char *result;
424
425 if (dot_path == 0 || ABSPATH(string))
426 result = savestring (string);
427 else
428 result = sh_makepath (dot_path, string, 0);
429
430 return (result);
431 }
432
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. */
435 int
436 absolute_pathname (string)
437 char *string;
438 {
439 if (string == 0 || *string == '\0')
440 return (0);
441
442 if (ABSPATH(string))
443 return (1);
444
445 if (string[0] == '.' && PATHSEP(string[1])) /* . and ./ */
446 return (1);
447
448 if (string[0] == '.' && string[1] == '.' && PATHSEP(string[2])) /* .. and ../ */
449 return (1);
450
451 return (0);
452 }
453
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
456 up through $PATH. */
457 int
458 absolute_program (string)
459 char *string;
460 {
461 return ((char *)strchr (string, '/') != (char *)NULL);
462 }
463
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. */
466 char *
467 base_pathname (string)
468 char *string;
469 {
470 char *p;
471
472 if (absolute_pathname (string) == 0)
473 return (string);
474
475 p = (char *)strrchr (string, '/');
476 return (p ? ++p : string);
477 }
478
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. */
483 char *
484 full_pathname (file)
485 char *file;
486 {
487 char *ret;
488
489 file = (*file == '~') ? bash_tilde_expand (file) : savestring (file);
490
491 if (ABSPATH(file))
492 return (file);
493
494 ret = sh_makepath ((char *)NULL, file, (MP_DOCWD|MP_RMDOT));
495 free (file);
496
497 return (ret);
498 }
499
500 /* A slightly related function. Get the prettiest name of this
501 directory possible. */
502 static char tdir[PATH_MAX];
503
504 /* Return a pretty pathname. If the first part of the pathname is
505 the same as $HOME, then replace that with `~'. */
506 char *
507 polite_directory_format (name)
508 char *name;
509 {
510 char *home;
511 int l;
512
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] == '/'))
516 {
517 strncpy (tdir + 1, name + l, sizeof(tdir) - 2);
518 tdir[0] = '~';
519 tdir[sizeof(tdir) - 1] = '\0';
520 return (tdir);
521 }
522 else
523 return (name);
524 }
525
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. */
529 char *
530 extract_colon_unit (string, p_index)
531 char *string;
532 int *p_index;
533 {
534 int i, start, len;
535 char *value;
536
537 if (string == 0)
538 return (string);
539
540 len = strlen (string);
541 if (*p_index >= len)
542 return ((char *)NULL);
543
544 i = *p_index;
545
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] == ':')
552 i++;
553
554 for (start = i; string[i] && string[i] != ':'; i++)
555 ;
556
557 *p_index = i;
558
559 if (i == start)
560 {
561 if (string[i])
562 (*p_index)++;
563 /* Return "" in the case of a trailing `:'. */
564 value = xmalloc (1);
565 value[0] = '\0';
566 }
567 else
568 value = substring (string, start, i);
569
570 return (value);
571 }
572
573 /* **************************************************************** */
574 /* */
575 /* Tilde Initialization and Expansion */
576 /* */
577 /* **************************************************************** */
578
579 #if defined (PUSHD_AND_POPD)
580 extern char *get_dirstack_from_string __P((char *));
581 #endif
582
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
587 directory stack. */
588 static char *
589 bash_special_tilde_expansions (text)
590 char *text;
591 {
592 char *result;
593
594 result = (char *)NULL;
595
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);
603 #endif
604
605 return (result ? savestring (result) : (char *)NULL);
606 }
607
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. */
611 void
612 tilde_initialize ()
613 {
614 static int times_called = 0;
615
616 /* Tell the tilde expander that we want a crack first. */
617 tilde_expansion_preexpansion_hook = (CPFunction *)bash_special_tilde_expansions;
618
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)
623 {
624 tilde_additional_prefixes = alloc_array (3);
625 tilde_additional_prefixes[0] = "=~";
626 tilde_additional_prefixes[1] = ":~";
627 tilde_additional_prefixes[2] = (char *)NULL;
628
629 tilde_additional_suffixes = alloc_array (3);
630 tilde_additional_suffixes[0] = ":";
631 tilde_additional_suffixes[1] = "=~";
632 tilde_additional_suffixes[2] = (char *)NULL;
633 }
634 }
635
636 char *
637 bash_tilde_expand (s)
638 char *s;
639 {
640 int old_immed;
641 char *ret;
642
643 old_immed = interrupt_immediately;
644 interrupt_immediately = 1;
645 ret = tilde_expand (s);
646 interrupt_immediately = old_immed;
647 return (ret);
648 }
649
650 /* **************************************************************** */
651 /* */
652 /* Functions to manipulate and search the group list */
653 /* */
654 /* **************************************************************** */
655
656 static int ngroups, maxgroups;
657
658 /* The set of groups that this user is a member of. */
659 static GETGROUPS_T *group_array = (GETGROUPS_T *)NULL;
660
661 #if !defined (NOGROUP)
662 # define NOGROUP (gid_t) -1
663 #endif
664
665 #if defined (HAVE_SYSCONF) && defined (_SC_NGROUPS_MAX)
666 # define getmaxgroups() sysconf(_SC_NGROUPS_MAX)
667 #else
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 */
678
679 static void
680 initialize_group_array ()
681 {
682 register int i;
683
684 if (maxgroups == 0)
685 maxgroups = getmaxgroups ();
686
687 ngroups = 0;
688 group_array = (GETGROUPS_T *)xrealloc (group_array, maxgroups * sizeof (GETGROUPS_T));
689
690 #if defined (HAVE_GETGROUPS)
691 ngroups = getgroups (maxgroups, group_array);
692 #endif
693
694 /* If getgroups returns nothing, or the OS does not support getgroups(),
695 make sure the groups array includes at least the current gid. */
696 if (ngroups == 0)
697 {
698 group_array[0] = current_user.gid;
699 ngroups = 1;
700 }
701
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])
706 break;
707 if (i == ngroups && ngroups < maxgroups)
708 {
709 for (i = ngroups; i > 0; i--)
710 group_array[i] = group_array[i - 1];
711 group_array[0] = current_user.gid;
712 ngroups++;
713 }
714
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)
719 {
720 for (i = 0; i < ngroups; i++)
721 if (group_array[i] == current_user.gid)
722 break;
723 if (i < ngroups)
724 {
725 group_array[i] = group_array[0];
726 group_array[0] = current_user.gid;
727 }
728 }
729 }
730
731 /* Return non-zero if GID is one that we have in our groups list. */
732 int
733 #if defined (__STDC__) || defined ( _MINIX)
734 group_member (gid_t gid)
735 #else
736 group_member (gid)
737 gid_t gid;
738 #endif /* !__STDC__ && !_MINIX */
739 {
740 #if defined (HAVE_GETGROUPS)
741 register int i;
742 #endif
743
744 /* Short-circuit if possible, maybe saving a call to getgroups(). */
745 if (gid == current_user.gid || gid == current_user.egid)
746 return (1);
747
748 #if defined (HAVE_GETGROUPS)
749 if (ngroups == 0)
750 initialize_group_array ();
751
752 /* In case of error, the user loses. */
753 if (ngroups <= 0)
754 return (0);
755
756 /* Search through the list looking for GID. */
757 for (i = 0; i < ngroups; i++)
758 if (gid == (gid_t)group_array[i])
759 return (1);
760 #endif
761
762 return (0);
763 }
764
765 char **
766 get_group_list (ngp)
767 int *ngp;
768 {
769 static char **group_vector = (char **)NULL;
770 register int i;
771 char *nbuf;
772
773 if (group_vector)
774 {
775 if (ngp)
776 *ngp = ngroups;
777 return group_vector;
778 }
779
780 if (ngroups == 0)
781 initialize_group_array ();
782
783 if (ngroups <= 0)
784 {
785 if (ngp)
786 *ngp = 0;
787 return (char **)NULL;
788 }
789
790 group_vector = alloc_array (ngroups);
791 for (i = 0; i < ngroups; i++)
792 {
793 nbuf = itos ((int)group_array[i]);
794 group_vector[i] = nbuf;
795 }
796
797 if (ngp)
798 *ngp = ngroups;
799 return group_vector;
800 }
801
802 int *
803 get_group_array (ngp)
804 int *ngp;
805 {
806 int i;
807 static int *group_iarray = (int *)NULL;
808
809 if (group_iarray)
810 {
811 if (ngp)
812 *ngp = ngroups;
813 return (group_iarray);
814 }
815
816 if (ngroups == 0)
817 initialize_group_array ();
818
819 if (ngroups <= 0)
820 {
821 if (ngp)
822 *ngp = 0;
823 return (int *)NULL;
824 }
825
826 group_iarray = (int *)xmalloc (ngroups * sizeof (int));
827 for (i = 0; i < ngroups; i++)
828 group_iarray[i] = (int)group_array[i];
829
830 if (ngp)
831 *ngp = ngroups;
832 return group_iarray;
833 }