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 */
382 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
383 setcompat(COMPAT_POSIX
|COMPAT_BSDPROT
); /* turn on seteuid support */
385 #if defined(sun) && defined(SVR4)
387 /* Solaris' login blocks SIGHUP! This is _very bad_ */
390 sigprocmask(SIG_SETMASK
, &sset
, 0);
395 * First, close all unused descriptors
396 * (otherwise, we might have problems with the select() call)
402 sprintf(version
, "%d.%.2d.%.2d%s (%s) %s", REV
, VERS
,
403 PATCHLEVEL
, STATE
, ORIGIN
, DATE
);
404 nversion
= REV
* 10000 + VERS
* 100 + PATCHLEVEL
;
405 debug2("-- screen debug started %s (%s)\n", *av
, version
);
419 debug("NAMEDPIPE\n");
421 #if defined(SIGWINCH) && defined(TIOCGWINSZ)
422 debug("Window size changing enabled\n");
452 debug1("NAME_MAX = %d\n", NAME_MAX
);
455 BellString
= SaveStr("Bell in window %n");
456 VisualBellString
= SaveStr(" Wuff, Wuff!! ");
457 ActivityString
= SaveStr("Activity in window %n");
458 screenlogfile
= SaveStr("screenlog.%n");
459 logtstamp_string
= SaveStr("-- %n:%t -- time-stamp -- %M/%d/%y %c:%s --\n");
460 hstatusstring
= SaveStr("%h");
461 captionstring
= SaveStr("%3n %t");
462 timestring
= SaveStr("%c:%s %M %d %H%? %l%?");
463 wlisttit
= SaveStr("Num Name%=Flags");
464 wliststr
= SaveStr("%3n %t%=%f");
466 BufferFile
= SaveStr(DEFAULT_BUFFERFILE
);
472 default_startup
= (ac
> 1) ? 0 : 1;
474 VBellWait
= VBELLWAIT
* 1000;
475 MsgWait
= MSGWAIT
* 1000;
476 MsgMinWait
= MSGMINWAIT
* 1000;
477 SilenceWait
= SILENCEWAIT
;
482 zmodem_sendcmd
= SaveStr("!!! sz -vv -b ");
483 zmodem_recvcmd
= SaveStr("!!! rz -vv -b -E");
487 CompileKeys((char *)0, 0, mark_key_tab
);
491 screenencodings
= SaveStr(SCREENENCODINGS
);
497 nwin_options
= nwin_undef
;
498 strcpy(screenterm
, "screen");
500 logreopen_register(lf_secreopen
);
503 /* if this is a login screen, assume -RR */
512 ShellProg
= SaveStr(DefaultShell
); /* to prevent nasty circles */
517 if (--ac
> 0 && *ap
== '-')
519 if (ap
[1] == '-' && ap
[2] == 0)
525 if (ap
[1] == '-' && !strcmp(ap
, "--version"))
526 Panic(0, "Screen version %s", version
);
527 if (ap
[1] == '-' && !strcmp(ap
, "--help"))
528 exit_with_usage(myname
, NULL
, NULL
);
529 while (ap
&& *ap
&& *++ap
)
534 nwin_options
.aflag
= 1;
539 case 'p': /* preselect */
545 exit_with_usage(myname
, "Specify a window to preselect with -p", NULL
);
552 bd
.bd_start_braille
= 1;
561 exit_with_usage(myname
, "Specify an alternate rc-filename with -c", NULL
);
570 exit_with_usage(myname
, "Specify command characters with -e", NULL
);
574 Panic(0, "Two characters are required with -e option, not '%s'.", ap
);
583 nwin_options
.flowflag
= FLOW_NOW
* 0;
590 nwin_options
.flowflag
= FLOW_NOW
* 1;
593 nwin_options
.flowflag
= FLOW_AUTOFLAG
;
596 exit_with_usage(myname
, "Unknown flow option -%s", --ap
);
601 exit_with_usage(myname
, NULL
, NULL
);
602 nwin_options
.histheight
= atoi(*++av
);
603 if (nwin_options
.histheight
< 0)
604 exit_with_usage(myname
, "-h: %s: negative scrollback size?", *av
);
609 case 't': /* title, the former AkA == -k */
611 exit_with_usage(myname
, "Specify a new window-name with -t", NULL
);
612 nwin_options
.aka
= *++av
;
620 nwin_options
.lflag
= 0;
627 nwin_options
.lflag
= 1;
630 nwin_options
.lflag
= 3;
633 case 'i': /* -list */
635 if (ac
> 1 && !SockMatch
)
643 exit_with_usage(myname
, "%s: Unknown suboption to -l", --ap
);
649 if (ac
> 1 && !SockMatch
)
656 nwin_options
.Lflag
= 1;
661 case 'O': /* to be (or not to be?) deleted. jw. */
666 exit_with_usage(myname
, "Specify terminal-type with -T", NULL
);
667 if (strlen(*++av
) < 20)
668 strcpy(screenterm
, *av
);
670 Panic(0, "-T: terminal name too long. (max. 20 char)");
671 nwin_options
.term
= screenterm
;
681 if (ac
> 1 && *av
[1] != '-' && !SockMatch
)
685 debug2("rflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
693 rflag
+= (*ap
== 'R') ? 2 : 1;
704 if (*av
[1] != '-' && !SockMatch
)
708 debug2("dflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
715 exit_with_usage(myname
, "Specify shell with -s", NULL
);
718 ShellProg
= SaveStr(*++av
);
719 debug1("ShellProg: '%s'\n", ShellProg
);
725 exit_with_usage(myname
, "Specify session-name with -S", NULL
);
729 exit_with_usage(myname
, "Empty session-name?", NULL
);
735 Panic(0, "Screen version %s", version
);
739 nwin_options
.encoding
= nwin_options
.encoding
== -1 ? UTF8
: 0;
743 exit_with_usage(myname
, "Unknown option %s", --ap
);
755 if (eff_uid
!= real_uid
)
757 /* if running with s-bit, we must install a special signal
758 * handler routine that resets the s-bit, so that we get a
761 #ifdef SIGBUS /* OOPS, linux has no bus errors! */
762 signal(SIGBUS
, CoreDump
);
764 signal(SIGSEGV
, CoreDump
);
768 setlocale(LC_ALL
, "");
771 if (nwin_options
.encoding
== -1)
773 /* ask locale if we should start in UTF-8 mode */
774 # ifdef HAVE_NL_LANGINFO
776 setlocale(LC_CTYPE
, "");
778 nwin_options
.encoding
= FindEncoding(nl_langinfo(CODESET
));
779 debug1("locale says encoding = %d\n", nwin_options
.encoding
);
783 if ((s
= locale_name()) && InStr(s
, "UTF-8"))
784 nwin_options
.encoding
= UTF8
;
786 debug1("environment says encoding=%d\n", nwin_options
.encoding
);
792 if ((s
= locale_name()))
794 if(!strncmp(s
, "zh_", 3) || !strncmp(s
, "ja_", 3) || !strncmp(s
, "ko_", 3))
802 if (nwin_options
.aka
)
805 if (nwin_options
.encoding
> 0)
807 size_t len
= strlen(nwin_options
.aka
);
809 char *newbuf
= malloc(3 * len
);
812 newsz
= RecodeBuf(nwin_options
.aka
, len
,
813 nwin_options
.encoding
, 0, newbuf
);
814 newbuf
[newsz
] = '\0';
815 nwin_options
.aka
= newbuf
;
820 /* If we just use the original value from av,
821 subsequent shelltitle invocations will attempt to free
822 space we don't own... */
823 nwin_options
.aka
= SaveStr(nwin_options
.aka
);
827 if (SockMatch
&& strlen(SockMatch
) >= MAXSTR
)
828 Panic(0, "Ridiculously long socketname - try again.");
829 if (cmdflag
&& !rflag
&& !dflag
&& !xflag
)
831 if (!cmdflag
&& dflag
&& mflag
&& !(rflag
|| xflag
))
835 nwin
.encoding
= nwin_undef
.encoding
; /* let screenrc overwrite it */
840 /* make the write() calls return -1 on all errors */
843 * Ronald F. Guilmette, Oct 29 '94, bug-gnu-utils@prep.ai.mit.edu:
844 * It appears that in System V Release 4, UNIX, if you are writing
845 * an output file and you exceed the currently set file size limit,
846 * you _don't_ just get the call to `write' returning with a
847 * failure code. Rather, you get a signal called `SIGXFSZ' which,
848 * if neither handled nor ignored, will cause your program to crash
851 signal(SIGXFSZ
, SIG_IGN
);
855 signal(SIGPIPE
, SIG_IGN
);
862 sh
= getenv("SHELL");
863 ShellProg
= SaveStr(sh
? sh
: DefaultShell
);
865 ShellArgs
[0] = ShellProg
;
866 home
= getenv("HOME");
867 if (!mflag
&& !SockMatch
)
870 if (sty
&& *sty
== 0)
875 if (!(nethackflag
= (getenv("NETHACKOPTIONS") != NULL
)))
877 char nethackrc
[MAXPATHLEN
];
879 if (home
&& (strlen(home
) < (MAXPATHLEN
- 20)))
881 sprintf(nethackrc
,"%s/.nethackrc", home
);
882 nethackflag
= !access(nethackrc
, F_OK
);
888 own_uid
= multi_uid
= real_uid
;
889 if (SockMatch
&& (sockp
= index(SockMatch
, '/')))
893 SockMatch
= sockp
+ 1;
897 if ((mppp
= getpwnam(multi
)) == (struct passwd
*)0)
898 Panic(0, "Cannot identify account '%s'.", multi
);
899 multi_uid
= mppp
->pw_uid
;
900 multi_home
= SaveStr(mppp
->pw_dir
);
901 if (strlen(multi_home
) > MAXPATHLEN
- 10)
902 Panic(0, "home directory path too long");
904 /* always fake multi attach mode */
911 /* Special case: effective user is multiuser. */
912 if (eff_uid
&& (multi_uid
!= eff_uid
))
913 Panic(0, "Must run suid root for multiuser support.");
915 if (SockMatch
&& *SockMatch
== 0)
917 #endif /* MULTIUSER */
919 if ((LoginName
= getlogin()) && LoginName
[0] != '\0')
921 if ((ppp
= getpwnam(LoginName
)) != (struct passwd
*) 0)
922 if ((int)ppp
->pw_uid
!= real_uid
)
923 ppp
= (struct passwd
*) 0;
927 if ((ppp
= getpwuid(real_uid
)) == 0)
929 Panic(0, "getpwuid() can't identify your account!");
932 LoginName
= ppp
->pw_name
;
934 LoginName
= SaveStr(LoginName
);
936 ppp
= getpwbyname(LoginName
, ppp
);
938 #if !defined(SOCKDIR) && defined(MULTIUSER)
939 if (multi
&& !multiattach
)
941 if (home
&& strcmp(home
, ppp
->pw_dir
))
942 Panic(0, "$HOME must match passwd entry for multiuser screens.");
946 #define SET_GUID() do \
950 eff_uid = real_uid; \
951 eff_gid = real_gid; \
954 #define SET_TTYNAME(fatal) do \
956 if (!(attach_tty = ttyname(0))) \
959 Panic(0, "Must be connected to a terminal."); \
963 else if (stat(attach_tty, &st)) \
964 Panic(errno, "Cannot access '%s'", attach_tty); \
965 if (strlen(attach_tty) >= MAXPATHLEN) \
966 Panic(0, "TtyName too long - sorry."); \
969 if (home
== 0 || *home
== '\0')
971 if (strlen(LoginName
) > 20)
972 Panic(0, "LoginName too long - sorry.");
974 if (multi
&& strlen(multi
) > 20)
975 Panic(0, "Screen owner name too long - sorry.");
977 if (strlen(home
) > MAXPATHLEN
- 25)
978 Panic(0, "$HOME too long - sorry.");
981 if (!detached
&& !lsflag
&& !cmdflag
&& !(dflag
&& !mflag
&& !rflag
&& !xflag
) && !(!mflag
&& !SockMatch
&& sty
&& !xflag
))
987 /* ttyname implies isatty */
990 tty_mode
= (int)st
.st_mode
& 0777;
994 fl
= fcntl(0, F_GETFL
, 0);
995 if (fl
!= -1 && (fl
& (O_RDWR
|O_RDONLY
|O_WRONLY
)) == O_RDWR
)
1000 if ((n
= secopen(attach_tty
, O_RDWR
| O_NONBLOCK
, 0)) < 0)
1001 Panic(0, "Cannot open your terminal '%s' - please check.", attach_tty
);
1004 debug2("attach_tty is %s, attach_fd is %d\n", attach_tty
, attach_fd
);
1006 if ((attach_term
= getenv("TERM")) == 0 || *attach_term
== 0)
1007 Panic(0, "Please set a terminal type.");
1008 if (strlen(attach_term
) > sizeof(D_termname
) - 1)
1009 Panic(0, "$TERM too long - sorry.");
1010 GetTTY(0, &attach_Mode
);
1011 #ifdef DEBUGGGGGGGGGGGGGGG
1012 DebugTTY(&attach_Mode
);
1017 oumask
= umask(0); /* well, unsigned never fails? jw. */
1019 if ((oumask
= (int)umask(0)) == -1)
1020 Panic(errno
, "Cannot change umask to zero");
1022 SockDir
= getenv("SCREENDIR");
1025 if (strlen(SockDir
) >= MAXPATHLEN
- 1)
1026 Panic(0, "Ridiculously long $SCREENDIR - try again.");
1029 Panic(0, "No $SCREENDIR with multi screens, please.");
1036 sprintf(SockPath
, "%s/.screen", multi_home
);
1040 sprintf(SockPath
, "%s/S-%s", SockDir
, multi
);
1049 sprintf(SockPath
, "%s/.screen", home
);
1055 if (access(SockDir
, F_OK
))
1057 debug1("SockDir '%s' missing ...\n", SockDir
);
1058 if (UserContext() > 0)
1060 if (mkdir(SockDir
, 0700))
1064 if (UserStatus() <= 0)
1065 Panic(0, "Cannot make directory '%s'.", SockDir
);
1067 if (SockDir
!= SockPath
)
1068 strcpy(SockPath
, SockDir
);
1074 if (lstat(SockDir
, &st
))
1076 n
= (eff_uid
== 0 && (real_uid
|| eff_gid
== real_gid
)) ? 0755 :
1077 (eff_gid
!= real_gid
) ? 0775 :
1083 if (mkdir(SockDir
, n
) == -1)
1084 Panic(errno
, "Cannot make directory '%s'", SockDir
);
1088 if (!S_ISDIR(st
.st_mode
))
1089 Panic(0, "'%s' must be a directory.", SockDir
);
1090 if (eff_uid
== 0 && real_uid
&& (int)st
.st_uid
!= eff_uid
)
1091 Panic(0, "Directory '%s' must be owned by root.", SockDir
);
1092 n
= (eff_uid
== 0 && (real_uid
|| (st
.st_mode
& 0775) != 0775)) ? 0755 :
1093 (eff_gid
== (int)st
.st_gid
&& eff_gid
!= real_gid
) ? 0775 :
1095 if (((int)st
.st_mode
& 0777) != n
)
1096 Panic(0, "Directory '%s' must have mode %03o.", SockDir
, n
);
1098 sprintf(SockPath
, "%s/S-%s", SockDir
, LoginName
);
1099 if (access(SockPath
, F_OK
))
1101 if (mkdir(SockPath
, 0700) == -1)
1102 Panic(errno
, "Cannot make directory '%s'", SockPath
);
1103 (void) chown(SockPath
, real_uid
, real_gid
);
1109 if (stat(SockPath
, &st
) == -1)
1110 Panic(errno
, "Cannot access %s", SockPath
);
1112 if (!S_ISDIR(st
.st_mode
))
1113 Panic(0, "%s is not a directory.", SockPath
);
1117 if ((int)st
.st_uid
!= multi_uid
)
1118 Panic(0, "%s is not the owner of %s.", multi
, SockPath
);
1123 if ((int)st
.st_uid
!= real_uid
)
1124 Panic(0, "You are not the owner of %s.", SockPath
);
1126 if ((st
.st_mode
& 0777) != 0700)
1127 Panic(0, "Directory %s must have mode 700.", SockPath
);
1128 if (SockMatch
&& index(SockMatch
, '/'))
1129 Panic(0, "Bad session name '%s'", SockMatch
);
1130 SockName
= SockPath
+ strlen(SockPath
) + 1;
1132 (void) umask(oumask
);
1133 debug2("SockPath: %s SockMatch: %s\n", SockPath
, SockMatch
? SockMatch
: "NULL");
1135 #if defined(SYSV) && !defined(ISC)
1136 if (uname(&utsnam
) == -1)
1137 Panic(errno
, "uname");
1138 strncpy(HostName
, utsnam
.nodename
, sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1);
1139 HostName
[sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1] = '\0';
1141 (void) gethostname(HostName
, MAXSTR
);
1142 HostName
[MAXSTR
- 1] = '\0';
1144 if ((ap
= index(HostName
, '.')) != NULL
)
1153 real_uid
= multi_uid
;
1156 i
= FindSocket((int *)NULL
, &fo
, &oth
, SockMatch
);
1158 exit(8 + (fo
? ((oth
|| i
) ? 2 : 1) : 0) + i
);
1160 Panic(0, "No Sockets found in %s.\n", SockPath
);
1161 Panic(0, "%d Socket%s in %s.\n", fo
, fo
> 1 ? "s" : "", SockPath
);
1164 signal(SIG_BYE
, AttacherFinit
); /* prevent races */
1167 /* attach_tty is not mandatory */
1170 Panic(0, "Please specify a command.");
1172 SendCmdMessage(sty
, SockMatch
, av
);
1175 else if (rflag
|| xflag
)
1177 debug("screen -r: - is there anybody out there?\n");
1178 if (Attach(MSG_ATTACH
))
1185 Panic(0, "Can't create sessions of other users.");
1187 debug("screen -r: backend not responding -- still crying\n");
1189 else if (dflag
&& !mflag
)
1193 Msg(0, "[%s %sdetached.]\n", SockName
, (dflag
> 1 ? "power " : ""));
1197 if (!SockMatch
&& !mflag
&& sty
)
1199 /* attach_tty is not mandatory */
1202 nwin_options
.args
= av
;
1203 SendCreateMsg(sty
, &nwin
);
1207 nwin_compose(&nwin_default
, &nwin_options
, &nwin_default
);
1209 if (!detached
|| dflag
!= 2)
1217 Panic(errno
, "fork");
1225 sprintf(socknamebuf
, "%d.%s", MasterPid
, SockMatch
);
1227 sprintf(socknamebuf
, "%d.%s.%s", MasterPid
, stripdev(attach_tty
), HostName
);
1228 for (ap
= socknamebuf
; *ap
; ap
++)
1232 if (strlen(socknamebuf
) > NAME_MAX
)
1233 socknamebuf
[NAME_MAX
] = 0;
1235 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1242 PanicPid
= getppid();
1244 if (DefaultEsc
== -1)
1245 DefaultEsc
= Ctrl('a');
1246 if (DefaultMetaEsc
== -1)
1247 DefaultMetaEsc
= 'a';
1249 ap
= av0
+ strlen(av0
) - 1;
1252 if (!strncmp("screen", ap
, 6))
1254 strncpy(ap
, "SCREEN", 6); /* name this process "SCREEN-BACKEND" */
1266 if (dfp
&& dfp
!= stderr
)
1268 sprintf(buf
, "%s/SCREEN.%d", DEBUGDIR
, (int)getpid());
1269 if ((dfp
= fopen(buf
, "w")) == NULL
)
1272 (void) chmod(buf
, 0666);
1277 if (attach_fd
== -1)
1279 if ((n
= secopen(attach_tty
, O_RDWR
, 0)) < 0)
1280 Panic(0, "Cannot reopen '%s' - please check.", attach_tty
);
1287 freopen("/dev/null", "r", stdin
);
1288 freopen("/dev/null", "w", stdout
);
1293 freopen("/dev/null", "w", stderr
);
1294 debug("-- screen.back debug started\n");
1297 * This guarantees that the session owner is listed, even when we
1298 * start detached. From now on we should not refer to 'LoginName'
1299 * any more, use users->u_name instead.
1301 if (UserAdd(LoginName
, (char *)0, (struct acluser
**)0) < 0)
1302 Panic(0, "Could not create user info");
1305 if (MakeDisplay(LoginName
, attach_tty
, attach_term
, n
, getppid(), &attach_Mode
) == 0)
1306 Panic(0, "Could not alloc display");
1309 D_encoding
= nwin_options
.encoding
> 0 ? nwin_options
.encoding
: 0;
1310 debug1("D_encoding = %d\n", D_encoding
);
1316 /* user started us with -S option */
1317 sprintf(socknamebuf
, "%d.%s", (int)getpid(), SockMatch
);
1321 sprintf(socknamebuf
, "%d.%s.%s", (int)getpid(), stripdev(attach_tty
),
1324 for (ap
= socknamebuf
; *ap
; ap
++)
1328 if (strlen(socknamebuf
) > NAME_MAX
)
1330 debug2("Socketname %s truncated to %d chars\n", socknamebuf
, NAME_MAX
);
1331 socknamebuf
[NAME_MAX
] = 0;
1334 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1336 ServerSocket
= MakeServerSocket();
1339 # ifdef ALLOW_SYSSCREENRC
1340 if ((ap
= getenv("SYSSCREENRC")))
1341 (void)StartRc(ap
, 0);
1344 (void)StartRc(ETCSCREENRC
, 0);
1346 (void)StartRc(RcFileName
, 0);
1350 # endif /* UTNOKEEP */
1351 # endif /* UTMPOK */
1354 if (InitTermcap(0, 0))
1356 debug("Could not init termcap - exiting\n");
1357 fcntl(D_userfd
, F_SETFL
, 0); /* Flush sets FNBLOCK */
1360 Kill(D_userpid
, SIG_BYE
);
1363 MakeDefaultCanvas();
1375 signal(SIGHUP
, SigHup
);
1376 signal(SIGINT
, FinitHandler
);
1377 signal(SIGQUIT
, FinitHandler
);
1378 signal(SIGTERM
, FinitHandler
);
1380 signal(SIGTTIN
, SIG_IGN
);
1381 signal(SIGTTOU
, SIG_IGN
);
1387 SetMode(&D_OldMode
, &D_NewMode
, D_flow
, iflag
);
1388 /* Note: SetMode must be called _before_ FinishRc. */
1389 SetTTY(D_userfd
, &D_NewMode
);
1390 if (fcntl(D_userfd
, F_SETFL
, FNBLOCK
))
1391 Msg(errno
, "Warning: NBLOCK fcntl failed");
1394 brktty(-1); /* just try */
1395 signal(SIGCHLD
, SigChld
);
1397 # ifdef ALLOW_SYSSCREENRC
1398 if ((ap
= getenv("SYSSCREENRC")))
1402 FinishRc(ETCSCREENRC
);
1404 FinishRc(RcFileName
);
1406 debug2("UID %d EUID %d\n", (int)getuid(), (int)geteuid());
1407 if (windows
== NULL
)
1409 debug("We open one default window, as screenrc did not specify one.\n");
1410 if (MakeWindow(&nwin
) == -1)
1412 Msg(0, "Sorry, could not find a PTY.");
1423 if (display
&& default_startup
)
1424 display_copyright();
1425 signal(SIGINT
, SigInt
);
1426 if (rflag
&& (rflag
& 1) == 0 && !quietflag
)
1428 Msg(0, "New screen...");
1432 serv_read
.type
= EV_READ
;
1433 serv_read
.fd
= ServerSocket
;
1434 serv_read
.handler
= serv_read_fn
;
1437 serv_select
.pri
= -10;
1438 serv_select
.type
= EV_ALWAYS
;
1439 serv_select
.handler
= serv_select_fn
;
1440 evenq(&serv_select
);
1442 logflushev
.type
= EV_TIMEOUT
;
1443 logflushev
.handler
= logflush_fn
;
1451 WindowDied(p
, wstat
, wstat_valid
)
1458 if (ZombieKey_destroy
&& ZombieKey_onerror
&& wstat_valid
&&
1459 WIFEXITED(wstat
) && WEXITSTATUS(wstat
) == 0)
1462 if (ZombieKey_destroy
&& !killit
)
1464 char buf
[100], *s
, reason
[100];
1468 if (WIFEXITED(wstat
))
1469 if (WEXITSTATUS(wstat
))
1470 sprintf(reason
, "terminated with exit status %d", WEXITSTATUS(wstat
));
1472 sprintf(reason
, "terminated normally");
1473 else if (WIFSIGNALED(wstat
))
1474 sprintf(reason
, "terminated with signal %d%s", WTERMSIG(wstat
),
1476 WCOREDUMP(wstat
) ? " (core file generated)" : "");
1481 sprintf(reason
, "detached from window");
1486 s
[strlen(s
) - 1] = '\0';
1487 debug3("window %d (%s) going into zombie state fd %d",
1488 p
->w_number
, p
->w_title
, p
->w_ptyfd
);
1490 if (p
->w_slot
!= (slot_t
)0 && p
->w_slot
!= (slot_t
)-1)
1493 p
->w_slot
= 0; /* "detached" */
1498 p
->w_deadpid
= p
->w_pid
;
1501 /* p->w_y = p->w_bot; */
1502 p
->w_y
= MFindUsedLine(p
, p
->w_bot
, 1);
1503 sprintf(buf
, "\n\r=== Command %s (%s) ===", reason
, s
? s
: "?");
1504 WriteString(p
, buf
, strlen(buf
));
1505 WindowChanged(p
, 'f');
1526 signal(SIGCHLD
, SigChld
);
1529 if (stat(SockPath
, &st
) == -1)
1531 debug1("SigChldHandler: Yuck! cannot stat '%s'\n", SockPath
);
1532 if (!RecoverSocket())
1534 debug("SCREEN cannot recover from corrupt Socket, bye\n");
1538 debug1("'%s' reconstructed\n", SockPath
);
1541 debug2("SigChldHandler: stat '%s' o.k. (%03o)\n", SockPath
, (int)st
.st_mode
);
1547 debug("SigChld()\n");
1555 /* Hangup all displays */
1556 while ((display
= displays
) != 0)
1562 * the backend's Interrupt handler
1563 * we cannot insert the intrc directly, as we never know
1572 debug("SigInt()\n");
1573 if (fore
&& displays
)
1575 # if defined(TERMIO) || defined(POSIX)
1576 ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
1578 ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
1581 write(fore
->w_ptyfd
, &ibuf
, 1);
1584 signal(SIGINT
, SigInt
);
1585 debug("SigInt() careful\n");
1586 InterruptPlease
= 1;
1594 struct display
*disp
;
1597 #if defined(SYSVSIGS) && defined(SIGHASARG)
1598 signal(sigsig
, SIG_IGN
);
1604 sprintf(buf
, "\r\n[screen caught signal %d.%s]\r\n", sigsig
,
1606 sprintf(buf
, "\r\n[screen caught a fatal signal.%s]\r\n",
1608 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1610 #else /* SHADOWPW && !DEBUG */
1612 #endif /* SHADOWPW && !DEBUG */
1614 for (disp
= displays
; disp
; disp
= disp
->d_next
)
1616 fcntl(disp
->d_userfd
, F_SETFL
, 0);
1617 SetTTY(disp
->d_userfd
, &D_OldMode
);
1618 write(disp
->d_userfd
, buf
, strlen(buf
));
1619 Kill(disp
->d_userpid
, SIG_BYE
);
1621 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1622 Kill(getpid(), SIGKILL
);
1624 #else /* SHADOWPW && !DEBUG */
1626 #endif /* SHADOWPW && !DEBUG */
1634 struct win
*p
, *next
;
1643 while ((pid
= waitpid(-1, &wstat
, WNOHANG
| WUNTRACED
)) > 0)
1647 * From: rouilj@sni-usa.com (John Rouillard)
1648 * note that WUNTRACED is not documented to work, but it is defined in
1649 * /usr/include/sys/wait.h, so it may work
1651 while ((pid
= wait2(&wstat
, WNOHANG
| WUNTRACED
)) > 0)
1652 # else /* USE_WAIT2 */
1653 while ((pid
= wait3(&wstat
, WNOHANG
| WUNTRACED
, (struct rusage
*) 0)) > 0)
1654 # endif /* USE_WAIT2 */
1657 while ((pid
= wait(&wstat
)) < 0)
1661 #endif /* BSDJOBS */
1663 for (p
= windows
; p
; p
= next
)
1666 if ( (p
->w_pid
&& pid
== p
->w_pid
) ||
1667 (p
->w_deadpid
&& pid
== p
->w_deadpid
) )
1669 /* child has ceased to exist */
1673 if (WIFSTOPPED(wstat
))
1675 debug3("Window %d pid %d: WIFSTOPPED (sig %d)\n", p
->w_number
, pid
, WSTOPSIG(wstat
));
1677 if (WSTOPSIG(wstat
) == SIGTTIN
)
1679 Msg(0, "Suspended (tty input)");
1684 if (WSTOPSIG(wstat
) == SIGTTOU
)
1686 Msg(0, "Suspended (tty output)");
1690 /* Try to restart process */
1691 Msg(0, "Child has been stopped, restarting.");
1692 if (killpg(pid
, SIGCONT
))
1698 WindowDied(p
, wstat
, 1);
1703 if (p
->w_pwin
&& pid
== p
->w_pwin
->p_pid
)
1705 debug2("pseudo of win Nr %d died. pid == %d\n", p
->w_number
, p
->w_pwin
->p_pid
);
1713 debug1("pid %d not found - hope that's ok\n", pid
);
1720 FinitHandler SIGDEFARG
1723 debug1("FinitHandler called, sig %d.\n", sigsig
);
1725 debug("FinitHandler called.\n");
1735 signal(SIGCHLD
, SIG_DFL
);
1736 signal(SIGHUP
, SIG_IGN
);
1737 debug1("Finit(%d);\n", i
);
1740 struct win
*p
= windows
;
1741 windows
= windows
->w_next
;
1744 if (ServerSocket
!= -1)
1746 debug1("we unlink(%s)\n", SockPath
);
1751 (void) unlink(SockPath
);
1757 for (display
= displays
; display
; display
= display
->d_next
)
1765 AddStr("[screen is terminating]\r\n");
1767 SetTTY(D_userfd
, &D_OldMode
);
1768 fcntl(D_userfd
, F_SETFL
, 0);
1770 Kill(D_userpid
, SIG_BYE
);
1773 * we _cannot_ call eexit(i) here,
1774 * instead of playing with the Socket above. Sigh.
1784 if (ServerSocket
!= -1)
1786 debug1("we unlink(%s)\n", SockPath
);
1789 (void) unlink(SockPath
);
1799 debug1("Hangup %x\n", display
);
1805 if (auto_detach
|| displays
->d_next
)
1812 * Detach now has the following modes:
1813 *D_DETACH SIG_BYE detach backend and exit attacher
1814 *D_HANGUP SIG_BYE detach backend and exit attacher
1815 *D_STOP SIG_STOP stop attacher (and detach backend)
1816 *D_REMOTE SIG_BYE remote detach -- reattach to new attacher
1817 *D_POWER SIG_POWER_BYE power detach -- attacher kills his parent
1818 *D_REMOTE_POWER SIG_POWER_BYE remote power detach -- both
1819 *D_LOCK SIG_LOCK lock the attacher
1821 * we always remove our utmp slots. (even when "lock" or "stop")
1822 * Note: Take extra care here, we may be called by interrupt!
1835 #define AddStrSock(msg) do { \
1838 AddStr("[" msg " from "); \
1843 AddStr("[" msg "]\r\n"); \
1846 signal(SIGHUP
, SIG_IGN
);
1847 debug1("Detach(%d)\n", mode
);
1859 AddStrSock("detached");
1867 #ifdef REMOTE_DETACH
1869 AddStrSock("remote detached");
1875 AddStrSock("power detached");
1876 if (PowDetachString
)
1878 AddStr(PowDetachString
);
1881 sign
= SIG_POWER_BYE
;
1883 #ifdef REMOTE_DETACH
1884 case D_REMOTE_POWER
:
1885 AddStrSock("remote power detached");
1886 if (PowDetachString
)
1888 AddStr(PowDetachString
);
1891 sign
= SIG_POWER_BYE
;
1898 /* tell attacher to lock terminal with a lockprg. */
1902 if (displays
->d_next
== 0)
1904 for (p
= windows
; p
; p
= p
->w_next
)
1906 if (p
->w_slot
!= (slot_t
) -1 && !(p
->w_lflag
& 2))
1910 * Set the slot to 0 to get the window
1913 p
->w_slot
= (slot_t
) 0;
1917 if (mode
!= D_HANGUP
)
1920 if (displays
->d_next
== 0 && console_window
)
1922 if (TtyGrabConsole(console_window
->w_ptyfd
, 0, "detach"))
1924 debug("could not release console - killing window\n");
1925 KillWindow(console_window
);
1926 display
= displays
; /* restore display */
1932 ReleaseAutoWritelock(display
, D_fore
);
1934 D_user
->u_detachwin
= D_fore
->w_number
;
1935 D_user
->u_detachotherwin
= D_other
? D_other
->w_number
: -1;
1937 AutosaveLayout(D_layout
);
1938 layout_last
= D_layout
;
1939 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
1941 p
= Layer2Window(cv
->c_layer
);
1942 SetCanvasWindow(cv
, 0);
1944 WindowChanged(p
, 'u');
1948 debug2("display: %#x displays: %#x\n", (unsigned int)display
, (unsigned int)displays
);
1951 /* Flag detached-ness */
1954 * tell father what to do. We do that after we
1955 * freed the tty, thus getty feels more comfortable on hpux
1956 * if it was a power detach.
1959 debug2("Detach: Signal %d to Attacher(%d)!\n", sign
, pid
);
1960 debug("Detach returns, we are successfully detached.\n");
1961 signal(SIGHUP
, SigHup
);
1972 return strncmp(e
, s
, l
) == 0 && e
[l
] == '=';
1978 register char **op
, **np
;
1979 static char stybuf
[MAXSTR
];
1981 for (op
= environ
; *op
; ++op
)
1984 free((char *)NewEnv
);
1985 NewEnv
= np
= (char **) malloc((unsigned) (op
- environ
+ 7 + 1) * sizeof(char **));
1988 sprintf(stybuf
, "STY=%s", strlen(SockName
) <= MAXSTR
- 5 ? SockName
: "?");
1989 *np
++ = stybuf
; /* NewEnv[0] */
1990 *np
++ = Term
; /* NewEnv[1] */
1991 np
++; /* room for SHELL */
1993 np
+= 2; /* room for TERMCAP and WINDOW */
1995 np
+= 4; /* room for TERMCAP WINDOW LINES COLUMNS */
1998 for (op
= environ
; *op
; ++op
)
2000 if (!IsSymbol(*op
, "TERM") && !IsSymbol(*op
, "TERMCAP")
2001 && !IsSymbol(*op
, "STY") && !IsSymbol(*op
, "WINDOW")
2002 && !IsSymbol(*op
, "SCREENCAP") && !IsSymbol(*op
, "SHELL")
2003 && !IsSymbol(*op
, "LINES") && !IsSymbol(*op
, "COLUMNS")
2012 #if defined(USEVARARGS) && defined(__STDC__)
2013 Msg(int err
, char *fmt
, VA_DOTS
)
2015 Msg(err
, fmt
, VA_DOTS
)
2022 char buf
[MAXPATHLEN
*2];
2027 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2034 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2035 buf
[sizeof(buf
) - 1] = 0;
2037 debug2("Msg('%s') (%#x);\n", buf
, (unsigned int)display
);
2039 if (display
&& displays
)
2043 for (display
= displays
; display
; display
= display
->d_next
)
2048 /* no displays but a display - must have forked.
2049 * send message to backend!
2051 char *tty
= D_usertty
;
2052 struct display
*olddisplay
= display
;
2053 display
= 0; /* only send once */
2054 SendErrorMsg(tty
, buf
);
2055 display
= olddisplay
;
2058 printf("%s\r\n", buf
);
2062 * Call FinitTerm for all displays, write a message to each and call eexit();
2066 #if defined(USEVARARGS) && defined(__STDC__)
2067 Panic(int err
, char *fmt
, VA_DOTS
)
2069 Panic(err
, fmt
, VA_DOTS
)
2076 char buf
[MAXPATHLEN
*2];
2081 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2088 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2089 buf
[sizeof(buf
) - 1] = 0;
2091 debug3("Panic('%s'); display=%x displays=%x\n", buf
, display
, displays
);
2092 if (displays
== 0 && display
== 0)
2094 printf("%s\r\n", buf
);
2096 Kill(PanicPid
, SIG_BYE
);
2098 else if (displays
== 0)
2100 /* no displays but a display - must have forked.
2101 * send message to backend!
2103 char *tty
= D_usertty
;
2105 SendErrorMsg(tty
, buf
);
2110 for (display
= displays
; display
; display
= display
->d_next
)
2119 SetTTY(D_userfd
, &D_OldMode
);
2120 fcntl(D_userfd
, F_SETFL
, 0);
2121 write(D_userfd
, buf
, strlen(buf
));
2122 write(D_userfd
, "\n", 1);
2125 Kill(D_userpid
, SIG_BYE
);
2128 if (tty_oldmode
>= 0)
2131 if (setuid(own_uid
))
2132 xseteuid(own_uid
); /* may be a loop. sigh. */
2136 debug1("Panic: changing back modes from %s\n", attach_tty
);
2137 chmod(attach_tty
, tty_oldmode
);
2145 * '^' is allowed as an escape mechanism for control characters. jw.
2147 * Added time insertion using ideas/code from /\ndy Jones
2148 * (andy@lingua.cltr.uq.OZ.AU) - thanks a lot!
2153 static const char days
[] = "SunMonTueWedThuFriSat";
2154 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2157 static char winmsg_buf
[MAXSTR
];
2158 #define MAX_WINMSG_REND 16 /* rendition changes */
2159 static int winmsg_rend
[MAX_WINMSG_REND
];
2160 static int winmsg_rendpos
[MAX_WINMSG_REND
];
2161 static int winmsg_numrend
;
2164 pad_expand(buf
, p
, numpad
, padlen
)
2173 padlen
= padlen
- (p
- buf
); /* space for rent */
2176 pn2
= pn
= p
+ padlen
;
2180 if (r
&& *p
!= 127 && p
- buf
== winmsg_rendpos
[r
- 1])
2182 winmsg_rendpos
[--r
] = pn
- buf
;
2189 i
= numpad
> 0 ? (padlen
+ numpad
- 1) / numpad
: 0;
2194 if (r
&& p
- buf
== winmsg_rendpos
[r
- 1])
2195 winmsg_rendpos
[--r
] = pn
- buf
;
2202 struct backtick
*next
;
2207 char result
[MAXSTR
];
2214 struct backtick
*backticks
;
2218 struct backtick
*bt
;
2223 for (p
= q
= bt
->result
; (c
= (unsigned char)*p
++) != 0;)
2227 if (c
>= ' ' || c
== '\005')
2234 backtick_fn(ev
, data
)
2238 struct backtick
*bt
;
2241 bt
= (struct backtick
*)data
;
2242 debug1("backtick_fn for #%d\n", bt
->num
);
2244 l
= read(ev
->fd
, bt
->buf
+ i
, MAXSTR
- i
);
2247 debug1("EOF on backtick #%d\n", bt
->num
);
2253 debug1("read %d bytes\n", l
);
2255 for (j
= 0; j
< l
; j
++)
2256 if (bt
->buf
[i
- j
- 1] == '\n')
2260 for (k
= i
- j
- 2; k
>= 0; k
--)
2261 if (bt
->buf
[k
] == '\n')
2264 bcopy(bt
->buf
+ k
, bt
->result
, i
- j
- k
);
2265 bt
->result
[i
- j
- k
- 1] = 0;
2266 backtick_filter(bt
);
2267 WindowChanged(0, '`');
2269 if (j
== l
&& i
== MAXSTR
)
2277 bcopy(bt
->buf
+ i
- j
, bt
->buf
, j
);
2284 setbacktick(num
, lifespan
, tick
, cmdv
)
2290 struct backtick
**btp
, *bt
;
2293 debug1("setbacktick called for backtick #%d\n", num
);
2294 for (btp
= &backticks
; (bt
= *btp
) != 0; btp
= &bt
->next
)
2301 for (v
= bt
->cmdv
; *v
; v
++)
2318 bt
= (struct backtick
*)malloc(sizeof *bt
);
2324 bzero(bt
, sizeof(*bt
));
2330 bt
->lifespan
= lifespan
;
2337 if (bt
->tick
== 0 && bt
->lifespan
== 0)
2339 debug("setbacktick: continuous mode\n");
2340 bt
->buf
= (char *)malloc(MAXSTR
);
2344 setbacktick(num
, 0, 0, (char **)0);
2347 bt
->ev
.type
= EV_READ
;
2348 bt
->ev
.fd
= readpipe(bt
->cmdv
);
2349 bt
->ev
.handler
= backtick_fn
;
2350 bt
->ev
.data
= (char *)bt
;
2357 runbacktick(bt
, tickp
, now
)
2358 struct backtick
*bt
;
2365 debug1("runbacktick called for backtick #%d\n", bt
->num
);
2366 if (bt
->tick
&& (!*tickp
|| bt
->tick
< *tickp
))
2368 if ((bt
->lifespan
== 0 && bt
->tick
== 0) || now
< bt
->bestbefore
)
2370 debug1("returning old result (%d)\n", bt
->lifespan
);
2373 f
= readpipe(bt
->cmdv
);
2377 while ((l
= read(f
, bt
->result
+ i
, sizeof(bt
->result
) - i
)) > 0)
2379 debug1("runbacktick: read %d bytes\n", l
);
2381 for (j
= 1; j
< l
; j
++)
2382 if (bt
->result
[i
- j
- 1] == '\n')
2384 if (j
== l
&& i
== sizeof(bt
->result
))
2386 j
= sizeof(bt
->result
) / 2;
2391 bcopy(bt
->result
+ i
- j
, bt
->result
, j
);
2396 bt
->result
[sizeof(bt
->result
) - 1] = '\n';
2397 if (i
&& bt
->result
[i
- 1] == '\n')
2399 debug1("runbacktick: finished, %d bytes\n", i
);
2401 backtick_filter(bt
);
2403 bt
->bestbefore
= now2
+ bt
->lifespan
;
2408 MakeWinMsgEv(str
, win
, esc
, padlen
, ev
, rec
)
2418 register char *p
= winmsg_buf
;
2428 int qmflag
= 0, omflag
= 0, qmnumrend
= 0;
2435 struct backtick
*bt
;
2437 if (winmsg_numrend
>= 0)
2440 winmsg_numrend
= -winmsg_numrend
;
2445 gettimeofday(&now
, NULL
);
2446 for (; *s
&& (l
= winmsg_buf
+ MAXSTR
- 1 - p
) > 0; s
++, p
++)
2452 if (*s
!= '^' && *s
>= 64)
2477 if (*++s
== esc
) /* double escape ? */
2479 if ((plusflg
= *s
== '+') != 0)
2481 if ((minusflg
= *s
== '-') != 0)
2483 if ((zeroflg
= *s
== '0') != 0)
2486 while(*s
>= '0' && *s
<= '9')
2487 num
= num
* 10 + (*s
++ - '0');
2488 if ((longflg
= *s
== 'L') != 0)
2496 if ((!qmflag
&& !omflag
) || omflag
== 1)
2499 if (qmnumrend
< winmsg_numrend
)
2500 winmsg_numrend
= qmnumrend
;
2506 qmnumrend
= winmsg_numrend
;
2507 qmflag
= omflag
= 0;
2513 if (qmflag
&& omflag
!= 1)
2517 qmnumrend
= winmsg_numrend
;
2522 if (qmnumrend
< winmsg_numrend
)
2523 winmsg_numrend
= qmnumrend
;
2527 case 'd': case 'D': case 'm': case 'M': case 'y': case 'Y':
2528 case 'a': case 'A': case 's': case 'c': case 'C':
2533 time_t nowsec
= now
.tv_sec
;
2534 tm
= localtime(&nowsec
);
2537 if (!tick
|| tick
> 3600)
2542 sprintf(p
, "%02d", tm
->tm_mday
% 100);
2546 strftime(p
, l
, (longflg
? "%A" : "%a"), tm
);
2548 sprintf(p
, "%3.3s", days
+ 3 * tm
->tm_wday
);
2552 sprintf(p
, "%02d", tm
->tm_mon
+ 1);
2556 strftime(p
, l
, (longflg
? "%B" : "%b"), tm
);
2558 sprintf(p
, "%3.3s", months
+ 3 * tm
->tm_mon
);
2562 sprintf(p
, "%02d", tm
->tm_year
% 100);
2565 sprintf(p
, "%04d", tm
->tm_year
+ 1900);
2568 sprintf(p
, tm
->tm_hour
>= 12 ? "pm" : "am");
2571 sprintf(p
, tm
->tm_hour
>= 12 ? "PM" : "AM");
2574 sprintf(p
, "%02d", tm
->tm_sec
);
2578 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", tm
->tm_hour
, tm
->tm_min
);
2579 if (!tick
|| tick
> 60)
2583 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", (tm
->tm_hour
+ 11) % 12 + 1, tm
->tm_min
);
2584 if (!tick
|| tick
> 60)
2604 if (!tick
|| tick
> 60)
2613 if (rec
>= 10 || (*s
== 'h' && (win
== 0 || win
->w_hstatus
== 0 || *win
->w_hstatus
== 0)))
2620 for (bt
= backticks
; bt
; bt
= bt
->next
)
2630 char savebuf
[sizeof(winmsg_buf
)];
2632 int oldnumrend
= winmsg_numrend
;
2635 strcpy(savebuf
, winmsg_buf
);
2636 winmsg_numrend
= -winmsg_numrend
;
2637 MakeWinMsgEv(*s
== 'h' ? win
->w_hstatus
: runbacktick(bt
, &oldtick
, now
.tv_sec
), win
, '\005', 0, (struct event
*)0, rec
+ 1);
2638 debug2("oldtick=%d tick=%d\n", oldtick
, tick
);
2639 if (!tick
|| oldtick
< tick
)
2641 if ((int)strlen(winmsg_buf
) < l
)
2642 strcat(savebuf
, winmsg_buf
);
2643 strcpy(winmsg_buf
, savebuf
);
2644 while (oldnumrend
< winmsg_numrend
)
2645 winmsg_rendpos
[oldnumrend
++] += p
- winmsg_buf
;
2654 struct win
*oldfore
= 0;
2662 ss
= AddWindows(p
, l
- 1, (*s
== 'w' ? 0 : 1) | (longflg
? 0 : 2) | (plusflg
? 4 : 0), win
? win
->w_number
: -1);
2675 AddOtherUsers(p
, l
- 1, win
);
2683 AddWindowFlags(p
, l
- 1, win
);
2690 if (win
&& (int)strlen(win
->w_title
) < l
)
2692 strcpy(p
, win
->w_title
);
2702 for (i
= 0; i
< 127; i
++)
2703 if (s
[i
] && s
[i
] != '}')
2707 if (s
[i
] == '}' && winmsg_numrend
< MAX_WINMSG_REND
)
2711 debug1("MakeWinMsg attrcolor %s\n", rbuf
);
2712 if (i
!= 1 || rbuf
[0] != '-')
2713 r
= ParseAttrColor(rbuf
, (char *)0, 0);
2714 if (r
!= -1 || (i
== 1 && rbuf
[0] == '-'))
2716 winmsg_rend
[winmsg_numrend
] = r
;
2717 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2727 if ((int)strlen(HostName
) < l
)
2729 strcpy(p
, HostName
);
2739 session_name
= strchr(SockName
, '.') + 1;
2740 if ((int)strlen(session_name
) < l
)
2742 strcpy(p
, session_name
);
2751 sprintf(p
, "%d", (plusflg
&& display
) ? D_userpid
: getpid());
2758 if (display
&& ((ev
&& ev
== &D_forecv
->c_captev
) || (!ev
&& win
&& win
== D_fore
)))
2759 minusflg
= !minusflg
;
2764 truncpos
= p
- winmsg_buf
;
2765 truncper
= num
> 100 ? 100 : num
;
2766 trunclong
= longflg
;
2772 if (num
|| zeroflg
|| plusflg
|| longflg
|| (*s
!= '='))
2774 /* expand all pads */
2777 num
= (plusflg
? lastpad
: padlen
) - num
;
2778 if (!plusflg
&& padlen
== 0)
2779 num
= p
- winmsg_buf
;
2784 if (*s
!= '=' && num
== 0 && !plusflg
)
2789 num
= p
- winmsg_buf
;
2791 num
= (padlen
- (plusflg
? lastpad
: 0)) * num
/ 100;
2797 if (num
> MAXSTR
- 1)
2800 p
= pad_expand(winmsg_buf
, p
, numpad
, num
);
2802 if (p
- winmsg_buf
> num
&& !longflg
)
2811 trunc
= lastpad
+ truncper
* (num
- lastpad
) / 100;
2814 if (trunc
< lastpad
)
2816 left
= truncpos
- trunc
;
2817 if (left
> p
- winmsg_buf
- num
)
2818 left
= p
- winmsg_buf
- num
;
2819 debug1("lastpad = %d, ", lastpad
);
2820 debug3("truncpos = %d, trunc = %d, left = %d\n", truncpos
, trunc
, left
);
2823 if (left
+ lastpad
> p
- winmsg_buf
)
2824 left
= p
- winmsg_buf
- lastpad
;
2825 if (p
- winmsg_buf
- lastpad
- left
> 0)
2826 bcopy(winmsg_buf
+ lastpad
+ left
, winmsg_buf
+ lastpad
, p
- winmsg_buf
- lastpad
- left
);
2829 while (r
&& winmsg_rendpos
[r
- 1] > lastpad
)
2832 winmsg_rendpos
[r
] -= left
;
2833 if (winmsg_rendpos
[r
] < lastpad
)
2834 winmsg_rendpos
[r
] = lastpad
;
2838 if (p
- winmsg_buf
> lastpad
)
2839 winmsg_buf
[lastpad
] = '.';
2840 if (p
- winmsg_buf
> lastpad
+ 1)
2841 winmsg_buf
[lastpad
+ 1] = '.';
2842 if (p
- winmsg_buf
> lastpad
+ 2)
2843 winmsg_buf
[lastpad
+ 2] = '.';
2846 if (p
- winmsg_buf
> num
)
2848 p
= winmsg_buf
+ num
;
2851 if (num
- 1 >= lastpad
)
2853 if (num
- 2 >= lastpad
)
2855 if (num
- 3 >= lastpad
)
2859 while (r
&& winmsg_rendpos
[r
- 1] > num
)
2860 winmsg_rendpos
[--r
] = num
;
2864 if (lastpad
> p
- winmsg_buf
)
2865 lastpad
= p
- winmsg_buf
;
2866 debug1("lastpad now %d\n", lastpad
);
2870 while (p
- winmsg_buf
< num
)
2872 lastpad
= p
- winmsg_buf
;
2875 debug1("lastpad2 now %d\n", lastpad
);
2881 *p
= 127; /* internal pad representation */
2895 sprintf(p
, "%*s", num
, num
> 1 ? "--" : "-");
2897 sprintf(p
, "%*d", num
, win
->w_number
);
2904 if (qmpos
&& !qmflag
)
2909 if (padlen
> MAXSTR
- 1)
2910 padlen
= MAXSTR
- 1;
2911 p
= pad_expand(winmsg_buf
, p
, numpad
, padlen
);
2915 evdeq(ev
); /* just in case */
2916 ev
->timeout
.tv_sec
= 0;
2917 ev
->timeout
.tv_usec
= 0;
2921 now
.tv_usec
= 100000;
2925 now
.tv_sec
+= tick
- (now
.tv_sec
% tick
);
2927 debug2("NEW timeout %d %d\n", ev
->timeout
.tv_sec
, tick
);
2933 MakeWinMsg(s
, win
, esc
)
2938 return MakeWinMsgEv(s
, win
, esc
, 0, (struct event
*)0, 0);
2942 PutWinMsg(s
, start
, max
)
2948 struct mchar rendstack
[MAX_WINMSG_REND
];
2951 if (s
!= winmsg_buf
)
2953 /* sorry, no fancy coloring available */
2954 debug1("PutWinMsg %s plain\n", s
);
2967 debug2("PutWinMsg %s start attr %x\n", s
, rend
.attr
);
2968 for (i
= 0; i
< winmsg_numrend
&& max
> 0; i
++)
2970 if (p
> winmsg_rendpos
[i
] || winmsg_rendpos
[i
] > l
)
2972 if (p
< winmsg_rendpos
[i
])
2974 n
= winmsg_rendpos
[i
] - p
;
2991 rend
= rendstack
[--rendstackn
];
2995 rendstack
[rendstackn
++] = rend
;
2996 ApplyAttrColor(r
, &rend
);
2998 SetRendition(&rend
);
3026 if ((j
= open("/dev/null", 0)) >= 0)
3033 while (dup(++i
) < 0 && errno
!= EBADF
)
3035 debug1(" [%d]\n", i
);
3048 serv_read_fn(ev
, data
)
3052 debug("Knock - knock!\n");
3057 serv_select_fn(ev
, data
)
3063 debug("serv_select_fn called\n");
3064 /* XXX: messages?? */
3069 if (InterruptPlease
)
3071 debug("Backend received interrupt\n");
3072 /* This approach is rather questionable in a multi-display
3074 if (fore
&& displays
)
3076 #if defined(TERMIO) || defined(POSIX)
3077 char ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
3079 char ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
3082 write(W_UWP(fore
) ? fore
->w_pwin
->p_ptyfd
: fore
->w_ptyfd
,
3084 debug1("Backend wrote interrupt to %d", fore
->w_number
);
3085 debug1("%s\n", W_UWP(fore
) ? " (pseudowin)" : "");
3087 write(fore
->w_ptyfd
, &ibuf
, 1);
3088 debug1("Backend wrote interrupt to %d\n", fore
->w_number
);
3091 InterruptPlease
= 0;
3094 for (p
= windows
; p
; p
= p
->w_next
)
3096 if (p
->w_bell
== BELL_FOUND
|| p
->w_bell
== BELL_VISUAL
)
3099 int visual
= p
->w_bell
== BELL_VISUAL
|| visual_bell
;
3100 p
->w_bell
= BELL_ON
;
3101 for (display
= displays
; display
; display
= display
->d_next
)
3103 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3104 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3108 p
->w_bell
= BELL_DONE
;
3109 Msg(0, "%s", MakeWinMsg(BellString
, p
, '%'));
3111 else if (visual
&& !D_VB
&& (!D_status
|| !D_status_bell
))
3113 Msg(0, "%s", VisualBellString
);
3117 debug1("using vbell timeout %d\n", VBellWait
);
3118 SetTimeout(&D_statusev
, VBellWait
);
3122 /* don't annoy the user with two messages */
3123 if (p
->w_monitor
== MON_FOUND
)
3124 p
->w_monitor
= MON_DONE
;
3125 WindowChanged(p
, 'f');
3127 if (p
->w_monitor
== MON_FOUND
)
3130 p
->w_monitor
= MON_ON
;
3131 for (display
= displays
; display
; display
= display
->d_next
)
3133 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3134 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3137 continue; /* user already sees window */
3139 if (!(ACLBYTE(p
->w_mon_notify
, D_user
->u_id
) & ACLBIT(D_user
->u_id
)))
3140 continue; /* user doesn't care */
3142 Msg(0, "%s", MakeWinMsg(ActivityString
, p
, '%'));
3143 p
->w_monitor
= MON_DONE
;
3145 WindowChanged(p
, 'f');
3149 for (display
= displays
; display
; display
= display
->d_next
)
3152 if (D_status
== STATUS_ON_WIN
)
3154 /* XXX: should use display functions! */
3155 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3159 /* normalize window, see resize.c */
3160 lx
= cv
->c_layer
->l_x
;
3161 ly
= cv
->c_layer
->l_y
;
3162 if (lx
== cv
->c_layer
->l_width
)
3164 if (ly
+ cv
->c_yoff
< cv
->c_ys
)
3166 int i
, n
= cv
->c_ys
- (ly
+ cv
->c_yoff
);
3167 cv
->c_yoff
= cv
->c_ys
- ly
;
3168 RethinkViewportOffsets(cv
);
3169 if (n
> cv
->c_layer
->l_height
)
3170 n
= cv
->c_layer
->l_height
;
3172 LScrollV(flayer
, -n
, 0, flayer
->l_height
- 1, 0);
3173 LayRedisplayLine(-1, -1, -1, 1);
3174 for (i
= 0; i
< n
; i
++)
3175 LayRedisplayLine(i
, 0, flayer
->l_width
- 1, 1);
3176 if (cv
== cv
->c_display
->d_forecv
)
3180 else if (ly
+ cv
->c_yoff
> cv
->c_ye
)
3182 int i
, n
= ly
+ cv
->c_yoff
- cv
->c_ye
;
3183 cv
->c_yoff
= cv
->c_ye
- ly
;
3184 RethinkViewportOffsets(cv
);
3185 if (n
> cv
->c_layer
->l_height
)
3186 n
= cv
->c_layer
->l_height
;
3188 LScrollV(flayer
, n
, 0, cv
->c_layer
->l_height
- 1, 0);
3189 LayRedisplayLine(-1, -1, -1, 1);
3190 for (i
= 0; i
< n
; i
++)
3191 LayRedisplayLine(i
+ flayer
->l_height
- n
, 0, flayer
->l_width
- 1, 1);
3192 if (cv
== cv
->c_display
->d_forecv
)
3196 if (lx
+ cv
->c_xoff
< cv
->c_xs
)
3198 int i
, n
= cv
->c_xs
- (lx
+ cv
->c_xoff
);
3199 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3200 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3201 if (cv
->c_xoff
+ n
> cv
->c_xs
)
3202 n
= cv
->c_xs
- cv
->c_xoff
;
3204 RethinkViewportOffsets(cv
);
3205 if (n
> cv
->c_layer
->l_width
)
3206 n
= cv
->c_layer
->l_width
;
3208 LayRedisplayLine(-1, -1, -1, 1);
3209 for (i
= 0; i
< flayer
->l_height
; i
++)
3211 LScrollH(flayer
, -n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3212 LayRedisplayLine(i
, 0, n
- 1, 1);
3214 if (cv
== cv
->c_display
->d_forecv
)
3218 else if (lx
+ cv
->c_xoff
> cv
->c_xe
)
3220 int i
, n
= lx
+ cv
->c_xoff
- cv
->c_xe
;
3221 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3222 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3223 if (cv
->c_xoff
- n
+ cv
->c_layer
->l_width
- 1 < cv
->c_xe
)
3224 n
= cv
->c_xoff
+ cv
->c_layer
->l_width
- 1 - cv
->c_xe
;
3226 RethinkViewportOffsets(cv
);
3227 if (n
> cv
->c_layer
->l_width
)
3228 n
= cv
->c_layer
->l_width
;
3230 LayRedisplayLine(-1, -1, -1, 1);
3231 for (i
= 0; i
< flayer
->l_height
; i
++)
3233 LScrollH(flayer
, n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3234 LayRedisplayLine(i
, flayer
->l_width
- n
, flayer
->l_width
- 1, 1);
3236 if (cv
== cv
->c_display
->d_forecv
)
3243 for (display
= displays
; display
; display
= display
->d_next
)
3245 if (D_status
== STATUS_ON_WIN
|| D_cvlist
== 0 || D_cvlist
->c_next
== 0)
3247 debug1("serv_select_fn: Restore on cv %#x\n", (int)D_forecv
);
3248 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
3253 logflush_fn(ev
, data
)
3261 if (!islogfile(NULL
))
3262 return; /* no more logfiles */
3264 n
= log_flush
? log_flush
: (logtstamp_after
+ 4) / 5;
3267 SetTimeout(ev
, n
* 1000);
3268 evenq(ev
); /* re-enqueue ourself */
3272 /* write fancy time-stamp */
3273 for (p
= windows
; p
; p
= p
->w_next
)
3277 p
->w_logsilence
+= n
;
3278 if (p
->w_logsilence
< logtstamp_after
)
3280 if (p
->w_logsilence
- n
>= logtstamp_after
)
3282 buf
= MakeWinMsg(logtstamp_string
, p
, '%');
3283 logfwrite(p
->w_log
, buf
, strlen(buf
));
3288 * Interprets ^?, ^@ and other ^-control-char notation.
3289 * Interprets \ddd octal notation
3291 * The result is placed in *cp, p is advanced behind the parsed expression and
3300 if (*p
== '^' && p
[1])
3310 else if (*p
== '\\' && *++p
<= '7' && *p
>= '0')
3314 *cp
= *cp
* 8 + *p
- '0';
3315 while (*++p
<= '7' && *p
>= '0');
3326 unsigned char buf
[2];
3329 SetEscape((struct acluser
*)0, -1, -1);
3332 if ((p
= ParseChar(p
, (char *)buf
)) == NULL
||
3333 (p
= ParseChar(p
, (char *)buf
+1)) == NULL
|| *p
)
3335 SetEscape((struct acluser
*)0, buf
[0], buf
[1]);