1 /* Copyright (c) 1993-2002
2 * Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de)
3 * Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de)
4 * Copyright (c) 1987 Oliver Laumann
7 * Authors: Hadi Bargi Rangin bargi@dots.physics.orst.edu
8 * Bill Barry barryb@dots.physics.orst.edu
9 * Randy Lundquist randyl@dots.physics.orst.edu
11 * Modifications Copyright (c) 1995 by
12 * Science Access Project, Oregon State University.
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2, or (at your option)
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program (see the file COPYING); if not, write to the
27 * Free Software Foundation, Inc.,
28 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
30 ****************************************************************
33 #include <sys/types.h>
39 # include <sys/sysmacros.h>
44 # include <sys/ioctl.h>
54 # include <sys/stropts.h>
57 #if defined(SYSV) && !defined(ISC)
58 # include <sys/utsname.h>
61 #if defined(sequent) || defined(SVR4)
62 # include <sys/resource.h>
63 #endif /* sequent || SVR4 */
67 # include <sys/sioctl.h>
71 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
74 #if defined(USE_LOCALE) || defined(ENCODINGS)
77 #if defined(HAVE_NL_LANGINFO) && defined(ENCODINGS)
78 # include <langinfo.h>
86 #include "patchlevel.h"
89 * At the moment we only need the real password if the
90 * builtin lock is used. Therefore disable SHADOWPW if
91 * we do not really need it (kind of security thing).
100 #endif /* SHADOWPW */
102 #include "logfile.h" /* islogfile, logfflush */
109 extern char Term
[], screenterm
[], **environ
, Termcap
[];
111 int VBellWait
, MsgWait
, MsgMinWait
, SilenceWait
;
113 extern struct acluser
*users
;
114 extern struct display
*displays
, *display
;
117 extern int visual_bell
;
119 extern unsigned char mark_key_tab
[];
121 extern char version
[];
122 extern char DefaultShell
[];
124 extern char *zmodem_sendcmd
;
125 extern char *zmodem_recvcmd
;
127 extern struct layout
*layout_last
;
133 extern struct NewWindow nwin_undef
, nwin_default
, nwin_options
;
136 static struct passwd
*getpwbyname
__P((char *, struct passwd
*));
137 static void SigChldHandler
__P((void));
138 static sigret_t SigChld
__P(SIGPROTOARG
);
139 static sigret_t SigInt
__P(SIGPROTOARG
);
140 static sigret_t CoreDump
__P(SIGPROTOARG
);
141 static sigret_t FinitHandler
__P(SIGPROTOARG
);
142 static void DoWait
__P((void));
143 static void serv_read_fn
__P((struct event
*, char *));
144 static void serv_select_fn
__P((struct event
*, char *));
145 static void logflush_fn
__P((struct event
*, char *));
146 static void backtick_filter
__P((struct backtick
*));
147 static void backtick_fn
__P((struct event
*, char *));
148 static char *runbacktick
__P((struct backtick
*, int *, time_t));
149 static int IsSymbol
__P((char *, char *));
150 static char *ParseChar
__P((char *, char *));
151 static int ParseEscape
__P((char *));
152 static char *pad_expand
__P((char *, char *, int, int));
154 static void fds
__P((void));
157 int nversion
; /* numerical version, used for secondary DA */
165 struct mode attach_Mode
;
167 char SockPath
[MAXPATHLEN
+ 2 * MAXSTR
];
168 char *SockName
; /* SockName is pointer in SockPath */
169 char *SockMatch
= NULL
; /* session id command line argument */
170 int ServerSocket
= -1;
171 struct event serv_read
;
172 struct event serv_select
;
173 struct event logflushev
;
175 char **NewEnv
= NULL
;
177 char *RcFileName
= NULL
;
180 char *screenlogfile
; /* filename layout */
181 int log_flush
= 10; /* flush interval in seconds */
182 int logtstamp_on
= 0; /* tstamp disabled */
183 char *logtstamp_string
; /* stamp layout */
184 int logtstamp_after
= 120; /* first tstamp after 120s */
185 char *hardcopydir
= NULL
;
187 char *VisualBellString
;
188 char *ActivityString
;
193 char *PowDetachString
;
201 int iflag
, rflag
, dflag
, lsflag
, quietflag
, wipeflag
, xflag
;
212 int tty_oldmode
= -1;
215 char HostName
[MAXSTR
];
216 int MasterPid
, PanicPid
;
217 int real_uid
, real_gid
, eff_uid
, eff_gid
;
219 int ZombieKey_destroy
, ZombieKey_resurrect
, ZombieKey_onerror
;
220 char *preselect
= NULL
; /* only used in Attach() */
223 char *screenencodings
;
236 struct layer
*flayer
;
239 struct win
*console_window
;
248 char strnomem
[] = "Out of memory.";
251 static int InterruptPlease
;
252 static int GotSigChld
;
255 lf_secreopen(name
, wantfd
, l
)
263 if (((got_fd
= secopen(name
, O_WRONLY
| O_CREAT
| O_APPEND
, 0666)) < 0) ||
264 lf_move_fd(got_fd
, wantfd
) < 0)
267 debug1("lf_secreopen: failed for %s\n", name
);
270 l
->st
->st_ino
= l
->st
->st_dev
= 0;
271 debug2("lf_secreopen: %d = %s\n", wantfd
, name
);
275 /********************************************************************/
276 /********************************************************************/
277 /********************************************************************/
280 static struct passwd
*
281 getpwbyname(name
, ppp
)
287 struct spwd
*sss
= NULL
;
288 static char *spw
= NULL
;
291 if (!ppp
&& !(ppp
= getpwnam(name
)))
294 /* Do password sanity check..., allow ##user for SUN_C2 security */
299 if (ppp
->pw_passwd
[0] == '#' && ppp
->pw_passwd
[1] == '#' &&
300 strcmp(ppp
->pw_passwd
+ 2, ppp
->pw_name
) == 0)
304 char c
= ppp
->pw_passwd
[n
];
305 if (!(c
== '.' || c
== '/' || c
== '$' ||
306 (c
>= '0' && c
<= '9') ||
307 (c
>= 'a' && c
<= 'z') ||
308 (c
>= 'A' && c
<= 'Z')))
313 /* try to determine real password */
314 if (n
< 13 && sss
== 0)
316 sss
= getspnam(ppp
->pw_name
);
321 ppp
->pw_passwd
= spw
= SaveStr(sss
->sp_pwdp
);
322 endspent(); /* this should delete all buffers ... */
325 endspent(); /* this should delete all buffers ... */
331 if (ppp
->pw_passwd
&& strlen(ppp
->pw_passwd
) == 13 + 11)
332 ppp
->pw_passwd
[13] = 0; /* beware of linux's long passwords */
343 s
= getenv("LC_ALL");
345 s
= getenv("LC_CTYPE");
359 char socknamebuf
[2 * MAXSTR
];
361 char *myname
= (ac
== 0) ? "screen" : av
[0];
364 #ifdef _MODE_T /* (jw) */
369 #if defined(SYSV) && !defined(ISC)
370 struct utsname utsnam
;
372 struct NewWindow nwin
;
373 int detached
= 0; /* start up detached */
379 #if (defined(AUX) || defined(_AUX_SOURCE)) && defined(POSIX)
380 setcompat(COMPAT_POSIX
|COMPAT_BSDPROT
); /* turn on seteuid support */
382 #if defined(sun) && defined(SVR4)
384 /* Solaris' login blocks SIGHUP! This is _very bad_ */
387 sigprocmask(SIG_SETMASK
, &sset
, 0);
392 * First, close all unused descriptors
393 * (otherwise, we might have problems with the select() call)
399 sprintf(version
, "%d.%.2d.%.2d%s (%s) %s", REV
, VERS
,
400 PATCHLEVEL
, STATE
, ORIGIN
, DATE
);
401 nversion
= REV
* 10000 + VERS
* 100 + PATCHLEVEL
;
402 debug2("-- screen debug started %s (%s)\n", *av
, version
);
416 debug("NAMEDPIPE\n");
418 #if defined(SIGWINCH) && defined(TIOCGWINSZ)
419 debug("Window size changing enabled\n");
449 debug1("NAME_MAX = %d\n", NAME_MAX
);
452 BellString
= SaveStr("Bell in window %n");
453 VisualBellString
= SaveStr(" Wuff, Wuff!! ");
454 ActivityString
= SaveStr("Activity in window %n");
455 screenlogfile
= SaveStr("screenlog.%n");
456 logtstamp_string
= SaveStr("-- %n:%t -- time-stamp -- %M/%d/%y %c:%s --\n");
457 hstatusstring
= SaveStr("%h");
458 captionstring
= SaveStr("%3n %t");
459 timestring
= SaveStr("%c:%s %M %d %H%? %l%?");
460 wlisttit
= SaveStr("Num Name%=Flags");
461 wliststr
= SaveStr("%3n %t%=%f");
463 BufferFile
= SaveStr(DEFAULT_BUFFERFILE
);
469 default_startup
= (ac
> 1) ? 0 : 1;
471 VBellWait
= VBELLWAIT
* 1000;
472 MsgWait
= MSGWAIT
* 1000;
473 MsgMinWait
= MSGMINWAIT
* 1000;
474 SilenceWait
= SILENCEWAIT
;
479 zmodem_sendcmd
= SaveStr("!!! sz -vv -b ");
480 zmodem_recvcmd
= SaveStr("!!! rz -vv -b -E");
484 CompileKeys((char *)0, 0, mark_key_tab
);
488 screenencodings
= SaveStr(SCREENENCODINGS
);
494 nwin_options
= nwin_undef
;
495 strcpy(screenterm
, "screen");
497 logreopen_register(lf_secreopen
);
500 /* if this is a login screen, assume -RR */
509 ShellProg
= SaveStr(DefaultShell
); /* to prevent nasty circles */
514 if (--ac
> 0 && *ap
== '-')
516 if (ap
[1] == '-' && ap
[2] == 0)
522 if (ap
[1] == '-' && !strcmp(ap
, "--version"))
523 Panic(0, "Screen version %s", version
);
524 if (ap
[1] == '-' && !strcmp(ap
, "--help"))
525 exit_with_usage(myname
, NULL
, NULL
);
526 while (ap
&& *ap
&& *++ap
)
531 nwin_options
.aflag
= 1;
536 case 'p': /* preselect */
542 exit_with_usage(myname
, "Specify a window to preselect with -p", NULL
);
549 bd
.bd_start_braille
= 1;
558 exit_with_usage(myname
, "Specify an alternate rc-filename with -c", NULL
);
567 exit_with_usage(myname
, "Specify command characters with -e", NULL
);
571 Panic(0, "Two characters are required with -e option, not '%s'.", ap
);
580 nwin_options
.flowflag
= FLOW_NOW
* 0;
587 nwin_options
.flowflag
= FLOW_NOW
* 1;
590 nwin_options
.flowflag
= FLOW_AUTOFLAG
;
593 exit_with_usage(myname
, "Unknown flow option -%s", --ap
);
598 exit_with_usage(myname
, NULL
, NULL
);
599 nwin_options
.histheight
= atoi(*++av
);
600 if (nwin_options
.histheight
< 0)
601 exit_with_usage(myname
, "-h: %s: negative scrollback size?", *av
);
606 case 't': /* title, the former AkA == -k */
608 exit_with_usage(myname
, "Specify a new window-name with -t", NULL
);
609 nwin_options
.aka
= *++av
;
617 nwin_options
.lflag
= 0;
624 nwin_options
.lflag
= 1;
627 nwin_options
.lflag
= 3;
630 case 'i': /* -list */
632 if (ac
> 1 && !SockMatch
)
640 exit_with_usage(myname
, "%s: Unknown suboption to -l", --ap
);
646 if (ac
> 1 && !SockMatch
)
653 nwin_options
.Lflag
= 1;
658 case 'O': /* to be (or not to be?) deleted. jw. */
663 exit_with_usage(myname
, "Specify terminal-type with -T", NULL
);
664 if (strlen(*++av
) < 20)
665 strcpy(screenterm
, *av
);
667 Panic(0, "-T: terminal name too long. (max. 20 char)");
668 nwin_options
.term
= screenterm
;
678 if (ac
> 1 && *av
[1] != '-' && !SockMatch
)
682 debug2("rflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
690 rflag
+= (*ap
== 'R') ? 2 : 1;
701 if (*av
[1] != '-' && !SockMatch
)
705 debug2("dflag=%d, SockMatch=%s\n", dflag
, SockMatch
);
712 exit_with_usage(myname
, "Specify shell with -s", NULL
);
715 ShellProg
= SaveStr(*++av
);
716 debug1("ShellProg: '%s'\n", ShellProg
);
722 exit_with_usage(myname
, "Specify session-name with -S", NULL
);
726 exit_with_usage(myname
, "Empty session-name?", NULL
);
732 Panic(0, "Screen version %s", version
);
736 nwin_options
.encoding
= nwin_options
.encoding
== -1 ? UTF8
: 0;
740 exit_with_usage(myname
, "Unknown option %s", --ap
);
752 if (eff_uid
!= real_uid
)
754 /* if running with s-bit, we must install a special signal
755 * handler routine that resets the s-bit, so that we get a
758 #ifdef SIGBUS /* OOPS, linux has no bus errors! */
759 signal(SIGBUS
, CoreDump
);
761 signal(SIGSEGV
, CoreDump
);
765 setlocale(LC_ALL
, "");
768 if (nwin_options
.encoding
== -1)
770 /* ask locale if we should start in UTF-8 mode */
771 # ifdef HAVE_NL_LANGINFO
773 setlocale(LC_CTYPE
, "");
775 nwin_options
.encoding
= FindEncoding(nl_langinfo(CODESET
));
776 debug1("locale says encoding = %d\n", nwin_options
.encoding
);
780 if ((s
= locale_name()) && InStr(s
, "UTF-8"))
781 nwin_options
.encoding
= UTF8
;
783 debug1("environment says encoding=%d\n", nwin_options
.encoding
);
789 if ((s
= locale_name()))
791 if(!strncmp(s
, "zh_", 3) || !strncmp(s
, "ja_", 3) || !strncmp(s
, "ko_", 3))
799 if (SockMatch
&& strlen(SockMatch
) >= MAXSTR
)
800 Panic(0, "Ridiculously long socketname - try again.");
801 if (cmdflag
&& !rflag
&& !dflag
&& !xflag
)
803 if (!cmdflag
&& dflag
&& mflag
&& !(rflag
|| xflag
))
807 nwin
.encoding
= nwin_undef
.encoding
; /* let screenrc overwrite it */
812 /* make the write() calls return -1 on all errors */
815 * Ronald F. Guilmette, Oct 29 '94, bug-gnu-utils@prep.ai.mit.edu:
816 * It appears that in System V Release 4, UNIX, if you are writing
817 * an output file and you exceed the currently set file size limit,
818 * you _don't_ just get the call to `write' returning with a
819 * failure code. Rather, you get a signal called `SIGXFSZ' which,
820 * if neither handled nor ignored, will cause your program to crash
823 signal(SIGXFSZ
, SIG_IGN
);
827 signal(SIGPIPE
, SIG_IGN
);
834 sh
= getenv("SHELL");
835 ShellProg
= SaveStr(sh
? sh
: DefaultShell
);
837 ShellArgs
[0] = ShellProg
;
838 home
= getenv("HOME");
839 if (!mflag
&& !SockMatch
)
842 if (sty
&& *sty
== 0)
847 if (!(nethackflag
= (getenv("NETHACKOPTIONS") != NULL
)))
849 char nethackrc
[MAXPATHLEN
];
851 if (home
&& (strlen(home
) < (MAXPATHLEN
- 20)))
853 sprintf(nethackrc
,"%s/.nethackrc", home
);
854 nethackflag
= !access(nethackrc
, F_OK
);
860 own_uid
= multi_uid
= real_uid
;
861 if (SockMatch
&& (sockp
= index(SockMatch
, '/')))
864 Panic(0, "Must run suid root for multiuser support.");
867 SockMatch
= sockp
+ 1;
871 if ((mppp
= getpwnam(multi
)) == (struct passwd
*)0)
872 Panic(0, "Cannot identify account '%s'.", multi
);
873 multi_uid
= mppp
->pw_uid
;
874 multi_home
= SaveStr(mppp
->pw_dir
);
875 if (strlen(multi_home
) > MAXPATHLEN
- 10)
876 Panic(0, "home directory path too long");
878 /* always fake multi attach mode */
886 if (SockMatch
&& *SockMatch
== 0)
888 #endif /* MULTIUSER */
890 if ((LoginName
= getlogin()) && LoginName
[0] != '\0')
892 if ((ppp
= getpwnam(LoginName
)) != (struct passwd
*) 0)
893 if ((int)ppp
->pw_uid
!= real_uid
)
894 ppp
= (struct passwd
*) 0;
898 if ((ppp
= getpwuid(real_uid
)) == 0)
900 Panic(0, "getpwuid() can't identify your account!");
903 LoginName
= ppp
->pw_name
;
905 LoginName
= SaveStr(LoginName
);
907 ppp
= getpwbyname(LoginName
, ppp
);
909 #if !defined(SOCKDIR) && defined(MULTIUSER)
910 if (multi
&& !multiattach
)
912 if (home
&& strcmp(home
, ppp
->pw_dir
))
913 Panic(0, "$HOME must match passwd entry for multiuser screens.");
917 #define SET_GUID() do \
921 eff_uid = real_uid; \
922 eff_gid = real_gid; \
925 #define SET_TTYNAME(fatal) do \
927 if (!(attach_tty = ttyname(0))) \
930 Panic(0, "Must be connected to a terminal."); \
934 else if (stat(attach_tty, &st)) \
935 Panic(errno, "Cannot access '%s'", attach_tty); \
936 if (strlen(attach_tty) >= MAXPATHLEN) \
937 Panic(0, "TtyName too long - sorry."); \
940 if (home
== 0 || *home
== '\0')
942 if (strlen(LoginName
) > 20)
943 Panic(0, "LoginName too long - sorry.");
945 if (multi
&& strlen(multi
) > 20)
946 Panic(0, "Screen owner name too long - sorry.");
948 if (strlen(home
) > MAXPATHLEN
- 25)
949 Panic(0, "$HOME too long - sorry.");
952 if (!detached
&& !lsflag
&& !cmdflag
&& !(dflag
&& !mflag
&& !rflag
&& !xflag
) && !(!mflag
&& !SockMatch
&& sty
))
958 /* ttyname implies isatty */
961 tty_mode
= (int)st
.st_mode
& 0777;
965 fl
= fcntl(0, F_GETFL
, 0);
966 if (fl
!= -1 && (fl
& (O_RDWR
|O_RDONLY
|O_WRONLY
)) == O_RDWR
)
971 if ((n
= secopen(attach_tty
, O_RDWR
| O_NONBLOCK
, 0)) < 0)
972 Panic(0, "Cannot open your terminal '%s' - please check.", attach_tty
);
975 debug2("attach_tty is %s, attach_fd is %d\n", attach_tty
, attach_fd
);
977 if ((attach_term
= getenv("TERM")) == 0 || *attach_term
== 0)
978 Panic(0, "Please set a terminal type.");
979 if (strlen(attach_term
) > sizeof(D_termname
) - 1)
980 Panic(0, "$TERM too long - sorry.");
981 GetTTY(0, &attach_Mode
);
982 #ifdef DEBUGGGGGGGGGGGGGGG
983 DebugTTY(&attach_Mode
);
988 oumask
= umask(0); /* well, unsigned never fails? jw. */
990 if ((oumask
= (int)umask(0)) == -1)
991 Panic(errno
, "Cannot change umask to zero");
993 SockDir
= getenv("SCREENDIR");
996 if (strlen(SockDir
) >= MAXPATHLEN
- 1)
997 Panic(0, "Ridiculously long $SCREENDIR - try again.");
1000 Panic(0, "No $SCREENDIR with multi screens, please.");
1007 sprintf(SockPath
, "%s/.screen", multi_home
);
1011 sprintf(SockPath
, "%s/S-%s", SockDir
, multi
);
1020 sprintf(SockPath
, "%s/.screen", home
);
1026 if (access(SockDir
, F_OK
))
1028 debug1("SockDir '%s' missing ...\n", SockDir
);
1029 if (UserContext() > 0)
1031 if (mkdir(SockDir
, 0700))
1035 if (UserStatus() <= 0)
1036 Panic(0, "Cannot make directory '%s'.", SockDir
);
1038 if (SockDir
!= SockPath
)
1039 strcpy(SockPath
, SockDir
);
1045 if (lstat(SockDir
, &st
))
1047 n
= (eff_uid
== 0 && (real_uid
|| eff_gid
== real_gid
)) ? 0755 :
1048 (eff_gid
!= real_gid
) ? 0775 :
1054 if (mkdir(SockDir
, n
) == -1)
1055 Panic(errno
, "Cannot make directory '%s'", SockDir
);
1059 if (!S_ISDIR(st
.st_mode
))
1060 Panic(0, "'%s' must be a directory.", SockDir
);
1061 if (eff_uid
== 0 && real_uid
&& (int)st
.st_uid
!= eff_uid
)
1062 Panic(0, "Directory '%s' must be owned by root.", SockDir
);
1063 n
= (eff_uid
== 0 && (real_uid
|| (st
.st_mode
& 0775) != 0775)) ? 0755 :
1064 (eff_gid
== (int)st
.st_gid
&& eff_gid
!= real_gid
) ? 0775 :
1066 if (((int)st
.st_mode
& 0777) != n
)
1067 Panic(0, "Directory '%s' must have mode %03o.", SockDir
, n
);
1069 sprintf(SockPath
, "%s/S-%s", SockDir
, LoginName
);
1070 if (access(SockPath
, F_OK
))
1072 if (mkdir(SockPath
, 0700) == -1)
1073 Panic(errno
, "Cannot make directory '%s'", SockPath
);
1074 (void) chown(SockPath
, real_uid
, real_gid
);
1080 if (stat(SockPath
, &st
) == -1)
1081 Panic(errno
, "Cannot access %s", SockPath
);
1083 if (!S_ISDIR(st
.st_mode
))
1084 Panic(0, "%s is not a directory.", SockPath
);
1088 if ((int)st
.st_uid
!= multi_uid
)
1089 Panic(0, "%s is not the owner of %s.", multi
, SockPath
);
1094 if ((int)st
.st_uid
!= real_uid
)
1095 Panic(0, "You are not the owner of %s.", SockPath
);
1097 if ((st
.st_mode
& 0777) != 0700)
1098 Panic(0, "Directory %s must have mode 700.", SockPath
);
1099 if (SockMatch
&& index(SockMatch
, '/'))
1100 Panic(0, "Bad session name '%s'", SockMatch
);
1101 SockName
= SockPath
+ strlen(SockPath
) + 1;
1103 (void) umask(oumask
);
1104 debug2("SockPath: %s SockMatch: %s\n", SockPath
, SockMatch
? SockMatch
: "NULL");
1106 #if defined(SYSV) && !defined(ISC)
1107 if (uname(&utsnam
) == -1)
1108 Panic(errno
, "uname");
1109 strncpy(HostName
, utsnam
.nodename
, sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1);
1110 HostName
[sizeof(utsnam
.nodename
) < MAXSTR
? sizeof(utsnam
.nodename
) : MAXSTR
- 1] = '\0';
1112 (void) gethostname(HostName
, MAXSTR
);
1113 HostName
[MAXSTR
- 1] = '\0';
1115 if ((ap
= index(HostName
, '.')) != NULL
)
1124 real_uid
= multi_uid
;
1127 i
= FindSocket((int *)NULL
, &fo
, &oth
, SockMatch
);
1129 exit(8 + (fo
? ((oth
|| i
) ? 2 : 1) : 0) + i
);
1131 Panic(0, "No Sockets found in %s.\n", SockPath
);
1132 Panic(0, "%d Socket%s in %s.\n", fo
, fo
> 1 ? "s" : "", SockPath
);
1135 signal(SIG_BYE
, AttacherFinit
); /* prevent races */
1138 /* attach_tty is not mandatory */
1141 Panic(0, "Please specify a command.");
1143 SendCmdMessage(sty
, SockMatch
, av
);
1146 else if (rflag
|| xflag
)
1148 debug("screen -r: - is there anybody out there?\n");
1149 if (Attach(MSG_ATTACH
))
1156 Panic(0, "Can't create sessions of other users.");
1158 debug("screen -r: backend not responding -- still crying\n");
1160 else if (dflag
&& !mflag
)
1162 (void) Attach(MSG_DETACH
);
1163 Msg(0, "[%s %sdetached.]\n", SockName
, (dflag
> 1 ? "power " : ""));
1167 if (!SockMatch
&& !mflag
&& sty
)
1169 /* attach_tty is not mandatory */
1172 nwin_options
.args
= av
;
1173 SendCreateMsg(sty
, &nwin
);
1177 nwin_compose(&nwin_default
, &nwin_options
, &nwin_default
);
1179 if (!detached
|| dflag
!= 2)
1187 Panic(errno
, "fork");
1195 sprintf(socknamebuf
, "%d.%s", MasterPid
, SockMatch
);
1197 sprintf(socknamebuf
, "%d.%s.%s", MasterPid
, stripdev(attach_tty
), HostName
);
1198 for (ap
= socknamebuf
; *ap
; ap
++)
1202 if (strlen(socknamebuf
) > NAME_MAX
)
1203 socknamebuf
[NAME_MAX
] = 0;
1205 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1212 PanicPid
= getppid();
1214 if (DefaultEsc
== -1)
1215 DefaultEsc
= Ctrl('a');
1216 if (DefaultMetaEsc
== -1)
1217 DefaultMetaEsc
= 'a';
1219 ap
= av0
+ strlen(av0
) - 1;
1222 if (!strncmp("screen", ap
, 6))
1224 strncpy(ap
, "SCREEN", 6); /* name this process "SCREEN-BACKEND" */
1236 if (dfp
&& dfp
!= stderr
)
1238 sprintf(buf
, "%s/SCREEN.%d", DEBUGDIR
, (int)getpid());
1239 if ((dfp
= fopen(buf
, "w")) == NULL
)
1242 (void) chmod(buf
, 0666);
1247 if (attach_fd
== -1)
1249 if ((n
= secopen(attach_tty
, O_RDWR
, 0)) < 0)
1250 Panic(0, "Cannot reopen '%s' - please check.", attach_tty
);
1257 freopen("/dev/null", "r", stdin
);
1258 freopen("/dev/null", "w", stdout
);
1263 freopen("/dev/null", "w", stderr
);
1264 debug("-- screen.back debug started\n");
1267 * This guarantees that the session owner is listed, even when we
1268 * start detached. From now on we should not refer to 'LoginName'
1269 * any more, use users->u_name instead.
1271 if (UserAdd(LoginName
, (char *)0, (struct acluser
**)0) < 0)
1272 Panic(0, "Could not create user info");
1275 if (MakeDisplay(LoginName
, attach_tty
, attach_term
, n
, getppid(), &attach_Mode
) == 0)
1276 Panic(0, "Could not alloc display");
1279 D_encoding
= nwin_options
.encoding
> 0 ? nwin_options
.encoding
: 0;
1280 debug1("D_encoding = %d\n", D_encoding
);
1286 /* user started us with -S option */
1287 sprintf(socknamebuf
, "%d.%s", (int)getpid(), SockMatch
);
1291 sprintf(socknamebuf
, "%d.%s.%s", (int)getpid(), stripdev(attach_tty
),
1294 for (ap
= socknamebuf
; *ap
; ap
++)
1298 if (strlen(socknamebuf
) > NAME_MAX
)
1300 debug2("Socketname %s truncated to %d chars\n", socknamebuf
, NAME_MAX
);
1301 socknamebuf
[NAME_MAX
] = 0;
1304 sprintf(SockPath
+ strlen(SockPath
), "/%s", socknamebuf
);
1306 ServerSocket
= MakeServerSocket();
1309 # ifdef ALLOW_SYSSCREENRC
1310 if ((ap
= getenv("SYSSCREENRC")))
1311 (void)StartRc(ap
, 0);
1314 (void)StartRc(ETCSCREENRC
, 0);
1316 (void)StartRc(RcFileName
, 0);
1320 # endif /* UTNOKEEP */
1321 # endif /* UTMPOK */
1324 if (InitTermcap(0, 0))
1326 debug("Could not init termcap - exiting\n");
1327 fcntl(D_userfd
, F_SETFL
, 0); /* Flush sets FNBLOCK */
1330 Kill(D_userpid
, SIG_BYE
);
1333 MakeDefaultCanvas();
1345 signal(SIGHUP
, SigHup
);
1346 signal(SIGINT
, FinitHandler
);
1347 signal(SIGQUIT
, FinitHandler
);
1348 signal(SIGTERM
, FinitHandler
);
1350 signal(SIGTTIN
, SIG_IGN
);
1351 signal(SIGTTOU
, SIG_IGN
);
1357 SetMode(&D_OldMode
, &D_NewMode
, D_flow
, iflag
);
1358 /* Note: SetMode must be called _before_ FinishRc. */
1359 SetTTY(D_userfd
, &D_NewMode
);
1360 if (fcntl(D_userfd
, F_SETFL
, FNBLOCK
))
1361 Msg(errno
, "Warning: NBLOCK fcntl failed");
1364 brktty(-1); /* just try */
1365 signal(SIGCHLD
, SigChld
);
1367 # ifdef ALLOW_SYSSCREENRC
1368 if ((ap
= getenv("SYSSCREENRC")))
1372 FinishRc(ETCSCREENRC
);
1374 FinishRc(RcFileName
);
1376 debug2("UID %d EUID %d\n", (int)getuid(), (int)geteuid());
1377 if (windows
== NULL
)
1379 debug("We open one default window, as screenrc did not specify one.\n");
1380 if (MakeWindow(&nwin
) == -1)
1382 Msg(0, "Sorry, could not find a PTY.");
1393 if (display
&& default_startup
)
1394 display_copyright();
1395 signal(SIGINT
, SigInt
);
1396 if (rflag
&& (rflag
& 1) == 0 && !quietflag
)
1398 Msg(0, "New screen...");
1402 serv_read
.type
= EV_READ
;
1403 serv_read
.fd
= ServerSocket
;
1404 serv_read
.handler
= serv_read_fn
;
1407 serv_select
.pri
= -10;
1408 serv_select
.type
= EV_ALWAYS
;
1409 serv_select
.handler
= serv_select_fn
;
1410 evenq(&serv_select
);
1412 logflushev
.type
= EV_TIMEOUT
;
1413 logflushev
.handler
= logflush_fn
;
1421 WindowDied(p
, wstat
, wstat_valid
)
1428 if (ZombieKey_destroy
&& ZombieKey_onerror
&& wstat_valid
&&
1429 WIFEXITED(wstat
) && WEXITSTATUS(wstat
) == 0)
1432 if (ZombieKey_destroy
&& !killit
)
1434 char buf
[100], *s
, reason
[100];
1438 if (WIFEXITED(wstat
))
1439 if (WEXITSTATUS(wstat
))
1440 sprintf(reason
, "terminated with exit status %d", WEXITSTATUS(wstat
));
1442 sprintf(reason
, "terminated normally");
1443 else if (WIFSIGNALED(wstat
))
1444 sprintf(reason
, "terminated with signal %d%s", WTERMSIG(wstat
),
1446 WCOREDUMP(wstat
) ? " (core file generated)" : "");
1451 sprintf(reason
, "detached from window");
1456 s
[strlen(s
) - 1] = '\0';
1457 debug3("window %d (%s) going into zombie state fd %d",
1458 p
->w_number
, p
->w_title
, p
->w_ptyfd
);
1460 if (p
->w_slot
!= (slot_t
)0 && p
->w_slot
!= (slot_t
)-1)
1463 p
->w_slot
= 0; /* "detached" */
1468 p
->w_deadpid
= p
->w_pid
;
1471 /* p->w_y = p->w_bot; */
1472 p
->w_y
= MFindUsedLine(p
, p
->w_bot
, 1);
1473 sprintf(buf
, "\n\r=== Command %s (%s) ===", reason
, s
? s
: "?");
1474 WriteString(p
, buf
, strlen(buf
));
1475 WindowChanged(p
, 'f');
1496 signal(SIGCHLD
, SigChld
);
1499 if (stat(SockPath
, &st
) == -1)
1501 debug1("SigChldHandler: Yuck! cannot stat '%s'\n", SockPath
);
1502 if (!RecoverSocket())
1504 debug("SCREEN cannot recover from corrupt Socket, bye\n");
1508 debug1("'%s' reconstructed\n", SockPath
);
1511 debug2("SigChldHandler: stat '%s' o.k. (%03o)\n", SockPath
, (int)st
.st_mode
);
1517 debug("SigChld()\n");
1525 /* Hangup all displays */
1526 while ((display
= displays
) != 0)
1532 * the backend's Interrupt handler
1533 * we cannot insert the intrc directly, as we never know
1542 debug("SigInt()\n");
1543 if (fore
&& displays
)
1545 # if defined(TERMIO) || defined(POSIX)
1546 ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
1548 ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
1551 write(fore
->w_ptyfd
, &ibuf
, 1);
1554 signal(SIGINT
, SigInt
);
1555 debug("SigInt() careful\n");
1556 InterruptPlease
= 1;
1564 struct display
*disp
;
1567 #if defined(SYSVSIGS) && defined(SIGHASARG)
1568 signal(sigsig
, SIG_IGN
);
1574 sprintf(buf
, "\r\n[screen caught signal %d.%s]\r\n", sigsig
,
1576 sprintf(buf
, "\r\n[screen caught a fatal signal.%s]\r\n",
1578 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1580 #else /* SHADOWPW && !DEBUG */
1582 #endif /* SHADOWPW && !DEBUG */
1584 for (disp
= displays
; disp
; disp
= disp
->d_next
)
1586 fcntl(disp
->d_userfd
, F_SETFL
, 0);
1587 SetTTY(disp
->d_userfd
, &D_OldMode
);
1588 write(disp
->d_userfd
, buf
, strlen(buf
));
1589 Kill(disp
->d_userpid
, SIG_BYE
);
1591 #if defined(SHADOWPW) && !defined(DEBUG) && !defined(DUMPSHADOW)
1592 Kill(getpid(), SIGKILL
);
1594 #else /* SHADOWPW && !DEBUG */
1596 #endif /* SHADOWPW && !DEBUG */
1604 struct win
*p
, *next
;
1613 while ((pid
= waitpid(-1, &wstat
, WNOHANG
| WUNTRACED
)) > 0)
1617 * From: rouilj@sni-usa.com (John Rouillard)
1618 * note that WUNTRACED is not documented to work, but it is defined in
1619 * /usr/include/sys/wait.h, so it may work
1621 while ((pid
= wait2(&wstat
, WNOHANG
| WUNTRACED
)) > 0)
1622 # else /* USE_WAIT2 */
1623 while ((pid
= wait3(&wstat
, WNOHANG
| WUNTRACED
, (struct rusage
*) 0)) > 0)
1624 # endif /* USE_WAIT2 */
1627 while ((pid
= wait(&wstat
)) < 0)
1631 #endif /* BSDJOBS */
1633 for (p
= windows
; p
; p
= next
)
1636 if ( (p
->w_pid
&& pid
== p
->w_pid
) ||
1637 (p
->w_deadpid
&& pid
== p
->w_deadpid
) )
1639 /* child has ceased to exist */
1643 if (WIFSTOPPED(wstat
))
1645 debug3("Window %d pid %d: WIFSTOPPED (sig %d)\n", p
->w_number
, pid
, WSTOPSIG(wstat
));
1647 if (WSTOPSIG(wstat
) == SIGTTIN
)
1649 Msg(0, "Suspended (tty input)");
1654 if (WSTOPSIG(wstat
) == SIGTTOU
)
1656 Msg(0, "Suspended (tty output)");
1660 /* Try to restart process */
1661 Msg(0, "Child has been stopped, restarting.");
1662 if (killpg(pid
, SIGCONT
))
1668 WindowDied(p
, wstat
, 1);
1673 if (p
->w_pwin
&& pid
== p
->w_pwin
->p_pid
)
1675 debug2("pseudo of win Nr %d died. pid == %d\n", p
->w_number
, p
->w_pwin
->p_pid
);
1683 debug1("pid %d not found - hope that's ok\n", pid
);
1690 FinitHandler SIGDEFARG
1693 debug1("FinitHandler called, sig %d.\n", sigsig
);
1695 debug("FinitHandler called.\n");
1705 signal(SIGCHLD
, SIG_DFL
);
1706 signal(SIGHUP
, SIG_IGN
);
1707 debug1("Finit(%d);\n", i
);
1710 struct win
*p
= windows
;
1711 windows
= windows
->w_next
;
1714 if (ServerSocket
!= -1)
1716 debug1("we unlink(%s)\n", SockPath
);
1721 (void) unlink(SockPath
);
1727 for (display
= displays
; display
; display
= display
->d_next
)
1735 AddStr("[screen is terminating]\r\n");
1737 SetTTY(D_userfd
, &D_OldMode
);
1738 fcntl(D_userfd
, F_SETFL
, 0);
1740 Kill(D_userpid
, SIG_BYE
);
1743 * we _cannot_ call eexit(i) here,
1744 * instead of playing with the Socket above. Sigh.
1754 if (ServerSocket
!= -1)
1756 debug1("we unlink(%s)\n", SockPath
);
1759 (void) unlink(SockPath
);
1769 debug1("Hangup %x\n", display
);
1775 if (auto_detach
|| displays
->d_next
)
1782 * Detach now has the following modes:
1783 *D_DETACH SIG_BYE detach backend and exit attacher
1784 *D_HANGUP SIG_BYE detach backend and exit attacher
1785 *D_STOP SIG_STOP stop attacher (and detach backend)
1786 *D_REMOTE SIG_BYE remote detach -- reattach to new attacher
1787 *D_POWER SIG_POWER_BYE power detach -- attacher kills his parent
1788 *D_REMOTE_POWER SIG_POWER_BYE remote power detach -- both
1789 *D_LOCK SIG_LOCK lock the attacher
1791 * we always remove our utmp slots. (even when "lock" or "stop")
1792 * Note: Take extra care here, we may be called by interrupt!
1805 signal(SIGHUP
, SIG_IGN
);
1806 debug1("Detach(%d)\n", mode
);
1818 AddStr("[detached]\r\n");
1826 #ifdef REMOTE_DETACH
1828 AddStr("[remote detached]\r\n");
1834 AddStr("[power detached]\r\n");
1835 if (PowDetachString
)
1837 AddStr(PowDetachString
);
1840 sign
= SIG_POWER_BYE
;
1842 #ifdef REMOTE_DETACH
1843 case D_REMOTE_POWER
:
1844 AddStr("[remote power detached]\r\n");
1845 if (PowDetachString
)
1847 AddStr(PowDetachString
);
1850 sign
= SIG_POWER_BYE
;
1857 /* tell attacher to lock terminal with a lockprg. */
1861 if (displays
->d_next
== 0)
1863 for (p
= windows
; p
; p
= p
->w_next
)
1865 if (p
->w_slot
!= (slot_t
) -1 && !(p
->w_lflag
& 2))
1869 * Set the slot to 0 to get the window
1872 p
->w_slot
= (slot_t
) 0;
1876 if (mode
!= D_HANGUP
)
1879 if (displays
->d_next
== 0 && console_window
)
1881 if (TtyGrabConsole(console_window
->w_ptyfd
, 0, "detach"))
1883 debug("could not release console - killing window\n");
1884 KillWindow(console_window
);
1885 display
= displays
; /* restore display */
1891 ReleaseAutoWritelock(display
, D_fore
);
1893 D_user
->u_detachwin
= D_fore
->w_number
;
1894 D_user
->u_detachotherwin
= D_other
? D_other
->w_number
: -1;
1896 AutosaveLayout(D_layout
);
1897 layout_last
= D_layout
;
1898 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
1900 p
= Layer2Window(cv
->c_layer
);
1901 SetCanvasWindow(cv
, 0);
1903 WindowChanged(p
, 'u');
1907 debug2("display: %#x displays: %#x\n", (unsigned int)display
, (unsigned int)displays
);
1910 /* Flag detached-ness */
1913 * tell father what to do. We do that after we
1914 * freed the tty, thus getty feels more comfortable on hpux
1915 * if it was a power detach.
1918 debug2("Detach: Signal %d to Attacher(%d)!\n", sign
, pid
);
1919 debug("Detach returns, we are successfully detached.\n");
1920 signal(SIGHUP
, SigHup
);
1930 return strncmp(e
, s
, l
) == 0 && e
[l
] == '=';
1936 register char **op
, **np
;
1937 static char stybuf
[MAXSTR
];
1939 for (op
= environ
; *op
; ++op
)
1942 free((char *)NewEnv
);
1943 NewEnv
= np
= (char **) malloc((unsigned) (op
- environ
+ 7 + 1) * sizeof(char **));
1946 sprintf(stybuf
, "STY=%s", strlen(SockName
) <= MAXSTR
- 5 ? SockName
: "?");
1947 *np
++ = stybuf
; /* NewEnv[0] */
1948 *np
++ = Term
; /* NewEnv[1] */
1949 np
++; /* room for SHELL */
1951 np
+= 2; /* room for TERMCAP and WINDOW */
1953 np
+= 4; /* room for TERMCAP WINDOW LINES COLUMNS */
1956 for (op
= environ
; *op
; ++op
)
1958 if (!IsSymbol(*op
, "TERM") && !IsSymbol(*op
, "TERMCAP")
1959 && !IsSymbol(*op
, "STY") && !IsSymbol(*op
, "WINDOW")
1960 && !IsSymbol(*op
, "SCREENCAP") && !IsSymbol(*op
, "SHELL")
1961 && !IsSymbol(*op
, "LINES") && !IsSymbol(*op
, "COLUMNS")
1970 #if defined(USEVARARGS) && defined(__STDC__)
1971 Msg(int err
, char *fmt
, VA_DOTS
)
1973 Msg(err
, fmt
, VA_DOTS
)
1980 char buf
[MAXPATHLEN
*2];
1985 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
1992 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
1993 buf
[sizeof(buf
) - 1] = 0;
1995 debug2("Msg('%s') (%#x);\n", buf
, (unsigned int)display
);
1997 if (display
&& displays
)
2001 for (display
= displays
; display
; display
= display
->d_next
)
2006 /* no displays but a display - must have forked.
2007 * send message to backend!
2009 char *tty
= D_usertty
;
2010 struct display
*olddisplay
= display
;
2011 display
= 0; /* only send once */
2012 SendErrorMsg(tty
, buf
);
2013 display
= olddisplay
;
2016 printf("%s\r\n", buf
);
2020 * Call FinitTerm for all displays, write a message to each and call eexit();
2024 #if defined(USEVARARGS) && defined(__STDC__)
2025 Panic(int err
, char *fmt
, VA_DOTS
)
2027 Panic(err
, fmt
, VA_DOTS
)
2034 char buf
[MAXPATHLEN
*2];
2039 (void)vsnprintf(p
, sizeof(buf
) - 100, fmt
, VA_ARGS(ap
));
2046 strncpy(p
, strerror(err
), buf
+ sizeof(buf
) - p
- 1);
2047 buf
[sizeof(buf
) - 1] = 0;
2049 debug3("Panic('%s'); display=%x displays=%x\n", buf
, display
, displays
);
2050 if (displays
== 0 && display
== 0)
2052 printf("%s\r\n", buf
);
2054 Kill(PanicPid
, SIG_BYE
);
2056 else if (displays
== 0)
2058 /* no displays but a display - must have forked.
2059 * send message to backend!
2061 char *tty
= D_usertty
;
2063 SendErrorMsg(tty
, buf
);
2068 for (display
= displays
; display
; display
= display
->d_next
)
2077 SetTTY(D_userfd
, &D_OldMode
);
2078 fcntl(D_userfd
, F_SETFL
, 0);
2079 write(D_userfd
, buf
, strlen(buf
));
2080 write(D_userfd
, "\n", 1);
2083 Kill(D_userpid
, SIG_BYE
);
2086 if (tty_oldmode
>= 0)
2089 if (setuid(own_uid
))
2090 xseteuid(own_uid
); /* may be a loop. sigh. */
2094 debug1("Panic: changing back modes from %s\n", attach_tty
);
2095 chmod(attach_tty
, tty_oldmode
);
2103 * '^' is allowed as an escape mechanism for control characters. jw.
2105 * Added time insertion using ideas/code from /\ndy Jones
2106 * (andy@lingua.cltr.uq.OZ.AU) - thanks a lot!
2111 static const char days
[] = "SunMonTueWedThuFriSat";
2112 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2115 static char winmsg_buf
[MAXSTR
];
2116 #define MAX_WINMSG_REND 16 /* rendition changes */
2117 static int winmsg_rend
[MAX_WINMSG_REND
];
2118 static int winmsg_rendpos
[MAX_WINMSG_REND
];
2119 static int winmsg_numrend
;
2122 pad_expand(buf
, p
, numpad
, padlen
)
2131 padlen
= padlen
- (p
- buf
); /* space for rent */
2134 pn2
= pn
= p
+ padlen
;
2138 if (r
&& p
- buf
== winmsg_rendpos
[r
- 1])
2140 winmsg_rendpos
[--r
] = pn
- buf
;
2147 i
= numpad
> 0 ? (padlen
+ numpad
- 1) / numpad
: 0;
2158 struct backtick
*next
;
2163 char result
[MAXSTR
];
2170 struct backtick
*backticks
;
2174 struct backtick
*bt
;
2179 for (p
= q
= bt
->result
; (c
= (unsigned char)*p
++) != 0;)
2183 if (c
>= ' ' || c
== '\005')
2190 backtick_fn(ev
, data
)
2194 struct backtick
*bt
;
2197 bt
= (struct backtick
*)data
;
2198 debug1("backtick_fn for #%d\n", bt
->num
);
2200 l
= read(ev
->fd
, bt
->buf
+ i
, MAXSTR
- i
);
2203 debug1("EOF on backtick #%d\n", bt
->num
);
2209 debug1("read %d bytes\n", l
);
2211 for (j
= 0; j
< l
; j
++)
2212 if (bt
->buf
[i
- j
- 1] == '\n')
2216 for (k
= i
- j
- 2; k
>= 0; k
--)
2217 if (bt
->buf
[k
] == '\n')
2220 bcopy(bt
->buf
+ k
, bt
->result
, i
- j
- k
);
2221 bt
->result
[i
- j
- k
- 1] = 0;
2222 backtick_filter(bt
);
2223 WindowChanged(0, '`');
2225 if (j
== l
&& i
== MAXSTR
)
2233 bcopy(bt
->buf
+ i
- j
, bt
->buf
, j
);
2240 setbacktick(num
, lifespan
, tick
, cmdv
)
2246 struct backtick
**btp
, *bt
;
2249 debug1("setbacktick called for backtick #%d\n", num
);
2250 for (btp
= &backticks
; (bt
= *btp
) != 0; btp
= &bt
->next
)
2257 for (v
= bt
->cmdv
; *v
; v
++)
2274 bt
= (struct backtick
*)malloc(sizeof *bt
);
2280 bzero(bt
, sizeof(*bt
));
2286 bt
->lifespan
= lifespan
;
2293 if (bt
->tick
== 0 && bt
->lifespan
== 0)
2295 debug("setbacktick: continuous mode\n");
2296 bt
->buf
= (char *)malloc(MAXSTR
);
2300 setbacktick(num
, 0, 0, (char **)0);
2303 bt
->ev
.type
= EV_READ
;
2304 bt
->ev
.fd
= readpipe(bt
->cmdv
);
2305 bt
->ev
.handler
= backtick_fn
;
2306 bt
->ev
.data
= (char *)bt
;
2313 runbacktick(bt
, tickp
, now
)
2314 struct backtick
*bt
;
2321 debug1("runbacktick called for backtick #%d\n", bt
->num
);
2322 if (bt
->tick
&& (!*tickp
|| bt
->tick
< *tickp
))
2324 if ((bt
->lifespan
== 0 && bt
->tick
== 0) || now
< bt
->bestbefore
)
2326 debug1("returning old result (%d)\n", bt
->lifespan
);
2329 f
= readpipe(bt
->cmdv
);
2333 while ((l
= read(f
, bt
->result
+ i
, sizeof(bt
->result
) - i
)) > 0)
2335 debug1("runbacktick: read %d bytes\n", l
);
2337 for (j
= 1; j
< l
; j
++)
2338 if (bt
->result
[i
- j
- 1] == '\n')
2340 if (j
== l
&& i
== sizeof(bt
->result
))
2342 j
= sizeof(bt
->result
) / 2;
2347 bcopy(bt
->result
+ i
- j
, bt
->result
, j
);
2352 bt
->result
[sizeof(bt
->result
) - 1] = '\n';
2353 if (i
&& bt
->result
[i
- 1] == '\n')
2355 debug1("runbacktick: finished, %d bytes\n", i
);
2357 backtick_filter(bt
);
2359 bt
->bestbefore
= now2
+ bt
->lifespan
;
2364 MakeWinMsgEv(str
, win
, esc
, padlen
, ev
, rec
)
2374 register char *p
= winmsg_buf
;
2384 int qmflag
= 0, omflag
= 0, qmnumrend
= 0;
2391 struct backtick
*bt
;
2393 if (winmsg_numrend
>= 0)
2396 winmsg_numrend
= -winmsg_numrend
;
2401 gettimeofday(&now
, NULL
);
2402 for (; *s
&& (l
= winmsg_buf
+ MAXSTR
- 1 - p
) > 0; s
++, p
++)
2408 if (*s
!= '^' && *s
>= 64)
2433 if (*++s
== esc
) /* double escape ? */
2435 if ((plusflg
= *s
== '+') != 0)
2437 if ((minusflg
= *s
== '-') != 0)
2439 if ((zeroflg
= *s
== '0') != 0)
2442 while(*s
>= '0' && *s
<= '9')
2443 num
= num
* 10 + (*s
++ - '0');
2444 if ((longflg
= *s
== 'L') != 0)
2452 if ((!qmflag
&& !omflag
) || omflag
== 1)
2455 if (qmnumrend
< winmsg_numrend
)
2456 winmsg_numrend
= qmnumrend
;
2462 qmnumrend
= winmsg_numrend
;
2463 qmflag
= omflag
= 0;
2469 if (qmflag
&& omflag
!= 1)
2473 qmnumrend
= winmsg_numrend
;
2478 if (qmnumrend
< winmsg_numrend
)
2479 winmsg_numrend
= qmnumrend
;
2483 case 'd': case 'D': case 'm': case 'M': case 'y': case 'Y':
2484 case 'a': case 'A': case 's': case 'c': case 'C':
2489 time_t nowsec
= now
.tv_sec
;
2490 tm
= localtime(&nowsec
);
2493 if (!tick
|| tick
> 3600)
2498 sprintf(p
, "%02d", tm
->tm_mday
% 100);
2502 strftime(p
, l
, (longflg
? "%A" : "%a"), tm
);
2504 sprintf(p
, "%3.3s", days
+ 3 * tm
->tm_wday
);
2508 sprintf(p
, "%02d", tm
->tm_mon
+ 1);
2512 strftime(p
, l
, (longflg
? "%B" : "%b"), tm
);
2514 sprintf(p
, "%3.3s", months
+ 3 * tm
->tm_mon
);
2518 sprintf(p
, "%02d", tm
->tm_year
% 100);
2521 sprintf(p
, "%04d", tm
->tm_year
+ 1900);
2524 sprintf(p
, tm
->tm_hour
>= 12 ? "pm" : "am");
2527 sprintf(p
, tm
->tm_hour
>= 12 ? "PM" : "AM");
2530 sprintf(p
, "%02d", tm
->tm_sec
);
2534 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", tm
->tm_hour
, tm
->tm_min
);
2535 if (!tick
|| tick
> 60)
2539 sprintf(p
, zeroflg
? "%02d:%02d" : "%2d:%02d", (tm
->tm_hour
+ 11) % 12 + 1, tm
->tm_min
);
2540 if (!tick
|| tick
> 60)
2560 if (!tick
|| tick
> 60)
2569 if (rec
>= 10 || (*s
== 'h' && (win
== 0 || win
->w_hstatus
== 0 || *win
->w_hstatus
== 0)))
2576 for (bt
= backticks
; bt
; bt
= bt
->next
)
2586 char savebuf
[sizeof(winmsg_buf
)];
2588 int oldnumrend
= winmsg_numrend
;
2591 strcpy(savebuf
, winmsg_buf
);
2592 winmsg_numrend
= -winmsg_numrend
;
2593 MakeWinMsgEv(*s
== 'h' ? win
->w_hstatus
: runbacktick(bt
, &oldtick
, now
.tv_sec
), win
, '\005', 0, (struct event
*)0, rec
+ 1);
2594 debug2("oldtick=%d tick=%d\n", oldtick
, tick
);
2595 if (!tick
|| oldtick
< tick
)
2597 if ((int)strlen(winmsg_buf
) < l
)
2598 strcat(savebuf
, winmsg_buf
);
2599 strcpy(winmsg_buf
, savebuf
);
2600 while (oldnumrend
< winmsg_numrend
)
2601 winmsg_rendpos
[oldnumrend
++] += p
- winmsg_buf
;
2610 struct win
*oldfore
= 0;
2618 ss
= AddWindows(p
, l
- 1, (*s
== 'w' ? 0 : 1) | (longflg
? 0 : 2) | (plusflg
? 4 : 0), win
? win
->w_number
: -1);
2631 AddOtherUsers(p
, l
- 1, win
);
2639 AddWindowFlags(p
, l
- 1, win
);
2646 if (win
&& (int)strlen(win
->w_title
) < l
)
2648 strcpy(p
, win
->w_title
);
2658 for (i
= 0; i
< 127; i
++)
2659 if (s
[i
] && s
[i
] != '}')
2663 if (s
[i
] == '}' && winmsg_numrend
< MAX_WINMSG_REND
)
2667 debug1("MakeWinMsg attrcolor %s\n", rbuf
);
2668 if (i
!= 1 || rbuf
[0] != '-')
2669 r
= ParseAttrColor(rbuf
, (char *)0, 0);
2670 if (r
!= -1 || (i
== 1 && rbuf
[0] == '-'))
2672 winmsg_rend
[winmsg_numrend
] = r
;
2673 winmsg_rendpos
[winmsg_numrend
] = p
- winmsg_buf
;
2683 if ((int)strlen(HostName
) < l
)
2685 strcpy(p
, HostName
);
2695 session_name
= strchr(SockName
, '.') + 1;
2696 if ((int)strlen(session_name
) < l
)
2698 strcpy(p
, session_name
);
2708 if (display
&& ((ev
&& ev
== &D_forecv
->c_captev
) || (!ev
&& win
&& win
== D_fore
)))
2709 minusflg
= !minusflg
;
2714 truncpos
= p
- winmsg_buf
;
2715 truncper
= num
> 100 ? 100 : num
;
2716 trunclong
= longflg
;
2722 if (num
|| zeroflg
|| plusflg
|| longflg
|| (*s
!= '='))
2724 /* expand all pads */
2727 num
= (plusflg
? lastpad
: padlen
) - num
;
2728 if (!plusflg
&& padlen
== 0)
2729 num
= p
- winmsg_buf
;
2734 if (*s
!= '=' && num
== 0 && !plusflg
)
2739 num
= p
- winmsg_buf
;
2741 num
= (padlen
- (plusflg
? lastpad
: 0)) * num
/ 100;
2747 if (num
> MAXSTR
- 1)
2750 p
= pad_expand(winmsg_buf
, p
, numpad
, num
);
2752 if (p
- winmsg_buf
> num
&& !longflg
)
2761 trunc
= lastpad
+ truncper
* (num
- lastpad
) / 100;
2764 if (trunc
< lastpad
)
2766 left
= truncpos
- trunc
;
2767 if (left
> p
- winmsg_buf
- num
)
2768 left
= p
- winmsg_buf
- num
;
2769 debug1("lastpad = %d, ", lastpad
);
2770 debug3("truncpos = %d, trunc = %d, left = %d\n", truncpos
, trunc
, left
);
2773 if (left
+ lastpad
> p
- winmsg_buf
)
2774 left
= p
- winmsg_buf
- lastpad
;
2775 if (p
- winmsg_buf
- lastpad
- left
> 0)
2776 bcopy(winmsg_buf
+ lastpad
+ left
, winmsg_buf
+ lastpad
, p
- winmsg_buf
- lastpad
- left
);
2779 while (r
&& winmsg_rendpos
[r
- 1] > lastpad
)
2782 winmsg_rendpos
[r
] -= left
;
2783 if (winmsg_rendpos
[r
] < lastpad
)
2784 winmsg_rendpos
[r
] = lastpad
;
2788 if (p
- winmsg_buf
> lastpad
)
2789 winmsg_buf
[lastpad
] = '.';
2790 if (p
- winmsg_buf
> lastpad
+ 1)
2791 winmsg_buf
[lastpad
+ 1] = '.';
2792 if (p
- winmsg_buf
> lastpad
+ 2)
2793 winmsg_buf
[lastpad
+ 2] = '.';
2796 if (p
- winmsg_buf
> num
)
2798 p
= winmsg_buf
+ num
;
2801 if (num
- 1 >= lastpad
)
2803 if (num
- 2 >= lastpad
)
2805 if (num
- 3 >= lastpad
)
2809 while (r
&& winmsg_rendpos
[r
- 1] > num
)
2810 winmsg_rendpos
[--r
] = num
;
2814 if (lastpad
> p
- winmsg_buf
)
2815 lastpad
= p
- winmsg_buf
;
2816 debug1("lastpad now %d\n", lastpad
);
2820 while (p
- winmsg_buf
< num
)
2822 lastpad
= p
- winmsg_buf
;
2825 debug1("lastpad2 now %d\n", lastpad
);
2831 *p
= 127; /* internal pad representation */
2845 sprintf(p
, "%*s", num
, num
> 1 ? "--" : "-");
2847 sprintf(p
, "%*d", num
, win
->w_number
);
2854 if (qmpos
&& !qmflag
)
2859 if (padlen
> MAXSTR
- 1)
2860 padlen
= MAXSTR
- 1;
2861 p
= pad_expand(winmsg_buf
, p
, numpad
, padlen
);
2865 evdeq(ev
); /* just in case */
2866 ev
->timeout
.tv_sec
= 0;
2867 ev
->timeout
.tv_usec
= 0;
2871 now
.tv_usec
= 100000;
2875 now
.tv_sec
+= tick
- (now
.tv_sec
% tick
);
2877 debug2("NEW timeout %d %d\n", ev
->timeout
.tv_sec
, tick
);
2883 MakeWinMsg(s
, win
, esc
)
2888 return MakeWinMsgEv(s
, win
, esc
, 0, (struct event
*)0, 0);
2892 PutWinMsg(s
, start
, max
)
2898 struct mchar rendstack
[MAX_WINMSG_REND
];
2901 if (s
!= winmsg_buf
)
2903 /* sorry, no fancy coloring available */
2904 debug1("PutWinMsg %s plain\n", s
);
2917 debug2("PutWinMsg %s start attr %x\n", s
, rend
.attr
);
2918 for (i
= 0; i
< winmsg_numrend
&& max
> 0; i
++)
2920 if (p
> winmsg_rendpos
[i
] || winmsg_rendpos
[i
] > l
)
2922 if (p
< winmsg_rendpos
[i
])
2924 n
= winmsg_rendpos
[i
] - p
;
2941 rend
= rendstack
[--rendstackn
];
2945 rendstack
[rendstackn
++] = rend
;
2946 ApplyAttrColor(r
, &rend
);
2948 SetRendition(&rend
);
2976 if ((j
= open("/dev/null", 0)) >= 0)
2983 while (dup(++i
) < 0 && errno
!= EBADF
)
2985 debug1(" [%d]\n", i
);
2998 serv_read_fn(ev
, data
)
3002 debug("Knock - knock!\n");
3007 serv_select_fn(ev
, data
)
3013 debug("serv_select_fn called\n");
3014 /* XXX: messages?? */
3019 if (InterruptPlease
)
3021 debug("Backend received interrupt\n");
3022 /* This approach is rather questionable in a multi-display
3024 if (fore
&& displays
)
3026 #if defined(TERMIO) || defined(POSIX)
3027 char ibuf
= displays
->d_OldMode
.tio
.c_cc
[VINTR
];
3029 char ibuf
= displays
->d_OldMode
.m_tchars
.t_intrc
;
3032 write(W_UWP(fore
) ? fore
->w_pwin
->p_ptyfd
: fore
->w_ptyfd
,
3034 debug1("Backend wrote interrupt to %d", fore
->w_number
);
3035 debug1("%s\n", W_UWP(fore
) ? " (pseudowin)" : "");
3037 write(fore
->w_ptyfd
, &ibuf
, 1);
3038 debug1("Backend wrote interrupt to %d\n", fore
->w_number
);
3041 InterruptPlease
= 0;
3044 for (p
= windows
; p
; p
= p
->w_next
)
3046 if (p
->w_bell
== BELL_FOUND
|| p
->w_bell
== BELL_VISUAL
)
3049 int visual
= p
->w_bell
== BELL_VISUAL
|| visual_bell
;
3050 p
->w_bell
= BELL_ON
;
3051 for (display
= displays
; display
; display
= display
->d_next
)
3053 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3054 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3058 p
->w_bell
= BELL_DONE
;
3059 Msg(0, "%s", MakeWinMsg(BellString
, p
, '%'));
3061 else if (visual
&& !D_VB
&& (!D_status
|| !D_status_bell
))
3063 Msg(0, "%s", VisualBellString
);
3067 debug1("using vbell timeout %d\n", VBellWait
);
3068 SetTimeout(&D_statusev
, VBellWait
);
3072 /* don't annoy the user with two messages */
3073 if (p
->w_monitor
== MON_FOUND
)
3074 p
->w_monitor
= MON_DONE
;
3075 WindowChanged(p
, 'f');
3077 if (p
->w_monitor
== MON_FOUND
)
3080 p
->w_monitor
= MON_ON
;
3081 for (display
= displays
; display
; display
= display
->d_next
)
3083 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3084 if (cv
->c_layer
->l_bottom
== &p
->w_layer
)
3087 continue; /* user already sees window */
3089 if (!(ACLBYTE(p
->w_mon_notify
, D_user
->u_id
) & ACLBIT(D_user
->u_id
)))
3090 continue; /* user doesn't care */
3092 Msg(0, "%s", MakeWinMsg(ActivityString
, p
, '%'));
3093 p
->w_monitor
= MON_DONE
;
3095 WindowChanged(p
, 'f');
3099 for (display
= displays
; display
; display
= display
->d_next
)
3102 if (D_status
== STATUS_ON_WIN
)
3104 /* XXX: should use display functions! */
3105 for (cv
= D_cvlist
; cv
; cv
= cv
->c_next
)
3109 /* normalize window, see resize.c */
3110 lx
= cv
->c_layer
->l_x
;
3111 ly
= cv
->c_layer
->l_y
;
3112 if (lx
== cv
->c_layer
->l_width
)
3114 if (ly
+ cv
->c_yoff
< cv
->c_ys
)
3116 int i
, n
= cv
->c_ys
- (ly
+ cv
->c_yoff
);
3117 cv
->c_yoff
= cv
->c_ys
- ly
;
3118 RethinkViewportOffsets(cv
);
3119 if (n
> cv
->c_layer
->l_height
)
3120 n
= cv
->c_layer
->l_height
;
3122 LScrollV(flayer
, -n
, 0, flayer
->l_height
- 1, 0);
3123 LayRedisplayLine(-1, -1, -1, 1);
3124 for (i
= 0; i
< n
; i
++)
3125 LayRedisplayLine(i
, 0, flayer
->l_width
- 1, 1);
3126 if (cv
== cv
->c_display
->d_forecv
)
3130 else if (ly
+ cv
->c_yoff
> cv
->c_ye
)
3132 int i
, n
= ly
+ cv
->c_yoff
- cv
->c_ye
;
3133 cv
->c_yoff
= cv
->c_ye
- ly
;
3134 RethinkViewportOffsets(cv
);
3135 if (n
> cv
->c_layer
->l_height
)
3136 n
= cv
->c_layer
->l_height
;
3138 LScrollV(flayer
, n
, 0, cv
->c_layer
->l_height
- 1, 0);
3139 LayRedisplayLine(-1, -1, -1, 1);
3140 for (i
= 0; i
< n
; i
++)
3141 LayRedisplayLine(i
+ flayer
->l_height
- n
, 0, flayer
->l_width
- 1, 1);
3142 if (cv
== cv
->c_display
->d_forecv
)
3146 if (lx
+ cv
->c_xoff
< cv
->c_xs
)
3148 int i
, n
= cv
->c_xs
- (lx
+ cv
->c_xoff
);
3149 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3150 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3151 if (cv
->c_xoff
+ n
> cv
->c_xs
)
3152 n
= cv
->c_xs
- cv
->c_xoff
;
3154 RethinkViewportOffsets(cv
);
3155 if (n
> cv
->c_layer
->l_width
)
3156 n
= cv
->c_layer
->l_width
;
3158 LayRedisplayLine(-1, -1, -1, 1);
3159 for (i
= 0; i
< flayer
->l_height
; i
++)
3161 LScrollH(flayer
, -n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3162 LayRedisplayLine(i
, 0, n
- 1, 1);
3164 if (cv
== cv
->c_display
->d_forecv
)
3168 else if (lx
+ cv
->c_xoff
> cv
->c_xe
)
3170 int i
, n
= lx
+ cv
->c_xoff
- cv
->c_xe
;
3171 if (n
< (cv
->c_xe
- cv
->c_xs
+ 1) / 2)
3172 n
= (cv
->c_xe
- cv
->c_xs
+ 1) / 2;
3173 if (cv
->c_xoff
- n
+ cv
->c_layer
->l_width
- 1 < cv
->c_xe
)
3174 n
= cv
->c_xoff
+ cv
->c_layer
->l_width
- 1 - cv
->c_xe
;
3176 RethinkViewportOffsets(cv
);
3177 if (n
> cv
->c_layer
->l_width
)
3178 n
= cv
->c_layer
->l_width
;
3180 LayRedisplayLine(-1, -1, -1, 1);
3181 for (i
= 0; i
< flayer
->l_height
; i
++)
3183 LScrollH(flayer
, n
, i
, 0, flayer
->l_width
- 1, 0, 0);
3184 LayRedisplayLine(i
, flayer
->l_width
- n
, flayer
->l_width
- 1, 1);
3186 if (cv
== cv
->c_display
->d_forecv
)
3193 for (display
= displays
; display
; display
= display
->d_next
)
3195 if (D_status
== STATUS_ON_WIN
|| D_cvlist
== 0 || D_cvlist
->c_next
== 0)
3197 debug1("serv_select_fn: Restore on cv %#x\n", (int)D_forecv
);
3198 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
3203 logflush_fn(ev
, data
)
3211 if (!islogfile(NULL
))
3212 return; /* no more logfiles */
3214 n
= log_flush
? log_flush
: (logtstamp_after
+ 4) / 5;
3217 SetTimeout(ev
, n
* 1000);
3218 evenq(ev
); /* re-enqueue ourself */
3222 /* write fancy time-stamp */
3223 for (p
= windows
; p
; p
= p
->w_next
)
3227 p
->w_logsilence
+= n
;
3228 if (p
->w_logsilence
< logtstamp_after
)
3230 if (p
->w_logsilence
- n
>= logtstamp_after
)
3232 buf
= MakeWinMsg(logtstamp_string
, p
, '%');
3233 logfwrite(p
->w_log
, buf
, strlen(buf
));
3238 * Interprets ^?, ^@ and other ^-control-char notation.
3239 * Interprets \ddd octal notation
3241 * The result is placed in *cp, p is advanced behind the parsed expression and
3250 if (*p
== '^' && p
[1])
3260 else if (*p
== '\\' && *++p
<= '7' && *p
>= '0')
3264 *cp
= *cp
* 8 + *p
- '0';
3265 while (*++p
<= '7' && *p
>= '0');
3276 unsigned char buf
[2];
3279 SetEscape((struct acluser
*)0, -1, -1);
3282 if ((p
= ParseChar(p
, (char *)buf
)) == NULL
||
3283 (p
= ParseChar(p
, (char *)buf
+1)) == NULL
|| *p
)
3285 SetEscape((struct acluser
*)0, buf
[0], buf
[1]);