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 */
347 char socknamebuf
[2 * MAXSTR
];
349 char *myname
= (ac
== 0) ? "screen" : av
[0];
352 #ifdef _MODE_T /* (jw) */
357 #if defined(SYSV) && !defined(ISC)
358 struct utsname utsnam
;
360 struct NewWindow nwin
;
361 int detached
= 0; /* start up detached */
367 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
368 setcompat(COMPAT_POSIX
|COMPAT_BSDPROT
); /* turn on seteuid support */
370 #if defined(sun) && defined(SVR4)
372 /* Solaris' login blocks SIGHUP! This is _very bad_ */
375 sigprocmask(SIG_SETMASK
, &sset
, 0);
380 * First, close all unused descriptors
381 * (otherwise, we might have problems with the select() call)
387 sprintf(version
, "%d.%.2d.%.2d%s (%s) %s", REV
, VERS
,
388 PATCHLEVEL
, STATE
, ORIGIN
, DATE
);
389 nversion
= REV
* 10000 + VERS
* 100 + PATCHLEVEL
;
390 debug2("-- screen debug started %s (%s)\n", *av
, version
);
404 debug("NAMEDPIPE\n");
406 #if defined(SIGWINCH) && defined(TIOCGWINSZ)
407 debug("Window size changing enabled\n");
437 debug1("NAME_MAX = %d\n", NAME_MAX
);
440 BellString
= SaveStr("Bell in window %n");
441 VisualBellString
= SaveStr(" Wuff, Wuff!! ");
442 ActivityString
= SaveStr("Activity in window %n");
443 screenlogfile
= SaveStr("screenlog.%n");
444 logtstamp_string
= SaveStr("-- %n:%t -- time-stamp -- %M/%d/%y %c:%s --\n");
445 hstatusstring
= SaveStr("%h");
446 captionstring
= SaveStr("%3n %t");
447 timestring
= SaveStr("%c:%s %M %d %H%? %l%?");
448 wlisttit
= SaveStr("Num Name%=Flags");
449 wliststr
= SaveStr("%3n %t%=%f");
451 BufferFile
= SaveStr(DEFAULT_BUFFERFILE
);
457 default_startup
= (ac
> 1) ? 0 : 1;
459 VBellWait
= VBELLWAIT
* 1000;
460 MsgWait
= MSGWAIT
* 1000;
461 MsgMinWait
= MSGMINWAIT
* 1000;
462 SilenceWait
= SILENCEWAIT
;
467 zmodem_sendcmd
= SaveStr("!!! sz -vv -b ");
468 zmodem_recvcmd
= SaveStr("!!! rz -vv -b -E");
472 CompileKeys((char *)0, 0, mark_key_tab
);
476 screenencodings
= SaveStr(SCREENENCODINGS
);
482 nwin_options
= nwin_undef
;
483 strcpy(screenterm
, "screen");
485 logreopen_register(lf_secreopen
);
488 /* if this is a login screen, assume -RR */
497 ShellProg
= SaveStr(DefaultShell
); /* to prevent nasty circles */
502 if (--ac
> 0 && *ap
== '-')
504 if (ap
[1] == '-' && ap
[2] == 0)
510 if (ap
[1] == '-' && !strcmp(ap
, "--version"))
511 Panic(0, "Screen version %s", version
);
512 if (ap
[1] == '-' && !strcmp(ap
, "--help"))
513 exit_with_usage(myname
, NULL
, NULL
);
514 while (ap
&& *ap
&& *++ap
)
519 nwin_options
.aflag
= 1;
524 case 'p': /* preselect */
530 exit_with_usage(myname
, "Specify a window to preselect with -p", NULL
);
537 bd
.bd_start_braille
= 1;
546 exit_with_usage(myname
, "Specify an alternate rc-filename with -c", NULL
);
555 exit_with_usage(myname
, "Specify command characters with -e", NULL
);
559 Panic(0, "Two characters are required with -e option, not '%s'.", ap
);
568 nwin_options
.flowflag
= FLOW_NOW
* 0;
575 nwin_options
.flowflag
= FLOW_NOW
* 1;
578 nwin_options
.flowflag
= FLOW_AUTOFLAG
;
581 exit_with_usage(myname
, "Unknown flow option -%s", --ap
);
586 exit_with_usage(myname
, NULL
, NULL
);
587 nwin_options
.histheight
= atoi(*++av
);
588 if (nwin_options
.histheight
< 0)
589 exit_with_usage(myname
, "-h: %s: negative scrollback size?", *av
);
594 case 't': /* title, the former AkA == -k */
596 exit_with_usage(myname
, "Specify a new window-name with -t", NULL
);
597 nwin_options
.aka
= *++av
;
605 nwin_options
.lflag
= 0;
612 nwin_options
.lflag
= 1;
615 nwin_options
.lflag
= 3;
618 case 'i': /* -list */
620 if (ac
> 1 && !SockMatch
)
628 exit_with_usage(myname
, "%s: Unknown suboption to -l", --ap
);
634 if (ac
> 1 && !SockMatch
)
641 nwin_options
.Lflag
= 1;
646 case 'O': /* to be (or not to be?) deleted. jw. */
651 exit_with_usage(myname
, "Specify terminal-type with -T", NULL
);
652 if (strlen(*++av
) < 20)
653 strcpy(screenterm
, *av
);
655 Panic(0, "-T: terminal name too long. (max. 20 char)");
656 nwin_options
.term
= screenterm
;
666 if (ac
> 1 && *av
[1] != '-' && !SockMatch
)
670 debug2("rflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
678 rflag
+= (*ap
== 'R') ? 2 : 1;
689 if (*av
[1] != '-' && !SockMatch
)
693 debug2("dflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
700 exit_with_usage(myname
, "Specify shell with -s", NULL
);
703 ShellProg
= SaveStr(*++av
);
704 debug1("ShellProg: '%s'\n", ShellProg
);
710 exit_with_usage(myname
, "Specify session-name with -S", NULL
);
714 exit_with_usage(myname
, "Empty session-name?", NULL
);
720 Panic(0, "Screen version %s", version
);
724 nwin_options
.encoding
= nwin_options
.encoding
== -1 ? UTF8
: 0;
728 exit_with_usage(myname
, "Unknown option %s", --ap
);
740 if (eff_uid
!= real_uid
)
742 /* if running with s-bit, we must install a special signal
743 * handler routine that resets the s-bit, so that we get a
746 #ifdef SIGBUS /* OOPS, linux has no bus errors! */
747 signal(SIGBUS
, CoreDump
);
749 signal(SIGSEGV
, CoreDump
);
753 setlocale(LC_ALL
, "");
756 if (nwin_options
.encoding
== -1)
758 /* ask locale if we should start in UTF-8 mode */
759 # ifdef HAVE_NL_LANGINFO
761 setlocale(LC_CTYPE
, "");
763 nwin_options
.encoding
= FindEncoding(nl_langinfo(CODESET
));
764 debug1("locale says encoding = %d\n", nwin_options
.encoding
);
768 if (((s
= getenv("LC_ALL")) || (s
= getenv("LC_CTYPE")) ||
769 (s
= getenv("LANG"))) && InStr(s
, "UTF-8"))
770 nwin_options
.encoding
= UTF8
;
772 debug1("environment says encoding=%d\n", nwin_options
.encoding
);
778 if((s
= getenv("LC_ALL")) || (s
= getenv("LC_CTYPE")) ||
779 (s
= getenv("LANG")))
781 if(!strncmp(s
, "zh_", 3) || !strncmp(s
, "ja_", 3) || !strncmp(s
, "ko_", 3))
789 if (SockMatch
&& strlen(SockMatch
) >= MAXSTR
)
790 Panic(0, "Ridiculously long socketname - try again.");
791 if (cmdflag
&& !rflag
&& !dflag
&& !xflag
)
793 if (!cmdflag
&& dflag
&& mflag
&& !(rflag
|| xflag
))
797 nwin
.encoding
= nwin_undef
.encoding
; /* let screenrc overwrite it */
802 /* make the write() calls return -1 on all errors */
805 * Ronald F. Guilmette, Oct 29 '94, bug-gnu-utils@prep.ai.mit.edu:
806 * It appears that in System V Release 4, UNIX, if you are writing
807 * an output file and you exceed the currently set file size limit,
808 * you _don't_ just get the call to `write' returning with a
809 * failure code. Rather, you get a signal called `SIGXFSZ' which,
810 * if neither handled nor ignored, will cause your program to crash
813 signal(SIGXFSZ
, SIG_IGN
);
817 signal(SIGPIPE
, SIG_IGN
);
824 sh
= getenv("SHELL");
825 ShellProg
= SaveStr(sh
? sh
: DefaultShell
);
827 ShellArgs
[0] = ShellProg
;
828 home
= getenv("HOME");
829 if (!mflag
&& !SockMatch
)
832 if (sty
&& *sty
== 0)
837 if (!(nethackflag
= (getenv("NETHACKOPTIONS") != NULL
)))
839 char nethackrc
[MAXPATHLEN
];
841 if (home
&& (strlen(home
) < (MAXPATHLEN
- 20)))
843 sprintf(nethackrc
,"%s/.nethackrc", home
);
844 nethackflag
= !access(nethackrc
, F_OK
);
850 own_uid
= multi_uid
= real_uid
;
851 if (SockMatch
&& (sockp
= index(SockMatch
, '/')))
854 Panic(0, "Must run suid root for multiuser support.");
857 SockMatch
= sockp
+ 1;
861 if ((mppp
= getpwnam(multi
)) == (struct passwd
*)0)
862 Panic(0, "Cannot identify account '%s'.", multi
);
863 multi_uid
= mppp
->pw_uid
;
864 multi_home
= SaveStr(mppp
->pw_dir
);
865 if (strlen(multi_home
) > MAXPATHLEN
- 10)
866 Panic(0, "home directory path too long");
868 /* always fake multi attach mode */
876 if (SockMatch
&& *SockMatch
== 0)
878 #endif /* MULTIUSER */
880 if ((LoginName
= getlogin()) && LoginName
[0] != '\0')
882 if ((ppp
= getpwnam(LoginName
)) != (struct passwd
*) 0)
883 if ((int)ppp
->pw_uid
!= real_uid
)
884 ppp
= (struct passwd
*) 0;
888 if ((ppp
= getpwuid(real_uid
)) == 0)
890 Panic(0, "getpwuid() can't identify your account!");
893 LoginName
= ppp
->pw_name
;
895 LoginName
= SaveStr(LoginName
);
897 ppp
= getpwbyname(LoginName
, ppp
);
899 #if !defined(SOCKDIR) && defined(MULTIUSER)
900 if (multi
&& !multiattach
)
902 if (home
&& strcmp(home
, ppp
->pw_dir
))
903 Panic(0, "$HOME must match passwd entry for multiuser screens.");
907 #define SET_GUID() do \
911 eff_uid = real_uid; \
912 eff_gid = real_gid; \
915 #define SET_TTYNAME(fatal) do \
917 if (!(attach_tty = ttyname(0))) \
920 Panic(0, "Must be connected to a terminal."); \
924 else if (stat(attach_tty, &st)) \
925 Panic(errno, "Cannot access '%s'", attach_tty); \
926 if (strlen(attach_tty) >= MAXPATHLEN) \
927 Panic(0, "TtyName too long - sorry."); \
930 if (home
== 0 || *home
== '\0')
932 if (strlen(LoginName
) > 20)
933 Panic(0, "LoginName too long - sorry.");
935 if (multi
&& strlen(multi
) > 20)
936 Panic(0, "Screen owner name too long - sorry.");
938 if (strlen(home
) > MAXPATHLEN
- 25)
939 Panic(0, "$HOME too long - sorry.");
942 if (!detached
&& !lsflag
&& !cmdflag
&& !(dflag
&& !mflag
&& !rflag
&& !xflag
) && !(!mflag
&& !SockMatch
&& sty
))
948 /* ttyname implies isatty */
951 tty_mode
= (int)st
.st_mode
& 0777;
955 fl
= fcntl(0, F_GETFL
, 0);
956 if (fl
!= -1 && (fl
& (O_RDWR
|O_RDONLY
|O_WRONLY
)) == O_RDWR
)
961 if ((n
= secopen(attach_tty
, O_RDWR
| O_NONBLOCK
, 0)) < 0)
962 Panic(0, "Cannot open your terminal '%s' - please check.", attach_tty
);
965 debug2("attach_tty is %s, attach_fd is %d\n", attach_tty
, attach_fd
);
967 if ((attach_term
= getenv("TERM")) == 0 || *attach_term
== 0)
968 Panic(0, "Please set a terminal type.");
969 if (strlen(attach_term
) > sizeof(D_termname
) - 1)
970 Panic(0, "$TERM too long - sorry.");
971 GetTTY(0, &attach_Mode
);
972 #ifdef DEBUGGGGGGGGGGGGGGG
973 DebugTTY(&attach_Mode
);
978 oumask
= umask(0); /* well, unsigned never fails? jw. */
980 if ((oumask
= (int)umask(0)) == -1)
981 Panic(errno
, "Cannot change umask to zero");
983 SockDir
= getenv("SCREENDIR");
986 if (strlen(SockDir
) >= MAXPATHLEN
- 1)
987 Panic(0, "Ridiculously long $SCREENDIR - try again.");
990 Panic(0, "No $SCREENDIR with multi screens, please.");
997 sprintf(SockPath
, "%s/.screen", multi_home
);
1001 sprintf(SockPath
, "%s/S-%s", SockDir
, multi
);
1010 sprintf(SockPath
, "%s/.screen", home
);
1016 if (access(SockDir
, F_OK
))
1018 debug1("SockDir '%s' missing ...\n", SockDir
);
1019 if (UserContext() > 0)
1021 if (mkdir(SockDir
, 0700))
1025 if (UserStatus() <= 0)
1026 Panic(0, "Cannot make directory '%s'.", SockDir
);
1028 if (SockDir
!= SockPath
)
1029 strcpy(SockPath
, SockDir
);
1035 if (lstat(SockDir
, &st
))
1037 n
= (eff_uid
== 0 && (real_uid
|| eff_gid
== real_gid
)) ? 0755 :
1038 (eff_gid
!= real_gid
) ? 0775 :
1044 if (mkdir(SockDir
, n
) == -1)
1045 Panic(errno
, "Cannot make directory '%s'", SockDir
);
1049 if (!S_ISDIR(st
.st_mode
))
1050 Panic(0, "'%s' must be a directory.", SockDir
);
1051 if (eff_uid
== 0 && real_uid
&& (int)st
.st_uid
!= eff_uid
)
1052 Panic(0, "Directory '%s' must be owned by root.", SockDir
);
1053 n
= (eff_uid
== 0 && (real_uid
|| (st
.st_mode
& 0775) != 0775)) ? 0755 :
1054 (eff_gid
== (int)st
.st_gid
&& eff_gid
!= real_gid
) ? 0775 :
1056 if (((int)st
.st_mode
& 0777) != n
)
1057 Panic(0, "Directory '%s' must have mode %03o.", SockDir
, n
);
1059 sprintf(SockPath
, "%s/S-%s", SockDir
, LoginName
);
1060 if (access(SockPath
, F_OK
))
1062 if (mkdir(SockPath
, 0700) == -1)
1063 Panic(errno
, "Cannot make directory '%s'", SockPath
);
1064 (void) chown(SockPath
, real_uid
, real_gid
);
1070 if (stat(SockPath
, &st
) == -1)
1071 Panic(errno
, "Cannot access %s", SockPath
);
1073 if (!S_ISDIR(st
.st_mode
))
1074 Panic(0, "%s is not a directory.", SockPath
);
1078 if ((int)st
.st_uid
!= multi_uid
)
1079 Panic(0, "%s is not the owner of %s.", multi
, SockPath
);
1084 if ((int)st
.st_uid
!= real_uid
)
1085 Panic(0, "You are not the owner of %s.", SockPath
);
1087 if ((st
.st_mode
& 0777) != 0700)
1088 Panic(0, "Directory %s must have mode 700.", SockPath
);
1089 if (SockMatch
&& index(SockMatch
, '/'))
1090 Panic(0, "Bad session name '%s'", SockMatch
);
1091 SockName
= SockPath
+ strlen(SockPath
) + 1;
1093 (void) umask(oumask
);
1094 debug2("SockPath: %s SockMatch: %s\n", SockPath
, SockMatch
? SockMatch
: "NULL");
1096 #if defined(SYSV) && !defined(ISC)
1097 if (uname(&utsnam
) == -1)
1098 Panic(errno
, "uname");
1099 strncpy(HostName
, utsnam
.nodename
, sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1);
1100 HostName
[sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1] = '\0';
1102 (void) gethostname(HostName
, MAXSTR
);
1103 HostName
[MAXSTR
- 1] = '\0';
1105 if ((ap
= index(HostName
, '.')) != NULL
)
1114 real_uid
= multi_uid
;
1117 i
= FindSocket((int *)NULL
, &fo
, &oth
, SockMatch
);
1119 exit(8 + (fo
? ((oth
|| i
) ? 2 : 1) : 0) + i
);
1121 Panic(0, "No Sockets found in %s.\n", SockPath
);
1122 Panic(0, "%d Socket%s in %s.\n", fo
, fo
> 1 ? "s" : "", SockPath
);
1125 signal(SIG_BYE
, AttacherFinit
); /* prevent races */
1128 /* attach_tty is not mandatory */
1131 Panic(0, "Please specify a command.");
1133 SendCmdMessage(sty
, SockMatch
, av
);
1136 else if (rflag
|| xflag
)
1138 debug("screen -r: - is there anybody out there?\n");
1139 if (Attach(MSG_ATTACH
))
1146 Panic(0, "Can't create sessions of other users.");
1148 debug("screen -r: backend not responding -- still crying\n");
1150 else if (dflag
&& !mflag
)
1152 (void) Attach(MSG_DETACH
);
1153 Msg(0, "[%s %sdetached.]\n", SockName
, (dflag
> 1 ? "power " : ""));
1157 if (!SockMatch
&& !mflag
&& sty
)
1159 /* attach_tty is not mandatory */
1162 nwin_options
.args
= av
;
1163 SendCreateMsg(sty
, &nwin
);
1167 nwin_compose(&nwin_default
, &nwin_options
, &nwin_default
);
1169 if (!detached
|| dflag
!= 2)
1177 Panic(errno
, "fork");
1185 sprintf(socknamebuf
, "%d.%s", MasterPid
, SockMatch
);
1187 sprintf(socknamebuf
, "%d.%s.%s", MasterPid
, stripdev(attach_tty
), HostName
);
1188 for (ap
= socknamebuf
; *ap
; ap
++)
1192 if (strlen(socknamebuf
) > NAME_MAX
)
1193 socknamebuf
[NAME_MAX
] = 0;
1195 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1202 PanicPid
= getppid();
1204 if (DefaultEsc
== -1)
1205 DefaultEsc
= Ctrl('a');
1206 if (DefaultMetaEsc
== -1)
1207 DefaultMetaEsc
= 'a';
1209 ap
= av0
+ strlen(av0
) - 1;
1212 if (!strncmp("screen", ap
, 6))
1214 strncpy(ap
, "SCREEN", 6); /* name this process "SCREEN-BACKEND" */
1226 if (dfp
&& dfp
!= stderr
)
1228 sprintf(buf
, "%s/SCREEN.%d", DEBUGDIR
, (int)getpid());
1229 if ((dfp
= fopen(buf
, "w")) == NULL
)
1232 (void) chmod(buf
, 0666);
1237 if (attach_fd
== -1)
1239 if ((n
= secopen(attach_tty
, O_RDWR
, 0)) < 0)
1240 Panic(0, "Cannot reopen '%s' - please check.", attach_tty
);
1247 freopen("/dev/null", "r", stdin
);
1248 freopen("/dev/null", "w", stdout
);
1253 freopen("/dev/null", "w", stderr
);
1254 debug("-- screen.back debug started\n");
1257 * This guarantees that the session owner is listed, even when we
1258 * start detached. From now on we should not refer to 'LoginName'
1259 * any more, use users->u_name instead.
1261 if (UserAdd(LoginName
, (char *)0, (struct acluser
**)0) < 0)
1262 Panic(0, "Could not create user info");
1265 if (MakeDisplay(LoginName
, attach_tty
, attach_term
, n
, getppid(), &attach_Mode
) == 0)
1266 Panic(0, "Could not alloc display");
1269 D_encoding
= nwin_options
.encoding
> 0 ? nwin_options
.encoding
: 0;
1270 debug1("D_encoding = %d\n", D_encoding
);
1276 /* user started us with -S option */
1277 sprintf(socknamebuf
, "%d.%s", (int)getpid(), SockMatch
);
1281 sprintf(socknamebuf
, "%d.%s.%s", (int)getpid(), stripdev(attach_tty
),
1284 for (ap
= socknamebuf
; *ap
; ap
++)
1288 if (strlen(socknamebuf
) > NAME_MAX
)
1290 debug2("Socketname %s truncated to %d chars\n", socknamebuf
, NAME_MAX
);
1291 socknamebuf
[NAME_MAX
] = 0;
1294 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1296 ServerSocket
= MakeServerSocket();
1299 # ifdef ALLOW_SYSSCREENRC
1300 if ((ap
= getenv("SYSSCREENRC")))
1301 (void)StartRc(ap
, 0);
1304 (void)StartRc(ETCSCREENRC
, 0);
1306 (void)StartRc(RcFileName
, 0);
1310 # endif /* UTNOKEEP */
1311 # endif /* UTMPOK */
1314 if (InitTermcap(0, 0))
1316 debug("Could not init termcap - exiting\n");
1317 fcntl(D_userfd
, F_SETFL
, 0); /* Flush sets FNBLOCK */
1320 Kill(D_userpid
, SIG_BYE
);
1323 MakeDefaultCanvas();
1335 signal(SIGHUP
, SigHup
);
1336 signal(SIGINT
, FinitHandler
);
1337 signal(SIGQUIT
, FinitHandler
);
1338 signal(SIGTERM
, FinitHandler
);
1340 signal(SIGTTIN
, SIG_IGN
);
1341 signal(SIGTTOU
, SIG_IGN
);
1347 SetMode(&D_OldMode
, &D_NewMode
, D_flow
, iflag
);
1348 /* Note: SetMode must be called _before_ FinishRc. */
1349 SetTTY(D_userfd
, &D_NewMode
);
1350 if (fcntl(D_userfd
, F_SETFL
, FNBLOCK
))
1351 Msg(errno
, "Warning: NBLOCK fcntl failed");
1354 brktty(-1); /* just try */
1355 signal(SIGCHLD
, SigChld
);
1357 # ifdef ALLOW_SYSSCREENRC
1358 if ((ap
= getenv("SYSSCREENRC")))
1362 FinishRc(ETCSCREENRC
);
1364 FinishRc(RcFileName
);
1366 debug2("UID %d EUID %d\n", (int)getuid(), (int)geteuid());
1367 if (windows
== NULL
)
1369 debug("We open one default window, as screenrc did not specify one.\n");
1370 if (MakeWindow(&nwin
) == -1)
1372 Msg(0, "Sorry, could not find a PTY.");
1383 if (display
&& default_startup
)
1384 display_copyright();
1385 signal(SIGINT
, SigInt
);
1386 if (rflag
&& (rflag
& 1) == 0 && !quietflag
)
1388 Msg(0, "New screen...");
1392 serv_read
.type
= EV_READ
;
1393 serv_read
.fd
= ServerSocket
;
1394 serv_read
.handler
= serv_read_fn
;
1397 serv_select
.pri
= -10;
1398 serv_select
.type
= EV_ALWAYS
;
1399 serv_select
.handler
= serv_select_fn
;
1400 evenq(&serv_select
);
1402 logflushev
.type
= EV_TIMEOUT
;
1403 logflushev
.handler
= logflush_fn
;
1411 WindowDied(p
, wstat
, wstat_valid
)
1418 if (ZombieKey_destroy
&& ZombieKey_onerror
&& wstat_valid
&&
1419 WIFEXITED(wstat
) && WEXITSTATUS(wstat
) == 0)
1422 if (ZombieKey_destroy
&& !killit
)
1424 char buf
[100], *s
, reason
[100];
1428 if (WIFEXITED(wstat
))
1429 if (WEXITSTATUS(wstat
))
1430 sprintf(reason
, "terminated with exit status %d", WEXITSTATUS(wstat
));
1432 sprintf(reason
, "terminated normally");
1433 else if (WIFSIGNALED(wstat
))
1434 sprintf(reason
, "terminated with signal %d%s", WTERMSIG(wstat
),
1436 WCOREDUMP(wstat
) ? " (core file generated)" : "");
1441 sprintf(reason
, "detached from window");
1446 s
[strlen(s
) - 1] = '\0';
1447 debug3("window %d (%s) going into zombie state fd %d",
1448 p
->w_number
, p
->w_title
, p
->w_ptyfd
);
1450 if (p
->w_slot
!= (slot_t
)0 && p
->w_slot
!= (slot_t
)-1)
1453 p
->w_slot
= 0; /* "detached" */
1458 p
->w_deadpid
= p
->w_pid
;
1461 /* p->w_y = p->w_bot; */
1462 p
->w_y
= MFindUsedLine(p
, p
->w_bot
, 1);
1463 sprintf(buf
, "\n\r=== Command %s (%s) ===", reason
, s
? s
: "?");
1464 WriteString(p
, buf
, strlen(buf
));
1465 WindowChanged(p
, 'f');
1486 signal(SIGCHLD
, SigChld
);
1489 if (stat(SockPath
, &st
) == -1)
1491 debug1("SigChldHandler: Yuck! cannot stat '%s'\n", SockPath
);
1492 if (!RecoverSocket())
1494 debug("SCREEN cannot recover from corrupt Socket, bye\n");
1498 debug1("'%s' reconstructed\n", SockPath
);
1501 debug2("SigChldHandler: stat '%s' o.k. (%03o)\n", SockPath
, (int)st
.st_mode
);
1507 debug("SigChld()\n");
1515 /* Hangup all displays */
1516 while ((display
= displays
) != 0)
1522 * the backend's Interrupt handler
1523 * we cannot insert the intrc directly, as we never know
1532 debug("SigInt()\n");
1533 if (fore
&& displays
)
1535 # if defined(TERMIO) || defined(POSIX)
1536 ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
1538 ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
1541 write(fore
->w_ptyfd
, &ibuf
, 1);
1544 signal(SIGINT
, SigInt
);
1545 debug("SigInt() careful\n");
1546 InterruptPlease
= 1;
1554 struct display
*disp
;
1557 #if defined(SYSVSIGS) && defined(SIGHASARG)
1558 signal(sigsig
, SIG_IGN
);
1564 sprintf(buf
, "\r\n[screen caught signal %d.%s]\r\n", sigsig
,
1566 sprintf(buf
, "\r\n[screen caught a fatal signal.%s]\r\n",
1568 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1570 #else /* SHADOWPW && !DEBUG */
1572 #endif /* SHADOWPW && !DEBUG */
1574 for (disp
= displays
; disp
; disp
= disp
->d_next
)
1576 fcntl(disp
->d_userfd
, F_SETFL
, 0);
1577 SetTTY(disp
->d_userfd
, &D_OldMode
);
1578 write(disp
->d_userfd
, buf
, strlen(buf
));
1579 Kill(disp
->d_userpid
, SIG_BYE
);
1581 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1582 Kill(getpid(), SIGKILL
);
1584 #else /* SHADOWPW && !DEBUG */
1586 #endif /* SHADOWPW && !DEBUG */
1594 struct win
*p
, *next
;
1603 while ((pid
= waitpid(-1, &wstat
, WNOHANG
| WUNTRACED
)) > 0)
1607 * From: rouilj@sni-usa.com (John Rouillard)
1608 * note that WUNTRACED is not documented to work, but it is defined in
1609 * /usr/include/sys/wait.h, so it may work
1611 while ((pid
= wait2(&wstat
, WNOHANG
| WUNTRACED
)) > 0)
1612 # else /* USE_WAIT2 */
1613 while ((pid
= wait3(&wstat
, WNOHANG
| WUNTRACED
, (struct rusage
*) 0)) > 0)
1614 # endif /* USE_WAIT2 */
1617 while ((pid
= wait(&wstat
)) < 0)
1621 #endif /* BSDJOBS */
1623 for (p
= windows
; p
; p
= next
)
1626 if ( (p
->w_pid
&& pid
== p
->w_pid
) ||
1627 (p
->w_deadpid
&& pid
== p
->w_deadpid
) )
1629 /* child has ceased to exist */
1633 if (WIFSTOPPED(wstat
))
1635 debug3("Window %d pid %d: WIFSTOPPED (sig %d)\n", p
->w_number
, pid
, WSTOPSIG(wstat
));
1637 if (WSTOPSIG(wstat
) == SIGTTIN
)
1639 Msg(0, "Suspended (tty input)");
1644 if (WSTOPSIG(wstat
) == SIGTTOU
)
1646 Msg(0, "Suspended (tty output)");
1650 /* Try to restart process */
1651 Msg(0, "Child has been stopped, restarting.");
1652 if (killpg(pid
, SIGCONT
))
1658 WindowDied(p
, wstat
, 1);
1663 if (p
->w_pwin
&& pid
== p
->w_pwin
->p_pid
)
1665 debug2("pseudo of win Nr %d died. pid == %d\n", p
->w_number
, p
->w_pwin
->p_pid
);
1673 debug1("pid %d not found - hope that's ok\n", pid
);
1680 FinitHandler SIGDEFARG
1683 debug1("FinitHandler called, sig %d.\n", sigsig
);
1685 debug("FinitHandler called.\n");
1695 signal(SIGCHLD
, SIG_DFL
);
1696 signal(SIGHUP
, SIG_IGN
);
1697 debug1("Finit(%d);\n", i
);
1700 struct win
*p
= windows
;
1701 windows
= windows
->w_next
;
1704 if (ServerSocket
!= -1)
1706 debug1("we unlink(%s)\n", SockPath
);
1711 (void) unlink(SockPath
);
1717 for (display
= displays
; display
; display
= display
->d_next
)
1725 AddStr("[screen is terminating]\r\n");
1727 SetTTY(D_userfd
, &D_OldMode
);
1728 fcntl(D_userfd
, F_SETFL
, 0);
1730 Kill(D_userpid
, SIG_BYE
);
1733 * we _cannot_ call eexit(i) here,
1734 * instead of playing with the Socket above. Sigh.
1744 if (ServerSocket
!= -1)
1746 debug1("we unlink(%s)\n", SockPath
);
1749 (void) unlink(SockPath
);
1759 debug1("Hangup %x\n", display
);
1765 if (auto_detach
|| displays
->d_next
)
1772 * Detach now has the following modes:
1773 *D_DETACH SIG_BYE detach backend and exit attacher
1774 *D_HANGUP SIG_BYE detach backend and exit attacher
1775 *D_STOP SIG_STOP stop attacher (and detach backend)
1776 *D_REMOTE SIG_BYE remote detach -- reattach to new attacher
1777 *D_POWER SIG_POWER_BYE power detach -- attacher kills his parent
1778 *D_REMOTE_POWER SIG_POWER_BYE remote power detach -- both
1779 *D_LOCK SIG_LOCK lock the attacher
1781 * we always remove our utmp slots. (even when "lock" or "stop")
1782 * Note: Take extra care here, we may be called by interrupt!
1795 signal(SIGHUP
, SIG_IGN
);
1796 debug1("Detach(%d)\n", mode
);
1808 AddStr("[detached]\r\n");
1816 #ifdef REMOTE_DETACH
1818 AddStr("[remote detached]\r\n");
1824 AddStr("[power detached]\r\n");
1825 if (PowDetachString
)
1827 AddStr(PowDetachString
);
1830 sign
= SIG_POWER_BYE
;
1832 #ifdef REMOTE_DETACH
1833 case D_REMOTE_POWER
:
1834 AddStr("[remote power detached]\r\n");
1835 if (PowDetachString
)
1837 AddStr(PowDetachString
);
1840 sign
= SIG_POWER_BYE
;
1847 /* tell attacher to lock terminal with a lockprg. */
1851 if (displays
->d_next
== 0)
1853 for (p
= windows
; p
; p
= p
->w_next
)
1855 if (p
->w_slot
!= (slot_t
) -1 && !(p
->w_lflag
& 2))
1859 * Set the slot to 0 to get the window
1862 p
->w_slot
= (slot_t
) 0;
1866 if (mode
!= D_HANGUP
)
1869 if (displays
->d_next
== 0 && console_window
)
1871 if (TtyGrabConsole(console_window
->w_ptyfd
, 0, "detach"))
1873 debug("could not release console - killing window\n");
1874 KillWindow(console_window
);
1875 display
= displays
; /* restore display */
1881 ReleaseAutoWritelock(display
, D_fore
);
1883 D_user
->u_detachwin
= D_fore
->w_number
;
1884 D_user
->u_detachotherwin
= D_other
? D_other
->w_number
: -1;
1886 AutosaveLayout(D_layout
);
1887 layout_last
= D_layout
;
1888 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
1890 p
= Layer2Window(cv
->c_layer
);
1891 SetCanvasWindow(cv
, 0);
1893 WindowChanged(p
, 'u');
1897 debug2("display: %#x displays: %#x\n", (unsigned int)display
, (unsigned int)displays
);
1900 /* Flag detached-ness */
1903 * tell father what to do. We do that after we
1904 * freed the tty, thus getty feels more comfortable on hpux
1905 * if it was a power detach.
1908 debug2("Detach: Signal %d to Attacher(%d)!\n", sign
, pid
);
1909 debug("Detach returns, we are successfully detached.\n");
1910 signal(SIGHUP
, SigHup
);
1920 return strncmp(e
, s
, l
) == 0 && e
[l
] == '=';
1926 register char **op
, **np
;
1927 static char stybuf
[MAXSTR
];
1929 for (op
= environ
; *op
; ++op
)
1932 free((char *)NewEnv
);
1933 NewEnv
= np
= (char **) malloc((unsigned) (op
- environ
+ 7 + 1) * sizeof(char **));
1936 sprintf(stybuf
, "STY=%s", strlen(SockName
) <= MAXSTR
- 5 ? SockName
: "?");
1937 *np
++ = stybuf
; /* NewEnv[0] */
1938 *np
++ = Term
; /* NewEnv[1] */
1939 np
++; /* room for SHELL */
1941 np
+= 2; /* room for TERMCAP and WINDOW */
1943 np
+= 4; /* room for TERMCAP WINDOW LINES COLUMNS */
1946 for (op
= environ
; *op
; ++op
)
1948 if (!IsSymbol(*op
, "TERM") && !IsSymbol(*op
, "TERMCAP")
1949 && !IsSymbol(*op
, "STY") && !IsSymbol(*op
, "WINDOW")
1950 && !IsSymbol(*op
, "SCREENCAP") && !IsSymbol(*op
, "SHELL")
1951 && !IsSymbol(*op
, "LINES") && !IsSymbol(*op
, "COLUMNS")
1960 #if defined(USEVARARGS) && defined(__STDC__)
1961 Msg(int err
, char *fmt
, VA_DOTS
)
1963 Msg(err
, fmt
, VA_DOTS
)
1970 char buf
[MAXPATHLEN
*2];
1975 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
1982 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
1983 buf
[sizeof(buf
) - 1] = 0;
1985 debug2("Msg('%s') (%#x);\n", buf
, (unsigned int)display
);
1987 if (display
&& displays
)
1991 for (display
= displays
; display
; display
= display
->d_next
)
1996 /* no displays but a display - must have forked.
1997 * send message to backend!
1999 char *tty
= D_usertty
;
2000 struct display
*olddisplay
= display
;
2001 display
= 0; /* only send once */
2002 SendErrorMsg(tty
, buf
);
2003 display
= olddisplay
;
2006 printf("%s\r\n", buf
);
2010 * Call FinitTerm for all displays, write a message to each and call eexit();
2014 #if defined(USEVARARGS) && defined(__STDC__)
2015 Panic(int err
, char *fmt
, VA_DOTS
)
2017 Panic(err
, fmt
, VA_DOTS
)
2024 char buf
[MAXPATHLEN
*2];
2029 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2036 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2037 buf
[sizeof(buf
) - 1] = 0;
2039 debug3("Panic('%s'); display=%x displays=%x\n", buf
, display
, displays
);
2040 if (displays
== 0 && display
== 0)
2042 printf("%s\r\n", buf
);
2044 Kill(PanicPid
, SIG_BYE
);
2046 else if (displays
== 0)
2048 /* no displays but a display - must have forked.
2049 * send message to backend!
2051 char *tty
= D_usertty
;
2053 SendErrorMsg(tty
, buf
);
2058 for (display
= displays
; display
; display
= display
->d_next
)
2067 SetTTY(D_userfd
, &D_OldMode
);
2068 fcntl(D_userfd
, F_SETFL
, 0);
2069 write(D_userfd
, buf
, strlen(buf
));
2070 write(D_userfd
, "\n", 1);
2073 Kill(D_userpid
, SIG_BYE
);
2076 if (tty_oldmode
>= 0)
2079 if (setuid(own_uid
))
2080 xseteuid(own_uid
); /* may be a loop. sigh. */
2084 debug1("Panic: changing back modes from %s\n", attach_tty
);
2085 chmod(attach_tty
, tty_oldmode
);
2093 * '^' is allowed as an escape mechanism for control characters. jw.
2095 * Added time insertion using ideas/code from /\ndy Jones
2096 * (andy@lingua.cltr.uq.OZ.AU) - thanks a lot!
2101 static const char days
[] = "SunMonTueWedThuFriSat";
2102 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2105 static char winmsg_buf
[MAXSTR
];
2106 #define MAX_WINMSG_REND 16 /* rendition changes */
2107 static int winmsg_rend
[MAX_WINMSG_REND
];
2108 static int winmsg_rendpos
[MAX_WINMSG_REND
];
2109 static int winmsg_numrend
;
2112 pad_expand(buf
, p
, numpad
, padlen
)
2121 padlen
= padlen
- (p
- buf
); /* space for rent */
2124 pn2
= pn
= p
+ padlen
;
2128 if (r
&& p
- buf
== winmsg_rendpos
[r
- 1])
2130 winmsg_rendpos
[--r
] = pn
- buf
;
2137 i
= numpad
> 0 ? (padlen
+ numpad
- 1) / numpad
: 0;
2148 struct backtick
*next
;
2153 char result
[MAXSTR
];
2160 struct backtick
*backticks
;
2164 struct backtick
*bt
;
2169 for (p
= q
= bt
->result
; (c
= (unsigned char)*p
++) != 0;)
2173 if (c
>= ' ' || c
== '\005')
2180 backtick_fn(ev
, data
)
2184 struct backtick
*bt
;
2187 bt
= (struct backtick
*)data
;
2188 debug1("backtick_fn for #%d\n", bt
->num
);
2190 l
= read(ev
->fd
, bt
->buf
+ i
, MAXSTR
- i
);
2193 debug1("EOF on backtick #%d\n", bt
->num
);
2199 debug1("read %d bytes\n", l
);
2201 for (j
= 0; j
< l
; j
++)
2202 if (bt
->buf
[i
- j
- 1] == '\n')
2206 for (k
= i
- j
- 2; k
>= 0; k
--)
2207 if (bt
->buf
[k
] == '\n')
2210 bcopy(bt
->buf
+ k
, bt
->result
, i
- j
- k
);
2211 bt
->result
[i
- j
- k
- 1] = 0;
2212 backtick_filter(bt
);
2213 WindowChanged(0, '`');
2215 if (j
== l
&& i
== MAXSTR
)
2223 bcopy(bt
->buf
+ i
- j
, bt
->buf
, j
);
2230 setbacktick(num
, lifespan
, tick
, cmdv
)
2236 struct backtick
**btp
, *bt
;
2239 debug1("setbacktick called for backtick #%d\n", num
);
2240 for (btp
= &backticks
; (bt
= *btp
) != 0; btp
= &bt
->next
)
2247 for (v
= bt
->cmdv
; *v
; v
++)
2264 bt
= (struct backtick
*)malloc(sizeof *bt
);
2270 bzero(bt
, sizeof(*bt
));
2276 bt
->lifespan
= lifespan
;
2283 if (bt
->tick
== 0 && bt
->lifespan
== 0)
2285 debug("setbacktick: continuous mode\n");
2286 bt
->buf
= (char *)malloc(MAXSTR
);
2290 setbacktick(num
, 0, 0, (char **)0);
2293 bt
->ev
.type
= EV_READ
;
2294 bt
->ev
.fd
= readpipe(bt
->cmdv
);
2295 bt
->ev
.handler
= backtick_fn
;
2296 bt
->ev
.data
= (char *)bt
;
2303 runbacktick(bt
, tickp
, now
)
2304 struct backtick
*bt
;
2311 debug1("runbacktick called for backtick #%d\n", bt
->num
);
2312 if (bt
->tick
&& (!*tickp
|| bt
->tick
< *tickp
))
2314 if ((bt
->lifespan
== 0 && bt
->tick
== 0) || now
< bt
->bestbefore
)
2316 debug1("returning old result (%d)\n", bt
->lifespan
);
2319 f
= readpipe(bt
->cmdv
);
2323 while ((l
= read(f
, bt
->result
+ i
, sizeof(bt
->result
) - i
)) > 0)
2325 debug1("runbacktick: read %d bytes\n", l
);
2327 for (j
= 1; j
< l
; j
++)
2328 if (bt
->result
[i
- j
- 1] == '\n')
2330 if (j
== l
&& i
== sizeof(bt
->result
))
2332 j
= sizeof(bt
->result
) / 2;
2337 bcopy(bt
->result
+ i
- j
, bt
->result
, j
);
2342 bt
->result
[sizeof(bt
->result
) - 1] = '\n';
2343 if (i
&& bt
->result
[i
- 1] == '\n')
2345 debug1("runbacktick: finished, %d bytes\n", i
);
2347 backtick_filter(bt
);
2349 bt
->bestbefore
= now2
+ bt
->lifespan
;
2354 MakeWinMsgEv(str
, win
, esc
, padlen
, ev
, rec
)
2364 register char *p
= winmsg_buf
;
2374 int qmflag
= 0, omflag
= 0, qmnumrend
= 0;
2381 struct backtick
*bt
;
2383 if (winmsg_numrend
>= 0)
2386 winmsg_numrend
= -winmsg_numrend
;
2391 gettimeofday(&now
, NULL
);
2392 for (; *s
&& (l
= winmsg_buf
+ MAXSTR
- 1 - p
) > 0; s
++, p
++)
2398 if (*s
!= '^' && *s
>= 64)
2423 if (*++s
== esc
) /* double escape ? */
2425 if ((plusflg
= *s
== '+') != 0)
2427 if ((minusflg
= *s
== '-') != 0)
2429 if ((zeroflg
= *s
== '0') != 0)
2432 while(*s
>= '0' && *s
<= '9')
2433 num
= num
* 10 + (*s
++ - '0');
2434 if ((longflg
= *s
== 'L') != 0)
2442 if ((!qmflag
&& !omflag
) || omflag
== 1)
2445 if (qmnumrend
< winmsg_numrend
)
2446 winmsg_numrend
= qmnumrend
;
2452 qmnumrend
= winmsg_numrend
;
2453 qmflag
= omflag
= 0;
2459 if (qmflag
&& omflag
!= 1)
2463 qmnumrend
= winmsg_numrend
;
2468 if (qmnumrend
< winmsg_numrend
)
2469 winmsg_numrend
= qmnumrend
;
2473 case 'd': case 'D': case 'm': case 'M': case 'y': case 'Y':
2474 case 'a': case 'A': case 's': case 'c': case 'C':
2479 time_t nowsec
= now
.tv_sec
;
2480 tm
= localtime(&nowsec
);
2483 if (!tick
|| tick
> 3600)
2488 sprintf(p
, "%02d", tm
->tm_mday
% 100);
2492 strftime(p
, l
, (longflg
? "%A" : "%a"), tm
);
2494 sprintf(p
, "%3.3s", days
+ 3 * tm
->tm_wday
);
2498 sprintf(p
, "%02d", tm
->tm_mon
+ 1);
2502 strftime(p
, l
, (longflg
? "%B" : "%b"), tm
);
2504 sprintf(p
, "%3.3s", months
+ 3 * tm
->tm_mon
);
2508 sprintf(p
, "%02d", tm
->tm_year
% 100);
2511 sprintf(p
, "%04d", tm
->tm_year
+ 1900);
2514 sprintf(p
, tm
->tm_hour
>= 12 ? "pm" : "am");
2517 sprintf(p
, tm
->tm_hour
>= 12 ? "PM" : "AM");
2520 sprintf(p
, "%02d", tm
->tm_sec
);
2524 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", tm
->tm_hour
, tm
->tm_min
);
2525 if (!tick
|| tick
> 60)
2529 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", (tm
->tm_hour
+ 11) % 12 + 1, tm
->tm_min
);
2530 if (!tick
|| tick
> 60)
2550 if (!tick
|| tick
> 60)
2559 if (rec
>= 10 || (*s
== 'h' && (win
== 0 || win
->w_hstatus
== 0 || *win
->w_hstatus
== 0)))
2566 for (bt
= backticks
; bt
; bt
= bt
->next
)
2576 char savebuf
[sizeof(winmsg_buf
)];
2578 int oldnumrend
= winmsg_numrend
;
2581 strcpy(savebuf
, winmsg_buf
);
2582 winmsg_numrend
= -winmsg_numrend
;
2583 MakeWinMsgEv(*s
== 'h' ? win
->w_hstatus
: runbacktick(bt
, &oldtick
, now
.tv_sec
), win
, '\005', 0, (struct event
*)0, rec
+ 1);
2584 debug2("oldtick=%d tick=%d\n", oldtick
, tick
);
2585 if (!tick
|| oldtick
< tick
)
2587 if ((int)strlen(winmsg_buf
) < l
)
2588 strcat(savebuf
, winmsg_buf
);
2589 strcpy(winmsg_buf
, savebuf
);
2590 while (oldnumrend
< winmsg_numrend
)
2591 winmsg_rendpos
[oldnumrend
++] += p
- winmsg_buf
;
2600 struct win
*oldfore
= 0;
2608 ss
= AddWindows(p
, l
- 1, (*s
== 'w' ? 0 : 1) | (longflg
? 0 : 2) | (plusflg
? 4 : 0), win
? win
->w_number
: -1);
2621 AddOtherUsers(p
, l
- 1, win
);
2629 AddWindowFlags(p
, l
- 1, win
);
2636 if (win
&& (int)strlen(win
->w_title
) < l
)
2638 strcpy(p
, win
->w_title
);
2648 for (i
= 0; i
< 127; i
++)
2649 if (s
[i
] && s
[i
] != '}')
2653 if (s
[i
] == '}' && winmsg_numrend
< MAX_WINMSG_REND
)
2657 debug1("MakeWinMsg attrcolor %s\n", rbuf
);
2658 if (i
!= 1 || rbuf
[0] != '-')
2659 r
= ParseAttrColor(rbuf
, (char *)0, 0);
2660 if (r
!= -1 || (i
== 1 && rbuf
[0] == '-'))
2662 winmsg_rend
[winmsg_numrend
] = r
;
2663 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2673 if ((int)strlen(HostName
) < l
)
2675 strcpy(p
, HostName
);
2683 char * session_name
;
2684 session_name
= strchr(SockName
, '.') + 1;
2685 if ((int)strlen(session_name
) < l
)
2687 strcpy(p
, session_name
);
2696 if (display
&& ((ev
&& ev
== &D_forecv
->c_captev
) || (!ev
&& win
&& win
== D_fore
)))
2697 minusflg
= !minusflg
;
2702 truncpos
= p
- winmsg_buf
;
2703 truncper
= num
> 100 ? 100 : num
;
2704 trunclong
= longflg
;
2710 if (num
|| zeroflg
|| plusflg
|| longflg
|| (*s
!= '='))
2712 /* expand all pads */
2715 num
= (plusflg
? lastpad
: padlen
) - num
;
2716 if (!plusflg
&& padlen
== 0)
2717 num
= p
- winmsg_buf
;
2722 if (*s
!= '=' && num
== 0 && !plusflg
)
2727 num
= p
- winmsg_buf
;
2729 num
= (padlen
- (plusflg
? lastpad
: 0)) * num
/ 100;
2735 if (num
> MAXSTR
- 1)
2738 p
= pad_expand(winmsg_buf
, p
, numpad
, num
);
2740 if (p
- winmsg_buf
> num
&& !longflg
)
2749 trunc
= lastpad
+ truncper
* (num
- lastpad
) / 100;
2752 if (trunc
< lastpad
)
2754 left
= truncpos
- trunc
;
2755 if (left
> p
- winmsg_buf
- num
)
2756 left
= p
- winmsg_buf
- num
;
2757 debug1("lastpad = %d, ", lastpad
);
2758 debug3("truncpos = %d, trunc = %d, left = %d\n", truncpos
, trunc
, left
);
2761 if (left
+ lastpad
> p
- winmsg_buf
)
2762 left
= p
- winmsg_buf
- lastpad
;
2763 if (p
- winmsg_buf
- lastpad
- left
> 0)
2764 bcopy(winmsg_buf
+ lastpad
+ left
, winmsg_buf
+ lastpad
, p
- winmsg_buf
- lastpad
- left
);
2767 while (r
&& winmsg_rendpos
[r
- 1] > lastpad
)
2770 winmsg_rendpos
[r
] -= left
;
2771 if (winmsg_rendpos
[r
] < lastpad
)
2772 winmsg_rendpos
[r
] = lastpad
;
2776 if (p
- winmsg_buf
> lastpad
)
2777 winmsg_buf
[lastpad
] = '.';
2778 if (p
- winmsg_buf
> lastpad
+ 1)
2779 winmsg_buf
[lastpad
+ 1] = '.';
2780 if (p
- winmsg_buf
> lastpad
+ 2)
2781 winmsg_buf
[lastpad
+ 2] = '.';
2784 if (p
- winmsg_buf
> num
)
2786 p
= winmsg_buf
+ num
;
2789 if (num
- 1 >= lastpad
)
2791 if (num
- 2 >= lastpad
)
2793 if (num
- 3 >= lastpad
)
2797 while (r
&& winmsg_rendpos
[r
- 1] > num
)
2798 winmsg_rendpos
[--r
] = num
;
2802 if (lastpad
> p
- winmsg_buf
)
2803 lastpad
= p
- winmsg_buf
;
2804 debug1("lastpad now %d\n", lastpad
);
2808 while (p
- winmsg_buf
< num
)
2810 lastpad
= p
- winmsg_buf
;
2813 debug1("lastpad2 now %d\n", lastpad
);
2819 *p
= 127; /* internal pad representation */
2833 sprintf(p
, "%*s", num
, num
> 1 ? "--" : "-");
2835 sprintf(p
, "%*d", num
, win
->w_number
);
2842 if (qmpos
&& !qmflag
)
2847 if (padlen
> MAXSTR
- 1)
2848 padlen
= MAXSTR
- 1;
2849 p
= pad_expand(winmsg_buf
, p
, numpad
, padlen
);
2853 evdeq(ev
); /* just in case */
2854 ev
->timeout
.tv_sec
= 0;
2855 ev
->timeout
.tv_usec
= 0;
2859 now
.tv_usec
= 100000;
2863 now
.tv_sec
+= tick
- (now
.tv_sec
% tick
);
2865 debug2("NEW timeout %d %d\n", ev
->timeout
.tv_sec
, tick
);
2871 MakeWinMsg(s
, win
, esc
)
2876 return MakeWinMsgEv(s
, win
, esc
, 0, (struct event
*)0, 0);
2880 PutWinMsg(s
, start
, max
)
2886 struct mchar rendstack
[MAX_WINMSG_REND
];
2889 if (s
!= winmsg_buf
)
2891 /* sorry, no fancy coloring available */
2892 debug1("PutWinMsg %s plain\n", s
);
2905 debug2("PutWinMsg %s start attr %x\n", s
, rend
.attr
);
2906 for (i
= 0; i
< winmsg_numrend
&& max
> 0; i
++)
2908 if (p
> winmsg_rendpos
[i
] || winmsg_rendpos
[i
] > l
)
2910 if (p
< winmsg_rendpos
[i
])
2912 n
= winmsg_rendpos
[i
] - p
;
2929 rend
= rendstack
[--rendstackn
];
2933 rendstack
[rendstackn
++] = rend
;
2934 ApplyAttrColor(r
, &rend
);
2936 SetRendition(&rend
);
2964 if ((j
= open("/dev/null", 0)) >= 0)
2971 while (dup(++i
) < 0 && errno
!= EBADF
)
2973 debug1(" [%d]\n", i
);
2986 serv_read_fn(ev
, data
)
2990 debug("Knock - knock!\n");
2995 serv_select_fn(ev
, data
)
3001 debug("serv_select_fn called\n");
3002 /* XXX: messages?? */
3007 if (InterruptPlease
)
3009 debug("Backend received interrupt\n");
3010 /* This approach is rather questionable in a multi-display
3012 if (fore
&& displays
)
3014 #if defined(TERMIO) || defined(POSIX)
3015 char ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
3017 char ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
3020 write(W_UWP(fore
) ? fore
->w_pwin
->p_ptyfd
: fore
->w_ptyfd
,
3022 debug1("Backend wrote interrupt to %d", fore
->w_number
);
3023 debug1("%s\n", W_UWP(fore
) ? " (pseudowin)" : "");
3025 write(fore
->w_ptyfd
, &ibuf
, 1);
3026 debug1("Backend wrote interrupt to %d\n", fore
->w_number
);
3029 InterruptPlease
= 0;
3032 for (p
= windows
; p
; p
= p
->w_next
)
3034 if (p
->w_bell
== BELL_FOUND
|| p
->w_bell
== BELL_VISUAL
)
3037 int visual
= p
->w_bell
== BELL_VISUAL
|| visual_bell
;
3038 p
->w_bell
= BELL_ON
;
3039 for (display
= displays
; display
; display
= display
->d_next
)
3041 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3042 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3046 p
->w_bell
= BELL_DONE
;
3047 Msg(0, "%s", MakeWinMsg(BellString
, p
, '%'));
3049 else if (visual
&& !D_VB
&& (!D_status
|| !D_status_bell
))
3051 Msg(0, "%s", VisualBellString
);
3055 debug1("using vbell timeout %d\n", VBellWait
);
3056 SetTimeout(&D_statusev
, VBellWait
);
3060 /* don't annoy the user with two messages */
3061 if (p
->w_monitor
== MON_FOUND
)
3062 p
->w_monitor
= MON_DONE
;
3063 WindowChanged(p
, 'f');
3065 if (p
->w_monitor
== MON_FOUND
)
3068 p
->w_monitor
= MON_ON
;
3069 for (display
= displays
; display
; display
= display
->d_next
)
3071 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3072 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3075 continue; /* user already sees window */
3077 if (!(ACLBYTE(p
->w_mon_notify
, D_user
->u_id
) & ACLBIT(D_user
->u_id
)))
3078 continue; /* user doesn't care */
3080 Msg(0, "%s", MakeWinMsg(ActivityString
, p
, '%'));
3081 p
->w_monitor
= MON_DONE
;
3083 WindowChanged(p
, 'f');
3087 for (display
= displays
; display
; display
= display
->d_next
)
3090 if (D_status
== STATUS_ON_WIN
)
3092 /* XXX: should use display functions! */
3093 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3097 /* normalize window, see resize.c */
3098 lx
= cv
->c_layer
->l_x
;
3099 ly
= cv
->c_layer
->l_y
;
3100 if (lx
== cv
->c_layer
->l_width
)
3102 if (ly
+ cv
->c_yoff
< cv
->c_ys
)
3104 int i
, n
= cv
->c_ys
- (ly
+ cv
->c_yoff
);
3105 cv
->c_yoff
= cv
->c_ys
- ly
;
3106 RethinkViewportOffsets(cv
);
3107 if (n
> cv
->c_layer
->l_height
)
3108 n
= cv
->c_layer
->l_height
;
3110 LScrollV(flayer
, -n
, 0, flayer
->l_height
- 1, 0);
3111 LayRedisplayLine(-1, -1, -1, 1);
3112 for (i
= 0; i
< n
; i
++)
3113 LayRedisplayLine(i
, 0, flayer
->l_width
- 1, 1);
3114 if (cv
== cv
->c_display
->d_forecv
)
3118 else if (ly
+ cv
->c_yoff
> cv
->c_ye
)
3120 int i
, n
= ly
+ cv
->c_yoff
- cv
->c_ye
;
3121 cv
->c_yoff
= cv
->c_ye
- ly
;
3122 RethinkViewportOffsets(cv
);
3123 if (n
> cv
->c_layer
->l_height
)
3124 n
= cv
->c_layer
->l_height
;
3126 LScrollV(flayer
, n
, 0, cv
->c_layer
->l_height
- 1, 0);
3127 LayRedisplayLine(-1, -1, -1, 1);
3128 for (i
= 0; i
< n
; i
++)
3129 LayRedisplayLine(i
+ flayer
->l_height
- n
, 0, flayer
->l_width
- 1, 1);
3130 if (cv
== cv
->c_display
->d_forecv
)
3134 if (lx
+ cv
->c_xoff
< cv
->c_xs
)
3136 int i
, n
= cv
->c_xs
- (lx
+ cv
->c_xoff
);
3137 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3138 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3139 if (cv
->c_xoff
+ n
> cv
->c_xs
)
3140 n
= cv
->c_xs
- cv
->c_xoff
;
3142 RethinkViewportOffsets(cv
);
3143 if (n
> cv
->c_layer
->l_width
)
3144 n
= cv
->c_layer
->l_width
;
3146 LayRedisplayLine(-1, -1, -1, 1);
3147 for (i
= 0; i
< flayer
->l_height
; i
++)
3149 LScrollH(flayer
, -n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3150 LayRedisplayLine(i
, 0, n
- 1, 1);
3152 if (cv
== cv
->c_display
->d_forecv
)
3156 else if (lx
+ cv
->c_xoff
> cv
->c_xe
)
3158 int i
, n
= lx
+ cv
->c_xoff
- cv
->c_xe
;
3159 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3160 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3161 if (cv
->c_xoff
- n
+ cv
->c_layer
->l_width
- 1 < cv
->c_xe
)
3162 n
= cv
->c_xoff
+ cv
->c_layer
->l_width
- 1 - cv
->c_xe
;
3164 RethinkViewportOffsets(cv
);
3165 if (n
> cv
->c_layer
->l_width
)
3166 n
= cv
->c_layer
->l_width
;
3168 LayRedisplayLine(-1, -1, -1, 1);
3169 for (i
= 0; i
< flayer
->l_height
; i
++)
3171 LScrollH(flayer
, n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3172 LayRedisplayLine(i
, flayer
->l_width
- n
, flayer
->l_width
- 1, 1);
3174 if (cv
== cv
->c_display
->d_forecv
)
3181 for (display
= displays
; display
; display
= display
->d_next
)
3183 if (D_status
== STATUS_ON_WIN
|| D_cvlist
== 0 || D_cvlist
->c_next
== 0)
3185 debug1("serv_select_fn: Restore on cv %#x\n", (int)D_forecv
);
3186 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
3191 logflush_fn(ev
, data
)
3199 if (!islogfile(NULL
))
3200 return; /* no more logfiles */
3202 n
= log_flush
? log_flush
: (logtstamp_after
+ 4) / 5;
3205 SetTimeout(ev
, n
* 1000);
3206 evenq(ev
); /* re-enqueue ourself */
3210 /* write fancy time-stamp */
3211 for (p
= windows
; p
; p
= p
->w_next
)
3215 p
->w_logsilence
+= n
;
3216 if (p
->w_logsilence
< logtstamp_after
)
3218 if (p
->w_logsilence
- n
>= logtstamp_after
)
3220 buf
= MakeWinMsg(logtstamp_string
, p
, '%');
3221 logfwrite(p
->w_log
, buf
, strlen(buf
));
3226 * Interprets ^?, ^@ and other ^-control-char notation.
3227 * Interprets \ddd octal notation
3229 * The result is placed in *cp, p is advanced behind the parsed expression and
3238 if (*p
== '^' && p
[1])
3248 else if (*p
== '\\' && *++p
<= '7' && *p
>= '0')
3252 *cp
= *cp
* 8 + *p
- '0';
3253 while (*++p
<= '7' && *p
>= '0');
3264 unsigned char buf
[2];
3267 SetEscape((struct acluser
*)0, -1, -1);
3270 if ((p
= ParseChar(p
, (char *)buf
)) == NULL
||
3271 (p
= ParseChar(p
, (char *)buf
+1)) == NULL
|| *p
)
3273 SetEscape((struct acluser
*)0, buf
[0], buf
[1]);