1 /* Copyright (c) 1993-2002
2 * Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de)
3 * Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de)
4 * Copyright (c) 1987 Oliver Laumann
7 * Authors: Hadi Bargi Rangin bargi@dots.physics.orst.edu
8 * Bill Barry barryb@dots.physics.orst.edu
9 * Randy Lundquist randyl@dots.physics.orst.edu
11 * Modifications Copyright (c) 1995 by
12 * Science Access Project, Oregon State University.
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2, or (at your option)
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program (see the file COPYING); if not, write to the
27 * Free Software Foundation, Inc.,
28 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
30 ****************************************************************
33 #include <sys/types.h>
39 # include <sys/sysmacros.h>
44 # include <sys/ioctl.h>
54 # include <sys/stropts.h>
57 #if defined(SYSV) && !defined(ISC)
58 # include <sys/utsname.h>
61 #if defined(sequent) || defined(SVR4)
62 # include <sys/resource.h>
63 #endif /* sequent || SVR4 */
67 # include <sys/sioctl.h>
71 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
74 #if defined(USE_LOCALE) || defined(ENCODINGS)
77 #if defined(HAVE_NL_LANGINFO) && defined(ENCODINGS)
78 # include <langinfo.h>
86 #include "patchlevel.h"
89 * At the moment we only need the real password if the
90 * builtin lock is used. Therefore disable SHADOWPW if
91 * we do not really need it (kind of security thing).
100 #endif /* SHADOWPW */
102 #include "logfile.h" /* islogfile, logfflush */
109 extern char Term
[], screenterm
[], **environ
, Termcap
[];
111 int VBellWait
, MsgWait
, MsgMinWait
, SilenceWait
;
113 extern struct acluser
*users
;
114 extern struct display
*displays
, *display
;
117 extern int visual_bell
;
119 extern unsigned char mark_key_tab
[];
121 extern char version
[];
122 extern char DefaultShell
[];
124 extern char *zmodem_sendcmd
;
125 extern char *zmodem_recvcmd
;
127 extern struct layout
*layout_last
;
133 extern struct NewWindow nwin_undef
, nwin_default
, nwin_options
;
136 static struct passwd
*getpwbyname
__P((char *, struct passwd
*));
137 static void SigChldHandler
__P((void));
138 static sigret_t SigChld
__P(SIGPROTOARG
);
139 static sigret_t SigInt
__P(SIGPROTOARG
);
140 static sigret_t CoreDump
__P(SIGPROTOARG
);
141 static sigret_t FinitHandler
__P(SIGPROTOARG
);
142 static void DoWait
__P((void));
143 static void serv_read_fn
__P((struct event
*, char *));
144 static void serv_select_fn
__P((struct event
*, char *));
145 static void logflush_fn
__P((struct event
*, char *));
146 static void backtick_filter
__P((struct backtick
*));
147 static void backtick_fn
__P((struct event
*, char *));
148 static char *runbacktick
__P((struct backtick
*, int *, time_t));
149 static int IsSymbol
__P((char *, char *));
150 static char *ParseChar
__P((char *, char *));
151 static int ParseEscape
__P((char *));
152 static char *pad_expand
__P((char *, char *, int, int));
154 static void fds
__P((void));
157 int nversion
; /* numerical version, used for secondary DA */
165 struct mode attach_Mode
;
167 char SockPath
[MAXPATHLEN
+ 2 * MAXSTR
];
168 char *SockName
; /* SockName is pointer in SockPath */
169 char *SockMatch
= NULL
; /* session id command line argument */
170 int ServerSocket
= -1;
171 struct event serv_read
;
172 struct event serv_select
;
173 struct event logflushev
;
175 char **NewEnv
= NULL
;
177 char *RcFileName
= NULL
;
180 char *screenlogfile
; /* filename layout */
181 int log_flush
= 10; /* flush interval in seconds */
182 int logtstamp_on
= 0; /* tstamp disabled */
183 char *logtstamp_string
; /* stamp layout */
184 int logtstamp_after
= 120; /* first tstamp after 120s */
185 char *hardcopydir
= NULL
;
187 char *VisualBellString
;
188 char *ActivityString
;
193 char *PowDetachString
;
201 int iflag
, rflag
, dflag
, lsflag
, quietflag
, wipeflag
, xflag
;
212 int tty_oldmode
= -1;
215 char HostName
[MAXSTR
];
216 int MasterPid
, PanicPid
;
217 int real_uid
, real_gid
, eff_uid
, eff_gid
;
219 int ZombieKey_destroy
, ZombieKey_resurrect
, ZombieKey_onerror
;
220 char *preselect
= NULL
; /* only used in Attach() */
223 char *screenencodings
;
236 struct layer
*flayer
;
239 struct win
*console_window
;
248 char strnomem
[] = "Out of memory.";
251 static int InterruptPlease
;
252 static int GotSigChld
;
255 lf_secreopen(name
, wantfd
, l
)
263 if (((got_fd
= secopen(name
, O_WRONLY
| O_CREAT
| O_APPEND
, 0666)) < 0) ||
264 lf_move_fd(got_fd
, wantfd
) < 0)
267 debug1("lf_secreopen: failed for %s\n", name
);
270 l
->st
->st_ino
= l
->st
->st_dev
= 0;
271 debug2("lf_secreopen: %d = %s\n", wantfd
, name
);
275 /********************************************************************/
276 /********************************************************************/
277 /********************************************************************/
280 static struct passwd
*
281 getpwbyname(name
, ppp
)
287 struct spwd
*sss
= NULL
;
288 static char *spw
= NULL
;
291 if (!ppp
&& !(ppp
= getpwnam(name
)))
294 /* Do password sanity check..., allow ##user for SUN_C2 security */
299 if (ppp
->pw_passwd
[0] == '#' && ppp
->pw_passwd
[1] == '#' &&
300 strcmp(ppp
->pw_passwd
+ 2, ppp
->pw_name
) == 0)
304 char c
= ppp
->pw_passwd
[n
];
305 if (!(c
== '.' || c
== '/' || c
== '$' ||
306 (c
>= '0' && c
<= '9') ||
307 (c
>= 'a' && c
<= 'z') ||
308 (c
>= 'A' && c
<= 'Z')))
313 /* try to determine real password */
314 if (n
< 13 && sss
== 0)
316 sss
= getspnam(ppp
->pw_name
);
321 ppp
->pw_passwd
= spw
= SaveStr(sss
->sp_pwdp
);
322 endspent(); /* this should delete all buffers ... */
325 endspent(); /* this should delete all buffers ... */
331 if (ppp
->pw_passwd
&& strlen(ppp
->pw_passwd
) == 13 + 11)
332 ppp
->pw_passwd
[13] = 0; /* beware of linux's long passwords */
345 s
= getenv("LC_ALL");
347 s
= getenv("LC_CTYPE");
362 char socknamebuf
[2 * MAXSTR
];
364 char *myname
= (ac
== 0) ? "screen" : av
[0];
367 #ifdef _MODE_T /* (jw) */
372 #if defined(SYSV) && !defined(ISC)
373 struct utsname utsnam
;
375 struct NewWindow nwin
;
376 int detached
= 0; /* start up detached */
380 char *script_file
= 0;
383 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
384 setcompat(COMPAT_POSIX
|COMPAT_BSDPROT
); /* turn on seteuid support */
386 #if defined(sun) && defined(SVR4)
388 /* Solaris' login blocks SIGHUP! This is _very bad_ */
391 sigprocmask(SIG_SETMASK
, &sset
, 0);
396 * First, close all unused descriptors
397 * (otherwise, we might have problems with the select() call)
403 sprintf(version
, "%d.%.2d.%.2d%s (%s) %s", REV
, VERS
,
404 PATCHLEVEL
, STATE
, ORIGIN
, DATE
);
405 nversion
= REV
* 10000 + VERS
* 100 + PATCHLEVEL
;
406 debug2("-- screen debug started %s (%s)\n", *av
, version
);
420 debug("NAMEDPIPE\n");
422 #if defined(SIGWINCH) && defined(TIOCGWINSZ)
423 debug("Window size changing enabled\n");
453 debug1("NAME_MAX = %d\n", NAME_MAX
);
456 BellString
= SaveStr("Bell in window %n");
457 VisualBellString
= SaveStr(" Wuff, Wuff!! ");
458 ActivityString
= SaveStr("Activity in window %n");
459 screenlogfile
= SaveStr("screenlog.%n");
460 logtstamp_string
= SaveStr("-- %n:%t -- time-stamp -- %M/%d/%y %c:%s --\n");
461 hstatusstring
= SaveStr("%h");
462 captionstring
= SaveStr("%3n %t");
463 timestring
= SaveStr("%c:%s %M %d %H%? %l%?");
464 wlisttit
= SaveStr("Num Name%=Flags");
465 wliststr
= SaveStr("%3n %t%=%f");
467 BufferFile
= SaveStr(DEFAULT_BUFFERFILE
);
473 default_startup
= (ac
> 1) ? 0 : 1;
475 VBellWait
= VBELLWAIT
* 1000;
476 MsgWait
= MSGWAIT
* 1000;
477 MsgMinWait
= MSGMINWAIT
* 1000;
478 SilenceWait
= SILENCEWAIT
;
483 zmodem_sendcmd
= SaveStr("!!! sz -vv -b ");
484 zmodem_recvcmd
= SaveStr("!!! rz -vv -b -E");
488 CompileKeys((char *)0, 0, mark_key_tab
);
492 screenencodings
= SaveStr(SCREENENCODINGS
);
498 nwin_options
= nwin_undef
;
499 strcpy(screenterm
, "screen");
501 logreopen_register(lf_secreopen
);
504 /* if this is a login screen, assume -RR */
513 ShellProg
= SaveStr(DefaultShell
); /* to prevent nasty circles */
518 if (--ac
> 0 && *ap
== '-')
520 if (ap
[1] == '-' && ap
[2] == 0)
526 if (ap
[1] == '-' && !strcmp(ap
, "--version"))
527 Panic(0, "Screen version %s", version
);
528 if (ap
[1] == '-' && !strcmp(ap
, "--help"))
529 exit_with_usage(myname
, NULL
, NULL
);
530 while (ap
&& *ap
&& *++ap
)
535 nwin_options
.aflag
= 1;
540 case 'p': /* preselect */
546 exit_with_usage(myname
, "Specify a window to preselect with -p", NULL
);
553 bd
.bd_start_braille
= 1;
562 exit_with_usage(myname
, "Specify an alternate rc-filename with -c", NULL
);
571 exit_with_usage(myname
, "Specify command characters with -e", NULL
);
575 Panic(0, "Two characters are required with -e option, not '%s'.", ap
);
584 nwin_options
.flowflag
= FLOW_NOW
* 0;
591 nwin_options
.flowflag
= FLOW_NOW
* 1;
594 nwin_options
.flowflag
= FLOW_AUTOFLAG
;
597 exit_with_usage(myname
, "Unknown flow option -%s", --ap
);
602 exit_with_usage(myname
, NULL
, NULL
);
603 nwin_options
.histheight
= atoi(*++av
);
604 if (nwin_options
.histheight
< 0)
605 exit_with_usage(myname
, "-h: %s: negative scrollback size?", *av
);
610 case 't': /* title, the former AkA == -k */
612 exit_with_usage(myname
, "Specify a new window-name with -t", NULL
);
613 nwin_options
.aka
= *++av
;
621 nwin_options
.lflag
= 0;
628 nwin_options
.lflag
= 1;
631 nwin_options
.lflag
= 3;
634 case 'i': /* -list */
636 if (ac
> 1 && !SockMatch
)
644 exit_with_usage(myname
, "%s: Unknown suboption to -l", --ap
);
650 if (ac
> 1 && !SockMatch
)
657 nwin_options
.Lflag
= 1;
662 case 'O': /* to be (or not to be?) deleted. jw. */
667 exit_with_usage(myname
, "Specify terminal-type with -T", NULL
);
668 if (strlen(*++av
) < 20)
669 strcpy(screenterm
, *av
);
671 Panic(0, "-T: terminal name too long. (max. 20 char)");
672 nwin_options
.term
= screenterm
;
682 if (ac
> 1 && *av
[1] != '-' && !SockMatch
)
686 debug2("rflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
694 rflag
+= (*ap
== 'R') ? 2 : 1;
705 if (*av
[1] != '-' && !SockMatch
)
709 debug2("dflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
716 exit_with_usage(myname
, "Specify shell with -s", NULL
);
719 ShellProg
= SaveStr(*++av
);
720 debug1("ShellProg: '%s'\n", ShellProg
);
726 exit_with_usage(myname
, "Specify session-name with -S", NULL
);
730 exit_with_usage(myname
, "Empty session-name?", NULL
);
736 Panic(0, "Screen version %s", version
);
740 nwin_options
.encoding
= nwin_options
.encoding
== -1 ? UTF8
: 0;
745 exit_with_usage(myname
, "Specify lua script file with -u", NULL
);
748 script_file
= SaveStr(*++av
);
751 exit_with_usage(myname
, "Unknown option %s", --ap
);
763 if (eff_uid
!= real_uid
)
765 /* if running with s-bit, we must install a special signal
766 * handler routine that resets the s-bit, so that we get a
769 #ifdef SIGBUS /* OOPS, linux has no bus errors! */
770 signal(SIGBUS
, CoreDump
);
772 signal(SIGSEGV
, CoreDump
);
776 setlocale(LC_ALL
, "");
779 if (nwin_options
.encoding
== -1)
781 /* ask locale if we should start in UTF-8 mode */
782 # ifdef HAVE_NL_LANGINFO
784 setlocale(LC_CTYPE
, "");
786 nwin_options
.encoding
= FindEncoding(nl_langinfo(CODESET
));
787 debug1("locale says encoding = %d\n", nwin_options
.encoding
);
791 if ((s
= locale_name()) && InStr(s
, "UTF-8"))
792 nwin_options
.encoding
= UTF8
;
794 debug1("environment says encoding=%d\n", nwin_options
.encoding
);
800 if ((s
= locale_name()))
802 if(!strncmp(s
, "zh_", 3) || !strncmp(s
, "ja_", 3) || !strncmp(s
, "ko_", 3))
810 if (nwin_options
.aka
)
813 if (nwin_options
.encoding
> 0)
815 size_t len
= strlen(nwin_options
.aka
);
817 char *newbuf
= malloc(3 * len
);
820 newsz
= RecodeBuf(nwin_options
.aka
, len
,
821 nwin_options
.encoding
, 0, newbuf
);
822 newbuf
[newsz
] = '\0';
823 nwin_options
.aka
= newbuf
;
828 /* If we just use the original value from av,
829 subsequent shelltitle invocations will attempt to free
830 space we don't own... */
831 nwin_options
.aka
= SaveStr(nwin_options
.aka
);
835 if (SockMatch
&& strlen(SockMatch
) >= MAXSTR
)
836 Panic(0, "Ridiculously long socketname - try again.");
837 if (cmdflag
&& !rflag
&& !dflag
&& !xflag
)
839 if (!cmdflag
&& dflag
&& mflag
&& !(rflag
|| xflag
))
843 nwin
.encoding
= nwin_undef
.encoding
; /* let screenrc overwrite it */
848 /* make the write() calls return -1 on all errors */
851 * Ronald F. Guilmette, Oct 29 '94, bug-gnu-utils@prep.ai.mit.edu:
852 * It appears that in System V Release 4, UNIX, if you are writing
853 * an output file and you exceed the currently set file size limit,
854 * you _don't_ just get the call to `write' returning with a
855 * failure code. Rather, you get a signal called `SIGXFSZ' which,
856 * if neither handled nor ignored, will cause your program to crash
859 signal(SIGXFSZ
, SIG_IGN
);
863 signal(SIGPIPE
, SIG_IGN
);
870 sh
= getenv("SHELL");
871 ShellProg
= SaveStr(sh
? sh
: DefaultShell
);
873 ShellArgs
[0] = ShellProg
;
874 home
= getenv("HOME");
875 if (!mflag
&& !SockMatch
)
878 if (sty
&& *sty
== 0)
883 if (!(nethackflag
= (getenv("NETHACKOPTIONS") != NULL
)))
885 char nethackrc
[MAXPATHLEN
];
887 if (home
&& (strlen(home
) < (MAXPATHLEN
- 20)))
889 sprintf(nethackrc
,"%s/.nethackrc", home
);
890 nethackflag
= !access(nethackrc
, F_OK
);
896 own_uid
= multi_uid
= real_uid
;
897 if (SockMatch
&& (sockp
= index(SockMatch
, '/')))
901 SockMatch
= sockp
+ 1;
905 if ((mppp
= getpwnam(multi
)) == (struct passwd
*)0)
906 Panic(0, "Cannot identify account '%s'.", multi
);
907 multi_uid
= mppp
->pw_uid
;
908 multi_home
= SaveStr(mppp
->pw_dir
);
909 if (strlen(multi_home
) > MAXPATHLEN
- 10)
910 Panic(0, "home directory path too long");
912 /* always fake multi attach mode */
919 /* Special case: effective user is multiuser. */
920 if (eff_uid
&& (multi_uid
!= eff_uid
))
921 Panic(0, "Must run suid root for multiuser support.");
923 if (SockMatch
&& *SockMatch
== 0)
925 #endif /* MULTIUSER */
927 if ((LoginName
= getlogin()) && LoginName
[0] != '\0')
929 if ((ppp
= getpwnam(LoginName
)) != (struct passwd
*) 0)
930 if ((int)ppp
->pw_uid
!= real_uid
)
931 ppp
= (struct passwd
*) 0;
935 if ((ppp
= getpwuid(real_uid
)) == 0)
937 Panic(0, "getpwuid() can't identify your account!");
940 LoginName
= ppp
->pw_name
;
942 LoginName
= SaveStr(LoginName
);
944 ppp
= getpwbyname(LoginName
, ppp
);
946 #if !defined(SOCKDIR) && defined(MULTIUSER)
947 if (multi
&& !multiattach
)
949 if (home
&& strcmp(home
, ppp
->pw_dir
))
950 Panic(0, "$HOME must match passwd entry for multiuser screens.");
954 #define SET_GUID() do \
958 eff_uid = real_uid; \
959 eff_gid = real_gid; \
962 #define SET_TTYNAME(fatal) do \
964 if (!(attach_tty = ttyname(0))) \
967 Panic(0, "Must be connected to a terminal."); \
971 else if (stat(attach_tty, &st)) \
972 Panic(errno, "Cannot access '%s'", attach_tty); \
973 if (strlen(attach_tty) >= MAXPATHLEN) \
974 Panic(0, "TtyName too long - sorry."); \
977 if (home
== 0 || *home
== '\0')
979 if (strlen(LoginName
) > 20)
980 Panic(0, "LoginName too long - sorry.");
982 if (multi
&& strlen(multi
) > 20)
983 Panic(0, "Screen owner name too long - sorry.");
985 if (strlen(home
) > MAXPATHLEN
- 25)
986 Panic(0, "$HOME too long - sorry.");
989 if (!detached
&& !lsflag
&& !cmdflag
&& !(dflag
&& !mflag
&& !rflag
&& !xflag
) && !(!mflag
&& !SockMatch
&& sty
))
995 /* ttyname implies isatty */
998 tty_mode
= (int)st
.st_mode
& 0777;
1002 fl
= fcntl(0, F_GETFL
, 0);
1003 if (fl
!= -1 && (fl
& (O_RDWR
|O_RDONLY
|O_WRONLY
)) == O_RDWR
)
1006 if (attach_fd
== -1)
1008 if ((n
= secopen(attach_tty
, O_RDWR
| O_NONBLOCK
, 0)) < 0)
1009 Panic(0, "Cannot open your terminal '%s' - please check.", attach_tty
);
1012 debug2("attach_tty is %s, attach_fd is %d\n", attach_tty
, attach_fd
);
1014 if ((attach_term
= getenv("TERM")) == 0 || *attach_term
== 0)
1015 Panic(0, "Please set a terminal type.");
1016 if (strlen(attach_term
) > sizeof(D_termname
) - 1)
1017 Panic(0, "$TERM too long - sorry.");
1018 GetTTY(0, &attach_Mode
);
1019 #ifdef DEBUGGGGGGGGGGGGGGG
1020 DebugTTY(&attach_Mode
);
1025 oumask
= umask(0); /* well, unsigned never fails? jw. */
1027 if ((oumask
= (int)umask(0)) == -1)
1028 Panic(errno
, "Cannot change umask to zero");
1030 SockDir
= getenv("SCREENDIR");
1033 if (strlen(SockDir
) >= MAXPATHLEN
- 1)
1034 Panic(0, "Ridiculously long $SCREENDIR - try again.");
1037 Panic(0, "No $SCREENDIR with multi screens, please.");
1044 sprintf(SockPath
, "%s/.screen", multi_home
);
1048 sprintf(SockPath
, "%s/S-%s", SockDir
, multi
);
1057 sprintf(SockPath
, "%s/.screen", home
);
1063 if (access(SockDir
, F_OK
))
1065 debug1("SockDir '%s' missing ...\n", SockDir
);
1066 if (UserContext() > 0)
1068 if (mkdir(SockDir
, 0700))
1072 if (UserStatus() <= 0)
1073 Panic(0, "Cannot make directory '%s'.", SockDir
);
1075 if (SockDir
!= SockPath
)
1076 strcpy(SockPath
, SockDir
);
1082 if (lstat(SockDir
, &st
))
1084 n
= (eff_uid
== 0 && (real_uid
|| eff_gid
== real_gid
)) ? 0755 :
1085 (eff_gid
!= real_gid
) ? 0775 :
1091 if (mkdir(SockDir
, n
) == -1)
1092 Panic(errno
, "Cannot make directory '%s'", SockDir
);
1096 if (!S_ISDIR(st
.st_mode
))
1097 Panic(0, "'%s' must be a directory.", SockDir
);
1098 if (eff_uid
== 0 && real_uid
&& (int)st
.st_uid
!= eff_uid
)
1099 Panic(0, "Directory '%s' must be owned by root.", SockDir
);
1100 n
= (eff_uid
== 0 && (real_uid
|| (st
.st_mode
& 0775) != 0775)) ? 0755 :
1101 (eff_gid
== (int)st
.st_gid
&& eff_gid
!= real_gid
) ? 0775 :
1103 if (((int)st
.st_mode
& 0777) != n
)
1104 Panic(0, "Directory '%s' must have mode %03o.", SockDir
, n
);
1106 sprintf(SockPath
, "%s/S-%s", SockDir
, LoginName
);
1107 if (access(SockPath
, F_OK
))
1109 if (mkdir(SockPath
, 0700) == -1)
1110 Panic(errno
, "Cannot make directory '%s'", SockPath
);
1111 (void) chown(SockPath
, real_uid
, real_gid
);
1117 if (stat(SockPath
, &st
) == -1)
1118 Panic(errno
, "Cannot access %s", SockPath
);
1120 if (!S_ISDIR(st
.st_mode
))
1121 Panic(0, "%s is not a directory.", SockPath
);
1125 if ((int)st
.st_uid
!= multi_uid
)
1126 Panic(0, "%s is not the owner of %s.", multi
, SockPath
);
1131 if ((int)st
.st_uid
!= real_uid
)
1132 Panic(0, "You are not the owner of %s.", SockPath
);
1134 if ((st
.st_mode
& 0777) != 0700)
1135 Panic(0, "Directory %s must have mode 700.", SockPath
);
1136 if (SockMatch
&& index(SockMatch
, '/'))
1137 Panic(0, "Bad session name '%s'", SockMatch
);
1138 SockName
= SockPath
+ strlen(SockPath
) + 1;
1140 (void) umask(oumask
);
1141 debug2("SockPath: %s SockMatch: %s\n", SockPath
, SockMatch
? SockMatch
: "NULL");
1143 #if defined(SYSV) && !defined(ISC)
1144 if (uname(&utsnam
) == -1)
1145 Panic(errno
, "uname");
1146 strncpy(HostName
, utsnam
.nodename
, sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1);
1147 HostName
[sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1] = '\0';
1149 (void) gethostname(HostName
, MAXSTR
);
1150 HostName
[MAXSTR
- 1] = '\0';
1152 if ((ap
= index(HostName
, '.')) != NULL
)
1161 real_uid
= multi_uid
;
1164 i
= FindSocket((int *)NULL
, &fo
, &oth
, SockMatch
);
1166 exit(8 + (fo
? ((oth
|| i
) ? 2 : 1) : 0) + i
);
1168 Panic(0, "No Sockets found in %s.\n", SockPath
);
1169 Panic(0, "%d Socket%s in %s.\n", fo
, fo
> 1 ? "s" : "", SockPath
);
1172 signal(SIG_BYE
, AttacherFinit
); /* prevent races */
1175 /* attach_tty is not mandatory */
1178 Panic(0, "Please specify a command.");
1180 SendCmdMessage(sty
, SockMatch
, av
);
1183 else if (rflag
|| xflag
)
1185 debug("screen -r: - is there anybody out there?\n");
1186 if (Attach(MSG_ATTACH
))
1193 Panic(0, "Can't create sessions of other users.");
1195 debug("screen -r: backend not responding -- still crying\n");
1197 else if (dflag
&& !mflag
)
1201 Msg(0, "[%s %sdetached.]\n", SockName
, (dflag
> 1 ? "power " : ""));
1205 if (!SockMatch
&& !mflag
&& sty
)
1207 /* attach_tty is not mandatory */
1210 nwin_options
.args
= av
;
1211 SendCreateMsg(sty
, &nwin
);
1215 nwin_compose(&nwin_default
, &nwin_options
, &nwin_default
);
1217 if (!detached
|| dflag
!= 2)
1225 Panic(errno
, "fork");
1233 sprintf(socknamebuf
, "%d.%s", MasterPid
, SockMatch
);
1235 sprintf(socknamebuf
, "%d.%s.%s", MasterPid
, stripdev(attach_tty
), HostName
);
1236 for (ap
= socknamebuf
; *ap
; ap
++)
1240 if (strlen(socknamebuf
) > NAME_MAX
)
1241 socknamebuf
[NAME_MAX
] = 0;
1243 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1250 PanicPid
= getppid();
1252 if (DefaultEsc
== -1)
1253 DefaultEsc
= Ctrl('a');
1254 if (DefaultMetaEsc
== -1)
1255 DefaultMetaEsc
= 'a';
1257 ap
= av0
+ strlen(av0
) - 1;
1260 if (!strncmp("screen", ap
, 6))
1262 strncpy(ap
, "SCREEN", 6); /* name this process "SCREEN-BACKEND" */
1274 if (dfp
&& dfp
!= stderr
)
1276 sprintf(buf
, "%s/SCREEN.%d", DEBUGDIR
, (int)getpid());
1277 if ((dfp
= fopen(buf
, "w")) == NULL
)
1280 (void) chmod(buf
, 0666);
1285 if (attach_fd
== -1)
1287 if ((n
= secopen(attach_tty
, O_RDWR
, 0)) < 0)
1288 Panic(0, "Cannot reopen '%s' - please check.", attach_tty
);
1295 freopen("/dev/null", "r", stdin
);
1296 freopen("/dev/null", "w", stdout
);
1301 freopen("/dev/null", "w", stderr
);
1302 debug("-- screen.back debug started\n");
1305 * This guarantees that the session owner is listed, even when we
1306 * start detached. From now on we should not refer to 'LoginName'
1307 * any more, use users->u_name instead.
1309 if (UserAdd(LoginName
, (char *)0, (struct acluser
**)0) < 0)
1310 Panic(0, "Could not create user info");
1313 if (MakeDisplay(LoginName
, attach_tty
, attach_term
, n
, getppid(), &attach_Mode
) == 0)
1314 Panic(0, "Could not alloc display");
1317 D_encoding
= nwin_options
.encoding
> 0 ? nwin_options
.encoding
: 0;
1318 debug1("D_encoding = %d\n", D_encoding
);
1324 /* user started us with -S option */
1325 sprintf(socknamebuf
, "%d.%s", (int)getpid(), SockMatch
);
1329 sprintf(socknamebuf
, "%d.%s.%s", (int)getpid(), stripdev(attach_tty
),
1332 for (ap
= socknamebuf
; *ap
; ap
++)
1336 if (strlen(socknamebuf
) > NAME_MAX
)
1338 debug2("Socketname %s truncated to %d chars\n", socknamebuf
, NAME_MAX
);
1339 socknamebuf
[NAME_MAX
] = 0;
1342 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1344 ServerSocket
= MakeServerSocket();
1351 ScriptSource(script_file
);
1357 # ifdef ALLOW_SYSSCREENRC
1358 if ((ap
= getenv("SYSSCREENRC")))
1359 (void)StartRc(ap
, 0);
1362 (void)StartRc(ETCSCREENRC
, 0);
1364 (void)StartRc(RcFileName
, 0);
1368 # endif /* UTNOKEEP */
1369 # endif /* UTMPOK */
1372 if (InitTermcap(0, 0))
1374 debug("Could not init termcap - exiting\n");
1375 fcntl(D_userfd
, F_SETFL
, 0); /* Flush sets FNBLOCK */
1378 Kill(D_userpid
, SIG_BYE
);
1381 MakeDefaultCanvas();
1393 signal(SIGHUP
, SigHup
);
1394 signal(SIGINT
, FinitHandler
);
1395 signal(SIGQUIT
, FinitHandler
);
1396 signal(SIGTERM
, FinitHandler
);
1398 signal(SIGTTIN
, SIG_IGN
);
1399 signal(SIGTTOU
, SIG_IGN
);
1405 SetMode(&D_OldMode
, &D_NewMode
, D_flow
, iflag
);
1406 /* Note: SetMode must be called _before_ FinishRc. */
1407 SetTTY(D_userfd
, &D_NewMode
);
1408 if (fcntl(D_userfd
, F_SETFL
, FNBLOCK
))
1409 Msg(errno
, "Warning: NBLOCK fcntl failed");
1412 brktty(-1); /* just try */
1413 signal(SIGCHLD
, SigChld
);
1415 # ifdef ALLOW_SYSSCREENRC
1416 if ((ap
= getenv("SYSSCREENRC")))
1420 FinishRc(ETCSCREENRC
);
1422 FinishRc(RcFileName
);
1424 debug2("UID %d EUID %d\n", (int)getuid(), (int)geteuid());
1425 if (windows
== NULL
)
1427 debug("We open one default window, as screenrc did not specify one.\n");
1428 if (MakeWindow(&nwin
) == -1)
1430 Msg(0, "Sorry, could not find a PTY.");
1441 if (display
&& default_startup
)
1442 display_copyright();
1443 signal(SIGINT
, SigInt
);
1444 if (rflag
&& (rflag
& 1) == 0 && !quietflag
)
1446 Msg(0, "New screen...");
1450 serv_read
.type
= EV_READ
;
1451 serv_read
.fd
= ServerSocket
;
1452 serv_read
.handler
= serv_read_fn
;
1455 serv_select
.pri
= -10;
1456 serv_select
.type
= EV_ALWAYS
;
1457 serv_select
.handler
= serv_select_fn
;
1458 evenq(&serv_select
);
1460 logflushev
.type
= EV_TIMEOUT
;
1461 logflushev
.handler
= logflush_fn
;
1469 WindowDied(p
, wstat
, wstat_valid
)
1476 if (ZombieKey_destroy
&& ZombieKey_onerror
&& wstat_valid
&&
1477 WIFEXITED(wstat
) && WEXITSTATUS(wstat
) == 0)
1480 if (ZombieKey_destroy
&& !killit
)
1482 char buf
[100], *s
, reason
[100];
1486 if (WIFEXITED(wstat
))
1487 if (WEXITSTATUS(wstat
))
1488 sprintf(reason
, "terminated with exit status %d", WEXITSTATUS(wstat
));
1490 sprintf(reason
, "terminated normally");
1491 else if (WIFSIGNALED(wstat
))
1492 sprintf(reason
, "terminated with signal %d%s", WTERMSIG(wstat
),
1494 WCOREDUMP(wstat
) ? " (core file generated)" : "");
1499 sprintf(reason
, "detached from window");
1504 s
[strlen(s
) - 1] = '\0';
1505 debug3("window %d (%s) going into zombie state fd %d",
1506 p
->w_number
, p
->w_title
, p
->w_ptyfd
);
1508 if (p
->w_slot
!= (slot_t
)0 && p
->w_slot
!= (slot_t
)-1)
1511 p
->w_slot
= 0; /* "detached" */
1516 p
->w_deadpid
= p
->w_pid
;
1519 /* p->w_y = p->w_bot; */
1520 p
->w_y
= MFindUsedLine(p
, p
->w_bot
, 1);
1521 sprintf(buf
, "\n\r=== Command %s (%s) ===", reason
, s
? s
: "?");
1522 WriteString(p
, buf
, strlen(buf
));
1523 WindowChanged(p
, 'f');
1544 signal(SIGCHLD
, SigChld
);
1547 if (stat(SockPath
, &st
) == -1)
1549 debug1("SigChldHandler: Yuck! cannot stat '%s'\n", SockPath
);
1550 if (!RecoverSocket())
1552 debug("SCREEN cannot recover from corrupt Socket, bye\n");
1556 debug1("'%s' reconstructed\n", SockPath
);
1559 debug2("SigChldHandler: stat '%s' o.k. (%03o)\n", SockPath
, (int)st
.st_mode
);
1565 debug("SigChld()\n");
1573 /* Hangup all displays */
1574 while ((display
= displays
) != 0)
1580 * the backend's Interrupt handler
1581 * we cannot insert the intrc directly, as we never know
1590 debug("SigInt()\n");
1591 if (fore
&& displays
)
1593 # if defined(TERMIO) || defined(POSIX)
1594 ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
1596 ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
1599 write(fore
->w_ptyfd
, &ibuf
, 1);
1602 signal(SIGINT
, SigInt
);
1603 debug("SigInt() careful\n");
1604 InterruptPlease
= 1;
1612 struct display
*disp
;
1615 #if defined(SYSVSIGS) && defined(SIGHASARG)
1616 signal(sigsig
, SIG_IGN
);
1622 sprintf(buf
, "\r\n[screen caught signal %d.%s]\r\n", sigsig
,
1624 sprintf(buf
, "\r\n[screen caught a fatal signal.%s]\r\n",
1626 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1628 #else /* SHADOWPW && !DEBUG */
1630 #endif /* SHADOWPW && !DEBUG */
1632 for (disp
= displays
; disp
; disp
= disp
->d_next
)
1634 fcntl(disp
->d_userfd
, F_SETFL
, 0);
1635 SetTTY(disp
->d_userfd
, &D_OldMode
);
1636 write(disp
->d_userfd
, buf
, strlen(buf
));
1637 Kill(disp
->d_userpid
, SIG_BYE
);
1639 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1640 Kill(getpid(), SIGKILL
);
1642 #else /* SHADOWPW && !DEBUG */
1644 #endif /* SHADOWPW && !DEBUG */
1652 struct win
*p
, *next
;
1661 while ((pid
= waitpid(-1, &wstat
, WNOHANG
| WUNTRACED
)) > 0)
1665 * From: rouilj@sni-usa.com (John Rouillard)
1666 * note that WUNTRACED is not documented to work, but it is defined in
1667 * /usr/include/sys/wait.h, so it may work
1669 while ((pid
= wait2(&wstat
, WNOHANG
| WUNTRACED
)) > 0)
1670 # else /* USE_WAIT2 */
1671 while ((pid
= wait3(&wstat
, WNOHANG
| WUNTRACED
, (struct rusage
*) 0)) > 0)
1672 # endif /* USE_WAIT2 */
1675 while ((pid
= wait(&wstat
)) < 0)
1679 #endif /* BSDJOBS */
1681 for (p
= windows
; p
; p
= next
)
1684 if ( (p
->w_pid
&& pid
== p
->w_pid
) ||
1685 (p
->w_deadpid
&& pid
== p
->w_deadpid
) )
1687 /* child has ceased to exist */
1691 if (WIFSTOPPED(wstat
))
1693 debug3("Window %d pid %d: WIFSTOPPED (sig %d)\n", p
->w_number
, pid
, WSTOPSIG(wstat
));
1695 if (WSTOPSIG(wstat
) == SIGTTIN
)
1697 Msg(0, "Suspended (tty input)");
1702 if (WSTOPSIG(wstat
) == SIGTTOU
)
1704 Msg(0, "Suspended (tty output)");
1708 /* Try to restart process */
1709 Msg(0, "Child has been stopped, restarting.");
1710 if (killpg(pid
, SIGCONT
))
1716 WindowDied(p
, wstat
, 1);
1721 if (p
->w_pwin
&& pid
== p
->w_pwin
->p_pid
)
1723 debug2("pseudo of win Nr %d died. pid == %d\n", p
->w_number
, p
->w_pwin
->p_pid
);
1731 debug1("pid %d not found - hope that's ok\n", pid
);
1738 FinitHandler SIGDEFARG
1741 debug1("FinitHandler called, sig %d.\n", sigsig
);
1743 debug("FinitHandler called.\n");
1753 signal(SIGCHLD
, SIG_DFL
);
1754 signal(SIGHUP
, SIG_IGN
);
1755 debug1("Finit(%d);\n", i
);
1761 struct win
*p
= windows
;
1762 windows
= windows
->w_next
;
1765 if (ServerSocket
!= -1)
1767 debug1("we unlink(%s)\n", SockPath
);
1772 (void) unlink(SockPath
);
1778 for (display
= displays
; display
; display
= display
->d_next
)
1786 AddStr("[screen is terminating]\r\n");
1788 SetTTY(D_userfd
, &D_OldMode
);
1789 fcntl(D_userfd
, F_SETFL
, 0);
1791 Kill(D_userpid
, SIG_BYE
);
1794 * we _cannot_ call eexit(i) here,
1795 * instead of playing with the Socket above. Sigh.
1805 if (ServerSocket
!= -1)
1807 debug1("we unlink(%s)\n", SockPath
);
1810 (void) unlink(SockPath
);
1820 debug1("Hangup %x\n", display
);
1826 if (auto_detach
|| displays
->d_next
)
1833 * Detach now has the following modes:
1834 *D_DETACH SIG_BYE detach backend and exit attacher
1835 *D_HANGUP SIG_BYE detach backend and exit attacher
1836 *D_STOP SIG_STOP stop attacher (and detach backend)
1837 *D_REMOTE SIG_BYE remote detach -- reattach to new attacher
1838 *D_POWER SIG_POWER_BYE power detach -- attacher kills his parent
1839 *D_REMOTE_POWER SIG_POWER_BYE remote power detach -- both
1840 *D_LOCK SIG_LOCK lock the attacher
1842 * we always remove our utmp slots. (even when "lock" or "stop")
1843 * Note: Take extra care here, we may be called by interrupt!
1856 signal(SIGHUP
, SIG_IGN
);
1857 debug1("Detach(%d)\n", mode
);
1869 AddStr("[detached]\r\n");
1877 #ifdef REMOTE_DETACH
1879 AddStr("[remote detached]\r\n");
1885 AddStr("[power detached]\r\n");
1886 if (PowDetachString
)
1888 AddStr(PowDetachString
);
1891 sign
= SIG_POWER_BYE
;
1893 #ifdef REMOTE_DETACH
1894 case D_REMOTE_POWER
:
1895 AddStr("[remote power detached]\r\n");
1896 if (PowDetachString
)
1898 AddStr(PowDetachString
);
1901 sign
= SIG_POWER_BYE
;
1908 /* tell attacher to lock terminal with a lockprg. */
1912 if (displays
->d_next
== 0)
1914 for (p
= windows
; p
; p
= p
->w_next
)
1916 if (p
->w_slot
!= (slot_t
) -1 && !(p
->w_lflag
& 2))
1920 * Set the slot to 0 to get the window
1923 p
->w_slot
= (slot_t
) 0;
1927 if (mode
!= D_HANGUP
)
1930 if (displays
->d_next
== 0 && console_window
)
1932 if (TtyGrabConsole(console_window
->w_ptyfd
, 0, "detach"))
1934 debug("could not release console - killing window\n");
1935 KillWindow(console_window
);
1936 display
= displays
; /* restore display */
1942 ReleaseAutoWritelock(display
, D_fore
);
1944 D_user
->u_detachwin
= D_fore
->w_number
;
1945 D_user
->u_detachotherwin
= D_other
? D_other
->w_number
: -1;
1947 AutosaveLayout(D_layout
);
1948 layout_last
= D_layout
;
1949 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
1951 p
= Layer2Window(cv
->c_layer
);
1952 SetCanvasWindow(cv
, 0);
1954 WindowChanged(p
, 'u');
1958 debug2("display: %#x displays: %#x\n", (unsigned int)display
, (unsigned int)displays
);
1961 /* Flag detached-ness */
1964 * tell father what to do. We do that after we
1965 * freed the tty, thus getty feels more comfortable on hpux
1966 * if it was a power detach.
1969 debug2("Detach: Signal %d to Attacher(%d)!\n", sign
, pid
);
1970 debug("Detach returns, we are successfully detached.\n");
1971 signal(SIGHUP
, SigHup
);
1981 return strncmp(e
, s
, l
) == 0 && e
[l
] == '=';
1987 register char **op
, **np
;
1988 static char stybuf
[MAXSTR
];
1990 for (op
= environ
; *op
; ++op
)
1993 free((char *)NewEnv
);
1994 NewEnv
= np
= (char **) malloc((unsigned) (op
- environ
+ 7 + 1) * sizeof(char **));
1997 sprintf(stybuf
, "STY=%s", strlen(SockName
) <= MAXSTR
- 5 ? SockName
: "?");
1998 *np
++ = stybuf
; /* NewEnv[0] */
1999 *np
++ = Term
; /* NewEnv[1] */
2000 np
++; /* room for SHELL */
2002 np
+= 2; /* room for TERMCAP and WINDOW */
2004 np
+= 4; /* room for TERMCAP WINDOW LINES COLUMNS */
2007 for (op
= environ
; *op
; ++op
)
2009 if (!IsSymbol(*op
, "TERM") && !IsSymbol(*op
, "TERMCAP")
2010 && !IsSymbol(*op
, "STY") && !IsSymbol(*op
, "WINDOW")
2011 && !IsSymbol(*op
, "SCREENCAP") && !IsSymbol(*op
, "SHELL")
2012 && !IsSymbol(*op
, "LINES") && !IsSymbol(*op
, "COLUMNS")
2021 #if defined(USEVARARGS) && defined(__STDC__)
2022 Msg(int err
, char *fmt
, VA_DOTS
)
2024 Msg(err
, fmt
, VA_DOTS
)
2031 char buf
[MAXPATHLEN
*2];
2036 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2043 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2044 buf
[sizeof(buf
) - 1] = 0;
2046 debug2("Msg('%s') (%#x);\n", buf
, (unsigned int)display
);
2048 if (display
&& displays
)
2052 for (display
= displays
; display
; display
= display
->d_next
)
2057 /* no displays but a display - must have forked.
2058 * send message to backend!
2060 char *tty
= D_usertty
;
2061 struct display
*olddisplay
= display
;
2062 display
= 0; /* only send once */
2063 SendErrorMsg(tty
, buf
);
2064 display
= olddisplay
;
2067 printf("%s\r\n", buf
);
2071 * Call FinitTerm for all displays, write a message to each and call eexit();
2075 #if defined(USEVARARGS) && defined(__STDC__)
2076 Panic(int err
, char *fmt
, VA_DOTS
)
2078 Panic(err
, fmt
, VA_DOTS
)
2085 char buf
[MAXPATHLEN
*2];
2090 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2097 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2098 buf
[sizeof(buf
) - 1] = 0;
2100 debug3("Panic('%s'); display=%x displays=%x\n", buf
, display
, displays
);
2101 if (displays
== 0 && display
== 0)
2103 printf("%s\r\n", buf
);
2105 Kill(PanicPid
, SIG_BYE
);
2107 else if (displays
== 0)
2109 /* no displays but a display - must have forked.
2110 * send message to backend!
2112 char *tty
= D_usertty
;
2114 SendErrorMsg(tty
, buf
);
2119 for (display
= displays
; display
; display
= display
->d_next
)
2128 SetTTY(D_userfd
, &D_OldMode
);
2129 fcntl(D_userfd
, F_SETFL
, 0);
2130 write(D_userfd
, buf
, strlen(buf
));
2131 write(D_userfd
, "\n", 1);
2134 Kill(D_userpid
, SIG_BYE
);
2137 if (tty_oldmode
>= 0)
2140 if (setuid(own_uid
))
2141 xseteuid(own_uid
); /* may be a loop. sigh. */
2145 debug1("Panic: changing back modes from %s\n", attach_tty
);
2146 chmod(attach_tty
, tty_oldmode
);
2154 * '^' is allowed as an escape mechanism for control characters. jw.
2156 * Added time insertion using ideas/code from /\ndy Jones
2157 * (andy@lingua.cltr.uq.OZ.AU) - thanks a lot!
2162 static const char days
[] = "SunMonTueWedThuFriSat";
2163 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2166 static char winmsg_buf
[MAXSTR
];
2167 #define MAX_WINMSG_REND 16 /* rendition changes */
2168 static int winmsg_rend
[MAX_WINMSG_REND
];
2169 static int winmsg_rendpos
[MAX_WINMSG_REND
];
2170 static int winmsg_numrend
;
2173 pad_expand(buf
, p
, numpad
, padlen
)
2182 padlen
= padlen
- (p
- buf
); /* space for rent */
2185 pn2
= pn
= p
+ padlen
;
2189 if (r
&& *p
!= 127 && p
- buf
== winmsg_rendpos
[r
- 1])
2191 winmsg_rendpos
[--r
] = pn
- buf
;
2198 i
= numpad
> 0 ? (padlen
+ numpad
- 1) / numpad
: 0;
2203 if (r
&& p
- buf
== winmsg_rendpos
[r
- 1])
2204 winmsg_rendpos
[--r
] = pn
- buf
;
2211 struct backtick
*next
;
2216 char result
[MAXSTR
];
2223 struct backtick
*backticks
;
2227 struct backtick
*bt
;
2232 for (p
= q
= bt
->result
; (c
= (unsigned char)*p
++) != 0;)
2236 if (c
>= ' ' || c
== '\005')
2243 backtick_fn(ev
, data
)
2247 struct backtick
*bt
;
2250 bt
= (struct backtick
*)data
;
2251 debug1("backtick_fn for #%d\n", bt
->num
);
2253 l
= read(ev
->fd
, bt
->buf
+ i
, MAXSTR
- i
);
2256 debug1("EOF on backtick #%d\n", bt
->num
);
2262 debug1("read %d bytes\n", l
);
2264 for (j
= 0; j
< l
; j
++)
2265 if (bt
->buf
[i
- j
- 1] == '\n')
2269 for (k
= i
- j
- 2; k
>= 0; k
--)
2270 if (bt
->buf
[k
] == '\n')
2273 bcopy(bt
->buf
+ k
, bt
->result
, i
- j
- k
);
2274 bt
->result
[i
- j
- k
- 1] = 0;
2275 backtick_filter(bt
);
2276 WindowChanged(0, '`');
2278 if (j
== l
&& i
== MAXSTR
)
2286 bcopy(bt
->buf
+ i
- j
, bt
->buf
, j
);
2293 setbacktick(num
, lifespan
, tick
, cmdv
)
2299 struct backtick
**btp
, *bt
;
2302 debug1("setbacktick called for backtick #%d\n", num
);
2303 for (btp
= &backticks
; (bt
= *btp
) != 0; btp
= &bt
->next
)
2310 for (v
= bt
->cmdv
; *v
; v
++)
2327 bt
= (struct backtick
*)malloc(sizeof *bt
);
2333 bzero(bt
, sizeof(*bt
));
2339 bt
->lifespan
= lifespan
;
2346 if (bt
->tick
== 0 && bt
->lifespan
== 0)
2348 debug("setbacktick: continuous mode\n");
2349 bt
->buf
= (char *)malloc(MAXSTR
);
2353 setbacktick(num
, 0, 0, (char **)0);
2356 bt
->ev
.type
= EV_READ
;
2357 bt
->ev
.fd
= readpipe(bt
->cmdv
);
2358 bt
->ev
.handler
= backtick_fn
;
2359 bt
->ev
.data
= (char *)bt
;
2366 runbacktick(bt
, tickp
, now
)
2367 struct backtick
*bt
;
2374 debug1("runbacktick called for backtick #%d\n", bt
->num
);
2375 if (bt
->tick
&& (!*tickp
|| bt
->tick
< *tickp
))
2377 if ((bt
->lifespan
== 0 && bt
->tick
== 0) || now
< bt
->bestbefore
)
2379 debug1("returning old result (%d)\n", bt
->lifespan
);
2382 f
= readpipe(bt
->cmdv
);
2386 while ((l
= read(f
, bt
->result
+ i
, sizeof(bt
->result
) - i
)) > 0)
2388 debug1("runbacktick: read %d bytes\n", l
);
2390 for (j
= 1; j
< l
; j
++)
2391 if (bt
->result
[i
- j
- 1] == '\n')
2393 if (j
== l
&& i
== sizeof(bt
->result
))
2395 j
= sizeof(bt
->result
) / 2;
2400 bcopy(bt
->result
+ i
- j
, bt
->result
, j
);
2405 bt
->result
[sizeof(bt
->result
) - 1] = '\n';
2406 if (i
&& bt
->result
[i
- 1] == '\n')
2408 debug1("runbacktick: finished, %d bytes\n", i
);
2410 backtick_filter(bt
);
2412 bt
->bestbefore
= now2
+ bt
->lifespan
;
2417 AppendWinMsgRend(str
, color
)
2422 if (winmsg_numrend
>= MAX_WINMSG_REND
)
2424 p
= winmsg_buf
+ strlen(winmsg_buf
);
2429 r
= ParseAttrColor(color
, 0, 0);
2433 winmsg_rend
[winmsg_numrend
] = r
;
2434 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2437 strncpy(p
, str
, winmsg_buf
+ sizeof(winmsg_buf
) - p
);
2441 MakeWinMsgEv(str
, win
, esc
, padlen
, ev
, rec
)
2451 register char *p
= winmsg_buf
;
2461 int qmflag
= 0, omflag
= 0, qmnumrend
= 0;
2468 struct backtick
*bt
;
2470 if (winmsg_numrend
>= 0)
2473 winmsg_numrend
= -winmsg_numrend
;
2476 if (ScriptProcessCaption(str
, win
, padlen
))
2484 gettimeofday(&now
, NULL
);
2485 for (s
= str
; *s
&& (l
= winmsg_buf
+ MAXSTR
- 1 - p
) > 0; s
++, p
++)
2491 if (*s
!= '^' && *s
>= 64)
2516 if (*++s
== esc
) /* double escape ? */
2518 if ((plusflg
= *s
== '+') != 0)
2520 if ((minusflg
= *s
== '-') != 0)
2522 if ((zeroflg
= *s
== '0') != 0)
2525 while(*s
>= '0' && *s
<= '9')
2526 num
= num
* 10 + (*s
++ - '0');
2527 if ((longflg
= *s
== 'L') != 0)
2535 if ((!qmflag
&& !omflag
) || omflag
== 1)
2538 if (qmnumrend
< winmsg_numrend
)
2539 winmsg_numrend
= qmnumrend
;
2545 qmnumrend
= winmsg_numrend
;
2546 qmflag
= omflag
= 0;
2552 if (qmflag
&& omflag
!= 1)
2556 qmnumrend
= winmsg_numrend
;
2561 if (qmnumrend
< winmsg_numrend
)
2562 winmsg_numrend
= qmnumrend
;
2566 case 'd': case 'D': case 'm': case 'M': case 'y': case 'Y':
2567 case 'a': case 'A': case 's': case 'c': case 'C':
2572 time_t nowsec
= now
.tv_sec
;
2573 tm
= localtime(&nowsec
);
2576 if (!tick
|| tick
> 3600)
2581 sprintf(p
, "%02d", tm
->tm_mday
% 100);
2585 strftime(p
, l
, (longflg
? "%A" : "%a"), tm
);
2587 sprintf(p
, "%3.3s", days
+ 3 * tm
->tm_wday
);
2591 sprintf(p
, "%02d", tm
->tm_mon
+ 1);
2595 strftime(p
, l
, (longflg
? "%B" : "%b"), tm
);
2597 sprintf(p
, "%3.3s", months
+ 3 * tm
->tm_mon
);
2601 sprintf(p
, "%02d", tm
->tm_year
% 100);
2604 sprintf(p
, "%04d", tm
->tm_year
+ 1900);
2607 sprintf(p
, tm
->tm_hour
>= 12 ? "pm" : "am");
2610 sprintf(p
, tm
->tm_hour
>= 12 ? "PM" : "AM");
2613 sprintf(p
, "%02d", tm
->tm_sec
);
2617 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", tm
->tm_hour
, tm
->tm_min
);
2618 if (!tick
|| tick
> 60)
2622 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", (tm
->tm_hour
+ 11) % 12 + 1, tm
->tm_min
);
2623 if (!tick
|| tick
> 60)
2643 if (!tick
|| tick
> 60)
2652 if (rec
>= 10 || (*s
== 'h' && (win
== 0 || win
->w_hstatus
== 0 || *win
->w_hstatus
== 0)))
2659 for (bt
= backticks
; bt
; bt
= bt
->next
)
2669 char savebuf
[sizeof(winmsg_buf
)];
2671 int oldnumrend
= winmsg_numrend
;
2674 strcpy(savebuf
, winmsg_buf
);
2675 winmsg_numrend
= -winmsg_numrend
;
2676 MakeWinMsgEv(*s
== 'h' ? win
->w_hstatus
: runbacktick(bt
, &oldtick
, now
.tv_sec
), win
, '\005', 0, (struct event
*)0, rec
+ 1);
2677 debug2("oldtick=%d tick=%d\n", oldtick
, tick
);
2678 if (!tick
|| oldtick
< tick
)
2680 if ((int)strlen(winmsg_buf
) < l
)
2681 strcat(savebuf
, winmsg_buf
);
2682 strcpy(winmsg_buf
, savebuf
);
2683 while (oldnumrend
< winmsg_numrend
)
2684 winmsg_rendpos
[oldnumrend
++] += p
- winmsg_buf
;
2693 struct win
*oldfore
= 0;
2701 ss
= AddWindows(p
, l
- 1, (*s
== 'w' ? 0 : 1) | (longflg
? 0 : 2) | (plusflg
? 4 : 0), win
? win
->w_number
: -1);
2714 AddOtherUsers(p
, l
- 1, win
);
2722 AddWindowFlags(p
, l
- 1, win
);
2729 if (win
&& (int)strlen(win
->w_title
) < l
)
2731 strcpy(p
, win
->w_title
);
2741 for (i
= 0; i
< 127; i
++)
2742 if (s
[i
] && s
[i
] != '}')
2746 if (s
[i
] == '}' && winmsg_numrend
< MAX_WINMSG_REND
)
2750 debug1("MakeWinMsg attrcolor %s\n", rbuf
);
2751 if (i
!= 1 || rbuf
[0] != '-')
2752 r
= ParseAttrColor(rbuf
, (char *)0, 0);
2753 if (r
!= -1 || (i
== 1 && rbuf
[0] == '-'))
2755 winmsg_rend
[winmsg_numrend
] = r
;
2756 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2766 if ((int)strlen(HostName
) < l
)
2768 strcpy(p
, HostName
);
2778 session_name
= strchr(SockName
, '.') + 1;
2779 if ((int)strlen(session_name
) < l
)
2781 strcpy(p
, session_name
);
2790 sprintf(p
, "%d", (plusflg
&& display
) ? D_userpid
: getpid());
2797 if (display
&& ((ev
&& ev
== &D_forecv
->c_captev
) || (!ev
&& win
&& win
== D_fore
)))
2798 minusflg
= !minusflg
;
2803 truncpos
= p
- winmsg_buf
;
2804 truncper
= num
> 100 ? 100 : num
;
2805 trunclong
= longflg
;
2811 if (num
|| zeroflg
|| plusflg
|| longflg
|| (*s
!= '='))
2813 /* expand all pads */
2816 num
= (plusflg
? lastpad
: padlen
) - num
;
2817 if (!plusflg
&& padlen
== 0)
2818 num
= p
- winmsg_buf
;
2823 if (*s
!= '=' && num
== 0 && !plusflg
)
2828 num
= p
- winmsg_buf
;
2830 num
= (padlen
- (plusflg
? lastpad
: 0)) * num
/ 100;
2836 if (num
> MAXSTR
- 1)
2839 p
= pad_expand(winmsg_buf
, p
, numpad
, num
);
2841 if (p
- winmsg_buf
> num
&& !longflg
)
2850 trunc
= lastpad
+ truncper
* (num
- lastpad
) / 100;
2853 if (trunc
< lastpad
)
2855 left
= truncpos
- trunc
;
2856 if (left
> p
- winmsg_buf
- num
)
2857 left
= p
- winmsg_buf
- num
;
2858 debug1("lastpad = %d, ", lastpad
);
2859 debug3("truncpos = %d, trunc = %d, left = %d\n", truncpos
, trunc
, left
);
2862 if (left
+ lastpad
> p
- winmsg_buf
)
2863 left
= p
- winmsg_buf
- lastpad
;
2864 if (p
- winmsg_buf
- lastpad
- left
> 0)
2865 bcopy(winmsg_buf
+ lastpad
+ left
, winmsg_buf
+ lastpad
, p
- winmsg_buf
- lastpad
- left
);
2868 while (r
&& winmsg_rendpos
[r
- 1] > lastpad
)
2871 winmsg_rendpos
[r
] -= left
;
2872 if (winmsg_rendpos
[r
] < lastpad
)
2873 winmsg_rendpos
[r
] = lastpad
;
2877 if (p
- winmsg_buf
> lastpad
)
2878 winmsg_buf
[lastpad
] = '.';
2879 if (p
- winmsg_buf
> lastpad
+ 1)
2880 winmsg_buf
[lastpad
+ 1] = '.';
2881 if (p
- winmsg_buf
> lastpad
+ 2)
2882 winmsg_buf
[lastpad
+ 2] = '.';
2885 if (p
- winmsg_buf
> num
)
2887 p
= winmsg_buf
+ num
;
2890 if (num
- 1 >= lastpad
)
2892 if (num
- 2 >= lastpad
)
2894 if (num
- 3 >= lastpad
)
2898 while (r
&& winmsg_rendpos
[r
- 1] > num
)
2899 winmsg_rendpos
[--r
] = num
;
2903 if (lastpad
> p
- winmsg_buf
)
2904 lastpad
= p
- winmsg_buf
;
2905 debug1("lastpad now %d\n", lastpad
);
2909 while (p
- winmsg_buf
< num
)
2911 lastpad
= p
- winmsg_buf
;
2914 debug1("lastpad2 now %d\n", lastpad
);
2920 *p
= 127; /* internal pad representation */
2934 sprintf(p
, "%*s", num
, num
> 1 ? "--" : "-");
2936 sprintf(p
, "%*d", num
, win
->w_number
);
2943 if (qmpos
&& !qmflag
)
2948 if (padlen
> MAXSTR
- 1)
2949 padlen
= MAXSTR
- 1;
2950 p
= pad_expand(winmsg_buf
, p
, numpad
, padlen
);
2954 evdeq(ev
); /* just in case */
2955 ev
->timeout
.tv_sec
= 0;
2956 ev
->timeout
.tv_usec
= 0;
2960 now
.tv_usec
= 100000;
2964 now
.tv_sec
+= tick
- (now
.tv_sec
% tick
);
2966 debug2("NEW timeout %d %d\n", ev
->timeout
.tv_sec
, tick
);
2972 MakeWinMsg(s
, win
, esc
)
2977 return MakeWinMsgEv(s
, win
, esc
, 0, (struct event
*)0, 0);
2981 PutWinMsg(s
, start
, max
)
2987 struct mchar rendstack
[MAX_WINMSG_REND
];
2990 if (s
!= winmsg_buf
)
2992 /* sorry, no fancy coloring available */
2993 debug1("PutWinMsg %s plain\n", s
);
3006 debug2("PutWinMsg %s start attr %x\n", s
, rend
.attr
);
3007 for (i
= 0; i
< winmsg_numrend
&& max
> 0; i
++)
3009 if (p
> winmsg_rendpos
[i
] || winmsg_rendpos
[i
] > l
)
3011 if (p
< winmsg_rendpos
[i
])
3013 n
= winmsg_rendpos
[i
] - p
;
3030 rend
= rendstack
[--rendstackn
];
3034 rendstack
[rendstackn
++] = rend
;
3035 ApplyAttrColor(r
, &rend
);
3037 SetRendition(&rend
);
3065 if ((j
= open("/dev/null", 0)) >= 0)
3072 while (dup(++i
) < 0 && errno
!= EBADF
)
3074 debug1(" [%d]\n", i
);
3087 serv_read_fn(ev
, data
)
3091 debug("Knock - knock!\n");
3096 serv_select_fn(ev
, data
)
3102 debug("serv_select_fn called\n");
3103 /* XXX: messages?? */
3108 if (InterruptPlease
)
3110 debug("Backend received interrupt\n");
3111 /* This approach is rather questionable in a multi-display
3113 if (fore
&& displays
)
3115 #if defined(TERMIO) || defined(POSIX)
3116 char ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
3118 char ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
3121 write(W_UWP(fore
) ? fore
->w_pwin
->p_ptyfd
: fore
->w_ptyfd
,
3123 debug1("Backend wrote interrupt to %d", fore
->w_number
);
3124 debug1("%s\n", W_UWP(fore
) ? " (pseudowin)" : "");
3126 write(fore
->w_ptyfd
, &ibuf
, 1);
3127 debug1("Backend wrote interrupt to %d\n", fore
->w_number
);
3130 InterruptPlease
= 0;
3133 for (p
= windows
; p
; p
= p
->w_next
)
3135 if (p
->w_bell
== BELL_FOUND
|| p
->w_bell
== BELL_VISUAL
)
3138 int visual
= p
->w_bell
== BELL_VISUAL
|| visual_bell
;
3139 p
->w_bell
= BELL_ON
;
3140 for (display
= displays
; display
; display
= display
->d_next
)
3142 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3143 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3147 p
->w_bell
= BELL_DONE
;
3148 Msg(0, "%s", MakeWinMsg(BellString
, p
, '%'));
3150 else if (visual
&& !D_VB
&& (!D_status
|| !D_status_bell
))
3152 Msg(0, "%s", VisualBellString
);
3156 debug1("using vbell timeout %d\n", VBellWait
);
3157 SetTimeout(&D_statusev
, VBellWait
);
3161 /* don't annoy the user with two messages */
3162 if (p
->w_monitor
== MON_FOUND
)
3163 p
->w_monitor
= MON_DONE
;
3164 WindowChanged(p
, 'f');
3166 if (p
->w_monitor
== MON_FOUND
)
3169 p
->w_monitor
= MON_ON
;
3170 for (display
= displays
; display
; display
= display
->d_next
)
3172 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3173 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3176 continue; /* user already sees window */
3178 if (!(ACLBYTE(p
->w_mon_notify
, D_user
->u_id
) & ACLBIT(D_user
->u_id
)))
3179 continue; /* user doesn't care */
3181 Msg(0, "%s", MakeWinMsg(ActivityString
, p
, '%'));
3182 p
->w_monitor
= MON_DONE
;
3184 WindowChanged(p
, 'f');
3188 for (display
= displays
; display
; display
= display
->d_next
)
3191 if (D_status
== STATUS_ON_WIN
)
3193 /* XXX: should use display functions! */
3194 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3198 /* normalize window, see resize.c */
3199 lx
= cv
->c_layer
->l_x
;
3200 ly
= cv
->c_layer
->l_y
;
3201 if (lx
== cv
->c_layer
->l_width
)
3203 if (ly
+ cv
->c_yoff
< cv
->c_ys
)
3205 int i
, n
= cv
->c_ys
- (ly
+ cv
->c_yoff
);
3206 cv
->c_yoff
= cv
->c_ys
- ly
;
3207 RethinkViewportOffsets(cv
);
3208 if (n
> cv
->c_layer
->l_height
)
3209 n
= cv
->c_layer
->l_height
;
3211 LScrollV(flayer
, -n
, 0, flayer
->l_height
- 1, 0);
3212 LayRedisplayLine(-1, -1, -1, 1);
3213 for (i
= 0; i
< n
; i
++)
3214 LayRedisplayLine(i
, 0, flayer
->l_width
- 1, 1);
3215 if (cv
== cv
->c_display
->d_forecv
)
3219 else if (ly
+ cv
->c_yoff
> cv
->c_ye
)
3221 int i
, n
= ly
+ cv
->c_yoff
- cv
->c_ye
;
3222 cv
->c_yoff
= cv
->c_ye
- ly
;
3223 RethinkViewportOffsets(cv
);
3224 if (n
> cv
->c_layer
->l_height
)
3225 n
= cv
->c_layer
->l_height
;
3227 LScrollV(flayer
, n
, 0, cv
->c_layer
->l_height
- 1, 0);
3228 LayRedisplayLine(-1, -1, -1, 1);
3229 for (i
= 0; i
< n
; i
++)
3230 LayRedisplayLine(i
+ flayer
->l_height
- n
, 0, flayer
->l_width
- 1, 1);
3231 if (cv
== cv
->c_display
->d_forecv
)
3235 if (lx
+ cv
->c_xoff
< cv
->c_xs
)
3237 int i
, n
= cv
->c_xs
- (lx
+ cv
->c_xoff
);
3238 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3239 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3240 if (cv
->c_xoff
+ n
> cv
->c_xs
)
3241 n
= cv
->c_xs
- cv
->c_xoff
;
3243 RethinkViewportOffsets(cv
);
3244 if (n
> cv
->c_layer
->l_width
)
3245 n
= cv
->c_layer
->l_width
;
3247 LayRedisplayLine(-1, -1, -1, 1);
3248 for (i
= 0; i
< flayer
->l_height
; i
++)
3250 LScrollH(flayer
, -n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3251 LayRedisplayLine(i
, 0, n
- 1, 1);
3253 if (cv
== cv
->c_display
->d_forecv
)
3257 else if (lx
+ cv
->c_xoff
> cv
->c_xe
)
3259 int i
, n
= lx
+ cv
->c_xoff
- cv
->c_xe
;
3260 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3261 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3262 if (cv
->c_xoff
- n
+ cv
->c_layer
->l_width
- 1 < cv
->c_xe
)
3263 n
= cv
->c_xoff
+ cv
->c_layer
->l_width
- 1 - cv
->c_xe
;
3265 RethinkViewportOffsets(cv
);
3266 if (n
> cv
->c_layer
->l_width
)
3267 n
= cv
->c_layer
->l_width
;
3269 LayRedisplayLine(-1, -1, -1, 1);
3270 for (i
= 0; i
< flayer
->l_height
; i
++)
3272 LScrollH(flayer
, n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3273 LayRedisplayLine(i
, flayer
->l_width
- n
, flayer
->l_width
- 1, 1);
3275 if (cv
== cv
->c_display
->d_forecv
)
3282 for (display
= displays
; display
; display
= display
->d_next
)
3284 if (D_status
== STATUS_ON_WIN
|| D_cvlist
== 0 || D_cvlist
->c_next
== 0)
3286 debug1("serv_select_fn: Restore on cv %#x\n", (int)D_forecv
);
3287 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
3292 logflush_fn(ev
, data
)
3300 if (!islogfile(NULL
))
3301 return; /* no more logfiles */
3303 n
= log_flush
? log_flush
: (logtstamp_after
+ 4) / 5;
3306 SetTimeout(ev
, n
* 1000);
3307 evenq(ev
); /* re-enqueue ourself */
3311 /* write fancy time-stamp */
3312 for (p
= windows
; p
; p
= p
->w_next
)
3316 p
->w_logsilence
+= n
;
3317 if (p
->w_logsilence
< logtstamp_after
)
3319 if (p
->w_logsilence
- n
>= logtstamp_after
)
3321 buf
= MakeWinMsg(logtstamp_string
, p
, '%');
3322 logfwrite(p
->w_log
, buf
, strlen(buf
));
3327 * Interprets ^?, ^@ and other ^-control-char notation.
3328 * Interprets \ddd octal notation
3330 * The result is placed in *cp, p is advanced behind the parsed expression and
3339 if (*p
== '^' && p
[1])
3349 else if (*p
== '\\' && *++p
<= '7' && *p
>= '0')
3353 *cp
= *cp
* 8 + *p
- '0';
3354 while (*++p
<= '7' && *p
>= '0');
3365 unsigned char buf
[2];
3368 SetEscape((struct acluser
*)0, -1, -1);
3371 if ((p
= ParseChar(p
, (char *)buf
)) == NULL
||
3372 (p
= ParseChar(p
, (char *)buf
+1)) == NULL
|| *p
)
3374 SetEscape((struct acluser
*)0, buf
[0], buf
[1]);