1 /* $NetBSD: main.c,v 1.13 2006/05/13 21:42:45 christos Exp $ */
4 * startup, main loop, environments and error handling
10 __RCSID("$NetBSD: main.c,v 1.13 2006/05/13 21:42:45 christos Exp $");
14 #define EXTERN /* define EXTERNs in sh.h */
20 extern char **environ
;
26 static void reclaim
ARGS((void));
27 static void remove_temps
ARGS((struct temp
*tp
));
28 static int is_restricted
ARGS((char *name
));
31 * shell initialization
34 static const char initifs
[] = "IFS= \t\n";
36 static const char initsubs
[] = "${PS2=> } ${PS3=#? } ${PS4=+ }";
38 static const char version_param
[] =
46 static const char *const initcoms
[] = {
47 "typeset", "-x", "SHELL", "PATH", "HOME", NULL
,
48 "typeset", "-r", version_param
, NULL
,
49 "typeset", "-i", "PPID", NULL
,
50 "typeset", "-i", "OPTIND=1", NULL
,
52 "eval", "typeset -i RANDOM MAILCHECK=\"${MAILCHECK-600}\" SECONDS=\"${SECONDS-0}\" TMOUT=\"${TMOUT-0}\"", NULL
,
55 /* Standard ksh aliases */
56 "hash=alias -t", /* not "alias -t --": hash -r needs to work */
60 "suspend=kill -STOP $$",
63 "autoload=typeset -fu",
64 "functions=typeset -f",
74 /* Aliases that are builtin commands in at&t */
78 #endif /* __NetBSD__ */
81 /* this is what at&t ksh seems to track, with the addition of emacs */
83 "cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
84 "mail", "make", "mv", "pr", "rm", "sed", "sh", "vi", "who",
88 #endif /* EXTRA_INITCOMS */
93 main(int argc
, char *argv
[])
99 int restricted
, errexit
;
105 chmem_set_defaults("ct", 1);
106 /* chmem_push("+c", 1); */
107 #endif /* MEM_DEBUG */
110 setmode (0, O_BINARY
);
114 /* make sure argv[] is sane */
116 static const char *empty_argv
[] = {
120 argv
= (char **)__UNCONST(empty_argv
);
125 ainit(&aperm
); /* initialize permanent Area */
127 /* set up base environment */
128 memset(&env
, 0, sizeof(env
));
132 newblock(); /* set up global l->vars and l->funs */
134 /* Do this first so output routines (eg, errorf, shellf) can work */
147 /* set up variable and command dictionaries */
148 tinit(&taliases
, APERM
, 0);
149 tinit(&aliases
, APERM
, 0);
150 tinit(&homedirs
, APERM
, 0);
152 /* define shell keywords */
155 /* define built-in commands */
156 tinit(&builtins
, APERM
, 64); /* must be 2^n (currently 40 builtins) */
157 for (i
= 0; shbuiltins
[i
].name
!= NULL
; i
++)
158 builtin(shbuiltins
[i
].name
, shbuiltins
[i
].func
);
159 for (i
= 0; kshbuiltins
[i
].name
!= NULL
; i
++)
160 builtin(kshbuiltins
[i
].name
, kshbuiltins
[i
].func
);
164 def_path
= DEFAULT__PATH
;
165 #if defined(HAVE_CONFSTR) && defined(_CS_PATH)
167 size_t len
= confstr(_CS_PATH
, (char *) 0, 0);
171 confstr(_CS_PATH
, new = alloc(len
+ 1, APERM
), len
+ 1);
175 #endif /* HAVE_CONFSTR && _CS_PATH */
177 /* Set PATH to def_path (will set the path global variable).
178 * (import of environment below will probably change this setting).
181 struct tbl
*vp
= global("PATH");
182 /* setstr can't fail here */
183 setstr(vp
, def_path
, KSH_RETURN_ERROR
);
187 /* Turn on nohup by default for now - will change to off
188 * by default once people are aware of its existence
189 * (at&t ksh does not have a nohup option - it always sends
194 /* Turn on brace expansion by default. At&t ksh's that have
195 * alternation always have it on. BUT, posix doesn't have
196 * brace expansion, so set this before setting up FPOSIX
197 * (change_flag() clears FBRACEEXPAND when FPOSIX is set).
200 Flag(FBRACEEXPAND
) = 1;
201 #endif /* BRACE_EXPAND */
203 /* set posix flag just before environment so that it will have
204 * exactly the same effect as the POSIXLY_CORRECT environment
205 * variable. If this needs to be done sooner to ensure correct posix
206 * operation, an initial scan of the environment will also have
209 #ifdef POSIXLY_CORRECT
210 change_flag(FPOSIX
, OF_SPECIAL
, 1);
211 #endif /* POSIXLY_CORRECT */
213 /* Set edit mode to emacs by default, may be overridden
214 * by the environment or the user. Also, we want tab completion
215 * on in vi by default. */
216 #if defined(EDIT) && defined(EMACS)
217 change_flag(FEMACS
, OF_SPECIAL
, 1);
218 #endif /* EDIT && EMACS */
219 #if defined(EDIT) && defined(VI)
220 Flag(FVITABCOMPLETE
) = 1;
221 #endif /* EDIT && VI */
223 /* import environment */
225 for (wp
= environ
; *wp
!= NULL
; wp
++)
226 typeset(*wp
, IMPORT
|EXPORT
, 0, 0, 0);
228 kshpid
= procpid
= getpid();
229 typeset(initifs
, 0, 0, 0, 0); /* for security */
231 /* assign default shell variable values */
232 substitute(initsubs
, 0);
234 /* Figure out the current working directory and set $PWD */
236 struct stat s_pwd
, s_dot
;
237 struct tbl
*pwd_v
= global("PWD");
238 char *pwd
= str_val(pwd_v
);
241 /* Try to use existing $PWD if it is valid */
243 || stat(pwd
, &s_pwd
) < 0 || stat(".", &s_dot
) < 0
244 || s_pwd
.st_dev
!= s_dot
.st_dev
245 || s_pwd
.st_ino
!= s_dot
.st_ino
)
247 set_current_wd(pwdx
);
249 simplify_path(current_wd
);
250 /* Only set pwd if we know where we are or if it had a
253 if (current_wd
[0] || pwd
!= null
)
254 /* setstr can't fail here */
255 setstr(pwd_v
, current_wd
, KSH_RETURN_ERROR
);
258 setint(global("PPID"), (long) ppid
);
260 setint(global("RANDOM"), (long) (time((time_t *)0) * kshpid
* ppid
));
262 /* setstr can't fail here */
263 setstr(global(version_param
), ksh_version
, KSH_RETURN_ERROR
);
265 /* execute initialization statements */
266 for (wp
= (char**)__UNCONST(initcoms
); *wp
!= NULL
; wp
++) {
268 for (; *wp
!= NULL
; wp
++)
274 safe_prompt
= ksheuid
? "$ " : "# ";
276 struct tbl
*vp
= global("PS1");
278 /* Set PS1 if it isn't set, or we are root and prompt doesn't
281 if (!(vp
->flag
& ISSET
)
282 || (!ksheuid
&& !strchr(str_val(vp
), '#')))
283 /* setstr can't fail here */
284 setstr(vp
, safe_prompt
, KSH_RETURN_ERROR
);
287 /* Set this before parsing arguments */
288 Flag(FPRIVILEGED
) = getuid() != ksheuid
|| getgid() != getegid();
290 /* this to note if monitor is set on command line (see below) */
291 Flag(FMONITOR
) = 127;
292 argi
= parse_args(argv
, OF_CMDLINE
, (int *) 0);
298 if (Flag(FCOMMAND
)) {
299 s
= pushs(SSTRING
, ATEMP
);
300 if (!(s
->start
= s
->str
= argv
[argi
++]))
301 errorf("-c requires an argument");
303 kshname
= argv
[argi
++];
304 } else if (argi
< argc
&& !Flag(FSTDIN
)) {
305 s
= pushs(SFILE
, ATEMP
);
307 /* a bug in os2 extproc shell processing doesn't
308 * pass full pathnames so we have to search for it.
309 * This changes the behavior of 'ksh arg' to search
310 * the users search path but it can't be helped.
312 s
->file
= search(argv
[argi
++], path
, R_OK
, (int *) 0);
313 if (!s
->file
|| !*s
->file
)
314 s
->file
= argv
[argi
- 1];
316 s
->file
= argv
[argi
++];
318 s
->u
.shf
= shf_open(s
->file
, O_RDONLY
, 0, SHF_MAPHI
|SHF_CLEXEC
);
319 if (s
->u
.shf
== NULL
) {
320 exstat
= 127; /* POSIX */
321 errorf("%s: %s", s
->file
, strerror(errno
));
326 s
= pushs(SSTDIN
, ATEMP
);
328 s
->u
.shf
= shf_fdopen(0, SHF_RD
| can_seek(0),
330 if (isatty(0) && isatty(2)) {
331 Flag(FTALKING
) = Flag(FTALKING_I
) = 1;
332 /* The following only if isatty(0) */
334 s
->u
.shf
->flags
|= SHF_INTERRUPT
;
335 s
->file
= (char *) 0;
339 /* This bizarreness is mandated by POSIX */
343 if (fstat(0, &s_stdin
) >= 0 && S_ISCHR(s_stdin
.st_mode
) &&
348 /* initialize job control */
349 i
= Flag(FMONITOR
) != 127;
353 /* Do this after j_init(), as tty_fd is not initialized 'til then */
359 l
->argv
= &argv
[argi
- 1];
360 l
->argc
= argc
- argi
;
361 l
->argv
[0] = (char *)__UNCONST(kshname
);
364 /* Disable during .profile/ENV reading */
365 restricted
= Flag(FRESTRICTED
);
366 Flag(FRESTRICTED
) = 0;
367 errexit
= Flag(FERREXIT
);
370 /* Do this before profile/$ENV so that if it causes problems in them,
371 * user will know why things broke.
373 if (!current_wd
[0] && Flag(FTALKING
))
374 warningf(FALSE
, "Cannot determine current working directory");
380 /* Try to find a profile - first see if $INIT has a value,
381 * then try /etc/profile.ksh, then c:/usr/etc/profile.ksh.
383 if (!Flag(FPRIVILEGED
)
384 && strcmp(profile
= substitute("$INIT/profile.ksh", 0),
386 include(profile
, 0, (char **) 0, 1);
387 else if (include("/etc/profile.ksh", 0, (char **) 0, 1) < 0)
388 include("c:/usr/etc/profile.ksh", 0, (char **) 0, 1);
389 if (!Flag(FPRIVILEGED
))
390 include(substitute("$HOME/profile.ksh", 0), 0,
393 include(KSH_SYSTEM_PROFILE
, 0, (char **) 0, 1);
394 if (!Flag(FPRIVILEGED
))
395 include(substitute("$HOME/.profile", 0), 0,
400 if (Flag(FPRIVILEGED
))
401 include("/etc/suid_profile", 0, (char **) 0, 1);
411 env_file
= str_val(global("ENV"));
414 /* If env isn't set, include default environment */
415 if (env_file
== null
)
416 env_file
= __UNCONST(DEFAULT_ENV
);
417 #endif /* DEFAULT_ENV */
418 env_file
= substitute(env_file
, DOTILDE
);
419 if (*env_file
!= '\0')
420 include(env_file
, 0, (char **) 0, 1);
422 else if (Flag(FTALKING
))
423 include(substitute("$HOME/kshrc.ksh", 0), 0,
428 if (is_restricted(argv
[0]) || is_restricted(str_val(global("SHELL"))))
431 static const char *const restr_com
[] = {
432 "typeset", "-r", "PATH",
436 shcomexec((char **)__UNCONST(restr_com
));
437 /* After typeset command... */
438 Flag(FRESTRICTED
) = 1;
443 if (Flag(FTALKING
)) {
449 Flag(FTRACKALL
) = 1; /* set after ENV */
451 setlocale(LC_CTYPE
, "");
452 shell(s
, TRUE
); /* doesn't return */
457 include(name
, argc
, argv
, intr_ok
)
463 register Source
*volatile s
= NULL
;
465 char **volatile old_argv
;
466 volatile int old_argc
;
469 shf
= shf_open(name
, O_RDONLY
, 0, SHF_MAPHI
|SHF_CLEXEC
);
474 old_argv
= e
->loc
->argv
;
475 old_argc
= e
->loc
->argc
;
477 old_argv
= (char **) 0;
481 i
= ksh_sigsetjmp(e
->jbuf
, 0);
483 if (s
) /* Do this before quitenv(), which frees the memory */
487 e
->loc
->argv
= old_argv
;
488 e
->loc
->argc
= old_argc
;
493 return exstat
& 0xff; /* see below */
495 /* intr_ok is set if we are including .profile or $ENV.
496 * If user ^C's out, we don't want to kill the shell...
498 if (intr_ok
&& (exstat
- 128) != SIGTERM
)
500 /* fall through... */
507 internal_errorf(1, "include: %d", i
);
515 s
= pushs(SFILE
, ATEMP
);
517 s
->file
= str_save(name
, ATEMP
);
522 e
->loc
->argv
= old_argv
;
523 e
->loc
->argc
= old_argc
;
525 return i
& 0xff; /* & 0xff to ensure value not -1 */
535 s
= pushs(SSTRING
, ATEMP
);
536 s
->start
= s
->str
= comm
;
543 * run the commands from the input source, returning status.
547 Source
*volatile s
; /* input source */
548 int volatile toplevel
;
551 volatile int wastty
= s
->flags
& SF_TTY
;
552 volatile int attempts
= 13;
553 volatile int interactive
= Flag(FTALKING
) && toplevel
;
554 Source
*volatile old_source
= source
;
560 i
= ksh_sigsetjmp(e
->jbuf
, 0);
563 case LINTR
: /* we get here if SIGINT not caught or ignored */
569 /* Reset any eof that was read as part of a
572 if (Flag(FIGNOREEOF
) && s
->type
== SEOF
575 /* Used by exit command to get back to
576 * top level shell. Kind of strange since
577 * interactive is set if we are reading from
578 * a tty, but to have stopped jobs, one only
579 * needs FMONITOR set (not FTALKING/SF_TTY)...
581 /* toss any input we have so far */
582 s
->start
= s
->str
= null
;
585 /* fall through... */
591 unwind(i
); /* keep on going */
596 internal_errorf(1, "shell: %d", i
);
605 if (s
->next
== NULL
) {
609 s
->flags
&= ~SF_ECHO
;
621 if (t
!= NULL
&& t
->type
== TEOF
) {
622 if (wastty
&& Flag(FIGNOREEOF
) && --attempts
> 0) {
623 shellf("Use `exit' to leave ksh\n");
625 } else if (wastty
&& !really_exit
626 && j_stopped_running())
631 /* this for POSIX, which says EXIT traps
632 * shall be taken in the environment
633 * immediately after the last command
642 if (t
&& (!Flag(FNOEXEC
) || (s
->flags
& SF_TTY
)))
643 exstat
= execute(t
, 0);
645 if (t
!= NULL
&& t
->type
!= TEOF
&& interactive
&& really_exit
)
655 /* return to closest error handler or shell(), exit if none found */
660 /* ordering for EXIT vs ERR is a bit odd (this is what at&t ksh does) */
661 if (i
== LEXIT
|| (Flag(FERREXIT
) && (i
== LERROR
|| i
== LINTR
)
662 && sigtraps
[SIGEXIT_
].trap
))
664 runtrap(&sigtraps
[SIGEXIT_
]);
666 } else if (Flag(FERREXIT
) && (i
== LERROR
|| i
== LINTR
)) {
667 runtrap(&sigtraps
[SIGERR_
]);
677 ksh_siglongjmp(e
->jbuf
, i
);
682 e
->flags
|= EF_FAKE_SIGDIE
;
683 /* Fall through... */
695 register struct env
*ep
;
697 ep
= (struct env
*) alloc(sizeof(*ep
), ATEMP
);
711 register struct env
*ep
= e
;
714 if (ep
->oenv
&& ep
->oenv
->loc
!= ep
->loc
)
716 if (ep
->savefd
!= NULL
) {
717 for (fd
= 0; fd
< NUFILE
; fd
++)
718 /* if ep->savefd[fd] < 0, means fd was closed */
720 restfd(fd
, ep
->savefd
[fd
]);
721 if (ep
->savefd
[2]) /* Clear any write errors */
722 shf_reopen(2, SHF_WR
, shl_out
);
726 /* Bottom of the stack.
727 * Either main shell is exiting or cleanup_parents_env() was called.
729 if (ep
->oenv
== NULL
) {
730 if (ep
->type
== E_NONE
) { /* Main shell exiting? */
734 if (ep
->flags
& EF_FAKE_SIGDIE
) {
735 int sig
= exstat
- 128;
737 /* ham up our death a bit (at&t ksh
738 * only seems to do this for SIGTERM)
739 * Don't do it for SIGQUIT, since we'd
742 if (sig
== SIGINT
|| sig
== SIGTERM
) {
743 setsig(&sigtraps
[sig
], SIG_DFL
,
744 SS_RESTORE_CURR
|SS_FORCE
);
750 #endif /* MEM_DEBUG */
759 /* Called after a fork to cleanup stuff left over from parents environment */
761 cleanup_parents_env()
766 /* Don't clean up temporary files - parent will probably need them.
767 * Also, can't easily reclaim memory since variables, etc. could be
771 /* close all file descriptors hiding in savefd */
772 for (ep
= e
; ep
; ep
= ep
->oenv
) {
774 for (fd
= 0; fd
< NUFILE
; fd
++)
775 if (ep
->savefd
[fd
] > 0)
776 close(ep
->savefd
[fd
]);
777 afree(ep
->savefd
, &ep
->area
);
778 ep
->savefd
= (short *) 0;
781 e
->oenv
= (struct env
*) 0;
784 /* Called just before an execve cleanup stuff temporary files */
790 for (ep
= e
; ep
; ep
= ep
->oenv
)
791 remove_temps(ep
->temps
);
794 /* remove temp files and free ATEMP Area */
798 remove_temps(e
->temps
);
808 static struct temp
*delayed_remove
;
809 struct temp
*t
, **tprev
;
811 if (delayed_remove
) {
812 for (tprev
= &delayed_remove
, t
= delayed_remove
; t
; t
= *tprev
)
813 /* No need to check t->pid here... */
814 if (unlink(t
->name
) >= 0 || errno
== ENOENT
) {
822 for (; tp
!= NULL
; tp
= tp
->next
)
823 if (tp
->pid
== procpid
) {
825 /* OS/2 (and dos) do not allow files that are currently
826 * open to be removed, so we cache it away for future
828 * XXX should only do this if errno
829 * is Efile-still-open-can't-remove
830 * (but I don't know what that is...)
832 if (unlink(tp
->name
) < 0 && errno
!= ENOENT
) {
833 t
= (struct temp
*) alloc(
834 sizeof(struct temp
) + strlen(tp
->name
) + 1,
836 memset(t
, 0, sizeof(struct temp
));
837 t
->name
= (char *) &t
[1];
838 strlcpy(t
->name
, tp
->name
, strlen(tp
->name
) + 1);
839 t
->next
= delayed_remove
;
848 /* Returns true if name refers to a restricted shell */
855 if ((p
= ksh_strrchr_dirsep(name
)))
857 /* accepts rsh, rksh, rpdksh, pdrksh, etc. */
858 return (p
= strchr(name
, 'r')) && strstr(p
, "sh");
866 internal_errorf(1, "alloc: %s", msg
);
867 errorf(null
); /* this is never executed - keeps gcc quiet */