1 /* Copyright (c) 2008, 2009
2 * Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de)
3 * Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de)
4 * Micah Cowan (micah@cowan.name)
5 * Sadrul Habib Chowdhury (sadrul@users.sourceforge.net)
6 * Copyright (c) 1993-2002, 2003, 2005, 2006, 2007
7 * Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de)
8 * Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de)
9 * Copyright (c) 1987 Oliver Laumann
12 * Authors: Hadi Bargi Rangin bargi@dots.physics.orst.edu
13 * Bill Barry barryb@dots.physics.orst.edu
14 * Randy Lundquist randyl@dots.physics.orst.edu
16 * Modifications Copyright (c) 1995 by
17 * Science Access Project, Oregon State University.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3, or (at your option)
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program (see the file COPYING); if not, see
32 * http://www.gnu.org/licenses/, or contact Free Software Foundation, Inc.,
33 * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
35 ****************************************************************
38 #include <sys/types.h>
44 # include <sys/sysmacros.h>
49 # include <sys/ioctl.h>
59 # include <sys/stropts.h>
62 #if defined(SYSV) && !defined(ISC)
63 # include <sys/utsname.h>
66 #if defined(sequent) || defined(SVR4)
67 # include <sys/resource.h>
68 #endif /* sequent || SVR4 */
72 # include <sys/sioctl.h>
76 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
79 #if defined(USE_LOCALE) || defined(ENCODINGS)
82 #if defined(HAVE_NL_LANGINFO) && defined(ENCODINGS)
83 # include <langinfo.h>
91 #include "patchlevel.h"
94 * At the moment we only need the real password if the
95 * builtin lock is used. Therefore disable SHADOWPW if
96 * we do not really need it (kind of security thing).
105 #endif /* SHADOWPW */
107 #include "logfile.h" /* islogfile, logfflush */
114 extern char Term
[], screenterm
[], **environ
, Termcap
[];
116 int VBellWait
, MsgWait
, MsgMinWait
, SilenceWait
;
118 extern struct acluser
*users
;
119 extern struct display
*displays
, *display
;
121 extern struct LayFuncs MarkLf
;
124 extern int visual_bell
;
126 extern unsigned char mark_key_tab
[];
128 extern char version
[];
129 extern char DefaultShell
[];
131 extern char *zmodem_sendcmd
;
132 extern char *zmodem_recvcmd
;
134 extern struct layout
*layout_last
;
140 extern struct NewWindow nwin_undef
, nwin_default
, nwin_options
;
143 static struct passwd
*getpwbyname
__P((char *, struct passwd
*));
144 static void SigChldHandler
__P((void));
145 static sigret_t SigChld
__P(SIGPROTOARG
);
146 static sigret_t SigInt
__P(SIGPROTOARG
);
147 static sigret_t CoreDump
__P(SIGPROTOARG
);
148 static sigret_t FinitHandler
__P(SIGPROTOARG
);
149 static void DoWait
__P((void));
150 static void serv_read_fn
__P((struct event
*, char *));
151 static void serv_select_fn
__P((struct event
*, char *));
152 static void logflush_fn
__P((struct event
*, char *));
153 static void backtick_filter
__P((struct backtick
*));
154 static void backtick_fn
__P((struct event
*, char *));
155 static char *runbacktick
__P((struct backtick
*, int *, time_t));
156 static int IsSymbol
__P((char *, char *));
157 static char *ParseChar
__P((char *, char *));
158 static int ParseEscape
__P((char *));
159 static char *pad_expand
__P((char *, char *, int, int));
161 static void fds
__P((void));
164 int nversion
; /* numerical version, used for secondary DA */
172 struct mode attach_Mode
;
174 char SockPath
[MAXPATHLEN
+ 2 * MAXSTR
];
175 char *SockName
; /* SockName is pointer in SockPath */
176 char *SockMatch
= NULL
; /* session id command line argument */
177 int ServerSocket
= -1;
178 struct event serv_read
;
179 struct event serv_select
;
180 struct event logflushev
;
182 char **NewEnv
= NULL
;
184 char *RcFileName
= NULL
;
187 char *screenlogfile
; /* filename layout */
188 int log_flush
= 10; /* flush interval in seconds */
189 int logtstamp_on
= 0; /* tstamp disabled */
190 char *logtstamp_string
; /* stamp layout */
191 int logtstamp_after
= 120; /* first tstamp after 120s */
192 char *hardcopydir
= NULL
;
194 char *VisualBellString
;
195 char *ActivityString
;
200 char *PowDetachString
;
208 int iflag
, rflag
, dflag
, lsflag
, quietflag
, wipeflag
, xflag
;
219 int tty_oldmode
= -1;
222 char HostName
[MAXSTR
];
223 int MasterPid
, PanicPid
;
224 int real_uid
, real_gid
, eff_uid
, eff_gid
;
226 int ZombieKey_destroy
, ZombieKey_resurrect
, ZombieKey_onerror
;
227 char *preselect
= NULL
; /* only used in Attach() */
230 char *screenencodings
;
243 struct layer
*flayer
;
246 struct win
*console_window
;
255 char strnomem
[] = "Out of memory.";
258 static int InterruptPlease
;
259 static int GotSigChld
;
262 lf_secreopen(name
, wantfd
, l
)
270 if (((got_fd
= secopen(name
, O_WRONLY
| O_CREAT
| O_APPEND
, 0666)) < 0) ||
271 lf_move_fd(got_fd
, wantfd
) < 0)
274 debug1("lf_secreopen: failed for %s\n", name
);
277 l
->st
->st_ino
= l
->st
->st_dev
= 0;
278 debug2("lf_secreopen: %d = %s\n", wantfd
, name
);
282 /********************************************************************/
283 /********************************************************************/
284 /********************************************************************/
287 static struct passwd
*
288 getpwbyname(name
, ppp
)
294 struct spwd
*sss
= NULL
;
295 static char *spw
= NULL
;
298 if (!ppp
&& !(ppp
= getpwnam(name
)))
301 /* Do password sanity check..., allow ##user for SUN_C2 security */
306 if (ppp
->pw_passwd
[0] == '#' && ppp
->pw_passwd
[1] == '#' &&
307 strcmp(ppp
->pw_passwd
+ 2, ppp
->pw_name
) == 0)
311 char c
= ppp
->pw_passwd
[n
];
312 if (!(c
== '.' || c
== '/' || c
== '$' ||
313 (c
>= '0' && c
<= '9') ||
314 (c
>= 'a' && c
<= 'z') ||
315 (c
>= 'A' && c
<= 'Z')))
320 /* try to determine real password */
321 if (n
< 13 && sss
== 0)
323 sss
= getspnam(ppp
->pw_name
);
328 ppp
->pw_passwd
= spw
= SaveStr(sss
->sp_pwdp
);
329 endspent(); /* this should delete all buffers ... */
332 endspent(); /* this should delete all buffers ... */
338 if (ppp
->pw_passwd
&& strlen(ppp
->pw_passwd
) == 13 + 11)
339 ppp
->pw_passwd
[13] = 0; /* beware of linux's long passwords */
352 s
= getenv("LC_ALL");
354 s
= getenv("LC_CTYPE");
369 char socknamebuf
[2 * MAXSTR
];
371 char *myname
= (ac
== 0) ? "screen" : av
[0];
374 #ifdef _MODE_T /* (jw) */
379 #if defined(SYSV) && !defined(ISC)
380 struct utsname utsnam
;
382 struct NewWindow nwin
;
383 int detached
= 0; /* start up detached */
389 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
390 setcompat(COMPAT_POSIX
|COMPAT_BSDPROT
); /* turn on seteuid support */
392 #if defined(sun) && defined(SVR4)
394 /* Solaris' login blocks SIGHUP! This is _very bad_ */
397 sigprocmask(SIG_SETMASK
, &sset
, 0);
402 * First, close all unused descriptors
403 * (otherwise, we might have problems with the select() call)
409 snprintf(version
, 59, "%d.%.2d.%.2d%s (%s%s) %s", REV
, VERS
,
410 PATCHLEVEL
, STATE
, ORIGIN
, GIT_REV
, DATE
);
411 nversion
= REV
* 10000 + VERS
* 100 + PATCHLEVEL
;
412 debug2("-- screen debug started %s (%s)\n", *av
, version
);
426 debug("NAMEDPIPE\n");
428 #if defined(SIGWINCH) && defined(TIOCGWINSZ)
429 debug("Window size changing enabled\n");
459 debug1("NAME_MAX = %d\n", NAME_MAX
);
462 BellString
= SaveStr("Bell in window %n");
463 VisualBellString
= SaveStr(" Wuff, Wuff!! ");
464 ActivityString
= SaveStr("Activity in window %n");
465 screenlogfile
= SaveStr("screenlog.%n");
466 logtstamp_string
= SaveStr("-- %n:%t -- time-stamp -- %M/%d/%y %c:%s --\n");
467 hstatusstring
= SaveStr("%h");
468 captionstring
= SaveStr("%3n %t");
469 timestring
= SaveStr("%c:%s %M %d %H%? %l%?");
470 wlisttit
= SaveStr("Num Name%=Flags");
471 wliststr
= SaveStr("%3n %t%=%f");
473 BufferFile
= SaveStr(DEFAULT_BUFFERFILE
);
479 default_startup
= (ac
> 1) ? 0 : 1;
481 VBellWait
= VBELLWAIT
* 1000;
482 MsgWait
= MSGWAIT
* 1000;
483 MsgMinWait
= MSGMINWAIT
* 1000;
484 SilenceWait
= SILENCEWAIT
;
489 zmodem_sendcmd
= SaveStr("!!! sz -vv -b ");
490 zmodem_recvcmd
= SaveStr("!!! rz -vv -b -E");
494 CompileKeys((char *)0, 0, mark_key_tab
);
498 screenencodings
= SaveStr(SCREENENCODINGS
);
504 nwin_options
= nwin_undef
;
505 strcpy(screenterm
, "screen");
507 logreopen_register(lf_secreopen
);
510 /* if this is a login screen, assume -RR */
519 ShellProg
= SaveStr(DefaultShell
); /* to prevent nasty circles */
524 if (--ac
> 0 && *ap
== '-')
526 if (ap
[1] == '-' && ap
[2] == 0)
532 if (ap
[1] == '-' && !strcmp(ap
, "--version"))
533 Panic(0, "Screen version %s", version
);
534 if (ap
[1] == '-' && !strcmp(ap
, "--help"))
535 exit_with_usage(myname
, NULL
, NULL
);
536 while (ap
&& *ap
&& *++ap
)
541 nwin_options
.aflag
= 1;
546 case 'p': /* preselect */
552 exit_with_usage(myname
, "Specify a window to preselect with -p", NULL
);
559 bd
.bd_start_braille
= 1;
568 exit_with_usage(myname
, "Specify an alternate rc-filename with -c", NULL
);
577 exit_with_usage(myname
, "Specify command characters with -e", NULL
);
581 Panic(0, "Two characters are required with -e option, not '%s'.", ap
);
590 nwin_options
.flowflag
= FLOW_NOW
* 0;
597 nwin_options
.flowflag
= FLOW_NOW
* 1;
600 nwin_options
.flowflag
= FLOW_AUTOFLAG
;
603 exit_with_usage(myname
, "Unknown flow option -%s", --ap
);
608 exit_with_usage(myname
, NULL
, NULL
);
609 nwin_options
.histheight
= atoi(*++av
);
610 if (nwin_options
.histheight
< 0)
611 exit_with_usage(myname
, "-h: %s: negative scrollback size?", *av
);
616 case 't': /* title, the former AkA == -k */
618 exit_with_usage(myname
, "Specify a new window-name with -t", NULL
);
619 nwin_options
.aka
= *++av
;
627 nwin_options
.lflag
= 0;
634 nwin_options
.lflag
= 1;
637 nwin_options
.lflag
= 3;
640 case 'i': /* -list */
642 if (ac
> 1 && !SockMatch
)
650 exit_with_usage(myname
, "%s: Unknown suboption to -l", --ap
);
656 if (ac
> 1 && !SockMatch
)
663 nwin_options
.Lflag
= 1;
668 case 'O': /* to be (or not to be?) deleted. jw. */
673 exit_with_usage(myname
, "Specify terminal-type with -T", NULL
);
674 if (strlen(*++av
) < 20)
675 strcpy(screenterm
, *av
);
677 Panic(0, "-T: terminal name too long. (max. 20 char)");
678 nwin_options
.term
= screenterm
;
688 if (ac
> 1 && *av
[1] != '-' && !SockMatch
)
692 debug2("rflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
700 rflag
+= (*ap
== 'R') ? 2 : 1;
711 if (*av
[1] != '-' && !SockMatch
)
715 debug2("dflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
722 exit_with_usage(myname
, "Specify shell with -s", NULL
);
725 ShellProg
= SaveStr(*++av
);
726 debug1("ShellProg: '%s'\n", ShellProg
);
732 exit_with_usage(myname
, "Specify session-name with -S", NULL
);
736 exit_with_usage(myname
, "Empty session-name?", NULL
);
742 Panic(0, "Screen version %s", version
);
746 nwin_options
.encoding
= nwin_options
.encoding
== -1 ? UTF8
: 0;
750 exit_with_usage(myname
, "Unknown option %s", --ap
);
762 if (eff_uid
!= real_uid
)
764 /* if running with s-bit, we must install a special signal
765 * handler routine that resets the s-bit, so that we get a
768 #ifdef SIGBUS /* OOPS, linux has no bus errors! */
769 signal(SIGBUS
, CoreDump
);
771 signal(SIGSEGV
, CoreDump
);
775 setlocale(LC_ALL
, "");
778 if (nwin_options
.encoding
== -1)
780 /* ask locale if we should start in UTF-8 mode */
781 # ifdef HAVE_NL_LANGINFO
783 setlocale(LC_CTYPE
, "");
785 nwin_options
.encoding
= FindEncoding(nl_langinfo(CODESET
));
786 debug1("locale says encoding = %d\n", nwin_options
.encoding
);
790 if ((s
= locale_name()) && InStr(s
, "UTF-8"))
791 nwin_options
.encoding
= UTF8
;
793 debug1("environment says encoding=%d\n", nwin_options
.encoding
);
799 if ((s
= locale_name()))
801 if(!strncmp(s
, "zh_", 3) || !strncmp(s
, "ja_", 3) || !strncmp(s
, "ko_", 3))
809 if (nwin_options
.aka
)
812 if (nwin_options
.encoding
> 0)
814 size_t len
= strlen(nwin_options
.aka
);
816 char *newbuf
= malloc(3 * len
);
819 newsz
= RecodeBuf(nwin_options
.aka
, len
,
820 nwin_options
.encoding
, 0, newbuf
);
821 newbuf
[newsz
] = '\0';
822 nwin_options
.aka
= newbuf
;
827 /* If we just use the original value from av,
828 subsequent shelltitle invocations will attempt to free
829 space we don't own... */
830 nwin_options
.aka
= SaveStr(nwin_options
.aka
);
834 if (SockMatch
&& strlen(SockMatch
) >= MAXSTR
)
835 Panic(0, "Ridiculously long socketname - try again.");
836 if (cmdflag
&& !rflag
&& !dflag
&& !xflag
)
838 if (!cmdflag
&& dflag
&& mflag
&& !(rflag
|| xflag
))
842 nwin
.encoding
= nwin_undef
.encoding
; /* let screenrc overwrite it */
847 /* make the write() calls return -1 on all errors */
850 * Ronald F. Guilmette, Oct 29 '94, bug-gnu-utils@prep.ai.mit.edu:
851 * It appears that in System V Release 4, UNIX, if you are writing
852 * an output file and you exceed the currently set file size limit,
853 * you _don't_ just get the call to `write' returning with a
854 * failure code. Rather, you get a signal called `SIGXFSZ' which,
855 * if neither handled nor ignored, will cause your program to crash
858 signal(SIGXFSZ
, SIG_IGN
);
862 signal(SIGPIPE
, SIG_IGN
);
869 sh
= getenv("SHELL");
870 ShellProg
= SaveStr(sh
? sh
: DefaultShell
);
872 ShellArgs
[0] = ShellProg
;
873 home
= getenv("HOME");
874 if (!mflag
&& !SockMatch
)
877 if (sty
&& *sty
== 0)
882 if (!(nethackflag
= (getenv("NETHACKOPTIONS") != NULL
)))
884 char nethackrc
[MAXPATHLEN
];
886 if (home
&& (strlen(home
) < (MAXPATHLEN
- 20)))
888 sprintf(nethackrc
,"%s/.nethackrc", home
);
889 nethackflag
= !access(nethackrc
, F_OK
);
895 own_uid
= multi_uid
= real_uid
;
896 if (SockMatch
&& (sockp
= index(SockMatch
, '/')))
900 SockMatch
= sockp
+ 1;
904 if ((mppp
= getpwnam(multi
)) == (struct passwd
*)0)
905 Panic(0, "Cannot identify account '%s'.", multi
);
906 multi_uid
= mppp
->pw_uid
;
907 multi_home
= SaveStr(mppp
->pw_dir
);
908 if (strlen(multi_home
) > MAXPATHLEN
- 10)
909 Panic(0, "home directory path too long");
911 /* always fake multi attach mode */
918 /* Special case: effective user is multiuser. */
919 if (eff_uid
&& (multi_uid
!= eff_uid
))
920 Panic(0, "Must run suid root for multiuser support.");
922 if (SockMatch
&& *SockMatch
== 0)
924 #endif /* MULTIUSER */
926 if ((LoginName
= getlogin()) && LoginName
[0] != '\0')
928 if ((ppp
= getpwnam(LoginName
)) != (struct passwd
*) 0)
929 if ((int)ppp
->pw_uid
!= real_uid
)
930 ppp
= (struct passwd
*) 0;
934 if ((ppp
= getpwuid(real_uid
)) == 0)
936 Panic(0, "getpwuid() can't identify your account!");
939 LoginName
= ppp
->pw_name
;
941 LoginName
= SaveStr(LoginName
);
943 ppp
= getpwbyname(LoginName
, ppp
);
945 #if !defined(SOCKDIR) && defined(MULTIUSER)
946 if (multi
&& !multiattach
)
948 if (home
&& strcmp(home
, ppp
->pw_dir
))
949 Panic(0, "$HOME must match passwd entry for multiuser screens.");
953 #define SET_GUID() do \
957 eff_uid = real_uid; \
958 eff_gid = real_gid; \
961 #define SET_TTYNAME(fatal) do \
963 if (!(attach_tty = ttyname(0))) \
966 Panic(0, "Must be connected to a terminal."); \
970 else if (stat(attach_tty, &st)) \
971 Panic(errno, "Cannot access '%s'", attach_tty); \
972 if (strlen(attach_tty) >= MAXPATHLEN) \
973 Panic(0, "TtyName too long - sorry."); \
976 if (home
== 0 || *home
== '\0')
978 if (strlen(LoginName
) > 20)
979 Panic(0, "LoginName too long - sorry.");
981 if (multi
&& strlen(multi
) > 20)
982 Panic(0, "Screen owner name too long - sorry.");
984 if (strlen(home
) > MAXPATHLEN
- 25)
985 Panic(0, "$HOME too long - sorry.");
988 if (!detached
&& !lsflag
&& !cmdflag
&& !(dflag
&& !mflag
&& !rflag
&& !xflag
) && !(!mflag
&& !SockMatch
&& sty
&& !xflag
))
994 /* ttyname implies isatty */
997 tty_mode
= (int)st
.st_mode
& 0777;
1001 fl
= fcntl(0, F_GETFL
, 0);
1002 if (fl
!= -1 && (fl
& (O_RDWR
|O_RDONLY
|O_WRONLY
)) == O_RDWR
)
1005 if (attach_fd
== -1)
1007 if ((n
= secopen(attach_tty
, O_RDWR
| O_NONBLOCK
, 0)) < 0)
1008 Panic(0, "Cannot open your terminal '%s' - please check.", attach_tty
);
1011 debug2("attach_tty is %s, attach_fd is %d\n", attach_tty
, attach_fd
);
1013 if ((attach_term
= getenv("TERM")) == 0 || *attach_term
== 0)
1014 Panic(0, "Please set a terminal type.");
1015 if (strlen(attach_term
) > sizeof(D_termname
) - 1)
1016 Panic(0, "$TERM too long - sorry.");
1017 GetTTY(0, &attach_Mode
);
1018 #ifdef DEBUGGGGGGGGGGGGGGG
1019 DebugTTY(&attach_Mode
);
1024 oumask
= umask(0); /* well, unsigned never fails? jw. */
1026 if ((oumask
= (int)umask(0)) == -1)
1027 Panic(errno
, "Cannot change umask to zero");
1029 SockDir
= getenv("SCREENDIR");
1032 if (strlen(SockDir
) >= MAXPATHLEN
- 1)
1033 Panic(0, "Ridiculously long $SCREENDIR - try again.");
1036 Panic(0, "No $SCREENDIR with multi screens, please.");
1043 sprintf(SockPath
, "%s/.screen", multi_home
);
1047 sprintf(SockPath
, "%s/S-%s", SockDir
, multi
);
1056 sprintf(SockPath
, "%s/.screen", home
);
1062 if (access(SockDir
, F_OK
))
1064 debug1("SockDir '%s' missing ...\n", SockDir
);
1065 if (UserContext() > 0)
1067 if (mkdir(SockDir
, 0700))
1071 if (UserStatus() <= 0)
1072 Panic(0, "Cannot make directory '%s'.", SockDir
);
1074 if (SockDir
!= SockPath
)
1075 strcpy(SockPath
, SockDir
);
1081 if (stat(SockDir
, &st
))
1083 n
= (eff_uid
== 0 && (real_uid
|| eff_gid
== real_gid
)) ? 0755 :
1084 (eff_gid
!= real_gid
) ? 0775 :
1090 if (mkdir(SockDir
, n
) == -1)
1091 Panic(errno
, "Cannot make directory '%s'", SockDir
);
1095 if (!S_ISDIR(st
.st_mode
))
1096 Panic(0, "'%s' must be a directory.", SockDir
);
1097 if (eff_uid
== 0 && real_uid
&& (int)st
.st_uid
!= eff_uid
)
1098 Panic(0, "Directory '%s' must be owned by root.", SockDir
);
1099 n
= (eff_uid
== 0 && (real_uid
|| (st
.st_mode
& 0775) != 0775)) ? 0755 :
1100 (eff_gid
== (int)st
.st_gid
&& eff_gid
!= real_gid
) ? 0775 :
1102 if (((int)st
.st_mode
& 0777) != n
)
1103 Panic(0, "Directory '%s' must have mode %03o.", SockDir
, n
);
1105 sprintf(SockPath
, "%s/S-%s", SockDir
, LoginName
);
1106 if (access(SockPath
, F_OK
))
1108 if (mkdir(SockPath
, 0700) == -1)
1109 Panic(errno
, "Cannot make directory '%s'", SockPath
);
1110 (void) chown(SockPath
, real_uid
, real_gid
);
1116 if (stat(SockPath
, &st
) == -1)
1117 Panic(errno
, "Cannot access %s", SockPath
);
1119 if (!S_ISDIR(st
.st_mode
))
1120 Panic(0, "%s is not a directory.", SockPath
);
1124 if ((int)st
.st_uid
!= multi_uid
)
1125 Panic(0, "%s is not the owner of %s.", multi
, SockPath
);
1130 if ((int)st
.st_uid
!= real_uid
)
1131 Panic(0, "You are not the owner of %s.", SockPath
);
1133 if ((st
.st_mode
& 0777) != 0700)
1134 Panic(0, "Directory %s must have mode 700.", SockPath
);
1135 if (SockMatch
&& index(SockMatch
, '/'))
1136 Panic(0, "Bad session name '%s'", SockMatch
);
1137 SockName
= SockPath
+ strlen(SockPath
) + 1;
1139 (void) umask(oumask
);
1140 debug2("SockPath: %s SockMatch: %s\n", SockPath
, SockMatch
? SockMatch
: "NULL");
1142 #if defined(SYSV) && !defined(ISC)
1143 if (uname(&utsnam
) == -1)
1144 Panic(errno
, "uname");
1145 strncpy(HostName
, utsnam
.nodename
, sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1);
1146 HostName
[sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1] = '\0';
1148 (void) gethostname(HostName
, MAXSTR
);
1149 HostName
[MAXSTR
- 1] = '\0';
1151 if ((ap
= index(HostName
, '.')) != NULL
)
1160 real_uid
= multi_uid
;
1163 i
= FindSocket((int *)NULL
, &fo
, &oth
, SockMatch
);
1165 exit(8 + (fo
? ((oth
|| i
) ? 2 : 1) : 0) + i
);
1167 Panic(0, "No Sockets found in %s.\n", SockPath
);
1168 Panic(0, "%d Socket%s in %s.\n", fo
, fo
> 1 ? "s" : "", SockPath
);
1171 signal(SIG_BYE
, AttacherFinit
); /* prevent races */
1174 /* attach_tty is not mandatory */
1177 Panic(0, "Please specify a command.");
1179 SendCmdMessage(sty
, SockMatch
, av
);
1182 else if (rflag
|| xflag
)
1184 debug("screen -r: - is there anybody out there?\n");
1185 if (Attach(MSG_ATTACH
))
1192 Panic(0, "Can't create sessions of other users.");
1194 debug("screen -r: backend not responding -- still crying\n");
1196 else if (dflag
&& !mflag
)
1200 Msg(0, "[%s %sdetached.]\n", SockName
, (dflag
> 1 ? "power " : ""));
1204 if (!SockMatch
&& !mflag
&& sty
)
1206 /* attach_tty is not mandatory */
1209 nwin_options
.args
= av
;
1210 SendCreateMsg(sty
, &nwin
);
1214 nwin_compose(&nwin_default
, &nwin_options
, &nwin_default
);
1216 if (!detached
|| dflag
!= 2)
1224 Panic(errno
, "fork");
1232 sprintf(socknamebuf
, "%d.%s", MasterPid
, SockMatch
);
1234 sprintf(socknamebuf
, "%d.%s.%s", MasterPid
, stripdev(attach_tty
), HostName
);
1235 for (ap
= socknamebuf
; *ap
; ap
++)
1239 if (strlen(socknamebuf
) > NAME_MAX
)
1240 socknamebuf
[NAME_MAX
] = 0;
1242 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1249 PanicPid
= getppid();
1251 if (DefaultEsc
== -1)
1252 DefaultEsc
= Ctrl('a');
1253 if (DefaultMetaEsc
== -1)
1254 DefaultMetaEsc
= 'a';
1256 ap
= av0
+ strlen(av0
) - 1;
1259 if (!strncmp("screen", ap
, 6))
1261 strncpy(ap
, "SCREEN", 6); /* name this process "SCREEN-BACKEND" */
1273 if (dfp
&& dfp
!= stderr
)
1275 sprintf(buf
, "%s/SCREEN.%d", DEBUGDIR
, (int)getpid());
1276 if ((dfp
= fopen(buf
, "w")) == NULL
)
1279 (void) chmod(buf
, 0666);
1284 if (attach_fd
== -1)
1286 if ((n
= secopen(attach_tty
, O_RDWR
, 0)) < 0)
1287 Panic(0, "Cannot reopen '%s' - please check.", attach_tty
);
1294 freopen("/dev/null", "r", stdin
);
1295 freopen("/dev/null", "w", stdout
);
1300 freopen("/dev/null", "w", stderr
);
1301 debug("-- screen.back debug started\n");
1304 * This guarantees that the session owner is listed, even when we
1305 * start detached. From now on we should not refer to 'LoginName'
1306 * any more, use users->u_name instead.
1308 if (UserAdd(LoginName
, (char *)0, (struct acluser
**)0) < 0)
1309 Panic(0, "Could not create user info");
1312 if (MakeDisplay(LoginName
, attach_tty
, attach_term
, n
, getppid(), &attach_Mode
) == 0)
1313 Panic(0, "Could not alloc display");
1316 D_encoding
= nwin_options
.encoding
> 0 ? nwin_options
.encoding
: 0;
1317 debug1("D_encoding = %d\n", D_encoding
);
1323 /* user started us with -S option */
1324 sprintf(socknamebuf
, "%d.%s", (int)getpid(), SockMatch
);
1328 sprintf(socknamebuf
, "%d.%s.%s", (int)getpid(), stripdev(attach_tty
),
1331 for (ap
= socknamebuf
; *ap
; ap
++)
1335 if (strlen(socknamebuf
) > NAME_MAX
)
1337 debug2("Socketname %s truncated to %d chars\n", socknamebuf
, NAME_MAX
);
1338 socknamebuf
[NAME_MAX
] = 0;
1341 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1343 ServerSocket
= MakeServerSocket();
1346 # ifdef ALLOW_SYSSCREENRC
1347 if ((ap
= getenv("SYSSCREENRC")))
1348 (void)StartRc(ap
, 0);
1351 (void)StartRc(ETCSCREENRC
, 0);
1353 (void)StartRc(RcFileName
, 0);
1357 # endif /* UTNOKEEP */
1358 # endif /* UTMPOK */
1361 if (InitTermcap(0, 0))
1363 debug("Could not init termcap - exiting\n");
1364 fcntl(D_userfd
, F_SETFL
, 0); /* Flush sets FNBLOCK */
1367 Kill(D_userpid
, SIG_BYE
);
1370 MakeDefaultCanvas();
1382 signal(SIGHUP
, SigHup
);
1383 signal(SIGINT
, FinitHandler
);
1384 signal(SIGQUIT
, FinitHandler
);
1385 signal(SIGTERM
, FinitHandler
);
1387 signal(SIGTTIN
, SIG_IGN
);
1388 signal(SIGTTOU
, SIG_IGN
);
1394 SetMode(&D_OldMode
, &D_NewMode
, D_flow
, iflag
);
1395 /* Note: SetMode must be called _before_ FinishRc. */
1396 SetTTY(D_userfd
, &D_NewMode
);
1397 if (fcntl(D_userfd
, F_SETFL
, FNBLOCK
))
1398 Msg(errno
, "Warning: NBLOCK fcntl failed");
1401 brktty(-1); /* just try */
1402 signal(SIGCHLD
, SigChld
);
1404 # ifdef ALLOW_SYSSCREENRC
1405 if ((ap
= getenv("SYSSCREENRC")))
1409 FinishRc(ETCSCREENRC
);
1411 FinishRc(RcFileName
);
1413 debug2("UID %d EUID %d\n", (int)getuid(), (int)geteuid());
1414 if (windows
== NULL
)
1416 debug("We open one default window, as screenrc did not specify one.\n");
1417 if (MakeWindow(&nwin
) == -1)
1420 struct timeval tv
= { MsgWait
/1000, 1000*(MsgWait
%1000) };
1423 Msg(0, "Sorry, could not find a PTY or TTY.");
1424 // allow user to exit early by pressing any key.
1425 select(1, &rfd
, NULL
, NULL
, &tv
);
1430 else if (ac
) /* Screen was invoked with a command */
1439 if (display
&& default_startup
)
1440 display_copyright();
1441 signal(SIGINT
, SigInt
);
1442 if (rflag
&& (rflag
& 1) == 0 && !quietflag
)
1444 Msg(0, "New screen...");
1448 serv_read
.type
= EV_READ
;
1449 serv_read
.fd
= ServerSocket
;
1450 serv_read
.handler
= serv_read_fn
;
1453 serv_select
.pri
= -10;
1454 serv_select
.type
= EV_ALWAYS
;
1455 serv_select
.handler
= serv_select_fn
;
1456 evenq(&serv_select
);
1458 logflushev
.type
= EV_TIMEOUT
;
1459 logflushev
.handler
= logflush_fn
;
1467 WindowDied(p
, wstat
, wstat_valid
)
1478 if (p
->w_destroyev
.data
== (char *)p
)
1480 wstat
= p
->w_exitstatus
;
1482 evdeq(&p
->w_destroyev
);
1483 p
->w_destroyev
.data
= 0;
1486 #if defined(BSDJOBS) && !defined(BSDWAIT)
1487 if (!wstat_valid
&& p
->w_pid
> 0)
1489 /* EOF on file descriptor. The process is probably also dead.
1491 if (waitpid(p
->w_pid
, &wstat
, WNOHANG
| WUNTRACED
) == p
->w_pid
)
1498 if (ZombieKey_destroy
&& ZombieKey_onerror
&& wstat_valid
&&
1499 WIFEXITED(wstat
) && WEXITSTATUS(wstat
) == 0)
1502 if (ZombieKey_destroy
&& !killit
)
1504 char buf
[100], *s
, reason
[100];
1508 if (WIFEXITED(wstat
))
1509 if (WEXITSTATUS(wstat
))
1510 sprintf(reason
, "terminated with exit status %d", WEXITSTATUS(wstat
));
1512 sprintf(reason
, "terminated normally");
1513 else if (WIFSIGNALED(wstat
))
1514 sprintf(reason
, "terminated with signal %d%s", WTERMSIG(wstat
),
1516 WCOREDUMP(wstat
) ? " (core file generated)" : "");
1521 sprintf(reason
, "detached from window");
1526 s
[strlen(s
) - 1] = '\0';
1527 debug3("window %d (%s) going into zombie state fd %d",
1528 p
->w_number
, p
->w_title
, p
->w_ptyfd
);
1530 if (p
->w_slot
!= (slot_t
)0 && p
->w_slot
!= (slot_t
)-1)
1533 p
->w_slot
= 0; /* "detached" */
1538 p
->w_deadpid
= p
->w_pid
;
1541 /* p->w_y = p->w_bot; */
1542 p
->w_y
= MFindUsedLine(p
, p
->w_bot
, 1);
1543 sprintf(buf
, "\n\r=== Command %s (%s) ===", reason
, s
? s
: "?");
1544 WriteString(p
, buf
, strlen(buf
));
1545 WindowChanged(p
, 'f');
1566 signal(SIGCHLD
, SigChld
);
1569 if (stat(SockPath
, &st
) == -1)
1571 debug1("SigChldHandler: Yuck! cannot stat '%s'\n", SockPath
);
1572 if (!RecoverSocket())
1574 debug("SCREEN cannot recover from corrupt Socket, bye\n");
1578 debug1("'%s' reconstructed\n", SockPath
);
1581 debug2("SigChldHandler: stat '%s' o.k. (%03o)\n", SockPath
, (int)st
.st_mode
);
1587 debug("SigChld()\n");
1595 /* Hangup all displays */
1596 while ((display
= displays
) != 0)
1602 * the backend's Interrupt handler
1603 * we cannot insert the intrc directly, as we never know
1612 debug("SigInt()\n");
1613 if (fore
&& displays
)
1615 # if defined(TERMIO) || defined(POSIX)
1616 ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
1618 ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
1621 write(fore
->w_ptyfd
, &ibuf
, 1);
1624 signal(SIGINT
, SigInt
);
1625 debug("SigInt() careful\n");
1626 InterruptPlease
= 1;
1634 struct display
*disp
;
1637 #if defined(SYSVSIGS) && defined(SIGHASARG)
1638 signal(sigsig
, SIG_IGN
);
1644 sprintf(buf
, "\r\n[screen caught signal %d.%s]\r\n", sigsig
,
1646 sprintf(buf
, "\r\n[screen caught a fatal signal.%s]\r\n",
1648 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1650 #else /* SHADOWPW && !DEBUG */
1652 #endif /* SHADOWPW && !DEBUG */
1654 for (disp
= displays
; disp
; disp
= disp
->d_next
)
1656 fcntl(disp
->d_userfd
, F_SETFL
, 0);
1657 SetTTY(disp
->d_userfd
, &D_OldMode
);
1658 write(disp
->d_userfd
, buf
, strlen(buf
));
1659 Kill(disp
->d_userpid
, SIG_BYE
);
1661 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1662 Kill(getpid(), SIGKILL
);
1664 #else /* SHADOWPW && !DEBUG */
1666 #endif /* SHADOWPW && !DEBUG */
1674 struct win
*p
, *next
;
1683 while ((pid
= waitpid(-1, &wstat
, WNOHANG
| WUNTRACED
)) > 0)
1687 * From: rouilj@sni-usa.com (John Rouillard)
1688 * note that WUNTRACED is not documented to work, but it is defined in
1689 * /usr/include/sys/wait.h, so it may work
1691 while ((pid
= wait2(&wstat
, WNOHANG
| WUNTRACED
)) > 0)
1692 # else /* USE_WAIT2 */
1693 while ((pid
= wait3(&wstat
, WNOHANG
| WUNTRACED
, (struct rusage
*) 0)) > 0)
1694 # endif /* USE_WAIT2 */
1697 while ((pid
= wait(&wstat
)) < 0)
1701 #endif /* BSDJOBS */
1703 for (p
= windows
; p
; p
= next
)
1706 if ( (p
->w_pid
&& pid
== p
->w_pid
) ||
1707 (p
->w_deadpid
&& pid
== p
->w_deadpid
) )
1709 /* child has ceased to exist */
1713 if (WIFSTOPPED(wstat
))
1715 debug3("Window %d pid %d: WIFSTOPPED (sig %d)\n", p
->w_number
, pid
, WSTOPSIG(wstat
));
1717 if (WSTOPSIG(wstat
) == SIGTTIN
)
1719 Msg(0, "Suspended (tty input)");
1724 if (WSTOPSIG(wstat
) == SIGTTOU
)
1726 Msg(0, "Suspended (tty output)");
1730 /* Try to restart process */
1731 Msg(0, "Child has been stopped, restarting.");
1732 if (killpg(pid
, SIGCONT
))
1738 /* Screen will detect the window has died when the window's
1739 * file descriptor signals EOF (which it will do when the process in
1740 * the window terminates). So do this in a timeout of 10 seconds.
1741 * (not doing this at all might also work)
1742 * See #27061 for more details.
1744 p
->w_destroyev
.data
= (char *)p
;
1745 p
->w_exitstatus
= wstat
;
1746 SetTimeout(&p
->w_destroyev
, 10 * 1000);
1747 evenq(&p
->w_destroyev
);
1752 if (p
->w_pwin
&& pid
== p
->w_pwin
->p_pid
)
1754 debug2("pseudo of win Nr %d died. pid == %d\n", p
->w_number
, p
->w_pwin
->p_pid
);
1762 debug1("pid %d not found - hope that's ok\n", pid
);
1769 FinitHandler SIGDEFARG
1772 debug1("FinitHandler called, sig %d.\n", sigsig
);
1774 debug("FinitHandler called.\n");
1784 signal(SIGCHLD
, SIG_DFL
);
1785 signal(SIGHUP
, SIG_IGN
);
1786 debug1("Finit(%d);\n", i
);
1789 struct win
*p
= windows
;
1790 windows
= windows
->w_next
;
1793 if (ServerSocket
!= -1)
1795 debug1("we unlink(%s)\n", SockPath
);
1800 (void) unlink(SockPath
);
1806 for (display
= displays
; display
; display
= display
->d_next
)
1814 AddStr("[screen is terminating]\r\n");
1816 SetTTY(D_userfd
, &D_OldMode
);
1817 fcntl(D_userfd
, F_SETFL
, 0);
1819 Kill(D_userpid
, SIG_BYE
);
1822 * we _cannot_ call eexit(i) here,
1823 * instead of playing with the Socket above. Sigh.
1833 if (ServerSocket
!= -1)
1835 debug1("we unlink(%s)\n", SockPath
);
1838 (void) unlink(SockPath
);
1848 debug1("Hangup %x\n", display
);
1854 if (auto_detach
|| displays
->d_next
)
1861 * Detach now has the following modes:
1862 *D_DETACH SIG_BYE detach backend and exit attacher
1863 *D_HANGUP SIG_BYE detach backend and exit attacher
1864 *D_STOP SIG_STOP stop attacher (and detach backend)
1865 *D_REMOTE SIG_BYE remote detach -- reattach to new attacher
1866 *D_POWER SIG_POWER_BYE power detach -- attacher kills his parent
1867 *D_REMOTE_POWER SIG_POWER_BYE remote power detach -- both
1868 *D_LOCK SIG_LOCK lock the attacher
1870 * we always remove our utmp slots. (even when "lock" or "stop")
1871 * Note: Take extra care here, we may be called by interrupt!
1884 #define AddStrSock(msg) do { \
1887 AddStr("[" msg " from "); \
1892 AddStr("[" msg "]\r\n"); \
1895 signal(SIGHUP
, SIG_IGN
);
1896 debug1("Detach(%d)\n", mode
);
1908 AddStrSock("detached");
1916 #ifdef REMOTE_DETACH
1918 AddStrSock("remote detached");
1924 AddStrSock("power detached");
1925 if (PowDetachString
)
1927 AddStr(PowDetachString
);
1930 sign
= SIG_POWER_BYE
;
1932 #ifdef REMOTE_DETACH
1933 case D_REMOTE_POWER
:
1934 AddStrSock("remote power detached");
1935 if (PowDetachString
)
1937 AddStr(PowDetachString
);
1940 sign
= SIG_POWER_BYE
;
1947 /* tell attacher to lock terminal with a lockprg. */
1951 if (displays
->d_next
== 0)
1953 for (p
= windows
; p
; p
= p
->w_next
)
1955 if (p
->w_slot
!= (slot_t
) -1 && !(p
->w_lflag
& 2))
1959 * Set the slot to 0 to get the window
1962 p
->w_slot
= (slot_t
) 0;
1966 if (mode
!= D_HANGUP
)
1969 if (displays
->d_next
== 0 && console_window
)
1971 if (TtyGrabConsole(console_window
->w_ptyfd
, 0, "detach"))
1973 debug("could not release console - killing window\n");
1974 KillWindow(console_window
);
1975 display
= displays
; /* restore display */
1981 ReleaseAutoWritelock(display
, D_fore
);
1983 D_user
->u_detachwin
= D_fore
->w_number
;
1984 D_user
->u_detachotherwin
= D_other
? D_other
->w_number
: -1;
1986 AutosaveLayout(D_layout
);
1987 layout_last
= D_layout
;
1988 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
1990 p
= Layer2Window(cv
->c_layer
);
1991 SetCanvasWindow(cv
, 0);
1993 WindowChanged(p
, 'u');
1997 debug2("display: %#x displays: %#x\n", (unsigned int)display
, (unsigned int)displays
);
2000 /* Flag detached-ness */
2003 * tell father what to do. We do that after we
2004 * freed the tty, thus getty feels more comfortable on hpux
2005 * if it was a power detach.
2008 debug2("Detach: Signal %d to Attacher(%d)!\n", sign
, pid
);
2009 debug("Detach returns, we are successfully detached.\n");
2010 signal(SIGHUP
, SigHup
);
2021 return strncmp(e
, s
, l
) == 0 && e
[l
] == '=';
2027 register char **op
, **np
;
2028 static char stybuf
[MAXSTR
];
2030 for (op
= environ
; *op
; ++op
)
2033 free((char *)NewEnv
);
2034 NewEnv
= np
= (char **) malloc((unsigned) (op
- environ
+ 7 + 1) * sizeof(char **));
2037 sprintf(stybuf
, "STY=%s", strlen(SockName
) <= MAXSTR
- 5 ? SockName
: "?");
2038 *np
++ = stybuf
; /* NewEnv[0] */
2039 *np
++ = Term
; /* NewEnv[1] */
2040 np
++; /* room for SHELL */
2042 np
+= 2; /* room for TERMCAP and WINDOW */
2044 np
+= 4; /* room for TERMCAP WINDOW LINES COLUMNS */
2047 for (op
= environ
; *op
; ++op
)
2049 if (!IsSymbol(*op
, "TERM") && !IsSymbol(*op
, "TERMCAP")
2050 && !IsSymbol(*op
, "STY") && !IsSymbol(*op
, "WINDOW")
2051 && !IsSymbol(*op
, "SCREENCAP") && !IsSymbol(*op
, "SHELL")
2052 && !IsSymbol(*op
, "LINES") && !IsSymbol(*op
, "COLUMNS")
2061 #if defined(USEVARARGS) && defined(__STDC__)
2062 Msg(int err
, const char *fmt
, VA_DOTS
)
2064 Msg(err
, fmt
, VA_DOTS
)
2071 char buf
[MAXPATHLEN
*2];
2076 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2083 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2084 buf
[sizeof(buf
) - 1] = 0;
2086 debug2("Msg('%s') (%#x);\n", buf
, (unsigned int)display
);
2088 if (display
&& displays
)
2092 for (display
= displays
; display
; display
= display
->d_next
)
2097 /* no displays but a display - must have forked.
2098 * send message to backend!
2100 char *tty
= D_usertty
;
2101 struct display
*olddisplay
= display
;
2102 display
= 0; /* only send once */
2103 SendErrorMsg(tty
, buf
);
2104 display
= olddisplay
;
2107 printf("%s\r\n", buf
);
2111 * Call FinitTerm for all displays, write a message to each and call eexit();
2115 #if defined(USEVARARGS) && defined(__STDC__)
2116 Panic(int err
, const char *fmt
, VA_DOTS
)
2118 Panic(err
, fmt
, VA_DOTS
)
2125 char buf
[MAXPATHLEN
*2];
2130 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2137 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2138 buf
[sizeof(buf
) - 1] = 0;
2140 debug3("Panic('%s'); display=%x displays=%x\n", buf
, display
, displays
);
2141 if (displays
== 0 && display
== 0)
2143 printf("%s\r\n", buf
);
2145 Kill(PanicPid
, SIG_BYE
);
2147 else if (displays
== 0)
2149 /* no displays but a display - must have forked.
2150 * send message to backend!
2152 char *tty
= D_usertty
;
2154 SendErrorMsg(tty
, buf
);
2159 for (display
= displays
; display
; display
= display
->d_next
)
2168 SetTTY(D_userfd
, &D_OldMode
);
2169 fcntl(D_userfd
, F_SETFL
, 0);
2170 write(D_userfd
, buf
, strlen(buf
));
2171 write(D_userfd
, "\n", 1);
2174 Kill(D_userpid
, SIG_BYE
);
2177 if (tty_oldmode
>= 0)
2180 if (setuid(own_uid
))
2181 xseteuid(own_uid
); /* may be a loop. sigh. */
2185 debug1("Panic: changing back modes from %s\n", attach_tty
);
2186 chmod(attach_tty
, tty_oldmode
);
2194 * '^' is allowed as an escape mechanism for control characters. jw.
2196 * Added time insertion using ideas/code from /\ndy Jones
2197 * (andy@lingua.cltr.uq.OZ.AU) - thanks a lot!
2202 static const char days
[] = "SunMonTueWedThuFriSat";
2203 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2206 static char winmsg_buf
[MAXSTR
];
2207 #define MAX_WINMSG_REND 16 /* rendition changes */
2208 static int winmsg_rend
[MAX_WINMSG_REND
];
2209 static int winmsg_rendpos
[MAX_WINMSG_REND
];
2210 static int winmsg_numrend
;
2213 pad_expand(buf
, p
, numpad
, padlen
)
2222 padlen
= padlen
- (p
- buf
); /* space for rent */
2225 pn2
= pn
= p
+ padlen
;
2229 if (r
&& *p
!= 127 && p
- buf
== winmsg_rendpos
[r
- 1])
2231 winmsg_rendpos
[--r
] = pn
- buf
;
2238 i
= numpad
> 0 ? (padlen
+ numpad
- 1) / numpad
: 0;
2243 if (r
&& p
- buf
== winmsg_rendpos
[r
- 1])
2244 winmsg_rendpos
[--r
] = pn
- buf
;
2251 struct backtick
*next
;
2256 char result
[MAXSTR
];
2263 struct backtick
*backticks
;
2267 struct backtick
*bt
;
2272 for (p
= q
= bt
->result
; (c
= (unsigned char)*p
++) != 0;)
2276 if (c
>= ' ' || c
== '\005')
2283 backtick_fn(ev
, data
)
2287 struct backtick
*bt
;
2290 bt
= (struct backtick
*)data
;
2291 debug1("backtick_fn for #%d\n", bt
->num
);
2293 l
= read(ev
->fd
, bt
->buf
+ i
, MAXSTR
- i
);
2296 debug1("EOF on backtick #%d\n", bt
->num
);
2302 debug1("read %d bytes\n", l
);
2304 for (j
= 0; j
< l
; j
++)
2305 if (bt
->buf
[i
- j
- 1] == '\n')
2309 for (k
= i
- j
- 2; k
>= 0; k
--)
2310 if (bt
->buf
[k
] == '\n')
2313 bcopy(bt
->buf
+ k
, bt
->result
, i
- j
- k
);
2314 bt
->result
[i
- j
- k
- 1] = 0;
2315 backtick_filter(bt
);
2316 WindowChanged(0, '`');
2318 if (j
== l
&& i
== MAXSTR
)
2326 bcopy(bt
->buf
+ i
- j
, bt
->buf
, j
);
2333 setbacktick(num
, lifespan
, tick
, cmdv
)
2339 struct backtick
**btp
, *bt
;
2342 debug1("setbacktick called for backtick #%d\n", num
);
2343 for (btp
= &backticks
; (bt
= *btp
) != 0; btp
= &bt
->next
)
2350 for (v
= bt
->cmdv
; *v
; v
++)
2367 bt
= (struct backtick
*)malloc(sizeof *bt
);
2373 bzero(bt
, sizeof(*bt
));
2379 bt
->lifespan
= lifespan
;
2386 if (bt
->tick
== 0 && bt
->lifespan
== 0)
2388 debug("setbacktick: continuous mode\n");
2389 bt
->buf
= (char *)malloc(MAXSTR
);
2393 setbacktick(num
, 0, 0, (char **)0);
2396 bt
->ev
.type
= EV_READ
;
2397 bt
->ev
.fd
= readpipe(bt
->cmdv
);
2398 bt
->ev
.handler
= backtick_fn
;
2399 bt
->ev
.data
= (char *)bt
;
2406 runbacktick(bt
, tickp
, now
)
2407 struct backtick
*bt
;
2414 debug1("runbacktick called for backtick #%d\n", bt
->num
);
2415 if (bt
->tick
&& (!*tickp
|| bt
->tick
< *tickp
))
2417 if ((bt
->lifespan
== 0 && bt
->tick
== 0) || now
< bt
->bestbefore
)
2419 debug1("returning old result (%d)\n", bt
->lifespan
);
2422 f
= readpipe(bt
->cmdv
);
2426 while ((l
= read(f
, bt
->result
+ i
, sizeof(bt
->result
) - i
)) > 0)
2428 debug1("runbacktick: read %d bytes\n", l
);
2430 for (j
= 1; j
< l
; j
++)
2431 if (bt
->result
[i
- j
- 1] == '\n')
2433 if (j
== l
&& i
== sizeof(bt
->result
))
2435 j
= sizeof(bt
->result
) / 2;
2440 bcopy(bt
->result
+ i
- j
, bt
->result
, j
);
2445 bt
->result
[sizeof(bt
->result
) - 1] = '\n';
2446 if (i
&& bt
->result
[i
- 1] == '\n')
2448 debug1("runbacktick: finished, %d bytes\n", i
);
2450 backtick_filter(bt
);
2452 bt
->bestbefore
= now2
+ bt
->lifespan
;
2457 AddWinMsgRend(str
, r
)
2461 if (winmsg_numrend
>= MAX_WINMSG_REND
|| str
< winmsg_buf
||
2462 str
>= winmsg_buf
+ MAXSTR
)
2465 winmsg_rend
[winmsg_numrend
] = r
;
2466 winmsg_rendpos
[winmsg_numrend
] = str
- winmsg_buf
;
2473 MakeWinMsgEv(str
, win
, esc
, padlen
, ev
, rec
)
2483 register char *p
= winmsg_buf
;
2493 int qmflag
= 0, omflag
= 0, qmnumrend
= 0;
2500 struct backtick
*bt
;
2502 if (winmsg_numrend
>= 0)
2505 winmsg_numrend
= -winmsg_numrend
;
2510 gettimeofday(&now
, NULL
);
2511 for (; *s
&& (l
= winmsg_buf
+ MAXSTR
- 1 - p
) > 0; s
++, p
++)
2517 if (*s
!= '^' && *s
>= 64)
2542 if (*++s
== esc
) /* double escape ? */
2544 if ((plusflg
= *s
== '+') != 0)
2546 if ((minusflg
= *s
== '-') != 0)
2548 if ((zeroflg
= *s
== '0') != 0)
2551 while(*s
>= '0' && *s
<= '9')
2552 num
= num
* 10 + (*s
++ - '0');
2553 if ((longflg
= *s
== 'L') != 0)
2561 if ((!qmflag
&& !omflag
) || omflag
== 1)
2564 if (qmnumrend
< winmsg_numrend
)
2565 winmsg_numrend
= qmnumrend
;
2571 qmnumrend
= winmsg_numrend
;
2572 qmflag
= omflag
= 0;
2578 if (qmflag
&& omflag
!= 1)
2582 qmnumrend
= winmsg_numrend
;
2587 if (qmnumrend
< winmsg_numrend
)
2588 winmsg_numrend
= qmnumrend
;
2592 case 'd': case 'D': case 'm': case 'M': case 'y': case 'Y':
2593 case 'a': case 'A': case 's': case 'c': case 'C':
2598 time_t nowsec
= now
.tv_sec
;
2599 tm
= localtime(&nowsec
);
2602 if (!tick
|| tick
> 3600)
2607 sprintf(p
, "%02d", tm
->tm_mday
% 100);
2611 strftime(p
, l
, (longflg
? "%A" : "%a"), tm
);
2613 sprintf(p
, "%3.3s", days
+ 3 * tm
->tm_wday
);
2617 sprintf(p
, "%02d", tm
->tm_mon
+ 1);
2621 strftime(p
, l
, (longflg
? "%B" : "%b"), tm
);
2623 sprintf(p
, "%3.3s", months
+ 3 * tm
->tm_mon
);
2627 sprintf(p
, "%02d", tm
->tm_year
% 100);
2630 sprintf(p
, "%04d", tm
->tm_year
+ 1900);
2633 sprintf(p
, tm
->tm_hour
>= 12 ? "pm" : "am");
2636 sprintf(p
, tm
->tm_hour
>= 12 ? "PM" : "AM");
2639 sprintf(p
, "%02d", tm
->tm_sec
);
2643 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", tm
->tm_hour
, tm
->tm_min
);
2644 if (!tick
|| tick
> 60)
2648 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", (tm
->tm_hour
+ 11) % 12 + 1, tm
->tm_min
);
2649 if (!tick
|| tick
> 60)
2669 if (!tick
|| tick
> 60)
2678 if (rec
>= 10 || (*s
== 'h' && (win
== 0 || win
->w_hstatus
== 0 || *win
->w_hstatus
== 0)))
2685 for (bt
= backticks
; bt
; bt
= bt
->next
)
2695 char savebuf
[sizeof(winmsg_buf
)];
2697 int oldnumrend
= winmsg_numrend
;
2700 strcpy(savebuf
, winmsg_buf
);
2701 winmsg_numrend
= -winmsg_numrend
;
2702 MakeWinMsgEv(*s
== 'h' ? win
->w_hstatus
: runbacktick(bt
, &oldtick
, now
.tv_sec
), win
, '\005', 0, (struct event
*)0, rec
+ 1);
2703 debug2("oldtick=%d tick=%d\n", oldtick
, tick
);
2704 if (!tick
|| oldtick
< tick
)
2706 if ((int)strlen(winmsg_buf
) < l
)
2707 strcat(savebuf
, winmsg_buf
);
2708 strcpy(winmsg_buf
, savebuf
);
2709 while (oldnumrend
< winmsg_numrend
)
2710 winmsg_rendpos
[oldnumrend
++] += p
- winmsg_buf
;
2719 struct win
*oldfore
= 0;
2727 ss
= AddWindows(p
, l
- 1, (*s
== 'w' ? 0 : 1) | (longflg
? 0 : 2) | (plusflg
? 4 : 0) | (minusflg
? 8 : 0), win
? win
->w_number
: -1);
2738 AddOtherUsers(p
, l
- 1, win
);
2746 AddWindowFlags(p
, l
- 1, win
);
2753 if (win
&& (int)strlen(win
->w_title
) < l
)
2755 strcpy(p
, win
->w_title
);
2765 for (i
= 0; i
< 127; i
++)
2766 if (s
[i
] && s
[i
] != '}')
2770 if (s
[i
] == '}' && winmsg_numrend
< MAX_WINMSG_REND
)
2774 debug1("MakeWinMsg attrcolor %s\n", rbuf
);
2775 if (i
!= 1 || rbuf
[0] != '-')
2776 r
= ParseAttrColor(rbuf
, (char *)0, 0);
2777 if (r
!= -1 || (i
== 1 && rbuf
[0] == '-'))
2779 winmsg_rend
[winmsg_numrend
] = r
;
2780 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2790 if ((int)strlen(HostName
) < l
)
2792 strcpy(p
, HostName
);
2802 session_name
= strchr(SockName
, '.') + 1;
2803 if ((int)strlen(session_name
) < l
)
2805 strcpy(p
, session_name
);
2814 sprintf(p
, "%d", (plusflg
&& display
) ? D_userpid
: getpid());
2821 if (display
&& ((ev
&& ev
== &D_forecv
->c_captev
) || (!ev
&& win
&& win
== D_fore
)))
2822 minusflg
= !minusflg
;
2828 if (display
&& ev
&& ev
!= &D_hstatusev
) /* Hack */
2830 /* Is the layer in the current canvas in copy mode? */
2831 struct canvas
*cv
= (struct canvas
*)ev
->data
;
2832 if (ev
== &cv
->c_captev
&& cv
->c_layer
->l_layfn
== &MarkLf
)
2837 truncpos
= p
- winmsg_buf
;
2838 truncper
= num
> 100 ? 100 : num
;
2839 trunclong
= longflg
;
2845 if (num
|| zeroflg
|| plusflg
|| longflg
|| (*s
!= '='))
2847 /* expand all pads */
2850 num
= (plusflg
? lastpad
: padlen
) - num
;
2851 if (!plusflg
&& padlen
== 0)
2852 num
= p
- winmsg_buf
;
2857 if (*s
!= '=' && num
== 0 && !plusflg
)
2862 num
= p
- winmsg_buf
;
2864 num
= (padlen
- (plusflg
? lastpad
: 0)) * num
/ 100;
2870 if (num
> MAXSTR
- 1)
2873 p
= pad_expand(winmsg_buf
, p
, numpad
, num
);
2875 if (p
- winmsg_buf
> num
&& !longflg
)
2884 trunc
= lastpad
+ truncper
* (num
- lastpad
) / 100;
2887 if (trunc
< lastpad
)
2889 left
= truncpos
- trunc
;
2890 if (left
> p
- winmsg_buf
- num
)
2891 left
= p
- winmsg_buf
- num
;
2892 debug1("lastpad = %d, ", lastpad
);
2893 debug3("truncpos = %d, trunc = %d, left = %d\n", truncpos
, trunc
, left
);
2896 if (left
+ lastpad
> p
- winmsg_buf
)
2897 left
= p
- winmsg_buf
- lastpad
;
2898 if (p
- winmsg_buf
- lastpad
- left
> 0)
2899 bcopy(winmsg_buf
+ lastpad
+ left
, winmsg_buf
+ lastpad
, p
- winmsg_buf
- lastpad
- left
);
2902 while (r
&& winmsg_rendpos
[r
- 1] > lastpad
)
2905 winmsg_rendpos
[r
] -= left
;
2906 if (winmsg_rendpos
[r
] < lastpad
)
2907 winmsg_rendpos
[r
] = lastpad
;
2911 if (p
- winmsg_buf
> lastpad
)
2912 winmsg_buf
[lastpad
] = '.';
2913 if (p
- winmsg_buf
> lastpad
+ 1)
2914 winmsg_buf
[lastpad
+ 1] = '.';
2915 if (p
- winmsg_buf
> lastpad
+ 2)
2916 winmsg_buf
[lastpad
+ 2] = '.';
2919 if (p
- winmsg_buf
> num
)
2921 p
= winmsg_buf
+ num
;
2924 if (num
- 1 >= lastpad
)
2926 if (num
- 2 >= lastpad
)
2928 if (num
- 3 >= lastpad
)
2932 while (r
&& winmsg_rendpos
[r
- 1] > num
)
2933 winmsg_rendpos
[--r
] = num
;
2937 if (lastpad
> p
- winmsg_buf
)
2938 lastpad
= p
- winmsg_buf
;
2939 debug1("lastpad now %d\n", lastpad
);
2943 while (p
- winmsg_buf
< num
)
2945 lastpad
= p
- winmsg_buf
;
2948 debug1("lastpad2 now %d\n", lastpad
);
2954 *p
= 127; /* internal pad representation */
2968 sprintf(p
, "%*s", num
, num
> 1 ? "--" : "-");
2970 sprintf(p
, "%*d", num
, win
->w_number
);
2977 if (qmpos
&& !qmflag
)
2982 if (padlen
> MAXSTR
- 1)
2983 padlen
= MAXSTR
- 1;
2984 p
= pad_expand(winmsg_buf
, p
, numpad
, padlen
);
2988 evdeq(ev
); /* just in case */
2989 ev
->timeout
.tv_sec
= 0;
2990 ev
->timeout
.tv_usec
= 0;
2994 now
.tv_usec
= 100000;
2998 now
.tv_sec
+= tick
- (now
.tv_sec
% tick
);
3000 debug2("NEW timeout %d %d\n", ev
->timeout
.tv_sec
, tick
);
3006 MakeWinMsg(s
, win
, esc
)
3011 return MakeWinMsgEv(s
, win
, esc
, 0, (struct event
*)0, 0);
3015 PutWinMsg(s
, start
, max
)
3021 struct mchar rendstack
[MAX_WINMSG_REND
];
3024 if (s
!= winmsg_buf
)
3026 /* sorry, no fancy coloring available */
3027 debug1("PutWinMsg %s plain\n", s
);
3040 debug2("PutWinMsg %s start attr %x\n", s
, rend
.attr
);
3041 for (i
= 0; i
< winmsg_numrend
&& max
> 0; i
++)
3043 if (p
> winmsg_rendpos
[i
] || winmsg_rendpos
[i
] > l
)
3045 if (p
< winmsg_rendpos
[i
])
3047 n
= winmsg_rendpos
[i
] - p
;
3064 rend
= rendstack
[--rendstackn
];
3068 rendstack
[rendstackn
++] = rend
;
3069 ApplyAttrColor(r
, &rend
);
3071 SetRendition(&rend
);
3099 if ((j
= open("/dev/null", 0)) >= 0)
3106 while (dup(++i
) < 0 && errno
!= EBADF
)
3108 debug1(" [%d]\n", i
);
3121 serv_read_fn(ev
, data
)
3125 debug("Knock - knock!\n");
3130 serv_select_fn(ev
, data
)
3136 debug("serv_select_fn called\n");
3137 /* XXX: messages?? */
3142 if (InterruptPlease
)
3144 debug("Backend received interrupt\n");
3145 /* This approach is rather questionable in a multi-display
3147 if (fore
&& displays
)
3149 #if defined(TERMIO) || defined(POSIX)
3150 char ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
3152 char ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
3155 write(W_UWP(fore
) ? fore
->w_pwin
->p_ptyfd
: fore
->w_ptyfd
,
3157 debug1("Backend wrote interrupt to %d", fore
->w_number
);
3158 debug1("%s\n", W_UWP(fore
) ? " (pseudowin)" : "");
3160 write(fore
->w_ptyfd
, &ibuf
, 1);
3161 debug1("Backend wrote interrupt to %d\n", fore
->w_number
);
3164 InterruptPlease
= 0;
3167 for (p
= windows
; p
; p
= p
->w_next
)
3169 if (p
->w_bell
== BELL_FOUND
|| p
->w_bell
== BELL_VISUAL
)
3172 int visual
= p
->w_bell
== BELL_VISUAL
|| visual_bell
;
3173 p
->w_bell
= BELL_ON
;
3174 for (display
= displays
; display
; display
= display
->d_next
)
3176 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3177 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3181 p
->w_bell
= BELL_DONE
;
3182 Msg(0, "%s", MakeWinMsg(BellString
, p
, '%'));
3184 else if (visual
&& !D_VB
&& (!D_status
|| !D_status_bell
))
3186 Msg(0, "%s", VisualBellString
);
3190 debug1("using vbell timeout %d\n", VBellWait
);
3191 SetTimeout(&D_statusev
, VBellWait
);
3195 /* don't annoy the user with two messages */
3196 if (p
->w_monitor
== MON_FOUND
)
3197 p
->w_monitor
= MON_DONE
;
3198 WindowChanged(p
, 'f');
3200 if (p
->w_monitor
== MON_FOUND
)
3203 p
->w_monitor
= MON_ON
;
3204 for (display
= displays
; display
; display
= display
->d_next
)
3206 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3207 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3210 continue; /* user already sees window */
3212 if (!(ACLBYTE(p
->w_mon_notify
, D_user
->u_id
) & ACLBIT(D_user
->u_id
)))
3213 continue; /* user doesn't care */
3215 Msg(0, "%s", MakeWinMsg(ActivityString
, p
, '%'));
3216 p
->w_monitor
= MON_DONE
;
3218 WindowChanged(p
, 'f');
3222 for (display
= displays
; display
; display
= display
->d_next
)
3225 if (D_status
== STATUS_ON_WIN
)
3227 /* XXX: should use display functions! */
3228 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3232 /* normalize window, see resize.c */
3233 lx
= cv
->c_layer
->l_x
;
3234 ly
= cv
->c_layer
->l_y
;
3235 if (lx
== cv
->c_layer
->l_width
)
3237 if (ly
+ cv
->c_yoff
< cv
->c_ys
)
3239 int i
, n
= cv
->c_ys
- (ly
+ cv
->c_yoff
);
3240 cv
->c_yoff
= cv
->c_ys
- ly
;
3241 RethinkViewportOffsets(cv
);
3242 if (n
> cv
->c_layer
->l_height
)
3243 n
= cv
->c_layer
->l_height
;
3245 LScrollV(flayer
, -n
, 0, flayer
->l_height
- 1, 0);
3246 LayRedisplayLine(-1, -1, -1, 1);
3247 for (i
= 0; i
< n
; i
++)
3248 LayRedisplayLine(i
, 0, flayer
->l_width
- 1, 1);
3249 if (cv
== cv
->c_display
->d_forecv
)
3253 else if (ly
+ cv
->c_yoff
> cv
->c_ye
)
3255 int i
, n
= ly
+ cv
->c_yoff
- cv
->c_ye
;
3256 cv
->c_yoff
= cv
->c_ye
- ly
;
3257 RethinkViewportOffsets(cv
);
3258 if (n
> cv
->c_layer
->l_height
)
3259 n
= cv
->c_layer
->l_height
;
3261 LScrollV(flayer
, n
, 0, cv
->c_layer
->l_height
- 1, 0);
3262 LayRedisplayLine(-1, -1, -1, 1);
3263 for (i
= 0; i
< n
; i
++)
3264 LayRedisplayLine(i
+ flayer
->l_height
- n
, 0, flayer
->l_width
- 1, 1);
3265 if (cv
== cv
->c_display
->d_forecv
)
3269 if (lx
+ cv
->c_xoff
< cv
->c_xs
)
3271 int i
, n
= cv
->c_xs
- (lx
+ cv
->c_xoff
);
3272 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3273 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3274 if (cv
->c_xoff
+ n
> cv
->c_xs
)
3275 n
= cv
->c_xs
- cv
->c_xoff
;
3277 RethinkViewportOffsets(cv
);
3278 if (n
> cv
->c_layer
->l_width
)
3279 n
= cv
->c_layer
->l_width
;
3281 LayRedisplayLine(-1, -1, -1, 1);
3282 for (i
= 0; i
< flayer
->l_height
; i
++)
3284 LScrollH(flayer
, -n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3285 LayRedisplayLine(i
, 0, n
- 1, 1);
3287 if (cv
== cv
->c_display
->d_forecv
)
3291 else if (lx
+ cv
->c_xoff
> cv
->c_xe
)
3293 int i
, n
= lx
+ cv
->c_xoff
- cv
->c_xe
;
3294 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3295 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3296 if (cv
->c_xoff
- n
+ cv
->c_layer
->l_width
- 1 < cv
->c_xe
)
3297 n
= cv
->c_xoff
+ cv
->c_layer
->l_width
- 1 - cv
->c_xe
;
3299 RethinkViewportOffsets(cv
);
3300 if (n
> cv
->c_layer
->l_width
)
3301 n
= cv
->c_layer
->l_width
;
3303 LayRedisplayLine(-1, -1, -1, 1);
3304 for (i
= 0; i
< flayer
->l_height
; i
++)
3306 LScrollH(flayer
, n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3307 LayRedisplayLine(i
, flayer
->l_width
- n
, flayer
->l_width
- 1, 1);
3309 if (cv
== cv
->c_display
->d_forecv
)
3316 for (display
= displays
; display
; display
= display
->d_next
)
3318 if (D_status
== STATUS_ON_WIN
|| D_cvlist
== 0 || D_cvlist
->c_next
== 0)
3320 debug1("serv_select_fn: Restore on cv %#x\n", (int)D_forecv
);
3321 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
3326 logflush_fn(ev
, data
)
3334 if (!islogfile(NULL
))
3335 return; /* no more logfiles */
3337 n
= log_flush
? log_flush
: (logtstamp_after
+ 4) / 5;
3340 SetTimeout(ev
, n
* 1000);
3341 evenq(ev
); /* re-enqueue ourself */
3345 /* write fancy time-stamp */
3346 for (p
= windows
; p
; p
= p
->w_next
)
3350 p
->w_logsilence
+= n
;
3351 if (p
->w_logsilence
< logtstamp_after
)
3353 if (p
->w_logsilence
- n
>= logtstamp_after
)
3355 buf
= MakeWinMsg(logtstamp_string
, p
, '%');
3356 logfwrite(p
->w_log
, buf
, strlen(buf
));
3361 * Interprets ^?, ^@ and other ^-control-char notation.
3362 * Interprets \ddd octal notation
3364 * The result is placed in *cp, p is advanced behind the parsed expression and
3373 if (*p
== '^' && p
[1])
3383 else if (*p
== '\\' && *++p
<= '7' && *p
>= '0')
3387 *cp
= *cp
* 8 + *p
- '0';
3388 while (*++p
<= '7' && *p
>= '0');
3399 unsigned char buf
[2];
3402 SetEscape((struct acluser
*)0, -1, -1);
3405 if ((p
= ParseChar(p
, (char *)buf
)) == NULL
||
3406 (p
= ParseChar(p
, (char *)buf
+1)) == NULL
|| *p
)
3408 SetEscape((struct acluser
*)0, buf
[0], buf
[1]);