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
;
122 extern int visual_bell
;
124 extern unsigned char mark_key_tab
[];
126 extern char version
[];
127 extern char DefaultShell
[];
129 extern char *zmodem_sendcmd
;
130 extern char *zmodem_recvcmd
;
132 extern struct layout
*layout_last
;
138 extern struct NewWindow nwin_undef
, nwin_default
, nwin_options
;
141 static struct passwd
*getpwbyname
__P((char *, struct passwd
*));
142 static void SigChldHandler
__P((void));
143 static sigret_t SigChld
__P(SIGPROTOARG
);
144 static sigret_t SigInt
__P(SIGPROTOARG
);
145 static sigret_t CoreDump
__P(SIGPROTOARG
);
146 static sigret_t FinitHandler
__P(SIGPROTOARG
);
147 static void DoWait
__P((void));
148 static void serv_read_fn
__P((struct event
*, char *));
149 static void serv_select_fn
__P((struct event
*, char *));
150 static void logflush_fn
__P((struct event
*, char *));
151 static void backtick_filter
__P((struct backtick
*));
152 static void backtick_fn
__P((struct event
*, char *));
153 static char *runbacktick
__P((struct backtick
*, int *, time_t));
154 static int IsSymbol
__P((char *, char *));
155 static char *ParseChar
__P((char *, char *));
156 static int ParseEscape
__P((char *));
157 static char *pad_expand
__P((char *, char *, int, int));
159 static void fds
__P((void));
162 int nversion
; /* numerical version, used for secondary DA */
170 struct mode attach_Mode
;
172 char SockPath
[MAXPATHLEN
+ 2 * MAXSTR
];
173 char *SockName
; /* SockName is pointer in SockPath */
174 char *SockMatch
= NULL
; /* session id command line argument */
175 int ServerSocket
= -1;
176 struct event serv_read
;
177 struct event serv_select
;
178 struct event logflushev
;
180 char **NewEnv
= NULL
;
182 char *RcFileName
= NULL
;
185 char *screenlogfile
; /* filename layout */
186 int log_flush
= 10; /* flush interval in seconds */
187 int logtstamp_on
= 0; /* tstamp disabled */
188 char *logtstamp_string
; /* stamp layout */
189 int logtstamp_after
= 120; /* first tstamp after 120s */
190 char *hardcopydir
= NULL
;
192 char *VisualBellString
;
193 char *ActivityString
;
198 char *PowDetachString
;
206 int iflag
, rflag
, dflag
, lsflag
, quietflag
, wipeflag
, xflag
;
217 int tty_oldmode
= -1;
220 char HostName
[MAXSTR
];
221 int MasterPid
, PanicPid
;
222 int real_uid
, real_gid
, eff_uid
, eff_gid
;
224 int ZombieKey_destroy
, ZombieKey_resurrect
, ZombieKey_onerror
;
225 char *preselect
= NULL
; /* only used in Attach() */
228 char *screenencodings
;
241 struct layer
*flayer
;
244 struct win
*console_window
;
253 char strnomem
[] = "Out of memory.";
256 static int InterruptPlease
;
257 static int GotSigChld
;
260 lf_secreopen(name
, wantfd
, l
)
268 if (((got_fd
= secopen(name
, O_WRONLY
| O_CREAT
| O_APPEND
, 0666)) < 0) ||
269 lf_move_fd(got_fd
, wantfd
) < 0)
272 debug1("lf_secreopen: failed for %s\n", name
);
275 l
->st
->st_ino
= l
->st
->st_dev
= 0;
276 debug2("lf_secreopen: %d = %s\n", wantfd
, name
);
280 /********************************************************************/
281 /********************************************************************/
282 /********************************************************************/
285 static struct passwd
*
286 getpwbyname(name
, ppp
)
292 struct spwd
*sss
= NULL
;
293 static char *spw
= NULL
;
296 if (!ppp
&& !(ppp
= getpwnam(name
)))
299 /* Do password sanity check..., allow ##user for SUN_C2 security */
304 if (ppp
->pw_passwd
[0] == '#' && ppp
->pw_passwd
[1] == '#' &&
305 strcmp(ppp
->pw_passwd
+ 2, ppp
->pw_name
) == 0)
309 char c
= ppp
->pw_passwd
[n
];
310 if (!(c
== '.' || c
== '/' || c
== '$' ||
311 (c
>= '0' && c
<= '9') ||
312 (c
>= 'a' && c
<= 'z') ||
313 (c
>= 'A' && c
<= 'Z')))
318 /* try to determine real password */
319 if (n
< 13 && sss
== 0)
321 sss
= getspnam(ppp
->pw_name
);
326 ppp
->pw_passwd
= spw
= SaveStr(sss
->sp_pwdp
);
327 endspent(); /* this should delete all buffers ... */
330 endspent(); /* this should delete all buffers ... */
336 if (ppp
->pw_passwd
&& strlen(ppp
->pw_passwd
) == 13 + 11)
337 ppp
->pw_passwd
[13] = 0; /* beware of linux's long passwords */
350 s
= getenv("LC_ALL");
352 s
= getenv("LC_CTYPE");
367 char socknamebuf
[2 * MAXSTR
];
369 char *myname
= (ac
== 0) ? "screen" : av
[0];
372 #ifdef _MODE_T /* (jw) */
377 #if defined(SYSV) && !defined(ISC)
378 struct utsname utsnam
;
380 struct NewWindow nwin
;
381 int detached
= 0; /* start up detached */
387 char *script_file
= 0;
392 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
393 setcompat(COMPAT_POSIX
|COMPAT_BSDPROT
); /* turn on seteuid support */
395 #if defined(sun) && defined(SVR4)
397 /* Solaris' login blocks SIGHUP! This is _very bad_ */
400 sigprocmask(SIG_SETMASK
, &sset
, 0);
405 * First, close all unused descriptors
406 * (otherwise, we might have problems with the select() call)
412 snprintf(version
, 59, "%d.%.2d.%.2d%s (%s%s) %s", REV
, VERS
,
413 PATCHLEVEL
, STATE
, ORIGIN
, GIT_REV
, DATE
);
414 nversion
= REV
* 10000 + VERS
* 100 + PATCHLEVEL
;
415 debug2("-- screen debug started %s (%s)\n", *av
, version
);
429 debug("NAMEDPIPE\n");
431 #if defined(SIGWINCH) && defined(TIOCGWINSZ)
432 debug("Window size changing enabled\n");
462 debug1("NAME_MAX = %d\n", NAME_MAX
);
465 BellString
= SaveStr("Bell in window %n");
466 VisualBellString
= SaveStr(" Wuff, Wuff!! ");
467 ActivityString
= SaveStr("Activity in window %n");
468 screenlogfile
= SaveStr("screenlog.%n");
469 logtstamp_string
= SaveStr("-- %n:%t -- time-stamp -- %M/%d/%y %c:%s --\n");
470 hstatusstring
= SaveStr("%h");
471 captionstring
= SaveStr("%3n %t");
472 timestring
= SaveStr("%c:%s %M %d %H%? %l%?");
473 wlisttit
= SaveStr("Num Name%=Flags");
474 wliststr
= SaveStr("%3n %t%=%f");
476 BufferFile
= SaveStr(DEFAULT_BUFFERFILE
);
482 default_startup
= (ac
> 1) ? 0 : 1;
484 VBellWait
= VBELLWAIT
* 1000;
485 MsgWait
= MSGWAIT
* 1000;
486 MsgMinWait
= MSGMINWAIT
* 1000;
487 SilenceWait
= SILENCEWAIT
;
492 zmodem_sendcmd
= SaveStr("!!! sz -vv -b ");
493 zmodem_recvcmd
= SaveStr("!!! rz -vv -b -E");
497 CompileKeys((char *)0, 0, mark_key_tab
);
501 screenencodings
= SaveStr(SCREENENCODINGS
);
507 nwin_options
= nwin_undef
;
508 strcpy(screenterm
, "screen");
510 logreopen_register(lf_secreopen
);
513 /* if this is a login screen, assume -RR */
522 ShellProg
= SaveStr(DefaultShell
); /* to prevent nasty circles */
527 if (--ac
> 0 && *ap
== '-')
529 if (ap
[1] == '-' && ap
[2] == 0)
535 if (ap
[1] == '-' && !strcmp(ap
, "--version"))
536 Panic(0, "Screen version %s", version
);
537 if (ap
[1] == '-' && !strcmp(ap
, "--help"))
538 exit_with_usage(myname
, NULL
, NULL
);
539 while (ap
&& *ap
&& *++ap
)
544 nwin_options
.aflag
= 1;
549 case 'p': /* preselect */
555 exit_with_usage(myname
, "Specify a window to preselect with -p", NULL
);
562 bd
.bd_start_braille
= 1;
571 exit_with_usage(myname
, "Specify an alternate rc-filename with -c", NULL
);
580 exit_with_usage(myname
, "Specify command characters with -e", NULL
);
584 Panic(0, "Two characters are required with -e option, not '%s'.", ap
);
593 nwin_options
.flowflag
= FLOW_NOW
* 0;
600 nwin_options
.flowflag
= FLOW_NOW
* 1;
603 nwin_options
.flowflag
= FLOW_AUTOFLAG
;
606 exit_with_usage(myname
, "Unknown flow option -%s", --ap
);
611 exit_with_usage(myname
, NULL
, NULL
);
612 nwin_options
.histheight
= atoi(*++av
);
613 if (nwin_options
.histheight
< 0)
614 exit_with_usage(myname
, "-h: %s: negative scrollback size?", *av
);
619 case 't': /* title, the former AkA == -k */
621 exit_with_usage(myname
, "Specify a new window-name with -t", NULL
);
622 nwin_options
.aka
= *++av
;
630 nwin_options
.lflag
= 0;
637 nwin_options
.lflag
= 1;
640 nwin_options
.lflag
= 3;
643 case 'i': /* -list */
645 if (ac
> 1 && !SockMatch
)
653 exit_with_usage(myname
, "%s: Unknown suboption to -l", --ap
);
659 if (ac
> 1 && !SockMatch
)
666 nwin_options
.Lflag
= 1;
671 case 'O': /* to be (or not to be?) deleted. jw. */
676 exit_with_usage(myname
, "Specify terminal-type with -T", NULL
);
677 if (strlen(*++av
) < 20)
678 strcpy(screenterm
, *av
);
680 Panic(0, "-T: terminal name too long. (max. 20 char)");
681 nwin_options
.term
= screenterm
;
691 if (ac
> 1 && *av
[1] != '-' && !SockMatch
)
695 debug2("rflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
703 rflag
+= (*ap
== 'R') ? 2 : 1;
714 if (*av
[1] != '-' && !SockMatch
)
718 debug2("dflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
725 exit_with_usage(myname
, "Specify shell with -s", NULL
);
728 ShellProg
= SaveStr(*++av
);
729 debug1("ShellProg: '%s'\n", ShellProg
);
735 exit_with_usage(myname
, "Specify session-name with -S", NULL
);
739 exit_with_usage(myname
, "Empty session-name?", NULL
);
745 Panic(0, "Screen version %s", version
);
749 nwin_options
.encoding
= nwin_options
.encoding
== -1 ? UTF8
: 0;
754 exit_with_usage(myname
, "Specify lua script file with -u", NULL
);
757 script_file
= SaveStr(*++av
);
760 exit_with_usage(myname
, "Unknown option %s", --ap
);
772 if (eff_uid
!= real_uid
)
774 /* if running with s-bit, we must install a special signal
775 * handler routine that resets the s-bit, so that we get a
778 #ifdef SIGBUS /* OOPS, linux has no bus errors! */
779 signal(SIGBUS
, CoreDump
);
781 signal(SIGSEGV
, CoreDump
);
785 setlocale(LC_ALL
, "");
788 if (nwin_options
.encoding
== -1)
790 /* ask locale if we should start in UTF-8 mode */
791 # ifdef HAVE_NL_LANGINFO
793 setlocale(LC_CTYPE
, "");
795 nwin_options
.encoding
= FindEncoding(nl_langinfo(CODESET
));
796 debug1("locale says encoding = %d\n", nwin_options
.encoding
);
800 if ((s
= locale_name()) && InStr(s
, "UTF-8"))
801 nwin_options
.encoding
= UTF8
;
803 debug1("environment says encoding=%d\n", nwin_options
.encoding
);
809 if ((s
= locale_name()))
811 if(!strncmp(s
, "zh_", 3) || !strncmp(s
, "ja_", 3) || !strncmp(s
, "ko_", 3))
819 if (nwin_options
.aka
)
822 if (nwin_options
.encoding
> 0)
824 size_t len
= strlen(nwin_options
.aka
);
826 char *newbuf
= malloc(3 * len
);
829 newsz
= RecodeBuf(nwin_options
.aka
, len
,
830 nwin_options
.encoding
, 0, newbuf
);
831 newbuf
[newsz
] = '\0';
832 nwin_options
.aka
= newbuf
;
837 /* If we just use the original value from av,
838 subsequent shelltitle invocations will attempt to free
839 space we don't own... */
840 nwin_options
.aka
= SaveStr(nwin_options
.aka
);
844 if (SockMatch
&& strlen(SockMatch
) >= MAXSTR
)
845 Panic(0, "Ridiculously long socketname - try again.");
846 if (cmdflag
&& !rflag
&& !dflag
&& !xflag
)
848 if (!cmdflag
&& dflag
&& mflag
&& !(rflag
|| xflag
))
852 nwin
.encoding
= nwin_undef
.encoding
; /* let screenrc overwrite it */
857 /* make the write() calls return -1 on all errors */
860 * Ronald F. Guilmette, Oct 29 '94, bug-gnu-utils@prep.ai.mit.edu:
861 * It appears that in System V Release 4, UNIX, if you are writing
862 * an output file and you exceed the currently set file size limit,
863 * you _don't_ just get the call to `write' returning with a
864 * failure code. Rather, you get a signal called `SIGXFSZ' which,
865 * if neither handled nor ignored, will cause your program to crash
868 signal(SIGXFSZ
, SIG_IGN
);
872 signal(SIGPIPE
, SIG_IGN
);
879 sh
= getenv("SHELL");
880 ShellProg
= SaveStr(sh
? sh
: DefaultShell
);
882 ShellArgs
[0] = ShellProg
;
883 home
= getenv("HOME");
884 if (!mflag
&& !SockMatch
)
887 if (sty
&& *sty
== 0)
892 if (!(nethackflag
= (getenv("NETHACKOPTIONS") != NULL
)))
894 char nethackrc
[MAXPATHLEN
];
896 if (home
&& (strlen(home
) < (MAXPATHLEN
- 20)))
898 sprintf(nethackrc
,"%s/.nethackrc", home
);
899 nethackflag
= !access(nethackrc
, F_OK
);
905 own_uid
= multi_uid
= real_uid
;
906 if (SockMatch
&& (sockp
= index(SockMatch
, '/')))
910 SockMatch
= sockp
+ 1;
914 if ((mppp
= getpwnam(multi
)) == (struct passwd
*)0)
915 Panic(0, "Cannot identify account '%s'.", multi
);
916 multi_uid
= mppp
->pw_uid
;
917 multi_home
= SaveStr(mppp
->pw_dir
);
918 if (strlen(multi_home
) > MAXPATHLEN
- 10)
919 Panic(0, "home directory path too long");
921 /* always fake multi attach mode */
928 /* Special case: effective user is multiuser. */
929 if (eff_uid
&& (multi_uid
!= eff_uid
))
930 Panic(0, "Must run suid root for multiuser support.");
932 if (SockMatch
&& *SockMatch
== 0)
934 #endif /* MULTIUSER */
936 if ((LoginName
= getlogin()) && LoginName
[0] != '\0')
938 if ((ppp
= getpwnam(LoginName
)) != (struct passwd
*) 0)
939 if ((int)ppp
->pw_uid
!= real_uid
)
940 ppp
= (struct passwd
*) 0;
944 if ((ppp
= getpwuid(real_uid
)) == 0)
946 Panic(0, "getpwuid() can't identify your account!");
949 LoginName
= ppp
->pw_name
;
951 LoginName
= SaveStr(LoginName
);
953 ppp
= getpwbyname(LoginName
, ppp
);
955 #if !defined(SOCKDIR) && defined(MULTIUSER)
956 if (multi
&& !multiattach
)
958 if (home
&& strcmp(home
, ppp
->pw_dir
))
959 Panic(0, "$HOME must match passwd entry for multiuser screens.");
963 #define SET_GUID() do \
967 eff_uid = real_uid; \
968 eff_gid = real_gid; \
971 #define SET_TTYNAME(fatal) do \
973 if (!(attach_tty = ttyname(0))) \
976 Panic(0, "Must be connected to a terminal."); \
980 else if (stat(attach_tty, &st)) \
981 Panic(errno, "Cannot access '%s'", attach_tty); \
982 if (strlen(attach_tty) >= MAXPATHLEN) \
983 Panic(0, "TtyName too long - sorry."); \
986 if (home
== 0 || *home
== '\0')
988 if (strlen(LoginName
) > 20)
989 Panic(0, "LoginName too long - sorry.");
991 if (multi
&& strlen(multi
) > 20)
992 Panic(0, "Screen owner name too long - sorry.");
994 if (strlen(home
) > MAXPATHLEN
- 25)
995 Panic(0, "$HOME too long - sorry.");
998 if (!detached
&& !lsflag
&& !cmdflag
&& !(dflag
&& !mflag
&& !rflag
&& !xflag
) && !(!mflag
&& !SockMatch
&& sty
&& !xflag
))
1004 /* ttyname implies isatty */
1007 tty_mode
= (int)st
.st_mode
& 0777;
1011 fl
= fcntl(0, F_GETFL
, 0);
1012 if (fl
!= -1 && (fl
& (O_RDWR
|O_RDONLY
|O_WRONLY
)) == O_RDWR
)
1015 if (attach_fd
== -1)
1017 if ((n
= secopen(attach_tty
, O_RDWR
| O_NONBLOCK
, 0)) < 0)
1018 Panic(0, "Cannot open your terminal '%s' - please check.", attach_tty
);
1021 debug2("attach_tty is %s, attach_fd is %d\n", attach_tty
, attach_fd
);
1023 if ((attach_term
= getenv("TERM")) == 0 || *attach_term
== 0)
1024 Panic(0, "Please set a terminal type.");
1025 if (strlen(attach_term
) > sizeof(D_termname
) - 1)
1026 Panic(0, "$TERM too long - sorry.");
1027 GetTTY(0, &attach_Mode
);
1028 #ifdef DEBUGGGGGGGGGGGGGGG
1029 DebugTTY(&attach_Mode
);
1034 oumask
= umask(0); /* well, unsigned never fails? jw. */
1036 if ((oumask
= (int)umask(0)) == -1)
1037 Panic(errno
, "Cannot change umask to zero");
1039 SockDir
= getenv("SCREENDIR");
1042 if (strlen(SockDir
) >= MAXPATHLEN
- 1)
1043 Panic(0, "Ridiculously long $SCREENDIR - try again.");
1046 Panic(0, "No $SCREENDIR with multi screens, please.");
1053 sprintf(SockPath
, "%s/.screen", multi_home
);
1057 sprintf(SockPath
, "%s/S-%s", SockDir
, multi
);
1066 sprintf(SockPath
, "%s/.screen", home
);
1072 if (access(SockDir
, F_OK
))
1074 debug1("SockDir '%s' missing ...\n", SockDir
);
1075 if (UserContext() > 0)
1077 if (mkdir(SockDir
, 0700))
1081 if (UserStatus() <= 0)
1082 Panic(0, "Cannot make directory '%s'.", SockDir
);
1084 if (SockDir
!= SockPath
)
1085 strcpy(SockPath
, SockDir
);
1091 if (lstat(SockDir
, &st
))
1093 n
= (eff_uid
== 0 && (real_uid
|| eff_gid
== real_gid
)) ? 0755 :
1094 (eff_gid
!= real_gid
) ? 0775 :
1100 if (mkdir(SockDir
, n
) == -1)
1101 Panic(errno
, "Cannot make directory '%s'", SockDir
);
1105 if (!S_ISDIR(st
.st_mode
))
1106 Panic(0, "'%s' must be a directory.", SockDir
);
1107 if (eff_uid
== 0 && real_uid
&& (int)st
.st_uid
!= eff_uid
)
1108 Panic(0, "Directory '%s' must be owned by root.", SockDir
);
1109 n
= (eff_uid
== 0 && (real_uid
|| (st
.st_mode
& 0775) != 0775)) ? 0755 :
1110 (eff_gid
== (int)st
.st_gid
&& eff_gid
!= real_gid
) ? 0775 :
1112 if (((int)st
.st_mode
& 0777) != n
)
1113 Panic(0, "Directory '%s' must have mode %03o.", SockDir
, n
);
1115 sprintf(SockPath
, "%s/S-%s", SockDir
, LoginName
);
1116 if (access(SockPath
, F_OK
))
1118 if (mkdir(SockPath
, 0700) == -1)
1119 Panic(errno
, "Cannot make directory '%s'", SockPath
);
1120 (void) chown(SockPath
, real_uid
, real_gid
);
1126 if (stat(SockPath
, &st
) == -1)
1127 Panic(errno
, "Cannot access %s", SockPath
);
1129 if (!S_ISDIR(st
.st_mode
))
1130 Panic(0, "%s is not a directory.", SockPath
);
1134 if ((int)st
.st_uid
!= multi_uid
)
1135 Panic(0, "%s is not the owner of %s.", multi
, SockPath
);
1140 if ((int)st
.st_uid
!= real_uid
)
1141 Panic(0, "You are not the owner of %s.", SockPath
);
1143 if ((st
.st_mode
& 0777) != 0700)
1144 Panic(0, "Directory %s must have mode 700.", SockPath
);
1145 if (SockMatch
&& index(SockMatch
, '/'))
1146 Panic(0, "Bad session name '%s'", SockMatch
);
1147 SockName
= SockPath
+ strlen(SockPath
) + 1;
1149 (void) umask(oumask
);
1150 debug2("SockPath: %s SockMatch: %s\n", SockPath
, SockMatch
? SockMatch
: "NULL");
1152 #if defined(SYSV) && !defined(ISC)
1153 if (uname(&utsnam
) == -1)
1154 Panic(errno
, "uname");
1155 strncpy(HostName
, utsnam
.nodename
, sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1);
1156 HostName
[sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1] = '\0';
1158 (void) gethostname(HostName
, MAXSTR
);
1159 HostName
[MAXSTR
- 1] = '\0';
1161 if ((ap
= index(HostName
, '.')) != NULL
)
1170 real_uid
= multi_uid
;
1173 i
= FindSocket((int *)NULL
, &fo
, &oth
, SockMatch
);
1175 exit(8 + (fo
? ((oth
|| i
) ? 2 : 1) : 0) + i
);
1177 Panic(0, "No Sockets found in %s.\n", SockPath
);
1178 Panic(0, "%d Socket%s in %s.\n", fo
, fo
> 1 ? "s" : "", SockPath
);
1181 signal(SIG_BYE
, AttacherFinit
); /* prevent races */
1184 /* attach_tty is not mandatory */
1187 Panic(0, "Please specify a command.");
1189 SendCmdMessage(sty
, SockMatch
, av
);
1192 else if (rflag
|| xflag
)
1194 debug("screen -r: - is there anybody out there?\n");
1195 if (Attach(MSG_ATTACH
))
1202 Panic(0, "Can't create sessions of other users.");
1204 debug("screen -r: backend not responding -- still crying\n");
1206 else if (dflag
&& !mflag
)
1210 Msg(0, "[%s %sdetached.]\n", SockName
, (dflag
> 1 ? "power " : ""));
1214 if (!SockMatch
&& !mflag
&& sty
)
1216 /* attach_tty is not mandatory */
1219 nwin_options
.args
= av
;
1220 SendCreateMsg(sty
, &nwin
);
1224 nwin_compose(&nwin_default
, &nwin_options
, &nwin_default
);
1226 if (!detached
|| dflag
!= 2)
1234 Panic(errno
, "fork");
1242 sprintf(socknamebuf
, "%d.%s", MasterPid
, SockMatch
);
1244 sprintf(socknamebuf
, "%d.%s.%s", MasterPid
, stripdev(attach_tty
), HostName
);
1245 for (ap
= socknamebuf
; *ap
; ap
++)
1249 if (strlen(socknamebuf
) > NAME_MAX
)
1250 socknamebuf
[NAME_MAX
] = 0;
1252 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1259 PanicPid
= getppid();
1261 if (DefaultEsc
== -1)
1262 DefaultEsc
= Ctrl('a');
1263 if (DefaultMetaEsc
== -1)
1264 DefaultMetaEsc
= 'a';
1266 ap
= av0
+ strlen(av0
) - 1;
1269 if (!strncmp("screen", ap
, 6))
1271 strncpy(ap
, "SCREEN", 6); /* name this process "SCREEN-BACKEND" */
1283 if (dfp
&& dfp
!= stderr
)
1285 sprintf(buf
, "%s/SCREEN.%d", DEBUGDIR
, (int)getpid());
1286 if ((dfp
= fopen(buf
, "w")) == NULL
)
1289 (void) chmod(buf
, 0666);
1294 if (attach_fd
== -1)
1296 if ((n
= secopen(attach_tty
, O_RDWR
, 0)) < 0)
1297 Panic(0, "Cannot reopen '%s' - please check.", attach_tty
);
1304 freopen("/dev/null", "r", stdin
);
1305 freopen("/dev/null", "w", stdout
);
1310 freopen("/dev/null", "w", stderr
);
1311 debug("-- screen.back debug started\n");
1314 * This guarantees that the session owner is listed, even when we
1315 * start detached. From now on we should not refer to 'LoginName'
1316 * any more, use users->u_name instead.
1318 if (UserAdd(LoginName
, (char *)0, (struct acluser
**)0) < 0)
1319 Panic(0, "Could not create user info");
1322 if (MakeDisplay(LoginName
, attach_tty
, attach_term
, n
, getppid(), &attach_Mode
) == 0)
1323 Panic(0, "Could not alloc display");
1326 D_encoding
= nwin_options
.encoding
> 0 ? nwin_options
.encoding
: 0;
1327 debug1("D_encoding = %d\n", D_encoding
);
1333 /* user started us with -S option */
1334 sprintf(socknamebuf
, "%d.%s", (int)getpid(), SockMatch
);
1338 sprintf(socknamebuf
, "%d.%s.%s", (int)getpid(), stripdev(attach_tty
),
1341 for (ap
= socknamebuf
; *ap
; ap
++)
1345 if (strlen(socknamebuf
) > NAME_MAX
)
1347 debug2("Socketname %s truncated to %d chars\n", socknamebuf
, NAME_MAX
);
1348 socknamebuf
[NAME_MAX
] = 0;
1351 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1353 ServerSocket
= MakeServerSocket();
1360 ScriptSource(script_file
);
1367 # ifdef ALLOW_SYSSCREENRC
1368 if ((ap
= getenv("SYSSCREENRC")))
1369 (void)StartRc(ap
, 0);
1372 (void)StartRc(ETCSCREENRC
, 0);
1374 (void)StartRc(RcFileName
, 0);
1378 # endif /* UTNOKEEP */
1379 # endif /* UTMPOK */
1382 if (InitTermcap(0, 0))
1384 debug("Could not init termcap - exiting\n");
1385 fcntl(D_userfd
, F_SETFL
, 0); /* Flush sets FNBLOCK */
1388 Kill(D_userpid
, SIG_BYE
);
1391 MakeDefaultCanvas();
1403 signal(SIGHUP
, SigHup
);
1404 signal(SIGINT
, FinitHandler
);
1405 signal(SIGQUIT
, FinitHandler
);
1406 signal(SIGTERM
, FinitHandler
);
1408 signal(SIGTTIN
, SIG_IGN
);
1409 signal(SIGTTOU
, SIG_IGN
);
1415 SetMode(&D_OldMode
, &D_NewMode
, D_flow
, iflag
);
1416 /* Note: SetMode must be called _before_ FinishRc. */
1417 SetTTY(D_userfd
, &D_NewMode
);
1418 if (fcntl(D_userfd
, F_SETFL
, FNBLOCK
))
1419 Msg(errno
, "Warning: NBLOCK fcntl failed");
1422 brktty(-1); /* just try */
1423 signal(SIGCHLD
, SigChld
);
1425 # ifdef ALLOW_SYSSCREENRC
1426 if ((ap
= getenv("SYSSCREENRC")))
1430 FinishRc(ETCSCREENRC
);
1432 FinishRc(RcFileName
);
1434 debug2("UID %d EUID %d\n", (int)getuid(), (int)geteuid());
1435 if (windows
== NULL
)
1437 debug("We open one default window, as screenrc did not specify one.\n");
1438 if (MakeWindow(&nwin
) == -1)
1441 struct timeval tv
= { MsgWait
/1000, 1000*(MsgWait
%1000) };
1444 Msg(0, "Sorry, could not find a PTY or TTY.");
1445 // allow user to exit early by pressing any key.
1446 select(1, &rfd
, NULL
, NULL
, &tv
);
1451 else if (ac
) /* Screen was invoked with a command */
1460 if (display
&& default_startup
)
1461 display_copyright();
1462 signal(SIGINT
, SigInt
);
1463 if (rflag
&& (rflag
& 1) == 0 && !quietflag
)
1465 Msg(0, "New screen...");
1469 serv_read
.type
= EV_READ
;
1470 serv_read
.fd
= ServerSocket
;
1471 serv_read
.handler
= serv_read_fn
;
1474 serv_select
.pri
= -10;
1475 serv_select
.type
= EV_ALWAYS
;
1476 serv_select
.handler
= serv_select_fn
;
1477 evenq(&serv_select
);
1479 logflushev
.type
= EV_TIMEOUT
;
1480 logflushev
.handler
= logflush_fn
;
1488 WindowDied(p
, wstat
, wstat_valid
)
1499 if (ZombieKey_destroy
&& ZombieKey_onerror
&& wstat_valid
&&
1500 WIFEXITED(wstat
) && WEXITSTATUS(wstat
) == 0)
1503 if (ZombieKey_destroy
&& !killit
)
1505 char buf
[100], *s
, reason
[100];
1509 if (WIFEXITED(wstat
))
1510 if (WEXITSTATUS(wstat
))
1511 sprintf(reason
, "terminated with exit status %d", WEXITSTATUS(wstat
));
1513 sprintf(reason
, "terminated normally");
1514 else if (WIFSIGNALED(wstat
))
1515 sprintf(reason
, "terminated with signal %d%s", WTERMSIG(wstat
),
1517 WCOREDUMP(wstat
) ? " (core file generated)" : "");
1522 sprintf(reason
, "detached from window");
1527 s
[strlen(s
) - 1] = '\0';
1528 debug3("window %d (%s) going into zombie state fd %d",
1529 p
->w_number
, p
->w_title
, p
->w_ptyfd
);
1531 if (p
->w_slot
!= (slot_t
)0 && p
->w_slot
!= (slot_t
)-1)
1534 p
->w_slot
= 0; /* "detached" */
1539 p
->w_deadpid
= p
->w_pid
;
1542 /* p->w_y = p->w_bot; */
1543 p
->w_y
= MFindUsedLine(p
, p
->w_bot
, 1);
1544 sprintf(buf
, "\n\r=== Command %s (%s) ===", reason
, s
? s
: "?");
1545 WriteString(p
, buf
, strlen(buf
));
1546 WindowChanged(p
, 'f');
1567 signal(SIGCHLD
, SigChld
);
1570 if (stat(SockPath
, &st
) == -1)
1572 debug1("SigChldHandler: Yuck! cannot stat '%s'\n", SockPath
);
1573 if (!RecoverSocket())
1575 debug("SCREEN cannot recover from corrupt Socket, bye\n");
1579 debug1("'%s' reconstructed\n", SockPath
);
1582 debug2("SigChldHandler: stat '%s' o.k. (%03o)\n", SockPath
, (int)st
.st_mode
);
1588 debug("SigChld()\n");
1596 /* Hangup all displays */
1597 while ((display
= displays
) != 0)
1603 * the backend's Interrupt handler
1604 * we cannot insert the intrc directly, as we never know
1613 debug("SigInt()\n");
1614 if (fore
&& displays
)
1616 # if defined(TERMIO) || defined(POSIX)
1617 ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
1619 ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
1622 write(fore
->w_ptyfd
, &ibuf
, 1);
1625 signal(SIGINT
, SigInt
);
1626 debug("SigInt() careful\n");
1627 InterruptPlease
= 1;
1635 struct display
*disp
;
1638 #if defined(SYSVSIGS) && defined(SIGHASARG)
1639 signal(sigsig
, SIG_IGN
);
1645 sprintf(buf
, "\r\n[screen caught signal %d.%s]\r\n", sigsig
,
1647 sprintf(buf
, "\r\n[screen caught a fatal signal.%s]\r\n",
1649 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1651 #else /* SHADOWPW && !DEBUG */
1653 #endif /* SHADOWPW && !DEBUG */
1655 for (disp
= displays
; disp
; disp
= disp
->d_next
)
1657 fcntl(disp
->d_userfd
, F_SETFL
, 0);
1658 SetTTY(disp
->d_userfd
, &D_OldMode
);
1659 write(disp
->d_userfd
, buf
, strlen(buf
));
1660 Kill(disp
->d_userpid
, SIG_BYE
);
1662 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1663 Kill(getpid(), SIGKILL
);
1665 #else /* SHADOWPW && !DEBUG */
1667 #endif /* SHADOWPW && !DEBUG */
1675 struct win
*p
, *next
;
1684 while ((pid
= waitpid(-1, &wstat
, WNOHANG
| WUNTRACED
)) > 0)
1688 * From: rouilj@sni-usa.com (John Rouillard)
1689 * note that WUNTRACED is not documented to work, but it is defined in
1690 * /usr/include/sys/wait.h, so it may work
1692 while ((pid
= wait2(&wstat
, WNOHANG
| WUNTRACED
)) > 0)
1693 # else /* USE_WAIT2 */
1694 while ((pid
= wait3(&wstat
, WNOHANG
| WUNTRACED
, (struct rusage
*) 0)) > 0)
1695 # endif /* USE_WAIT2 */
1698 while ((pid
= wait(&wstat
)) < 0)
1702 #endif /* BSDJOBS */
1704 for (p
= windows
; p
; p
= next
)
1707 if ( (p
->w_pid
&& pid
== p
->w_pid
) ||
1708 (p
->w_deadpid
&& pid
== p
->w_deadpid
) )
1710 /* child has ceased to exist */
1714 if (WIFSTOPPED(wstat
))
1716 debug3("Window %d pid %d: WIFSTOPPED (sig %d)\n", p
->w_number
, pid
, WSTOPSIG(wstat
));
1718 if (WSTOPSIG(wstat
) == SIGTTIN
)
1720 Msg(0, "Suspended (tty input)");
1725 if (WSTOPSIG(wstat
) == SIGTTOU
)
1727 Msg(0, "Suspended (tty output)");
1731 /* Try to restart process */
1732 Msg(0, "Child has been stopped, restarting.");
1733 if (killpg(pid
, SIGCONT
))
1739 WindowDied(p
, wstat
, 1);
1744 if (p
->w_pwin
&& pid
== p
->w_pwin
->p_pid
)
1746 debug2("pseudo of win Nr %d died. pid == %d\n", p
->w_number
, p
->w_pwin
->p_pid
);
1754 debug1("pid %d not found - hope that's ok\n", pid
);
1761 FinitHandler SIGDEFARG
1764 debug1("FinitHandler called, sig %d.\n", sigsig
);
1766 debug("FinitHandler called.\n");
1776 signal(SIGCHLD
, SIG_DFL
);
1777 signal(SIGHUP
, SIG_IGN
);
1778 debug1("Finit(%d);\n", i
);
1786 struct win
*p
= windows
;
1787 windows
= windows
->w_next
;
1790 if (ServerSocket
!= -1)
1792 debug1("we unlink(%s)\n", SockPath
);
1797 (void) unlink(SockPath
);
1803 for (display
= displays
; display
; display
= display
->d_next
)
1811 AddStr("[screen is terminating]\r\n");
1813 SetTTY(D_userfd
, &D_OldMode
);
1814 fcntl(D_userfd
, F_SETFL
, 0);
1816 Kill(D_userpid
, SIG_BYE
);
1819 * we _cannot_ call eexit(i) here,
1820 * instead of playing with the Socket above. Sigh.
1830 if (ServerSocket
!= -1)
1832 debug1("we unlink(%s)\n", SockPath
);
1835 (void) unlink(SockPath
);
1845 debug1("Hangup %x\n", display
);
1851 if (auto_detach
|| displays
->d_next
)
1858 * Detach now has the following modes:
1859 *D_DETACH SIG_BYE detach backend and exit attacher
1860 *D_HANGUP SIG_BYE detach backend and exit attacher
1861 *D_STOP SIG_STOP stop attacher (and detach backend)
1862 *D_REMOTE SIG_BYE remote detach -- reattach to new attacher
1863 *D_POWER SIG_POWER_BYE power detach -- attacher kills his parent
1864 *D_REMOTE_POWER SIG_POWER_BYE remote power detach -- both
1865 *D_LOCK SIG_LOCK lock the attacher
1867 * we always remove our utmp slots. (even when "lock" or "stop")
1868 * Note: Take extra care here, we may be called by interrupt!
1881 #define AddStrSock(msg) do { \
1884 AddStr("[" msg " from "); \
1889 AddStr("[" msg "]\r\n"); \
1892 signal(SIGHUP
, SIG_IGN
);
1893 debug1("Detach(%d)\n", mode
);
1905 AddStrSock("detached");
1908 trigger_sevent(&globalevents
.detached
, display
, 0x0);
1916 #ifdef REMOTE_DETACH
1918 AddStrSock("remote detached");
1921 trigger_sevent(&globalevents
.detached
, display
, 0x1);
1927 AddStrSock("power detached");
1928 if (PowDetachString
)
1930 AddStr(PowDetachString
);
1933 sign
= SIG_POWER_BYE
;
1935 trigger_sevent(&globalevents
.detached
, display
, 0x2);
1938 #ifdef REMOTE_DETACH
1939 case D_REMOTE_POWER
:
1940 AddStrSock("remote power detached");
1941 if (PowDetachString
)
1943 AddStr(PowDetachString
);
1946 sign
= SIG_POWER_BYE
;
1948 trigger_sevent(&globalevents
.detached
, display
, 0x1 | 0x2); /* Remote and power */
1956 /* tell attacher to lock terminal with a lockprg. */
1960 if (displays
->d_next
== 0)
1962 for (p
= windows
; p
; p
= p
->w_next
)
1964 if (p
->w_slot
!= (slot_t
) -1 && !(p
->w_lflag
& 2))
1968 * Set the slot to 0 to get the window
1971 p
->w_slot
= (slot_t
) 0;
1975 if (mode
!= D_HANGUP
)
1978 if (displays
->d_next
== 0 && console_window
)
1980 if (TtyGrabConsole(console_window
->w_ptyfd
, 0, "detach"))
1982 debug("could not release console - killing window\n");
1983 KillWindow(console_window
);
1984 display
= displays
; /* restore display */
1990 ReleaseAutoWritelock(display
, D_fore
);
1992 D_user
->u_detachwin
= D_fore
->w_number
;
1993 D_user
->u_detachotherwin
= D_other
? D_other
->w_number
: -1;
1995 AutosaveLayout(D_layout
);
1996 layout_last
= D_layout
;
1997 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
1999 p
= Layer2Window(cv
->c_layer
);
2000 SetCanvasWindow(cv
, 0);
2002 WindowChanged(p
, 'u');
2006 debug2("display: %#x displays: %#x\n", (unsigned int)display
, (unsigned int)displays
);
2009 /* Flag detached-ness */
2012 * tell father what to do. We do that after we
2013 * freed the tty, thus getty feels more comfortable on hpux
2014 * if it was a power detach.
2017 debug2("Detach: Signal %d to Attacher(%d)!\n", sign
, pid
);
2018 debug("Detach returns, we are successfully detached.\n");
2019 signal(SIGHUP
, SigHup
);
2030 return strncmp(e
, s
, l
) == 0 && e
[l
] == '=';
2036 register char **op
, **np
;
2037 static char stybuf
[MAXSTR
];
2039 for (op
= environ
; *op
; ++op
)
2042 free((char *)NewEnv
);
2043 NewEnv
= np
= (char **) malloc((unsigned) (op
- environ
+ 7 + 1) * sizeof(char **));
2046 sprintf(stybuf
, "STY=%s", strlen(SockName
) <= MAXSTR
- 5 ? SockName
: "?");
2047 *np
++ = stybuf
; /* NewEnv[0] */
2048 *np
++ = Term
; /* NewEnv[1] */
2049 np
++; /* room for SHELL */
2051 np
+= 2; /* room for TERMCAP and WINDOW */
2053 np
+= 4; /* room for TERMCAP WINDOW LINES COLUMNS */
2056 for (op
= environ
; *op
; ++op
)
2058 if (!IsSymbol(*op
, "TERM") && !IsSymbol(*op
, "TERMCAP")
2059 && !IsSymbol(*op
, "STY") && !IsSymbol(*op
, "WINDOW")
2060 && !IsSymbol(*op
, "SCREENCAP") && !IsSymbol(*op
, "SHELL")
2061 && !IsSymbol(*op
, "LINES") && !IsSymbol(*op
, "COLUMNS")
2070 #if defined(USEVARARGS) && defined(__STDC__)
2071 Msg(int err
, char *fmt
, VA_DOTS
)
2073 Msg(err
, fmt
, VA_DOTS
)
2080 char buf
[MAXPATHLEN
*2];
2085 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2092 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2093 buf
[sizeof(buf
) - 1] = 0;
2095 debug2("Msg('%s') (%#x);\n", buf
, (unsigned int)display
);
2097 if (display
&& displays
)
2101 for (display
= displays
; display
; display
= display
->d_next
)
2106 /* no displays but a display - must have forked.
2107 * send message to backend!
2109 char *tty
= D_usertty
;
2110 struct display
*olddisplay
= display
;
2111 display
= 0; /* only send once */
2112 SendErrorMsg(tty
, buf
);
2113 display
= olddisplay
;
2116 printf("%s\r\n", buf
);
2120 * Call FinitTerm for all displays, write a message to each and call eexit();
2124 #if defined(USEVARARGS) && defined(__STDC__)
2125 Panic(int err
, char *fmt
, VA_DOTS
)
2127 Panic(err
, fmt
, VA_DOTS
)
2134 char buf
[MAXPATHLEN
*2];
2139 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2146 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2147 buf
[sizeof(buf
) - 1] = 0;
2149 debug3("Panic('%s'); display=%x displays=%x\n", buf
, display
, displays
);
2150 if (displays
== 0 && display
== 0)
2152 printf("%s\r\n", buf
);
2154 Kill(PanicPid
, SIG_BYE
);
2156 else if (displays
== 0)
2158 /* no displays but a display - must have forked.
2159 * send message to backend!
2161 char *tty
= D_usertty
;
2163 SendErrorMsg(tty
, buf
);
2168 for (display
= displays
; display
; display
= display
->d_next
)
2177 SetTTY(D_userfd
, &D_OldMode
);
2178 fcntl(D_userfd
, F_SETFL
, 0);
2179 write(D_userfd
, buf
, strlen(buf
));
2180 write(D_userfd
, "\n", 1);
2183 Kill(D_userpid
, SIG_BYE
);
2186 if (tty_oldmode
>= 0)
2189 if (setuid(own_uid
))
2190 xseteuid(own_uid
); /* may be a loop. sigh. */
2194 debug1("Panic: changing back modes from %s\n", attach_tty
);
2195 chmod(attach_tty
, tty_oldmode
);
2203 * '^' is allowed as an escape mechanism for control characters. jw.
2205 * Added time insertion using ideas/code from /\ndy Jones
2206 * (andy@lingua.cltr.uq.OZ.AU) - thanks a lot!
2211 static const char days
[] = "SunMonTueWedThuFriSat";
2212 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2215 static char winmsg_buf
[MAXSTR
];
2216 #define MAX_WINMSG_REND 16 /* rendition changes */
2217 static int winmsg_rend
[MAX_WINMSG_REND
];
2218 static int winmsg_rendpos
[MAX_WINMSG_REND
];
2219 static int winmsg_numrend
;
2222 pad_expand(buf
, p
, numpad
, padlen
)
2231 padlen
= padlen
- (p
- buf
); /* space for rent */
2234 pn2
= pn
= p
+ padlen
;
2238 if (r
&& *p
!= 127 && p
- buf
== winmsg_rendpos
[r
- 1])
2240 winmsg_rendpos
[--r
] = pn
- buf
;
2247 i
= numpad
> 0 ? (padlen
+ numpad
- 1) / numpad
: 0;
2252 if (r
&& p
- buf
== winmsg_rendpos
[r
- 1])
2253 winmsg_rendpos
[--r
] = pn
- buf
;
2260 struct backtick
*next
;
2265 char result
[MAXSTR
];
2272 struct backtick
*backticks
;
2276 struct backtick
*bt
;
2281 for (p
= q
= bt
->result
; (c
= (unsigned char)*p
++) != 0;)
2285 if (c
>= ' ' || c
== '\005')
2292 backtick_fn(ev
, data
)
2296 struct backtick
*bt
;
2299 bt
= (struct backtick
*)data
;
2300 debug1("backtick_fn for #%d\n", bt
->num
);
2302 l
= read(ev
->fd
, bt
->buf
+ i
, MAXSTR
- i
);
2305 debug1("EOF on backtick #%d\n", bt
->num
);
2311 debug1("read %d bytes\n", l
);
2313 for (j
= 0; j
< l
; j
++)
2314 if (bt
->buf
[i
- j
- 1] == '\n')
2318 for (k
= i
- j
- 2; k
>= 0; k
--)
2319 if (bt
->buf
[k
] == '\n')
2322 bcopy(bt
->buf
+ k
, bt
->result
, i
- j
- k
);
2323 bt
->result
[i
- j
- k
- 1] = 0;
2324 backtick_filter(bt
);
2325 WindowChanged(0, '`');
2327 if (j
== l
&& i
== MAXSTR
)
2335 bcopy(bt
->buf
+ i
- j
, bt
->buf
, j
);
2342 setbacktick(num
, lifespan
, tick
, cmdv
)
2348 struct backtick
**btp
, *bt
;
2351 debug1("setbacktick called for backtick #%d\n", num
);
2352 for (btp
= &backticks
; (bt
= *btp
) != 0; btp
= &bt
->next
)
2359 for (v
= bt
->cmdv
; *v
; v
++)
2376 bt
= (struct backtick
*)malloc(sizeof *bt
);
2382 bzero(bt
, sizeof(*bt
));
2388 bt
->lifespan
= lifespan
;
2395 if (bt
->tick
== 0 && bt
->lifespan
== 0)
2397 debug("setbacktick: continuous mode\n");
2398 bt
->buf
= (char *)malloc(MAXSTR
);
2402 setbacktick(num
, 0, 0, (char **)0);
2405 bt
->ev
.type
= EV_READ
;
2406 bt
->ev
.fd
= readpipe(bt
->cmdv
);
2407 bt
->ev
.handler
= backtick_fn
;
2408 bt
->ev
.data
= (char *)bt
;
2415 runbacktick(bt
, tickp
, now
)
2416 struct backtick
*bt
;
2423 debug1("runbacktick called for backtick #%d\n", bt
->num
);
2424 if (bt
->tick
&& (!*tickp
|| bt
->tick
< *tickp
))
2426 if ((bt
->lifespan
== 0 && bt
->tick
== 0) || now
< bt
->bestbefore
)
2428 debug1("returning old result (%d)\n", bt
->lifespan
);
2431 f
= readpipe(bt
->cmdv
);
2435 while ((l
= read(f
, bt
->result
+ i
, sizeof(bt
->result
) - i
)) > 0)
2437 debug1("runbacktick: read %d bytes\n", l
);
2439 for (j
= 1; j
< l
; j
++)
2440 if (bt
->result
[i
- j
- 1] == '\n')
2442 if (j
== l
&& i
== sizeof(bt
->result
))
2444 j
= sizeof(bt
->result
) / 2;
2449 bcopy(bt
->result
+ i
- j
, bt
->result
, j
);
2454 bt
->result
[sizeof(bt
->result
) - 1] = '\n';
2455 if (i
&& bt
->result
[i
- 1] == '\n')
2457 debug1("runbacktick: finished, %d bytes\n", i
);
2459 backtick_filter(bt
);
2461 bt
->bestbefore
= now2
+ bt
->lifespan
;
2466 AppendWinMsgRend(str
, color
)
2471 if (winmsg_numrend
>= MAX_WINMSG_REND
)
2473 p
= winmsg_buf
+ strlen(winmsg_buf
);
2478 r
= ParseAttrColor(color
, 0, 0);
2482 winmsg_rend
[winmsg_numrend
] = r
;
2483 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2486 strncpy(p
, str
, winmsg_buf
+ sizeof(winmsg_buf
) - p
);
2490 AddWinMsgRend(str
, r
)
2494 if (winmsg_numrend
>= MAX_WINMSG_REND
|| str
< winmsg_buf
||
2495 str
>= winmsg_buf
+ MAXSTR
)
2498 winmsg_rend
[winmsg_numrend
] = r
;
2499 winmsg_rendpos
[winmsg_numrend
] = str
- winmsg_buf
;
2506 MakeWinMsgEv(str
, win
, esc
, padlen
, ev
, rec
)
2516 register char *p
= winmsg_buf
;
2526 int qmflag
= 0, omflag
= 0, qmnumrend
= 0;
2533 struct backtick
*bt
;
2535 if (winmsg_numrend
>= 0)
2538 winmsg_numrend
= -winmsg_numrend
;
2547 gettimeofday(&now
, NULL
);
2548 for (s
= str
; *s
&& (l
= winmsg_buf
+ MAXSTR
- 1 - p
) > 0; s
++, p
++)
2554 if (*s
!= '^' && *s
>= 64)
2579 if (*++s
== esc
) /* double escape ? */
2581 if ((plusflg
= *s
== '+') != 0)
2583 if ((minusflg
= *s
== '-') != 0)
2585 if ((zeroflg
= *s
== '0') != 0)
2588 while(*s
>= '0' && *s
<= '9')
2589 num
= num
* 10 + (*s
++ - '0');
2590 if ((longflg
= *s
== 'L') != 0)
2598 if ((!qmflag
&& !omflag
) || omflag
== 1)
2601 if (qmnumrend
< winmsg_numrend
)
2602 winmsg_numrend
= qmnumrend
;
2608 qmnumrend
= winmsg_numrend
;
2609 qmflag
= omflag
= 0;
2615 if (qmflag
&& omflag
!= 1)
2619 qmnumrend
= winmsg_numrend
;
2624 if (qmnumrend
< winmsg_numrend
)
2625 winmsg_numrend
= qmnumrend
;
2629 case 'd': case 'D': case 'm': case 'M': case 'y': case 'Y':
2630 case 'a': case 'A': case 's': case 'c': case 'C':
2635 time_t nowsec
= now
.tv_sec
;
2636 tm
= localtime(&nowsec
);
2639 if (!tick
|| tick
> 3600)
2644 sprintf(p
, "%02d", tm
->tm_mday
% 100);
2648 strftime(p
, l
, (longflg
? "%A" : "%a"), tm
);
2650 sprintf(p
, "%3.3s", days
+ 3 * tm
->tm_wday
);
2654 sprintf(p
, "%02d", tm
->tm_mon
+ 1);
2658 strftime(p
, l
, (longflg
? "%B" : "%b"), tm
);
2660 sprintf(p
, "%3.3s", months
+ 3 * tm
->tm_mon
);
2664 sprintf(p
, "%02d", tm
->tm_year
% 100);
2667 sprintf(p
, "%04d", tm
->tm_year
+ 1900);
2670 sprintf(p
, tm
->tm_hour
>= 12 ? "pm" : "am");
2673 sprintf(p
, tm
->tm_hour
>= 12 ? "PM" : "AM");
2676 sprintf(p
, "%02d", tm
->tm_sec
);
2680 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", tm
->tm_hour
, tm
->tm_min
);
2681 if (!tick
|| tick
> 60)
2685 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", (tm
->tm_hour
+ 11) % 12 + 1, tm
->tm_min
);
2686 if (!tick
|| tick
> 60)
2706 if (!tick
|| tick
> 60)
2715 if (rec
>= 10 || (*s
== 'h' && (win
== 0 || win
->w_hstatus
== 0 || *win
->w_hstatus
== 0)))
2722 for (bt
= backticks
; bt
; bt
= bt
->next
)
2732 char savebuf
[sizeof(winmsg_buf
)];
2734 int oldnumrend
= winmsg_numrend
;
2737 strcpy(savebuf
, winmsg_buf
);
2738 winmsg_numrend
= -winmsg_numrend
;
2739 MakeWinMsgEv(*s
== 'h' ? win
->w_hstatus
: runbacktick(bt
, &oldtick
, now
.tv_sec
), win
, '\005', 0, (struct event
*)0, rec
+ 1);
2740 debug2("oldtick=%d tick=%d\n", oldtick
, tick
);
2741 if (!tick
|| oldtick
< tick
)
2743 if ((int)strlen(winmsg_buf
) < l
)
2744 strcat(savebuf
, winmsg_buf
);
2745 strcpy(winmsg_buf
, savebuf
);
2746 while (oldnumrend
< winmsg_numrend
)
2747 winmsg_rendpos
[oldnumrend
++] += p
- winmsg_buf
;
2756 struct win
*oldfore
= 0;
2764 ss
= AddWindows(p
, l
- 1, (*s
== 'w' ? 0 : 1) | (longflg
? 0 : 2) | (plusflg
? 4 : 0) | (minusflg
? 8 : 0), win
? win
->w_number
: -1);
2775 AddOtherUsers(p
, l
- 1, win
);
2783 AddWindowFlags(p
, l
- 1, win
);
2790 if (win
&& (int)strlen(win
->w_title
) < l
)
2792 strcpy(p
, win
->w_title
);
2802 for (i
= 0; i
< 127; i
++)
2803 if (s
[i
] && s
[i
] != '}')
2807 if (s
[i
] == '}' && winmsg_numrend
< MAX_WINMSG_REND
)
2811 debug1("MakeWinMsg attrcolor %s\n", rbuf
);
2812 if (i
!= 1 || rbuf
[0] != '-')
2813 r
= ParseAttrColor(rbuf
, (char *)0, 0);
2814 if (r
!= -1 || (i
== 1 && rbuf
[0] == '-'))
2816 winmsg_rend
[winmsg_numrend
] = r
;
2817 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2827 if ((int)strlen(HostName
) < l
)
2829 strcpy(p
, HostName
);
2839 session_name
= strchr(SockName
, '.') + 1;
2840 if ((int)strlen(session_name
) < l
)
2842 strcpy(p
, session_name
);
2851 sprintf(p
, "%d", (plusflg
&& display
) ? D_userpid
: getpid());
2858 if (display
&& ((ev
&& ev
== &D_forecv
->c_captev
) || (!ev
&& win
&& win
== D_fore
)))
2859 minusflg
= !minusflg
;
2864 truncpos
= p
- winmsg_buf
;
2865 truncper
= num
> 100 ? 100 : num
;
2866 trunclong
= longflg
;
2872 if (num
|| zeroflg
|| plusflg
|| longflg
|| (*s
!= '='))
2874 /* expand all pads */
2877 num
= (plusflg
? lastpad
: padlen
) - num
;
2878 if (!plusflg
&& padlen
== 0)
2879 num
= p
- winmsg_buf
;
2884 if (*s
!= '=' && num
== 0 && !plusflg
)
2889 num
= p
- winmsg_buf
;
2891 num
= (padlen
- (plusflg
? lastpad
: 0)) * num
/ 100;
2897 if (num
> MAXSTR
- 1)
2900 p
= pad_expand(winmsg_buf
, p
, numpad
, num
);
2902 if (p
- winmsg_buf
> num
&& !longflg
)
2911 trunc
= lastpad
+ truncper
* (num
- lastpad
) / 100;
2914 if (trunc
< lastpad
)
2916 left
= truncpos
- trunc
;
2917 if (left
> p
- winmsg_buf
- num
)
2918 left
= p
- winmsg_buf
- num
;
2919 debug1("lastpad = %d, ", lastpad
);
2920 debug3("truncpos = %d, trunc = %d, left = %d\n", truncpos
, trunc
, left
);
2923 if (left
+ lastpad
> p
- winmsg_buf
)
2924 left
= p
- winmsg_buf
- lastpad
;
2925 if (p
- winmsg_buf
- lastpad
- left
> 0)
2926 bcopy(winmsg_buf
+ lastpad
+ left
, winmsg_buf
+ lastpad
, p
- winmsg_buf
- lastpad
- left
);
2929 while (r
&& winmsg_rendpos
[r
- 1] > lastpad
)
2932 winmsg_rendpos
[r
] -= left
;
2933 if (winmsg_rendpos
[r
] < lastpad
)
2934 winmsg_rendpos
[r
] = lastpad
;
2938 if (p
- winmsg_buf
> lastpad
)
2939 winmsg_buf
[lastpad
] = '.';
2940 if (p
- winmsg_buf
> lastpad
+ 1)
2941 winmsg_buf
[lastpad
+ 1] = '.';
2942 if (p
- winmsg_buf
> lastpad
+ 2)
2943 winmsg_buf
[lastpad
+ 2] = '.';
2946 if (p
- winmsg_buf
> num
)
2948 p
= winmsg_buf
+ num
;
2951 if (num
- 1 >= lastpad
)
2953 if (num
- 2 >= lastpad
)
2955 if (num
- 3 >= lastpad
)
2959 while (r
&& winmsg_rendpos
[r
- 1] > num
)
2960 winmsg_rendpos
[--r
] = num
;
2964 if (lastpad
> p
- winmsg_buf
)
2965 lastpad
= p
- winmsg_buf
;
2966 debug1("lastpad now %d\n", lastpad
);
2970 while (p
- winmsg_buf
< num
)
2972 lastpad
= p
- winmsg_buf
;
2975 debug1("lastpad2 now %d\n", lastpad
);
2981 *p
= 127; /* internal pad representation */
2995 sprintf(p
, "%*s", num
, num
> 1 ? "--" : "-");
2997 sprintf(p
, "%*d", num
, win
->w_number
);
3004 if (qmpos
&& !qmflag
)
3009 if (padlen
> MAXSTR
- 1)
3010 padlen
= MAXSTR
- 1;
3011 p
= pad_expand(winmsg_buf
, p
, numpad
, padlen
);
3015 evdeq(ev
); /* just in case */
3016 ev
->timeout
.tv_sec
= 0;
3017 ev
->timeout
.tv_usec
= 0;
3021 now
.tv_usec
= 100000;
3025 now
.tv_sec
+= tick
- (now
.tv_sec
% tick
);
3027 debug2("NEW timeout %d %d\n", ev
->timeout
.tv_sec
, tick
);
3033 MakeWinMsg(s
, win
, esc
)
3038 return MakeWinMsgEv(s
, win
, esc
, 0, (struct event
*)0, 0);
3042 PutWinMsg(s
, start
, max
)
3048 struct mchar rendstack
[MAX_WINMSG_REND
];
3051 if (s
!= winmsg_buf
)
3053 /* sorry, no fancy coloring available */
3054 debug1("PutWinMsg %s plain\n", s
);
3067 debug2("PutWinMsg %s start attr %x\n", s
, rend
.attr
);
3068 for (i
= 0; i
< winmsg_numrend
&& max
> 0; i
++)
3070 if (p
> winmsg_rendpos
[i
] || winmsg_rendpos
[i
] > l
)
3072 if (p
< winmsg_rendpos
[i
])
3074 n
= winmsg_rendpos
[i
] - p
;
3091 rend
= rendstack
[--rendstackn
];
3095 rendstack
[rendstackn
++] = rend
;
3096 ApplyAttrColor(r
, &rend
);
3098 SetRendition(&rend
);
3126 if ((j
= open("/dev/null", 0)) >= 0)
3133 while (dup(++i
) < 0 && errno
!= EBADF
)
3135 debug1(" [%d]\n", i
);
3148 serv_read_fn(ev
, data
)
3152 debug("Knock - knock!\n");
3157 serv_select_fn(ev
, data
)
3163 debug("serv_select_fn called\n");
3164 /* XXX: messages?? */
3169 if (InterruptPlease
)
3171 debug("Backend received interrupt\n");
3172 /* This approach is rather questionable in a multi-display
3174 if (fore
&& displays
)
3176 #if defined(TERMIO) || defined(POSIX)
3177 char ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
3179 char ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
3182 write(W_UWP(fore
) ? fore
->w_pwin
->p_ptyfd
: fore
->w_ptyfd
,
3184 debug1("Backend wrote interrupt to %d", fore
->w_number
);
3185 debug1("%s\n", W_UWP(fore
) ? " (pseudowin)" : "");
3187 write(fore
->w_ptyfd
, &ibuf
, 1);
3188 debug1("Backend wrote interrupt to %d\n", fore
->w_number
);
3191 InterruptPlease
= 0;
3194 for (p
= windows
; p
; p
= p
->w_next
)
3196 if (p
->w_bell
== BELL_FOUND
|| p
->w_bell
== BELL_VISUAL
)
3199 int visual
= p
->w_bell
== BELL_VISUAL
|| visual_bell
;
3200 p
->w_bell
= BELL_ON
;
3201 for (display
= displays
; display
; display
= display
->d_next
)
3203 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3204 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3208 p
->w_bell
= BELL_DONE
;
3209 Msg(0, "%s", MakeWinMsg(BellString
, p
, '%'));
3211 else if (visual
&& !D_VB
&& (!D_status
|| !D_status_bell
))
3213 Msg(0, "%s", VisualBellString
);
3217 debug1("using vbell timeout %d\n", VBellWait
);
3218 SetTimeout(&D_statusev
, VBellWait
);
3222 /* don't annoy the user with two messages */
3223 if (p
->w_monitor
== MON_FOUND
)
3224 p
->w_monitor
= MON_DONE
;
3225 WindowChanged(p
, 'f');
3227 if (p
->w_monitor
== MON_FOUND
)
3230 p
->w_monitor
= MON_ON
;
3231 for (display
= displays
; display
; display
= display
->d_next
)
3233 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3234 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3237 continue; /* user already sees window */
3239 if (!(ACLBYTE(p
->w_mon_notify
, D_user
->u_id
) & ACLBIT(D_user
->u_id
)))
3240 continue; /* user doesn't care */
3243 if (!trigger_sevent(&p
->w_sev
.onactivity
, display
, p
))
3245 Msg(0, "%s", MakeWinMsg(ActivityString
, p
, '%'));
3246 p
->w_monitor
= MON_DONE
;
3248 WindowChanged(p
, 'f');
3252 for (display
= displays
; display
; display
= display
->d_next
)
3255 if (D_status
== STATUS_ON_WIN
)
3257 /* XXX: should use display functions! */
3258 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3262 /* normalize window, see resize.c */
3263 lx
= cv
->c_layer
->l_x
;
3264 ly
= cv
->c_layer
->l_y
;
3265 if (lx
== cv
->c_layer
->l_width
)
3267 if (ly
+ cv
->c_yoff
< cv
->c_ys
)
3269 int i
, n
= cv
->c_ys
- (ly
+ cv
->c_yoff
);
3270 cv
->c_yoff
= cv
->c_ys
- ly
;
3271 RethinkViewportOffsets(cv
);
3272 if (n
> cv
->c_layer
->l_height
)
3273 n
= cv
->c_layer
->l_height
;
3275 LScrollV(flayer
, -n
, 0, flayer
->l_height
- 1, 0);
3276 LayRedisplayLine(-1, -1, -1, 1);
3277 for (i
= 0; i
< n
; i
++)
3278 LayRedisplayLine(i
, 0, flayer
->l_width
- 1, 1);
3279 if (cv
== cv
->c_display
->d_forecv
)
3283 else if (ly
+ cv
->c_yoff
> cv
->c_ye
)
3285 int i
, n
= ly
+ cv
->c_yoff
- cv
->c_ye
;
3286 cv
->c_yoff
= cv
->c_ye
- ly
;
3287 RethinkViewportOffsets(cv
);
3288 if (n
> cv
->c_layer
->l_height
)
3289 n
= cv
->c_layer
->l_height
;
3291 LScrollV(flayer
, n
, 0, cv
->c_layer
->l_height
- 1, 0);
3292 LayRedisplayLine(-1, -1, -1, 1);
3293 for (i
= 0; i
< n
; i
++)
3294 LayRedisplayLine(i
+ flayer
->l_height
- n
, 0, flayer
->l_width
- 1, 1);
3295 if (cv
== cv
->c_display
->d_forecv
)
3299 if (lx
+ cv
->c_xoff
< cv
->c_xs
)
3301 int i
, n
= cv
->c_xs
- (lx
+ cv
->c_xoff
);
3302 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3303 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3304 if (cv
->c_xoff
+ n
> cv
->c_xs
)
3305 n
= cv
->c_xs
- cv
->c_xoff
;
3307 RethinkViewportOffsets(cv
);
3308 if (n
> cv
->c_layer
->l_width
)
3309 n
= cv
->c_layer
->l_width
;
3311 LayRedisplayLine(-1, -1, -1, 1);
3312 for (i
= 0; i
< flayer
->l_height
; i
++)
3314 LScrollH(flayer
, -n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3315 LayRedisplayLine(i
, 0, n
- 1, 1);
3317 if (cv
== cv
->c_display
->d_forecv
)
3321 else if (lx
+ cv
->c_xoff
> cv
->c_xe
)
3323 int i
, n
= lx
+ cv
->c_xoff
- cv
->c_xe
;
3324 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3325 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3326 if (cv
->c_xoff
- n
+ cv
->c_layer
->l_width
- 1 < cv
->c_xe
)
3327 n
= cv
->c_xoff
+ cv
->c_layer
->l_width
- 1 - cv
->c_xe
;
3329 RethinkViewportOffsets(cv
);
3330 if (n
> cv
->c_layer
->l_width
)
3331 n
= cv
->c_layer
->l_width
;
3333 LayRedisplayLine(-1, -1, -1, 1);
3334 for (i
= 0; i
< flayer
->l_height
; i
++)
3336 LScrollH(flayer
, n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3337 LayRedisplayLine(i
, flayer
->l_width
- n
, flayer
->l_width
- 1, 1);
3339 if (cv
== cv
->c_display
->d_forecv
)
3346 for (display
= displays
; display
; display
= display
->d_next
)
3348 if (D_status
== STATUS_ON_WIN
|| D_cvlist
== 0 || D_cvlist
->c_next
== 0)
3350 debug1("serv_select_fn: Restore on cv %#x\n", (int)D_forecv
);
3351 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
3356 logflush_fn(ev
, data
)
3364 if (!islogfile(NULL
))
3365 return; /* no more logfiles */
3367 n
= log_flush
? log_flush
: (logtstamp_after
+ 4) / 5;
3370 SetTimeout(ev
, n
* 1000);
3371 evenq(ev
); /* re-enqueue ourself */
3375 /* write fancy time-stamp */
3376 for (p
= windows
; p
; p
= p
->w_next
)
3380 p
->w_logsilence
+= n
;
3381 if (p
->w_logsilence
< logtstamp_after
)
3383 if (p
->w_logsilence
- n
>= logtstamp_after
)
3385 buf
= MakeWinMsg(logtstamp_string
, p
, '%');
3386 logfwrite(p
->w_log
, buf
, strlen(buf
));
3391 * Interprets ^?, ^@ and other ^-control-char notation.
3392 * Interprets \ddd octal notation
3394 * The result is placed in *cp, p is advanced behind the parsed expression and
3403 if (*p
== '^' && p
[1])
3413 else if (*p
== '\\' && *++p
<= '7' && *p
>= '0')
3417 *cp
= *cp
* 8 + *p
- '0';
3418 while (*++p
<= '7' && *p
>= '0');
3429 unsigned char buf
[2];
3432 SetEscape((struct acluser
*)0, -1, -1);
3435 if ((p
= ParseChar(p
, (char *)buf
)) == NULL
||
3436 (p
= ParseChar(p
, (char *)buf
+1)) == NULL
|| *p
)
3438 SetEscape((struct acluser
*)0, buf
[0], buf
[1]);